feat(7835): what resembles the work but is not shown is named by id in one pointer line
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Python tests (push) Failing after 2m1s
CI & Build / integration (push) Successful in 2m20s
CI & Build / Build & push image (push) Skipped

A pointer before a payload:
- the notes arms fetch a few results past the menu; those that cleared
  the floor but were held back by the gate, the band or the budget are
  named by id per kind, with the call that opens each kind, in one line
  ("Also resembling this, not shown: ...") at the message and the write
  path;
- they are recorded in the record ledger as `pointed`, so an open that
  follows is counted apart from pushed lines;
- setting a task in progress returns records_in_area: the notes and open
  issues tagged to the task's areas, by id (a work.start row in the
  kind x moment table says which kinds; it answers in a tool reply, so it
  is shown as unmeasured).

The static context says what a pointer line means. Plugin version minted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 19:16:01 -05:00
co-authored by Claude Opus 5.5
parent a2e474f401
commit b68aefc109
17 changed files with 307 additions and 33 deletions
+28
View File
@@ -18,6 +18,8 @@ Sentinels (preserved from existing fable-mcp):
"""
from __future__ import annotations
import logging
from grimoire.mcp._context import current_user_id
from grimoire.mcp.tools import systems as systems_tools
from grimoire.services import access as access_svc
@@ -34,6 +36,7 @@ from grimoire.services.notes import minted_kind
from grimoire.services import placement as placement_svc
from grimoire.services import planning as planning_svc
from grimoire.services import record_batch as batch_svc
from grimoire.services import record_kinds, record_links
from grimoire.services import rulebooks as rulebooks_svc
from grimoire.services import systems as systems_svc
from grimoire.services import task_logs as task_logs_svc
@@ -43,6 +46,8 @@ from grimoire.services.record_refs import refuse_guessed_ids
from grimoire.services.text import elide
from grimoire.services import moment_delivery
logger = logging.getLogger(__name__)
# A work log entry is prose, often long — the discipline asks for what was
# decided and why, not a line of status. Two caps, not one, because the entries
@@ -410,6 +415,11 @@ async def update_task(
reconstructing them, because a remembered milestone title or "next step"
reads exactly like a real one when it is wrong.
Setting a task `in_progress` also returns `records_in_area` when the
task's areas hold notes or open issues: one line naming them by id with
the call that opens each. Read the ones that bear on the work before
starting it.
Closing a task (done or cancelled) also returns `reply_shape`, the
default shape of the completion report you are about to write, and
`report_back`: a one-line reminder of what that reply should cover. The
@@ -465,11 +475,29 @@ async def update_task(
# Owed family adoptions filed while the task was open — work now
# waiting in some project, which the report names.
await family_adoption_svc.attach_owed_adoptions(uid, data, note)
if status == "in_progress":
await _attach_area_records(uid, task_id, data)
return await moment_delivery.attach_moment_rules(
uid, "update_task", {"status": status, "project_id": project_id}, data,
)
async def _attach_area_records(uid: int, task_id: int, data: dict) -> None:
"""Name, by id, what is recorded in the areas of a task being taken up:
the `work.start` row of the kind×moment table says which kinds. Absent
when the task has no area or nothing is recorded there."""
try:
kinds = await record_kinds.kinds_for(uid, "work.start")
found = await record_links.area_records(uid, task_id, kinds)
line = record_kinds.pointer_line(
found, "Recorded in this task's areas", capped_at=record_links.AREA_DEPTH,
)
if line:
data["records_in_area"] = line[0].removeprefix("> ")
except Exception: # noqa: BLE001 - a decoration never breaks the payload
logger.debug("area records for task %s could not be attached", task_id, exc_info=True)
async def add_task_log(task_id: int, content: str) -> dict:
"""Append a timestamped progress log entry to a Grimoire task.
+2 -1
View File
@@ -10,7 +10,8 @@ from grimoire.models.base import iso
PUSHED = "pushed" # a hook put it there unasked (auto-inject, the write path, a slot)
ASKED = "asked" # it was a result of a search the session ran itself
DIRECT = "direct" # it was opened with nothing delivering it first in the session
WAYS = (PUSHED, ASKED, DIRECT)
POINTED = "pointed" # named by id in a pointer line, without its title or passage
WAYS = (PUSHED, POINTED, ASKED, DIRECT)
class RecordDelivery(Base):
+32 -4
View File
@@ -25,6 +25,8 @@ from grimoire.services import knowledge as knowledge_svc
from grimoire.services import notes as notes_svc
from grimoire.services import projects as projects_svc
from grimoire.services import record_refs as record_refs_svc
from grimoire.models.record_delivery import POINTED
from grimoire.services import record_deliveries as record_deliveries_svc
from grimoire.services import record_kinds
from grimoire.services import record_links as record_links_svc
from grimoire.services import shape_ledger as shape_ledger_svc
@@ -695,7 +697,7 @@ async def build_autoinject_hint(
if not _has_subject(q):
# Nothing to search for: the menu would answer the previous reply,
# not the operator. Records named by number are still shown.
kept, chunks = [], {}
kept, chunks, pointers = [], {}, {}
else:
# Everything below searches, logs and fills its slots on the ENRICHED
# query, so the telemetry row records what was actually asked.
@@ -709,8 +711,8 @@ async def build_autoinject_hint(
),
floor=cfg["threshold"], budget=cfg["top_k"], io=_note_io(),
)
kept, chunks = result.menu, result.chunks
if not kept and not named:
kept, chunks, pointers = result.menu, result.chunks, result.pointers
if not kept and not named and not pointers:
return empty
# A collaborator's note can reach this menu via a shared project, and the
@@ -838,6 +840,17 @@ async def build_autoinject_hint(
ids={hook_payload.NOTE: (nid,)},
))
# What else cleared the floor, named by id only. Recorded as `pointed`
# rather than surfaced: no line was spent on these, so an open that
# follows says whether a pointer is enough.
pointer = record_kinds.pointer_line(pointers, POINTER_LEAD)
if pointer:
lines.append(pointer[0])
parts.append(hook_payload.Part(
text=pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(pointer[1])},
))
record_deliveries_svc.record(user_id, pointer[1], "auto_inject_pointer", way=POINTED)
# A lookup, not a ranking, so it writes no retrieval_logs row — there is no
# score or bar to tune — and its surfacings are its own source, which is
# what lets pull-through say whether a named record gets opened. The
@@ -1070,6 +1083,11 @@ def _rule_io() -> rp.RuleIO:
# this exact file" is a stronger claim than "this resembles something".
# How a door's pointer line opens: records that cleared the floor and were
# not shown. The static context teaches what a line opening this way means.
POINTER_LEAD = "Also resembling this, not shown"
def _prior_art_line(item: dict, marker: str, owner: str | None, foreign_lang: str = "") -> str:
"""One menu line: `- #12 [here] "title"`, attributed when it isn't yours.
@@ -1492,6 +1510,7 @@ async def build_write_path_hint(
# loop is not conditional, so it needs something to read either way, and an
# empty mapping means every line falls back to its title alone.
wp_chunks: dict[int, dict] = {}
pointers: dict[str, list[int]] = {}
if remaining > 0 and query:
# The ranked half is `retrieval_pipeline.run_note_arm` with the
# WRITE_PATH spec: which kinds it asks for and why, the withheld-menu
@@ -1511,6 +1530,7 @@ async def build_write_path_hint(
floor=cfg["threshold"], budget=remaining, io=_note_io(),
)
wp_chunks = result.chunks
pointers = result.pointers
resembles = {
int(note.id): float(score) for score, note in result.answered
if int(note.id) in pulled
@@ -1721,7 +1741,7 @@ async def build_write_path_hint(
]
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 and not pointers):
if design_text or rulings["lines"]:
return {
**empty,
@@ -1846,6 +1866,14 @@ async def build_write_path_hint(
entry.append(f"> ↳ {passage}")
parts[-1] = replace(parts[-1], text="\n".join(entry))
pointer = record_kinds.pointer_line(pointers, POINTER_LEAD)
if pointer:
lines.append(pointer[0])
parts.append(hook_payload.Part(
text=pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(pointer[1])},
))
record_deliveries_svc.record(user_id, pointer[1], "write_path_pointer", way=POINTED)
if suggested:
lines.append(_suggest_line(path, suggested))
parts.append(hook_payload.Part(text=lines[-1]))
+9 -7
View File
@@ -14,7 +14,8 @@ four calls:
of it in the session gets the stamp. With nothing delivering it first, a
`direct` row is written, delivered and opened at once: the record was
reached without being shown.
- `summary` — per kind, how records arrived (`pushed`, `asked`, `direct`),
- `summary` — per kind, how records arrived (`pushed`, `pointed`, `asked`,
`direct`),
by door, and how many were opened.
Only rows from a plugin that reports its version count in the readout: an
@@ -30,7 +31,7 @@ from sqlalchemy import case, delete, func, select, tuple_, update
from grimoire.models import async_session
from grimoire.models.note import Note
from grimoire.models.record_delivery import ASKED, DIRECT, PUSHED, RecordDelivery
from grimoire.models.record_delivery import ASKED, DIRECT, POINTED, PUSHED, RecordDelivery
from grimoire.models.retrieval_log import RetrievalLog
from grimoire.services import rule_deliveries
from grimoire.services.access import readable_notes_clause
@@ -55,15 +56,16 @@ def reset() -> None:
_pending.set([])
def record(user_id: int | None, note_ids, source: str) -> None:
"""Record records a hook pushed to the bound session. A no-op outside a
plugin request, since an open could never be tied back to it."""
def record(user_id: int | None, note_ids, source: str, way: str = PUSHED) -> None:
"""Record records a hook put in front of the bound session: `pushed` as a
line, or `pointed` when only named by id in a pointer line. A no-op
outside a plugin request, since an open could never be tied back to it."""
sid = rule_deliveries.current_session()
if not sid or not user_id:
return
try:
rows = [{"user_id": int(user_id), "session_id": sid, "note_id": int(n),
"way": PUSHED, "source": source, "plugin": rule_deliveries.current_plugin()}
"way": way, "source": source, "plugin": rule_deliveries.current_plugin()}
for n in dict.fromkeys(note_ids or [])]
except Exception: # noqa: BLE001 - observation never breaks the observed
logger.debug("record delivery payload build failed", exc_info=True)
@@ -239,7 +241,7 @@ async def summary(user_id: int, days: int = 30) -> dict:
)).scalar_one()
def zero() -> dict:
return {w: {"delivered": 0, "opened": 0} for w in (PUSHED, ASKED, DIRECT)}
return {w: {"delivered": 0, "opened": 0} for w in (PUSHED, POINTED, ASKED, DIRECT)}
kinds: dict[str, dict] = {}
totals = zero()
+67 -4
View File
@@ -31,10 +31,10 @@ back to its default removes the stored change.
THE DOORS
A door is a point where a record search fires: a catalog moment
(`work.change`), or the operator's message, which is when a session first
hears what the work is and is not a moment rules mount on, so it has its
own key (`message`).
A door is a point where records are offered: a catalog moment
(`work.change` before a write, `work.start` when a task is taken up), or the
operator's message, which is when a session first hears what the work is and
is not a moment rules mount on, so it has its own key (`message`).
"""
from __future__ import annotations
@@ -98,6 +98,13 @@ DOORS: dict[str, Door] = {
sources=("write_path_semantic", "write_path_place", "write_path_sync",
"write_path_linked"),
),
# Taking up a task: what is recorded in the task's own areas, named by id
# in the reply that set it in progress. Notes for what is known there,
# open issues for what is still wrong there.
"work.start": Door(
"work.start", "Taking up a piece of work", "when a task is set in progress",
frozenset({"note", "task:issue"}),
),
}
@@ -139,6 +146,59 @@ def kinds_clause(kinds: Iterable[str]):
return or_(*parts) if parts else false()
# A pointer line names at most this many records of a kind; the count says
# how many there were.
POINTER_IDS = 3
_PLURALS = {
"snippet": "snippets", "note": "notes", "lesson": "lessons", "process": "processes",
"task:issue": "issues", "task:work": "tasks", "task:spike": "spikes",
"task:plan": "plans",
}
def opener(kind: str) -> str:
"""The MCP call that opens a record of this kind."""
if kind.startswith(TASK_PREFIX):
return "get_task"
return {"snippet": "get_snippet", "lesson": "get_lesson",
"process": "get_process"}.get(kind, "get_note")
def pointer_line(
pointers: dict[str, list[int]], lead: str, *, capped_at: int | None = None,
) -> tuple[str, list[int]] | None:
"""One line naming records by id, per kind, with the call that opens each
kind; and the ids it named. None when there is nothing to point at.
A line and a passage per record is what a payload cannot afford for
everything that may bear on the work; an id costs a few characters, and
the session is the one placed to judge whether to open it. A kind with
more records than it names says how many; `capped_at` is the depth the
lookup stopped at, so a count that reached it reads as "at least".
"""
named: list[int] = []
phrases: list[str] = []
for kind in KINDS:
ids = pointers.get(kind) or []
if not ids:
continue
shown = ids[:POINTER_IDS]
named.extend(shown)
count = ""
if len(ids) > len(shown):
count = f"{len(ids)}+ " if capped_at and len(ids) >= capped_at else f"{len(ids)} "
phrases.append(
f"{count}{_PLURALS[kind]} " + ", ".join(f"#{i}" for i in shown)
+ f" (`{opener(kind)}(id)`)"
)
if not phrases:
return None
return (
f"> {lead}: " + "; ".join(phrases) + ". Open one if it may bear on the work.",
named,
)
async def _stored(user_id: int) -> dict[str, frozenset[str]]:
from grimoire.services.settings import get_setting
@@ -195,6 +255,9 @@ async def table(user_id: int, days: int = 30) -> dict:
"kinds": sorted(stored.get(d.key, d.default), key=KINDS.index),
"default": sorted(d.default, key=KINDS.index),
"changed": d.key in stored,
# A door whose lines reach the session in a tool reply rather
# than a plugin hook has no session to record them against.
"measured": bool(d.sources),
"evidence": (evidence or {}).get(d.key, {}),
}
for d in DOORS.values()
+46
View File
@@ -20,6 +20,9 @@ THE TWO LINKS, strongest first
history the file may not share; an open one is live work on it.
Both are scoped to the project and to what the reader may read.
`area_records` answers the same question for a task being taken up: the
records tagged to the task's own areas, which its reply names by id.
"""
from __future__ import annotations
@@ -32,6 +35,7 @@ from grimoire.models.note import Note
from grimoire.models.system import RecordSystem
from grimoire.models.task_log import TaskLog
from grimoire.services.access import readable_notes_clause
from grimoire.services.record_kinds import kind_of, kinds_clause
logger = logging.getLogger(__name__)
@@ -111,3 +115,45 @@ async def issues_for_path(
except Exception: # noqa: BLE001 - a recall aid never breaks its act
logger.warning("linked-issue lookup failed", exc_info=True)
return out
# How many records of a task's areas are counted for its pointer line; past
# this the count reads "at least".
AREA_DEPTH = 20
async def area_records(
user_id: int, record_id: int, kinds, *, depth: int = AREA_DEPTH,
) -> dict[str, list[int]]:
"""`{kind: [id, …]}` of the records sharing an area with `record_id`,
newest first: of the given kinds, readable by this user, and, for tasks,
still open. The record itself is left out."""
kinds = list(kinds or ())
if not record_id or not kinds:
return {}
try:
async with async_session() as session:
areas = select(RecordSystem.system_id).where(RecordSystem.note_id == record_id)
rows = (await session.execute(
select(Note.id, Note.note_type, Note.status, Note.task_kind)
.where(
Note.id != record_id,
Note.deleted_at.is_(None),
readable_notes_clause(user_id),
kinds_clause(kinds),
or_(Note.status.is_(None), Note.status.not_in(_CLOSED)),
exists().where(
RecordSystem.note_id == Note.id,
RecordSystem.system_id.in_(areas),
),
)
.order_by(Note.updated_at.desc(), Note.id.desc())
.limit(depth)
)).all()
except Exception: # noqa: BLE001 - a decoration never breaks the payload
logger.warning("area records lookup failed", exc_info=True)
return {}
out: dict[str, list[int]] = {}
for nid, note_type, status, task_kind in rows:
out.setdefault(kind_of(note_type, status, task_kind), []).append(int(nid))
return out
+37 -2
View File
@@ -1274,6 +1274,12 @@ class NoteResult:
slot_ids: dict = field(default_factory=dict)
"""{slot source: the id it spent}."""
pointers: dict = field(default_factory=dict)
"""{kind: [id, …]} — records the search found past the floor that the
payload does not show (the gate held them back, or the budget had no
room), best first. A door names them by id in one pointer line instead
of spending a line and a passage on each."""
gate: Any = None
"""The `cue_gate.Gate` this call's lines were held to, or None."""
@@ -1390,6 +1396,27 @@ async def _reserve_note_slot(
return (menu + placed)[:budget], slot_id
# How many results past the menu's own a notes arm fetches for its pointer
# line. The line names at most a few per kind, so a deeper fetch would only
# count records nobody is told the ids of.
POINTER_DEPTH = 6
def _pointers(answered: list, exclude) -> dict[str, list[int]]:
"""{kind: ids} of the answered records not excluded, in rank order."""
out: dict[str, list[int]] = {}
for _s, note in answered:
nid = int(note.id)
if nid in exclude:
continue
kind = record_kinds.kind_of(
getattr(note, "note_type", None), getattr(note, "status", None),
getattr(note, "task_kind", None),
)
out.setdefault(kind, []).append(nid)
return out
async def run_note_arm(
arm: NoteArm, moment: NoteMoment, *, floor: float, budget: int, io: NoteIO,
) -> NoteResult:
@@ -1417,8 +1444,9 @@ async def run_note_arm(
scored = moment.in_menu & moment.still_scored
kwargs: dict = {
# The still-scored ids come back and are dropped below, so the
# limit has to cover them.
"limit": budget + len(scored), "threshold": floor,
# limit has to cover them; POINTER_DEPTH more are fetched for the
# pointer line, and never reach the menu or the call row.
"limit": budget + len(scored) + POINTER_DEPTH, "threshold": floor,
"project_id": moment.project_id or None,
**note_search_filters(arm), "report": report,
"record_kinds": record_kinds.search_kinds(allowed),
@@ -1474,6 +1502,7 @@ async def run_note_arm(
_telemetry_failed(source)
result = NoteResult(
answered=answered, chunks=report.get("best_chunk") or {}, gate=gate,
pointers=_pointers(answered, moment.in_menu | moment.seen | moment.named),
)
if not hits:
return result
@@ -1507,6 +1536,12 @@ async def run_note_arm(
# A named record is shown once, in its own block, never again as a match.
menu = [(s, n) for s, n in menu if int(n.id) not in moment.named]
result.menu = menu
shown_here = {int(n.id) for _s, n in menu} | set(result.slot_ids.values())
result.pointers = {
k: [i for i in ids if i not in shown_here]
for k, ids in result.pointers.items()
}
result.pointers = {k: ids for k, ids in result.pointers.items() if ids}
# What SURVIVED the band — the menu the reader saw — where the call
# row holds the candidate set a floor is tuned against. FRESH ONLY,