Skip to content

feat(memory): rebuild the group relationship graph pipeline on observations - #13

Merged
zhx8702 merged 6 commits into
mainfrom
feat/group-graph-observation-pipeline
Sep 28, 2026
Merged

zhx8702 merged 6 commits into
mainfrom
feat/group-graph-observation-pipeline

Conversation

@zhx8702

@zhx8702 zhx8702 commented Sep 16, 2026 •

Copy link
Copy Markdown
Owner

Summary

群聊关系图在线上已经"看起来没价值"一段时间,根因是几层叠加的:

  • 自动抽取只读 plugin_memory_event,而群消息早已只进 plugin_wxbot_group_observations,tick 静默跳过、无汇总日志。
  • 规则层几乎只有 co_participated(同窗共现),图里"人人相连"没有信息量。
  • LLM 层每窗口 >60s 超时(网关上 reasoning tier),且即使成功,_insert_or_touch_memory_item 把 "Group window relation: wxid_xxx …" 里的 wxid 当 PII → 全部 pending → fact 不进图。新旧代码都如此,LLM 关系从来没进过图。
  • 前端固定列布局 + 服务端按时间截断 500 条,看到的是随机 500 条而不是最强的 500 条。
  • 人工审核按钮在 Postgres 上一直是坏的:审计写入把 reviewed_at 的 ISO 字符串绑进 CAST(... AS TIMESTAMP),asyncpg 直接拒绝。

本 PR 三个 commit:后端管线(plugins/memory)、前端关系图页、待审核自动化。

后端

  • 数据源:observation 表成为一等证据源;窗口 / 游标 / 历史统计都带 source,两套 id 空间不混用;observation 证据保留脱敏元数据(发送者标签、时间)而不是被丢掉。每个 tick 输出一条 memory.group_graph_auto_extract_tick 汇总。
  • 规则层:基于结构化元数据的引用回复、@(元数据 + 文本)、前缀回复,经 GroupMemberDirectory 把别名 id / 昵称归一到同一成员。co_participated 改为可选(MEMORY_GROUP_GRAPH_CO_PARTICIPATION_EDGES,默认关)。信号按证据 id 集合累计,重跑窗口不会涨计数;strength 由直接信号、弱信号、活跃天数合成。
  • LLM 层:补算按窗口入队(plugin_memory_extraction_job,trace 前缀 group-window-llm:),scheduler 每 tick 按窗口超时 / 重试 / 退避消化;模型层级可配(默认 tier-1,线上 10–16s 出合法 JSON)。Prompt 要求短词、中文优先、product/model 归 tool、至少 2 条消息支撑、不再输出 co_participated;校验丢弃单条证据、id 形状的幻觉人物、"大家/the group"、句子和纯数字。
  • 接受策略:直接信号立即接受;模型关系跨天复现或同窗 ≥3 条证据接受,否则进待审;人工决定始终优先。group window 关系只对非人物 object 词做敏感检测,不受 prompt 置信度阈值影响。
  • 待审自动化(第三个 commit):每个 tick 末尾跑一遍印证扫描,待审的模型关系只要被同群已通过的图印证——同一主题 / 工具已有别的已通过关系(说明这个词在群里是真的),或两个人之间已有 co_participated 以外的已通过边——就以 system/auto-review 身份走 review_memory_item_acceptance 接受,审计、fact、向量更新与人工点击完全一致。既没复现也没印证的,群关系有自己的待审保留期 MEMORY_GROUP_RELATION_REVIEW_RETENTION_DAYS(默认 14 天,不再和通用 30 天取 max),到期由治理过期。
  • 图 API:过滤下推 SQL、按 strength 排序、补齐缺失端点实体、合并对称 co_participated、返回 page.total/truncated;边的时间用证据日期而不是抽取时间;node_type 语义改为"触及该类型的边 + 两端"(原先要求两端同型,tool/topic 永远为空)。
  • 审计修复:append_memory_acceptance_audit 把 reviewed_at 转成 datetime 再绑定。

前端

  • 可读视图默认只看直接互动并折叠 co_participated;摘要说明隐藏了多少、服务端是否截断。
  • 人物用带种子的力导向布局;主题 / 产品放右侧 lane,仅在有节点时渲染,有最小间距,满了走第二列。
  • 线宽 log(证据数),透明度随最近证据时间;边卡片显示 strength 和活跃天数;详情显示证据来源与观察日期区间。
  • 修掉预算裁边后的孤点;主题 / 工具节点始终有标签且不压到邻近节点;小写工具名(cursor、uniapp)不再被当账号 id 匿名成"成员 N"。
  • 待审核队列显示 "已显示 / 总数"(来自 page.total)而不是封顶的 100,文案说明自动通过 / 自动过期的路径。

线上验证(15.204.10.156,已部署本分支)

  • 首个 tick:29 个目标全部来自 observation(memory_event 为 0),规则层 322 条,LLM 6/6。
  • claude-relay 群 7 天重跑:152 个窗口 152 成功 0 失败,21 分钟,1043 条;修复后 361 条被 PII 误判卡住的已接受关系恢复 active。
  • 印证扫描首次跑:682 条待审扫描,接受 297(主题印证 187、人物对印证 110),0 失败;剩余 385 条等跨天复现或 14 天过期。之后每 tick 处理 200 条,日志 memory.group_relation_auto_review。
  • 现在图内 78 人 / 67 主题 / 64 工具;replied_to 758、addressed 106、interested_in 196+。
  • 回滚:/opt/agent-console-backups/pre-group-graph-20260916T015700Z.tgz + 镜像 tag rollback-20260916T015700Z。

Test plan

  • pytest tests/unit -k "memory or group_graph"(含新增:噪声形状过滤、prompt 内容、PII probe、node_type 语义、跨窗口合并并接受、印证扫描的 SQL 范围与接受逻辑、tick 顺序、审计 datetime 绑定)
  • pytest tests/unit 全量:仅 test_persona_profile_catalog_migration / test_plugin_manifest_contract / compose contract 失败,三者在干净 main 上同样失败
  • ruff check plugins/memory tests
  • frontend: tsc -b --noEmit、vitest run src/pages/relationship-graph、vite build(Docker 内)
  • CI:main 当前在 "Verify plugin descriptor and manifest consistency" 步骤即失败(10 个插件 description/digest drift,与本 PR 无关),本 PR 预计同一步骤失败

配置新增(均有默认值,.env.example / docker-compose.yml 已同步)

MEMORY_GROUP_GRAPH_AUTO_ACCEPT、MEMORY_GROUP_GRAPH_CO_PARTICIPATION_EDGES、MEMORY_GROUP_GRAPH_LLM_MODEL_TIER、MEMORY_GROUP_GRAPH_LLM_TIMEOUT_SECONDS、MEMORY_GROUP_GRAPH_LLM_JOBS_PER_TICK、MEMORY_GROUP_GRAPH_LLM_JOB_MAX_ATTEMPTS、MEMORY_GROUP_GRAPH_AUTO_REVIEW_BATCH、MEMORY_GROUP_RELATION_REVIEW_RETENTION_DAYS(14)、MEMORY_LLM_EXTRACTION_JOB_STALE_DAYS;MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED 默认改为 false。

Made with Cursor

…gnals and LLM window jobs

The group relationship graph had gone quiet in production: the auto-extract
tick only read plugin_memory_event, which stopped receiving group traffic, and
scope denials were logged at info without any tick summary. Even when the LLM
did run, every relation it produced was parked in `pending` because the
generic sensitivity detector read the participant id ("wxid_...") in the
synthetic item content as PII, so no model relation ever reached the graph.

Data source and observability
- plugin_wxbot_group_observations is a first-class evidence source; windows,
  cursors and history stats carry `source` so memory-event and observation id
  spaces never mix. Observation evidence keeps display-safe metadata (sender
  label, timestamp) instead of being dropped.
- Every tick logs one `memory.group_graph_auto_extract_tick` summary with
  targets, sources, applied counts, skip reasons and LLM job results.
- get_group_graph_history_dates resolves session aliases and counts
  observations per day.

Rule layer
- Deterministic candidates come from structured metadata: quoted replies,
  @-mentions (metadata and text) and prefix replies, resolved through a
  GroupMemberDirectory so alias ids and nicknames map to one canonical member.
- Same-window co-participation is opt-in (memory_group_graph_co_participation_edges,
  default off); it said little more than "both were online".
- Signals are tracked as per-signal evidence id sets, so re-running a window
  never inflates counts; strength combines direct signals, weak signals and
  distinct days.

LLM layer
- Catch-up enqueues one durable job per window (plugin_memory_extraction_job,
  trace prefix group-window-llm:) and the tick drains them with a per-window
  timeout, retries and backoff; the generic per-event drain leaves them alone.
- Model tier is configurable (default tier-1: the reasoning tier needed >60s
  per window on the production gateway, the non-reasoning tier answers in
  10-16s).
- Prompt asks for short canonical terms in the group's language, tool/project
  typing and at least two supporting messages; it no longer offers
  co_participated. Validation drops single-message claims, id-shaped phantom
  members, "the group" pseudo-objects, sentences and bare numbers.

Acceptance and lifecycle
- Tiered policy: direct signals accept immediately; model-only relations
  accept once they repeat across days or have >=3 supporting messages in one
  window, otherwise they wait in needs_review; human decisions always stick.
- Group window relations keep their own sensitivity probe (only a free-text
  object term is checked) and are not gated by the prompt confidence floor.
- needs_review group relations wait memory_group_relation_review_retention_days
  (180) before governance expires them, instead of the generic 30 days.

Graph API
- Filters are pushed into SQL, facts are ordered by relation strength, missing
  endpoint entities are backfilled, symmetric co_participated pairs merge, and
  the response reports page totals/truncation. Edge timestamps are evidence
  dates (when messages were observed), not extraction time.
- node_type selects edges touching a node of that type instead of requiring
  both endpoints to match, which made tool/topic filters return nothing.
… out by force

The page drew a fixed-lane picture where every member sat in one column and
most edges were same-window co-participation, so it read as "everyone talked
to everyone". It now follows the strength-ranked API and shows who actually
interacts.

- Default 可读 view keeps direct interactions (quoted replies, @-mentions,
  Q&A, model relations) and folds co_participated; the summary explains how
  many people/edges are hidden and whether the server truncated the page.
- People are placed with a seeded force layout (edges pull by log evidence,
  nodes repel, light gravity); topics/projects and products/tools sit in
  right-hand lanes that only render when populated, with a minimum vertical
  gap and a second staggered column when a lane is full.
- Stroke width follows log(evidence), opacity follows evidence recency;
  edge cards show strength and active-day count; the details panel shows the
  evidence source (memory events vs observations) and observed date range.
- Nodes whose every edge fell under the edge budget are no longer drawn as
  unexplained isolated dots.
- Topic/tool nodes are always labelled, labels point away from the
  neighbouring lane and never cover another node, and lowercase term names
  ("cursor", "uniapp", "sub2api") are no longer mistaken for account ids and
  anonymised as "成员 N".
- Single-window extraction sends its own per-window model timeout; catch-up
  and recent-coverage run in `enqueue` mode so the request pays only for the
  rule layer and the scheduler drains the model jobs.
…d of waiting for a reviewer

Single-window model claims land in needs_review, and on production that
queue reached several hundred entries within two days with nobody expected
to click through them. The queue is now drained by the system:

- Each scheduler tick ends with a corroboration sweep. A pending model
  relation is accepted when the accepted graph of the same group already
  agrees with it: the object term has another accepted relation (any member,
  so the term is real in this group), or the two people already share an
  accepted edge other than co-participation. Accepts go through
  review_memory_item_acceptance as `system/auto-review`, so the audit trail
  and item/fact/vector updates are the same as a human decision.
- Group relations get their own review retention (default 14 days instead of
  inheriting max(30, 180)); whatever is neither repeated nor corroborated by
  then is expired by governance rather than parked for half a year.
- The acceptance audit insert bound the reviewed_at ISO string into a
  TIMESTAMP cast, which asyncpg rejects; every manual accept/reject on
  Postgres failed with a DBAPIError. It now binds a datetime.
- The review queue panel shows "shown / total" from page.total instead of a
  capped 100, and its copy explains the automatic paths.

First production run over 682 pending relations accepted 297 (187 by term,
110 by pair) with no failures; the rest wait for a second day or expiry.
…to real interest

An operator asked how "two people interested in TFBOYS" came about when no
message contains the string. The evidence panel only listed counts and
dates, so there was no way to see that the model had grouped 易烊千玺 /
王源 / 王俊凯 under the band name, or that the five minutes in question
were people mocking the band rather than liking it.

- The evidence endpoint now returns a `judgement` block: extraction method,
  per-signal counts, the policy that accepted the edge, who reviewed it, and
  for model relations the model's own one-line rationale (a paraphrase; chat
  text still never leaves the API). The details panel renders it as
  "怎么判定的" with a note that terms may be the model's generalisation.
- The window prompt now defines interested_in as wanting/liking/using/asking
  for the thing; mocking, criticising, gossiping, or discussing whether the
  system labelled something correctly is `mentioned`. The rationale must be
  one short sentence in the group's language naming the concrete behaviour.

The second finding was a genuine false positive: the operator's own group
message "好像有 bug,怎么还有对 tfboys 感兴趣的" was extracted as him being
interested in tfboys. Rejected through the review endpoint, which also
confirmed the audit fix on production Postgres.
Rows written before the participant-id PII fix still carried
sensitivity=pii. The touch path keeps the more sensitive of the stored and
requested categories, so a legacy row could never return to normal: when the
corrected re-extraction accepted such a relation it landed in pending again
and its fact stayed invisible (洋白 -> TFBOYS after the relabel run).

Group window relations now always take the freshly probed value; the stored
flag is only inherited for ordinary memory items. Production rows were
repaired once (917 flagged, 159 accepted relations reactivated).
Selecting a node dimmed the rest of the graph and there was no way back:
no background click, no button, no key. Users reloaded the page.

- Clicking empty canvas (not a pan) clears the selection.
- Esc on the canvas clears it.
- Clicking the already selected node/edge toggles it off.
- The details panel gets a 取消选中 button while something is selected.
@zhx8702
zhx8702 merged commit 92631d3 into main Sep 28, 2026
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant