Milestone 639 steps 3–4: one assembler per hook under a budget; prior art and preferences behind a cue-swap gate #225
@@ -0,0 +1,28 @@
|
|||||||
|
"""retrieval_logs records the cue-swap gate: its bar and how many lines passed
|
||||||
|
|
||||||
|
Revision ID: 0131
|
||||||
|
Revises: 0130
|
||||||
|
Create Date: 2026-11-23
|
||||||
|
|
||||||
|
A gated surface shows a line found by resemblance only when its score beats
|
||||||
|
most of the user's own recent cues on that surface. Each call row keeps the
|
||||||
|
bar it was held to and how many lines reached it, so how often a surface
|
||||||
|
speaks can be read back, per surface, as the store grows.
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0131"
|
||||||
|
down_revision = "0130"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("retrieval_logs", sa.Column("gate_bar", sa.Float(), nullable=True))
|
||||||
|
op.add_column("retrieval_logs", sa.Column("gate_kept", sa.Integer(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("retrieval_logs", "gate_kept")
|
||||||
|
op.drop_column("retrieval_logs", "gate_bar")
|
||||||
@@ -172,6 +172,42 @@ const kbReplyRuleThreshold = ref("0.8");
|
|||||||
// is raising its bar, which discards the surface's best candidates along with
|
// is raising its bar, which discards the surface's best candidates along with
|
||||||
// its worst. A budget keeps the top of the ranking and drops the tail.
|
// its worst. A budget keeps the top of the ranking and drops the tail.
|
||||||
const kbWritePathTopK = ref("3");
|
const kbWritePathTopK = ref("3");
|
||||||
|
// The most one hook call may inject, in characters (hook_payload.DEFAULT_BUDGET).
|
||||||
|
const kbHookBudget = ref("4500");
|
||||||
|
// How often a record found by resemblance alone may speak, as a percent of
|
||||||
|
// cues that match nothing in particular (cue_gate.RATE_DEFAULT).
|
||||||
|
const kbCueGateRate = ref("10");
|
||||||
|
|
||||||
|
// GatedSurface — one row of /api/retrieval/gate.
|
||||||
|
interface GatedSurface {
|
||||||
|
surface: string;
|
||||||
|
gates: string;
|
||||||
|
bar: number | null;
|
||||||
|
sample: number;
|
||||||
|
calls: number;
|
||||||
|
fired: number;
|
||||||
|
days: number;
|
||||||
|
unreadable?: boolean;
|
||||||
|
}
|
||||||
|
const gatedSurfaces = ref<GatedSurface[]>([]);
|
||||||
|
const gateMinSample = ref(20);
|
||||||
|
|
||||||
|
function gateSummary(g: GatedSurface): string {
|
||||||
|
if (g.unreadable) return "unreadable right now";
|
||||||
|
const spoke = g.calls ? `spoke on ${g.fired} of ${g.calls} calls in ${g.days} days` : "no gated calls yet";
|
||||||
|
if (g.bar === null) return `learning (${g.sample} of ${gateMinSample.value} cues), silent until then; ${spoke}`;
|
||||||
|
return `bar ${g.bar.toFixed(2)} from your last ${g.sample} cues; ${spoke}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadGate() {
|
||||||
|
try {
|
||||||
|
const res = await apiGet<{ surfaces: GatedSurface[]; min_sample: number }>("/api/retrieval/gate");
|
||||||
|
gatedSurfaces.value = res.surfaces ?? [];
|
||||||
|
gateMinSample.value = res.min_sample ?? 20;
|
||||||
|
} catch {
|
||||||
|
gatedSurfaces.value = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
const kbRuleHintTopK = ref("5");
|
const kbRuleHintTopK = ref("5");
|
||||||
const kbToolRuleTopK = ref("5");
|
const kbToolRuleTopK = ref("5");
|
||||||
const kbPromptRuleTopK = ref("3");
|
const kbPromptRuleTopK = ref("3");
|
||||||
@@ -385,6 +421,13 @@ async function saveKbInject() {
|
|||||||
const prK = asK(kbPromptRuleTopK.value, 3);
|
const prK = asK(kbPromptRuleTopK.value, 3);
|
||||||
const ryK = asK(kbReplyRuleTopK.value, 1);
|
const ryK = asK(kbReplyRuleTopK.value, 1);
|
||||||
kbWritePathTopK.value = String(wpK);
|
kbWritePathTopK.value = String(wpK);
|
||||||
|
// Clamped as the server clamps it (hook_payload.HARD_MAX): Claude Code shows
|
||||||
|
// a hook's context past its cap only as a short preview.
|
||||||
|
const budget = Math.min(7500, Math.max(1000, Math.floor(Number(kbHookBudget.value) || 4500)));
|
||||||
|
kbHookBudget.value = String(budget);
|
||||||
|
// Clamped as the server clamps it (cue_gate.RATE_MIN / RATE_MAX).
|
||||||
|
const gateRate = Math.min(50, Math.max(1, Math.floor(Number(kbCueGateRate.value) || 10)));
|
||||||
|
kbCueGateRate.value = String(gateRate);
|
||||||
kbRuleHintTopK.value = String(rhK);
|
kbRuleHintTopK.value = String(rhK);
|
||||||
kbToolRuleTopK.value = String(trK);
|
kbToolRuleTopK.value = String(trK);
|
||||||
kbPromptRuleTopK.value = String(prK);
|
kbPromptRuleTopK.value = String(prK);
|
||||||
@@ -433,6 +476,8 @@ async function saveKbInject() {
|
|||||||
// change the OPERATOR made — which is the one entry the model must not
|
// change the OPERATOR made — which is the one entry the model must not
|
||||||
// quietly tune back.
|
// quietly tune back.
|
||||||
kb_writepath_top_k: String(wpK),
|
kb_writepath_top_k: String(wpK),
|
||||||
|
kb_hook_budget_chars: String(budget),
|
||||||
|
kb_cue_gate_rate: String(gateRate),
|
||||||
kb_rulehint_top_k: String(rhK),
|
kb_rulehint_top_k: String(rhK),
|
||||||
kb_toolrule_top_k: String(trK),
|
kb_toolrule_top_k: String(trK),
|
||||||
kb_promptrule_top_k: String(prK),
|
kb_promptrule_top_k: String(prK),
|
||||||
@@ -454,6 +499,7 @@ async function saveKbInject() {
|
|||||||
// the operator is looking at it to confirm.
|
// the operator is looking at it to confirm.
|
||||||
await loadTuningHistory();
|
await loadTuningHistory();
|
||||||
await loadSurfaces();
|
await loadSurfaces();
|
||||||
|
await loadGate();
|
||||||
} catch {
|
} catch {
|
||||||
toastStore.show('Failed to save auto-inject settings', 'error');
|
toastStore.show('Failed to save auto-inject settings', 'error');
|
||||||
} finally {
|
} finally {
|
||||||
@@ -857,6 +903,12 @@ onMounted(async () => {
|
|||||||
if (allSettings.kb_writepath_threshold !== undefined) {
|
if (allSettings.kb_writepath_threshold !== undefined) {
|
||||||
kbWritePathThreshold.value = allSettings.kb_writepath_threshold;
|
kbWritePathThreshold.value = allSettings.kb_writepath_threshold;
|
||||||
}
|
}
|
||||||
|
if (allSettings.kb_hook_budget_chars !== undefined) {
|
||||||
|
kbHookBudget.value = allSettings.kb_hook_budget_chars;
|
||||||
|
}
|
||||||
|
if (allSettings.kb_cue_gate_rate !== undefined) {
|
||||||
|
kbCueGateRate.value = allSettings.kb_cue_gate_rate;
|
||||||
|
}
|
||||||
if (allSettings.kb_writepath_top_k !== undefined) {
|
if (allSettings.kb_writepath_top_k !== undefined) {
|
||||||
kbWritePathTopK.value = allSettings.kb_writepath_top_k;
|
kbWritePathTopK.value = allSettings.kb_writepath_top_k;
|
||||||
} else if (allSettings.kb_autoinject_top_k !== undefined) {
|
} else if (allSettings.kb_autoinject_top_k !== undefined) {
|
||||||
@@ -879,6 +931,7 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
await loadTuningHistory();
|
await loadTuningHistory();
|
||||||
await loadSurfaces();
|
await loadSurfaces();
|
||||||
|
await loadGate();
|
||||||
if (allSettings.kb_duplicate_threshold_snippet !== undefined) {
|
if (allSettings.kb_duplicate_threshold_snippet !== undefined) {
|
||||||
kbDupThresholdSnippet.value = allSettings.kb_duplicate_threshold_snippet;
|
kbDupThresholdSnippet.value = allSettings.kb_duplicate_threshold_snippet;
|
||||||
}
|
}
|
||||||
@@ -1654,7 +1707,7 @@ async function deleteUser(userId: number) {
|
|||||||
class="fs-input input"
|
class="fs-input input"
|
||||||
style="max-width: 8rem"
|
style="max-width: 8rem"
|
||||||
/>
|
/>
|
||||||
<p class="field-hint">Ceiling on titles surfaced at once (1–10).</p>
|
<p class="field-hint">How many records each prompt is ranked against (1–10); at most two are shown, and only past the resemblance gate below.</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="checkbox-field">
|
<div class="checkbox-field">
|
||||||
<label>
|
<label>
|
||||||
@@ -1695,6 +1748,45 @@ async function deleteUser(userId: number) {
|
|||||||
location, not by resemblance.
|
location, not by resemblance.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="kb-hook-budget">Most context one hook may add (characters)</label>
|
||||||
|
<input
|
||||||
|
id="kb-hook-budget"
|
||||||
|
v-model="kbHookBudget"
|
||||||
|
type="number"
|
||||||
|
min="1000"
|
||||||
|
max="7500"
|
||||||
|
step="500"
|
||||||
|
class="fs-input input"
|
||||||
|
style="max-width: 8rem"
|
||||||
|
/>
|
||||||
|
<p class="field-hint">Everything Grimoire adds beside one prompt, edit or command, from 1,000 to 7,500 characters. Rules go in first, then the reply shape, then records, until this is spent; whatever is left out can arrive on a later call. Claude Code shows a hook's context past its cap only as a short preview, so the ceiling stays well under it.</p>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="kb-cue-gate-rate">How often records found by resemblance may speak (%)</label>
|
||||||
|
<input
|
||||||
|
id="kb-cue-gate-rate"
|
||||||
|
v-model="kbCueGateRate"
|
||||||
|
type="number"
|
||||||
|
min="1"
|
||||||
|
max="50"
|
||||||
|
step="1"
|
||||||
|
class="fs-input input"
|
||||||
|
style="max-width: 8rem"
|
||||||
|
/>
|
||||||
|
<p class="field-hint">
|
||||||
|
A record or preference matched only by wording is shown when the message
|
||||||
|
resembles it better than all but this share of your recent messages did:
|
||||||
|
at most two lines, and none until {{ gateMinSample }} messages have been seen.
|
||||||
|
</p>
|
||||||
|
<ul v-if="gatedSurfaces.length" class="gate-readout">
|
||||||
|
<li v-for="g in gatedSurfaces" :key="g.surface">
|
||||||
|
<span class="tuning-surface">{{ g.surface }}</span>
|
||||||
|
<span class="gate-gates">{{ g.gates }}</span>
|
||||||
|
<span class="gate-state">{{ gateSummary(g) }}</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label for="kb-writepath-topk">Max prior-art lines per edit</label>
|
<label for="kb-writepath-topk">Max prior-art lines per edit</label>
|
||||||
<input
|
<input
|
||||||
@@ -4258,6 +4350,23 @@ async function deleteUser(userId: number) {
|
|||||||
font-family: var(--fs-font-mono);
|
font-family: var(--fs-font-mono);
|
||||||
color: var(--fs-text-primary);
|
color: var(--fs-text-primary);
|
||||||
}
|
}
|
||||||
|
.gate-readout {
|
||||||
|
list-style: none;
|
||||||
|
margin: var(--fs-space-2) 0 0;
|
||||||
|
padding: 0;
|
||||||
|
display: grid;
|
||||||
|
gap: var(--fs-space-1);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
.gate-readout li {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: var(--fs-space-2);
|
||||||
|
}
|
||||||
|
.gate-gates,
|
||||||
|
.gate-state {
|
||||||
|
color: var(--fs-text-secondary);
|
||||||
|
}
|
||||||
.tuning-dial,
|
.tuning-dial,
|
||||||
.tuning-move {
|
.tuning-move {
|
||||||
color: var(--fs-text-secondary);
|
color: var(--fs-text-secondary);
|
||||||
|
|||||||
@@ -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), 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), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
|
||||||
"version": "2026.11.22.2312",
|
"version": "2026.11.23.0004",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "Bryan Van Deusen"
|
"name": "Bryan Van Deusen"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -100,10 +100,10 @@ Two constraints on *how* that's achieved:
|
|||||||
**lesson** is what is worth knowing — a better way to think about a
|
**lesson** is what is worth knowing — a better way to think about a
|
||||||
problem, a solution that transfers — and ignoring it costs time. All three
|
problem, a solution that transfers — and ignoring it costs time. All three
|
||||||
are worth reading and all three arrive beside your work; only the first is
|
are worth reading and all three arrive beside your work; only the first is
|
||||||
a mistake to miss. An injected line names which in its opening words —
|
a mistake to miss. A line names which up front (*"Rule 11 …; it binds:"*,
|
||||||
*"Standing rule that may apply…"* against *"Preference that may apply…"* —
|
*"Preference 173 …; how this has been done before:"*) and on first mention
|
||||||
a lesson arrives in the records menu marked `lesson`, under a header that
|
quotes the statement; `get_rule(id)` gives the why and how. A lesson is
|
||||||
says outright that it binds nothing, and every payload carries `kind`.
|
marked `lesson` under a header saying it binds nothing; payloads carry `kind`.
|
||||||
|
|
||||||
**One question sorts them, and it is worth asking out loud: what happens if
|
**One question sorts them, and it is worth asking out loud: what happens if
|
||||||
someone doesn't do this?** *Something breaks, or a boundary is crossed* — a
|
someone doesn't do this?** *Something breaks, or a boundary is crossed* — a
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ asyncio_mode = "auto"
|
|||||||
testpaths = ["tests"]
|
testpaths = ["tests"]
|
||||||
markers = [
|
markers = [
|
||||||
"integration: requires a real Postgres database (runs only in the CI integration lane)",
|
"integration: requires a real Postgres database (runs only in the CI integration lane)",
|
||||||
|
"cue_gate: runs with the plugin doors' cue-swap gate on rather than stubbed off",
|
||||||
]
|
]
|
||||||
|
|
||||||
[tool.ruff]
|
[tool.ruff]
|
||||||
|
|||||||
@@ -781,6 +781,33 @@ def check_version_is_minted(base: str = "origin/main") -> None:
|
|||||||
ok(f"nothing version-relevant changed against {base} — no mint required")
|
ok(f"nothing version-relevant changed against {base} — no mint required")
|
||||||
|
|
||||||
|
|
||||||
|
# The lower of the two caps recorded for a hook's additional context: the docs
|
||||||
|
# give 10,000 characters, and an installed build has been read capping it at
|
||||||
|
# 8,000. Past the cap the model gets only a short preview.
|
||||||
|
HOOK_CONTEXT_CAP = 8_000
|
||||||
|
PAYLOAD_MODULE = ROOT / "src" / "grimoire" / "services" / "hook_payload.py"
|
||||||
|
|
||||||
|
|
||||||
|
def check_payload_bound() -> None:
|
||||||
|
"""The server fits every hook payload under `hook_payload.HARD_MAX`, and
|
||||||
|
that ceiling must sit under Claude Code's cap whatever a user sets."""
|
||||||
|
try:
|
||||||
|
text = PAYLOAD_MODULE.read_text()
|
||||||
|
except OSError:
|
||||||
|
fail(f"no payload assembler at {PAYLOAD_MODULE.relative_to(ROOT)}")
|
||||||
|
return
|
||||||
|
found = re.search(r"^HARD_MAX\s*=\s*([0-9_]+)\s*$", text, re.M)
|
||||||
|
if not found:
|
||||||
|
fail("hook_payload.HARD_MAX is not a literal this check can read")
|
||||||
|
return
|
||||||
|
hard_max = int(found.group(1).replace("_", ""))
|
||||||
|
if hard_max >= HOOK_CONTEXT_CAP:
|
||||||
|
fail(f"hook_payload.HARD_MAX is {hard_max}, at or past Claude Code's "
|
||||||
|
f"{HOOK_CONTEXT_CAP}-character hook context cap")
|
||||||
|
else:
|
||||||
|
ok(f"hook payloads are bounded at {hard_max} characters, under {HOOK_CONTEXT_CAP}")
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
parser = argparse.ArgumentParser(description=__doc__)
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
parser.add_argument("--no-version", action="store_true",
|
parser.add_argument("--no-version", action="store_true",
|
||||||
@@ -800,6 +827,7 @@ def main() -> int:
|
|||||||
check_fail_open()
|
check_fail_open()
|
||||||
check_local_prior_art_needs_no_instance()
|
check_local_prior_art_needs_no_instance()
|
||||||
check_session_context_reports_its_version()
|
check_session_context_reports_its_version()
|
||||||
|
check_payload_bound()
|
||||||
if not args.no_version:
|
if not args.no_version:
|
||||||
check_version_is_minted(args.base)
|
check_version_is_minted(args.base)
|
||||||
|
|
||||||
|
|||||||
@@ -74,6 +74,12 @@ class RetrievalLog(Base):
|
|||||||
# [{"id": int, "score": float, "rank": int}, ...], highest-first.
|
# [{"id": int, "score": float, "rank": int}, ...], highest-first.
|
||||||
result_ids: Mapped[list] = mapped_column(JSONB, nullable=False, default=list)
|
result_ids: Mapped[list] = mapped_column(JSONB, nullable=False, default=list)
|
||||||
duration_ms: Mapped[float | None] = mapped_column(Float, nullable=True)
|
duration_ms: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||||
|
# THE CUE-SWAP GATE, on a surface that has one (`cue_gate`): the score a
|
||||||
|
# line had to reach on this call, and how many lines reached it. Both null
|
||||||
|
# on an ungated surface. A count beside a null bar is a gate that had too
|
||||||
|
# few earlier cues to judge by, so nothing found by resemblance spoke.
|
||||||
|
gate_bar: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||||
|
gate_kept: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||||
|
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index("ix_retrieval_logs_created_at", "created_at"),
|
Index("ix_retrieval_logs_created_at", "created_at"),
|
||||||
@@ -99,4 +105,6 @@ class RetrievalLog(Base):
|
|||||||
"min_score": self.min_score,
|
"min_score": self.min_score,
|
||||||
"result_ids": self.result_ids,
|
"result_ids": self.result_ids,
|
||||||
"duration_ms": self.duration_ms,
|
"duration_ms": self.duration_ms,
|
||||||
|
"gate_bar": self.gate_bar,
|
||||||
|
"gate_kept": self.gate_kept,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ from quart import Blueprint, g, jsonify, request
|
|||||||
|
|
||||||
from grimoire.auth import admin_required, get_current_user_id, login_required
|
from grimoire.auth import admin_required, get_current_user_id, login_required
|
||||||
from grimoire.config import Config
|
from grimoire.config import Config
|
||||||
|
from grimoire.services import hook_payload as hook_payload_svc
|
||||||
from grimoire.services import lesson_rules as lesson_rules_svc
|
from grimoire.services import lesson_rules as lesson_rules_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
|
||||||
@@ -53,6 +54,17 @@ async def _bind_delivery_session() -> None:
|
|||||||
rule_deliveries_svc.bind_session(sid)
|
rule_deliveries_svc.bind_session(sid)
|
||||||
|
|
||||||
|
|
||||||
|
@plugin_bp.after_request
|
||||||
|
async def _flush_deliveries(response):
|
||||||
|
"""Write any rule deliveries a door rendered without fitting a payload.
|
||||||
|
|
||||||
|
A door that fits its payload (`hook_payload.fit`) has already written the
|
||||||
|
lines it kept and dropped the rest, so this finds nothing left for it.
|
||||||
|
"""
|
||||||
|
rule_deliveries_svc.flush()
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
def _int_list(raw: str | None) -> list[int]:
|
def _int_list(raw: str | None) -> list[int]:
|
||||||
"""A comma-separated id list from the query string; non-ints dropped."""
|
"""A comma-separated id list from the query string; non-ints dropped."""
|
||||||
return [int(p) for p in (raw or "").split(",") if p.strip().isdigit()]
|
return [int(p) for p in (raw or "").split(",") if p.strip().isdigit()]
|
||||||
@@ -155,10 +167,12 @@ async def autoinject_retrieve():
|
|||||||
ledger is swept on compaction, which is how the
|
ledger is swept on compaction, which is how the
|
||||||
full core comes back after one.
|
full core comes back after one.
|
||||||
|
|
||||||
THE TURN'S REPLY SHAPE COMES FIRST. Every turn ends
|
ONE PAYLOAD, IN ONE ORDER, UNDER ONE BUDGET (`hook_payload`): the rules
|
||||||
in a reply and this is the last point before it is written, so the core
|
this prompt reaches and those mounted on `reply.report`, then the turn's
|
||||||
shape and whatever is mounted on `reply.report` lead the payload. Fresh
|
reply shape, then the records menu. Every turn ends in a reply and this
|
||||||
shape keys come back as `shape_keys` for the ledger.
|
is the last point before it is written, so the shape rides every call;
|
||||||
|
what does not fit is left off the ledgers and can arrive on a later call.
|
||||||
|
Shape keys sent in full come back as `shape_keys` for the ledger.
|
||||||
|
|
||||||
TWO ARMS, TWO SETS OF GATES. Rules ride the same hook and the same query
|
TWO ARMS, TWO SETS OF GATES. Rules ride the same hook and the same query
|
||||||
but nothing else: the notes menu can be disabled, thresholded and top-k'd
|
but nothing else: the notes menu can be disabled, thresholded and top-k'd
|
||||||
@@ -199,12 +213,32 @@ async def autoinject_retrieve():
|
|||||||
project_id=project_id,
|
project_id=project_id,
|
||||||
exclude=frozenset(exclude_rule_ids) | frozenset(rules["rule_ids"]),
|
exclude=frozenset(exclude_rule_ids) | frozenset(rules["rule_ids"]),
|
||||||
held=frozenset(held_rule_ids),
|
held=frozenset(held_rule_ids),
|
||||||
|
record=False,
|
||||||
)
|
)
|
||||||
blocks = [b for b in (turn["context"], rules["context"], result["context"], proposal) if b]
|
# One payload, in the one order: the rules, then the reply shape, then
|
||||||
result["context"] = "\n\n".join(blocks)
|
# the records menu, then the lesson-rule proposal, fitted to the budget.
|
||||||
result["rule_ids"] = list(dict.fromkeys([*rules["rule_ids"], *turn["rule_ids"]]))
|
turn_parts = (
|
||||||
result["shape_keys"] = [k for k, form in turn["shape_forms"].items()
|
[*turn["rule_parts"], *turn["shape_parts"]] if "shape_parts" in turn
|
||||||
if form == reply_shapes_svc.FULL]
|
else [hook_payload_svc.Part(text=turn.get("context") or "", ids={
|
||||||
|
hook_payload_svc.RULE: tuple(turn.get("rule_ids") or ()),
|
||||||
|
hook_payload_svc.SHAPE: tuple(turn.get("shape_forms") or ()),
|
||||||
|
})]
|
||||||
|
)
|
||||||
|
fitted = await hook_payload_svc.fit(g.user.id, [
|
||||||
|
*hook_payload_svc.parts_of(rules, {hook_payload_svc.RULE: "shown_rule_ids"}),
|
||||||
|
*turn_parts,
|
||||||
|
*hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}),
|
||||||
|
*([hook_payload_svc.Part(text=proposal)] if proposal else []),
|
||||||
|
])
|
||||||
|
shapes = set(fitted.ids(hook_payload_svc.SHAPE))
|
||||||
|
forms = {k: f for k, f in turn["shape_forms"].items() if k in shapes}
|
||||||
|
await reply_shapes_svc.record_delivery(g.user.id, forms, via="turn")
|
||||||
|
result["context"] = fitted.context
|
||||||
|
result["note_ids"] = fitted.keep_only(hook_payload_svc.NOTE, result.get("note_ids"))
|
||||||
|
result["rule_ids"] = fitted.keep_only(
|
||||||
|
hook_payload_svc.RULE, dict.fromkeys([*rules["rule_ids"], *turn["rule_ids"]]),
|
||||||
|
)
|
||||||
|
result["shape_keys"] = [k for k, form in forms.items() if form == reply_shapes_svc.FULL]
|
||||||
return jsonify(result)
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
@@ -282,6 +316,15 @@ async def pre_tool_rules():
|
|||||||
cwd=(request.args.get("cwd") or "").strip(),
|
cwd=(request.args.get("cwd") or "").strip(),
|
||||||
seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")),
|
seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")),
|
||||||
)
|
)
|
||||||
|
fitted = await hook_payload_svc.fit(g.user.id, hook_payload_svc.parts_of(result, {
|
||||||
|
hook_payload_svc.RULE: "rule_ids", hook_payload_svc.RULING: "ruling_system_ids",
|
||||||
|
}))
|
||||||
|
result["context"] = fitted.context
|
||||||
|
result["rule_ids"] = fitted.keep_only(hook_payload_svc.RULE, result.get("rule_ids"))
|
||||||
|
if "ruling_system_ids" in result:
|
||||||
|
result["ruling_system_ids"] = fitted.keep_only(
|
||||||
|
hook_payload_svc.RULING, result["ruling_system_ids"],
|
||||||
|
)
|
||||||
return jsonify(result)
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
@@ -318,9 +361,10 @@ async def moment():
|
|||||||
`moments` (the names reached). A lookup, not a ranked search: no
|
`moments` (the names reached). A lookup, not a ranked search: no
|
||||||
retrieval_logs row; each fresh rule is recorded surfaced with its moment.
|
retrieval_logs row; each fresh rule is recorded surfaced with its moment.
|
||||||
|
|
||||||
A moment that carries a default reply shape brings it too,
|
A moment that carries a default reply shape brings it too, after the
|
||||||
ahead of the rules: in full unless `shapes_seen` names it, then as its
|
rules: in full unless `shapes_seen` names it, then as its reminder. The
|
||||||
reminder. `shape_keys` are the ones sent in full, for the hook's ledger.
|
payload is fitted to the user's budget (`hook_payload`), and `shape_keys`
|
||||||
|
are the ones sent in full and kept, for the hook's ledger.
|
||||||
"""
|
"""
|
||||||
event = await request.get_json(silent=True) or {}
|
event = await request.get_json(silent=True) or {}
|
||||||
tool = str(event.get("tool_name") or "").strip()
|
tool = str(event.get("tool_name") or "").strip()
|
||||||
@@ -337,11 +381,17 @@ async def moment():
|
|||||||
shapes, forms = moment_delivery_svc.shapes_for_act(
|
shapes, forms = moment_delivery_svc.shapes_for_act(
|
||||||
reached, reply_shapes_svc.parse_seen(request.args.get("shapes_seen")),
|
reached, reply_shapes_svc.parse_seen(request.args.get("shapes_seen")),
|
||||||
)
|
)
|
||||||
|
fitted = await hook_payload_svc.fit(g.user.id, [
|
||||||
|
*hook_payload_svc.rule_parts(result.lines, result.rule_per_line(), block="rules"),
|
||||||
|
*(hook_payload_svc.Part(text=block, ids={hook_payload_svc.SHAPE: (key,)})
|
||||||
|
for block, key in zip(shapes, forms, strict=False)),
|
||||||
|
])
|
||||||
|
kept_shapes = set(fitted.ids(hook_payload_svc.SHAPE))
|
||||||
|
forms = {k: f for k, f in forms.items() if k in kept_shapes}
|
||||||
await reply_shapes_svc.record_delivery(g.user.id, forms, via="hook")
|
await reply_shapes_svc.record_delivery(g.user.id, forms, via="hook")
|
||||||
context = "\n\n".join(b for b in ("\n\n".join(shapes), "\n".join(result.lines)) if b)
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"context": context,
|
"context": fitted.context,
|
||||||
"rule_ids": result.rule_ids,
|
"rule_ids": fitted.keep_only(hook_payload_svc.RULE, result.rule_ids),
|
||||||
"moments": [hit["moment"] for hit in reached],
|
"moments": [hit["moment"] for hit in reached],
|
||||||
"shape_keys": [k for k, form in forms.items() if form == reply_shapes_svc.FULL],
|
"shape_keys": [k for k, form in forms.items() if form == reply_shapes_svc.FULL],
|
||||||
})
|
})
|
||||||
@@ -537,6 +587,19 @@ async def write_path_prior_art():
|
|||||||
exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids,
|
exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids,
|
||||||
seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")),
|
seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")),
|
||||||
)
|
)
|
||||||
|
fitted = await hook_payload_svc.fit(g.user.id, hook_payload_svc.parts_of(result, {
|
||||||
|
hook_payload_svc.NOTE: "note_ids", hook_payload_svc.SYNC: "sync_note_ids",
|
||||||
|
hook_payload_svc.DERIVE: "derive_keys", hook_payload_svc.RULE: "rule_ids",
|
||||||
|
hook_payload_svc.RULING: "ruling_system_ids",
|
||||||
|
}))
|
||||||
|
result["context"] = fitted.context
|
||||||
|
for key, kind in (
|
||||||
|
("note_ids", hook_payload_svc.NOTE), ("sync_note_ids", hook_payload_svc.SYNC),
|
||||||
|
("derive_keys", hook_payload_svc.DERIVE), ("rule_ids", hook_payload_svc.RULE),
|
||||||
|
("ruling_system_ids", hook_payload_svc.RULING),
|
||||||
|
):
|
||||||
|
if key in result:
|
||||||
|
result[key] = fitted.keep_only(kind, result[key])
|
||||||
return jsonify(result)
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -57,6 +57,24 @@ async def get_surfaces_route():
|
|||||||
return jsonify({"surfaces": surfaces, "total": len(surfaces)})
|
return jsonify({"surfaces": surfaces, "total": len(surfaces)})
|
||||||
|
|
||||||
|
|
||||||
|
@retrieval_bp.route("/gate", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
async def get_gate_route():
|
||||||
|
"""The cue-swap gate on each surface it holds: the rate it speaks at, the
|
||||||
|
bar that rate comes to on the user's own recent cues, and how often each
|
||||||
|
surface actually spoke over the last week."""
|
||||||
|
from grimoire.services import cue_gate
|
||||||
|
from grimoire.services import retrieval_pipeline as rp
|
||||||
|
|
||||||
|
uid = get_current_user_id()
|
||||||
|
surfaces = [(arm.source, "records") for arm in rp.NOTE_ARMS if arm.gated] + [
|
||||||
|
(arm.source, "preferences") for arm in rp.RULE_ARMS if arm.gates_preferences
|
||||||
|
]
|
||||||
|
rows = await cue_gate.readout(uid, surfaces)
|
||||||
|
return jsonify({"surfaces": rows, "rate": rows[0]["rate"] if rows else cue_gate.RATE_DEFAULT,
|
||||||
|
"lines": cue_gate.LINES, "min_sample": cue_gate.MIN_SAMPLE})
|
||||||
|
|
||||||
|
|
||||||
@retrieval_bp.route("/surfaces/<surface>", methods=["PUT"])
|
@retrieval_bp.route("/surfaces/<surface>", methods=["PUT"])
|
||||||
@login_required
|
@login_required
|
||||||
async def tune_surface_route(surface: str):
|
async def tune_surface_route(surface: str):
|
||||||
|
|||||||
@@ -95,6 +95,10 @@ async def update_settings_route():
|
|||||||
|
|
||||||
if to_save:
|
if to_save:
|
||||||
await set_settings_batch(uid, to_save)
|
await set_settings_batch(uid, to_save)
|
||||||
|
# The gate caches its bar for a few minutes; a new rate takes at once.
|
||||||
|
from grimoire.services import cue_gate
|
||||||
|
if cue_gate.RATE_KEY in data:
|
||||||
|
cue_gate.forget(uid)
|
||||||
|
|
||||||
settings = await get_all_settings(uid)
|
settings = await get_all_settings(uid)
|
||||||
return jsonify(_masked(settings))
|
return jsonify(_masked(settings))
|
||||||
|
|||||||
@@ -0,0 +1,219 @@
|
|||||||
|
"""When a record found by resemblance alone may speak: the cue-swap gate.
|
||||||
|
|
||||||
|
WHY A FIXED BAR CANNOT DO THIS
|
||||||
|
|
||||||
|
Every message resembles something in a store of any size. The best score that
|
||||||
|
N unrelated records reach against a message keeps rising as N grows, so a
|
||||||
|
similarity bar that is quiet on a small store fires on nearly every message on
|
||||||
|
a large one: the bar measures the store, not the message. (*The Price of Scale
|
||||||
|
in Proactive Memory Recall*, arXiv 2610.34507: a cosine bar tuned to 5% false
|
||||||
|
alarms on 8 memories hit 84–100% at 2,048, and a cross-encoder fared no
|
||||||
|
better.) A floor tuned on one install says nothing about another, or about the
|
||||||
|
same install a year later.
|
||||||
|
|
||||||
|
WHAT THE GATE ASKS INSTEAD
|
||||||
|
|
||||||
|
Not "is this score high" but "is this message's best match unusual for this
|
||||||
|
reader". The comparison set is the best score each of the user's own recent
|
||||||
|
messages reached on the same surface and scope — already in `retrieval_logs`
|
||||||
|
as `best_available_score`, measured before any bar. A line may speak only when
|
||||||
|
its score beats all but `rate` of them: a conformal test whose null is the
|
||||||
|
user's other cues against (very nearly) the same store. Because the null is
|
||||||
|
drawn from the same store, the bar rises with the store by construction, and
|
||||||
|
on cues that match nothing in particular it fires at about `rate` however large
|
||||||
|
the store grows.
|
||||||
|
|
||||||
|
The recent messages include relevant ones, so the comparison set runs high
|
||||||
|
and the gate errs toward silence. That is the intended direction: injected
|
||||||
|
retrieval has measured below no memory at all in three independent benchmarks,
|
||||||
|
so a missed line costs less than a wrong one,
|
||||||
|
and every record stays one `search` away.
|
||||||
|
|
||||||
|
TOO FEW CUES TO JUDGE BY IS SILENCE. Until `MIN_SAMPLE` messages have been
|
||||||
|
searched on a surface, nothing found by resemblance is shown there. The
|
||||||
|
searches still run and are still logged, so the gate calibrates itself within
|
||||||
|
a session or so; records reached by number, path or moment are not gated.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
from grimoire.services.settings import get_setting
|
||||||
|
|
||||||
|
RATE_KEY = "kb_cue_gate_rate"
|
||||||
|
# Percent of cues a gated surface may speak on when they match nothing in
|
||||||
|
# particular. The paper's cue-swap gate fired on 6–8% against 57% for the
|
||||||
|
# deployed similarity bar; 10 sits just above it so a store whose cues are
|
||||||
|
# mostly relevant is not muted outright.
|
||||||
|
RATE_DEFAULT = 10
|
||||||
|
RATE_MIN, RATE_MAX = 1, 50
|
||||||
|
|
||||||
|
# At most this many lines found by resemblance per call, whatever the arm's
|
||||||
|
# search width: the top one or two, and the reader asks for more.
|
||||||
|
LINES = 2
|
||||||
|
|
||||||
|
SAMPLE = 200
|
||||||
|
MIN_SAMPLE = 20
|
||||||
|
WINDOW_DAYS = 30
|
||||||
|
_TTL_SECONDS = 300.0
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Gate:
|
||||||
|
"""The bar one surface's lines must reach on this call."""
|
||||||
|
|
||||||
|
bar: float | None
|
||||||
|
"""None when there are too few cues to judge by: nothing passes."""
|
||||||
|
|
||||||
|
sample: int
|
||||||
|
rate: int
|
||||||
|
scope: str = "project"
|
||||||
|
""""project" when the comparison set is this project's own cues, "all"
|
||||||
|
when there were too few and the user's cues everywhere stood in."""
|
||||||
|
|
||||||
|
def passes(self, score: float) -> bool:
|
||||||
|
return self.bar is not None and float(score) >= self.bar
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
return {"bar": None if self.bar is None else round(self.bar, 4),
|
||||||
|
"sample": self.sample, "rate": self.rate, "scope": self.scope,
|
||||||
|
"calibrated": self.bar is not None}
|
||||||
|
|
||||||
|
|
||||||
|
OPEN = Gate(bar=-math.inf, sample=0, rate=100, scope="open")
|
||||||
|
"""Everything passes — for a caller that has no gate to apply."""
|
||||||
|
|
||||||
|
|
||||||
|
def clamp_rate(raw) -> int:
|
||||||
|
try:
|
||||||
|
n = int(float(raw))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return RATE_DEFAULT
|
||||||
|
return max(RATE_MIN, min(RATE_MAX, n))
|
||||||
|
|
||||||
|
|
||||||
|
def conformal_bar(null_scores, rate: int) -> float | None:
|
||||||
|
"""The score a cue must reach to beat all but `rate`% of `null_scores`.
|
||||||
|
|
||||||
|
With K cues sorted ascending, a score at or above the k-th, where
|
||||||
|
k = ceil((K + 1) * (1 - rate / 100)), has a conformal p-value of at most
|
||||||
|
`rate`%. None when K is too small for any score to get there.
|
||||||
|
"""
|
||||||
|
scores = sorted(float(s) for s in null_scores if s is not None)
|
||||||
|
k = math.ceil((len(scores) + 1) * (1 - rate / 100.0))
|
||||||
|
if len(scores) < MIN_SAMPLE or k > len(scores) or k < 1:
|
||||||
|
return None
|
||||||
|
return scores[k - 1]
|
||||||
|
|
||||||
|
|
||||||
|
_cache: dict[tuple, tuple[float, Gate]] = {}
|
||||||
|
|
||||||
|
|
||||||
|
async def _null_scores(user_id: int, source: str, project_id: int | None,
|
||||||
|
*, any_project: bool) -> list[float]:
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from grimoire.models import async_session
|
||||||
|
from grimoire.models.retrieval_log import RetrievalLog
|
||||||
|
|
||||||
|
since = datetime.now(timezone.utc) - timedelta(days=WINDOW_DAYS)
|
||||||
|
stmt = (
|
||||||
|
select(RetrievalLog.best_available_score)
|
||||||
|
.where(
|
||||||
|
RetrievalLog.source == source,
|
||||||
|
RetrievalLog.user_id == user_id,
|
||||||
|
RetrievalLog.created_at >= since,
|
||||||
|
RetrievalLog.best_available_score.isnot(None),
|
||||||
|
)
|
||||||
|
.order_by(RetrievalLog.created_at.desc())
|
||||||
|
.limit(SAMPLE)
|
||||||
|
)
|
||||||
|
if not any_project:
|
||||||
|
stmt = stmt.where(RetrievalLog.project_id.is_not_distinct_from(project_id))
|
||||||
|
async with async_session() as session:
|
||||||
|
return [float(s) for (s,) in (await session.execute(stmt)).all()]
|
||||||
|
|
||||||
|
|
||||||
|
async def gate_for(user_id: int, source: str, project_id: int | None) -> Gate:
|
||||||
|
"""This surface's gate for this user and scope, cached for a few minutes.
|
||||||
|
|
||||||
|
The comparison set moves by one cue per call, so re-reading it on every
|
||||||
|
call buys nothing: a bar five minutes old is the same bar. A read that
|
||||||
|
fails is a gate that cannot judge, which is silence.
|
||||||
|
"""
|
||||||
|
project_id = project_id or None
|
||||||
|
key = (user_id, source, project_id)
|
||||||
|
hit = _cache.get(key)
|
||||||
|
now = time.monotonic()
|
||||||
|
if hit and now - hit[0] < _TTL_SECONDS:
|
||||||
|
return hit[1]
|
||||||
|
try:
|
||||||
|
rate = clamp_rate(await get_setting(user_id, RATE_KEY, str(RATE_DEFAULT)))
|
||||||
|
except Exception: # noqa: BLE001 - a settings read never costs the gate
|
||||||
|
rate = RATE_DEFAULT
|
||||||
|
try:
|
||||||
|
scores = await _null_scores(user_id, source, project_id, any_project=False)
|
||||||
|
scope = "project"
|
||||||
|
if len(scores) < MIN_SAMPLE and project_id is not None:
|
||||||
|
scores = await _null_scores(user_id, source, project_id, any_project=True)
|
||||||
|
scope = "all"
|
||||||
|
gate = Gate(bar=conformal_bar(scores, rate), sample=len(scores),
|
||||||
|
rate=rate, scope=scope)
|
||||||
|
except Exception: # noqa: BLE001 - an unreadable gate is a quiet one
|
||||||
|
gate = Gate(bar=None, sample=0, rate=rate, scope="unreadable")
|
||||||
|
_cache[key] = (now, gate)
|
||||||
|
return gate
|
||||||
|
|
||||||
|
|
||||||
|
def forget(user_id: int | None = None) -> None:
|
||||||
|
"""Drop cached gates — after the rate setting changes, so it takes at once."""
|
||||||
|
if user_id is None:
|
||||||
|
_cache.clear()
|
||||||
|
return
|
||||||
|
for key in [k for k in _cache if k[0] == user_id]:
|
||||||
|
_cache.pop(key, None)
|
||||||
|
|
||||||
|
|
||||||
|
async def readout(user_id: int, surfaces: list[tuple[str, str]], *, days: int = 7) -> list[dict]:
|
||||||
|
"""Each gated surface as Settings shows it: the bar it holds lines to now,
|
||||||
|
from the user's cues on every project, and how often it spoke lately.
|
||||||
|
|
||||||
|
`surfaces` is `(source, what it gates)` pairs. `fired` counts calls in the
|
||||||
|
last `days` where at least one line passed; `calls` every gated call.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
|
||||||
|
from grimoire.models import async_session
|
||||||
|
from grimoire.models.retrieval_log import RetrievalLog
|
||||||
|
|
||||||
|
try:
|
||||||
|
rate = clamp_rate(await get_setting(user_id, RATE_KEY, str(RATE_DEFAULT)))
|
||||||
|
except Exception: # noqa: BLE001 - a settings read never costs the readout
|
||||||
|
rate = RATE_DEFAULT
|
||||||
|
since = datetime.now(timezone.utc) - timedelta(days=days)
|
||||||
|
out: list[dict] = []
|
||||||
|
for source, gates in surfaces:
|
||||||
|
row = {"surface": source, "gates": gates, "rate": rate, "bar": None,
|
||||||
|
"sample": 0, "calls": 0, "fired": 0, "days": days}
|
||||||
|
try:
|
||||||
|
scores = await _null_scores(user_id, source, None, any_project=True)
|
||||||
|
bar = conformal_bar(scores, rate)
|
||||||
|
row["bar"] = None if bar is None else round(bar, 4)
|
||||||
|
row["sample"] = len(scores)
|
||||||
|
async with async_session() as session:
|
||||||
|
calls, fired = (await session.execute(
|
||||||
|
select(func.count(),
|
||||||
|
func.count().filter(RetrievalLog.gate_kept > 0))
|
||||||
|
.where(RetrievalLog.user_id == user_id,
|
||||||
|
RetrievalLog.source == source,
|
||||||
|
RetrievalLog.created_at >= since,
|
||||||
|
RetrievalLog.gate_kept.isnot(None))
|
||||||
|
)).one()
|
||||||
|
row["calls"], row["fired"] = int(calls or 0), int(fired or 0)
|
||||||
|
except Exception: # noqa: BLE001 - one unreadable surface leaves the rest
|
||||||
|
row["unreadable"] = True
|
||||||
|
out.append(row)
|
||||||
|
return out
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
"""What one hook call puts in front of the session, fitted to a budget.
|
||||||
|
|
||||||
|
Every plugin door that injects context builds its payload as `Part`s in one
|
||||||
|
priority order: rules first, then the reply shape, then prior art and the
|
||||||
|
rest. `assemble` keeps parts in that order while they fit and leaves out
|
||||||
|
whole any that do not. A part's ids leave with it, so the plugin's ledgers
|
||||||
|
mark only what the session was actually shown and a trimmed record can still
|
||||||
|
arrive on a later call. `fit` is the one call a door makes: it reads the
|
||||||
|
user's budget, assembles, and records the rule deliveries that made it in.
|
||||||
|
|
||||||
|
Claude Code caps a hook's additional context: its docs give 10,000
|
||||||
|
characters, past which the model gets a 2,000-character preview it is not
|
||||||
|
asked to open, and an installed build has been read capping it at 8,000.
|
||||||
|
`HARD_MAX` sits under the lower figure whatever the setting says, with room
|
||||||
|
for the lines a hook adds on its own side.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
HARD_MAX = 7500
|
||||||
|
MIN_BUDGET = 1000
|
||||||
|
# Fits the full core reply shape (about 2,300 characters) beside two full rule
|
||||||
|
# lines (up to about 750 each) with room for a few records.
|
||||||
|
DEFAULT_BUDGET = 4500
|
||||||
|
BUDGET_KEY = "kb_hook_budget_chars"
|
||||||
|
|
||||||
|
# The id kinds a part can carry, each the source of one response list.
|
||||||
|
RULE = "rule"
|
||||||
|
SHAPE = "shape"
|
||||||
|
NOTE = "note"
|
||||||
|
SYNC = "sync"
|
||||||
|
DERIVE = "derive"
|
||||||
|
RULING = "ruling"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Part:
|
||||||
|
"""One unit the assembler keeps or drops whole.
|
||||||
|
|
||||||
|
Parts sharing a `block` print as consecutive lines, and the block's
|
||||||
|
`header` prints once, before its first kept part, and is charged to it.
|
||||||
|
A part with no block is a block of its own. Blocks are separated by a
|
||||||
|
blank line.
|
||||||
|
"""
|
||||||
|
|
||||||
|
text: str
|
||||||
|
block: str = ""
|
||||||
|
header: str = ""
|
||||||
|
ids: dict[str, tuple] = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Fitted:
|
||||||
|
context: str = ""
|
||||||
|
kept: list[Part] = field(default_factory=list)
|
||||||
|
dropped: list[Part] = field(default_factory=list)
|
||||||
|
|
||||||
|
def ids(self, kind: str) -> list:
|
||||||
|
"""The ids of this kind on kept parts, in payload order."""
|
||||||
|
return list(dict.fromkeys(i for p in self.kept for i in p.ids.get(kind, ())))
|
||||||
|
|
||||||
|
def keep_only(self, kind: str, values) -> list:
|
||||||
|
"""`values` filtered to those a kept part carries, order preserved."""
|
||||||
|
kept = set(self.ids(kind))
|
||||||
|
return [v for v in (values or []) if v in kept]
|
||||||
|
|
||||||
|
|
||||||
|
def clamp(budget) -> int:
|
||||||
|
try:
|
||||||
|
n = int(budget)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
n = DEFAULT_BUDGET
|
||||||
|
return max(MIN_BUDGET, min(HARD_MAX, n))
|
||||||
|
|
||||||
|
|
||||||
|
async def payload_budget(user_id: int) -> int:
|
||||||
|
from grimoire.services.settings import get_setting
|
||||||
|
|
||||||
|
try:
|
||||||
|
return clamp(await get_setting(user_id, BUDGET_KEY, str(DEFAULT_BUDGET)))
|
||||||
|
except Exception: # noqa: BLE001 - a settings read never costs the payload
|
||||||
|
return DEFAULT_BUDGET
|
||||||
|
|
||||||
|
|
||||||
|
def assemble(parts, budget: int) -> Fitted:
|
||||||
|
"""Keep `parts` in order while the joined payload stays within `budget`.
|
||||||
|
|
||||||
|
A part that does not fit is skipped, not a stopping point: a smaller,
|
||||||
|
lower-priority part after it may still fit.
|
||||||
|
"""
|
||||||
|
budget = clamp(budget)
|
||||||
|
blocks: list[tuple[object, list[str]]] = []
|
||||||
|
started: set = set()
|
||||||
|
used = 0
|
||||||
|
out = Fitted()
|
||||||
|
for part in parts:
|
||||||
|
text = (part.text or "").strip("\n")
|
||||||
|
if not text.strip():
|
||||||
|
continue
|
||||||
|
key = part.block or id(part)
|
||||||
|
lines = [text]
|
||||||
|
if part.header and key not in started:
|
||||||
|
lines.insert(0, part.header)
|
||||||
|
joins_last = bool(blocks) and blocks[-1][0] == key
|
||||||
|
sep = 1 if joins_last else (2 if blocks else 0)
|
||||||
|
cost = sep + len("\n".join(lines))
|
||||||
|
if used + cost > budget:
|
||||||
|
out.dropped.append(part)
|
||||||
|
continue
|
||||||
|
used += cost
|
||||||
|
if joins_last:
|
||||||
|
blocks[-1][1].extend(lines)
|
||||||
|
else:
|
||||||
|
blocks.append((key, lines))
|
||||||
|
started.add(key)
|
||||||
|
out.kept.append(part)
|
||||||
|
out.context = "\n\n".join("\n".join(lines) for _key, lines in blocks)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
async def fit(user_id: int, parts) -> Fitted:
|
||||||
|
"""Assemble under this user's budget and record the rule lines delivered."""
|
||||||
|
from grimoire.services import rule_deliveries
|
||||||
|
|
||||||
|
fitted = assemble(list(parts), await payload_budget(user_id))
|
||||||
|
rule_deliveries.flush(set(fitted.ids(RULE)))
|
||||||
|
return fitted
|
||||||
|
|
||||||
|
|
||||||
|
def parts_of(result: dict, ids: dict[str, str]) -> list[Part]:
|
||||||
|
"""A builder result's parts, removed from it so it can be serialised.
|
||||||
|
|
||||||
|
A result that carries none is one part: its whole `context`, holding
|
||||||
|
every id its `ids` map names (`{kind: result key}`).
|
||||||
|
"""
|
||||||
|
parts = result.pop("parts", None)
|
||||||
|
if parts is not None:
|
||||||
|
return list(parts)
|
||||||
|
text = result.get("context") or ""
|
||||||
|
if not text:
|
||||||
|
return []
|
||||||
|
return [Part(text=text, ids={
|
||||||
|
kind: tuple(result.get(key) or ()) for kind, key in ids.items()
|
||||||
|
})]
|
||||||
|
|
||||||
|
|
||||||
|
def rule_parts(lines: list[str], rule_ids: list[int], *, block: str) -> list[Part]:
|
||||||
|
"""One part per rule line, each carrying the rule it names."""
|
||||||
|
return [
|
||||||
|
Part(text=line, block=block, ids={RULE: (rid,)} if rid else {})
|
||||||
|
for line, rid in zip(lines, list(rule_ids) + [0] * (len(lines) - len(rule_ids)), strict=False)
|
||||||
|
]
|
||||||
@@ -16,7 +16,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
from grimoire.services import moment_actions, reply_shapes
|
from grimoire.services import hook_payload, moment_actions, reply_shapes
|
||||||
from grimoire.services import retrieval_pipeline as rp
|
from grimoire.services import retrieval_pipeline as rp
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -147,6 +147,7 @@ _REACHED_BY_TURN = "the reply this turn will end with"
|
|||||||
async def deliver_for_turn(
|
async def deliver_for_turn(
|
||||||
user_id: int, *, seen: frozenset[str] = frozenset(), project_id: int | None = None,
|
user_id: int, *, seen: frozenset[str] = frozenset(), project_id: int | None = None,
|
||||||
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
||||||
|
record: bool = True,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""What every turn carries before its reply is written.
|
"""What every turn carries before its reply is written.
|
||||||
|
|
||||||
@@ -157,10 +158,17 @@ async def deliver_for_turn(
|
|||||||
the reply exists, which is too late to shape it and is kept as the
|
the reply exists, which is too late to shape it and is kept as the
|
||||||
backstop; this is the point before.
|
backstop; this is the point before.
|
||||||
|
|
||||||
Returns `{context, rule_ids, shape_forms}`. Fails open to the core alone,
|
Returns `{context, rule_ids, shape_forms, shape_parts, rule_parts}`; the
|
||||||
and the core itself never fails: it is a constant.
|
parts are for a door that fits its payload, which passes `record=False`
|
||||||
|
and records the shapes it kept. Fails open to the core alone, and the
|
||||||
|
core itself never fails: it is a constant.
|
||||||
"""
|
"""
|
||||||
blocks, forms = reply_shapes.deliver([reply_shapes.core()], seen)
|
blocks, forms = reply_shapes.deliver([reply_shapes.core()], seen)
|
||||||
|
shape_parts = [
|
||||||
|
hook_payload.Part(text=block, ids={hook_payload.SHAPE: (key,)})
|
||||||
|
for block, key in zip(blocks, forms, strict=False)
|
||||||
|
]
|
||||||
|
rule_parts: list[hook_payload.Part] = []
|
||||||
rule_ids: list[int] = []
|
rule_ids: list[int] = []
|
||||||
try:
|
try:
|
||||||
reached = [{"moment": "reply.report", "tool": "", "match": _REACHED_BY_TURN,
|
reached = [{"moment": "reply.report", "tool": "", "match": _REACHED_BY_TURN,
|
||||||
@@ -170,10 +178,17 @@ async def deliver_for_turn(
|
|||||||
)
|
)
|
||||||
blocks.extend(result.lines)
|
blocks.extend(result.lines)
|
||||||
rule_ids = result.rule_ids
|
rule_ids = result.rule_ids
|
||||||
|
rule_parts = hook_payload.rule_parts(
|
||||||
|
result.lines, result.rule_per_line(), block="rules",
|
||||||
|
)
|
||||||
except Exception: # noqa: BLE001 - the mounted half never costs the core
|
except Exception: # noqa: BLE001 - the mounted half never costs the core
|
||||||
logger.debug("reply.report mounts not delivered for the turn", exc_info=True)
|
logger.debug("reply.report mounts not delivered for the turn", exc_info=True)
|
||||||
await reply_shapes.record_delivery(user_id, forms, via="turn")
|
if record:
|
||||||
return {"context": "\n\n".join(blocks), "rule_ids": rule_ids, "shape_forms": forms}
|
await reply_shapes.record_delivery(user_id, forms, via="turn")
|
||||||
|
return {
|
||||||
|
"context": "\n\n".join(blocks), "rule_ids": rule_ids, "shape_forms": forms,
|
||||||
|
"shape_parts": shape_parts, "rule_parts": rule_parts,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
async def attach_moment_rules(
|
async def attach_moment_rules(
|
||||||
|
|||||||
@@ -17,9 +17,10 @@ from __future__ import annotations
|
|||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
import textwrap
|
import textwrap
|
||||||
|
from dataclasses import replace
|
||||||
|
|
||||||
from grimoire.services import design_systems as design_systems_svc
|
from grimoire.services import design_systems as design_systems_svc
|
||||||
|
from grimoire.services import cue_gate, hook_payload
|
||||||
from grimoire.services import knowledge as knowledge_svc
|
from grimoire.services import knowledge as knowledge_svc
|
||||||
from grimoire.services import notes as notes_svc
|
from grimoire.services import notes as notes_svc
|
||||||
from grimoire.services import projects as projects_svc
|
from grimoire.services import projects as projects_svc
|
||||||
@@ -451,6 +452,22 @@ _NO_SUBJECT_WORDS = frozenset("""
|
|||||||
""".split())
|
""".split())
|
||||||
|
|
||||||
|
|
||||||
|
# A TURN THE HARNESS WROTE. Claude Code delivers a background task's
|
||||||
|
# completion, a slash command's expansion and a local command's output as if
|
||||||
|
# the operator had typed them. None is a question about anything, so none is
|
||||||
|
# searched: the plugin skips them before calling, and the server refuses them
|
||||||
|
# too, for a plugin that predates the skip.
|
||||||
|
_HARNESS_OPENINGS = (
|
||||||
|
"<task-notification>", "<agent-message>", "<agent-message ",
|
||||||
|
"<command-name>", "<command-message>", "<command-args>",
|
||||||
|
"<local-command-stdout>", "<local-command-stderr>", "<local-command-caveat>",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def is_harness_turn(prompt: str) -> bool:
|
||||||
|
return (prompt or "").lstrip().startswith(_HARNESS_OPENINGS)
|
||||||
|
|
||||||
|
|
||||||
def _has_subject(prompt: str) -> bool:
|
def _has_subject(prompt: str) -> bool:
|
||||||
"""Does the operator's message name anything a record could be about?
|
"""Does the operator's message name anything a record could be about?
|
||||||
|
|
||||||
@@ -646,7 +663,7 @@ async def build_autoinject_hint(
|
|||||||
cfg = await get_autoinject_config(user_id)
|
cfg = await get_autoinject_config(user_id)
|
||||||
empty = {"context": "", "note_ids": [], "config": cfg}
|
empty = {"context": "", "note_ids": [], "config": cfg}
|
||||||
q = (query or "").strip()
|
q = (query or "").strip()
|
||||||
if not cfg["enabled"] or not q:
|
if not cfg["enabled"] or not q or is_harness_turn(q):
|
||||||
return empty
|
return empty
|
||||||
# RECORDS NAMED BY NUMBER, read from the operator's own words before
|
# RECORDS NAMED BY NUMBER, read from the operator's own words before
|
||||||
# the query is enriched: a number in the assistant's reply is not one the
|
# the query is enriched: a number in the assistant's reply is not one the
|
||||||
@@ -711,27 +728,37 @@ async def build_autoinject_hint(
|
|||||||
|
|
||||||
lines: list[str] = []
|
lines: list[str] = []
|
||||||
note_ids: list[int] = []
|
note_ids: list[int] = []
|
||||||
|
# The same menu as parts, one per record, for a door that fits its payload
|
||||||
|
# to a budget (`hook_payload`): a block's header rides its first kept record.
|
||||||
|
parts: list[hook_payload.Part] = []
|
||||||
|
named_header = ""
|
||||||
# FIRST, because the operator said which record they meant and everything
|
# FIRST, because the operator said which record they meant and everything
|
||||||
# after this block is a guess at what else might bear on it. The header
|
# after this block is a guess at what else might bear on it. The header
|
||||||
# says these were found by NUMBER: the parser reads "with 4448" as a
|
# says these were found by NUMBER: the parser reads "with 4448" as a
|
||||||
# reference, and the reader is the one placed to notice it was a quantity.
|
# reference, and the reader is the one placed to notice it was a quantity.
|
||||||
if named:
|
if named:
|
||||||
lines.append(
|
named_header = (
|
||||||
"> Named in your message — the records with those numbers, looked "
|
"> Named in your message — the records with those numbers, looked "
|
||||||
"up by id rather than matched. Open any in full with `get_note(id)`; "
|
"up by id rather than matched. Open any in full with `get_note(id)`; "
|
||||||
"a line marked `seen` is already in your context:"
|
"a line marked `seen` is already in your context:"
|
||||||
)
|
)
|
||||||
|
lines.append(named_header)
|
||||||
for note in named:
|
for note in named:
|
||||||
nid = int(note.id)
|
nid = int(note.id)
|
||||||
note_ids.append(nid)
|
note_ids.append(nid)
|
||||||
# The OPENING under the line, not a passage: nothing matched here, so
|
# The OPENING under the line, not a passage: nothing matched here, so
|
||||||
# there is no passage to keep, and what the reader needs is what the
|
# there is no passage to keep, and what the reader needs is what the
|
||||||
# record IS — which is where a record says it.
|
# record IS — which is where a record says it.
|
||||||
lines.extend(menu_entry(
|
entry = menu_entry(
|
||||||
nid, kind=_record_kind(note),
|
nid, kind=_record_kind(note),
|
||||||
name=_menu_name(note.title, note.note_type, note.data, note.body),
|
name=_menu_name(note.title, note.note_type, note.data, note.body),
|
||||||
systems=systems.get(nid), seen=nid in already, stale=nid in stale,
|
systems=systems.get(nid), seen=nid in already, stale=nid in stale,
|
||||||
shared_by=_shared_by(note), under=_named_opening(note.body),
|
shared_by=_shared_by(note), under=_named_opening(note.body),
|
||||||
|
)
|
||||||
|
lines.extend(entry)
|
||||||
|
parts.append(hook_payload.Part(
|
||||||
|
text="\n".join(entry), block="named", header=named_header,
|
||||||
|
ids={hook_payload.NOTE: (nid,)},
|
||||||
))
|
))
|
||||||
|
|
||||||
# "records", not "notes" — the menu can hold snippets, processes and tasks
|
# "records", not "notes" — the menu can hold snippets, processes and tasks
|
||||||
@@ -740,6 +767,7 @@ async def build_autoinject_hint(
|
|||||||
# A repeat is shown again with a marker rather than withheld, so the header
|
# A repeat is shown again with a marker rather than withheld, so the header
|
||||||
# says what the marker means, once, rather than each repeated line having
|
# says what the marker means, once, rather than each repeated line having
|
||||||
# to explain itself.
|
# to explain itself.
|
||||||
|
head_at = len(lines)
|
||||||
if kept:
|
if kept:
|
||||||
lines.append(
|
lines.append(
|
||||||
"> Possibly relevant from your Grimoire records — open any in full with "
|
"> Possibly relevant from your Grimoire records — open any in full with "
|
||||||
@@ -771,6 +799,7 @@ async def build_autoinject_hint(
|
|||||||
"what you are doing and use your judgement — a lesson is not a "
|
"what you are doing and use your judgement — a lesson is not a "
|
||||||
"rule and binds nothing."
|
"rule and binds nothing."
|
||||||
)
|
)
|
||||||
|
kept_header = "\n".join(lines[head_at:])
|
||||||
|
|
||||||
for score, note in kept:
|
for score, note in kept:
|
||||||
nid = int(note.id)
|
nid = int(note.id)
|
||||||
@@ -789,11 +818,16 @@ async def build_autoinject_hint(
|
|||||||
(chunks.get(nid) or {}).get("text"), name,
|
(chunks.get(nid) or {}).get("text"), name,
|
||||||
)
|
)
|
||||||
who = _shared_by(note)
|
who = _shared_by(note)
|
||||||
lines.extend(menu_entry(
|
entry = menu_entry(
|
||||||
nid, kind=_record_kind(note), name=name, systems=systems.get(nid),
|
nid, kind=_record_kind(note), name=name, systems=systems.get(nid),
|
||||||
seen=nid in already, stale=nid in stale, score=score,
|
seen=nid in already, stale=nid in stale, score=score,
|
||||||
shared_by=f"{who}, treat as a suggestion" if who else "",
|
shared_by=f"{who}, treat as a suggestion" if who else "",
|
||||||
under=passage,
|
under=passage,
|
||||||
|
)
|
||||||
|
lines.extend(entry)
|
||||||
|
parts.append(hook_payload.Part(
|
||||||
|
text="\n".join(entry), block="kept", header=kept_header,
|
||||||
|
ids={hook_payload.NOTE: (nid,)},
|
||||||
))
|
))
|
||||||
|
|
||||||
# A lookup, not a ranking, so it writes no retrieval_logs row — there is no
|
# A lookup, not a ranking, so it writes no retrieval_logs row — there is no
|
||||||
@@ -818,7 +852,7 @@ async def build_autoinject_hint(
|
|||||||
]
|
]
|
||||||
return {
|
return {
|
||||||
"context": "\n".join(lines), "note_ids": note_ids, "config": cfg,
|
"context": "\n".join(lines), "note_ids": note_ids, "config": cfg,
|
||||||
"lesson_ids": lesson_ids,
|
"lesson_ids": lesson_ids, "parts": parts,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -829,9 +863,15 @@ def _note_io() -> rp.NoteIO:
|
|||||||
search=semantic_search_notes,
|
search=semantic_search_notes,
|
||||||
record_retrieval=record_retrieval,
|
record_retrieval=record_retrieval,
|
||||||
record_surfaced=record_surfaced,
|
record_surfaced=record_surfaced,
|
||||||
|
gate=_gate_for,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def _gate_for(user_id: int, source: str, project_id):
|
||||||
|
"""`cue_gate.gate_for`, read at call time like the rest of the door's IO."""
|
||||||
|
return await cue_gate.gate_for(user_id, source, project_id)
|
||||||
|
|
||||||
|
|
||||||
async def _rules_via_lessons(
|
async def _rules_via_lessons(
|
||||||
user_id: int, query: str, *, project_id: int | None, skip: set[int],
|
user_id: int, query: str, *, project_id: int | None, skip: set[int],
|
||||||
held: set[int], where: str,
|
held: set[int], where: str,
|
||||||
@@ -886,6 +926,7 @@ async def _rule_moment(
|
|||||||
skip=set(moment.exclude) | set(result.shown_rule_ids),
|
skip=set(moment.exclude) | set(result.shown_rule_ids),
|
||||||
held=set(moment.held), where=moment.where,
|
held=set(moment.held), where=moment.where,
|
||||||
)
|
)
|
||||||
|
result.line_rule_ids = [*result.rule_per_line(), *ids]
|
||||||
result.lines.extend(lines)
|
result.lines.extend(lines)
|
||||||
result.rule_ids.extend(ids)
|
result.rule_ids.extend(ids)
|
||||||
return result
|
return result
|
||||||
@@ -919,7 +960,7 @@ async def build_prompt_rule_hint(
|
|||||||
THE OUTPUT IS DELIBERATELY NOT QUOTED, where the notes menu is, and the
|
THE OUTPUT IS DELIBERATELY NOT QUOTED, where the notes menu is, and the
|
||||||
two share no header. A note line is a bare title and needs the menu's header to say what
|
two share no header. A note line is a bare title and needs the menu's header to say what
|
||||||
it is doing there, while a rule line names itself in its opening words
|
it is doing there, while a rule line names itself in its opening words
|
||||||
("Standing rule that may apply…" / "Preference that may apply…"). Leaving
|
("Rule N …; it binds" / "Preference N …; how this has been done before"). Leaving
|
||||||
rules unquoted separates the two claims visually with no extra prose, and
|
rules unquoted separates the two claims visually with no extra prose, and
|
||||||
matches how a rule line already renders on both act arms.
|
matches how a rule line already renders on both act arms.
|
||||||
|
|
||||||
@@ -932,7 +973,7 @@ async def build_prompt_rule_hint(
|
|||||||
"""
|
"""
|
||||||
out: dict = {"context": "", "rule_ids": []}
|
out: dict = {"context": "", "rule_ids": []}
|
||||||
q = (query or "").strip()
|
q = (query or "").strip()
|
||||||
if not q:
|
if not q or is_harness_turn(q):
|
||||||
return out
|
return out
|
||||||
# The same enrichment the notes arm gets. A rule is meant to
|
# The same enrichment the notes arm gets. A rule is meant to
|
||||||
# arrive while the work it governs is under way, not once the operator
|
# arrive while the work it governs is under way, not once the operator
|
||||||
@@ -958,6 +999,9 @@ async def build_prompt_rule_hint(
|
|||||||
if result.lines:
|
if result.lines:
|
||||||
out["context"] = "\n".join(result.lines)
|
out["context"] = "\n".join(result.lines)
|
||||||
out["rule_ids"] = result.rule_ids
|
out["rule_ids"] = result.rule_ids
|
||||||
|
out["parts"] = hook_payload.rule_parts(
|
||||||
|
result.lines, result.rule_per_line(), block="rules",
|
||||||
|
)
|
||||||
# Every rule LINE the direct arm showed, repeats and the reserved
|
# Every rule LINE the direct arm showed, repeats and the reserved
|
||||||
# slot included — for the soft-link recorder. Distinct
|
# slot included — for the soft-link recorder. Distinct
|
||||||
# from `rule_ids`, which is telemetry's fresh-only cut.
|
# from `rule_ids`, which is telemetry's fresh-only cut.
|
||||||
@@ -984,6 +1028,7 @@ def _rule_io() -> rp.RuleIO:
|
|||||||
history=rule_deliveries.history if bound else None,
|
history=rule_deliveries.history if bound else None,
|
||||||
record_delivery=rule_deliveries.record if bound else None,
|
record_delivery=rule_deliveries.record if bound else None,
|
||||||
retired=rule_deliveries.retired if bound else None,
|
retired=rule_deliveries.retired if bound else None,
|
||||||
|
gate=_gate_for,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -1581,6 +1626,7 @@ async def build_write_path_hint(
|
|||||||
# The direct band, then a rule reached through a linked lesson,
|
# The direct band, then a rule reached through a linked lesson,
|
||||||
# composed by `_rule_moment` exactly as the other two rule builders are.
|
# composed by `_rule_moment` exactly as the other two rule builders are.
|
||||||
rule_lines: list[str] = []
|
rule_lines: list[str] = []
|
||||||
|
rule_line_ids: list[int] = []
|
||||||
rule_ids: list[int] = []
|
rule_ids: list[int] = []
|
||||||
shown_rule_ids: list[int] = []
|
shown_rule_ids: list[int] = []
|
||||||
checkpoint: dict = {}
|
checkpoint: dict = {}
|
||||||
@@ -1597,6 +1643,7 @@ async def build_write_path_hint(
|
|||||||
checkpoint_floor=cfg["checkpoint_threshold"],
|
checkpoint_floor=cfg["checkpoint_threshold"],
|
||||||
)
|
)
|
||||||
rule_lines = result.lines
|
rule_lines = result.lines
|
||||||
|
rule_line_ids = result.rule_per_line()
|
||||||
rule_ids.extend(result.rule_ids)
|
rule_ids.extend(result.rule_ids)
|
||||||
# Every rule line the band showed, repeats included — what the
|
# Every rule line the band showed, repeats included — what the
|
||||||
# soft-link recorder pairs with this response's lessons.
|
# soft-link recorder pairs with this response's lessons.
|
||||||
@@ -1605,6 +1652,25 @@ async def build_write_path_hint(
|
|||||||
except Exception:
|
except Exception:
|
||||||
logger.debug("write-path rule arm failed", exc_info=True)
|
logger.debug("write-path rule arm failed", exc_info=True)
|
||||||
|
|
||||||
|
# The payload as parts, for the door that fits it to a budget: the rules,
|
||||||
|
# then the rulings and design system that bind, then the prior art.
|
||||||
|
binding: list[hook_payload.Part] = []
|
||||||
|
if rulings["lines"]:
|
||||||
|
binding.append(hook_payload.Part(
|
||||||
|
text="\n".join(rulings["lines"]),
|
||||||
|
ids={hook_payload.RULING: tuple(rulings["system_ids"])},
|
||||||
|
))
|
||||||
|
if design_text:
|
||||||
|
binding.append(hook_payload.Part(
|
||||||
|
text=design_text,
|
||||||
|
ids={hook_payload.DERIVE: (design_dedup,)} if design_dedup else {},
|
||||||
|
))
|
||||||
|
parts = [
|
||||||
|
*hook_payload.rule_parts(rule_lines, rule_line_ids, block="rules"),
|
||||||
|
*binding,
|
||||||
|
*(hook_payload.Part(text=line) for line in staleness),
|
||||||
|
]
|
||||||
|
|
||||||
if (not staleness and not synced and not menu and not suggested
|
if (not staleness and not synced and not menu and not suggested
|
||||||
and not divergence and not derive and not rule_lines):
|
and not divergence and not derive and not rule_lines):
|
||||||
if design_text or rulings["lines"]:
|
if design_text or rulings["lines"]:
|
||||||
@@ -1613,6 +1679,7 @@ async def build_write_path_hint(
|
|||||||
"context": "\n".join(rulings["lines"] + ([design_text] if design_text else [])),
|
"context": "\n".join(rulings["lines"] + ([design_text] if design_text else [])),
|
||||||
"derive_keys": [design_dedup] if design_dedup else [],
|
"derive_keys": [design_dedup] if design_dedup else [],
|
||||||
"ruling_system_ids": rulings["system_ids"],
|
"ruling_system_ids": rulings["system_ids"],
|
||||||
|
"parts": parts,
|
||||||
}
|
}
|
||||||
return empty
|
return empty
|
||||||
|
|
||||||
@@ -1639,12 +1706,13 @@ async def build_write_path_hint(
|
|||||||
if design_text:
|
if design_text:
|
||||||
lines.append(design_text)
|
lines.append(design_text)
|
||||||
sync_note_ids: list[int] = []
|
sync_note_ids: list[int] = []
|
||||||
|
sync_header = ""
|
||||||
if synced:
|
if synced:
|
||||||
# The sync framing. Deliberately imperative about the record —
|
# The sync framing. Deliberately imperative about the record —
|
||||||
# the reuse claim ("start from this shape") is still implied by the
|
# the reuse claim ("start from this shape") is still implied by the
|
||||||
# title being right there, but the load-bearing sentence is the one no
|
# title being right there, but the load-bearing sentence is the one no
|
||||||
# other surface says: keeping the record true is part of THIS edit.
|
# other surface says: keeping the record true is part of THIS edit.
|
||||||
lines.append(
|
sync_header = (
|
||||||
f"> Recorded in Grimoire AT `{path}` — the snippet(s) below record "
|
f"> Recorded in Grimoire AT `{path}` — the snippet(s) below record "
|
||||||
"the file this edit is changing. Reuse/extend the recorded shape "
|
"the file this edit is changing. Reuse/extend the recorded shape "
|
||||||
"rather than writing a parallel one; and if this edit changes what "
|
"rather than writing a parallel one; and if this edit changes what "
|
||||||
@@ -1653,10 +1721,18 @@ async def build_write_path_hint(
|
|||||||
"`verify_snippet(id, status=\"ok\", commit_sha=…)` after confirming "
|
"`verify_snippet(id, status=\"ok\", commit_sha=…)` after confirming "
|
||||||
"it still holds. Open with `get_snippet(id)` (shown once per session):"
|
"it still holds. Open with `get_snippet(id)` (shown once per session):"
|
||||||
)
|
)
|
||||||
|
lines.append(sync_header)
|
||||||
for item in synced:
|
for item in synced:
|
||||||
sync_note_ids.append(int(item["id"]))
|
sid = int(item["id"])
|
||||||
lines.append(_prior_art_line(item, "records this file", _owner_of(item)))
|
sync_note_ids.append(sid)
|
||||||
|
line = _prior_art_line(item, "records this file", _owner_of(item))
|
||||||
|
lines.append(line)
|
||||||
|
parts.append(hook_payload.Part(
|
||||||
|
text=line, block="synced", header=sync_header,
|
||||||
|
ids={hook_payload.SYNC: (sid,), hook_payload.NOTE: (sid,)},
|
||||||
|
))
|
||||||
|
|
||||||
|
menu_at = len(lines)
|
||||||
if menu:
|
if menu:
|
||||||
lines.append(
|
lines.append(
|
||||||
f"> Prior art already recorded in Grimoire for `{path}` — open one with "
|
f"> Prior art already recorded in Grimoire for `{path}` — open one with "
|
||||||
@@ -1691,10 +1767,17 @@ async def build_write_path_hint(
|
|||||||
"shape of a solution to adapt, not code to copy."
|
"shape of a solution to adapt, not code to copy."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
menu_header = "\n".join(lines[menu_at:])
|
||||||
note_ids: list[int] = list(sync_note_ids)
|
note_ids: list[int] = list(sync_note_ids)
|
||||||
for item, marker, owner, foreign_lang in rendered:
|
for item, marker, owner, foreign_lang in rendered:
|
||||||
note_ids.append(int(item["id"]))
|
nid = int(item["id"])
|
||||||
lines.append(_prior_art_line(item, marker, owner, foreign_lang))
|
note_ids.append(nid)
|
||||||
|
entry = [_prior_art_line(item, marker, owner, foreign_lang)]
|
||||||
|
lines.append(entry[0])
|
||||||
|
parts.append(hook_payload.Part(
|
||||||
|
text=entry[0], block="menu", header=menu_header,
|
||||||
|
ids={hook_payload.NOTE: (nid,)},
|
||||||
|
))
|
||||||
# Only the semantically-matched lines carry a passage. The records-this-
|
# Only the semantically-matched lines carry a passage. The records-this-
|
||||||
# file lines came from a LOCATION lookup — nothing was matched, so there
|
# file lines came from a LOCATION lookup — nothing was matched, so there
|
||||||
# is no matching passage and the body's opening would be a fabricated
|
# is no matching passage and the body's opening would be a fabricated
|
||||||
@@ -1711,15 +1794,23 @@ async def build_write_path_hint(
|
|||||||
)
|
)
|
||||||
if passage:
|
if passage:
|
||||||
lines.append(f"> ↳ {passage}")
|
lines.append(f"> ↳ {passage}")
|
||||||
|
entry.append(f"> ↳ {passage}")
|
||||||
|
parts[-1] = replace(parts[-1], text="\n".join(entry))
|
||||||
|
|
||||||
if suggested:
|
if suggested:
|
||||||
lines.append(_suggest_line(path, suggested))
|
lines.append(_suggest_line(path, suggested))
|
||||||
|
parts.append(hook_payload.Part(text=lines[-1]))
|
||||||
if divergence:
|
if divergence:
|
||||||
lines.append(_divergence_line(path, divergence))
|
lines.append(_divergence_line(path, divergence))
|
||||||
|
parts.append(hook_payload.Part(text=lines[-1]))
|
||||||
if derive:
|
if derive:
|
||||||
lines.append(_derive_line(path, derive))
|
lines.append(_derive_line(path, derive))
|
||||||
|
parts.append(hook_payload.Part(
|
||||||
|
text=lines[-1], ids={hook_payload.DERIVE: tuple(d["key"] for d in derive)},
|
||||||
|
))
|
||||||
if copies:
|
if copies:
|
||||||
lines.append(_copy_line(copies))
|
lines.append(_copy_line(copies))
|
||||||
|
parts.append(hook_payload.Part(text=lines[-1]))
|
||||||
|
|
||||||
# Split by arm, which is the whole reason this table exists. The place arm
|
# Split by arm, which is the whole reason this table exists. The place arm
|
||||||
# carries no score and so has no home in retrieval_logs, yet it fires on
|
# carries no score and so has no home in retrieval_logs, yet it fires on
|
||||||
@@ -1758,9 +1849,11 @@ async def build_write_path_hint(
|
|||||||
)
|
)
|
||||||
if proposal:
|
if proposal:
|
||||||
lines.append(proposal)
|
lines.append(proposal)
|
||||||
|
parts.append(hook_payload.Part(text=proposal))
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"context": "\n".join(lines),
|
"context": "\n".join(lines),
|
||||||
|
"parts": parts,
|
||||||
"note_ids": note_ids,
|
"note_ids": note_ids,
|
||||||
"sync_note_ids": sync_note_ids,
|
"sync_note_ids": sync_note_ids,
|
||||||
"config": cfg,
|
"config": cfg,
|
||||||
@@ -1855,6 +1948,9 @@ async def build_tool_rule_hint(
|
|||||||
out["context"] = "\n".join(result.lines)
|
out["context"] = "\n".join(result.lines)
|
||||||
out["rule_ids"] = result.rule_ids
|
out["rule_ids"] = result.rule_ids
|
||||||
out["checkpoint"] = result.checkpoint
|
out["checkpoint"] = result.checkpoint
|
||||||
|
out["parts"] = hook_payload.rule_parts(
|
||||||
|
result.lines, result.rule_per_line(), block="rules",
|
||||||
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.debug("pre-tool rule arm failed", exc_info=True)
|
logger.debug("pre-tool rule arm failed", exc_info=True)
|
||||||
|
|
||||||
@@ -1875,6 +1971,10 @@ async def build_tool_rule_hint(
|
|||||||
rulings["lines"] + ([out["context"]] if out.get("context") else [])
|
rulings["lines"] + ([out["context"]] if out.get("context") else [])
|
||||||
)
|
)
|
||||||
out["ruling_system_ids"] = rulings["system_ids"]
|
out["ruling_system_ids"] = rulings["system_ids"]
|
||||||
|
out["parts"] = [hook_payload.Part(
|
||||||
|
text="\n".join(rulings["lines"]),
|
||||||
|
ids={hook_payload.RULING: tuple(rulings["system_ids"])},
|
||||||
|
), *out.get("parts", [])]
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.debug("pre-tool rulings arm failed", exc_info=True)
|
logger.debug("pre-tool rulings arm failed", exc_info=True)
|
||||||
return out
|
return out
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ import time
|
|||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Any, Callable
|
from typing import Any, Callable
|
||||||
|
|
||||||
from grimoire.services import rule_order
|
from grimoire.services import cue_gate, rule_order
|
||||||
from grimoire.services.lessons import LESSON_NOTE_TYPE, claim_line
|
from grimoire.services.lessons import LESSON_NOTE_TYPE, claim_line
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -185,139 +185,67 @@ def checkpoint_reason(checkpoint: dict) -> str:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# How much of a rule's statement a first mention carries. A statement past it
|
||||||
|
# is cut at a sentence boundary and the line says where the rest is.
|
||||||
|
STATEMENT_CHARS = 600
|
||||||
|
# The register clause, the one place a line says how much force it carries.
|
||||||
|
RULE_FORCE = "it binds"
|
||||||
|
PREFERENCE_FORCE = "how this has been done before"
|
||||||
|
|
||||||
|
|
||||||
|
def _statement_excerpt(rule) -> str:
|
||||||
|
"""The rule's own words, up to STATEMENT_CHARS, cut where a sentence ends."""
|
||||||
|
text = getattr(rule, "statement", "")
|
||||||
|
text = " ".join(text.split()) if isinstance(text, str) else ""
|
||||||
|
if len(text) <= STATEMENT_CHARS:
|
||||||
|
return text
|
||||||
|
cut = text[:STATEMENT_CHARS]
|
||||||
|
stop = max(cut.rfind(". "), cut.rfind("; "), cut.rfind(": "))
|
||||||
|
return (cut[: stop + 1] if stop > STATEMENT_CHARS // 2 else cut.rstrip()) + " …"
|
||||||
|
|
||||||
|
|
||||||
def _rule_hint_line(
|
def _rule_hint_line(
|
||||||
rule, *, where: str, seen: bool, held: bool = False, compact: bool = False,
|
rule, *, where: str, seen: bool, held: bool = False, compact: bool = False,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""One rule hint line — both arms, both tails, both kinds.
|
"""One rule line, for every arm and both kinds.
|
||||||
|
|
||||||
THREE INDEPENDENT AXES. `compact` joins `kind` and `seen`, and like them
|
A first mention carries the rule itself — its title, why it is here, and
|
||||||
it reads none of the others: it says how much ROOM this line
|
its statement — so the reader has what the rule says without a second
|
||||||
gets, which is a fact about its rank among today's hits rather than about
|
call. A repeat, or a lower-ranked line (`compact`), is a reference: the
|
||||||
the rule. A compact line is still a full claim that the rule may apply —
|
rule's number and title. Every line ends by saying where this session
|
||||||
it simply cites the rule instead of quoting its trigger. Crucially it
|
stands with the rule and where its full text is.
|
||||||
still carries the `seen` tail, so the three axes stay genuinely
|
|
||||||
independent: shortening a line must not decide what it says about whether
|
|
||||||
the session is holding the rule.
|
|
||||||
|
|
||||||
WHY THE LATER LINES ARE QUIETER. A full line runs ~143 tokens once the
|
Written as statements about the rule, never as instructions to the
|
||||||
trigger is rendered, so five full lines cost ~568 tokens before every Bash
|
reader: a line beside the work reports what applies, and the reader
|
||||||
call. Top-full-plus-references costs ~299 — about 2x a single full line,
|
decides what to do with it.
|
||||||
for four more rules. The token budget forbids four voices at full volume,
|
|
||||||
not four voices.
|
|
||||||
|
|
||||||
The top hit keeps the full rendering because it is the one the ranker is
|
Three independent axes:
|
||||||
most confident about, and a reader who acts on exactly one line should
|
- `kind` moves the noun and the register clause: a rule binds, a
|
||||||
have acted on that one.
|
preference says how this has been done before.
|
||||||
|
- the ledger moves the closing clause: first mention, named earlier and
|
||||||
TWO INDEPENDENT AXES. `kind` decides the head, `seen` decides the tail,
|
not opened (`seen`), or opened earlier (`held`). The server cannot know
|
||||||
and neither reads the other. A preference and a rule differ in force; a
|
what the reader still holds, only what it named and what was opened.
|
||||||
repeat and a first surfacing differ in whether the session already holds
|
- `compact`, or any repeat, drops the statement and keeps the rest.
|
||||||
the line. Those are unrelated facts, and keeping them unrelated in the
|
|
||||||
code is what lets a new kind join without reopening the repeat question.
|
|
||||||
|
|
||||||
ONE FUNCTION BECAUSE THE TAILS MUST NOT DRIFT. The two arms phrase their
|
|
||||||
heads differently ("may apply here" vs "may apply to this Bash call") and
|
|
||||||
that difference is deliberate. Everything after it must not differ: an
|
|
||||||
arm modelled on its sibling rather than sharing with it inherits its
|
|
||||||
defects, and two copies of a two-branch string is how one branch gets
|
|
||||||
fixed and the other does not.
|
|
||||||
|
|
||||||
WHY A REPEAT GETS A LINE AT ALL. Dropping a hit whose id is already on the
|
|
||||||
session's exclusion ledger is correct only while the session still HOLDS
|
|
||||||
what it was told, and a compaction breaks exactly that: the earlier
|
|
||||||
injection is summarized away while the id stays on the ledger, so the rule
|
|
||||||
would be absent from context AND unreachable for the rest of the session.
|
|
||||||
The same holds, more slowly, for a session that simply stops holding a
|
|
||||||
line it read an hour ago.
|
|
||||||
|
|
||||||
Only ONE CLAUSE of a first-surfacing line is false on a repeat — the claim that
|
|
||||||
the rule is not in the session's loaded set. So only that clause changes.
|
|
||||||
Title, trigger and pull pointer are identical either way, the statement is
|
|
||||||
never injected either way, and a repeat therefore costs the same ~40 tokens
|
|
||||||
as a first surfacing and no more.
|
|
||||||
|
|
||||||
DELIBERATELY NOT ASKING THE SESSION WHETHER IT HOLDS THE RULE. A model
|
|
||||||
asked "do you still hold rule N?" will say yes, and the claim is
|
|
||||||
unverifiable self-report about its own context. The answer is also not
|
|
||||||
needed: the line is cheap enough to always emit and carries its own remedy
|
|
||||||
in both branches. Removing the question removes the fragility rather than
|
|
||||||
managing it.
|
|
||||||
"""
|
"""
|
||||||
trigger = (rule.when_to_apply or "").strip()
|
|
||||||
preference = rule.kind == "preference"
|
preference = rule.kind == "preference"
|
||||||
# KIND CHANGES THE HEAD; `seen` CHANGES THE TAIL. The two axes are
|
noun = "Preference" if preference else "Rule"
|
||||||
# independent and stay that way, which is what lets the repeat logic above
|
force = PREFERENCE_FORCE if preference else RULE_FORCE
|
||||||
# survive a second kind without being reasoned about again: whether a
|
|
||||||
# record is already on the ledger has nothing to do with how much force it
|
|
||||||
# carries, so the seen-branch is shared verbatim.
|
|
||||||
#
|
|
||||||
# The noun is the whole of the visual difference, and that is deliberate.
|
|
||||||
# A reader skimming an injected block gets one word to place the register \u2014
|
|
||||||
# so it is the SECOND word that moves, and it is the word naming force.
|
|
||||||
# Everything structural after it is identical, so the three kinds read as
|
|
||||||
# one set rather than three formats (the lesson voice is written against
|
|
||||||
# these two; they are one paragraph, not three).
|
|
||||||
noun = "Preference" if preference else "Standing rule"
|
|
||||||
# The only other place force is asserted. A rule's line tells the reader
|
|
||||||
# not to dismiss it unread, because dismissing a rule unread is how the
|
|
||||||
# thing it prevents happens. A preference makes no such claim: it says
|
|
||||||
# where to find how this has been done, and following it is what keeps
|
|
||||||
# things consistent rather than what keeps them correct.
|
|
||||||
reason = (
|
|
||||||
"for how this has been done before" if preference
|
|
||||||
else "before deciding it does not apply"
|
|
||||||
)
|
|
||||||
# THREE STATES, BECAUSE TWO OF THEM MUST NOT BE TOLD THE SAME THING.
|
|
||||||
#
|
|
||||||
# `seen` means an arm NAMED this rule earlier. It does not mean the session
|
|
||||||
# read it — the line is a teaser, and a teaser skimmed past leaves nothing
|
|
||||||
# behind, least of all after a compaction summarises the turn it arrived
|
|
||||||
# in. "You saw it earlier this session" would assert something about the
|
|
||||||
# reader's context that the server has no way to know.
|
|
||||||
#
|
|
||||||
# `held` is the observable half: a PostToolUse hook watches for the
|
|
||||||
# `get_rule` call itself, so this is a recorded EVENT rather than a claim.
|
|
||||||
# That distinction is what keeps the non-goal above intact — the objection
|
|
||||||
# was to asking a model about its own context, not to noticing what it did.
|
|
||||||
#
|
|
||||||
# The middle state is the honest one: named, not opened. It gets the full
|
|
||||||
# invitation, because a session that skipped
|
|
||||||
# the teaser is in almost the same position as one that never saw it.
|
|
||||||
if held:
|
if held:
|
||||||
tail = (
|
state = "Opened earlier this session"
|
||||||
f"You opened it earlier this session; pull it with "
|
|
||||||
f"get_rule({rule.id}) again if you no longer hold it."
|
|
||||||
)
|
|
||||||
elif seen:
|
elif seen:
|
||||||
tail = (
|
state = "Named earlier this session, not opened"
|
||||||
f"Mentioned earlier this session but not opened — read it with "
|
|
||||||
f"get_rule({rule.id}) {reason}."
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
tail = (
|
state = "First mention this session"
|
||||||
f"Read it with get_rule({rule.id}) {reason}; it is not in this "
|
tail = f"{state}; full text: get_rule({rule.id})."
|
||||||
"session's loaded set."
|
if compact or seen or held:
|
||||||
)
|
return f"Also relevant: {noun} {rule.id} \u201c{rule.title}\u201d ({force}). {tail}"
|
||||||
if compact:
|
statement = _statement_excerpt(rule)
|
||||||
# THE TRIGGER GOES; THE TAIL STAYS. Only one of the two is expensive \u2014
|
if statement and statement[-1] not in ".!?…":
|
||||||
# a trigger runs 300-400 characters, the tail about 100 \u2014
|
statement += "."
|
||||||
# so dropping the trigger is nearly the whole saving and dropping the
|
|
||||||
# tail would be mostly sacrifice.
|
|
||||||
#
|
|
||||||
# It would also destroy the one thing a repeat line exists to say. The
|
|
||||||
# tail is what tells a reader whether they were already told this and
|
|
||||||
# may no longer be holding it, and that is the entire difference they
|
|
||||||
# can act on; a reference with no tail reads as a first surfacing
|
|
||||||
# whether it is one or not.
|
|
||||||
# test_a_rule_the_session_already_holds_is_referenced_not_re_offered
|
|
||||||
# pins this.
|
|
||||||
return (
|
|
||||||
f"Also \u2014 {noun.lower()} \u201c{rule.title}\u201d. {tail}"
|
|
||||||
)
|
|
||||||
return (
|
return (
|
||||||
f"{noun} that may apply {where} \u2014 \u201c{rule.title}\u201d"
|
f"{noun} {rule.id} \u201c{rule.title}\u201d may apply {where}; "
|
||||||
+ (f" ({trigger})" if trigger else "")
|
+ (f"{force}: {statement}" if statement else f"{force}.")
|
||||||
+ f". {tail}"
|
+ f" {tail}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -446,6 +374,12 @@ class RuleArm:
|
|||||||
kind: str | None = None
|
kind: str | None = None
|
||||||
"""Ask the ranker for one record kind only ("preference"), or every kind."""
|
"""Ask the ranker for one record kind only ("preference"), or every kind."""
|
||||||
|
|
||||||
|
gates_preferences: bool = False
|
||||||
|
"""A preference this arm found by resemblance alone speaks only past the
|
||||||
|
cue-swap gate (`cue_gate`). A rule binds, so a missed rule costs a mistake
|
||||||
|
and is never gated here; a preference guides, and an unrelated one beside
|
||||||
|
the work costs the reader's attention on every call."""
|
||||||
|
|
||||||
stop_only: bool = False
|
stop_only: bool = False
|
||||||
"""The door shows nothing but the stop (the reply moment).
|
"""The door shows nothing but the stop (the reply moment).
|
||||||
|
|
||||||
@@ -481,7 +415,7 @@ RULE_FLOOR_DEFAULT = 0.70
|
|||||||
# preference.
|
# preference.
|
||||||
PROMPT_RULE = RuleArm(
|
PROMPT_RULE = RuleArm(
|
||||||
"prompt_rule", band=False, compact_tail=False, checkpoint=False,
|
"prompt_rule", band=False, compact_tail=False, checkpoint=False,
|
||||||
preference_slot=True,
|
preference_slot=True, gates_preferences=True,
|
||||||
tuning=Surface(
|
tuning=Surface(
|
||||||
name="prompt_rule",
|
name="prompt_rule",
|
||||||
floor_key=RULE_FLOOR_KEY,
|
floor_key=RULE_FLOOR_KEY,
|
||||||
@@ -496,7 +430,7 @@ PROMPT_RULE = RuleArm(
|
|||||||
)
|
)
|
||||||
PRE_TOOL_RULE = RuleArm(
|
PRE_TOOL_RULE = RuleArm(
|
||||||
"pre_tool_rule", band=True, compact_tail=True, checkpoint=True,
|
"pre_tool_rule", band=True, compact_tail=True, checkpoint=True,
|
||||||
preference_slot=True,
|
preference_slot=True, gates_preferences=True,
|
||||||
tuning=Surface(
|
tuning=Surface(
|
||||||
name="pre_tool_rule",
|
name="pre_tool_rule",
|
||||||
floor_key=RULE_FLOOR_KEY,
|
floor_key=RULE_FLOOR_KEY,
|
||||||
@@ -511,7 +445,7 @@ PRE_TOOL_RULE = RuleArm(
|
|||||||
)
|
)
|
||||||
WRITE_PATH_RULE = RuleArm(
|
WRITE_PATH_RULE = RuleArm(
|
||||||
"write_path_rule", band=True, compact_tail=True, checkpoint=True,
|
"write_path_rule", band=True, compact_tail=True, checkpoint=True,
|
||||||
preference_slot=True,
|
preference_slot=True, gates_preferences=True,
|
||||||
tuning=Surface(
|
tuning=Surface(
|
||||||
name="write_path_rule",
|
name="write_path_rule",
|
||||||
floor_key=RULE_FLOOR_KEY,
|
floor_key=RULE_FLOOR_KEY,
|
||||||
@@ -586,6 +520,9 @@ class RuleIO:
|
|||||||
retired: Callable[..., Any] | None = None
|
retired: Callable[..., Any] | None = None
|
||||||
"""`rule_deliveries.retired`: the repeats this session has already had
|
"""`rule_deliveries.retired`: the repeats this session has already had
|
||||||
its one reminder of. None retires nothing."""
|
its one reminder of. None retires nothing."""
|
||||||
|
gate: Callable[..., Any] | None = None
|
||||||
|
"""`cue_gate.gate_for`: the bar a line found by resemblance must reach.
|
||||||
|
None, or a call returning None, leaves the arm ungated."""
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -626,6 +563,13 @@ class RuleResult:
|
|||||||
|
|
||||||
checkpoint: dict = field(default_factory=dict)
|
checkpoint: dict = field(default_factory=dict)
|
||||||
|
|
||||||
|
line_rule_ids: list[int] = field(default_factory=list)
|
||||||
|
"""The rule behind each of `lines`, in order, when a caller added lines
|
||||||
|
of its own after the arm's; empty means `shown_rule_ids` lines up."""
|
||||||
|
|
||||||
|
def rule_per_line(self) -> list[int]:
|
||||||
|
return list(self.line_rule_ids or self.shown_rule_ids)
|
||||||
|
|
||||||
|
|
||||||
# ── The stages ───────────────────────────────────────────────────────────
|
# ── The stages ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -643,9 +587,35 @@ def _telemetry_failed(source: str) -> None:
|
|||||||
logger.debug("retrieval telemetry failed for %s", source, exc_info=True)
|
logger.debug("retrieval telemetry failed for %s", source, exc_info=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _gate_preferences(kept: list, gate) -> list:
|
||||||
|
"""`kept` without the preferences the gate turned away; rules untouched."""
|
||||||
|
if gate is None:
|
||||||
|
return kept
|
||||||
|
return [(score, rule) for score, rule in kept
|
||||||
|
if getattr(rule, "kind", None) != "preference" or gate.passes(score)]
|
||||||
|
|
||||||
|
|
||||||
|
def _gate_fields(gate, kept: int) -> dict:
|
||||||
|
"""The call row's record of the gate: its bar and how many lines passed."""
|
||||||
|
if gate is None:
|
||||||
|
return {}
|
||||||
|
return {"gate_bar": gate.bar, "gate_kept": kept}
|
||||||
|
|
||||||
|
|
||||||
|
async def _gate(io, user_id: int, source: str, project_id) -> Any:
|
||||||
|
"""This arm's gate, or None when the door has none or it cannot be read."""
|
||||||
|
if io.gate is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return await io.gate(user_id, source, project_id or None)
|
||||||
|
except Exception: # noqa: BLE001 - an unreadable gate leaves the arm as it was
|
||||||
|
logger.debug("cue gate unreadable for %s", source, exc_info=True)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
async def _ranked(
|
async def _ranked(
|
||||||
io: RuleIO, moment: RuleMoment, *, source: str, floor: float, limit: int,
|
io: RuleIO, moment: RuleMoment, *, source: str, floor: float, limit: int,
|
||||||
band: bool = False, kind: str | None = None,
|
band: bool = False, kind: str | None = None, gate=None,
|
||||||
) -> tuple[list, list, list]:
|
) -> tuple[list, list, list]:
|
||||||
"""Search, band, split fresh from repeats, and log the call — every call.
|
"""Search, band, split fresh from repeats, and log the call — every call.
|
||||||
|
|
||||||
@@ -675,6 +645,11 @@ async def _ranked(
|
|||||||
hits = [(score, rule) for score, rule in hits
|
hits = [(score, rule) for score, rule in hits
|
||||||
if getattr(rule, "kind", None) == kind]
|
if getattr(rule, "kind", None) == kind]
|
||||||
kept = _rule_band(hits) if band else hits
|
kept = _rule_band(hits) if band else hits
|
||||||
|
# The gate is part of the cut, like the band: what it turns away is not
|
||||||
|
# shown, so it is not in the row's results either.
|
||||||
|
gated = _gate_preferences(kept, gate)
|
||||||
|
passed = sum(1 for _s, r in gated if getattr(r, "kind", None) == "preference")
|
||||||
|
kept = gated
|
||||||
fresh = [(score, rule) for score, rule in kept if rule.id not in moment.exclude]
|
fresh = [(score, rule) for score, rule in kept if rule.id not in moment.exclude]
|
||||||
try:
|
try:
|
||||||
io.record_retrieval(
|
io.record_retrieval(
|
||||||
@@ -686,6 +661,7 @@ async def _ranked(
|
|||||||
best_available_id=report.get("best_available_id"),
|
best_available_id=report.get("best_available_id"),
|
||||||
searched=bool(report.get("searched", True)),
|
searched=bool(report.get("searched", True)),
|
||||||
suppressed=len(hits) - len(fresh),
|
suppressed=len(hits) - len(fresh),
|
||||||
|
**_gate_fields(gate, passed),
|
||||||
)
|
)
|
||||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||||
_telemetry_failed(source)
|
_telemetry_failed(source)
|
||||||
@@ -693,7 +669,7 @@ async def _ranked(
|
|||||||
|
|
||||||
|
|
||||||
async def _reserve_slot_for_preference(
|
async def _reserve_slot_for_preference(
|
||||||
io: RuleIO, moment: RuleMoment, hits: list, *, floor: float,
|
io: RuleIO, moment: RuleMoment, hits: list, *, floor: float, gate=None,
|
||||||
) -> tuple[list, int | None]:
|
) -> tuple[list, int | None]:
|
||||||
"""Guarantee a preference one slot, if one clears the bar.
|
"""Guarantee a preference one slot, if one clears the bar.
|
||||||
|
|
||||||
@@ -744,12 +720,12 @@ async def _reserve_slot_for_preference(
|
|||||||
# ITS OWN SOURCE, and both sides of the trade logged. A slot whose query
|
# ITS OWN SOURCE, and both sides of the trade logged. A slot whose query
|
||||||
# is not logged beside the hit it pushed out can never be judged against
|
# is not logged beside the hit it pushed out can never be judged against
|
||||||
# what it displaced.
|
# what it displaced.
|
||||||
found, _kept, _fresh = await _ranked(
|
_found, kept, _fresh = await _ranked(
|
||||||
io, moment, source=PREFERENCE_SLOT_SOURCE, floor=floor, limit=1,
|
io, moment, source=PREFERENCE_SLOT_SOURCE, floor=floor, limit=1,
|
||||||
kind="preference",
|
kind="preference", gate=gate,
|
||||||
)
|
)
|
||||||
seen = {rule.id for _s, rule in hits}
|
seen = {rule.id for _s, rule in hits}
|
||||||
slot = [(s, r) for s, r in found
|
slot = [(s, r) for s, r in kept
|
||||||
if r.kind == "preference" and r.id not in seen][:1]
|
if r.kind == "preference" and r.id not in seen][:1]
|
||||||
if not slot:
|
if not slot:
|
||||||
return hits, None
|
return hits, None
|
||||||
@@ -842,9 +818,13 @@ async def run_rule_arm(
|
|||||||
surfacing rows → checkpoint. Fails open to an empty result.
|
surfacing rows → checkpoint. Fails open to an empty result.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
|
gate = (
|
||||||
|
await _gate(io, moment.user_id, arm.source, moment.project_id)
|
||||||
|
if arm.gates_preferences else None
|
||||||
|
)
|
||||||
_hits, kept, fresh = await _ranked(
|
_hits, kept, fresh = await _ranked(
|
||||||
io, moment, source=arm.source, floor=floor, limit=budget,
|
io, moment, source=arm.source, floor=floor, limit=budget,
|
||||||
band=arm.band, kind=arm.kind,
|
band=arm.band, kind=arm.kind, gate=gate,
|
||||||
)
|
)
|
||||||
shown = kept
|
shown = kept
|
||||||
if arm.preference_slot:
|
if arm.preference_slot:
|
||||||
@@ -854,7 +834,7 @@ async def run_rule_arm(
|
|||||||
# preference ranked below that window is invisible to it while a
|
# preference ranked below that window is invisible to it while a
|
||||||
# kind-filtered query finds it at once.
|
# kind-filtered query finds it at once.
|
||||||
shown, _slot_id = await _reserve_slot_for_preference(
|
shown, _slot_id = await _reserve_slot_for_preference(
|
||||||
io, moment, shown, floor=floor,
|
io, moment, shown, floor=floor, gate=gate,
|
||||||
)
|
)
|
||||||
# A repeat already reminded once this session says nothing more.
|
# A repeat already reminded once this session says nothing more.
|
||||||
gone = await _retired(io, moment, [rule for _s, rule in shown])
|
gone = await _retired(io, moment, [rule for _s, rule in shown])
|
||||||
@@ -1143,6 +1123,10 @@ class NoteArm:
|
|||||||
a record shared one-to-one with the operator."""
|
a record shared one-to-one with the operator."""
|
||||||
|
|
||||||
slots: tuple[NoteSlot, ...] = ()
|
slots: tuple[NoteSlot, ...] = ()
|
||||||
|
gated: bool = False
|
||||||
|
"""Its lines speak only past the cue-swap gate (`cue_gate`), and at most
|
||||||
|
`cue_gate.LINES` of them, slots included."""
|
||||||
|
|
||||||
withholds: bool = False
|
withholds: bool = False
|
||||||
"""A menu sits above this arm in the same response, and what it lists is
|
"""A menu sits above this arm in the same response, and what it lists is
|
||||||
kept out of the search (`exclude_ids`) — same-call duplication, which is a
|
kept out of the search (`exclude_ids`) — same-call duplication, which is a
|
||||||
@@ -1154,6 +1138,7 @@ class NoteArm:
|
|||||||
|
|
||||||
AUTO_INJECT = NoteArm(
|
AUTO_INJECT = NoteArm(
|
||||||
"auto_inject", surfaced_as="auto_inject", slots=(REUSE_SLOT, LESSON_SLOT),
|
"auto_inject", surfaced_as="auto_inject", slots=(REUSE_SLOT, LESSON_SLOT),
|
||||||
|
gated=True,
|
||||||
tuning=Surface(
|
tuning=Surface(
|
||||||
name="auto_inject",
|
name="auto_inject",
|
||||||
floor_key="kb_autoinject_threshold",
|
floor_key="kb_autoinject_threshold",
|
||||||
@@ -1176,7 +1161,7 @@ AUTO_INJECT = NoteArm(
|
|||||||
WRITE_PATH = NoteArm(
|
WRITE_PATH = NoteArm(
|
||||||
"write_path", surfaced_as="write_path_semantic",
|
"write_path", surfaced_as="write_path_semantic",
|
||||||
note_type=("snippet", "note", LESSON_NOTE_TYPE), task_kind="issue",
|
note_type=("snippet", "note", LESSON_NOTE_TYPE), task_kind="issue",
|
||||||
withholds=True,
|
withholds=True, gated=True,
|
||||||
tuning=Surface(
|
tuning=Surface(
|
||||||
name="write_path",
|
name="write_path",
|
||||||
floor_key="kb_writepath_threshold",
|
floor_key="kb_writepath_threshold",
|
||||||
@@ -1229,6 +1214,8 @@ class NoteIO:
|
|||||||
|
|
||||||
record_retrieval: Callable[..., Any]
|
record_retrieval: Callable[..., Any]
|
||||||
record_surfaced: Callable[..., Any]
|
record_surfaced: Callable[..., Any]
|
||||||
|
gate: Callable[..., Any] | None = None
|
||||||
|
"""`cue_gate.gate_for`, for a gated arm. None leaves the arm ungated."""
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -1274,6 +1261,9 @@ class NoteResult:
|
|||||||
slot_ids: dict = field(default_factory=dict)
|
slot_ids: dict = field(default_factory=dict)
|
||||||
"""{slot source: the id it spent}."""
|
"""{slot source: the id it spent}."""
|
||||||
|
|
||||||
|
gate: Any = None
|
||||||
|
"""The `cue_gate.Gate` this call's lines were held to, or None."""
|
||||||
|
|
||||||
|
|
||||||
def _note_band(hits: list) -> list:
|
def _note_band(hits: list) -> list:
|
||||||
"""The top hit, plus every hit within `_NOTE_BAND` of it.
|
"""The top hit, plus every hit within `_NOTE_BAND` of it.
|
||||||
@@ -1290,7 +1280,7 @@ def _note_band(hits: list) -> list:
|
|||||||
|
|
||||||
async def _reserve_note_slot(
|
async def _reserve_note_slot(
|
||||||
io: NoteIO, arm: NoteArm, slot: NoteSlot, moment: NoteMoment, menu: list,
|
io: NoteIO, arm: NoteArm, slot: NoteSlot, moment: NoteMoment, menu: list,
|
||||||
*, floor: float, budget: int, shown: set[int],
|
*, floor: float, budget: int, shown: set[int], capped: bool = False,
|
||||||
) -> tuple[list, int | None]:
|
) -> tuple[list, int | None]:
|
||||||
"""Guarantee `slot.kinds` one line, if one clears the arm's own bar.
|
"""Guarantee `slot.kinds` one line, if one clears the arm's own bar.
|
||||||
|
|
||||||
@@ -1319,6 +1309,10 @@ async def _reserve_note_slot(
|
|||||||
"""
|
"""
|
||||||
if any(_record_kind(n) in slot.kinds for _s, n in menu):
|
if any(_record_kind(n) in slot.kinds for _s, n in menu):
|
||||||
return menu, None
|
return menu, None
|
||||||
|
# Under the gate the budget is a ceiling for every line, so a slot that
|
||||||
|
# only extends has no room once the menu is full.
|
||||||
|
if capped and not slot.evicts and len(menu) >= budget:
|
||||||
|
return menu, None
|
||||||
|
|
||||||
t0 = time.perf_counter()
|
t0 = time.perf_counter()
|
||||||
report: dict = {}
|
report: dict = {}
|
||||||
@@ -1389,6 +1383,10 @@ async def run_note_arm(
|
|||||||
band → reserved slots → surfacing rows. Fails open to an empty result.
|
band → reserved slots → surfacing rows. Fails open to an empty result.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
|
gate = (
|
||||||
|
await _gate(io, moment.user_id, arm.source, moment.project_id)
|
||||||
|
if arm.gated else None
|
||||||
|
)
|
||||||
t0 = time.perf_counter()
|
t0 = time.perf_counter()
|
||||||
report: dict = {}
|
report: dict = {}
|
||||||
scored = moment.in_menu & moment.still_scored
|
scored = moment.in_menu & moment.still_scored
|
||||||
@@ -1420,6 +1418,12 @@ async def run_note_arm(
|
|||||||
(s, n) for s, n in hits
|
(s, n) for s, n in hits
|
||||||
if int(n.id) not in moment.seen and int(n.id) not in moment.named
|
if int(n.id) not in moment.seen and int(n.id) not in moment.named
|
||||||
]
|
]
|
||||||
|
# What the gate lets through, counted before the band and the slots so
|
||||||
|
# the row says how often this arm spoke at all.
|
||||||
|
passed = (
|
||||||
|
min(cue_gate.LINES, sum(1 for s, _n in hits if gate.passes(s)))
|
||||||
|
if gate is not None else 0
|
||||||
|
)
|
||||||
source = arm.source
|
source = arm.source
|
||||||
try:
|
try:
|
||||||
io.record_retrieval(
|
io.record_retrieval(
|
||||||
@@ -1438,21 +1442,34 @@ async def run_note_arm(
|
|||||||
searched=bool(report.get("searched", True)),
|
searched=bool(report.get("searched", True)),
|
||||||
suppressed=len(hits) - len(fresh),
|
suppressed=len(hits) - len(fresh),
|
||||||
duration_ms=(time.perf_counter() - t0) * 1000.0,
|
duration_ms=(time.perf_counter() - t0) * 1000.0,
|
||||||
|
**_gate_fields(gate, passed),
|
||||||
)
|
)
|
||||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||||
_telemetry_failed(source)
|
_telemetry_failed(source)
|
||||||
result = NoteResult(answered=answered, chunks=report.get("best_chunk") or {})
|
result = NoteResult(
|
||||||
|
answered=answered, chunks=report.get("best_chunk") or {}, gate=gate,
|
||||||
|
)
|
||||||
if not hits:
|
if not hits:
|
||||||
return result
|
return result
|
||||||
|
|
||||||
menu = _note_band(hits)
|
menu = _note_band(hits)
|
||||||
|
if gate is not None:
|
||||||
|
# ABSTAIN BY DEFAULT. A line speaks only past the gate, and at most
|
||||||
|
# the top few do; a cue whose best match is ordinary for this
|
||||||
|
# reader gets nothing, slots included — a slot's candidate scores
|
||||||
|
# no higher than the best hit, so it could not pass either.
|
||||||
|
menu = [(s, n) for s, n in menu if gate.passes(s)][:cue_gate.LINES]
|
||||||
|
if not menu:
|
||||||
|
return result
|
||||||
|
floor = max(floor, gate.bar)
|
||||||
|
budget = min(budget, cue_gate.LINES)
|
||||||
# The slots are told about the named records as if already shown, so
|
# The slots are told about the named records as if already shown, so
|
||||||
# a slot that picks one does not book a surfacing the lookup booked.
|
# a slot that picks one does not book a surfacing the lookup booked.
|
||||||
shown = set(moment.seen | moment.named)
|
shown = set(moment.seen | moment.named)
|
||||||
for slot in arm.slots:
|
for slot in arm.slots:
|
||||||
menu, slot_id = await _reserve_note_slot(
|
menu, slot_id = await _reserve_note_slot(
|
||||||
io, arm, slot, moment, menu, floor=floor, budget=budget,
|
io, arm, slot, moment, menu, floor=floor, budget=budget,
|
||||||
shown=shown,
|
shown=shown, capped=gate is not None,
|
||||||
)
|
)
|
||||||
if slot_id is not None:
|
if slot_id is not None:
|
||||||
result.slot_ids[slot.source] = slot_id
|
result.slot_ids[slot.source] = slot_id
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ Settings UI all enumerate THIS table rather than hard-coding special cases.
|
|||||||
WHAT A FLOOR IS, AND WHAT IT IS NOT
|
WHAT A FLOOR IS, AND WHAT IT IS NOT
|
||||||
|
|
||||||
It is not a relevance judgement. Relevance is decided by the reader, which is
|
It is not a relevance judgement. Relevance is decided by the reader, which is
|
||||||
the only participant that can read a trigger against a situation — and the
|
the only participant that can read a rule against a situation, which is why
|
||||||
injected line says so out loud ("read it before deciding it does not apply").
|
the injected line carries the rule's statement rather than a verdict.
|
||||||
|
|
||||||
A floor answers the cheaper question: *is this worth ranking at all*. `k` is
|
A floor answers the cheaper question: *is this worth ranking at all*. `k` is
|
||||||
what binds, and `k` is a BUDGET — how much of this surface's attention a
|
what binds, and `k` is a BUDGET — how much of this surface's attention a
|
||||||
|
|||||||
@@ -152,6 +152,8 @@ def _build_payload(
|
|||||||
suppressed: int | None = None,
|
suppressed: int | None = None,
|
||||||
best_available: float | None = None,
|
best_available: float | None = None,
|
||||||
best_available_id: int | None = None,
|
best_available_id: int | None = None,
|
||||||
|
gate_bar: float | None = None,
|
||||||
|
gate_kept: int | None = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Reduce a retrieval call to a flat, JSON-safe RetrievalLog payload.
|
"""Reduce a retrieval call to a flat, JSON-safe RetrievalLog payload.
|
||||||
|
|
||||||
@@ -200,6 +202,14 @@ def _build_payload(
|
|||||||
),
|
),
|
||||||
"result_ids": items,
|
"result_ids": items,
|
||||||
"duration_ms": (round(duration_ms, 2) if duration_ms is not None else None),
|
"duration_ms": (round(duration_ms, 2) if duration_ms is not None else None),
|
||||||
|
# The cue-swap gate, on a gated surface: the bar a line had to reach
|
||||||
|
# and how many did. Null bar with a count means the gate could not
|
||||||
|
# judge yet and nothing spoke; both null means the surface is ungated.
|
||||||
|
"gate_bar": (
|
||||||
|
None if gate_bar is None or gate_bar == float("-inf")
|
||||||
|
else round(float(gate_bar), 5)
|
||||||
|
),
|
||||||
|
"gate_kept": None if gate_kept is None else int(gate_kept),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -239,6 +249,8 @@ def record_retrieval(
|
|||||||
best_available: float | None = None,
|
best_available: float | None = None,
|
||||||
best_available_id: int | None = None,
|
best_available_id: int | None = None,
|
||||||
searched: bool = True,
|
searched: bool = True,
|
||||||
|
gate_bar: float | None = None,
|
||||||
|
gate_kept: int | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Fire-and-forget: record one retrieval call.
|
"""Fire-and-forget: record one retrieval call.
|
||||||
|
|
||||||
@@ -292,6 +304,8 @@ def record_retrieval(
|
|||||||
suppressed=suppressed,
|
suppressed=suppressed,
|
||||||
best_available=best_available,
|
best_available=best_available,
|
||||||
best_available_id=best_available_id,
|
best_available_id=best_available_id,
|
||||||
|
gate_bar=gate_bar,
|
||||||
|
gate_kept=gate_kept,
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.debug("retrieval telemetry payload build failed", exc_info=True)
|
logger.debug("retrieval telemetry payload build failed", exc_info=True)
|
||||||
|
|||||||
@@ -3,8 +3,10 @@ that history says about where a rule is worth delivering.
|
|||||||
|
|
||||||
Three calls, one table (`rule_deliveries`):
|
Three calls, one table (`rule_deliveries`):
|
||||||
|
|
||||||
- `record` — fire-and-forget, from the plugin doors that know the session:
|
- `record` — from the plugin doors that know the session: every line an arm
|
||||||
every line an arm put in front of it, full or repeat.
|
rendered, full or repeat. Within a bound request the rows wait in a buffer
|
||||||
|
until the door's payload is assembled, and `flush` writes only the lines
|
||||||
|
that made it into the payload (`hook_payload.fit`).
|
||||||
- `mark_opened` — the session opened a rule: the latest unopened delivery of
|
- `mark_opened` — the session opened a rule: the latest unopened delivery of
|
||||||
it in that session gets the stamp. An open with no delivery behind it (the
|
it in that session gets the stamp. An open with no delivery behind it (the
|
||||||
agent looked a rule up unprompted) stamps nothing.
|
agent looked a rule up unprompted) stamps nothing.
|
||||||
@@ -42,10 +44,27 @@ _UNSAFE = re.compile(r"[^A-Za-z0-9._-]")
|
|||||||
# plugin routes so the arms several calls deep record against it without every
|
# plugin routes so the arms several calls deep record against it without every
|
||||||
# signature between carrying it. Unbound (the MCP door, a test) records nothing.
|
# signature between carrying it. Unbound (the MCP door, a test) records nothing.
|
||||||
_session: ContextVar[str] = ContextVar("rule_delivery_session", default="")
|
_session: ContextVar[str] = ContextVar("rule_delivery_session", default="")
|
||||||
|
# Rows rendered during the bound request, written by `flush`.
|
||||||
|
_pending: ContextVar[list | None] = ContextVar("rule_delivery_pending", default=None)
|
||||||
|
|
||||||
|
|
||||||
def bind_session(session_id: str | None) -> None:
|
def bind_session(session_id: str | None) -> None:
|
||||||
_session.set(_clean_session(session_id))
|
_session.set(_clean_session(session_id))
|
||||||
|
_pending.set([])
|
||||||
|
|
||||||
|
|
||||||
|
def flush(kept: set[int] | None = None) -> None:
|
||||||
|
"""Write this request's buffered rows: those for rules in `kept`, or all
|
||||||
|
of them when `kept` is None. Rows for a line the payload left out are
|
||||||
|
dropped, since the session was never shown it."""
|
||||||
|
rows = _pending.get()
|
||||||
|
if not rows:
|
||||||
|
return
|
||||||
|
_pending.set([])
|
||||||
|
if kept is not None:
|
||||||
|
rows = [r for r in rows if r["rule_id"] in kept]
|
||||||
|
if rows:
|
||||||
|
spawn(_insert(rows), site="rule_delivery_write")
|
||||||
|
|
||||||
|
|
||||||
def bound() -> bool:
|
def bound() -> bool:
|
||||||
@@ -64,9 +83,9 @@ def record(
|
|||||||
user_id: int, session_id: str | None, source: str,
|
user_id: int, session_id: str | None, source: str,
|
||||||
lines: list[tuple[int, str, str]],
|
lines: list[tuple[int, str, str]],
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Record delivered lines: `(rule_id, at, form)` each. Fire-and-forget,
|
"""Record delivered lines: `(rule_id, at, form)` each. A no-op without a
|
||||||
and a no-op without a session, since an open could never be tied back.
|
session, since an open could never be tied back. `session_id` None means
|
||||||
`session_id` None means the one bound for this request."""
|
the one bound for this request, whose rows wait for `flush`."""
|
||||||
sid = _clean_session(_session.get() if session_id is None else session_id)
|
sid = _clean_session(_session.get() if session_id is None else session_id)
|
||||||
if not sid or not lines:
|
if not sid or not lines:
|
||||||
return
|
return
|
||||||
@@ -79,6 +98,10 @@ def record(
|
|||||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||||
logger.debug("rule delivery payload build failed", exc_info=True)
|
logger.debug("rule delivery payload build failed", exc_info=True)
|
||||||
return
|
return
|
||||||
|
pending = _pending.get() if session_id is None else None
|
||||||
|
if pending is not None:
|
||||||
|
pending.extend(rows)
|
||||||
|
return
|
||||||
spawn(_insert(rows), site="rule_delivery_write")
|
spawn(_insert(rows), site="rule_delivery_write")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -347,3 +347,39 @@ def _default_gate_bars():
|
|||||||
|
|
||||||
with patch("grimoire.services.dedup._gate_setting", AsyncMock(side_effect=_default)):
|
with patch("grimoire.services.dedup._gate_setting", AsyncMock(side_effect=_default)):
|
||||||
yield
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _default_payload_budget(request):
|
||||||
|
"""Stub the settings read behind a hook payload's budget.
|
||||||
|
|
||||||
|
Every injecting plugin door fits its payload through `hook_payload.fit`,
|
||||||
|
which reads the user's budget; stubbed to the default so a unit test of a
|
||||||
|
door needs no database. The integration lane reads the real setting.
|
||||||
|
"""
|
||||||
|
if request.node.get_closest_marker("integration"):
|
||||||
|
yield
|
||||||
|
return
|
||||||
|
from grimoire.services import hook_payload
|
||||||
|
|
||||||
|
with patch.object(hook_payload, "payload_budget",
|
||||||
|
AsyncMock(return_value=hook_payload.DEFAULT_BUDGET)):
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _ungated_doors(request):
|
||||||
|
"""Leave the plugin doors' cue-swap gate off unless a test asks for it.
|
||||||
|
|
||||||
|
The gate reads the user's earlier cues from `retrieval_logs`, which a
|
||||||
|
test that is about something else has not written, so with it on every
|
||||||
|
door would abstain. A test of the gate marks itself `cue_gate`, or calls
|
||||||
|
`cue_gate` directly.
|
||||||
|
"""
|
||||||
|
if request.node.get_closest_marker("cue_gate"):
|
||||||
|
yield
|
||||||
|
return
|
||||||
|
from grimoire.services import plugin_context
|
||||||
|
|
||||||
|
with patch.object(plugin_context, "_gate_for", AsyncMock(return_value=None)):
|
||||||
|
yield
|
||||||
|
|||||||
@@ -0,0 +1,181 @@
|
|||||||
|
"""The cue-swap gate: when a record found by resemblance alone may speak.
|
||||||
|
|
||||||
|
The property it exists for is pinned by replay: on cues that match nothing in
|
||||||
|
particular, a fixed similarity bar fires more and more often as the store
|
||||||
|
grows, while the gate fires at about its rate on a small store and a large
|
||||||
|
one alike. Then the arms that take it: a notes menu abstains unless its top
|
||||||
|
line is unusual for this reader and shows at most two lines; a preference
|
||||||
|
found by resemblance is held to the gate while a rule is not.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import random
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from grimoire.services import cue_gate
|
||||||
|
from grimoire.services import retrieval_pipeline as rp
|
||||||
|
from grimoire.services.cue_gate import Gate, conformal_bar
|
||||||
|
from tests.helpers import fake_note
|
||||||
|
|
||||||
|
|
||||||
|
# ── the statistic ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def test_too_few_cues_to_judge_by_is_no_bar():
|
||||||
|
assert conformal_bar([0.5] * (cue_gate.MIN_SAMPLE - 1), 10) is None
|
||||||
|
assert Gate(bar=None, sample=3, rate=10).passes(0.99) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_bar_beats_all_but_the_rate_of_earlier_cues():
|
||||||
|
scores = [i / 100 for i in range(100)] # 0.00 … 0.99
|
||||||
|
# k = ceil(101 * 0.9) = 91, so the bar is the 91st smallest: 0.90.
|
||||||
|
assert conformal_bar(scores, 10) == pytest.approx(0.90)
|
||||||
|
assert conformal_bar(scores, 50) == pytest.approx(0.50)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_rate_setting_is_clamped():
|
||||||
|
assert cue_gate.clamp_rate("0") == cue_gate.RATE_MIN
|
||||||
|
assert cue_gate.clamp_rate("90") == cue_gate.RATE_MAX
|
||||||
|
assert cue_gate.clamp_rate("x") == cue_gate.RATE_DEFAULT
|
||||||
|
|
||||||
|
|
||||||
|
def _best_of(store_size: int, rng: random.Random) -> float:
|
||||||
|
"""The best score a cue that matches nothing reaches against a store:
|
||||||
|
the maximum of `store_size` unrelated resemblances."""
|
||||||
|
return max(0.45 + 0.05 * rng.gauss(0, 1) for _ in range(store_size))
|
||||||
|
|
||||||
|
|
||||||
|
def test_on_unrelated_cues_a_fixed_bar_fires_more_as_the_store_grows_and_the_gate_does_not():
|
||||||
|
rng = random.Random(7)
|
||||||
|
small, large, calibration, trials, rate = 32, 2048, 200, 400, 10
|
||||||
|
|
||||||
|
def cues(n, count):
|
||||||
|
return [_best_of(n, rng) for _ in range(count)]
|
||||||
|
|
||||||
|
# A fixed bar tuned to fire on 5% of unrelated cues against the small store.
|
||||||
|
tuned = sorted(cues(small, 1000))[949]
|
||||||
|
fired = {}
|
||||||
|
for n in (small, large):
|
||||||
|
bar = conformal_bar(cues(n, calibration), rate)
|
||||||
|
test = cues(n, trials)
|
||||||
|
fired[n] = (
|
||||||
|
sum(s >= tuned for s in test) / trials,
|
||||||
|
sum(s >= bar for s in test) / trials,
|
||||||
|
)
|
||||||
|
fixed_small, gate_small = fired[small]
|
||||||
|
fixed_large, gate_large = fired[large]
|
||||||
|
assert fixed_small < 0.10 and fixed_large > 0.80, fired
|
||||||
|
assert gate_small <= 0.16 and gate_large <= 0.16, fired
|
||||||
|
assert abs(gate_small - gate_large) < 0.08, fired
|
||||||
|
|
||||||
|
|
||||||
|
# ── the notes arm ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def _note(nid, score):
|
||||||
|
return score, fake_note(id=nid, title=f"record {nid}", user_id=1)
|
||||||
|
|
||||||
|
|
||||||
|
def _note_io(hits, gate):
|
||||||
|
async def search(_uid, _q, **kw):
|
||||||
|
return [] if kw.get("note_type") else list(hits)
|
||||||
|
|
||||||
|
return rp.NoteIO(search=search, record_retrieval=MagicMock(),
|
||||||
|
record_surfaced=MagicMock(), gate=AsyncMock(return_value=gate))
|
||||||
|
|
||||||
|
|
||||||
|
async def _menu(hits, gate, budget=4):
|
||||||
|
io = _note_io(hits, gate)
|
||||||
|
result = await rp.run_note_arm(
|
||||||
|
rp.AUTO_INJECT, rp.NoteMoment(user_id=1, query="q", project_id=2),
|
||||||
|
floor=0.5, budget=budget, io=io,
|
||||||
|
)
|
||||||
|
return result, io
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_a_menu_speaks_only_past_the_gate_and_at_most_two_lines():
|
||||||
|
hits = [_note(1, 0.86), _note(2, 0.85), _note(3, 0.84), _note(4, 0.83)]
|
||||||
|
result, io = await _menu(hits, Gate(bar=0.80, sample=200, rate=10))
|
||||||
|
assert [int(n.id) for _s, n in result.menu] == [1, 2]
|
||||||
|
(row,) = [c.kwargs for c in io.record_retrieval.call_args_list
|
||||||
|
if c.kwargs["source"] == "auto_inject"]
|
||||||
|
assert row["gate_bar"] == 0.80 and row["gate_kept"] == 2
|
||||||
|
# The searched candidates are still the row's results: they are what the
|
||||||
|
# next call's comparison set and any floor review read.
|
||||||
|
assert len(row["results"]) == 4
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_a_cue_whose_best_match_is_ordinary_gets_nothing():
|
||||||
|
hits = [_note(1, 0.79), _note(2, 0.75)]
|
||||||
|
result, io = await _menu(hits, Gate(bar=0.80, sample=200, rate=10))
|
||||||
|
assert result.menu == []
|
||||||
|
io.record_surfaced.assert_not_called()
|
||||||
|
(row,) = [c.kwargs for c in io.record_retrieval.call_args_list]
|
||||||
|
assert row["gate_kept"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_an_uncalibrated_gate_is_silence_and_no_gate_is_the_old_menu():
|
||||||
|
hits = [_note(1, 0.95), _note(2, 0.90)]
|
||||||
|
quiet, _ = await _menu(hits, Gate(bar=None, sample=4, rate=10))
|
||||||
|
assert quiet.menu == []
|
||||||
|
ungated, _ = await _menu(hits, None)
|
||||||
|
assert [int(n.id) for _s, n in ungated.menu] == [1, 2]
|
||||||
|
|
||||||
|
|
||||||
|
# ── preferences on the rule arms ──────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def _rule(rid, kind):
|
||||||
|
return SimpleNamespace(id=rid, title=f"{kind} {rid}", kind=kind, statement="Said plainly.",
|
||||||
|
when_to_apply="when", enforcement="inform", salience="normal")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_a_preference_found_by_resemblance_is_held_to_the_gate_and_a_rule_is_not():
|
||||||
|
hits = [(0.78, _rule(1, "rule")), (0.77, _rule(2, "preference")), (0.92, _rule(3, "preference"))]
|
||||||
|
hits.sort(key=lambda h: -h[0])
|
||||||
|
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
|
||||||
|
record_rule_surfaced=MagicMock(),
|
||||||
|
gate=AsyncMock(return_value=Gate(bar=0.85, sample=200, rate=10)))
|
||||||
|
result = await rp.run_rule_arm(
|
||||||
|
rp.PROMPT_RULE, rp.RuleMoment(user_id=1, query="q", project_id=2, where="here"),
|
||||||
|
floor=0.5, budget=5, io=io,
|
||||||
|
)
|
||||||
|
assert sorted(result.shown_rule_ids) == [1, 3]
|
||||||
|
row = io.record_retrieval.call_args_list[0].kwargs
|
||||||
|
assert row["gate_bar"] == 0.85 and row["gate_kept"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_reply_backstop_takes_no_gate():
|
||||||
|
assert rp.REPLY_RULE.gates_preferences is False
|
||||||
|
assert all(arm.gates_preferences for arm in (rp.PROMPT_RULE, rp.PRE_TOOL_RULE, rp.WRITE_PATH_RULE))
|
||||||
|
assert rp.AUTO_INJECT.gated and rp.WRITE_PATH.gated
|
||||||
|
|
||||||
|
|
||||||
|
# ── turns the harness wrote ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_turn_the_harness_wrote_is_not_searched():
|
||||||
|
from grimoire.services.plugin_context import is_harness_turn
|
||||||
|
|
||||||
|
assert is_harness_turn(" <task-notification><task-id>x</task-id>")
|
||||||
|
assert is_harness_turn("<command-name>/compact</command-name>")
|
||||||
|
assert not is_harness_turn("merge it and redeploy")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_the_prompt_menu_refuses_a_harness_turn(monkeypatch):
|
||||||
|
from grimoire.services import plugin_context
|
||||||
|
|
||||||
|
monkeypatch.setattr(plugin_context, "get_autoinject_config", AsyncMock(
|
||||||
|
return_value={"enabled": True, "threshold": 0.55, "top_k": 3}))
|
||||||
|
search = AsyncMock(return_value=[])
|
||||||
|
monkeypatch.setattr(plugin_context, "semantic_search_notes", search)
|
||||||
|
out = await plugin_context.build_autoinject_hint(1, "<task-notification>done</task-notification>")
|
||||||
|
assert out["context"] == "" and not search.called
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
"""A hook payload fitted to a budget: what is kept, in what order, what its
|
||||||
|
ids say, and which rule deliveries are recorded."""
|
||||||
|
import contextvars
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
from grimoire.services import hook_payload as hp
|
||||||
|
from grimoire.services import rule_deliveries
|
||||||
|
from grimoire.services.hook_payload import Part
|
||||||
|
|
||||||
|
|
||||||
|
def _p(text, **kw):
|
||||||
|
return Part(text=text, **kw)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parts_are_kept_in_order_and_the_payload_stays_within_the_budget():
|
||||||
|
parts = [_p("a" * 600, ids={hp.RULE: (1,)}), _p("b" * 600, ids={hp.RULE: (2,)}),
|
||||||
|
_p("c" * 600, ids={hp.NOTE: (9,)})]
|
||||||
|
fitted = hp.assemble(parts, 1300)
|
||||||
|
assert len(fitted.context) <= 1300
|
||||||
|
assert fitted.ids(hp.RULE) == [1, 2] and fitted.ids(hp.NOTE) == []
|
||||||
|
assert fitted.context.index("a") < fitted.context.index("b")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_part_that_does_not_fit_is_skipped_and_a_smaller_later_one_still_fits():
|
||||||
|
parts = [_p("r" * 500), _p("S" * 2000, ids={hp.SHAPE: ("core",)}), _p("n" * 300, ids={hp.NOTE: (4,)})]
|
||||||
|
fitted = hp.assemble(parts, 1000)
|
||||||
|
assert "S" not in fitted.context
|
||||||
|
assert fitted.ids(hp.SHAPE) == [] and fitted.ids(hp.NOTE) == [4]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_blocks_header_prints_once_before_its_first_kept_part_and_is_charged():
|
||||||
|
head = "> Possibly relevant:"
|
||||||
|
parts = [_p("> - #1 one", block="menu", header=head, ids={hp.NOTE: (1,)}),
|
||||||
|
_p("> - #2 two", block="menu", header=head, ids={hp.NOTE: (2,)})]
|
||||||
|
fitted = hp.assemble(parts, 5000)
|
||||||
|
assert fitted.context == f"{head}\n> - #1 one\n> - #2 two"
|
||||||
|
# The header counts against the part it rides: one that fits alone does
|
||||||
|
# not fit once its block's header is added.
|
||||||
|
long_head, line = "h" * 600, "x" * 500
|
||||||
|
tight = hp.assemble([_p(line, block="m", header=long_head, ids={hp.NOTE: (1,)})], 1000)
|
||||||
|
assert tight.context == "" and tight.ids(hp.NOTE) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_separate_blocks_are_separated_by_a_blank_line():
|
||||||
|
fitted = hp.assemble([_p("rule", block="rules"), _p("shape")], 5000)
|
||||||
|
assert fitted.context == "rule\n\nshape"
|
||||||
|
|
||||||
|
|
||||||
|
def test_keep_only_filters_a_response_list_to_what_was_shown():
|
||||||
|
fitted = hp.assemble([_p("x" * 400, ids={hp.RULE: (3,)}), _p("y" * 9000, ids={hp.RULE: (5,)})], 2000)
|
||||||
|
assert fitted.keep_only(hp.RULE, [5, 3, 7]) == [3]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_budget_is_bounded_under_the_hook_context_cap():
|
||||||
|
assert hp.HARD_MAX < 8_000
|
||||||
|
assert hp.clamp(50_000) == hp.HARD_MAX
|
||||||
|
assert hp.clamp(10) == hp.MIN_BUDGET
|
||||||
|
assert hp.clamp("not a number") == hp.DEFAULT_BUDGET
|
||||||
|
assert hp.MIN_BUDGET <= hp.DEFAULT_BUDGET <= hp.HARD_MAX
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_result_without_parts_is_one_part_carrying_all_its_ids():
|
||||||
|
result = {"context": "whole", "rule_ids": [1, 2]}
|
||||||
|
parts = hp.parts_of(result, {hp.RULE: "rule_ids"})
|
||||||
|
assert parts == [Part(text="whole", ids={hp.RULE: (1, 2)})]
|
||||||
|
assert hp.parts_of({"context": ""}, {}) == []
|
||||||
|
own = {"context": "c", "parts": [_p("p")]}
|
||||||
|
assert hp.parts_of(own, {}) == [_p("p")] and "parts" not in own
|
||||||
|
|
||||||
|
|
||||||
|
def test_rule_parts_pair_each_line_with_its_rule():
|
||||||
|
parts = hp.rule_parts(["one", "two"], [11, 34], block="rules")
|
||||||
|
assert [p.ids[hp.RULE] for p in parts] == [(11,), (34,)]
|
||||||
|
|
||||||
|
|
||||||
|
# ── the delivery record ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
# Each runs in a copy of the context, so the session it binds ends with it.
|
||||||
|
|
||||||
|
def test_a_bound_request_records_only_the_rule_lines_that_were_kept():
|
||||||
|
contextvars.copy_context().run(_bound_request_records_only_kept)
|
||||||
|
|
||||||
|
|
||||||
|
def _bound_request_records_only_kept():
|
||||||
|
spawned = MagicMock()
|
||||||
|
with patch.object(rule_deliveries, "spawn", spawned), \
|
||||||
|
patch.object(rule_deliveries, "_insert", lambda rows: rows):
|
||||||
|
rule_deliveries.bind_session("s-1")
|
||||||
|
rule_deliveries.record(1, None, "pre_tool_rule", [(11, "pre_tool_rule", "full"),
|
||||||
|
(34, "pre_tool_rule", "full")])
|
||||||
|
assert not spawned.called, "a bound request's rows wait for the payload"
|
||||||
|
rule_deliveries.flush({11})
|
||||||
|
rows = spawned.call_args.args[0]
|
||||||
|
assert [r["rule_id"] for r in rows] == [11]
|
||||||
|
spawned.reset_mock()
|
||||||
|
rule_deliveries.flush()
|
||||||
|
assert not spawned.called, "the buffer is spent once flushed"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_session_named_outright_records_at_once():
|
||||||
|
contextvars.copy_context().run(_named_session_records_at_once)
|
||||||
|
|
||||||
|
|
||||||
|
def _named_session_records_at_once():
|
||||||
|
spawned = MagicMock()
|
||||||
|
with patch.object(rule_deliveries, "spawn", spawned), \
|
||||||
|
patch.object(rule_deliveries, "_insert", lambda rows: rows):
|
||||||
|
rule_deliveries.bind_session("s-2")
|
||||||
|
rule_deliveries.record(1, "other", "x", [(5, "x", "full")])
|
||||||
|
assert spawned.called
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""Real-Postgres tests for the cue-swap gate: its comparison set is the user's
|
||||||
|
own recent cues on one surface and scope, read from `retrieval_logs`."""
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy import delete
|
||||||
|
|
||||||
|
from grimoire.models import async_session
|
||||||
|
from grimoire.models.retrieval_log import RetrievalLog
|
||||||
|
from grimoire.services import cue_gate
|
||||||
|
from tests.helpers import ensure_user
|
||||||
|
|
||||||
|
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
|
||||||
|
|
||||||
|
SOURCE = "auto_inject"
|
||||||
|
|
||||||
|
|
||||||
|
async def _user() -> int:
|
||||||
|
async with async_session() as s:
|
||||||
|
user = await ensure_user(s, "cue_gate_owner")
|
||||||
|
uid = user.id
|
||||||
|
await s.commit()
|
||||||
|
await s.execute(delete(RetrievalLog).where(RetrievalLog.user_id == uid))
|
||||||
|
await s.commit()
|
||||||
|
cue_gate.forget(uid)
|
||||||
|
return uid
|
||||||
|
|
||||||
|
|
||||||
|
async def _cues(uid, scores, *, project_id=None, source=SOURCE):
|
||||||
|
async with async_session() as s:
|
||||||
|
for score in scores:
|
||||||
|
s.add(RetrievalLog(user_id=uid, source=source, query="q", project_id=project_id,
|
||||||
|
result_count=0, result_ids=[], best_available_score=score))
|
||||||
|
await s.commit()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_the_bar_is_read_from_this_users_cues_on_this_surface_and_project():
|
||||||
|
uid = await _user()
|
||||||
|
await _cues(uid, [i / 100 for i in range(100)], project_id=5)
|
||||||
|
# Another surface's cues and another project's do not move it.
|
||||||
|
await _cues(uid, [0.99] * 50, project_id=5, source="write_path")
|
||||||
|
await _cues(uid, [0.99] * 50, project_id=6)
|
||||||
|
gate = await cue_gate.gate_for(uid, SOURCE, 5)
|
||||||
|
assert gate.scope == "project" and gate.sample == 100
|
||||||
|
assert gate.bar == pytest.approx(0.90)
|
||||||
|
assert gate.passes(0.91) and not gate.passes(0.89)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_a_project_with_too_few_cues_borrows_the_users_cues_everywhere():
|
||||||
|
uid = await _user()
|
||||||
|
await _cues(uid, [0.5] * 30, project_id=7)
|
||||||
|
await _cues(uid, [0.6] * 5, project_id=8)
|
||||||
|
gate = await cue_gate.gate_for(uid, SOURCE, 8)
|
||||||
|
assert gate.scope == "all" and gate.sample == 35
|
||||||
|
|
||||||
|
|
||||||
|
async def test_with_too_few_cues_anywhere_nothing_passes():
|
||||||
|
uid = await _user()
|
||||||
|
await _cues(uid, [0.5] * 5)
|
||||||
|
gate = await cue_gate.gate_for(uid, SOURCE, None)
|
||||||
|
assert gate.bar is None and not gate.passes(0.99)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_the_readout_counts_how_often_a_surface_spoke():
|
||||||
|
uid = await _user()
|
||||||
|
await _cues(uid, [0.5] * 25)
|
||||||
|
async with async_session() as s:
|
||||||
|
for kept in (0, 0, 2, 1):
|
||||||
|
s.add(RetrievalLog(user_id=uid, source=SOURCE, query="q", result_count=0,
|
||||||
|
result_ids=[], gate_bar=0.8, gate_kept=kept))
|
||||||
|
await s.commit()
|
||||||
|
(row,) = await cue_gate.readout(uid, [(SOURCE, "records")])
|
||||||
|
assert row["calls"] == 4 and row["fired"] == 2 and row["sample"] == 25
|
||||||
@@ -35,7 +35,10 @@ async def _rows(uid: int) -> list[RuleDelivery]:
|
|||||||
|
|
||||||
|
|
||||||
async def _record(uid, sid, source, lines):
|
async def _record(uid, sid, source, lines):
|
||||||
|
# A bound request's rows wait for the door's payload; flushing all of
|
||||||
|
# them is what a door does when every line it rendered was kept.
|
||||||
rule_deliveries.record(uid, sid, source, lines)
|
rule_deliveries.record(uid, sid, source, lines)
|
||||||
|
rule_deliveries.flush()
|
||||||
await background.drain()
|
await background.drain()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ _CFG = {"enabled": True, "threshold": 0.55, "top_k": 3}
|
|||||||
|
|
||||||
# The phrase the rule arms use. A lesson line that acquired it would be a rule
|
# The phrase the rule arms use. A lesson line that acquired it would be a rule
|
||||||
# with a different table, which is the thing this milestone exists to avoid.
|
# with a different table, which is the thing this milestone exists to avoid.
|
||||||
_BINDING_PHRASE = "before deciding it does not apply"
|
_BINDING_PHRASE = "it binds"
|
||||||
|
|
||||||
|
|
||||||
async def _menu(main_hits, *, lesson_hits=None, reuse_hits=None, cfg=None,
|
async def _menu(main_hits, *, lesson_hits=None, reuse_hits=None, cfg=None,
|
||||||
@@ -284,5 +284,5 @@ def test_the_surfacing_guards_can_fail():
|
|||||||
assert [42] != []
|
assert [42] != []
|
||||||
# A header that borrowed the binding voice.
|
# A header that borrowed the binding voice.
|
||||||
assert _BINDING_PHRASE in (
|
assert _BINDING_PHRASE in (
|
||||||
"Read it with get_rule(9) before deciding it does not apply."
|
"Rule 9 “CI polling” may apply here; it binds: CI is polled by the agent."
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -462,7 +462,7 @@ async def test_an_unshaped_act_through_a_tool_carries_no_shape():
|
|||||||
assert "reply_shape" not in out
|
assert "reply_shape" not in out
|
||||||
|
|
||||||
|
|
||||||
async def test_the_route_puts_the_shape_ahead_of_the_rules_and_returns_its_key():
|
async def test_the_route_puts_the_rules_ahead_of_the_shape_and_returns_its_key():
|
||||||
from grimoire.routes import plugin as routes
|
from grimoire.routes import plugin as routes
|
||||||
|
|
||||||
deliver = AsyncMock(return_value=(ASK, rp.RuleResult(lines=["a line"], rule_ids=[5])))
|
deliver = AsyncMock(return_value=(ASK, rp.RuleResult(lines=["a line"], rule_ids=[5])))
|
||||||
@@ -473,7 +473,7 @@ async def test_the_route_puts_the_shape_ahead_of_the_rules_and_returns_its_key()
|
|||||||
with patch.object(routes.moment_delivery_svc, "deliver_for_act", deliver):
|
with patch.object(routes.moment_delivery_svc, "deliver_for_act", deliver):
|
||||||
body = await (await routes.moment.__wrapped__()).get_json()
|
body = await (await routes.moment.__wrapped__()).get_json()
|
||||||
assert body["shape_keys"] == ["asks"]
|
assert body["shape_keys"] == ["asks"]
|
||||||
assert body["context"].index("Who decides what") < body["context"].index("a line")
|
assert body["context"].index("a line") < body["context"].index("Who decides what")
|
||||||
|
|
||||||
async with app.test_request_context("/api/plugin/moment", method="POST", json=event,
|
async with app.test_request_context("/api/plugin/moment", method="POST", json=event,
|
||||||
query_string={"shapes_seen": "asks"}):
|
query_string={"shapes_seen": "asks"}):
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
"""The core reply shape rides every turn.
|
"""The core reply shape rides every turn.
|
||||||
|
|
||||||
Every turn ends in a reply, and the operator's prompt is the last point before
|
Every turn ends in a reply, and the operator's prompt is the last point before
|
||||||
it is written, so the per-turn retrieval carries the core shape ahead of
|
it is written, so the per-turn retrieval carries the core shape after the
|
||||||
everything else: in full the first time a session sees it, as its one-line
|
rules and ahead of the records menu: in full the first time a session sees it, as its one-line
|
||||||
reminder after that, and in full again once a compaction has swept the
|
reminder after that, and in full again once a compaction has swept the
|
||||||
ledger. What is pinned here is that round trip across the shell/Python seam —
|
ledger. What is pinned here is that round trip across the shell/Python seam —
|
||||||
the route's order and keys, and the hook's ledger.
|
the route's order and keys, and the hook's ledger.
|
||||||
@@ -49,10 +49,10 @@ async def _retrieve(query_string, turn_context="CORE SHAPE"):
|
|||||||
return await resp.get_json(), turn
|
return await resp.get_json(), turn
|
||||||
|
|
||||||
|
|
||||||
async def test_the_turns_shape_leads_the_payload_and_its_key_comes_back():
|
async def test_the_turns_shape_follows_the_rules_and_its_key_comes_back():
|
||||||
body, _turn = await _retrieve({"q": "fix the flaky thing"})
|
body, _turn = await _retrieve({"q": "fix the flaky thing"})
|
||||||
ctx = body["context"]
|
ctx = body["context"]
|
||||||
assert ctx.index("CORE SHAPE") < ctx.index("RULE LINE") < ctx.index("NOTES MENU")
|
assert ctx.index("RULE LINE") < ctx.index("CORE SHAPE") < ctx.index("NOTES MENU")
|
||||||
assert body["shape_keys"] == ["core"]
|
assert body["shape_keys"] == ["core"]
|
||||||
# Both arms' fresh rules reach the shared ledger.
|
# Both arms' fresh rules reach the shared ledger.
|
||||||
assert body["rule_ids"] == [11, 173]
|
assert body["rule_ids"] == [11, 173]
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ def test_every_endpoint_is_reachable_on_the_app():
|
|||||||
assert rules == {
|
assert rules == {
|
||||||
"/api/retrieval/surfaces",
|
"/api/retrieval/surfaces",
|
||||||
"/api/retrieval/surfaces/<surface>",
|
"/api/retrieval/surfaces/<surface>",
|
||||||
|
"/api/retrieval/gate",
|
||||||
"/api/retrieval/tuning-history",
|
"/api/retrieval/tuning-history",
|
||||||
"/api/retrieval/moments",
|
"/api/retrieval/moments",
|
||||||
"/api/retrieval/moments/mappings",
|
"/api/retrieval/moments/mappings",
|
||||||
|
|||||||
@@ -107,15 +107,13 @@ def test_the_band_is_computed_from_scores_not_from_the_ledger():
|
|||||||
assert [r.id for _s, r in kept] == [1, 2]
|
assert [r.id for _s, r in kept] == [1, 2]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("seen", [False, True])
|
def test_the_leading_line_carries_the_statement_on_a_first_mention():
|
||||||
def test_the_leading_line_carries_the_trigger(seen):
|
"""Rank 0 on a first mention says what the rule says; a repeat cites it."""
|
||||||
"""Rank 0 gets the full rendering, on either tail."""
|
rule = fake_rule(id=4, title="dev is home", when_to_apply=_TRIGGER)
|
||||||
line = _rule_hint_line(
|
first = _rule_hint_line(rule, where="to this Bash call", seen=False)
|
||||||
fake_rule(id=4, title="dev is home", when_to_apply=_TRIGGER),
|
assert rule.statement in first and "get_rule(4)" in first
|
||||||
where="to this Bash call", seen=seen, compact=False,
|
again = _rule_hint_line(rule, where="to this Bash call", seen=True)
|
||||||
)
|
assert rule.statement not in again and "get_rule(4)" in again
|
||||||
assert _TRIGGER in line
|
|
||||||
assert "get_rule(4)" in line
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("seen", [False, True])
|
@pytest.mark.parametrize("seen", [False, True])
|
||||||
@@ -161,12 +159,12 @@ def test_shortening_a_line_does_not_decide_what_it_says_about_holding():
|
|||||||
assert len({fresh, named, held}) == 3, (
|
assert len({fresh, named, held}) == 3, (
|
||||||
"the compact branch collapsed two holding states into one line"
|
"the compact branch collapsed two holding states into one line"
|
||||||
)
|
)
|
||||||
assert "not in this session's loaded set" in fresh
|
assert "First mention" in fresh
|
||||||
assert "not opened" in named
|
assert "not opened" in named
|
||||||
assert "no longer hold it" in held
|
assert "Opened earlier" in held
|
||||||
# The claim that most needs to survive shortening: a line the session never
|
# The claim that most needs to survive shortening: a line the session never
|
||||||
# opened must not imply it did, however little room the line was given.
|
# opened must not imply it did, however little room the line was given.
|
||||||
assert "no longer hold it" not in named
|
assert "Opened earlier" not in named
|
||||||
|
|
||||||
|
|
||||||
def test_a_compact_line_is_materially_shorter_than_a_full_one():
|
def test_a_compact_line_is_materially_shorter_than_a_full_one():
|
||||||
@@ -188,7 +186,8 @@ def test_a_compact_line_is_materially_shorter_than_a_full_one():
|
|||||||
"the next step feels like shipping it, and whenever an earlier merge "
|
"the next step feels like shipping it, and whenever an earlier merge "
|
||||||
"this session reads like standing permission for the next one."
|
"this session reads like standing permission for the next one."
|
||||||
)
|
)
|
||||||
rule = fake_rule(id=4, title="dev is home", when_to_apply=long_trigger)
|
rule = fake_rule(id=4, title="dev is home", when_to_apply=long_trigger,
|
||||||
|
statement=long_trigger)
|
||||||
full = _rule_hint_line(rule, where="here", seen=False, compact=False)
|
full = _rule_hint_line(rule, where="here", seen=False, compact=False)
|
||||||
compact = _rule_hint_line(rule, where="here", seen=False, compact=True)
|
compact = _rule_hint_line(rule, where="here", seen=False, compact=True)
|
||||||
assert len(compact) * 2 < len(full)
|
assert len(compact) * 2 < len(full)
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ def _rule(rid=156, kind="rule"):
|
|||||||
|
|
||||||
def test_a_rule_never_surfaced_is_offered_as_new():
|
def test_a_rule_never_surfaced_is_offered_as_new():
|
||||||
line = _rule_hint_line(_rule(), where="here", seen=False, held=False)
|
line = _rule_hint_line(_rule(), where="here", seen=False, held=False)
|
||||||
assert "not in this session's loaded set" in line
|
assert "First mention this session" in line
|
||||||
|
|
||||||
|
|
||||||
def test_a_rule_named_but_not_opened_says_so_and_still_invites():
|
def test_a_rule_named_but_not_opened_says_so_and_still_invites():
|
||||||
@@ -65,7 +65,7 @@ def test_a_rule_named_but_not_opened_says_so_and_still_invites():
|
|||||||
|
|
||||||
def test_a_rule_the_session_opened_is_described_as_opened():
|
def test_a_rule_the_session_opened_is_described_as_opened():
|
||||||
line = _rule_hint_line(_rule(), where="here", seen=True, held=True)
|
line = _rule_hint_line(_rule(), where="here", seen=True, held=True)
|
||||||
assert "opened it earlier" in line
|
assert "Opened earlier this session" in line
|
||||||
assert "get_rule(156)" in line
|
assert "get_rule(156)" in line
|
||||||
|
|
||||||
|
|
||||||
@@ -85,7 +85,7 @@ def test_held_outranks_seen_regardless_of_kind():
|
|||||||
the two together is how one of them gets forgotten."""
|
the two together is how one of them gets forgotten."""
|
||||||
for kind in ("rule", "preference"):
|
for kind in ("rule", "preference"):
|
||||||
line = _rule_hint_line(_rule(kind=kind), where="here", seen=True, held=True)
|
line = _rule_hint_line(_rule(kind=kind), where="here", seen=True, held=True)
|
||||||
assert "opened it earlier" in line
|
assert "Opened earlier this session" in line
|
||||||
|
|
||||||
|
|
||||||
# ── the recorder ───────────────────────────────────────────────────────────
|
# ── the recorder ───────────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -1149,14 +1149,14 @@ _HELD = fake_rule(
|
|||||||
statement="Every wait on something that can fail to answer carries a deadline.",
|
statement="Every wait on something that can fail to answer carries a deadline.",
|
||||||
when_to_apply="writing any call that crosses a process boundary",
|
when_to_apply="writing any call that crosses a process boundary",
|
||||||
)
|
)
|
||||||
_FRESH_TAIL = "not in this session's loaded set"
|
_FRESH_TAIL = "First mention this session"
|
||||||
# `seen` WITHOUT `held` is the middle state: an arm named this rule earlier,
|
# `seen` WITHOUT `held` is the middle state: an arm named this rule earlier,
|
||||||
# and the session never opened it. Every test below drives the arms with
|
# and the session never opened it. Every test below drives the arms with
|
||||||
# `exclude_rule_ids` alone — the naming ledger — so this is the tail they
|
# `exclude_rule_ids` alone — the naming ledger — so this is the tail they
|
||||||
# produce, and it must not claim the session read a teaser nobody opened.
|
# produce, and it must not claim the session read a teaser nobody opened.
|
||||||
_SEEN_TAIL = "Mentioned earlier this session but not opened"
|
_SEEN_TAIL = "Named earlier this session, not opened"
|
||||||
# The third state, reached only when the opened ledger names the rule too.
|
# The third state, reached only when the opened ledger names the rule too.
|
||||||
_HELD_TAIL = "You opened it earlier this session"
|
_HELD_TAIL = "Opened earlier this session"
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(("source", "run"), _ARMS, ids=["write_path", "pre_tool", "prompt"])
|
@pytest.mark.parametrize(("source", "run"), _ARMS, ids=["write_path", "pre_tool", "prompt"])
|
||||||
@@ -1235,8 +1235,8 @@ _PREF = fake_rule(
|
|||||||
statement="Advance one investigative step per turn.",
|
statement="Advance one investigative step per turn.",
|
||||||
when_to_apply="during hard debugging",
|
when_to_apply="during hard debugging",
|
||||||
)
|
)
|
||||||
_RULE_FORCE = "before deciding it does not apply"
|
_RULE_FORCE = "it binds"
|
||||||
_PREF_FORCE = "for how this has been done before"
|
_PREF_FORCE = "how this has been done before"
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(("source", "run"), _ARMS, ids=["write_path", "pre_tool", "prompt"])
|
@pytest.mark.parametrize(("source", "run"), _ARMS, ids=["write_path", "pre_tool", "prompt"])
|
||||||
@@ -1251,7 +1251,7 @@ async def test_a_preference_does_not_speak_in_the_rules_voice(source, run):
|
|||||||
"""
|
"""
|
||||||
ctx = (await run([(0.81, _PREF)], MagicMock()))["context"]
|
ctx = (await run([(0.81, _PREF)], MagicMock()))["context"]
|
||||||
|
|
||||||
assert "Preference that may apply" in ctx, (
|
assert "Preference 177" in ctx, (
|
||||||
f"{source} announced a preference as something else. The noun is the "
|
f"{source} announced a preference as something else. The noun is the "
|
||||||
f"one word a skimming reader gets to place the register, so it is the "
|
f"one word a skimming reader gets to place the register, so it is the "
|
||||||
f"word that has to move. Context was: {ctx!r}"
|
f"word that has to move. Context was: {ctx!r}"
|
||||||
@@ -1297,7 +1297,7 @@ async def test_kind_and_seen_do_not_read_each_other(source, run):
|
|||||||
)
|
)
|
||||||
# And the head still differs in the seen case — a repeat of a preference
|
# And the head still differs in the seen case — a repeat of a preference
|
||||||
# is still a preference.
|
# is still a preference.
|
||||||
assert "Preference that may apply" in pref_seen, (
|
assert "Preference 177" in pref_seen, (
|
||||||
f"{source} lost the preference register on a repeat, so a preference "
|
f"{source} lost the preference register on a repeat, so a preference "
|
||||||
f"seen twice reads as a rule the second time"
|
f"seen twice reads as a rule the second time"
|
||||||
)
|
)
|
||||||
@@ -1305,25 +1305,24 @@ async def test_kind_and_seen_do_not_read_each_other(source, run):
|
|||||||
|
|
||||||
@pytest.mark.parametrize(("source", "run"), _ARMS, ids=["write_path", "pre_tool", "prompt"])
|
@pytest.mark.parametrize(("source", "run"), _ARMS, ids=["write_path", "pre_tool", "prompt"])
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_neither_tail_injects_the_rule_statement(source, run):
|
async def test_a_first_mention_carries_the_statement_and_a_repeat_does_not(source, run):
|
||||||
"""The budget, pinned on both branches.
|
"""What a line is for, pinned on both branches.
|
||||||
|
|
||||||
A reference costs the same ~40 tokens as a first surfacing precisely
|
A first mention carries the rule's own words, so the reader has what it
|
||||||
because neither carries the statement. If a repeat ever starts inlining the
|
says without a second call. A repeat is a reference: the session was
|
||||||
body "since we are re-showing it anyway", this arm stops being cheap enough
|
handed the statement already, and quoting it again on every call is the
|
||||||
to always emit — and always emitting is the whole mechanism.
|
cost this line is built to avoid.
|
||||||
"""
|
"""
|
||||||
for excluded in ([], [156]):
|
fresh = (await run([(0.81, _HELD)], MagicMock()))["context"]
|
||||||
ctx = (await run([(0.81, _HELD)], MagicMock(),
|
assert _HELD.statement in fresh, (
|
||||||
exclude_rule_ids=excluded))["context"]
|
f"{source} named the rule without saying what it says"
|
||||||
assert _HELD.statement not in ctx, (
|
)
|
||||||
f"{source} inlined the rule statement (excluded={excluded!r}); the "
|
repeat = (await run([(0.81, _HELD)], MagicMock(), exclude_rule_ids=[156]))["context"]
|
||||||
f"line carries title, trigger and a pull pointer and nothing more"
|
assert _HELD.statement not in repeat, (
|
||||||
)
|
f"{source} quoted the statement again on a repeat"
|
||||||
assert _HELD.title in ctx and "process boundary" in ctx, (
|
)
|
||||||
"the line dropped the title or the trigger — those are what let a "
|
for ctx in (fresh, repeat):
|
||||||
"reader decide whether to pull without pulling"
|
assert _HELD.title in ctx and "get_rule(156)" in ctx
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# ── What a reference IS in the telemetry: nothing new ──────────────────────
|
# ── What a reference IS in the telemetry: nothing new ──────────────────────
|
||||||
@@ -1449,7 +1448,7 @@ async def test_a_preference_that_lost_the_ranking_still_gets_a_line():
|
|||||||
"dropped — which is the outcome with no symptom: the rules that won "
|
"dropped — which is the outcome with no symptom: the rules that won "
|
||||||
"are legitimate hits and nothing in the telemetry looks wrong"
|
"are legitimate hits and nothing in the telemetry looks wrong"
|
||||||
)
|
)
|
||||||
assert "Preference that may apply" in out["context"]
|
assert "Preference 140" in out["context"]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
@@ -1466,7 +1465,7 @@ async def test_the_slot_is_not_spent_when_a_preference_already_placed():
|
|||||||
"reserved line for a kind already represented is noise the general "
|
"reserved line for a kind already represented is noise the general "
|
||||||
"ranking had already decided against"
|
"ranking had already decided against"
|
||||||
)
|
)
|
||||||
assert out["context"].count("Preference that may apply") == 1
|
assert out["context"].count("Preference 140") == 1
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ async def test_a_matching_linked_lesson_brings_its_rule_in_rule_voice():
|
|||||||
)
|
)
|
||||||
lines, ids = await _run(stack)
|
lines, ids = await _run(stack)
|
||||||
assert ids == [7]
|
assert ids == [7]
|
||||||
assert lines[0].startswith("Standing rule")
|
assert lines[0].startswith("Rule ")
|
||||||
assert "Reached through lesson #41" in lines[0]
|
assert "Reached through lesson #41" in lines[0]
|
||||||
assert log.call_args.kwargs["source"] == "rule_via_lesson"
|
assert log.call_args.kwargs["source"] == "rule_via_lesson"
|
||||||
assert surfaced.call_args.kwargs == {"user_id": 1, "rule_ids": [7], "source": "rule_via_lesson"}
|
assert surfaced.call_args.kwargs == {"user_id": 1, "rule_ids": [7], "source": "rule_via_lesson"}
|
||||||
|
|||||||
Reference in New Issue
Block a user