diff --git a/.env.example b/.env.example index f0f42d3..de77f25 100644 --- a/.env.example +++ b/.env.example @@ -132,6 +132,10 @@ MEMORY_GRAPH_LLM_EXTRACTION_MAX_EPISODES=2 MEMORY_GRAPH_LLM_EXTRACTION_MIN_CONFIDENCE=0.8 MEMORY_GOVERNANCE_AUTO_CLEANUP_ENABLED=true MEMORY_GOVERNANCE_INTERVAL_SECONDS=86400 +MEMORY_GROUP_GRAPH_AUTO_ACCEPT=true +MEMORY_GROUP_GRAPH_CO_PARTICIPATION_EDGES=false +MEMORY_GROUP_GRAPH_AUTO_REVIEW_BATCH=200 +MEMORY_GROUP_RELATION_REVIEW_RETENTION_DAYS=14 MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED=true MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED=true MEMORY_GROUP_GRAPH_AUTO_EXTRACT_INTERVAL_SECONDS=3600 @@ -141,8 +145,17 @@ MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_WINDOWS_PER_SESSION=20 MEMORY_GROUP_GRAPH_AUTO_EXTRACT_WINDOW_SIZE=50 MEMORY_GROUP_GRAPH_AUTO_EXTRACT_TIME_BUDGET_SECONDS=180 MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ROLES=scheduler -MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED=true +# Group relationship targets come from imported memory events and live group +# observations. The legacy SDK history sync before each tick is opt-in. +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED=false MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_MAX_MESSAGES=200 +# LLM window pass: fixed per-window timeout, queued per window, bounded per tick. +# tier-1 (non-reasoning) answers a 50-message window in 10-16s; reasoning tiers time out. +MEMORY_GROUP_GRAPH_LLM_MODEL_TIER=tier-1 +MEMORY_GROUP_GRAPH_LLM_TIMEOUT_SECONDS=60 +MEMORY_GROUP_GRAPH_LLM_JOBS_PER_TICK=6 +MEMORY_GROUP_GRAPH_LLM_JOB_MAX_ATTEMPTS=3 +MEMORY_LLM_EXTRACTION_JOB_STALE_DAYS=30 MEMORY_NEEDS_REVIEW_RETENTION_DAYS=30 MEMORY_REJECTED_RETENTION_DAYS=7 MEMORY_AUTO_EXPIRE_DAYS=180 @@ -409,6 +422,10 @@ COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_EPISODES=2 COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MIN_CONFIDENCE=0.8 COMPOSE_MEMORY_GOVERNANCE_AUTO_CLEANUP_ENABLED=true COMPOSE_MEMORY_GOVERNANCE_INTERVAL_SECONDS=86400 +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_ACCEPT=true +COMPOSE_MEMORY_GROUP_GRAPH_CO_PARTICIPATION_EDGES=false +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_REVIEW_BATCH=200 +COMPOSE_MEMORY_GROUP_RELATION_REVIEW_RETENTION_DAYS=14 COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED=true COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED=true COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_INTERVAL_SECONDS=3600 @@ -418,8 +435,13 @@ COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_WINDOWS_PER_SESSION=20 COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_WINDOW_SIZE=50 COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_TIME_BUDGET_SECONDS=180 COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ROLES=scheduler -COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED=true +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED=false COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_MAX_MESSAGES=200 +COMPOSE_MEMORY_GROUP_GRAPH_LLM_MODEL_TIER=tier-1 +COMPOSE_MEMORY_GROUP_GRAPH_LLM_TIMEOUT_SECONDS=60 +COMPOSE_MEMORY_GROUP_GRAPH_LLM_JOBS_PER_TICK=6 +COMPOSE_MEMORY_GROUP_GRAPH_LLM_JOB_MAX_ATTEMPTS=3 +COMPOSE_MEMORY_LLM_EXTRACTION_JOB_STALE_DAYS=30 COMPOSE_MEMORY_NEEDS_REVIEW_RETENTION_DAYS=30 COMPOSE_MEMORY_REJECTED_RETENTION_DAYS=7 COMPOSE_MEMORY_AUTO_EXPIRE_DAYS=180 diff --git a/app/common/config.py b/app/common/config.py index 0575280..210ae7f 100644 --- a/app/common/config.py +++ b/app/common/config.py @@ -424,6 +424,18 @@ def guarded_dotenv_settings() -> dict[str, Any]: memory_governance_auto_cleanup_enabled: bool = True memory_governance_interval_seconds: float = Field(default=86_400.0, gt=0) memory_group_graph_auto_accept: bool = True + # Same-window co-participation pairs mostly mean "both were online"; the + # rule layer relies on quoted replies, @-mentions and explicit reply + # prefixes instead. Opt in to keep writing co_participated edges. + memory_group_graph_co_participation_edges: bool = False + # Pending model relations are promoted automatically once the accepted + # graph corroborates them (same term used by another accepted relation, or + # an accepted direct edge between the two people) or once they repeat on a + # second day; this is how many candidates one tick re-checks. + memory_group_graph_auto_review_batch: int = Field(default=200, ge=0, le=1000) + # A model relation that is neither corroborated nor repeated within this + # window is expired by governance instead of waiting for a reviewer. + memory_group_relation_review_retention_days: int = Field(default=14, ge=1) memory_group_graph_auto_extract_enabled: bool = True memory_group_graph_auto_extract_llm_enabled: bool = True memory_group_graph_auto_extract_interval_seconds: float = Field(default=3_600.0, gt=0) @@ -433,7 +445,24 @@ def guarded_dotenv_settings() -> dict[str, Any]: memory_group_graph_auto_extract_window_size: int = Field(default=50, ge=10, le=100) memory_group_graph_auto_extract_time_budget_seconds: int = Field(default=180, ge=5, le=180) memory_group_graph_auto_extract_roles: str = "scheduler" - memory_group_graph_auto_extract_sync_enabled: bool = True + # Per-window LLM timeout. The time budget decides how many windows fit in a + # run; it is never divided across windows any more. + memory_group_graph_llm_timeout_seconds: int = Field(default=60, ge=5, le=600) + # Model tier for the window extraction prompt. Structured JSON over a short + # transcript is a fast-model task; reasoning tiers were measured at >60s per + # window on the production gateway versus 10-16s for the non-reasoning tier. + memory_group_graph_llm_model_tier: str = "tier-1" + # The scheduler tick queues one durable LLM job per window and processes at + # most this many per tick with the full timeout each. 0 disables the pass. + memory_group_graph_llm_jobs_per_tick: int = Field(default=6, ge=0, le=50) + memory_group_graph_llm_job_max_attempts: int = Field(default=3, ge=1, le=10) + # Governance marks extraction jobs that stayed pending/failed this long as + # dead so a disabled drain cannot leave them queued forever. + memory_llm_extraction_job_stale_days: int = Field(default=30, ge=1) + # The pre-tick SDK history sync only works for the legacy account-wide + # wxbot connection; live groups already stream into + # plugin_wxbot_group_observations, which the tick now reads directly. + memory_group_graph_auto_extract_sync_enabled: bool = False memory_group_graph_auto_extract_sync_max_messages: int = Field(default=200, ge=20, le=500) memory_needs_review_retention_days: int = Field(default=30, ge=1) memory_rejected_retention_days: int = Field(default=7, ge=1) diff --git a/docker-compose.yml b/docker-compose.yml index 15868aa..9051aba 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -133,6 +133,10 @@ x-app-env: &app-env MEMORY_GRAPH_LLM_EXTRACTION_MIN_CONFIDENCE: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MIN_CONFIDENCE:-0.8} MEMORY_GOVERNANCE_AUTO_CLEANUP_ENABLED: ${COMPOSE_MEMORY_GOVERNANCE_AUTO_CLEANUP_ENABLED:-true} MEMORY_GOVERNANCE_INTERVAL_SECONDS: ${COMPOSE_MEMORY_GOVERNANCE_INTERVAL_SECONDS:-86400} + MEMORY_GROUP_GRAPH_AUTO_ACCEPT: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_ACCEPT:-true} + MEMORY_GROUP_GRAPH_CO_PARTICIPATION_EDGES: ${COMPOSE_MEMORY_GROUP_GRAPH_CO_PARTICIPATION_EDGES:-false} + MEMORY_GROUP_GRAPH_AUTO_REVIEW_BATCH: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_REVIEW_BATCH:-200} + MEMORY_GROUP_RELATION_REVIEW_RETENTION_DAYS: ${COMPOSE_MEMORY_GROUP_RELATION_REVIEW_RETENTION_DAYS:-14} MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED:-true} MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED:-true} MEMORY_GROUP_GRAPH_AUTO_EXTRACT_INTERVAL_SECONDS: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_INTERVAL_SECONDS:-3600} @@ -142,8 +146,13 @@ x-app-env: &app-env MEMORY_GROUP_GRAPH_AUTO_EXTRACT_WINDOW_SIZE: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_WINDOW_SIZE:-50} MEMORY_GROUP_GRAPH_AUTO_EXTRACT_TIME_BUDGET_SECONDS: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_TIME_BUDGET_SECONDS:-180} MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ROLES: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ROLES:-scheduler} - MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED:-true} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED:-false} MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_MAX_MESSAGES: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_MAX_MESSAGES:-200} + MEMORY_GROUP_GRAPH_LLM_MODEL_TIER: ${COMPOSE_MEMORY_GROUP_GRAPH_LLM_MODEL_TIER:-tier-1} + MEMORY_GROUP_GRAPH_LLM_TIMEOUT_SECONDS: ${COMPOSE_MEMORY_GROUP_GRAPH_LLM_TIMEOUT_SECONDS:-60} + MEMORY_GROUP_GRAPH_LLM_JOBS_PER_TICK: ${COMPOSE_MEMORY_GROUP_GRAPH_LLM_JOBS_PER_TICK:-6} + MEMORY_GROUP_GRAPH_LLM_JOB_MAX_ATTEMPTS: ${COMPOSE_MEMORY_GROUP_GRAPH_LLM_JOB_MAX_ATTEMPTS:-3} + MEMORY_LLM_EXTRACTION_JOB_STALE_DAYS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_STALE_DAYS:-30} MEMORY_NEEDS_REVIEW_RETENTION_DAYS: ${COMPOSE_MEMORY_NEEDS_REVIEW_RETENTION_DAYS:-30} MEMORY_REJECTED_RETENTION_DAYS: ${COMPOSE_MEMORY_REJECTED_RETENTION_DAYS:-7} MEMORY_AUTO_EXPIRE_DAYS: ${COMPOSE_MEMORY_AUTO_EXPIRE_DAYS:-180} diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 5316886..582e3b0 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -510,9 +510,32 @@ export type GroupGraphEdge = { acceptance_score?: number | null; acceptance_reason?: string | null; evidence_dates?: string[]; + evidence_day_count?: number; + /** `memory_event`, `observation` or `mixed`: which table backs this edge's evidence. */ + evidence_source?: string; + observation_count?: number; + first_seen_date?: string | null; + last_seen_date?: string | null; + /** When the relation row was written, as opposed to when the messages happened. */ + extracted_at?: string | null; + /** Accumulated interaction strength in [0, 1] (direct signals + distinct days). */ + strength?: number | null; + signals?: Record | null; + /** Fact ids folded into this edge when a symmetric relation was stored in both directions. */ + mirror_ids?: string[]; history?: unknown[]; }; +export type GroupGraphObservationEvidence = { + id: number; + session_id?: string; + sender_label?: string | null; + sender_is_technical?: boolean; + occurred_at?: string | null; + source?: string; + [key: string]: unknown; +}; + export type GroupGraphResponse = { schema?: { version?: string; @@ -527,6 +550,14 @@ export type GroupGraphResponse = { nodes?: number; edges?: number; }; + /** Server-side paging info: `total` matched the filters, `truncated` means the row cap cut some. */ + page?: { + limit?: number; + total?: number; + truncated?: boolean; + order?: string; + next_cursor?: string | null; + }; generated_from?: string[]; }; @@ -566,24 +597,49 @@ export type GroupGraphEdgeEvidenceResponse = { updated_at?: string | null; valid_at?: string | null; invalid_at?: string | null; + /** Fact row timestamp, i.e. when the relation was extracted. */ + extracted_at?: string | null; + first_observed_at?: string | null; + last_observed_at?: string | null; }; evidence_ids?: { memory_item_ids?: Array; event_ids?: Array; episode_ids?: Array; + observation_ids?: Array; }; evidence_counts?: { memory_items?: number; events?: number; episodes?: number; + observations?: number; + evidence_days?: number; [key: string]: number | undefined; }; + evidence_source?: string; + evidence_dates?: string[]; memory_items?: GroupGraphEdgeEvidenceEntity[]; events?: GroupGraphEdgeEvidenceEntity[]; episodes?: GroupGraphEdgeEvidenceEntity[]; + observations?: GroupGraphObservationEvidence[]; + /** Why the pipeline believes this edge: method, signals, policy, model rationale. No chat text. */ + judgement?: GroupGraphEdgeJudgement; [key: string]: unknown; }; +export type GroupGraphEdgeJudgement = { + extraction_method?: string; + signals?: Record; + policy?: string; + acceptance_status?: string; + reviewed_by?: string; + review_reason?: string; + /** The model's own one-line rationale (a paraphrase, never a message). */ + model_reason?: string; + day_count?: number; + strength?: number | null; +}; + export type GroupGraphQuery = { tenant_id: string; channel?: string; @@ -767,8 +823,16 @@ export type GroupGraphWindowExtractionRequest = { cursor_event_id?: number; dry_run?: boolean; include_llm?: boolean; + /** Per-window model timeout in seconds (server clamps to 5–180). */ + llm_timeout_seconds?: number; }; +/** + * `inline` waits for the model inside the request; `enqueue` only runs the rule + * layer and leaves one LLM job per window for the scheduler. + */ +export type GroupGraphLlmMode = "inline" | "enqueue"; + export type GroupGraphWindowCatchupRequest = { tenant_id: string; channel?: string; @@ -782,6 +846,8 @@ export type GroupGraphWindowCatchupRequest = { dry_run?: boolean; time_budget_seconds?: number; include_llm?: boolean; + llm_timeout_seconds?: number; + llm_mode?: GroupGraphLlmMode; }; export type GroupGraphWindowExtractionResponse = { @@ -848,6 +914,11 @@ export type GroupGraphWindowCatchupResponse = { more_remain?: boolean; stop_reason?: string; generated_from?: string[]; + /** Windows whose LLM pass was handed to the scheduler (enqueue mode). */ + llm_jobs_enqueued?: number; + llm_failures?: number; + signal_counts?: Record; + unresolved_targets?: number; [key: string]: unknown; }; diff --git a/frontend/src/pages/relationship-graph/RelationshipActionPanel.tsx b/frontend/src/pages/relationship-graph/RelationshipActionPanel.tsx index a1d87ac..38af2d6 100644 --- a/frontend/src/pages/relationship-graph/RelationshipActionPanel.tsx +++ b/frontend/src/pages/relationship-graph/RelationshipActionPanel.tsx @@ -116,6 +116,7 @@ export function RelationshipActionPanel(controller: RelationshipGraphController) 仅演练 当前游标 {windowExtractionCursor} + 单窗口抽取会等模型最多 45 秒;追平只跑规则,语义部分排成任务由调度进程每小时处理。 diff --git a/frontend/src/pages/relationship-graph/RelationshipDetailsAndDanger.tsx b/frontend/src/pages/relationship-graph/RelationshipDetailsAndDanger.tsx index d6dfea9..82e0f62 100644 --- a/frontend/src/pages/relationship-graph/RelationshipDetailsAndDanger.tsx +++ b/frontend/src/pages/relationship-graph/RelationshipDetailsAndDanger.tsx @@ -7,6 +7,8 @@ import { displayEdgeSource, displayEdgeTarget, evidenceCountsLabel, + evidenceObservedRange, + evidenceSourceLabel, formatConfidence, formatTimestamp, graphNodeLabel, @@ -19,6 +21,7 @@ import { edgeCanReturnToReview, evidenceQuality, extractionMethodLabel, + judgementSummary, counterpartEdges, firstMemoryItemId, formatAcceptanceScore, @@ -169,6 +172,7 @@ export function RelationshipUnavailableReset() { export function RelationshipDetailPanel(controller: RelationshipGraphController) { const { selection, + setSelection, selectedNode, selectedEdge, nodesById, @@ -185,6 +189,7 @@ export function RelationshipDetailPanel(controller: RelationshipGraphController) const replaceableEdges = selectedEdge ? counterpartEdges(selectedEdge, [...(graphEdges || []), ...(pendingEdges || [])]) : []; + const judgement = judgementSummary(evidence?.judgement); return (
@@ -193,6 +198,16 @@ export function RelationshipDetailPanel(controller: RelationshipGraphController)

详情

{selection ? (selection.kind === "node" ? "这个人" : "这条互动") : "点一个人或一条线"}

+ {selection && ( + + )} {!selection && (
@@ -359,10 +374,39 @@ export function RelationshipDetailPanel(controller: RelationshipGraphController) <>
证据来源
{evidenceCountsLabel(evidence)}
+ {evidenceSourceLabel(evidence.evidence_source) && ( +
证据类型
{evidenceSourceLabel(evidence.evidence_source)}
+ )}
审核状态
{acceptanceStatusLabel(evidence.edge?.acceptance_status)}
首次出现
{formatTimestamp(evidence.edge?.first_seen)}
最近出现
{formatTimestamp(evidence.edge?.last_seen)}
+ {evidenceObservedRange(evidence) && ( +
群消息时间
{evidenceObservedRange(evidence)}
+ )} + {(evidence.evidence_counts?.evidence_days ?? 0) > 0 && ( +
覆盖天数
{evidence.evidence_counts?.evidence_days}
+ )}
+ {judgement && ( +
+

怎么判定的

+
+
抽取方式
{judgement.method}
+ {judgement.signals.length > 0 && ( +
信号
{judgement.signals.join(",")}
+ )} + {judgement.policyText && ( +
通过依据
{judgement.policyText}
+ )} + {judgement.reviewerText && ( +
判定者
{judgement.reviewerText}
+ )} + {judgement.modelReason && ( +
模型理由
{judgement.modelReason} 模型自己的转述,不是聊天原文;主题词可能是模型归纳的(如把成员名归为组合名),按"群消息时间"去原聊天里核对。
+ )} +
+
+ )} )} diff --git a/frontend/src/pages/relationship-graph/RelationshipGraphPresentation.tsx b/frontend/src/pages/relationship-graph/RelationshipGraphPresentation.tsx index 07c202d..be2ca4a 100644 --- a/frontend/src/pages/relationship-graph/RelationshipGraphPresentation.tsx +++ b/frontend/src/pages/relationship-graph/RelationshipGraphPresentation.tsx @@ -4,6 +4,7 @@ import { DangerAction } from "../../components/DangerAction"; import { GRAPH_CANVAS_HEIGHT, GRAPH_CANVAS_WIDTH, + GRAPH_LANES, GRAPH_RANGE_PRESETS, GRAPH_VIEW_MODES, NODE_TYPE_LEGEND, @@ -18,14 +19,17 @@ import { edgeSeenOnDate, edgeStrokeWidth, extractionMethodLabel, + formatStrength, quadraticEdgePath, formatConfidence, isPendingReviewStatus, + isPersonNode, nodeIsFocused, nodeSecondaryLabel, nodeTypeLabel, nodeVisualType, graphNodeLabel, + populatedGraphLanes, readableRelationType, relationLabel, selectedEdgeTouchesNode, @@ -63,6 +67,7 @@ export type RelationshipGraphPresentationProps = Pick< | "applyPlaybackDate" | "playbackDates" | "pendingEdges" + | "pendingTotal" | "pendingReviewError" | "pendingReviewLoading" | "reviewing" @@ -185,13 +190,21 @@ export function RelationshipGraphPresentation(controller: RelationshipGraphPrese applyPlaybackDate, playbackDates, pendingEdges, + pendingTotal, pendingReviewError, pendingReviewLoading, reviewing, reviewEdge, } = controller; + const pendingShown = pendingEdges.length; + const pendingCountLabel = pendingTotal !== null && pendingTotal > pendingShown + ? `${pendingShown} / ${pendingTotal}` + : String(pendingShown); const canvas = useCanvasViewport(); const bundleOffsets = edgeBundleOffsets(visibleGraphEdges); + const populatedLanes = populatedGraphLanes(graphNodes); + const pageInfo = graph?.page; + const serverTruncated = Boolean(pageInfo?.truncated) && Number(pageInfo?.total || 0) > (graph?.edges?.length || 0); return ( <> @@ -280,7 +293,9 @@ export function RelationshipGraphPresentation(controller: RelationshipGraphPrese )} {!!graphNodes.length && (

- {graphSummaryText} 可在画布上点选、拖动画布平移、滚轮缩放;待审关系用虚线,线宽表示证据数,透明度表示新旧。 + {graphSummaryText} + {serverTruncated && ` 服务端共 ${pageInfo?.total} 条匹配关系,按互动强度只返回了前 ${graph?.edges?.length},收窄时间范围或关系类型可以看到其余部分。`} + {" "}可在画布上点选、拖动画布平移、滚轮缩放;待审关系用虚线,线宽表示证据消息数(对数),透明度表示最近一次证据的新旧。

)} {loading ? ( @@ -295,17 +310,37 @@ export function RelationshipGraphPresentation(controller: RelationshipGraphPrese viewBox={`0 0 ${GRAPH_CANVAS_WIDTH} ${GRAPH_CANVAS_HEIGHT}`} role="img" aria-label="群聊关系图" + tabIndex={-1} onPointerDown={canvas.onPointerDown} onPointerMove={canvas.onPointerMove} onPointerUp={canvas.onPointerUp} onPointerCancel={canvas.onPointerUp} + onClick={(event) => { + // Empty canvas: drop the focus. Node/edge clicks stop propagation, + // and a drag that ended here is a pan, not a deselect. + if (canvas.didPan()) return; + if ((event.target as Element).closest("[data-graph-item]")) return; + if (selection) setSelection(null); + }} + onKeyDown={(event) => { + if (event.key === "Escape" && selection) { + event.preventDefault(); + setSelection(null); + } + }} > {visibleGraphEdges.map((edge) => { const from = layout.get(displayEdgeSource(edge)); @@ -329,12 +364,13 @@ export function RelationshipGraphPresentation(controller: RelationshipGraphPrese onClick={(event) => { event.stopPropagation(); if (canvas.didPan()) return; - setSelection({ kind: "edge", item: edge }); + // Clicking the focused edge again releases the focus. + setSelection(selected ? null : { kind: "edge", item: edge }); }} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); - setSelection({ kind: "edge", item: edge }); + setSelection(selected ? null : { kind: "edge", item: edge }); } }} > @@ -376,12 +412,13 @@ export function RelationshipGraphPresentation(controller: RelationshipGraphPrese onClick={(event) => { event.stopPropagation(); if (canvas.didPan()) return; - setSelection({ kind: "node", item: node }); + // Clicking the focused node again releases the focus. + setSelection(selected ? null : { kind: "node", item: node }); }} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); - setSelection({ kind: "node", item: node }); + setSelection(selected ? null : { kind: "node", item: node }); } }} > @@ -410,9 +447,13 @@ export function RelationshipGraphPresentation(controller: RelationshipGraphPrese

审核

待审核队列

-

新抽的关系会自动通过。这里只剩还没转完或被退回的,最多 100 条。

+

+ 引用、@ 这类直接互动即时通过;模型推断的关系在跨天复现、同窗有 3 条以上消息支撑,或与已通过的关系相互印证(同一主题已有人在聊、两人已有直接互动)后由系统自动通过,14 天内都没印证的自动过期。这里是还在等印证的候选,人工点不点都不影响自动流程;最多显示 100 条。 +

- {pendingEdges.length} + + {pendingCountLabel} +
{pendingReviewError && ( @@ -497,6 +538,8 @@ export function RelationshipGraphPresentation(controller: RelationshipGraphPrese {acceptanceStatusLabel(edge.acceptance_status)} {readableRelationType(edge.label || edge.type)} · {extractionMethodLabel(edge.extraction_method)} · 置信度 {formatConfidence(edge.confidence)} · {edge.evidence_count ?? 0} 条证据 + {edge.strength !== undefined && edge.strength !== null ? ` · 强度 ${formatStrength(edge.strength)}` : ""} + {(edge.evidence_day_count ?? 0) > 1 ? ` · ${edge.evidence_day_count} 天` : ""} ))} diff --git a/frontend/src/pages/relationship-graph/RelationshipModules.test.tsx b/frontend/src/pages/relationship-graph/RelationshipModules.test.tsx index ad7b0ef..bcc6a26 100644 --- a/frontend/src/pages/relationship-graph/RelationshipModules.test.tsx +++ b/frontend/src/pages/relationship-graph/RelationshipModules.test.tsx @@ -14,6 +14,145 @@ import { RelationshipGraphPresentation, type RelationshipGraphPresentationProps, } from "./RelationshipGraphPresentation"; +import { + GRAPH_CANVAS_WIDTH, + GRAPH_LANES, + buildGraphLayout, + edgeRecencyOpacity, + edgeStrokeWidth, + evidenceCountsLabel, + evidenceObservedRange, + evidenceSourceLabel, + judgementSummary, + populatedGraphLanes, + sanitizeEdgeEvidence, + shouldKeepEdgeForMode, +} from "./graphModel"; + +function personNode(id: string, label: string): GroupGraphNode { + return { id, type: "person", label, display_label: label, acceptance_status: "accepted", confidence: 1 }; +} + +function edgeBetween(id: string, source: string, target: string, type: string, evidence = 1): GroupGraphEdge { + return { id, source, target, type, label: type, confidence: 0.9, acceptance_status: "accepted", evidence_count: evidence }; +} + +describe("relationship graph layout and encodings", () => { + it("spreads people across the canvas instead of one vertical lane", () => { + const people = Array.from({ length: 12 }, (_, index) => personNode(`p${index}`, `成员${index}`)); + const edges = [ + edgeBetween("e1", "p0", "p1", "replied_to", 40), + edgeBetween("e2", "p0", "p2", "replied_to", 12), + edgeBetween("e3", "p1", "p2", "addressed", 3), + edgeBetween("e4", "p3", "p4", "replied_to", 2), + edgeBetween("e5", "p5", "p6", "replied_to", 1), + ]; + + const layout = buildGraphLayout(people, edges); + const points = people.map((node) => layout.get(node.id)!); + + expect(points.every((point) => Number.isFinite(point.x) && Number.isFinite(point.y))).toBe(true); + const xs = points.map((point) => point.x); + expect(Math.max(...xs) - Math.min(...xs)).toBeGreaterThan(GRAPH_CANVAS_WIDTH * 0.35); + // Strongly connected pair ends up closer than an unconnected pair. + const distance = (a: string, b: string) => Math.hypot(layout.get(a)!.x - layout.get(b)!.x, layout.get(a)!.y - layout.get(b)!.y); + expect(distance("p0", "p1")).toBeLessThan(distance("p0", "p9")); + // Deterministic: the same input always yields the same picture. + expect(buildGraphLayout(people, edges).get("p7")).toEqual(layout.get("p7")); + }); + + it("keeps topics in their own lane only when topic nodes exist", () => { + const people = [personNode("p0", "洋白"), personNode("p1", "小海")]; + const topic: GroupGraphNode = { id: "t1", type: "topic", label: "并发", display_label: "并发", acceptance_status: "accepted", confidence: 0.8 }; + const edges = [edgeBetween("e1", "p0", "p1", "replied_to", 5), edgeBetween("e2", "p0", "t1", "mentioned", 2)]; + + expect(populatedGraphLanes(people)).toEqual(new Set()); + expect(populatedGraphLanes([...people, topic])).toEqual(new Set(["topic"])); + const layout = buildGraphLayout([...people, topic], edges); + expect(layout.get("t1")!.x).toBeGreaterThan(GRAPH_LANES.topic.x - 60); + expect(layout.get("p0")!.x).toBeLessThan(560); + }); + + it("folds same-window co-participation out of the default view only", () => { + const nodes = new Map([["p0", personNode("p0", "洋白")], ["p1", personNode("p1", "小海")]]); + const coParticipated = edgeBetween("e1", "p0", "p1", "co_participated"); + const reply = edgeBetween("e2", "p0", "p1", "replied_to"); + + expect(shouldKeepEdgeForMode(coParticipated, nodes, "readable", new Set())).toBe(false); + expect(shouldKeepEdgeForMode(reply, nodes, "readable", new Set())).toBe(true); + expect(shouldKeepEdgeForMode(coParticipated, nodes, "people", new Set())).toBe(true); + expect(shouldKeepEdgeForMode(coParticipated, nodes, "all", new Set())).toBe(true); + // Selecting a node brings its co-participation edges back. + expect(shouldKeepEdgeForMode(coParticipated, nodes, "readable", new Set(["p0"]))).toBe(true); + }); + + it("scales stroke width by evidence on a log scale and opacity by the last evidence date", () => { + const widths = [1, 4, 20, 100].map((evidence) => edgeStrokeWidth(edgeBetween("e", "a", "b", "replied_to", evidence))); + expect(widths[0]).toBeLessThan(widths[1]); + expect(widths[1]).toBeLessThan(widths[2]); + expect(widths[2]).toBeLessThan(widths[3]); + expect(widths[3]).toBeLessThanOrEqual(5.5); + + const today = new Date().toISOString().slice(0, 10); + const fresh = { ...edgeBetween("e", "a", "b", "replied_to"), last_seen: "2026-01-01T00:00:00", last_seen_date: today }; + const stale = { ...edgeBetween("e", "a", "b", "replied_to"), last_seen: "2026-01-01T00:00:00" }; + expect(edgeRecencyOpacity(fresh)).toBeGreaterThan(edgeRecencyOpacity(stale)); + }); +}); + +describe("relationship graph evidence labels", () => { + it("adds live group-message evidence to the counts label without exposing text", () => { + const evidence = sanitizeEdgeEvidence({ + edge: { + id: "fact:1", + type: "replied_to", + first_observed_at: "2026-08-09T01:02:03", + last_observed_at: "2026-09-04T04:05:06", + }, + evidence_counts: { memory_items: 1, events: 0, episodes: 0, observations: 12, evidence_days: 2 }, + evidence_source: "observation", + observations: [ + { id: 154604, sender_label: "小海", occurred_at: "2026-08-09T01:02:03", content: "private text" }, + ], + }); + + expect(evidenceCountsLabel(evidence)).toBe("记忆项 1 / 事件 0 / 片段 0 / 群消息 12"); + expect(evidenceSourceLabel(evidence.evidence_source)).toBe("实时群消息"); + expect(evidenceObservedRange(evidence)).toContain("→"); + expect(JSON.stringify(evidence)).not.toContain("private text"); + }); + + it("keeps the legacy label when no observation evidence exists", () => { + expect(evidenceCountsLabel({ evidence_counts: { memory_items: 2, events: 1, episodes: 1 } })).toBe( + "记忆项 2 / 事件 1 / 片段 1", + ); + expect(evidenceSourceLabel("memory_event")).toBe("导入事件"); + expect(evidenceSourceLabel(undefined)).toBe(""); + expect(evidenceObservedRange(null)).toBe(""); + }); + + it("explains how an edge was decided from the judgement block", () => { + const summary = judgementSummary({ + extraction_method: "llm", + signals: { llm: 10, quote: 0 }, + policy: "group_window_weak_signal", + acceptance_status: "accepted", + reviewed_by: "system/auto-review", + review_reason: "group_window_term_corroborated", + model_reason: "多次比较三位成员并评价其外貌", + day_count: 1, + }); + + expect(summary).not.toBeNull(); + expect(summary?.method).toBe("语义抽取"); + expect(summary?.signals).toEqual(["模型判定的支撑消息 10 条"]); + // The review reason (why it was finally accepted) wins over the initial policy. + expect(summary?.policyText).toBe("同一主题已有其他已通过的关系,系统印证通过"); + expect(summary?.reviewerText).toBe("系统印证扫描"); + expect(summary?.modelReason).toBe("多次比较三位成员并评价其外貌"); + expect(judgementSummary(undefined)).toBeNull(); + }); +}); describe("relationship graph modules", () => { it("keeps the unsupported destructive reset visibly unavailable", () => { @@ -145,6 +284,7 @@ describe("relationship graph modules", () => { applyPlaybackDate: vi.fn(), playbackDates: ["2026-08-25", "2026-08-26", "2026-08-27"], pendingEdges: [pendingEdge], + pendingTotal: 637, pendingReviewError: "", pendingReviewLoading: false, reviewing: false, @@ -155,7 +295,9 @@ describe("relationship graph modules", () => { const nodeList = screen.getByRole("region", { name: "这些人" }); const edgeList = screen.getByRole("region", { name: "这些互动" }); const queue = screen.getByRole("region", { name: "待审核队列" }); - expect(within(queue).getByText(/新抽的关系会自动通过/)).toBeInTheDocument(); + expect(within(queue).getByText(/相互印证.*自动通过/)).toBeInTheDocument(); + // The list is capped; the badge tells how many are really waiting. + expect(within(queue).getByText("1 / 637")).toBeInTheDocument(); const nodeRow = within(nodeList).getByRole("button", { name: /成员甲/ }); await user.click(nodeRow); @@ -173,6 +315,21 @@ describe("relationship graph modules", () => { fireEvent.click(canvas.querySelector("[data-graph-item='edge']") as SVGElement); expect(setSelection).toHaveBeenCalledWith({ kind: "edge", item: edge }); + // With something selected, the empty canvas, Esc and a second click on the + // selected item all release the focus; without a selection they are no-ops. + setSelection.mockClear(); + fireEvent.click(canvas); + expect(setSelection).not.toHaveBeenCalled(); + rerender(); + fireEvent.click(canvas); + expect(setSelection).toHaveBeenLastCalledWith(null); + fireEvent.keyDown(canvas, { key: "Escape" }); + expect(setSelection).toHaveBeenLastCalledWith(null); + setSelection.mockClear(); + fireEvent.click(canvas.querySelector("[data-graph-item='node']") as SVGElement); + expect(setSelection).toHaveBeenLastCalledWith(null); + rerender(); + await user.click(screen.getByRole("button", { name: "近14天" })); expect(applyGraphRangeDays).toHaveBeenCalledWith(14); expect(screen.getByRole("slider")).toBeInTheDocument(); @@ -220,8 +377,10 @@ describe("relationship graph modules", () => { acceptance_score: 0.62, acceptance_reason: "window_relation", }; + const setSelection = vi.fn(); const controller = { selection: { kind: "edge", item: edge }, + setSelection, selectedNode: null, selectedEdge: edge, nodesById: new Map([[node.id, node], [otherNode.id, otherNode]]), @@ -240,6 +399,9 @@ describe("relationship graph modules", () => { expect(screen.getByText("语义抽取")).toBeInTheDocument(); expect(screen.getByText("验收分")).toBeInTheDocument(); expect(screen.getByText("window_relation")).toBeInTheDocument(); + // The panel offers a way back to the whole graph without reloading. + await user.click(screen.getByRole("button", { name: "取消选中" })); + expect(setSelection).toHaveBeenCalledWith(null); await user.click(screen.getByRole("button", { name: "接受关系" })); const dialog = screen.getByRole("dialog", { name: "确认接受该关系" }); diff --git a/frontend/src/pages/relationship-graph/graphModel.tsx b/frontend/src/pages/relationship-graph/graphModel.tsx index 59ebc9d..26bf7b6 100644 --- a/frontend/src/pages/relationship-graph/graphModel.tsx +++ b/frontend/src/pages/relationship-graph/graphModel.tsx @@ -2,6 +2,7 @@ import type { GroupGraphEdge, GroupGraphEdgeEvidenceEntity, GroupGraphEdgeEvidenceResponse, + GroupGraphEdgeJudgement, GroupGraphNode, GroupGraphResponse, MemoryBackfillResponse, @@ -133,13 +134,16 @@ export const GRAPH_VIEW_BUDGETS: Record = [ - { value: "readable", label: "可读", description: "核心摘要,隐藏低信号关系和值节点" }, - { value: "core", label: "核心", description: "优先高连接关系" }, - { value: "people", label: "人物", description: "只看人物之间的关系" }, + { value: "readable", label: "可读", description: "按互动强度取前 N 条直接互动(引用、@、问答),隐藏同窗共现和值节点" }, + { value: "core", label: "核心", description: "优先高连接关系,按强度取前 N" }, + { value: "people", label: "人物", description: "只看人物之间的关系(含同窗共现)" }, { value: "topics", label: "主题", description: "人物与主题/项目/工具" }, { value: "all", label: "全部", description: "显示当前查询返回的关系" }, ]; +/** Same-window co-participation is folded out of the default view; it says little more than "both were online". */ +export const FOLDED_BY_DEFAULT_EDGE_TYPES = new Set(["co_participated"]); + export type NodeVisualType = "person" | "topic" | "product" | "tool" | "value" | "other"; export const NODE_TYPE_LEGEND: Array<{ type: NodeVisualType; label: string }> = [ @@ -214,19 +218,42 @@ export function isPendingReviewStatus(status?: string | null) { return normalized === "needs_review" || normalized === "candidate"; } +/** Evidence count (messages / observations behind the edge) on a log scale so 1, 4, 20 and 100 are all distinguishable. */ export function edgeStrokeWidth(edge: GroupGraphEdge) { - return Math.min(5, 1.15 + Number(edge.evidence_count || 0) * 0.32); + const evidence = Math.max(0, Number(edge.evidence_count || 0)); + const scaled = Math.log1p(evidence) / Math.log1p(60); + return Math.min(5.5, 0.9 + 4.6 * Math.min(1, scaled)); +} + +/** Most recent evidence date drives opacity; fall back to the row timestamp for legacy edges. */ +export function edgeLastSeenValue(edge: GroupGraphEdge) { + return edge.last_seen_date || edge.last_seen || null; } export function edgeRecencyOpacity(edge: GroupGraphEdge) { - if (!edge.last_seen) return 0.82; - const ageDays = (Date.now() - new Date(edge.last_seen).getTime()) / 86_400_000; + const lastSeen = edgeLastSeenValue(edge); + if (!lastSeen) return 0.82; + const ageDays = (Date.now() - new Date(lastSeen).getTime()) / 86_400_000; if (!Number.isFinite(ageDays) || ageDays <= 7) return 0.9; if (ageDays <= 14) return 0.68; if (ageDays <= 30) return 0.46; return 0.28; } +export function formatStrength(value?: number | null) { + if (value === undefined || value === null || Number.isNaN(Number(value))) return "-"; + return `${Math.round(Number(value) * 100)}%`; +} + +export function edgeStrengthValue(edge: GroupGraphEdge) { + const strength = Number(edge.strength); + if (Number.isFinite(strength) && strength > 0) return strength; + // Legacy edges without a stored strength: approximate from evidence and days. + const evidence = Number(edge.evidence_count || 0); + const days = Number(edge.evidence_day_count || (edge.evidence_dates || []).length || 0); + return 1 - Math.exp(-(evidence / 3 + Math.max(0, days - 1) / 4)); +} + export function restoreGraphSelection(selection: Selection, graph: GroupGraphResponse): Selection { if (!selection) return null; if (selection.kind === "edge") { @@ -411,10 +438,21 @@ export function isTechnicalLabel(value?: string | null) { return !normalized || isTechnicalUserId(normalized) || /^entity:\d+$/i.test(normalized); } +/** + * Only people carry opaque ids (wxid_..., openid) that must be hidden behind + * a nickname or "成员 N". A topic/tool/project label is the term itself: + * "cursor" or "uniapp" is a name, not an account id. + */ +function labelLooksTechnical(node: GroupGraphNode, value?: string | null) { + if (isPersonNode(node)) return isTechnicalLabel(value); + const normalized = String(value || "").trim(); + return !normalized || /^entity:\d+$/i.test(normalized); +} + export function nodeDisplayLabel(node?: GroupGraphNode | null) { if (!node) return ""; const candidates = [node.display_label, node.label, ...(node.aliases || [])]; - const friendly = candidates.find((value) => value && !isTechnicalLabel(value)); + const friendly = candidates.find((value) => value && !labelLooksTechnical(node, value)); if (friendly) return String(friendly); return shortTechnicalId(node.technical_label || node.label || node.id) || shortTechnicalId(node.id) || node.type || "?"; } @@ -453,15 +491,14 @@ export function safeNodeAliases(node?: GroupGraphNode | null) { export function graphLabelCandidate(node: GroupGraphNode) { if (nodeVisualType(node) === "value") return "值节点"; const candidates = [node.display_label, node.label, ...(node.aliases || [])]; - const friendly = candidates.find((value) => value && !isTechnicalLabel(value)); + const friendly = candidates.find((value) => value && !labelLooksTechnical(node, value)); if (friendly) return String(friendly).replace(/^user:/i, ""); return ""; } export function buildAnonymousGraphLabels(nodes: GroupGraphNode[]) { const technicalNodes = nodes - .filter((node) => !graphLabelCandidate(node)) - .filter((node) => nodeVisualType(node) !== "value") + .filter((node) => isPersonNode(node) && !graphLabelCandidate(node)) .sort((first, second) => ( String(first.technical_label || first.label || first.id).localeCompare(String(second.technical_label || second.label || second.id)) )); @@ -569,12 +606,16 @@ export function edgeImportance(edge: GroupGraphEdge, nodesById: Map = { - person: { x: 138, top: 82, bottom: 558 }, - core: { x: 360, top: 96, bottom: 528 }, - topic: { x: 604, top: 76, bottom: 540 }, - product: { x: 752, top: 92, bottom: 520 }, - value: { x: 806, top: 430, bottom: 570 }, - other: { x: 472, top: 132, bottom: 548 }, +/** Right-hand lanes for non-person nodes. People take the remaining width with a force layout. */ +export const GRAPH_LANES: Record<"topic" | "product" | "value" | "other", { x: number; top: number; bottom: number; label: string }> = { + topic: { x: 640, top: 76, bottom: 540, label: "主题 / 项目" }, + product: { x: 772, top: 92, bottom: 520, label: "产品 / 工具" }, + other: { x: 706, top: 120, bottom: 560, label: "其他" }, + value: { x: 836, top: 430, bottom: 570, label: "值" }, +}; + +export type GraphLaneKey = keyof typeof GRAPH_LANES; + +/** Minimum vertical distance between two nodes in the same side lane. */ +export const LANE_MIN_GAP = 26; +/** Horizontal offset of the second column when a lane holds more nodes than its height allows. */ +export const LANE_STAGGER_X = 30; + +export function laneKeyForNode(node: GroupGraphNode): GraphLaneKey | "person" { + if (isPersonNode(node)) return "person"; + const visualType = nodeVisualType(node); + if (visualType === "product" || visualType === "tool") return "product"; + if (visualType === "topic") return "topic"; + if (visualType === "value") return "value"; + return "other"; +} + +/** Deterministic LCG so the same graph always lands in the same layout. */ +function seededRandom(seed: number) { + let state = seed >>> 0; + return () => { + state = (state * 1664525 + 1013904223) >>> 0; + return state / 4294967296; }; +} + +/** + * Force-directed placement for the person subgraph inside a rectangle. + * Edges pull proportionally to log(evidence); nodes repel; a light gravity + * keeps the cluster centred. Runs synchronously in a few milliseconds for the + * ≤72 nodes the view budgets allow. + */ +export function forceLayoutPersons( + people: GroupGraphNode[], + edges: GroupGraphEdge[], + region: { left: number; right: number; top: number; bottom: number }, +) { + const points = new Map(); + const count = people.length; + if (!count) return points; + const width = region.right - region.left; + const height = region.bottom - region.top; + const centerX = region.left + width / 2; + const centerY = region.top + height / 2; + if (count === 1) { + points.set(people[0].id, { x: centerX, y: centerY }); + return points; + } + const index = new Map(people.map((node, position) => [node.id, position])); + const random = seededRandom(20260916 + count); + const xs = new Float64Array(count); + const ys = new Float64Array(count); + const degree = buildDegreeMap(edges); + // Start on a ring ordered by degree so hubs begin near the middle. + const ordered = [...people].sort((first, second) => (degree.get(second.id) || 0) - (degree.get(first.id) || 0)); + ordered.forEach((node, position) => { + const slot = index.get(node.id) ?? position; + const angle = (position / count) * Math.PI * 2; + const radius = Math.min(width, height) * (0.08 + 0.34 * (position / count)) * (0.85 + 0.3 * random()); + xs[slot] = centerX + radius * Math.cos(angle); + ys[slot] = centerY + radius * Math.sin(angle); + }); + let maxEvidence = 1; + for (const edge of edges) maxEvidence = Math.max(maxEvidence, Number(edge.evidence_count || 0)); + const springs = edges + .map((edge) => ({ + a: index.get(displayEdgeSource(edge)) ?? -1, + b: index.get(displayEdgeTarget(edge)) ?? -1, + weight: Math.log1p(Number(edge.evidence_count || 0)) / Math.log1p(maxEvidence), + })) + .filter((spring) => spring.a >= 0 && spring.b >= 0 && spring.a !== spring.b); + const ideal = Math.sqrt((width * height) / count) * 1.05; + const minDistance = 38; + let temperature = width / 6; + const dx = new Float64Array(count); + const dy = new Float64Array(count); + for (let iteration = 0; iteration < 260; iteration += 1) { + dx.fill(0); + dy.fill(0); + for (let i = 0; i < count; i += 1) { + for (let j = i + 1; j < count; j += 1) { + let deltaX = xs[i] - xs[j]; + let deltaY = ys[i] - ys[j]; + let squared = deltaX * deltaX + deltaY * deltaY; + if (squared < 0.01) { + deltaX = random() - 0.5; + deltaY = random() - 0.5; + squared = deltaX * deltaX + deltaY * deltaY; + } + const distance = Math.sqrt(squared); + let force = (ideal * ideal) / distance; + if (distance < minDistance) force += (minDistance - distance) * 3; + const fx = (deltaX / distance) * force; + const fy = (deltaY / distance) * force; + dx[i] += fx; + dy[i] += fy; + dx[j] -= fx; + dy[j] -= fy; + } + } + for (const spring of springs) { + const deltaX = xs[spring.a] - xs[spring.b]; + const deltaY = ys[spring.a] - ys[spring.b]; + const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY) + 0.01; + const force = ((distance * distance) / ideal) * (0.25 + 1.1 * spring.weight); + const fx = (deltaX / distance) * force; + const fy = (deltaY / distance) * force; + dx[spring.a] -= fx; + dy[spring.a] -= fy; + dx[spring.b] += fx; + dy[spring.b] += fy; + } + for (let i = 0; i < count; i += 1) { + dx[i] += (centerX - xs[i]) * 0.012; + dy[i] += (centerY - ys[i]) * 0.012; + const magnitude = Math.sqrt(dx[i] * dx[i] + dy[i] * dy[i]) || 1; + const step = Math.min(magnitude, temperature); + xs[i] = Math.max(region.left, Math.min(region.right, xs[i] + (dx[i] / magnitude) * step)); + ys[i] = Math.max(region.top, Math.min(region.bottom, ys[i] + (dy[i] / magnitude) * step)); + } + temperature = Math.max(0.6, temperature * 0.985); + } + people.forEach((node, position) => points.set(node.id, { x: xs[position], y: ys[position] })); + return points; +} + +export function buildGraphLayout(nodes: GroupGraphNode[], edges: GroupGraphEdge[] = []) { const degree = buildDegreeMap(edges); const nodesById = new Map(nodes.map((node) => [node.id, node])); const sortedNodes = sortNodesByImportance(nodes, degree); - const topCoreIds = new Set(sortedNodes.filter((node) => !isPersonNode(node)).slice(0, Math.min(6, sortedNodes.length)).map((node) => node.id)); - const laneNodes = new Map([ + const laneNodes = new Map([ ["person", []], - ["core", []], ["topic", []], ["product", []], - ["value", []], ["other", []], + ["value", []], ]); - for (const node of sortedNodes) { - const visualType = nodeVisualType(node); - if (isPersonNode(node)) { - laneNodes.get("person")?.push(node); - } else if (["product", "tool"].includes(visualType)) { - laneNodes.get("product")?.push(node); - } else if (visualType === "topic") { - laneNodes.get("topic")?.push(node); - } else if (topCoreIds.has(node.id) && visualType !== "value") { - laneNodes.get("core")?.push(node); - } else if (visualType === "value") { - laneNodes.get("value")?.push(node); - } else { - laneNodes.get("other")?.push(node); - } + laneNodes.get(laneKeyForNode(node))?.push(node); } - const layout = new Map(); - const personItems = laneNodes.get("person") || []; - const personSlots = centerSlotOrder(personItems.length); - personItems.forEach((node, index) => { - const lane = lanes.person; - const slot = personSlots[index] ?? index; - layout.set(node.id, { - x: lane.x + Math.min(36, (degree.get(node.id) || 0) * 2.4), - y: laneY(slot, personItems.length, lane.top, lane.bottom), - }); - }); + const hasSideLanes = (["topic", "product", "other", "value"] as GraphLaneKey[]).some( + (lane) => (laneNodes.get(lane) || []).length > 0, + ); + const personRegion = hasSideLanes + ? { left: 60, right: 540, top: 72, bottom: GRAPH_CANVAS_HEIGHT - 40 } + : { left: 60, right: GRAPH_CANVAS_WIDTH - 60, top: 72, bottom: GRAPH_CANVAS_HEIGHT - 40 }; + const people = laneNodes.get("person") || []; + const personEdges = edges.filter((edge) => ( + isPersonNode(nodesById.get(displayEdgeSource(edge))) && isPersonNode(nodesById.get(displayEdgeTarget(edge))) + )); + const layout = forceLayoutPersons(people, personEdges, personRegion); for (const [laneKey, laneItems] of laneNodes.entries()) { - if (laneKey === "person") continue; - const lane = lanes[laneKey] || lanes.other; + if (laneKey === "person" || !laneItems.length) continue; + const lane = GRAPH_LANES[laneKey]; const ordered = [...laneItems].sort((first, second) => { const firstAnchor = connectedPersonAnchor(first, edges, layout, degree, nodesById); const secondAnchor = connectedPersonAnchor(second, edges, layout, degree, nodesById); @@ -787,14 +940,30 @@ export function buildGraphLayout(nodes: GroupGraphNode[], edges: GroupGraphEdge[ return importanceDiff || nodeDisplayLabel(first).localeCompare(nodeDisplayLabel(second)); }); const count = Math.max(ordered.length, 1); - ordered.forEach((node, index) => { + // Anchoring a term next to the people who use it pulls many terms toward + // the same hub; keep at least LANE_MIN_GAP between neighbours, and when the + // lane is too full for that, spread evenly over two staggered columns. + const dense = ordered.length * LANE_MIN_GAP > lane.bottom - lane.top; + const ys = ordered.map((node, position) => { + const spreadY = laneY(position, count, lane.top, lane.bottom); + if (dense) return spreadY; const anchor = connectedPersonAnchor(node, edges, layout, degree, nodesById); - const spreadY = laneY(index, count, lane.top, lane.bottom); - const y = anchor === undefined ? spreadY : Math.max(lane.top, Math.min(lane.bottom, anchor * 0.7 + spreadY * 0.3)); + return anchor === undefined ? spreadY : Math.max(lane.top, Math.min(lane.bottom, anchor * 0.6 + spreadY * 0.4)); + }); + if (!dense) { + for (let index = 1; index < ys.length; index += 1) ys[index] = Math.max(ys[index], ys[index - 1] + LANE_MIN_GAP); + const overflow = ys[ys.length - 1] - lane.bottom; + if (overflow > 0) { + for (let index = 0; index < ys.length; index += 1) ys[index] -= overflow; + for (let index = ys.length - 2; index >= 0; index -= 1) ys[index] = Math.min(ys[index], ys[index + 1] - LANE_MIN_GAP); + } + } + ordered.forEach((node, position) => { const xPull = Math.min(44, (degree.get(node.id) || 0) * 4); + const stagger = dense && position % 2 === 1 ? LANE_STAGGER_X : 0; layout.set(node.id, { - x: Math.max(56, Math.min(GRAPH_CANVAS_WIDTH - 56, lane.x - (laneKey === "topic" || laneKey === "product" ? xPull : 0))), - y, + x: Math.max(56, Math.min(GRAPH_CANVAS_WIDTH - 56, lane.x - (laneKey === "topic" || laneKey === "product" ? xPull : 0) + stagger)), + y: ys[position], }); }); } @@ -802,6 +971,16 @@ export function buildGraphLayout(nodes: GroupGraphNode[], edges: GroupGraphEdge[ return layout; } +/** Which side lanes actually hold nodes, so the canvas only labels populated columns. */ +export function populatedGraphLanes(nodes: GroupGraphNode[]) { + const lanes = new Set(); + for (const node of nodes) { + const lane = laneKeyForNode(node); + if (lane !== "person") lanes.add(lane); + } + return lanes; +} + export function estimatedLabelSize(text: string) { const width = Array.from(text).reduce((sum, char) => sum + (char.charCodeAt(0) > 255 ? 13 : 7.4), 14); return { width: Math.min(148, Math.max(42, width)), height: 18 }; @@ -841,6 +1020,30 @@ export function labelCandidates(point: GraphPoint, text: string) { )); } +/** + * Candidate order per node kind. Side-lane nodes sit in tight columns, so + * their labels go sideways, away from the neighbouring lane: topics point + * left toward the people, products/tools point right toward the canvas edge. + */ +export function labelCandidatesForNode(node: GroupGraphNode, point: GraphPoint, text: string) { + const candidates = labelCandidates(point, text); + const lane = laneKeyForNode(node); + if (lane === "person" || lane === "value") return candidates; + const preferred: Array<"start" | "end" | "middle"> = lane === "topic" ? ["end", "start"] : ["start", "end"]; + return [...candidates].sort((first, second) => { + const rank = (anchor: "start" | "end" | "middle") => { + const index = preferred.indexOf(anchor); + return index === -1 ? preferred.length : index; + }; + return rank(first.anchor) - rank(second.anchor); + }); +} + +/** Footprint of a node circle, so labels are not painted over neighbouring nodes. */ +function nodeFootprint(point: GraphPoint) { + return { left: point.x - 11, right: point.x + 11, top: point.y - 11, bottom: point.y + 11 }; +} + export function buildVisibleLabels( nodes: GroupGraphNode[], edges: GroupGraphEdge[], @@ -857,6 +1060,12 @@ export function buildVisibleLabels( requiredIds.add(displayEdgeSource(selectedEdge)); requiredIds.add(displayEdgeTarget(selectedEdge)); } + // A topic/tool dot without its name says nothing, and lane nodes sit in a + // column where labels rarely collide, so they are labelled regardless of budget. + for (const node of nodes) { + const lane = laneKeyForNode(node); + if (lane !== "person" && lane !== "value") requiredIds.add(node.id); + } const sorted = [...nodes].sort((first, second) => { const firstRequired = requiredIds.has(first.id); @@ -865,7 +1074,14 @@ export function buildVisibleLabels( const scoreDiff = nodeImportance(second, degree) - nodeImportance(first, degree); return scoreDiff || graphNodeLabel(first, anonymousLabels).localeCompare(graphNodeLabel(second, anonymousLabels)); }); - const placedBoxes: Array<{ left: number; right: number; top: number; bottom: number }> = []; + // Other nodes' circles count as occupied from the start: a label that + // covers a neighbouring dot is worse than a label placed on its other side. + const footprints = new Map(); + for (const node of nodes) { + const point = layout.get(node.id); + if (point) footprints.set(node.id, nodeFootprint(point)); + } + const placedBoxes: Array<{ left: number; right: number; top: number; bottom: number }> = [...footprints.values()]; const labels = new Map(); for (const node of sorted) { @@ -875,8 +1091,9 @@ export function buildVisibleLabels( const point = layout.get(node.id); if (!point) continue; const text = graphNodeLabel(node, anonymousLabels); - const candidates = labelCandidates(point, text); - const candidate = candidates.find((item) => !placedBoxes.some((box) => boxesOverlap(item.box, box))) + const candidates = labelCandidatesForNode(node, point, text); + const ownFootprint = footprints.get(node.id); + const candidate = candidates.find((item) => !placedBoxes.some((box) => box !== ownFootprint && boxesOverlap(item.box, box))) || (required ? candidates[0] : undefined); if (!candidate) continue; labels.set(node.id, { nodeId: node.id, text, x: candidate.x, y: candidate.y, anchor: candidate.anchor }); @@ -933,7 +1150,72 @@ export function sanitizeEdgeEvidence(payload: GroupGraphEdgeEvidenceResponse): G export function evidenceCountsLabel(evidence?: GroupGraphEdgeEvidenceResponse | null) { const counts = evidence?.evidence_counts || {}; - return `记忆项 ${counts.memory_items ?? 0} / 事件 ${counts.events ?? 0} / 片段 ${counts.episodes ?? 0}`; + const base = `记忆项 ${counts.memory_items ?? 0} / 事件 ${counts.events ?? 0} / 片段 ${counts.episodes ?? 0}`; + const observations = counts.observations ?? 0; + return observations > 0 ? `${base} / 群消息 ${observations}` : base; +} + +export function evidenceSourceLabel(value?: string | null) { + const normalized = String(value || "").trim().toLowerCase(); + if (normalized === "observation") return "实时群消息"; + if (normalized === "mixed") return "导入事件 + 实时群消息"; + if (normalized === "memory_event") return "导入事件"; + return ""; +} + +export function evidenceObservedRange(evidence?: GroupGraphEdgeEvidenceResponse | null) { + const first = evidence?.edge?.first_observed_at; + const last = evidence?.edge?.last_observed_at; + if (!first && !last) return ""; + if (first && last && first !== last) return `${formatTimestamp(first)} → ${formatTimestamp(last)}`; + return formatTimestamp(first || last); +} + +const SIGNAL_LABELS: Record = { + quote: "引用回复", + mention: "@ 提及", + prefix_reply: "前缀回复", + co_participation: "同窗共现", + llm: "模型判定的支撑消息", +}; + +const POLICY_LABELS: Record = { + group_window_direct_signal: "有引用 / @ 这类直接互动,立即通过", + group_window_llm_multi_day: "模型关系在不止一天里出现,自动通过", + group_window_llm_repeated_evidence: "同一窗口内有 3 条以上消息支撑,自动通过", + group_window_repeated_weak_signal: "弱信号跨天重复出现,自动通过", + group_window_weak_signal: "只有单日弱信号,等待印证", + group_window_term_corroborated: "同一主题已有其他已通过的关系,系统印证通过", + group_window_pair_corroborated: "两人之间已有其他已通过的互动,系统印证通过", + group_window_auto_accept: "旧版策略:全部自动通过", + group_window_relation: "自动通过已关闭,等待人工", +}; + +/** Human-readable breakdown of why an edge exists; empty when the payload has nothing to say. */ +export function judgementSummary(judgement?: GroupGraphEdgeJudgement | null) { + if (!judgement) return null; + const signals = Object.entries(judgement.signals || {}) + .filter(([, count]) => Number(count) > 0) + .map(([key, count]) => `${SIGNAL_LABELS[key] || key} ${count} 条`); + const policyKey = String(judgement.policy || "").trim(); + const reviewKey = String(judgement.review_reason || "").trim(); + const policyText = POLICY_LABELS[reviewKey] || POLICY_LABELS[policyKey] || policyKey || ""; + const reviewer = String(judgement.reviewed_by || "").trim(); + const reviewerText = !reviewer + ? "" + : reviewer === "system/auto-review" + ? "系统印证扫描" + : reviewer === "system/auto" + ? "策略自动通过" + : reviewer; + return { + method: extractionMethodLabel(judgement.extraction_method), + signals, + policyText, + reviewerText, + modelReason: String(judgement.model_reason || "").trim(), + dayCount: Number(judgement.day_count || 0), + }; } export function evidenceRecordMeta(record: GroupGraphEdgeEvidenceEntity) { diff --git a/frontend/src/pages/relationship-graph/useRelationshipGraphController.ts b/frontend/src/pages/relationship-graph/useRelationshipGraphController.ts index ee19132..e45c673 100644 --- a/frontend/src/pages/relationship-graph/useRelationshipGraphController.ts +++ b/frontend/src/pages/relationship-graph/useRelationshipGraphController.ts @@ -89,6 +89,11 @@ export function useRelationshipGraphController() { const [windowCatchupMaxWindows, setWindowCatchupMaxWindows] = useState("20"); const [actionPanelOpen, setActionPanelOpen] = useState(false); const extractionTimeBudgetSeconds = 60; + // The console talks to the API through a proxy with a ~60s read timeout, so a + // single-window run gives the model 45s; multi-window catch-up only runs the + // rule layer inline and leaves one LLM job per window for the scheduler. + const windowLlmTimeoutSeconds = 45; + const catchupLlmMode = "enqueue" as const; const currentGraphScopeKey = selectedGroupIsVerified ? [config.tenantId.trim(), channel.trim(), sourceKey.trim(), selectedGroupId].join("\u001f") : ""; @@ -122,6 +127,8 @@ export function useRelationshipGraphController() { const [windowStatsStatus, setWindowStatsStatus] = useState("选择已验证群聊后可查看窗口关系统计。"); const [pendingEdges, setPendingEdges] = useState([]); const [pendingNodes, setPendingNodes] = useState([]); + // Server-side total of pending relations; the list itself is capped at 100. + const [pendingTotal, setPendingTotal] = useState(null); const [pendingReviewLoading, setPendingReviewLoading] = useState(false); const selectedNode = selection?.kind === "node" ? selection.item : null; const selectedEdge = selection?.kind === "edge" ? selection.item : null; @@ -200,9 +207,10 @@ export function useRelationshipGraphController() { [nodes, pendingNodes], ); const graphStateMessage = graphError || projectedGraphStateMessage; - const pendingReviewCount = pendingEdges.length - || Number(windowStatsAcceptance.needs_review || 0) - + Number(windowStatsAcceptance.candidate || 0); + const pendingReviewCount = pendingTotal + ?? (pendingEdges.length + || Number(windowStatsAcceptance.needs_review || 0) + + Number(windowStatsAcceptance.candidate || 0)); const scopeQuery = useMemo(() => { const tenantId = config.tenantId.trim(); @@ -438,6 +446,7 @@ export function useRelationshipGraphController() { if (!tenantId || !selectedGroupIsVerified) { setPendingEdges([]); setPendingNodes([]); + setPendingTotal(null); setPendingReviewError(""); setPendingReviewLoading(false); return; @@ -459,11 +468,14 @@ export function useRelationshipGraphController() { if (activeGraphScopeKeyRef.current !== requestScopeKey) return; setPendingEdges(result.edges || []); setPendingNodes(result.nodes || []); + const serverTotal = Number(result.page?.total); + setPendingTotal(Number.isFinite(serverTotal) && serverTotal >= (result.edges || []).length ? serverTotal : null); setPendingReviewError(""); } catch (err) { if (activeGraphScopeKeyRef.current !== requestScopeKey) return; setPendingEdges([]); setPendingNodes([]); + setPendingTotal(null); setPendingReviewError( `待审核关系加载失败:${ err instanceof ApiError || err instanceof Error ? err.message : "pending review request failed" @@ -892,6 +904,7 @@ export function useRelationshipGraphController() { cursor_event_id: windowExtractionCursor, dry_run: windowExtractionDryRun, include_llm: true, + llm_timeout_seconds: windowLlmTimeoutSeconds, }; const result = await apiRequest>>( config, @@ -998,6 +1011,7 @@ export function useRelationshipGraphController() { dry_run: windowExtractionDryRun, time_budget_seconds: extractionTimeBudgetSeconds, include_llm: true, + llm_mode: catchupLlmMode, }; const result = await apiRequest>>( config, @@ -1146,6 +1160,7 @@ export function useRelationshipGraphController() { dry_run: false, time_budget_seconds: extractionTimeBudgetSeconds, include_llm: true, + llm_mode: catchupLlmMode, }), }, }, @@ -1157,6 +1172,7 @@ export function useRelationshipGraphController() { windows_processed: result.windows_processed ?? 0, more_remain: result.more_remain, stop_reason: result.stop_reason, + llm_jobs_enqueued: result.llm_jobs_enqueued ?? 0, }); } catch (err) { catchups.push({ @@ -1220,6 +1236,7 @@ export function useRelationshipGraphController() { setEvidence(null); setPendingEdges([]); setPendingNodes([]); + setPendingTotal(null); setGraphError(""); setPendingReviewError(""); setReviewError(""); @@ -1354,6 +1371,7 @@ export function useRelationshipGraphController() { windowStatsAcceptance, pendingReviewCount, pendingEdges, + pendingTotal, pendingReviewLoading, governanceStatus, governanceStatusText, diff --git a/frontend/src/pages/relationship-graph/useRelationshipGraphProjection.ts b/frontend/src/pages/relationship-graph/useRelationshipGraphProjection.ts index d9f9eea..3469700 100644 --- a/frontend/src/pages/relationship-graph/useRelationshipGraphProjection.ts +++ b/frontend/src/pages/relationship-graph/useRelationshipGraphProjection.ts @@ -12,6 +12,7 @@ import type { ConsoleConfig } from "../../state/console-config"; import { DEFAULT_EDGE_TYPES, DEFAULT_NODE_TYPES, + FOLDED_BY_DEFAULT_EDGE_TYPES, GRAPH_VIEW_BUDGETS, buildAnonymousGraphLabels, buildGraphLayout, @@ -155,21 +156,32 @@ export function useRelationshipGraphProjection({ ), [filteredNodeIds, forcedGraphNodeIds, modeFilteredEdges, nodesById], ); - const graphNodes = useMemo( + const selectedGraphNodes = useMemo( () => selectGraphNodes(modeFilteredNodes, rankedGraphEdges, graphBudget.nodes, forcedGraphNodeIds), [forcedGraphNodeIds, graphBudget.nodes, modeFilteredNodes, rankedGraphEdges], ); - const graphNodeIds = useMemo(() => new Set(graphNodes.map((node) => node.id)), [graphNodes]); + const selectedGraphNodeIds = useMemo(() => new Set(selectedGraphNodes.map((node) => node.id)), [selectedGraphNodes]); const graphEdges = useMemo( - () => rankedGraphEdges.filter((edge) => graphNodeIds.has(displayEdgeSource(edge)) && graphNodeIds.has(displayEdgeTarget(edge))), - [graphNodeIds, rankedGraphEdges], + () => rankedGraphEdges.filter((edge) => selectedGraphNodeIds.has(displayEdgeSource(edge)) && selectedGraphNodeIds.has(displayEdgeTarget(edge))), + [selectedGraphNodeIds, rankedGraphEdges], ); - const layout = useMemo(() => buildGraphLayout(graphNodes, graphEdges), [graphEdges, graphNodes]); + const budgetedGraphEdges = useMemo(() => graphEdges.slice(0, graphBudget.edges), [graphBudget.edges, graphEdges]); + // Outside 全部, a node whose every edge fell under the edge budget would render + // as an unexplained isolated dot; drop it unless the user pinned it. + const graphNodes = useMemo(() => { + if (graphViewMode === "all") return selectedGraphNodes; + const connected = new Set(); + for (const edge of budgetedGraphEdges) { + connected.add(displayEdgeSource(edge)); + connected.add(displayEdgeTarget(edge)); + } + return selectedGraphNodes.filter((node) => connected.has(node.id) || forcedGraphNodeIds.has(node.id)); + }, [budgetedGraphEdges, forcedGraphNodeIds, graphViewMode, selectedGraphNodes]); + const layout = useMemo(() => buildGraphLayout(graphNodes, budgetedGraphEdges), [budgetedGraphEdges, graphNodes]); const visibleGraphEdges = useMemo( - () => graphEdges - .filter((edge) => layout.has(displayEdgeSource(edge)) && layout.has(displayEdgeTarget(edge))) - .slice(0, graphBudget.edges), - [graphBudget.edges, graphEdges, layout], + () => budgetedGraphEdges + .filter((edge) => layout.has(displayEdgeSource(edge)) && layout.has(displayEdgeTarget(edge))), + [budgetedGraphEdges, layout], ); const visibleLabels = useMemo( () => buildVisibleLabels( @@ -189,7 +201,7 @@ export function useRelationshipGraphProjection({ const modeHiddenEdgeCount = Math.max(0, visibleEdges.length - rankedGraphEdges.length); const graphSummaryText = graphViewMode === "all" ? `现在能看到 ${graphNodes.length} 个人或主题,${visibleGraphEdges.length} 条互动。` - : `先看最常一起出现的 ${graphNodes.length} 个人或主题、${visibleGraphEdges.length} 条互动;其余 ${modeHiddenNodeCount + hiddenGraphNodeCount} 人 / ${modeHiddenEdgeCount + hiddenGraphEdgeCount} 条被收进摘要。`; + : `按互动强度先看前 ${graphNodes.length} 个人或主题、${visibleGraphEdges.length} 条互动;其余 ${modeHiddenNodeCount + hiddenGraphNodeCount} 人 / ${modeHiddenEdgeCount + hiddenGraphEdgeCount} 条(含默认折叠的同窗共现)在"人物"或"全部"里。`; const selectedDateStatus = useMemo( () => dateRows.find((row) => row.date === targetDate), [dateRows, targetDate], @@ -262,6 +274,11 @@ export function useRelationshipGraphProjection({ } return ids; }, [selectedNode, visibleGraphEdges]); + const foldedEdgeCount = useMemo( + () => filteredEdges.filter((edge) => FOLDED_BY_DEFAULT_EDGE_TYPES.has(String(edge.label || edge.type || "").toLowerCase())).length, + [filteredEdges], + ); + const onlyFoldedEdges = filteredEdges.length > 0 && foldedEdgeCount === filteredEdges.length; const graphStateMessage = loading ? "正在加载关系图,请稍候。" : graph === null @@ -270,6 +287,8 @@ export function useRelationshipGraphProjection({ ? "当前范围没有关系图数据。可点“显示全部关系”、放宽审核状态,或打开抽取控制同步近 7 天。" : !filteredNodes.length && (nodeSearch.trim() || edgeSearch.trim()) ? "当前搜索没有匹配节点或关系;请调整节点/关系关键词。" + : !graphNodes.length && graphViewMode === "readable" && onlyFoldedEdges + ? `当前只有 ${foldedEdgeCount} 条“同一时段一起聊过”这类弱关系,默认视图已折叠。切到“人物”或“全部”可以查看;运行一次新的抽取后会出现引用回复、@ 等直接互动。` : !graphNodes.length ? "当前视图模式隐藏了所有可见节点;可切换到“全部”或调整搜索条件。" : ""; diff --git a/frontend/src/styles/pages/relationship-graph.css b/frontend/src/styles/pages/relationship-graph.css index 472ecc8..3a6abfc 100644 --- a/frontend/src/styles/pages/relationship-graph.css +++ b/frontend/src/styles/pages/relationship-graph.css @@ -576,6 +576,10 @@ font-size: var(--font-size-xs); font-weight: 800; text-align: center; + /* "shown / total" must stay on one line next to the panel copy. */ + flex-shrink: 0; + align-self: flex-start; + white-space: nowrap; } .relationship-queue-item { @@ -980,6 +984,26 @@ font-weight: 700; } +.relationship-judgement { + margin-top: var(--space-3); + padding: var(--space-2-5) var(--space-3); + border-radius: var(--radius); + border: 1px dashed var(--line-light); + background: var(--color-paper-bright); +} + +.relationship-judgement h4 { + margin: 0 0 var(--space-2); + font-size: var(--font-size-sm); + font-weight: 800; +} + +.relationship-judgement small { + display: block; + margin-top: var(--space-1); + font-weight: 400; +} + .relationship-evidence-records { display: grid; gap: var(--space-3); diff --git a/plugins/memory/plugin.py b/plugins/memory/plugin.py index 6532294..30cd146 100644 --- a/plugins/memory/plugin.py +++ b/plugins/memory/plugin.py @@ -231,12 +231,21 @@ async def _group_graph_auto_extract_loop(self) -> None: getattr(settings, "memory_group_graph_auto_extract_llm_enabled", True) ), sync_missing_history=bool( - getattr(settings, "memory_group_graph_auto_extract_sync_enabled", True) + getattr(settings, "memory_group_graph_auto_extract_sync_enabled", False) ), sync_max_messages=int( getattr(settings, "memory_group_graph_auto_extract_sync_max_messages", 200) or 200 ), + llm_jobs_per_tick=int( + getattr(settings, "memory_group_graph_llm_jobs_per_tick", 6) or 0 + ), + llm_timeout_seconds=int( + getattr(settings, "memory_group_graph_llm_timeout_seconds", 60) or 60 + ), + auto_review_batch=int( + getattr(settings, "memory_group_graph_auto_review_batch", 200) or 0 + ), ) except asyncio.CancelledError: raise diff --git a/plugins/memory/router.py b/plugins/memory/router.py index fb7a53a..a56d400 100644 --- a/plugins/memory/router.py +++ b/plugins/memory/router.py @@ -495,9 +495,13 @@ class MemoryWindowRelationshipCatchupRequest(StrictRequestModel): dry_run: bool = False time_budget_seconds: int | None = None include_llm: bool = True + llm_timeout_seconds: int | None = None + # "inline" calls the model during the request; "enqueue" records one LLM job + # per window for the scheduler, so the request only pays for the rule layer. + llm_mode: str | None = None - def extraction_controls(self) -> dict[str, int | bool]: - return { + def extraction_controls(self) -> dict[str, int | bool | str]: + controls: dict[str, int | bool | str] = { "window_size": max(10, min(int(self.window_size or 50), 100)), "max_windows_per_run": max(1, min(int(self.max_windows_per_run or 20), 100)), "cursor_event_id": max(0, int(self.cursor_event_id or 0)), @@ -505,6 +509,13 @@ def extraction_controls(self) -> dict[str, int | bool]: "time_budget_seconds": max(1, min(int(self.time_budget_seconds or 60), 180)), "include_llm": bool(self.include_llm), } + if self.llm_timeout_seconds is not None: + # Per-window model timeout; the budget only bounds how many windows run. + controls["llm_timeout_seconds"] = max(5, min(int(self.llm_timeout_seconds), 180)) + llm_mode = str(self.llm_mode or "").strip().lower() + if llm_mode in {"inline", "enqueue"}: + controls["llm_mode"] = llm_mode + return controls class MemoryEdgeAcceptanceReviewRequest(StrictRequestModel): diff --git a/plugins/memory/store.py b/plugins/memory/store.py index bf1d8df..aaf799b 100644 --- a/plugins/memory/store.py +++ b/plugins/memory/store.py @@ -133,6 +133,9 @@ AUTO_SOURCE_TYPES = {"auto", "explicit_user", "backfill"} LLM_GROUP_WINDOW_SOURCE_TYPE = "llm_group_window" DETERMINISTIC_GROUP_WINDOW_SOURCE_TYPE = "deterministic_group_window" +GROUP_WINDOW_RELATION_SOURCE_TYPES = frozenset( + {LLM_GROUP_WINDOW_SOURCE_TYPE, DETERMINISTIC_GROUP_WINDOW_SOURCE_TYPE} +) PROFILE_ENRICHMENT_SOURCE_TYPE = "profile_enrichment" PROFILE_ENRICHMENT_MEMORY_TYPE = "profile_enrichment_candidate" PROFILE_ENRICHMENT_ACCEPTANCE_STATUSES = { @@ -175,6 +178,9 @@ "tested", ) GRAPH_LLM_BACKING_SOURCE_TYPE = "auto" +# LLM window jobs share plugin_memory_extraction_job with per-event jobs; this +# trace prefix is how the generic per-event drain leaves them alone. +GROUP_WINDOW_LLM_JOB_TRACE_PREFIX = "group-window-llm:" GROUP_WINDOW_DETERMINISTIC_MAX_SENDERS = 8 GROUP_WINDOW_DETERMINISTIC_MAX_PAIRS = 20 HYBRID_ITEM_SQL_CANDIDATE_MULTIPLIER = 4 @@ -1021,6 +1027,24 @@ def _detect_sensitivity(content: str) -> str: return "normal" +def _group_window_relation_sensitivity_probe(value_json: Any) -> str: + """Return the only part of a group window relation worth sensitivity-checking. + + Participant ids are the graph's node identities and are already stored by + the rule layer; a free-text object term (topic/tool/project) is the one + place a model could smuggle in a phone number or similar. + """ + + value = value_json if isinstance(value_json, dict) else _safe_json_loads(value_json, {}) + relation = value.get("relation") if isinstance(value, dict) else None + if not isinstance(relation, dict): + return "" + object_type = str(relation.get("object_type") or "person").strip().lower() + if object_type == "person": + return "" + return str(relation.get("object") or "") + + def _memory_type_for_content(content: str) -> str: if any(keyword in content for keyword in ("我叫", "我是", "我的名字")): return "profile_fact" @@ -3735,11 +3759,34 @@ async def candidate_ids(condition: str, days: int) -> list[int]: ) return [int(row["id"]) for row in rows] + # Independent of the generic retention: group relations have their own + # promotion paths (second day, corroboration sweep), so what is left + # after this window is noise and can go sooner than 30 days. + group_relation_review_days = max( + 1, + int( + getattr(self.settings, "memory_group_relation_review_retention_days", 14) + or 14 + ), + ) + group_relation_source_types = ( + f"('{DETERMINISTIC_GROUP_WINDOW_SOURCE_TYPE}', '{LLM_GROUP_WINDOW_SOURCE_TYPE}')" + ) review_ids = await candidate_ids( "COALESCE(NULLIF(value_json, '')::jsonb #>> '{acceptance,status}', '') " - "IN ('candidate', 'needs_review')", + "IN ('candidate', 'needs_review') " + f"AND source_type NOT IN {group_relation_source_types}", review_days, ) + # Group relations are promoted automatically (second day, corroboration + # sweep); whatever is still waiting after their own retention window + # is expired here. + review_ids += await candidate_ids( + "COALESCE(NULLIF(value_json, '')::jsonb #>> '{acceptance,status}', '') " + "IN ('candidate', 'needs_review') " + f"AND source_type IN {group_relation_source_types}", + group_relation_review_days, + ) rejected_ids = await candidate_ids( "COALESCE(NULLIF(value_json, '')::jsonb #>> '{acceptance,status}', '') = 'rejected'", reject_days, @@ -3750,17 +3797,34 @@ async def candidate_ids(condition: str, days: int) -> list[int]: "IN ('accepted', '')", expire_days, ) + # Extraction jobs that nobody drained (drain disabled, worker gone) must + # not stay queued forever; they are marked dead after a long grace period. + stale_job_days = max( + 1, + int(getattr(self.settings, "memory_llm_extraction_job_stale_days", 30) or 30), + ) + stale_job_rows = await _exec( + "SELECT id FROM plugin_memory_extraction_job " + "WHERE status IN ('pending', 'failed') " + "AND updated_at < NOW() - (:days * INTERVAL '1 day') " + "AND (locked_until IS NULL OR locked_until < NOW()) " + "ORDER BY updated_at ASC, id ASC LIMIT :limit", + {"days": stale_job_days, "limit": batch}, + ) + stale_job_ids = [int(row["id"]) for row in stale_job_rows or []] result = { "dry_run": dry_run, "skipped_locked": False, "needs_review_expired": len(review_ids), "rejected_purged": len(rejected_ids), "stale_auto_expired": len(stale_ids), + "stale_jobs_dead": len(stale_job_ids), "selected": len(set(review_ids + rejected_ids + stale_ids)), "ids": { "needs_review": review_ids, "rejected": rejected_ids, "stale_auto": stale_ids, + "stale_jobs": stale_job_ids, }, } physical_expiry = await self._run_physical_expiry_sweep( @@ -3768,13 +3832,30 @@ async def candidate_ids(condition: str, days: int) -> list[int]: batch=batch, ) result["physical_expiry"] = physical_expiry - total_selected = int(result["selected"]) + int( - physical_expiry.get("selected") or 0 + total_selected = ( + int(result["selected"]) + + int(physical_expiry.get("selected") or 0) + + len(stale_job_ids) ) if dry_run or total_selected <= 0: MEMORY_GOVERNANCE_EVENTS.labels(action="cleanup", result="dry_run").inc() return result + if stale_job_ids: + await _exec( + "UPDATE plugin_memory_extraction_job SET status = 'dead', " + "last_error = CASE WHEN COALESCE(last_error, '') = '' " + "THEN 'stale: not processed within retention' ELSE last_error END, " + "locked_until = NULL, locked_by = '', updated_at = NOW() " + "WHERE id = ANY(:ids) AND status IN ('pending', 'failed')", + {"ids": stale_job_ids}, + ) + logger.info( + "memory.governance_stale_jobs_dead", + count=len(stale_job_ids), + stale_days=stale_job_days, + ) + expire_ids = sorted(set(review_ids + stale_ids)) if expire_ids: await _exec( @@ -4293,11 +4374,18 @@ async def _insert_or_touch_memory_item( ) -> dict[str, Any] | None: raw_original_text = _sanitize_db_text(original_text) raw_content = _sanitize_db_text(content) - detected_sensitivity = ( - "normal" - if source_type == DETERMINISTIC_GROUP_WINDOW_SOURCE_TYPE - else _detect_sensitivity(raw_content) - ) + is_group_window_relation = source_type in GROUP_WINDOW_RELATION_SOURCE_TYPES + if is_group_window_relation: + # The content is the synthetic " " + # line, never chat text. Participant ids contain "wxid", which the + # generic detector reads as PII and would park every accepted + # model relation in pending. Only a non-person object term can + # carry something sensitive, so probe just that. + detected_sensitivity = _detect_sensitivity( + _group_window_relation_sensitivity_probe(value_json) + ) + else: + detected_sensitivity = _detect_sensitivity(raw_content) original_text = _redact_memory_storage_text(raw_original_text) content = _normalize_line(_redact_memory_storage_text(raw_content))[:500] if not content: @@ -4354,9 +4442,11 @@ async def _insert_or_touch_memory_item( confidence = max(float(confidence or 0.0), 0.9) if status in {"deleted", "invalidated"}: status = "active" - elif source_type != DETERMINISTIC_GROUP_WINDOW_SOURCE_TYPE and ( + elif not is_group_window_relation and ( sensitivity != "normal" or float(confidence or 0.0) < PROMPT_AUTO_CONFIDENCE_MIN ): + # Group window relations are gated by their own acceptance policy + # (signals, evidence count, day count), not by raw model confidence. status = "pending" if sensitivity != "normal": status = "pending" @@ -4513,9 +4603,13 @@ async def _insert_or_touch_memory_item( if current_sensitivity not in MEMORY_SENSITIVITY_CATEGORIES: current_sensitivity = "sensitive" sensitivity_order = {"normal": 0, "pii": 1, "sensitive": 2} - if sensitivity_order.get(current_sensitivity, 3) > sensitivity_order.get( - sensitivity_category, 3 - ): + # Group window relations are re-probed on every touch (only the + # object term can be sensitive); inheriting the stored value would + # keep rows flagged by the old participant-id false positive + # parked in pending forever. + if not is_group_window_relation and sensitivity_order.get( + current_sensitivity, 3 + ) > sensitivity_order.get(sensitivity_category, 3): sensitivity_category = current_sensitivity sensitivity = current_sensitivity current_expiry = _coerce_datetime(current.get("expires_at")) @@ -6762,7 +6856,9 @@ async def append_memory_acceptance_audit( "reason": str(reason or "")[:1000], "superseded_by_item_id": superseded_by_item_id, "supersedes_item_id": supersedes_item_id, - "reviewed_at": reviewed_at, + # asyncpg binds the CAST(... AS TIMESTAMP) parameter as a + # timestamp and rejects the ISO string the reviewer built. + "reviewed_at": _coerce_datetime(reviewed_at), }, ) diff --git a/plugins/memory/store_backfill.py b/plugins/memory/store_backfill.py index 2b3a4d7..b29736f 100644 --- a/plugins/memory/store_backfill.py +++ b/plugins/memory/store_backfill.py @@ -858,6 +858,17 @@ async def get_group_graph_history_dates( recent_days = max(1, min(int(recent_days or 14), 90)) today = datetime.now().date() + # Imported events and relations live under the operator session id while + # the console addresses the group by its runtime alias; count both. + resolver = getattr(self, "_resolve_group_graph_session_ids", None) + session_ids = [session_id] + if callable(resolver): + try: + session_ids = await resolver(tenant_id=tenant_id, session_id=session_id) or [ + session_id + ] + except Exception: + session_ids = [session_id] rows: list[dict[str, Any]] = [] for offset in range(recent_days): day = today - timedelta(days=offset) @@ -875,20 +886,27 @@ async def get_group_graph_history_dates( "SELECT COUNT(*) AS count FROM plugin_memory_event " "WHERE tenant_id = :tid AND channel = :channel " "AND source_key IN (:source_key, '*') " - "AND user_id = :uid AND session_id = :sid " + "AND user_id = :uid AND session_id = ANY(:sids) " "AND created_at >= :start_at AND created_at < :end_at", { "tid": tenant_id, "channel": channel, "source_key": source_key, "uid": user_id, - "sid": session_id, + "sids": session_ids, "start_at": start_at, "end_at": end_at, }, ) - raw_count = len(messages) - imported_count = int((imported[0] if imported else {}).get("count") or 0) + observation_count = await self._count_group_observations_for_day( + tenant_id=tenant_id, + session_ids=session_ids, + start_at=start_at, + end_at=end_at, + ) + raw_count = max(len(messages), observation_count) + memory_event_count = int((imported[0] if imported else {}).get("count") or 0) + imported_count = memory_event_count + observation_count job_counts = await self.get_llm_extraction_job_status_counts_for_day( tenant_id=tenant_id, channel=channel, @@ -911,6 +929,8 @@ async def get_group_graph_history_dates( "date": day.isoformat(), "raw_message_count": raw_count, "imported_count": imported_count, + "memory_event_count": memory_event_count, + "observation_count": observation_count, "job_counts": job_counts, "status": status, } @@ -921,6 +941,7 @@ async def get_group_graph_history_dates( "channel": channel, "source_key": source_key, "session_id": session_id, + "session_ids": session_ids, "user_id": user_id, "user_id_scope": user_id, "user_id_auto": user_id_auto, @@ -928,6 +949,34 @@ async def get_group_graph_history_dates( "items": rows, } + async def _count_group_observations_for_day( + self, + *, + tenant_id: str, + session_ids: list[str], + start_at: datetime, + end_at: datetime, + ) -> int: + rooms = [str(item).strip() for item in session_ids if str(item or "").strip()] + if not rooms: + return 0 + try: + rows = await _exec( + "SELECT COUNT(*) AS count FROM plugin_wxbot_group_observations " + "WHERE tenant_id = :tid AND session_id = ANY(:sids) " + "AND occurred_ts >= :start_ts AND occurred_ts < :end_ts " + "AND sender_wxid <> '' AND content <> ''", + { + "tid": str(tenant_id or "").strip(), + "sids": rooms, + "start_ts": int(start_at.timestamp()), + "end_ts": int(end_at.timestamp()), + }, + ) + except Exception: + return 0 + return int((rows[0] if rows else {}).get("count") or 0) + async def _live_group_backfill_messages( self, *, diff --git a/plugins/memory/store_group_graph.py b/plugins/memory/store_group_graph.py index 0e61c3f..a9c12b4 100644 --- a/plugins/memory/store_group_graph.py +++ b/plugins/memory/store_group_graph.py @@ -4,6 +4,7 @@ import asyncio import json +import math import re from collections.abc import Iterable from datetime import UTC, datetime, timedelta @@ -19,6 +20,7 @@ GROUP_HISTORY_USER_ID_SCOPE, GROUP_WINDOW_DETERMINISTIC_MAX_PAIRS, GROUP_WINDOW_DETERMINISTIC_MAX_SENDERS, + GROUP_WINDOW_LLM_JOB_TRACE_PREFIX, LLM_GROUP_WINDOW_SOURCE_TYPE, MEMORY_ACCEPTANCE_REVIEW_ACTIONS, _append_unique_int, @@ -77,26 +79,206 @@ def _group_graph_item_value(item: dict[str, Any] | None) -> dict[str, Any]: return loaded if isinstance(loaded, dict) else {} +EVIDENCE_SOURCE_MEMORY_EVENT = "memory_event" +EVIDENCE_SOURCE_OBSERVATION = "observation" +EVIDENCE_SOURCE_MIXED = "mixed" +GROUP_GRAPH_EVIDENCE_SOURCES = (EVIDENCE_SOURCE_MEMORY_EVENT, EVIDENCE_SOURCE_OBSERVATION) + + +def _group_graph_evidence_source(event_ids: Iterable[Any], observation_ids: Iterable[Any]) -> str: + has_events = bool(_coerce_int_set(event_ids)) + has_observations = bool(_coerce_int_set(observation_ids)) + if has_events and has_observations: + return EVIDENCE_SOURCE_MIXED + if has_observations: + return EVIDENCE_SOURCE_OBSERVATION + return EVIDENCE_SOURCE_MEMORY_EVENT + + def _group_graph_edge_quality(item: dict[str, Any] | None) -> dict[str, Any]: value = _group_graph_item_value(item) acceptance = value.get("acceptance") if isinstance(value.get("acceptance"), dict) else {} + relation = value.get("relation") if isinstance(value.get("relation"), dict) else {} dates = value.get("evidence_dates") evidence_dates = ( [str(entry).strip()[:10] for entry in dates if str(entry).strip()] if isinstance(dates, list) else [] ) + evidence_dates = list(dict.fromkeys(evidence_dates))[:90] score = acceptance.get("score") if score is None: score = item.get("acceptance_score") if item else None reason = str(acceptance.get("reason") or (item or {}).get("acceptance_reason") or "").strip() + event_ids = _coerce_int_set( + relation.get("evidence_event_ids") or value.get("source_event_ids") or [] + ) + observation_ids = _coerce_int_set( + relation.get("evidence_observation_ids") or value.get("source_observation_ids") or [] + ) + first_seen_date = str(value.get("first_seen_date") or "").strip()[:10] or ( + min(evidence_dates) if evidence_dates else None + ) + last_seen_date = str(value.get("last_seen_date") or "").strip()[:10] or ( + max(evidence_dates) if evidence_dates else None + ) return { - "evidence_dates": list(dict.fromkeys(evidence_dates))[:90], + "evidence_dates": evidence_dates, "acceptance_score": _clamp_score(score) if score is not None else None, "acceptance_reason": reason[:80] or None, + "evidence_event_count": len(event_ids), + "evidence_observation_count": len(observation_ids), + "evidence_day_count": len(evidence_dates), + "evidence_source": str(value.get("evidence_source") or "").strip() + or _group_graph_evidence_source(event_ids, observation_ids), + "first_seen_date": first_seen_date or None, + "last_seen_date": last_seen_date or None, } +def _group_relation_judgement(item: dict[str, Any] | None) -> dict[str, Any]: + """Why the pipeline believes this edge, without any chat text. + + Operators asking "how was this decided?" get the extraction method, the + per-signal counts, the acceptance policy that fired and who/what reviewed + it, plus the model's one-line rationale for model relations. That rationale + is the model's own paraphrase (capped when stored), not a message. + """ + + value = _group_graph_item_value(item) + acceptance = value.get("acceptance") if isinstance(value.get("acceptance"), dict) else {} + relation = value.get("relation") if isinstance(value.get("relation"), dict) else {} + source_type = str((item or {}).get("source_type") or "").strip() + method = ( + "llm" + if source_type == LLM_GROUP_WINDOW_SOURCE_TYPE + else "deterministic" + if source_type == DETERMINISTIC_GROUP_WINDOW_SOURCE_TYPE + else str(relation.get("extraction_method") or "").strip() or "unknown" + ) + raw_signals = relation.get("signals") if isinstance(relation.get("signals"), dict) else {} + signals = { + key: max(0, _safe_int(raw_signals.get(key), 0)) + for key in GROUP_SIGNAL_KEYS + if _safe_int(raw_signals.get(key), 0) > 0 + } + model_reason = _normalize_line(str(relation.get("reason") or ""))[:240] + return { + "extraction_method": method, + "signals": signals, + "policy": str(acceptance.get("policy") or acceptance.get("reason") or "").strip()[:80], + "acceptance_status": str(acceptance.get("status") or "").strip(), + "reviewed_by": str(acceptance.get("reviewed_by") or "").strip()[:120], + "review_reason": _normalize_line(str(acceptance.get("review_reason") or ""))[:240], + "model_reason": model_reason if method == "llm" else "", + "day_count": max(0, _safe_int(acceptance.get("day_count"), 0)), + "strength": _clamp_score(relation.get("strength")) if relation.get("strength") is not None else None, + } + + +SYMMETRIC_GROUP_PREDICATES = frozenset({"co_participated", "collaborated_with"}) + + +def _end_of_day(value: datetime, date_text: Any) -> datetime: + """Treat a date-only evidence boundary as the end of that day.""" + + if date_text and len(str(date_text).strip()) <= 10: + return value.replace(hour=23, minute=59, second=59, microsecond=999999) + return value + + +def _merge_symmetric_group_edges(edges: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Collapse A→B and B→A rows of symmetric predicates into one edge. + + Co-participation is stored directionally because the pair order depends on + who spoke first in a window; on the wire it is one undirected relation. + """ + + merged: list[dict[str, Any]] = [] + by_pair: dict[tuple[str, str, str], dict[str, Any]] = {} + for edge in edges: + predicate = str(edge.get("type") or "") + if predicate not in SYMMETRIC_GROUP_PREDICATES: + merged.append(edge) + continue + source = str(edge.get("source") or "") + target = str(edge.get("target") or "") + key = (predicate, *sorted((source, target))) + existing = by_pair.get(key) + if existing is None: + edge = {**edge, "mirror_ids": []} + by_pair[key] = edge + merged.append(edge) + continue + existing["mirror_ids"] = [*existing.get("mirror_ids", []), edge.get("id")] + existing["confidence"] = max( + _clamp_score(existing.get("confidence"), 0.0), _clamp_score(edge.get("confidence"), 0.0) + ) + existing["evidence_count"] = int(existing.get("evidence_count") or 0) + int( + edge.get("evidence_count") or 0 + ) + existing["observation_count"] = int(existing.get("observation_count") or 0) + int( + edge.get("observation_count") or 0 + ) + dates = list(dict.fromkeys([*(existing.get("evidence_dates") or []), *(edge.get("evidence_dates") or [])])) + existing["evidence_dates"] = sorted(dates)[:90] + existing["evidence_day_count"] = max( + len(existing["evidence_dates"]), int(existing.get("evidence_day_count") or 0) + ) + for key_name, pick in (("first_seen", min), ("last_seen", max)): + values = [str(v) for v in (existing.get(key_name), edge.get(key_name)) if v] + if values: + existing[key_name] = pick(values) + for key_name, pick in (("first_seen_date", min), ("last_seen_date", max)): + values = [str(v) for v in (existing.get(key_name), edge.get(key_name)) if v] + existing[key_name] = pick(values) if values else None + strengths = [ + float(v) for v in (existing.get("strength"), edge.get("strength")) if v is not None + ] + if strengths: + existing["strength"] = round(max(strengths), 4) + existing["source_event_ids"] = _merge_int_lists( + existing.get("source_event_ids"), edge.get("source_event_ids"), max_items=200 + ) + existing["memory_item_ids"] = _merge_int_lists( + existing.get("memory_item_ids"), edge.get("memory_item_ids"), max_items=200 + ) + if existing.get("acceptance_status") != "accepted" and edge.get("acceptance_status") == "accepted": + existing["acceptance_status"] = "accepted" + return merged + + +def _group_graph_item_observation_ids(item: dict[str, Any] | None) -> list[int]: + value = _group_graph_item_value(item) + relation = value.get("relation") if isinstance(value.get("relation"), dict) else {} + return sorted( + _coerce_int_set(relation.get("evidence_observation_ids") or []) + | _coerce_int_set(value.get("source_observation_ids") or []) + ) + + +def _split_window_evidence_ids( + candidate_ids: Iterable[Any], + observation_ids: set[int], +) -> tuple[list[int], list[int]]: + """Split window evidence into memory-event ids and group-observation ids. + + Observation rows come from ``plugin_wxbot_group_observations`` whose id + space is unrelated to ``plugin_memory_event``. Keeping them under their own + key preserves the evidence trail without tricking the memory-event + provenance check that runs when the item is written. + """ + + event_ids: list[int] = [] + observation_evidence: list[int] = [] + for event_id in sorted(_coerce_int_set(candidate_ids)): + if event_id in observation_ids: + observation_evidence.append(event_id) + else: + event_ids.append(event_id) + return event_ids, observation_evidence + + def _group_graph_auto_cursor_key( *, tenant_id: str, @@ -109,6 +291,327 @@ def _group_graph_auto_cursor_key( return f"group-graph-auto-cursor:v1:{_normalize_key(scope)}" +def _normalize_evidence_source(value: Any) -> str | None: + text = str(value or "").strip().lower() + return text if text in GROUP_GRAPH_EVIDENCE_SOURCES else None + + +# Deterministic interaction signals. ``direct`` signals are observable platform +# facts (a quoted reply, an @-mention, an explicit "回复" prefix); they may be +# accepted on first sight. Anything else needs repetition before acceptance. +SIGNAL_QUOTE = "quote" +SIGNAL_MENTION = "mention" +SIGNAL_PREFIX_REPLY = "prefix_reply" +SIGNAL_CO_PARTICIPATION = "co_participation" +SIGNAL_LLM = "llm" +DIRECT_GROUP_SIGNALS = (SIGNAL_QUOTE, SIGNAL_MENTION, SIGNAL_PREFIX_REPLY) +GROUP_SIGNAL_KEYS = (*DIRECT_GROUP_SIGNALS, SIGNAL_CO_PARTICIPATION, SIGNAL_LLM) +QUOTE_REPLY_CONFIDENCE = 0.9 +MENTION_METADATA_CONFIDENCE = 0.85 +MENTION_TEXT_CONFIDENCE = 0.72 +PREFIX_REPLY_CONFIDENCE = 0.62 +CO_PARTICIPATION_CONFIDENCE = 0.45 +GROUP_RELATION_MIN_LLM_DAYS = 2 +# A model-only relation is also accepted without a second day once this many +# distinct messages in the window support it; one-off claims stay in review. +GROUP_RELATION_MIN_LLM_EVIDENCE = 3 +# Below this many supporting messages an LLM candidate is not stored at all: +# on the production data single-message claims were the bulk of the noise. +GROUP_RELATION_MIN_LLM_WINDOW_EVIDENCE = 2 +GROUP_RELATION_MIN_WEAK_DAYS = 2 +GROUP_RELATION_MIN_WEAK_COUNT = 3 +# Actor recorded on acceptance audits written by the corroboration sweep. +GROUP_RELATION_AUTO_REVIEWER = "system/auto-review" +# The rule layer owns these; a model re-stating them adds nothing but noise. +LLM_EXCLUDED_PREDICATES = frozenset({"co_participated"}) +# Objects for the pseudo-entity "the group" ("asked the group") are dropped. +LLM_GROUP_PSEUDO_OBJECTS = frozenset({"group", "the group", "群", "群聊", "大家", "everyone", "all"}) +LLM_TERM_MIN_LENGTH = 2 +LLM_TERM_MAX_LENGTH = 40 + +_MENTION_TOKEN_RE = re.compile(r"@([^\s\u2005\u00a0@::,,;;]+)") + +# LLM window jobs live in plugin_memory_extraction_job next to per-event jobs +# (see GROUP_WINDOW_LLM_JOB_TRACE_PREFIX in store.py). +GROUP_WINDOW_LLM_JOB_KIND = "group_window_llm" +LLM_MODE_INLINE = "inline" +LLM_MODE_ENQUEUE = "enqueue" +GROUP_WINDOW_LLM_TIMEOUT_DEFAULT = 60 +GROUP_WINDOW_LLM_TIMEOUT_MIN = 5 +GROUP_WINDOW_LLM_TIMEOUT_MAX = 600 +GROUP_WINDOW_LLM_MODEL_TIER_DEFAULT = "tier-1" +# LLM-proposed objects typed "person" that are not real participants are almost +# always terms ("缩水", "gpt", "4.8"); these predicates keep them as topics. +LLM_PERSON_TO_TOPIC_PREDICATES = frozenset( + {"mentioned", "interested_in", "asked", "requested", "reported_issue", "works_on", "provided_resource"} +) + + +def _group_window_llm_job_key( + *, + tenant_id: str, + channel: str, + source_key: str, + session_id: str, + target_date: str, + source: str, + first_event_id: Any, + last_event_id: Any, +) -> str: + scope = "\x1f".join( + ( + tenant_id, + channel, + source_key, + session_id, + target_date, + source or EVIDENCE_SOURCE_MEMORY_EVENT, + str(first_event_id or 0), + str(last_event_id or 0), + ) + ) + return f"{GROUP_WINDOW_LLM_JOB_TRACE_PREFIX}v1:{_normalize_key(scope)}" + + +def _normalize_llm_mode(value: Any) -> str: + text = str(value or "").strip().lower() + return LLM_MODE_ENQUEUE if text == LLM_MODE_ENQUEUE else LLM_MODE_INLINE + + +def _normalize_group_name(value: Any) -> str: + text = _normalize_line(_sanitize_db_text(value)) + return re.sub(r"[\s\u2005\u00a0]+", "", text).lower() + + +_LLM_TERM_WORD_RE = re.compile(r"[^\W\d_]", re.UNICODE) +# wxid_xxx, bare QQ-style numbers and letter+digits account ids: member +# identifiers, never topics. +_PARTICIPANT_ID_RE = re.compile(r"^(?:wxid_[\w-]+|\d{5,}|[a-z]\d{6,})$", re.IGNORECASE) + + +def _looks_like_participant_id(value: str) -> bool: + return bool(_PARTICIPANT_ID_RE.match(_normalize_line(str(value or "")))) + + +def _is_usable_llm_term(value: str) -> bool: + """Reject model-proposed terms that cannot be a graph node. + + Sentences (too long), single characters, bare numbers/times ("9点", "4.8") + and punctuation-only strings are dropped; a term must contain at least one + letter or CJK character and stay within ``LLM_TERM_MAX_LENGTH``. + """ + + text = _normalize_line(str(value or "")) + if len(text) < LLM_TERM_MIN_LENGTH or len(text) > LLM_TERM_MAX_LENGTH: + return False + letters = _LLM_TERM_WORD_RE.findall(text) + if not letters: + return False + # "9点" / "5x" style: one letter riding on digits is still a number. + if len(letters) < 2 and re.search(r"\d", text): + return False + return True + + +def _observation_interaction_metadata( + raw_metadata: Any, + *, + sender_name: Any = None, +) -> dict[str, Any]: + """Pull the interaction facts out of ``metadata_json`` without keeping text. + + Only identifiers, display names and message ids are retained: who was + quoted (``quote.fromusr`` / ``quote.sender_name``), who was @-mentioned + (``at_wxids``) and the bot's own id so it can be excluded as a target. + """ + + metadata = raw_metadata if isinstance(raw_metadata, dict) else _safe_json_loads(raw_metadata, {}) + if not isinstance(metadata, dict): + metadata = {} + quote = metadata.get("quote") if isinstance(metadata.get("quote"), dict) else {} + at_wxids_raw = metadata.get("at_wxids") + at_wxids = ( + [str(item).strip() for item in at_wxids_raw if str(item or "").strip()] + if isinstance(at_wxids_raw, list) + else [] + ) + return { + "sender_name": _normalize_line(_sanitize_db_text(sender_name))[:80], + "quote_from": str(quote.get("fromusr") or "").strip()[:200], + "quote_sender_name": _normalize_line(_sanitize_db_text(quote.get("sender_name")))[:80], + "quote_message_id": str(quote.get("refer_msg_svr_id") or "").strip()[:64], + "at_wxids": at_wxids[:20], + "bot_wxid": str(metadata.get("bot_wxid") or "").strip()[:200], + } + + +class GroupMemberDirectory: + """Resolve the different id/name forms a member shows up under in one group. + + ``sender_wxid`` is the canonical node id. Quote and @ metadata sometimes + carry a member's alias id instead, so resolution goes: known sender id → + nickname match → alias id known to the membership table → unresolved. + Unresolved targets are dropped rather than turned into phantom nodes. + """ + + def __init__(self) -> None: + self.names_by_id: dict[str, str] = {} + self.ids_by_name: dict[str, str] = {} + self.sender_ids: set[str] = set() + self._sorted_names: list[str] | None = None + + def add_sender(self, member_id: Any, name: Any = None) -> None: + canonical = _normalize_line(_sanitize_db_text(member_id))[:200] + if not canonical: + return + self.sender_ids.add(canonical) + self.add_member(canonical, name, prefer=True) + + def add_member(self, member_id: Any, name: Any = None, *, prefer: bool = False) -> None: + canonical = _normalize_line(_sanitize_db_text(member_id))[:200] + if not canonical: + return + display = _normalize_line(_sanitize_db_text(name))[:80] + if display and display != canonical: + self.names_by_id.setdefault(canonical, display) + key = _normalize_group_name(display) + if key and ( + key not in self.ids_by_name + or (prefer and self.ids_by_name[key] not in self.sender_ids) + ): + self.ids_by_name[key] = canonical + self._sorted_names = None + + def resolve_name(self, name: Any) -> str | None: + key = _normalize_group_name(name) + if not key: + return None + exact = self.ids_by_name.get(key) + if exact: + return exact + if self._sorted_names is None: + self._sorted_names = sorted(self.ids_by_name, key=len, reverse=True) + for known in self._sorted_names: + if len(known) >= 2 and key.startswith(known): + return self.ids_by_name[known] + return None + + def resolve_id(self, raw_id: Any, *, fallback_name: Any = None) -> str | None: + candidate = _normalize_line(_sanitize_db_text(raw_id))[:200] + if candidate.startswith("user:"): + candidate = candidate[5:] + if candidate and candidate in self.sender_ids: + return candidate + via_name = self.resolve_name(fallback_name) if fallback_name else None + if via_name: + return via_name + if candidate and candidate in self.names_by_id: + via_alias = self.resolve_name(self.names_by_id[candidate]) + return via_alias or candidate + return None + + +def _empty_group_signals() -> dict[str, int]: + return dict.fromkeys(GROUP_SIGNAL_KEYS, 0) + + +def _merge_group_signals(*values: Any) -> dict[str, int]: + merged = _empty_group_signals() + for value in values: + if not isinstance(value, dict): + continue + for key in GROUP_SIGNAL_KEYS: + merged[key] += max(0, _safe_int(value.get(key), 0)) + return merged + + +def _merge_signal_evidence(*values: Any, max_items: int = 200) -> dict[str, list[int]]: + """Union per-signal evidence ids. Counting ids instead of occurrences keeps + ``signals`` idempotent when a window is processed twice (retries, manual + re-runs, the LLM pass following the deterministic pass).""" + + merged: dict[str, list[int]] = {key: [] for key in GROUP_SIGNAL_KEYS} + for value in values: + if not isinstance(value, dict): + continue + for key in GROUP_SIGNAL_KEYS: + merged[key] = _merge_int_lists(merged[key], value.get(key), max_items=max_items) + return merged + + +def _signals_from_evidence(signal_evidence: dict[str, list[int]]) -> dict[str, int]: + signals = _empty_group_signals() + for key in GROUP_SIGNAL_KEYS: + signals[key] = len(_coerce_int_set(signal_evidence.get(key) or [])) + return signals + + +_LEGACY_REASON_SIGNALS = { + "deterministic_quote_reply": SIGNAL_QUOTE, + "deterministic_at_mention_metadata": SIGNAL_MENTION, + "deterministic_addressed_participant": SIGNAL_MENTION, + "deterministic_adjacent_reply_window": SIGNAL_PREFIX_REPLY, + "deterministic_same_window_participation": SIGNAL_CO_PARTICIPATION, +} + + +def _infer_legacy_group_signals(relation: dict[str, Any], source_type: str) -> dict[str, int]: + """Signal counts for relations written before ``signals`` existed.""" + + signals = _empty_group_signals() + reason = str(relation.get("reason") or "").strip() + mapped = _LEGACY_REASON_SIGNALS.get(reason) + if mapped is None: + method = str(relation.get("extraction_method") or source_type or "") + if method == DETERMINISTIC_GROUP_WINDOW_SOURCE_TYPE: + mapped = ( + SIGNAL_CO_PARTICIPATION + if str(relation.get("predicate") or "") == "co_participated" + else SIGNAL_PREFIX_REPLY + ) + else: + mapped = SIGNAL_LLM + # One legacy item = one known occurrence; evidence ids per occurrence vary + # by rule, so they are not a reliable count. + signals[mapped] = 1 + return signals + + +def _group_relation_strength(signals: dict[str, int], day_count: int) -> float: + """Accumulated interaction strength in [0, 1]: more direct hits and more + distinct days saturate towards 1 with diminishing returns.""" + + direct = sum(signals.get(key, 0) for key in DIRECT_GROUP_SIGNALS) + weak = signals.get(SIGNAL_CO_PARTICIPATION, 0) + signals.get(SIGNAL_LLM, 0) + exponent = direct / 3.0 + weak / 10.0 + max(0, int(day_count) - 1) / 4.0 + return round(_clamp_score(1.0 - math.exp(-exponent), 0.0), 4) + + +def _group_relation_acceptance_decision( + signals: dict[str, int], + *, + day_count: int, + auto_accept: bool, +) -> tuple[str, str]: + """Deterministic acceptance policy for group window relations.""" + + if not auto_accept: + return "needs_review", "group_window_relation" + if any(signals.get(key, 0) > 0 for key in DIRECT_GROUP_SIGNALS): + return "accepted", "group_window_direct_signal" + llm_count = int(signals.get(SIGNAL_LLM, 0) or 0) + if llm_count > 0 and int(day_count) >= GROUP_RELATION_MIN_LLM_DAYS: + return "accepted", "group_window_llm_multi_day" + if llm_count >= GROUP_RELATION_MIN_LLM_EVIDENCE: + return "accepted", "group_window_llm_repeated_evidence" + if ( + signals.get(SIGNAL_CO_PARTICIPATION, 0) >= GROUP_RELATION_MIN_WEAK_COUNT + and int(day_count) >= GROUP_RELATION_MIN_WEAK_DAYS + ): + return "accepted", "group_window_repeated_weak_signal" + return "needs_review", "group_window_weak_signal" + + def _clean_session_ids(*values: Any) -> list[str]: cleaned: list[str] = [] for value in values: @@ -222,6 +725,112 @@ async def list_memory_graph_entities( row["confidence"] = float(row.get("confidence") or 0.0) return rows + def _group_graph_fact_filter_sql( + self, + params: dict[str, Any], + *, + predicates: list[str] | None, + min_confidence: float | None, + acceptance_statuses: list[str] | None, + default_accepted_only: bool, + from_date: str | None, + to_date: str | None, + ) -> list[str]: + """SQL conditions for the graph read path, evaluated before LIMIT. + + Acceptance and evidence dates live on the backing memory item + (``backing``), so the caller must LEFT JOIN it. Doing this in SQL keeps a + 500-row cap from silently hiding older or non-dominant edges. + """ + + conditions: list[str] = [] + acceptance_expr = ( + "COALESCE(NULLIF(NULLIF(backing.value_json, '')::jsonb #>> '{acceptance,status}', ''), " + "CASE WHEN backing.status = 'active' THEN 'accepted' ELSE 'needs_review' END)" + ) + if predicates: + conditions.append("fact.predicate = ANY(:predicates)") + params["predicates"] = list(predicates) + if min_confidence is not None: + conditions.append("fact.confidence >= :min_confidence") + params["min_confidence"] = float(min_confidence) + if acceptance_statuses: + conditions.append(f"{acceptance_expr} = ANY(:acceptance_statuses)") + params["acceptance_statuses"] = list(acceptance_statuses) + elif default_accepted_only: + conditions.append( + f"{acceptance_expr} = 'accepted' " + "AND backing.status = 'active' AND backing.deleted_at IS NULL" + ) + first_seen_expr = ( + "COALESCE(NULLIF(NULLIF(backing.value_json, '')::jsonb ->> 'first_seen_date', ''), " + "to_char(COALESCE(fact.valid_at, fact.created_at, fact.updated_at), 'YYYY-MM-DD'))" + ) + last_seen_expr = ( + "COALESCE(NULLIF(NULLIF(backing.value_json, '')::jsonb ->> 'last_seen_date', ''), " + "to_char(COALESCE(fact.valid_at, fact.created_at, fact.updated_at), 'YYYY-MM-DD'))" + ) + if from_date: + # An edge is in range when its evidence interval overlaps the window. + conditions.append(f"{last_seen_expr} >= :from_date") + params["from_date"] = from_date + if to_date: + conditions.append(f"{first_seen_expr} <= :to_date") + params["to_date"] = to_date + return conditions + + async def count_memory_graph_facts( + self, + *, + tenant_id: str, + channel: str | None = None, + source_key: str | None = None, + session_ids: list[str] | None = None, + status: str | None = None, + predicates: list[str] | None = None, + min_confidence: float | None = None, + acceptance_statuses: list[str] | None = None, + default_accepted_only: bool = False, + from_date: str | None = None, + to_date: str | None = None, + ) -> int: + conditions = ["fact.tenant_id = :tid"] + params: dict[str, Any] = {"tid": tenant_id} + if channel is not None: + conditions.append("fact.channel = :channel") + params["channel"] = channel + if source_key is not None: + conditions.append("fact.source_key = :source_key") + params["source_key"] = source_key + if session_ids: + conditions.append("backing.session_id = ANY(:sids)") + params["sids"] = list(session_ids) + if status is not None: + conditions.append("fact.status = :status") + params["status"] = status + conditions.extend( + self._group_graph_fact_filter_sql( + params, + predicates=predicates, + min_confidence=min_confidence, + acceptance_statuses=acceptance_statuses, + default_accepted_only=default_accepted_only, + from_date=from_date, + to_date=to_date, + ) + ) + try: + rows = await _exec( + "SELECT COUNT(*) AS count FROM plugin_memory_fact fact " + "LEFT JOIN plugin_memory_item backing ON backing.id = fact.memory_item_id " + f"WHERE {' AND '.join(conditions)}", + params, + ) + except Exception: + logger.warning("memory.group_graph_fact_count_failed", exc_info=True) + return 0 + return _safe_int((rows[0] if rows else {}).get("count"), 0) + async def list_memory_graph_facts( self, *, @@ -233,6 +842,13 @@ async def list_memory_graph_facts( session_ids: list[str] | None = None, status: str | None = None, limit: int = 100, + predicates: list[str] | None = None, + min_confidence: float | None = None, + acceptance_statuses: list[str] | None = None, + default_accepted_only: bool = False, + from_date: str | None = None, + to_date: str | None = None, + order_by_strength: bool = False, ) -> list[dict[str, Any]]: conditions = ["fact.tenant_id = :tid"] params: dict[str, Any] = {"tid": tenant_id, "lim": max(1, min(int(limit or 100), 500))} @@ -269,6 +885,28 @@ async def list_memory_graph_facts( if status is not None: conditions.append("fact.status = :status") params["status"] = status + graph_filters = self._group_graph_fact_filter_sql( + params, + predicates=predicates, + min_confidence=min_confidence, + acceptance_statuses=acceptance_statuses, + default_accepted_only=default_accepted_only, + from_date=from_date, + to_date=to_date, + ) + conditions.extend(graph_filters) + needs_backing = bool(graph_filters) or order_by_strength + backing_join = ( + "LEFT JOIN plugin_memory_item backing ON backing.id = fact.memory_item_id " + if needs_backing + else "" + ) + order_sql = ( + "ORDER BY COALESCE((NULLIF(backing.value_json, '')::jsonb #>> '{relation,strength}')::float, 0) DESC, " + "fact.updated_at DESC, fact.id DESC" + if order_by_strength + else "ORDER BY fact.updated_at DESC, fact.id DESC" + ) rows = await _exec( "SELECT fact.id, fact.tenant_id, fact.channel, fact.source_key, fact.user_id, " "fact.subject_entity_id, subject.name AS subject_name, fact.predicate, " @@ -282,14 +920,45 @@ async def list_memory_graph_facts( "LEFT JOIN plugin_memory_entity object_entity ON object_entity.id = fact.object_entity_id " "AND object_entity.tenant_id = fact.tenant_id AND object_entity.channel = fact.channel " "AND object_entity.source_key = fact.source_key AND object_entity.user_id = fact.user_id " + f"{backing_join}" f"WHERE {' AND '.join(conditions)} " - "ORDER BY fact.updated_at DESC, fact.id DESC LIMIT :lim", + f"{order_sql} LIMIT :lim", params, ) for row in rows: row["confidence"] = float(row.get("confidence") or 0.0) return rows + async def _list_memory_graph_entities_by_ids( + self, + *, + tenant_id: str, + entity_ids: Iterable[Any], + ) -> list[dict[str, Any]]: + """Fetch the endpoints of already-selected facts so no edge is dropped + just because its entity fell outside the recency-ordered entity page.""" + + ids = sorted(_coerce_int_set(entity_ids)) + if not ids: + return [] + try: + rows = await _exec( + "SELECT entity.id, entity.tenant_id, entity.channel, entity.source_key, " + "entity.user_id, entity.entity_type, entity.name, entity.normalized_name, " + "entity.aliases_json, entity.confidence, entity.status, " + "entity.created_at, entity.updated_at " + "FROM plugin_memory_entity entity " + "WHERE entity.tenant_id = :tid AND entity.id = ANY(:ids)", + {"tid": tenant_id, "ids": ids[:1000]}, + ) + except Exception: + logger.warning("memory.group_graph_entity_fetch_failed", exc_info=True) + return [] + for row in rows or []: + row["aliases"] = _safe_json_loads(row.get("aliases_json"), []) + row["confidence"] = float(row.get("confidence") or 0.0) + return list(rows or []) + async def list_memory_graph_episodes( self, *, @@ -360,11 +1029,18 @@ async def get_group_relationship_graph( for value in str(acceptance_status or "").split(",") if value.strip() } + requested_predicates = [ + value.strip() + for value in str(edge_type or "").split(",") + if value.strip() + ] confidence_floor = ( _clamp_score(min_confidence, default=0.0) if min_confidence is not None else None ) from_dt = _coerce_datetime(from_) to_dt = _coerce_datetime(to) + from_date = from_dt.date().isoformat() if from_dt is not None else None + to_date = to_dt.date().isoformat() if to_dt is not None else None status_filter = None if requested_acceptance - {"accepted"} else "active" generated_from = ["plugin_memory_entity", "plugin_memory_fact", "plugin_memory_episode"] scope = _group_graph_scope( @@ -406,6 +1082,16 @@ async def get_group_relationship_graph( status=status_filter, limit=fetch_limit, ) + # Filters are applied in SQL before the row cap so the strongest matching + # edges come back first instead of the most recently touched rows. + fact_filter_kwargs: dict[str, Any] = { + "predicates": requested_predicates or None, + "min_confidence": confidence_floor, + "acceptance_statuses": sorted(requested_acceptance) or None, + "default_accepted_only": not requested_acceptance, + "from_date": from_date, + "to_date": to_date, + } facts = await self.list_memory_graph_facts( tenant_id=tenant_id, channel=channel, @@ -415,7 +1101,34 @@ async def get_group_relationship_graph( session_ids=scoped_session_ids or None, status=status_filter, limit=fetch_limit, + order_by_strength=True, + **fact_filter_kwargs, ) + total_matching_facts = await self.count_memory_graph_facts( + tenant_id=tenant_id, + channel=channel, + source_key=source_key, + session_ids=scoped_session_ids or None, + status=status_filter, + **fact_filter_kwargs, + ) + # Endpoints of the selected facts must be present even when they fall + # outside the recency-ordered entity page. + known_entity_ids = {row.get("id") for row in entities if row.get("id") is not None} + missing_entity_ids = { + entity_id + for fact in facts + for entity_id in (fact.get("subject_entity_id"), fact.get("object_entity_id")) + if entity_id is not None and entity_id not in known_entity_ids + } + if missing_entity_ids: + entities = [ + *entities, + *await self._list_memory_graph_entities_by_ids( + tenant_id=tenant_id, + entity_ids=missing_entity_ids, + ), + ] episodes = await self.list_memory_graph_episodes( tenant_id=tenant_id, channel=channel, @@ -476,15 +1189,19 @@ async def get_group_relationship_graph( edges: list[dict[str, Any]] = [] connected_node_ids: set[str] = set() + # node_type selects edges that touch a node of that type; the other + # endpoint stays so a person -> tool graph filtered to "tool" still + # shows who is attached to each tool. Unconnected nodes are pruned below. + typed_node_ids: set[str] = set() for entity in entities: node_id = _group_graph_node_id(entity) status = str(entity.get("status") or "active") confidence = _clamp_score(entity.get("confidence")) node_acceptance = _group_graph_acceptance_status(entity) - if node_type and str(entity.get("entity_type") or "") != node_type: - continue if confidence_floor is not None and confidence < confidence_floor: continue + if node_type and str(entity.get("entity_type") or "") == node_type: + typed_node_ids.add(node_id) nodes[node_id] = { "id": node_id, "type": str(entity.get("entity_type") or "thing"), @@ -505,7 +1222,7 @@ async def get_group_relationship_graph( for fact in facts: predicate = str(fact.get("predicate") or "") - if edge_type and predicate != edge_type: + if requested_predicates and predicate not in requested_predicates: continue confidence = _clamp_score(fact.get("confidence")) if confidence_floor is not None and confidence < confidence_floor: @@ -531,9 +1248,15 @@ async def get_group_relationship_graph( continue timestamp = _group_graph_timestamp(fact, "valid_at", "created_at", "updated_at") timestamp_dt = _coerce_datetime(timestamp) - if from_dt is not None and timestamp_dt is not None and timestamp_dt < from_dt: - continue - if to_dt is not None and timestamp_dt is not None and timestamp_dt > to_dt: + quality = _group_graph_edge_quality(backing_item) + # Evidence dates (when the message was observed) win over fact + # timestamps (when the relation was extracted) for time filtering. + first_seen_dt = _coerce_datetime(quality["first_seen_date"]) or timestamp_dt + last_seen_dt = _coerce_datetime(quality["last_seen_date"]) or timestamp_dt + if from_dt is not None and last_seen_dt is not None: + if _end_of_day(last_seen_dt, quality["last_seen_date"]) < from_dt: + continue + if to_dt is not None and first_seen_dt is not None and first_seen_dt > to_dt: continue acceptance_row = backing_item or fact @@ -558,6 +1281,10 @@ async def get_group_relationship_graph( target_node_id = _group_graph_node_id(object_entity) if target_node_id not in nodes: continue + if node_type and not typed_node_ids.intersection( + {source_node_id, target_node_id} + ): + continue else: if node_type and node_type != "value": continue @@ -596,10 +1323,15 @@ async def get_group_relationship_graph( _append_unique_int(memory_item_ids_for_edge, evidence_item_id) source_ref_count = len(set(source_event_ids)) + len(set(memory_item_ids_for_edge)) - quality = _group_graph_edge_quality(backing_item) evidence_dates = quality["evidence_dates"] if not evidence_dates and timestamp: evidence_dates = [str(timestamp)[:10]] + stored_evidence_count = int(quality["evidence_event_count"]) + int( + quality["evidence_observation_count"] + ) + relation_payload = _group_graph_item_value(backing_item).get("relation") + relation_payload = relation_payload if isinstance(relation_payload, dict) else {} + extracted_at = _group_graph_timestamp(fact, "updated_at", "valid_at", "created_at") edge = { "id": _group_graph_edge_id(fact), "source": source_node_id, @@ -610,10 +1342,26 @@ async def get_group_relationship_graph( "acceptance_status": edge_acceptance, "acceptance_score": quality["acceptance_score"], "acceptance_reason": quality["acceptance_reason"], - "evidence_count": max(1, source_ref_count), + "evidence_count": max(1, source_ref_count, stored_evidence_count), "evidence_dates": evidence_dates, - "first_seen": timestamp, - "last_seen": _group_graph_timestamp(fact, "updated_at", "valid_at", "created_at"), + "evidence_day_count": max(len(evidence_dates), int(quality["evidence_day_count"])), + "evidence_source": quality["evidence_source"], + "observation_count": int(quality["evidence_observation_count"]), + # first/last_seen follow the evidence (message dates) when known; + # the extraction timestamp is kept separately. + "first_seen": quality["first_seen_date"] or timestamp, + "last_seen": quality["last_seen_date"] or extracted_at, + "first_seen_date": quality["first_seen_date"], + "last_seen_date": quality["last_seen_date"], + "extracted_at": extracted_at, + "strength": _clamp_score(relation_payload.get("strength"), 0.0) + if relation_payload.get("strength") is not None + else None, + "signals": ( + dict(relation_payload.get("signals")) + if isinstance(relation_payload.get("signals"), dict) + else None + ), "source_event_ids": source_event_ids, "memory_item_ids": memory_item_ids_for_edge, "extraction_method": str((backing_item or {}).get("source_type") or "graph"), @@ -630,7 +1378,12 @@ async def get_group_relationship_graph( if len(edges) >= safe_limit: break - if session_id is not None: + edges = _merge_symmetric_group_edges(edges) + connected_node_ids = { + node_id for edge in edges for node_id in (edge["source"], edge["target"]) + } + + if session_id is not None or node_type: nodes = { node_id: node for node_id, node in nodes.items() if node_id in connected_node_ids } @@ -648,6 +1401,11 @@ async def get_group_relationship_graph( ) node_items = list(nodes.values())[:safe_limit] + visible_edges = edges[:safe_limit] + # The COUNT runs with the same SQL filters, so anything above what is + # shown was cut by the row cap rather than by a filter. + total_edges = max(total_matching_facts, len(visible_edges)) + truncated = len(facts) >= fetch_limit or total_matching_facts > len(visible_edges) return { "schema": { "version": GROUP_GRAPH_SCHEMA_VERSION, @@ -657,10 +1415,17 @@ async def get_group_relationship_graph( "scope": scope, "filters": filters, "nodes": node_items, - "edges": edges[:safe_limit], + "edges": visible_edges, "counts": { "nodes": len(node_items), - "edges": len(edges[:safe_limit]), + "edges": len(visible_edges), + }, + "page": { + "limit": safe_limit, + "total": total_edges, + "truncated": bool(truncated), + "order": "strength_desc", + "next_cursor": None, }, "generated_from": generated_from, } @@ -957,6 +1722,35 @@ async def get_group_relationship_edge_evidence( memory_item_ids=memory_item_ids, event_ids=event_ids, ) + quality = _group_graph_edge_quality(backing_item) + observation_ids = _group_graph_item_observation_ids(backing_item) + observations = ( + await self._get_group_observation_evidence_by_ids(observation_ids) + if observation_ids + else [] + ) + payload["evidence_ids"]["observation_ids"] = observation_ids[:200] + payload["evidence_counts"]["observations"] = len(observation_ids) + payload["evidence_counts"]["evidence_days"] = quality["evidence_day_count"] + payload["observations"] = observations + payload["evidence_source"] = quality["evidence_source"] + payload["evidence_dates"] = quality["evidence_dates"] + payload["judgement"] = _group_relation_judgement(backing_item) + edge_payload = payload.get("edge") + if isinstance(edge_payload, dict): + edge_payload["extracted_at"] = edge_payload.get("first_seen") + if quality["first_seen_date"]: + edge_payload["first_seen"] = quality["first_seen_date"] + if quality["last_seen_date"]: + edge_payload["last_seen"] = quality["last_seen_date"] + observed = [ + str(entry.get("occurred_at") or "") + for entry in observations + if entry.get("occurred_at") + ] + if observed: + edge_payload["first_observed_at"] = min(observed) + edge_payload["last_observed_at"] = max(observed) if include_raw: raw_items = await self._get_memory_items_by_ids(memory_item_ids) payload["raw"] = { @@ -967,6 +1761,57 @@ async def get_group_relationship_edge_evidence( } return payload + async def _get_group_observation_evidence_by_ids( + self, + observation_ids: Iterable[Any], + *, + limit: int = 200, + ) -> list[dict[str, Any]]: + """Return display-safe metadata for group observations used as evidence. + + Only ids, the session, the sender's group nickname and the timestamp are + exposed; message content never leaves this method. + """ + + ids = sorted(_coerce_int_set(observation_ids))[: max(1, min(int(limit or 200), 500))] + if not ids: + return [] + try: + rows = await _exec( + "SELECT id, session_id, sender_name, occurred_ts " + "FROM plugin_wxbot_group_observations " + "WHERE id = ANY(:ids) " + "ORDER BY occurred_ts ASC, id ASC", + {"ids": ids}, + ) + except Exception: + logger.warning("memory.group_graph_observation_evidence_failed", exc_info=True) + return [] + evidence: list[dict[str, Any]] = [] + for row in rows or []: + occurred = _safe_int(row.get("occurred_ts"), 0) + sender_name = _normalize_line(_sanitize_db_text(row.get("sender_name")))[:80] + label = ( + sender_name + if sender_name and not _group_graph_label_is_technical(sender_name) + else "" + ) + evidence.append( + { + "id": _safe_int(row.get("id"), 0), + "session_id": str(row.get("session_id") or ""), + "sender_label": label or None, + "sender_is_technical": not label, + "occurred_at": ( + datetime.fromtimestamp(occurred, UTC).replace(tzinfo=None).isoformat() + if occurred > 0 + else None + ), + "source": EVIDENCE_SOURCE_OBSERVATION, + } + ) + return evidence + def _build_group_relationship_windows( self, event_rows: list[dict[str, Any]], @@ -996,6 +1841,12 @@ def _build_group_relationship_windows( break transcript_lines.append(line) prompt_chars += len(line) + 1 + observation_row_ids = { + int(row.get("id") or 0) + for row in rows + if str(row.get("_graph_source") or "") == EVIDENCE_SOURCE_OBSERVATION + and int(row.get("id") or 0) + } windows.append( { "index": index, @@ -1005,6 +1856,14 @@ def _build_group_relationship_windows( "last_event_id": event_ids[-1] if event_ids else None, "sender_ids": sender_ids, "transcript": "\n".join(transcript_lines), + "source": ( + EVIDENCE_SOURCE_OBSERVATION + if observation_row_ids and len(observation_row_ids) == len(event_ids) + else EVIDENCE_SOURCE_MIXED + if observation_row_ids + else EVIDENCE_SOURCE_MEMORY_EVENT + ), + "observation_ids": observation_row_ids, } ) return windows @@ -1021,38 +1880,80 @@ def _extract_addressed_participant_ids( body: str, *, participants: Iterable[str], + directory: GroupMemberDirectory | None = None, ) -> list[str]: + """Resolve text ``@`` mentions to participant ids. + + WeChat renders mentions as ``@昵称`` (followed by U+2005), so the text + is matched against the member directory's nicknames as well as against + raw participant ids. + """ + if not body: return [] participant_set = {self._normalize_group_participant_id(item) for item in participants} participant_set.discard("") - if not participant_set: + if not participant_set and directory is None: return [] targets: list[str] = [] - for mention in re.findall(r"@([^\s\u2005\u00a0::,,;;]+)", body): - normalized = self._normalize_group_participant_id(mention) - if normalized in participant_set and normalized not in targets: + def add_target(value: str | None) -> None: + normalized = self._normalize_group_participant_id(value) + if normalized and normalized not in targets: targets.append(normalized) + for mention in _MENTION_TOKEN_RE.findall(body): + normalized = self._normalize_group_participant_id(mention) + if normalized in participant_set: + add_target(normalized) + continue + if directory is not None: + add_target(directory.resolve_name(mention)) + stripped = body.strip() for participant in sorted(participant_set, key=len, reverse=True): if participant in targets: continue escaped = re.escape(participant) if re.search(rf"(^|[\s@]){escaped}([::,,\s]|$)", stripped): - targets.append(participant) + add_target(participant) continue if re.search(rf"(回复|回|问|告诉|建议)\s*@?{escaped}", stripped): - targets.append(participant) + add_target(participant) return targets[:5] def _build_deterministic_group_window_candidates( self, window: dict[str, Any], + *, + directory: GroupMemberDirectory | None = None, + co_participation_edges: bool | None = None, ) -> list[dict[str, Any]]: + """Rule-based relation candidates for one window. + + Signals, strongest first: + + * quoted reply (``metadata_json.quote``) → ``replied_to`` + * ``@`` mention (``metadata_json.at_wxids`` or ``@昵称`` text) → ``addressed`` + * explicit "回复/回/接着/关于" prefix right after another member → ``replied_to`` + * same-window co-participation → ``co_participated`` (opt-in only; in a + busy group it means little more than "both were online") + + Every candidate carries ``signals`` counts so acceptance and strength can + be computed from what was actually observed rather than a flat confidence. + """ + rows = window.get("rows") if isinstance(window.get("rows"), list) else [] + if co_participation_edges is None: + co_participation_edges = bool( + getattr( + getattr(self, "settings", None), + "memory_group_graph_co_participation_edges", + False, + ) + ) + local_directory = directory or GroupMemberDirectory() events: list[dict[str, Any]] = [] participants: list[str] = [] for row in rows: @@ -1063,11 +1964,23 @@ def _build_deterministic_group_window_candidates( event_id = next(iter(_coerce_int_set([row.get("id")])), None) if event_id is None: continue + observation = ( + row.get("_observation") if isinstance(row.get("_observation"), dict) else {} + ) + local_directory.add_sender(sender_id, observation.get("sender_name")) if sender_id not in participants: participants.append(sender_id) - events.append({"id": event_id, "sender": sender_id, "body": str(body or "")}) + events.append( + { + "id": event_id, + "sender": sender_id, + "body": str(body or ""), + "observation": observation, + } + ) candidates_by_key: dict[tuple[str, str, str], dict[str, Any]] = {} + unresolved_targets = 0 def add_candidate( *, @@ -1077,6 +1990,8 @@ def add_candidate( confidence: float, evidence_event_ids: Iterable[Any], reason: str, + signal: str, + signal_event_id: int, ) -> None: subject = self._normalize_group_participant_id(subject) object_value = self._normalize_group_participant_id(object_value) @@ -1097,7 +2012,12 @@ def add_candidate( evidence_ids, max_items=200, ) + existing["signal_evidence"] = _merge_signal_evidence( + existing.get("signal_evidence"), {signal: [signal_event_id]} + ) + existing["signals"] = _signals_from_evidence(existing["signal_evidence"]) return + signal_evidence = _merge_signal_evidence({signal: [signal_event_id]}) candidates_by_key[key] = { "subject": subject, "subject_type": "person", @@ -1108,26 +2028,79 @@ def add_candidate( "evidence_event_ids": evidence_ids, "reason": reason, "extraction_method": DETERMINISTIC_GROUP_WINDOW_SOURCE_TYPE, + "signals": _signals_from_evidence(signal_evidence), + "signal_evidence": signal_evidence, } for index, event in enumerate(events): sender = str(event["sender"]) event_id = int(event["id"]) + observation = event.get("observation") or {} + bot_wxid = self._normalize_group_participant_id(observation.get("bot_wxid")) + body = str(event.get("body") or "").strip() + + # 1. Quoted reply: the platform tells us exactly whose message this answers. + quote_from = str(observation.get("quote_from") or "") + quote_name = str(observation.get("quote_sender_name") or "") + if (quote_from or quote_name) and self._normalize_group_participant_id( + quote_from + ) != bot_wxid: + target = local_directory.resolve_id(quote_from, fallback_name=quote_name) + if target and target != bot_wxid: + add_candidate( + subject=sender, + predicate="replied_to", + object_value=target, + confidence=QUOTE_REPLY_CONFIDENCE, + evidence_event_ids=[event_id], + reason="deterministic_quote_reply", + signal=SIGNAL_QUOTE, + signal_event_id=event_id, + ) + elif not target: + unresolved_targets += 1 + + # 2. @ mentions: structured ids first, then nicknames in the text. + mention_targets: list[str] = [] + for raw_id in observation.get("at_wxids") or []: + if self._normalize_group_participant_id(raw_id) == bot_wxid: + continue + target = local_directory.resolve_id(raw_id) + if target and target != bot_wxid: + if target not in mention_targets: + mention_targets.append(target) + elif not target: + unresolved_targets += 1 + metadata_mentions = set(mention_targets) for target in self._extract_addressed_participant_ids( - str(event.get("body") or ""), + body, participants=participants, + directory=local_directory, ): + if target != bot_wxid and target not in mention_targets: + mention_targets.append(target) + for target in mention_targets[:5]: add_candidate( subject=sender, predicate="addressed", object_value=target, - confidence=0.72, + confidence=( + MENTION_METADATA_CONFIDENCE + if target in metadata_mentions + else MENTION_TEXT_CONFIDENCE + ), evidence_event_ids=[event_id], - reason="deterministic_addressed_participant", + reason=( + "deterministic_at_mention_metadata" + if target in metadata_mentions + else "deterministic_addressed_participant" + ), + signal=SIGNAL_MENTION, + signal_event_id=event_id, ) + # 3. Explicit reply prefix right after somebody else spoke. previous = events[index - 1] if index > 0 else None - body = str(event.get("body") or "").strip() if ( previous and previous.get("sender") != sender @@ -1137,11 +2110,18 @@ def add_candidate( subject=sender, predicate="replied_to", object_value=str(previous.get("sender") or ""), - confidence=0.62, + confidence=PREFIX_REPLY_CONFIDENCE, evidence_event_ids=[previous.get("id"), event_id], reason="deterministic_adjacent_reply_window", + signal=SIGNAL_PREFIX_REPLY, + signal_event_id=event_id, ) + window["unresolved_targets"] = unresolved_targets + if not co_participation_edges: + return list(candidates_by_key.values()) + + # 4. Legacy co-participation pairs, only when explicitly enabled. participant_counts = { participant: sum(1 for event in events if event.get("sender") == participant) for participant in participants @@ -1157,15 +2137,57 @@ def add_candidate( subject=subject, predicate="co_participated", object_value=object_value, - confidence=0.45, + confidence=CO_PARTICIPATION_CONFIDENCE, evidence_event_ids=evidence_ids, reason="deterministic_same_window_participation", + signal=SIGNAL_CO_PARTICIPATION, + # One co-participation observation per window. + signal_event_id=int(evidence_ids[0]), ) if len(candidates_by_key) >= GROUP_WINDOW_DETERMINISTIC_MAX_PAIRS: return list(candidates_by_key.values()) return list(candidates_by_key.values()) + async def _load_group_member_directory( + self, + *, + tenant_id: str, + session_ids: Iterable[str], + event_rows: Iterable[dict[str, Any]], + ) -> GroupMemberDirectory: + """Build the id/nickname directory for one group from the day's rows plus + the membership table, so quote/@ targets resolve to sender ids.""" + + directory = GroupMemberDirectory() + for row in event_rows: + sender_id, _body = _split_group_event_text(row.get("user_text")) + observation = ( + row.get("_observation") if isinstance(row.get("_observation"), dict) else {} + ) + directory.add_sender(sender_id or row.get("user_id"), observation.get("sender_name")) + rooms = [ + _normalize_line(_sanitize_db_text(session_id)) + for session_id in session_ids + if _is_group_session_id(session_id) + ] + if not rooms: + return directory + try: + member_rows = await _exec( + "SELECT user_wxid, user_name " + "FROM plugin_wxbot_group_membership " + "WHERE tenant_id = :tid AND session_id = ANY(:sids) " + "AND user_wxid <> ''", + {"tid": str(tenant_id or "").strip(), "sids": rooms}, + ) + except Exception: + logger.warning("memory.group_graph_member_directory_failed", exc_info=True) + member_rows = [] + for row in member_rows or []: + directory.add_member(row.get("user_wxid"), row.get("user_name")) + return directory + async def _extract_group_relationship_window_candidates( self, *, @@ -1179,13 +2201,39 @@ async def _extract_group_relationship_window_candidates( llm_service = getattr(self.graph_extractor, "llm_service", None) if llm_service is None: return {"relations": []} + allowed_predicates = [ + predicate + for predicate in GROUP_GRAPH_EDGE_TYPES + if predicate not in LLM_EXCLUDED_PREDICATES + ] system = ( "Extract conservative group-chat relationship candidates from a bounded transcript. " "Return JSON only with key relations. Each relation must include subject, subject_type, " "predicate, object, object_type, confidence, evidence_event_ids, and optional reason. " "Allowed predicates: " - + ", ".join(GROUP_GRAPH_EDGE_TYPES) - + ". Evidence ids must come from the provided event ids. Do not quote raw messages." + + ", ".join(allowed_predicates) + + ". Evidence ids must come from the provided event ids. Do not quote raw messages. " + "Rules: (1) subject is always a participant id exactly as written in the transcript; " + "a person object must also be a participant id. " + "(2) Only report a relation when at least two different messages support it and list " + "each supporting message id in evidence_event_ids; skip one-off remarks. " + "(3) Objects that are not people are short canonical terms, not sentences: " + "products, models, services and software are object_type tool " + "(e.g. Claude, DeepSeek, 阿里云); named efforts are project; everything else is topic. " + "Write terms in the language the group uses (Chinese chat -> Chinese term), keep the " + "common spelling of product names, at most 12 Chinese characters or 4 English words, " + "and reuse one spelling for the same term. " + "(4) Do not emit 'the group', '大家' or the chat itself as an object, and do not report " + "who merely talked in the same time span; direct replies and @-mentions are already " + "tracked, so prefer asked/answered/requested/provided_resource/collaborated_with between " + "people and interested_in/reported_issue/works_on/maintains/tested/fixed_issue/asked " + "between a person and a term. " + "(5) interested_in means the person wants, likes, uses or asks how to get the thing. " + "Mocking it, criticizing it, gossiping about it, or discussing whether this system " + "labelled it correctly is mentioned, never interested_in. " + "(6) reason is one short sentence in the group's language that names the concrete " + "behaviour (what was asked, compared, complained about), so a reviewer can find the " + "messages; never quote a message verbatim. Return an empty list rather than guessing." ) payload = { "date": target_date, @@ -1193,10 +2241,21 @@ async def _extract_group_relationship_window_candidates( "event_ids": event_ids, "transcript": transcript, } + # Structured extraction over a short transcript is a fast-model task: on + # the production gateway the reasoning tier needs >60s per window while + # the non-reasoning tier answers in 10-16s with valid JSON. + model_tier = str( + getattr( + getattr(self, "settings", None), + "memory_group_graph_llm_model_tier", + GROUP_WINDOW_LLM_MODEL_TIER_DEFAULT, + ) + or GROUP_WINDOW_LLM_MODEL_TIER_DEFAULT + ).strip() request = ChatRequest( tenant_id=tenant_id, trace_id=trace_id, - model_tier="tier-3", + model_tier=model_tier, messages=[ChatMessage(role=Role.USER, content=json.dumps(payload, ensure_ascii=False))], system=system, temperature=0.0, @@ -1216,11 +2275,22 @@ def _validate_group_window_candidate( raw_candidate: Any, *, allowed_event_ids: set[int], + participants: Iterable[str] | None = None, + directory: GroupMemberDirectory | None = None, ) -> dict[str, Any] | None: + """Validate one LLM-proposed relation. + + Besides predicate/evidence checks, ``person`` endpoints must resolve to a + real participant (window sender or directory member). A subject that does + not resolve is dropped; an unresolvable ``person`` object is kept as a + ``topic`` for mention-like predicates and dropped otherwise, so the model + cannot mint phantom members out of terms it misclassified. + """ + if not isinstance(raw_candidate, dict): return None predicate = str(raw_candidate.get("predicate") or "").strip().lower() - if predicate not in GROUP_GRAPH_EDGE_TYPES: + if predicate not in GROUP_GRAPH_EDGE_TYPES or predicate in LLM_EXCLUDED_PREDICATES: return None subject = _normalize_line(str(raw_candidate.get("subject") or ""))[:200] object_value = _normalize_line(str(raw_candidate.get("object") or ""))[:200] @@ -1228,7 +2298,7 @@ def _validate_group_window_candidate( return None evidence_ids = sorted(_coerce_int_set(raw_candidate.get("evidence_event_ids") or [])) evidence_ids = [event_id for event_id in evidence_ids if event_id in allowed_event_ids] - if not evidence_ids: + if len(evidence_ids) < GROUP_RELATION_MIN_LLM_WINDOW_EVIDENCE: return None subject_type = str(raw_candidate.get("subject_type") or "person").strip().lower() object_type = str(raw_candidate.get("object_type") or "person").strip().lower() @@ -1236,6 +2306,46 @@ def _validate_group_window_candidate( subject_type = "person" if object_type not in GROUP_GRAPH_NODE_TYPES: object_type = "person" + if subject_type == "group" or object_type == "group": + return None + if object_value.strip().lower() in LLM_GROUP_PSEUDO_OBJECTS: + return None + + participant_set = { + self._normalize_group_participant_id(item) for item in (participants or []) + } + participant_set.discard("") + can_resolve = bool(participant_set) or directory is not None + + def resolve_person(value: str) -> str | None: + normalized = self._normalize_group_participant_id(value) + if normalized in participant_set: + return normalized + if directory is not None: + return directory.resolve_id(normalized) or directory.resolve_name(normalized) + return None + + if can_resolve and subject_type == "person": + resolved_subject = resolve_person(subject) + if not resolved_subject: + return None + subject = resolved_subject + if can_resolve and object_type == "person": + resolved_object = resolve_person(object_value) + if resolved_object: + object_value = resolved_object + elif predicate in LLM_PERSON_TO_TOPIC_PREDICATES and not _looks_like_participant_id( + object_value + ): + object_type = "topic" + else: + # An unknown id-shaped "person" is a hallucinated member, not a term. + return None + if subject_type == object_type == "person" and subject == object_value: + return None + if object_type != "person" and not _is_usable_llm_term(object_value): + return None + signal_evidence = _merge_signal_evidence({SIGNAL_LLM: evidence_ids}) return { "subject": subject, "subject_type": subject_type, @@ -1245,6 +2355,8 @@ def _validate_group_window_candidate( "confidence": _clamp_score(raw_candidate.get("confidence"), 0.5), "evidence_event_ids": evidence_ids, "reason": _normalize_line(str(raw_candidate.get("reason") or ""))[:240], + "signals": _signals_from_evidence(signal_evidence), + "signal_evidence": signal_evidence, } def _parse_group_window_candidates( @@ -1252,6 +2364,8 @@ def _parse_group_window_candidates( raw_payload: Any, *, allowed_event_ids: set[int], + participants: Iterable[str] | None = None, + directory: GroupMemberDirectory | None = None, ) -> tuple[list[dict[str, Any]], int]: try: payload = ( @@ -1270,7 +2384,10 @@ def _parse_group_window_candidates( skipped = 0 for raw_candidate in raw_candidates: candidate = self._validate_group_window_candidate( - raw_candidate, allowed_event_ids=allowed_event_ids + raw_candidate, + allowed_event_ids=allowed_event_ids, + participants=participants, + directory=directory, ) if candidate is None: skipped += 1 @@ -1304,6 +2421,10 @@ def _merge_group_window_candidates( candidate.get("evidence_event_ids"), max_items=200, ) + existing["signal_evidence"] = _merge_signal_evidence( + existing.get("signal_evidence"), candidate.get("signal_evidence") + ) + existing["signals"] = _signals_from_evidence(existing["signal_evidence"]) if not existing.get("reason") and candidate.get("reason"): existing["reason"] = candidate.get("reason") return list(merged.values()) @@ -1328,11 +2449,16 @@ async def _apply_group_relationship_window_candidate( object_value=candidate["object"], ) evidence_event_ids = _merge_int_lists(candidate.get("evidence_event_ids"), max_items=200) + evidence_observation_ids = _merge_int_lists( + candidate.get("evidence_observation_ids"), max_items=200 + ) relation_payload = dict(candidate) relation_payload["evidence_event_ids"] = evidence_event_ids + relation_payload["evidence_observation_ids"] = evidence_observation_ids evidence_dates = [target_date] existing_item: dict[str, Any] | None = None existing_acceptance: dict[str, Any] = {} + existing_relation: dict[str, Any] = {} existing_items = await self._find_memory_item_by_normalized_key( tenant_id=tenant_id, @@ -1367,12 +2493,19 @@ async def _apply_group_relationship_window_candidate( candidate.get("evidence_event_ids"), max_items=200, ) + evidence_observation_ids = _merge_int_lists( + existing_relation.get("evidence_observation_ids"), + existing_value.get("source_observation_ids"), + candidate.get("evidence_observation_ids"), + max_items=200, + ) relation_payload = {**existing_relation, **candidate} relation_payload["confidence"] = max( _clamp_score(existing_relation.get("confidence"), 0.0), _clamp_score(candidate.get("confidence"), 0.0), ) relation_payload["evidence_event_ids"] = evidence_event_ids + relation_payload["evidence_observation_ids"] = evidence_observation_ids existing_dates = existing_value.get("evidence_dates") if not isinstance(existing_dates, list): existing_dates = [] @@ -1395,23 +2528,73 @@ async def _apply_group_relationship_window_candidate( DETERMINISTIC_GROUP_WINDOW_SOURCE_TYPE, }: relation_source_type = LLM_GROUP_WINDOW_SOURCE_TYPE - # Keep a human reject/accept. Otherwise auto-accept so the graph - # and recall do not wait on a manual queue. + + # Accumulate what was actually observed. Legacy items carry no signal + # counts, so infer one from their reason/source before merging. + candidate_signal_evidence = candidate.get("signal_evidence") + if not isinstance(candidate_signal_evidence, dict): + # Callers that only pass counts get one occurrence per flagged signal, + # anchored on the first evidence id so re-runs stay idempotent. + anchor_ids = sorted( + _coerce_int_set(candidate.get("evidence_event_ids") or []) + | _coerce_int_set(candidate.get("evidence_observation_ids") or []) + ) + candidate_signal_evidence = { + key: anchor_ids[:1] + for key, count in (candidate.get("signals") or {}).items() + if _safe_int(count, 0) > 0 and anchor_ids + } + signal_evidence = _merge_signal_evidence( + existing_relation.get("signal_evidence"), + candidate_signal_evidence, + ) + signals = _signals_from_evidence(signal_evidence) + # Items written before signal evidence existed contribute one known + # occurrence per inferred signal; never less than what the ids show. + if existing_item is not None and not isinstance( + existing_relation.get("signal_evidence"), dict + ): + legacy = ( + existing_relation.get("signals") + if isinstance(existing_relation.get("signals"), dict) + else _infer_legacy_group_signals(existing_relation, relation_source_type) + ) + for key in GROUP_SIGNAL_KEYS: + signals[key] = max(signals[key], max(0, _safe_int(legacy.get(key), 0))) + if not any(signals.values()): + signals = _merge_group_signals( + signals, _infer_legacy_group_signals(candidate, relation_source_type) + ) + day_count = len(evidence_dates) + strength = _group_relation_strength(signals, day_count) + relation_payload["signals"] = signals + relation_payload["signal_evidence"] = signal_evidence + relation_payload["strength"] = strength + + # Human accept/reject decisions stick. Everything else follows the + # deterministic policy, which may promote a needs_review relation to + # accepted once it has repeated across days. prior_acceptance_status = str( existing_acceptance.get("status") or (existing_item or {}).get("acceptance_status") or "" ).strip().lower() - auto_accept = bool(getattr(self.settings, "memory_group_graph_auto_accept", True)) + auto_accept = bool( + getattr(getattr(self, "settings", None), "memory_group_graph_auto_accept", True) + ) + policy_status, policy_reason = _group_relation_acceptance_decision( + signals, + day_count=day_count, + auto_accept=auto_accept, + ) if prior_acceptance_status in {"accepted", "rejected"}: acceptance_status = prior_acceptance_status + acceptance_reason = str( + existing_acceptance.get("reason") or relation_payload.get("reason") or policy_reason + )[:80] else: - acceptance_status = "accepted" if auto_accept else "needs_review" - acceptance_reason = str( - existing_acceptance.get("reason") - or relation_payload.get("reason") - or ("group_window_auto_accept" if acceptance_status == "accepted" else "group_window_relation") - )[:80] + acceptance_status = policy_status + acceptance_reason = policy_reason acceptance_payload = { **existing_acceptance, "status": acceptance_status, @@ -1424,10 +2607,17 @@ async def _apply_group_relationship_window_candidate( _clamp_score(existing_acceptance.get("extraction_confidence"), 0.0), _clamp_score(relation_payload.get("confidence"), 0.0), ), + "strength": strength, + "signals": signals, + "day_count": day_count, + "policy": policy_reason, } if acceptance_status == "accepted" and prior_acceptance_status != "accepted": acceptance_payload.setdefault("reviewed_by", "system/auto") - acceptance_payload.setdefault("review_reason", "group_window_auto_accept") + acceptance_payload.setdefault("review_reason", policy_reason) + evidence_source = _group_graph_evidence_source( + evidence_event_ids, evidence_observation_ids + ) value_payload = { "kind": "group_window_relation", "date": target_date, @@ -1438,9 +2628,12 @@ async def _apply_group_relationship_window_candidate( "index": window["index"], "first_event_id": window["first_event_id"], "last_event_id": window["last_event_id"], + "source": str(window.get("source") or EVIDENCE_SOURCE_MEMORY_EVENT), }, "relation": relation_payload, "source_event_ids": evidence_event_ids, + "source_observation_ids": evidence_observation_ids, + "evidence_source": evidence_source, "acceptance": acceptance_payload, } is_group_history_scope = user_id == GROUP_HISTORY_USER_ID_SCOPE @@ -1463,6 +2656,7 @@ async def _apply_group_relationship_window_candidate( status=( str(existing_item.get("status") or "pending") if existing_item is not None + and acceptance_status == prior_acceptance_status and acceptance_status in {"accepted", "rejected"} else _memory_status_for_acceptance(acceptance_status, sensitivity="normal") ), @@ -1494,7 +2688,19 @@ async def run_group_relationship_window_extraction( dry_run: bool = False, include_llm: bool = True, llm_timeout_seconds: int | None = None, + source: str | None = None, + llm_mode: str | None = None, + deterministic: bool = True, ) -> dict[str, Any]: + """Extract relations for up to ``max_windows`` windows of one day. + + ``llm_mode``: ``inline`` calls the LLM per window with a full + ``llm_timeout_seconds``; ``enqueue`` writes one durable job per window + instead, so the cheap deterministic pass never waits on the model and + failed LLM windows are retried by ``run_group_window_llm_jobs``. + ``deterministic=False`` skips the rule layer (used by that retry path). + """ + session_id = str(session_id or "").strip() if not session_id: raise RuntimeError("session_id required") @@ -1506,8 +2712,13 @@ async def run_group_relationship_window_extraction( effective_max_windows = _clamp_int(max_windows, 1, minimum=1, maximum=10) effective_cursor = max(0, int(cursor_event_id or 0)) effective_llm_timeout = _clamp_int( - llm_timeout_seconds, 60, minimum=1, maximum=180 + llm_timeout_seconds, + self._group_window_llm_timeout_default(), + minimum=1, + maximum=GROUP_WINDOW_LLM_TIMEOUT_MAX, ) + effective_llm_mode = _normalize_llm_mode(llm_mode) + effective_source = _normalize_evidence_source(source) user_id_scope, user_id_auto = _group_history_user_scope(session_id, user_id) if not user_id_scope: raise RuntimeError("user_id required") @@ -1527,14 +2738,23 @@ async def run_group_relationship_window_extraction( ), cursor_event_id=effective_cursor, limit=fetch_limit, + source=effective_source, ) more_remain = len(event_rows) > effective_window_size * effective_max_windows event_rows = event_rows[: effective_window_size * effective_max_windows] observation_event_ids = { int(row.get("id") or 0) for row in event_rows - if str(row.get("_graph_source") or "") == "observation" and int(row.get("id") or 0) + if str(row.get("_graph_source") or "") == EVIDENCE_SOURCE_OBSERVATION + and int(row.get("id") or 0) } + resolved_source = ( + EVIDENCE_SOURCE_OBSERVATION + if observation_event_ids and len(observation_event_ids) == len(event_rows) + else EVIDENCE_SOURCE_MIXED + if observation_event_ids + else EVIDENCE_SOURCE_MEMORY_EVENT + ) windows = self._build_group_relationship_windows( event_rows, window_size=effective_window_size ) @@ -1548,9 +2768,13 @@ async def run_group_relationship_window_extraction( "candidate_count": 0, "applied_count": 0, "skipped_count": 0, + "signal_counts": _empty_group_signals(), + "unresolved_targets": 0, } for window in windows ] + signal_totals = _empty_group_signals() + unresolved_total = 0 next_cursor_event_id = max( [effective_cursor, *[int(window["last_event_id"] or 0) for window in windows]] ) @@ -1574,7 +2798,13 @@ async def run_group_relationship_window_extraction( "dry_run": bool(dry_run), "include_llm": bool(include_llm), "llm_timeout_seconds": effective_llm_timeout, + "llm_mode": effective_llm_mode, + "deterministic": bool(deterministic), + "source": effective_source, }, + "source": resolved_source, + "llm_jobs_enqueued": 0, + "llm_failures": 0, "windows": window_summaries, "totals": { "events": sum(len(window["event_ids"]) for window in windows), @@ -1601,17 +2831,71 @@ async def run_group_relationship_window_extraction( and self.graph_extractor.config.enabled and self.graph_extractor.llm_service is not None ) + llm_inline = llm_available and effective_llm_mode == LLM_MODE_INLINE + llm_enqueue = llm_available and effective_llm_mode == LLM_MODE_ENQUEUE total_candidates = 0 total_applied = 0 total_skipped = 0 - generated_from = ["plugin_memory_event", "deterministic_window_participants"] - if llm_available: + llm_jobs_enqueued = 0 + llm_jobs_seen = 0 + llm_failures = 0 + generated_from = [ + ( + "plugin_wxbot_group_observations" + if resolved_source == EVIDENCE_SOURCE_OBSERVATION + else "plugin_memory_event" + ), + ] + if resolved_source == EVIDENCE_SOURCE_MIXED: + generated_from.append("plugin_wxbot_group_observations") + if deterministic: + generated_from.append("deterministic_window_participants") + if llm_inline: generated_from.append("llm_window_extractor") + if llm_enqueue: + generated_from.append("llm_window_jobs") + directory = ( + await self._load_group_member_directory( + tenant_id=tenant_id, + session_ids=await self._resolve_group_graph_session_ids( + tenant_id=tenant_id, + session_id=session_id, + ) + or [session_id], + event_rows=event_rows, + ) + if (deterministic or llm_inline) + else None + ) for window, summary in zip(windows, window_summaries, strict=True): - deterministic_candidates = self._build_deterministic_group_window_candidates(window) + deterministic_candidates = ( + self._build_deterministic_group_window_candidates( + window, + directory=directory, + ) + if deterministic + else [] + ) + summary["unresolved_targets"] = int(window.get("unresolved_targets") or 0) + unresolved_total += summary["unresolved_targets"] llm_candidates: list[dict[str, Any]] = [] - if llm_available: + if llm_enqueue: + enqueued = await self._enqueue_group_window_llm_job( + tenant_id=tenant_id, + channel=channel, + source_key=source_key, + session_id=session_id, + target_date=target_date, + source=str(window.get("source") or resolved_source), + window=window, + window_size=effective_window_size, + ) + if enqueued: + llm_jobs_enqueued += 1 + llm_jobs_seen += 1 + summary["llm_job"] = "enqueued" if enqueued else "exists" + if llm_inline: try: raw_payload = await asyncio.wait_for( self._extract_group_relationship_window_candidates( @@ -1636,69 +2920,595 @@ async def run_group_relationship_window_extraction( error=_truncate_error(exc), ) summary["skipped_count"] += 1 + summary["llm_failed"] = True total_skipped += 1 + llm_failures += 1 else: llm_candidates, skipped = self._parse_group_window_candidates( raw_payload, allowed_event_ids=set(window["event_ids"]), + participants=window.get("sender_ids") or [], + directory=directory, ) summary["skipped_count"] += skipped + summary["llm_candidates"] = len(llm_candidates) total_skipped += skipped candidates = self._merge_group_window_candidates( deterministic_candidates, llm_candidates, ) if not candidates: - summary["skipped_count"] += 1 - total_skipped += 1 + if not summary.get("llm_job"): + # Nothing found and nothing deferred: the window is done. + summary["skipped_count"] += 1 + total_skipped += 1 + continue + summary["candidate_count"] = len(candidates) + total_candidates += len(candidates) + # Count what this run actually saw, rule signals and model claims alike. + for candidate in candidates: + for key, count in (candidate.get("signals") or {}).items(): + if key in signal_totals: + summary["signal_counts"][key] += int(count or 0) + signal_totals[key] += int(count or 0) + for candidate in candidates: + if observation_event_ids: + # Observation ids are not memory-event ids; keep them as their + # own evidence list instead of throwing the trail away. + event_evidence, observation_evidence = _split_window_evidence_ids( + candidate.get("evidence_event_ids") or [], + observation_event_ids, + ) + candidate = { + **candidate, + "evidence_event_ids": event_evidence, + "evidence_observation_ids": _merge_int_lists( + candidate.get("evidence_observation_ids"), + observation_evidence, + max_items=200, + ), + } + item = await self._apply_group_relationship_window_candidate( + tenant_id=tenant_id, + channel=channel, + source_key=source_key, + user_id=user_id_scope, + session_id=session_id, + target_date=target_date, + window=window, + candidate=candidate, + ) + if not item or item.get("id") is None: + summary["skipped_count"] += 1 + total_skipped += 1 + continue + summary["applied_count"] += 1 + total_applied += 1 + await self._refresh_legacy_cache_for_item_scope(item) + await self._sync_memory_graph_for_item_safe(item) + await self._sync_memory_vector_for_item_safe(item) + + if total_applied == 0 and total_candidates == 0 and llm_jobs_seen == 0: + base_payload["status"] = "skipped" + if not llm_available: + base_payload["skipped_reason"] = "no_deterministic_candidates" + else: + base_payload["status"] = "completed" if total_skipped == 0 else "partial" + base_payload["llm_jobs_enqueued"] = llm_jobs_enqueued + base_payload["llm_failures"] = llm_failures + base_payload["generated_from"] = generated_from + base_payload["totals"] = { + "events": sum(len(window["event_ids"]) for window in windows), + "windows": len(windows), + "candidates": total_candidates, + "applied": total_applied, + "skipped": total_skipped, + } + base_payload["signal_counts"] = signal_totals + base_payload["unresolved_targets"] = unresolved_total + return base_payload + + def _group_window_llm_timeout_default(self) -> int: + return _clamp_int( + getattr( + getattr(self, "settings", None), + "memory_group_graph_llm_timeout_seconds", + GROUP_WINDOW_LLM_TIMEOUT_DEFAULT, + ), + GROUP_WINDOW_LLM_TIMEOUT_DEFAULT, + minimum=GROUP_WINDOW_LLM_TIMEOUT_MIN, + maximum=GROUP_WINDOW_LLM_TIMEOUT_MAX, + ) + + async def _enqueue_group_window_llm_job( + self, + *, + tenant_id: str, + channel: str, + source_key: str, + session_id: str, + target_date: str, + source: str, + window: dict[str, Any], + window_size: int, + ) -> bool: + """Durably record that a window still needs its LLM pass. + + Idempotent per (scope, date, source, window bounds): a window whose job + already exists (pending, running, succeeded or dead) is not re-queued. + Returns True when a new job row was created. + """ + + first_event_id = int(window.get("first_event_id") or 0) + last_event_id = int(window.get("last_event_id") or 0) + if not first_event_id or not last_event_id: + return False + job_key = _group_window_llm_job_key( + tenant_id=tenant_id, + channel=channel, + source_key=source_key, + session_id=session_id, + target_date=target_date, + source=source, + first_event_id=first_event_id, + last_event_id=last_event_id, + ) + payload = json.dumps( + { + "kind": GROUP_WINDOW_LLM_JOB_KIND, + "version": 1, + "scope": { + "tenant_id": tenant_id, + "channel": channel, + "source_key": source_key, + "session_id": session_id, + "date": target_date, + "source": source, + }, + "window": { + "index": int(window.get("index") or 0), + "first_event_id": first_event_id, + "last_event_id": last_event_id, + "event_count": len(window.get("event_ids") or []), + "window_size": int(window_size), + }, + }, + ensure_ascii=False, + separators=(",", ":"), + ) + max_attempts = _clamp_int( + getattr( + getattr(self, "settings", None), + "memory_group_graph_llm_job_max_attempts", + 3, + ), + 3, + minimum=1, + maximum=10, + ) + rows = await _exec( + "INSERT INTO plugin_memory_extraction_job " + "(tenant_id, channel, source_key, user_id, session_id, source_event_id, " + "source_trace_id, status, attempts, max_attempts, next_run_at, result_json, " + "idempotency_key, created_at, updated_at) " + "VALUES (:tid, :channel, :source_key, :group_uid, :sid, NULL, :trace, " + "'pending', 0, :max_attempts, NOW(), :result_json, :job_key, NOW(), NOW()) " + "ON CONFLICT (idempotency_key) DO NOTHING " + "RETURNING id", + { + "tid": tenant_id, + "channel": channel, + "source_key": source_key, + "group_uid": GROUP_HISTORY_USER_ID_SCOPE, + "sid": session_id, + "trace": job_key[:128], + "max_attempts": max_attempts, + "result_json": payload, + "job_key": job_key, + }, + ) + return bool(rows) + + async def _claim_group_window_llm_jobs( + self, + *, + limit: int, + lock_ttl_seconds: int, + ) -> list[dict[str, Any]]: + rows = await _exec( + "WITH candidate AS (" + " SELECT id FROM plugin_memory_extraction_job " + " WHERE source_trace_id LIKE :trace_prefix " + " AND (status IN ('pending', 'failed') " + " OR (status = 'running' AND locked_until < NOW())) " + " AND next_run_at <= NOW() " + " AND (locked_until IS NULL OR locked_until < NOW()) " + " ORDER BY next_run_at ASC, created_at ASC " + " LIMIT :limit " + " FOR UPDATE SKIP LOCKED" + ") " + "UPDATE plugin_memory_extraction_job job SET " + "status = 'running', locked_until = NOW() + (:lock_ttl * INTERVAL '1 second'), " + "locked_by = :locked_by, updated_at = NOW() " + "FROM candidate WHERE job.id = candidate.id " + "RETURNING job.id, job.tenant_id, job.channel, job.source_key, job.session_id, " + "job.attempts, job.max_attempts, job.result_json, job.idempotency_key", + { + "trace_prefix": f"{GROUP_WINDOW_LLM_JOB_TRACE_PREFIX}%", + "limit": max(1, int(limit)), + "lock_ttl": max(1, int(lock_ttl_seconds)), + "locked_by": f"group-window-llm:{monotonic():.0f}", + }, + ) + return list(rows or []) + + async def _finish_group_window_llm_job( + self, + job: dict[str, Any], + *, + status: str, + error: str = "", + result: dict[str, Any] | None = None, + retry_after_seconds: int = 0, + ) -> None: + payload = _safe_json_loads(job.get("result_json"), {}) + if not isinstance(payload, dict): + payload = {} + if result is not None: + payload["last_result"] = result + await _exec( + "UPDATE plugin_memory_extraction_job SET " + "status = :status, attempts = attempts + 1, " + "next_run_at = NOW() + (:retry_after * INTERVAL '1 second'), " + "locked_until = NULL, locked_by = '', last_error = :error, " + "result_json = :result_json, updated_at = NOW() " + "WHERE id = :id", + { + "id": int(job["id"]), + "status": status, + "retry_after": max(0, int(retry_after_seconds)), + "error": _truncate_error(error) if error else "", + "result_json": json.dumps(payload, ensure_ascii=False, separators=(",", ":")), + }, + ) + + async def run_group_window_llm_jobs( + self, + *, + limit: int | None = None, + llm_timeout_seconds: int | None = None, + time_budget_seconds: int | None = None, + ) -> dict[str, Any]: + """Run the LLM pass for windows queued by the deterministic catch-up. + + Each job gets the full ``llm_timeout_seconds``; the run stops when the + time budget cannot fit another attempt. Failures back off and retry + until ``max_attempts``, then the job is marked ``dead``. + """ + + settings = getattr(self, "settings", None) + effective_limit = _clamp_int( + limit, + _clamp_int( + getattr(settings, "memory_group_graph_llm_jobs_per_tick", 6), + 6, + minimum=0, + maximum=50, + ), + minimum=0, + maximum=50, + ) + effective_timeout = _clamp_int( + llm_timeout_seconds, + self._group_window_llm_timeout_default(), + minimum=GROUP_WINDOW_LLM_TIMEOUT_MIN, + maximum=GROUP_WINDOW_LLM_TIMEOUT_MAX, + ) + effective_budget = _clamp_int( + time_budget_seconds, + effective_timeout * max(1, effective_limit), + minimum=effective_timeout, + maximum=3600, + ) + summary: dict[str, Any] = { + "ok": True, + "claimed": 0, + "succeeded": 0, + "failed": 0, + "dead": 0, + "deferred": 0, + "applied": 0, + "stop_reason": "no_jobs", + "controls": { + "limit": effective_limit, + "llm_timeout_seconds": effective_timeout, + "time_budget_seconds": effective_budget, + }, + } + if effective_limit <= 0: + summary["stop_reason"] = "disabled" + return summary + llm_available = bool( + self.graph_extractor.config.enabled and self.graph_extractor.llm_service is not None + ) + if not llm_available: + summary["stop_reason"] = "llm_unavailable" + return summary + jobs = await self._claim_group_window_llm_jobs( + limit=effective_limit, + lock_ttl_seconds=effective_timeout * 2 + 30, + ) + summary["claimed"] = len(jobs) + started_at = monotonic() + for index, job in enumerate(jobs): + remaining = effective_budget - (monotonic() - started_at) + if index > 0 and remaining < effective_timeout: + # Release the claim untouched; the next tick picks it up. + await self._finish_group_window_llm_job(job, status="pending") + summary["deferred"] += 1 + summary["stop_reason"] = "time_budget_reached" continue - summary["candidate_count"] = len(candidates) - total_candidates += len(candidates) - for candidate in candidates: - if observation_event_ids: - candidate = { - **candidate, - "evidence_event_ids": [ - event_id - for event_id in (candidate.get("evidence_event_ids") or []) - if int(event_id or 0) not in observation_event_ids - ], - } - item = await self._apply_group_relationship_window_candidate( + payload = _safe_json_loads(job.get("result_json"), {}) + scope = payload.get("scope") if isinstance(payload, dict) else None + window = payload.get("window") if isinstance(payload, dict) else None + if not isinstance(scope, dict) or not isinstance(window, dict): + await self._finish_group_window_llm_job( + job, status="dead", error="malformed group window job payload" + ) + summary["dead"] += 1 + continue + tenant_id = str(scope.get("tenant_id") or job.get("tenant_id") or "") + session_id = str(scope.get("session_id") or job.get("session_id") or "") + if not await self._group_graph_auto_extract_scope_allowed(tenant_id, session_id): + await self._finish_group_window_llm_job( + job, status="pending", retry_after_seconds=6 * 3600 + ) + summary["deferred"] += 1 + continue + first_event_id = max(0, _safe_int(window.get("first_event_id"), 0)) + event_count = _safe_int(window.get("event_count"), 0) + window_size = _clamp_int( + event_count or window.get("window_size"), 50, minimum=10, maximum=100 + ) + try: + result = await self.run_group_relationship_window_extraction( tenant_id=tenant_id, - channel=channel, - source_key=source_key, - user_id=user_id_scope, + channel=str(scope.get("channel") or job.get("channel") or "wechat"), + source_key=str(scope.get("source_key") or job.get("source_key") or "wxbot"), session_id=session_id, - target_date=target_date, - window=window, - candidate=candidate, + date=str(scope.get("date") or ""), + window_size=window_size, + max_windows=1, + cursor_event_id=max(0, first_event_id - 1), + include_llm=True, + llm_timeout_seconds=effective_timeout, + source=_normalize_evidence_source(scope.get("source")), + llm_mode=LLM_MODE_INLINE, + deterministic=False, ) - if not item or item.get("id") is None: - summary["skipped_count"] += 1 - total_skipped += 1 - continue - summary["applied_count"] += 1 - total_applied += 1 - await self._refresh_legacy_cache_for_item_scope(item) - await self._sync_memory_graph_for_item_safe(item) - await self._sync_memory_vector_for_item_safe(item) + except Exception as exc: + attempts = _safe_int(job.get("attempts"), 0) + 1 + max_attempts = max(1, _safe_int(job.get("max_attempts"), 3)) + dead = attempts >= max_attempts + await self._finish_group_window_llm_job( + job, + status="dead" if dead else "failed", + error=f"{exc.__class__.__name__}: {exc}", + retry_after_seconds=0 if dead else min(6 * 3600, 600 * attempts), + ) + summary["dead" if dead else "failed"] += 1 + logger.warning( + "memory.group_window_llm_job_failed", + job_id=job.get("id"), + tenant_id=tenant_id, + session_id=session_id, + attempts=attempts, + dead=dead, + error_type=exc.__class__.__name__, + error=_truncate_error(exc), + ) + continue + totals = result.get("totals") if isinstance(result.get("totals"), dict) else {} + if int(result.get("llm_failures") or 0) > 0: + attempts = _safe_int(job.get("attempts"), 0) + 1 + max_attempts = max(1, _safe_int(job.get("max_attempts"), 3)) + dead = attempts >= max_attempts + await self._finish_group_window_llm_job( + job, + status="dead" if dead else "failed", + error="llm_window_extraction_failed", + result={"totals": totals, "status": result.get("status")}, + retry_after_seconds=0 if dead else min(6 * 3600, 600 * attempts), + ) + summary["dead" if dead else "failed"] += 1 + continue + await self._finish_group_window_llm_job( + job, + status="succeeded", + result={ + "totals": totals, + "status": result.get("status"), + "signal_counts": result.get("signal_counts"), + }, + ) + summary["succeeded"] += 1 + summary["applied"] += int(totals.get("applied") or 0) + summary["stop_reason"] = "completed" + logger.info( + "memory.group_window_llm_jobs", + claimed=summary["claimed"], + succeeded=summary["succeeded"], + failed=summary["failed"], + dead=summary["dead"], + deferred=summary["deferred"], + applied=summary["applied"], + stop_reason=summary["stop_reason"], + llm_timeout_seconds=effective_timeout, + ) + return summary - if total_applied == 0 and total_candidates == 0: - base_payload["status"] = "skipped" - if not llm_available: - base_payload["skipped_reason"] = "no_deterministic_candidates" - else: - base_payload["status"] = "completed" if total_skipped == 0 else "partial" - base_payload["generated_from"] = generated_from - base_payload["totals"] = { - "events": sum(len(window["event_ids"]) for window in windows), - "windows": len(windows), - "candidates": total_candidates, - "applied": total_applied, - "skipped": total_skipped, + async def _list_group_relation_auto_review_candidates( + self, + *, + limit: int, + tenant_id: str | None = None, + ) -> list[dict[str, Any]]: + """Pending model relations with the two corroboration flags computed in SQL. + + A relation is corroborated when the rest of 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 non-co-participation edge. + """ + + params: dict[str, Any] = { + "llm_source": LLM_GROUP_WINDOW_SOURCE_TYPE, + "weak_predicate": "co_participated", + "limit": max(1, int(limit)), } - return base_payload + tenant_clause = "" + if tenant_id: + tenant_clause = "AND item.tenant_id = :tid " + params["tid"] = str(tenant_id) + rows = await _exec( + "WITH pending AS (" + " SELECT item.id, item.tenant_id, item.session_id, item.created_at, " + " fact.subject_entity_id AS subject_id, fact.object_entity_id AS object_id, " + " fact.predicate, " + " COALESCE(NULLIF(item.value_json, '')::jsonb #>> '{relation,object_type}', 'person') " + " AS object_type " + " FROM plugin_memory_item item " + " JOIN plugin_memory_fact fact ON fact.memory_item_id = item.id " + " WHERE item.deleted_at IS NULL AND item.status = 'pending' " + " AND item.source_type = :llm_source " + " AND fact.object_entity_id IS NOT NULL " + " AND COALESCE(NULLIF(item.value_json, '')::jsonb #>> '{kind}', '') = 'group_window_relation' " + " AND COALESCE(NULLIF(item.value_json, '')::jsonb #>> '{acceptance,status}', '') " + " IN ('needs_review', 'candidate') " + f" {tenant_clause}" + " ORDER BY item.updated_at ASC, item.id ASC " + " LIMIT :limit" + ") " + "SELECT pending.id, pending.tenant_id, pending.session_id, pending.predicate, " + " pending.object_type, " + " EXISTS (" + " SELECT 1 FROM plugin_memory_fact other " + " JOIN plugin_memory_item other_item ON other_item.id = other.memory_item_id " + " WHERE other.status = 'active' AND other_item.deleted_at IS NULL " + " AND other_item.tenant_id = pending.tenant_id " + " AND other_item.session_id = pending.session_id " + " AND other.memory_item_id <> pending.id " + " AND other.object_entity_id = pending.object_id" + " ) AS term_corroborated, " + " EXISTS (" + " SELECT 1 FROM plugin_memory_fact other " + " JOIN plugin_memory_item other_item ON other_item.id = other.memory_item_id " + " WHERE other.status = 'active' AND other_item.deleted_at IS NULL " + " AND other_item.tenant_id = pending.tenant_id " + " AND other_item.session_id = pending.session_id " + " AND other.memory_item_id <> pending.id " + " AND other.predicate <> :weak_predicate " + " AND ((other.subject_entity_id = pending.subject_id " + " AND other.object_entity_id = pending.object_id) " + " OR (other.subject_entity_id = pending.object_id " + " AND other.object_entity_id = pending.subject_id))" + " ) AS pair_corroborated " + "FROM pending ORDER BY pending.id ASC", + params, + ) + return [dict(row) for row in rows or []] + + async def run_group_relation_auto_review( + self, + *, + limit: int | None = None, + tenant_id: str | None = None, + ) -> dict[str, Any]: + """Accept pending model relations that the accepted graph already corroborates. + + Single-window model claims wait in needs_review. Instead of a human + clicking through them, this pass promotes the ones the rest of the + group's graph supports: a term that some member already has an accepted + relation with, or two people who already have an accepted direct edge. + Uncorroborated claims stay pending until they repeat on another day or + governance expires them after the review retention window. + """ + + settings = getattr(self, "settings", None) + effective_limit = _clamp_int( + limit, + _clamp_int( + getattr(settings, "memory_group_graph_auto_review_batch", 200), + 200, + minimum=0, + maximum=1000, + ), + minimum=0, + maximum=1000, + ) + summary: dict[str, Any] = { + "ok": True, + "scanned": 0, + "accepted": 0, + "accepted_term": 0, + "accepted_pair": 0, + "failed": 0, + "remaining": 0, + "stop_reason": "disabled" if effective_limit <= 0 else "completed", + } + if effective_limit <= 0: + return summary + candidates = await self._list_group_relation_auto_review_candidates( + limit=effective_limit, + tenant_id=tenant_id, + ) + summary["scanned"] = len(candidates) + for candidate in candidates: + object_type = str(candidate.get("object_type") or "person").strip().lower() + if object_type != "person" and candidate.get("term_corroborated"): + reason = "group_window_term_corroborated" + bucket = "accepted_term" + elif object_type == "person" and candidate.get("pair_corroborated"): + reason = "group_window_pair_corroborated" + bucket = "accepted_pair" + else: + summary["remaining"] += 1 + continue + item_id = _safe_int(candidate.get("id"), 0) + try: + reviewed = await self.review_memory_item_acceptance( + item_id, + action="accept", + review_reason=reason, + reviewed_by=GROUP_RELATION_AUTO_REVIEWER, + ) + except Exception as exc: + summary["failed"] += 1 + logger.warning( + "memory.group_relation_auto_review_failed", + item_id=item_id, + error_type=exc.__class__.__name__, + error=_truncate_error(exc), + ) + continue + if not reviewed: + summary["failed"] += 1 + continue + summary["accepted"] += 1 + summary[bucket] += 1 + if len(candidates) >= effective_limit: + summary["stop_reason"] = "batch_limit_reached" + logger.info( + "memory.group_relation_auto_review", + scanned=summary["scanned"], + accepted=summary["accepted"], + accepted_term=summary["accepted_term"], + accepted_pair=summary["accepted_pair"], + failed=summary["failed"], + remaining=summary["remaining"], + stop_reason=summary["stop_reason"], + ) + return summary async def run_group_relationship_window_catchup( self, @@ -1715,13 +3525,30 @@ async def run_group_relationship_window_catchup( dry_run: bool = False, time_budget_seconds: int | None = None, include_llm: bool = True, + source: str | None = None, + llm_timeout_seconds: int | None = None, + llm_mode: str | None = None, ) -> dict[str, Any]: + """Walk a day window by window until the budget or window cap is hit. + + The LLM timeout is a fixed per-window value (``llm_timeout_seconds``, + default from settings). The time budget only decides how many windows + fit in this run; it is never divided across windows, which is what used + to leave the model 3 seconds per call. + """ + effective_window_size = _clamp_int(window_size, 50, minimum=10, maximum=100) effective_max_windows = _clamp_int(max_windows_per_run, 20, minimum=1, maximum=100) effective_cursor = max(0, int(cursor_event_id or 0)) - effective_time_budget = _clamp_int(time_budget_seconds, 60, minimum=1, maximum=180) - per_window_llm_timeout = max( - 1, effective_time_budget // effective_max_windows + effective_time_budget = _clamp_int(time_budget_seconds, 60, minimum=1, maximum=900) + effective_source = _normalize_evidence_source(source) + effective_llm_mode = _normalize_llm_mode(llm_mode) + llm_inline = bool(include_llm) and effective_llm_mode == LLM_MODE_INLINE + per_window_llm_timeout = _clamp_int( + llm_timeout_seconds, + self._group_window_llm_timeout_default(), + minimum=1, + maximum=GROUP_WINDOW_LLM_TIMEOUT_MAX, ) started_at = monotonic() totals = {"events": 0, "windows": 0, "candidates": 0, "applied": 0, "skipped": 0} @@ -1733,25 +3560,43 @@ async def run_group_relationship_window_catchup( "time_budget_seconds": effective_time_budget, "include_llm": bool(include_llm), "llm_timeout_seconds": per_window_llm_timeout, + "llm_mode": effective_llm_mode, + "source": effective_source, } windows_processed = 0 more_remain = False stop_reason = "no_more_events" status = "completed" next_cursor_event_id = effective_cursor + resolved_source: str | None = effective_source + signal_totals = _empty_group_signals() + unresolved_total = 0 + llm_jobs_enqueued = 0 + llm_failures = 0 while windows_processed < effective_max_windows: elapsed = monotonic() - started_at - if elapsed >= effective_time_budget: + remaining_budget = effective_time_budget - elapsed + if remaining_budget <= 0: + stop_reason = "time_budget_reached" + more_remain = True + break + if ( + llm_inline + and windows_processed > 0 + and remaining_budget < min(per_window_llm_timeout, 10) + ): + # Not enough budget left for a real model call; stop cleanly + # instead of starting a window that can only time out. stop_reason = "time_budget_reached" more_remain = True break - remaining_budget = max(0.001, effective_time_budget - elapsed) - # Keep LLM-backed calls to one window so each successful return is + remaining_budget = max(0.001, remaining_budget) + # Keep inline LLM calls to one window so each successful return is # also a durable checkpoint for the automatic runner. batch_limit = ( 1 - if include_llm + if llm_inline else min(effective_max_windows - windows_processed, 10) ) try: @@ -1772,6 +3617,8 @@ async def run_group_relationship_window_catchup( 1, min(per_window_llm_timeout, int(remaining_budget)), ), + source=effective_source, + llm_mode=effective_llm_mode, ), timeout=remaining_budget, ) @@ -1784,6 +3631,12 @@ async def run_group_relationship_window_catchup( processed = int(result_totals.get("windows") or 0) for key in totals: totals[key] += int(result_totals.get(key) or 0) + if result.get("source") and processed: + resolved_source = str(result.get("source")) + signal_totals = _merge_group_signals(signal_totals, result.get("signal_counts")) + unresolved_total += int(result.get("unresolved_targets") or 0) + llm_jobs_enqueued += int(result.get("llm_jobs_enqueued") or 0) + llm_failures += int(result.get("llm_failures") or 0) next_cursor_event_id = int(result.get("next_cursor_event_id") or next_cursor_event_id) more_remain = bool(result.get("more_remain")) result_status = str(result.get("status") or "") @@ -1815,13 +3668,22 @@ async def run_group_relationship_window_catchup( }, "date": _parse_daily_relationship_date(date).date().isoformat(), "controls": controls, + "source": resolved_source, "totals": totals, + "signal_counts": signal_totals, + "unresolved_targets": unresolved_total, + "llm_jobs_enqueued": llm_jobs_enqueued, + "llm_failures": llm_failures, "windows_processed": windows_processed, "next_cursor_event_id": next_cursor_event_id, "more_remain": more_remain, "stop_reason": stop_reason, "generated_from": [ - "plugin_memory_event", + ( + "plugin_wxbot_group_observations" + if resolved_source == EVIDENCE_SOURCE_OBSERVATION + else "plugin_memory_event" + ), "deterministic_window_participants", "llm_window_extractor", ], @@ -1838,21 +3700,44 @@ async def get_group_relationship_window_stats( date: str | None = None, limit: int = 5000, ) -> dict[str, Any]: - items = await self._list_memory_acceptance_audit_items( - tenant_id=tenant_id, - channel=channel, - source_key=source_key, - user_id=user_id, - session_id=session_id, - scope_type="session", - source_type=None, - include_deleted=False, - limit=max(1, min(int(limit or 5000), 10000)), - ) + # Relations are stored under the operator session id, so a runtime + # alias (cx1:...) must be expanded before counting, otherwise the panel + # shows zeros for a group that has thousands of relations. + scoped_session_ids = ( + await self._resolve_group_graph_session_ids( + tenant_id=tenant_id, + session_id=session_id, + ) + if session_id + else [None] + ) or [session_id] + safe_limit = max(1, min(int(limit or 5000), 10000)) + items: list[dict[str, Any]] = [] + seen_item_ids: set[int] = set() + for scoped_session_id in scoped_session_ids: + scoped_items = await self._list_memory_acceptance_audit_items( + tenant_id=tenant_id, + channel=channel, + source_key=source_key, + user_id=user_id, + session_id=scoped_session_id, + scope_type="session", + source_type=None, + include_deleted=False, + limit=safe_limit, + ) + for item in scoped_items: + item_id = _safe_int(item.get("id"), 0) + if item_id and item_id in seen_item_ids: + continue + if item_id: + seen_item_ids.add(item_id) + items.append(item) target_date = _parse_daily_relationship_date(date).date().isoformat() if date else "" totals = { "items": 0, "events": 0, + "observations": 0, "windows": 0, "accepted": 0, "needs_review": 0, @@ -1865,7 +3750,9 @@ async def get_group_relationship_window_stats( status_counts: dict[str, int] = {} acceptance_counts: dict[str, int] = {} predicate_counts: dict[str, int] = {} + source_counts: dict[str, int] = {} event_ids: set[int] = set() + observation_ids: set[int] = set() window_keys: set[tuple[Any, Any, Any]] = set() for item in items: value = _safe_json_loads(item.get("value_json"), {}) @@ -1896,11 +3783,20 @@ async def get_group_relationship_window_stats( relation.get("evidence_event_ids") or value.get("source_event_ids") or [] ): event_ids.add(event_id) + for observation_id in _coerce_int_set( + relation.get("evidence_observation_ids") + or value.get("source_observation_ids") + or [] + ): + observation_ids.add(observation_id) + evidence_source = str(value.get("evidence_source") or EVIDENCE_SOURCE_MEMORY_EVENT) + source_counts[evidence_source] = source_counts.get(evidence_source, 0) + 1 window = value.get("window") if isinstance(value.get("window"), dict) else {} window_keys.add( (value.get("date"), window.get("first_event_id"), window.get("last_event_id")) ) totals["events"] = len(event_ids) + totals["observations"] = len(observation_ids) totals["windows"] = len( [key for key in window_keys if key[1] is not None or key[2] is not None] ) @@ -1911,6 +3807,7 @@ async def get_group_relationship_window_stats( "channel": channel or "", "source_key": source_key or "", "session_id": session_id or "", + "session_ids": [item for item in scoped_session_ids if item], "user_id": user_id or "", "date": target_date, }, @@ -1918,6 +3815,7 @@ async def get_group_relationship_window_stats( "status_counts": status_counts, "acceptance_counts": acceptance_counts, "predicate_counts": predicate_counts, + "evidence_source_counts": source_counts, "generated_from": [ "plugin_memory_item", DETERMINISTIC_GROUP_WINDOW_SOURCE_TYPE, @@ -2482,11 +4380,30 @@ async def _load_group_relationship_events( columns: str, cursor_event_id: int | None = None, limit: int | None = None, + source: str | None = None, ) -> list[dict[str, Any]]: + """Load one day of group messages for window extraction. + + ``source`` pins the evidence source: ``memory_event`` reads only imported + memory events, ``observation`` reads only live group observations. When + omitted the legacy order is kept (scoped events, live events, then + observations) so manual API callers keep working. + """ + session_ids = await self._resolve_group_graph_session_ids( tenant_id=tenant_id, session_id=session_id, ) or [session_id] + effective_source = _normalize_evidence_source(source) + if effective_source == EVIDENCE_SOURCE_OBSERVATION: + return await self._load_group_relationship_events_from_observations( + tenant_id=tenant_id, + session_ids=session_ids, + start_at=start_at, + end_at=end_at, + cursor_event_id=cursor_event_id, + limit=limit, + ) params: dict[str, Any] = { "tid": tenant_id, "channel": channel, @@ -2534,6 +4451,8 @@ async def _load_group_relationship_events( ) if live_rows: return live_rows + if effective_source == EVIDENCE_SOURCE_MEMORY_EVENT: + return [] return await self._load_group_relationship_events_from_observations( tenant_id=tenant_id, session_ids=session_ids, @@ -2574,10 +4493,12 @@ async def _load_group_relationship_events_from_observations( limit_sql = "LIMIT :lim" params["lim"] = int(limit) rows = await _exec( - "SELECT id, tenant_id, session_id, sender_wxid, content, occurred_ts " + "SELECT id, tenant_id, session_id, sender_wxid, sender_name, content, " + "occurred_ts, is_self_sent, metadata_json " "FROM plugin_wxbot_group_observations " "WHERE tenant_id = :tid AND session_id = ANY(:sids) " "AND occurred_ts >= :start_ts AND occurred_ts < :end_ts " + "AND COALESCE(is_self_sent, FALSE) = FALSE " f"{cursor_sql}" "ORDER BY occurred_ts ASC, id ASC " f"{limit_sql}", @@ -2589,6 +4510,9 @@ async def _load_group_relationship_events_from_observations( content = str(row.get("content") or "").strip() if not sender or not content: continue + if str(row.get("is_self_sent") or "").strip().lower() in {"true", "t", "1"}: + # Defensive: the bot's own replies are not group-member interactions. + continue occurred = int(row.get("occurred_ts") or 0) created_at = ( datetime.fromtimestamp(occurred, UTC).replace(tzinfo=None) @@ -2608,7 +4532,11 @@ async def _load_group_relationship_events_from_observations( "trace_id": "", "event_key": f"observation:{row.get('id')}", "created_at": created_at, - "_graph_source": "observation", + "_graph_source": EVIDENCE_SOURCE_OBSERVATION, + "_observation": _observation_interaction_metadata( + row.get("metadata_json"), + sender_name=row.get("sender_name"), + ), } ) return events @@ -2622,9 +4550,15 @@ async def _group_graph_auto_extract_scope_allowed( return True gate = getattr(self, "combined_history_scope_execution_allowed", None) if not callable(gate): + logger.warning( + "memory.group_graph_auto_extract_scope_denied", + tenant_id=tenant_id, + session_id=session_id, + reason="scope_gate_unavailable", + ) return False try: - return await gate(str(tenant_id or ""), str(session_id or "")) is True + allowed = await gate(str(tenant_id or ""), str(session_id or "")) is True except Exception: logger.warning( "memory.group_graph_auto_extract_scope_failed", @@ -2633,6 +4567,16 @@ async def _group_graph_auto_extract_scope_allowed( exc_info=True, ) return False + if not allowed: + # Per-target detail stays at debug; the tick summary reports the + # aggregated skipped_reasons at info level. + logger.debug( + "memory.group_graph_auto_extract_scope_denied", + tenant_id=tenant_id, + session_id=session_id, + reason="plugin_scope_disabled", + ) + return allowed async def list_known_group_graph_sessions( self, @@ -2660,6 +4604,10 @@ async def list_known_group_graph_sessions( "lim": effective_max_sessions, }, ) + observation_rows = await self._list_group_observation_session_counts( + start_at=cutoff, + limit=effective_max_sessions, + ) activity_rows = await _exec( "SELECT tenant_id, channel, session_id " "FROM sessions " @@ -2674,7 +4622,7 @@ async def list_known_group_graph_sessions( ) sessions: list[dict[str, Any]] = [] merged: dict[tuple[str, str, str, str], dict[str, Any]] = {} - for row in list(rows or []) + [ + for row in list(rows or []) + list(observation_rows) + [ { **item, "source_key": "wxbot", @@ -2741,9 +4689,13 @@ async def list_imported_group_graph_targets( "lim": fetch_limit, }, ) + observation_rows = await self._list_group_observation_day_counts( + start_at=cutoff, + limit=fetch_limit, + ) targets: list[dict[str, Any]] = [] merged: dict[tuple[str, str, str, str, str], dict[str, Any]] = {} - for row in rows: + for row in [*rows, *observation_rows]: session_id = str(row.get("session_id") or "").strip() if not _is_group_session_id(session_id): continue @@ -2757,34 +4709,144 @@ async def list_imported_group_graph_targets( tenant_id = str(row.get("tenant_id") or "").strip() channel = str(row.get("channel") or "").strip() or "wechat" source_key = str(row.get("source_key") or "").strip() or "wxbot" + row_source = _normalize_evidence_source(row.get("source")) or EVIDENCE_SOURCE_MEMORY_EVENT operator_session = await self._operator_group_session_id( tenant_id=tenant_id, session_id=session_id, ) key = (tenant_id, channel, source_key, operator_session, date_value) event_count = int(row.get("event_count") or 0) - last_event_id = int(row.get("last_event_id") or 0) + last_id = int(row.get("last_event_id") or 0) current = merged.get(key) if current is None: - merged[key] = { + current = { "tenant_id": tenant_id, "channel": channel, "source_key": source_key, "session_id": operator_session, "date": date_value, - "event_count": event_count, - "last_event_id": last_event_id, + "event_count": 0, + "last_event_id": 0, + "last_observation_id": 0, + "memory_event_count": 0, + "observation_count": 0, } - continue + merged[key] = current current["event_count"] = int(current.get("event_count") or 0) + event_count - current["last_event_id"] = max(int(current.get("last_event_id") or 0), last_event_id) - targets = list(merged.values()) + if row_source == EVIDENCE_SOURCE_OBSERVATION: + current["observation_count"] = int(current.get("observation_count") or 0) + event_count + current["last_observation_id"] = max( + int(current.get("last_observation_id") or 0), last_id + ) + else: + current["memory_event_count"] = ( + int(current.get("memory_event_count") or 0) + event_count + ) + current["last_event_id"] = max(int(current.get("last_event_id") or 0), last_id) + targets = [] + for item in merged.values(): + # Imported memory events keep priority for a day; observations are the + # source for every day that only exists in the live group stream. + item["source"] = ( + EVIDENCE_SOURCE_MEMORY_EVENT + if int(item.get("memory_event_count") or 0) > 0 + else EVIDENCE_SOURCE_OBSERVATION + ) + targets.append(item) targets.sort( key=lambda item: (str(item.get("date") or ""), int(item.get("event_count") or 0)), reverse=True, ) return targets[:effective_max_targets] + async def _list_group_observation_day_counts( + self, + *, + start_at: datetime, + limit: int, + ) -> list[dict[str, Any]]: + """Group observation counts per (session, UTC day) shaped like memory-event rows.""" + + start_dt = ( + start_at + if isinstance(start_at, datetime) + else datetime.combine(start_at, datetime.min.time()) + ) + try: + rows = await _exec( + "SELECT tenant_id, session_id, " + "CAST(to_timestamp(occurred_ts) AT TIME ZONE 'UTC' AS date) AS day, " + "COUNT(*) AS event_count, MAX(id) AS last_event_id " + "FROM plugin_wxbot_group_observations " + "WHERE occurred_ts >= :start_ts " + "AND session_id LIKE '%@chatroom' " + "AND sender_wxid <> '' AND content <> '' " + "GROUP BY tenant_id, session_id, " + "CAST(to_timestamp(occurred_ts) AT TIME ZONE 'UTC' AS date) " + "ORDER BY day DESC, event_count DESC " + "LIMIT :lim", + { + "start_ts": int(start_dt.replace(tzinfo=UTC).timestamp()), + "lim": int(limit), + }, + ) + except Exception: + logger.warning("memory.group_graph_observation_targets_failed", exc_info=True) + return [] + return [ + { + "tenant_id": row.get("tenant_id"), + "channel": "wechat", + "source_key": "wxbot", + "session_id": row.get("session_id"), + "day": row.get("day"), + "event_count": row.get("event_count"), + "last_event_id": row.get("last_event_id"), + "source": EVIDENCE_SOURCE_OBSERVATION, + } + for row in rows or [] + ] + + async def _list_group_observation_session_counts( + self, + *, + start_at: datetime, + limit: int, + ) -> list[dict[str, Any]]: + start_dt = ( + start_at + if isinstance(start_at, datetime) + else datetime.combine(start_at, datetime.min.time()) + ) + try: + rows = await _exec( + "SELECT tenant_id, session_id, COUNT(*) AS event_count, " + "MAX(occurred_ts) AS last_seen_ts " + "FROM plugin_wxbot_group_observations " + "WHERE occurred_ts >= :start_ts " + "AND session_id LIKE '%@chatroom' " + "GROUP BY tenant_id, session_id " + "ORDER BY last_seen_ts DESC, event_count DESC " + "LIMIT :lim", + { + "start_ts": int(start_dt.replace(tzinfo=UTC).timestamp()), + "lim": int(limit), + }, + ) + except Exception: + logger.warning("memory.group_graph_observation_sessions_failed", exc_info=True) + return [] + return [ + { + "tenant_id": row.get("tenant_id"), + "channel": "wechat", + "source_key": "wxbot", + "session_id": row.get("session_id"), + "event_count": row.get("event_count"), + } + for row in rows or [] + ] + async def _load_group_graph_auto_extract_cursor( self, *, @@ -2793,6 +4855,7 @@ async def _load_group_graph_auto_extract_cursor( source_key: str, session_id: str, target_date: str, + source: str | None = None, ) -> int: cursor_key = _group_graph_auto_cursor_key( tenant_id=tenant_id, @@ -2825,6 +4888,14 @@ async def _load_group_graph_auto_extract_cursor( } if payload.get("scope") != expected_scope: return 0 + requested_source = _normalize_evidence_source(source) + stored_source = ( + _normalize_evidence_source(payload.get("source")) or EVIDENCE_SOURCE_MEMORY_EVENT + ) + if requested_source is not None and stored_source != requested_source: + # Memory-event ids and observation ids live in different id spaces; a + # cursor from one source must never be applied to the other. + return 0 return max(0, _safe_int(payload.get("cursor_event_id"), 0)) async def _save_group_graph_auto_extract_cursor( @@ -2836,8 +4907,10 @@ async def _save_group_graph_auto_extract_cursor( session_id: str, target_date: str, cursor_event_id: int, + source: str | None = None, ) -> None: cursor = max(0, int(cursor_event_id or 0)) + cursor_source = _normalize_evidence_source(source) or EVIDENCE_SOURCE_MEMORY_EVENT cursor_key = _group_graph_auto_cursor_key( tenant_id=tenant_id, channel=channel, @@ -2848,7 +4921,7 @@ async def _save_group_graph_auto_extract_cursor( payload = json.dumps( { "kind": "group_graph_auto_cursor", - "version": 1, + "version": 2, "scope": { "tenant_id": tenant_id, "channel": channel, @@ -2856,11 +4929,15 @@ async def _save_group_graph_auto_extract_cursor( "session_id": session_id, "date": target_date, }, + "source": cursor_source, "cursor_event_id": cursor, }, ensure_ascii=False, separators=(",", ":"), ) + # A cursor only advances within the same source; switching source (for + # example a day that used to read imported events and now reads live + # observations) restarts from the new source's beginning. await _exec( "INSERT INTO plugin_memory_extraction_job " "(tenant_id, channel, source_key, user_id, session_id, source_event_id, " @@ -2869,7 +4946,10 @@ async def _save_group_graph_auto_extract_cursor( "VALUES (:tid, :channel, :source_key, :group_uid, :sid, NULL, :trace, " "'succeeded', 0, 1, NOW(), :result_json, :cursor_key, NOW(), NOW()) " "ON CONFLICT (idempotency_key) DO UPDATE SET " - "result_json = CASE WHEN COALESCE(NULLIF(" + "result_json = CASE WHEN " + "COALESCE(NULLIF(plugin_memory_extraction_job.result_json, '')::jsonb ->> 'source', " + "'memory_event') <> :cursor_source " + "OR COALESCE(NULLIF(" "plugin_memory_extraction_job.result_json, '')::jsonb ->> 'cursor_event_id', '0')::bigint " "< :cursor_event_id THEN EXCLUDED.result_json " "ELSE plugin_memory_extraction_job.result_json END, " @@ -2884,6 +4964,7 @@ async def _save_group_graph_auto_extract_cursor( "result_json": payload, "cursor_key": cursor_key, "cursor_event_id": cursor, + "cursor_source": cursor_source, }, ) @@ -2898,9 +4979,16 @@ async def run_group_graph_auto_extract_tick( include_llm: bool = True, sync_missing_history: bool = False, sync_max_messages: int = 200, + llm_jobs_per_tick: int | None = None, + llm_timeout_seconds: int | None = None, + auto_review_batch: int | None = None, ) -> dict[str, Any]: + """One scheduler tick: deterministic catch-up for every target, a bounded + number of queued LLM window jobs with a full per-job timeout, then the + corroboration sweep that promotes pending model relations.""" + effective_time_budget = _clamp_int( - time_budget_seconds, 180, minimum=1, maximum=180 + time_budget_seconds, 180, minimum=1, maximum=900 ) skipped: list[dict[str, Any]] = [] synced: list[dict[str, Any]] = [] @@ -2959,6 +5047,14 @@ async def run_group_graph_auto_extract_tick( "ok": backfill.get("ok"), } ) + logger.info( + "memory.group_graph_auto_extract_synced", + tenant_id=tenant_id, + session_id=session_id, + imported_count=backfill.get("imported_count"), + events_inserted=backfill.get("events_inserted"), + ok=backfill.get("ok"), + ) targets = await self.list_imported_group_graph_targets( lookback_days=lookback_days, max_targets=min( @@ -2980,14 +5076,28 @@ async def run_group_graph_auto_extract_tick( channel = str(target.get("channel") or "wechat") source_key = str(target.get("source_key") or "wxbot") target_date = str(target.get("date") or "") - cursor_event_id = await self._load_group_graph_auto_extract_cursor( - tenant_id=tenant_id, - channel=channel, - source_key=source_key, - session_id=session_id, - target_date=target_date, + target_source = _normalize_evidence_source(target.get("source")) + cursor_kwargs: dict[str, Any] = { + "tenant_id": tenant_id, + "channel": channel, + "source_key": source_key, + "session_id": session_id, + "target_date": target_date, + } + if target_source is not None: + cursor_kwargs["source"] = target_source + cursor_event_id = await self._load_group_graph_auto_extract_cursor(**cursor_kwargs) + last_event_id = max( + 0, + int( + ( + target.get("last_observation_id") + if target_source == EVIDENCE_SOURCE_OBSERVATION + else target.get("last_event_id") + ) + or 0 + ), ) - last_event_id = max(0, int(target.get("last_event_id") or 0)) if last_event_id > 0 and cursor_event_id >= last_event_id: skipped.append({**target, "reason": "up_to_date"}) continue @@ -3006,6 +5116,11 @@ async def run_group_graph_auto_extract_tick( cursor_event_id=cursor_event_id, time_budget_seconds=effective_time_budget, include_llm=include_llm, + source=target_source, + # The tick never waits on the model inline: windows get a + # durable LLM job and are processed below with a real timeout. + llm_mode=LLM_MODE_ENQUEUE, + llm_timeout_seconds=llm_timeout_seconds, ) except Exception as exc: logger.warning( @@ -3029,14 +5144,11 @@ async def run_group_graph_auto_extract_tick( int(catchup.get("next_cursor_event_id") or cursor_event_id), ) if next_cursor_event_id > cursor_event_id: - await self._save_group_graph_auto_extract_cursor( - tenant_id=tenant_id, - channel=channel, - source_key=source_key, - session_id=session_id, - target_date=target_date, - cursor_event_id=next_cursor_event_id, - ) + save_kwargs: dict[str, Any] = { + **cursor_kwargs, + "cursor_event_id": next_cursor_event_id, + } + await self._save_group_graph_auto_extract_cursor(**save_kwargs) results.append( { **target, @@ -3048,13 +5160,80 @@ async def run_group_graph_auto_extract_tick( "next_cursor_event_id": next_cursor_event_id, } ) + llm_jobs: dict[str, Any] = {"claimed": 0, "succeeded": 0, "failed": 0, "dead": 0} + if include_llm: + try: + llm_jobs = await self.run_group_window_llm_jobs( + limit=llm_jobs_per_tick, + llm_timeout_seconds=llm_timeout_seconds, + ) + except Exception as exc: + logger.warning( + "memory.group_window_llm_jobs_failed", + error_type=exc.__class__.__name__, + error=_truncate_error(exc), + ) + llm_jobs = {"claimed": 0, "succeeded": 0, "failed": 0, "dead": 0, "error": exc.__class__.__name__} + auto_review: dict[str, Any] = {"scanned": 0, "accepted": 0, "remaining": 0} + try: + # Runs after the model pass so relations produced this tick can + # already be corroborated by the rest of the accepted graph. + auto_review = await self.run_group_relation_auto_review(limit=auto_review_batch) + except Exception as exc: + logger.warning( + "memory.group_relation_auto_review_sweep_failed", + error_type=exc.__class__.__name__, + error=_truncate_error(exc), + ) + auto_review = {"scanned": 0, "accepted": 0, "remaining": 0, "error": exc.__class__.__name__} + skipped_reasons: dict[str, int] = {} + for item in skipped: + reason = str(item.get("reason") or "unknown") + skipped_reasons[reason] = skipped_reasons.get(reason, 0) + 1 + applied_total = sum( + int((item.get("totals") or {}).get("applied") or 0) for item in results + ) + applied_total += int(llm_jobs.get("applied") or 0) + failed_total = len([item for item in results if item.get("status") == "failed"]) + # Always leave a trace, even for a no-op tick: an idle scheduler must be + # distinguishable from a broken one in the logs. + logger.info( + "memory.group_graph_auto_extract_tick", + target_count=len(targets), + ran=len(results) - failed_total, + failed=failed_total, + applied=applied_total, + synced=len(synced), + skipped=len(skipped), + skipped_reasons=skipped_reasons, + sources={ + source: len([item for item in targets if item.get("source") == source]) + for source in GROUP_GRAPH_EVIDENCE_SOURCES + }, + include_llm=bool(include_llm), + lookback_days=_clamp_int(lookback_days, 7, minimum=1, maximum=14), + llm_jobs={ + key: llm_jobs.get(key) + for key in ("claimed", "succeeded", "failed", "dead", "deferred", "stop_reason") + if key in llm_jobs + }, + auto_review={ + key: auto_review.get(key) + for key in ("scanned", "accepted", "accepted_term", "accepted_pair", "remaining", "stop_reason") + if key in auto_review + }, + ) return { "ok": True, "lookback_days": _clamp_int(lookback_days, 7, minimum=1, maximum=14), "include_llm": bool(include_llm), "sync_missing_history": bool(sync_missing_history), "target_count": len(targets), - "ran": len([item for item in results if item.get("status") != "failed"]), + "ran": len(results) - failed_total, + "applied": applied_total, + "skipped_reasons": skipped_reasons, + "llm_jobs": llm_jobs, + "auto_review": auto_review, "synced": synced, "skipped": skipped, "results": results, diff --git a/plugins/memory/store_jobs.py b/plugins/memory/store_jobs.py index b3823bd..7d58918 100644 --- a/plugins/memory/store_jobs.py +++ b/plugins/memory/store_jobs.py @@ -14,6 +14,7 @@ _LLM_JOB_SCOPE_GROUP_KEYS, GRAPH_LLM_BACKING_SOURCE_TYPE, GROUP_HISTORY_USER_ID_SCOPE, + GROUP_WINDOW_LLM_JOB_TRACE_PREFIX, MEMORY_EXTRACTION_JOB_STATUSES, _clamp_int, _job_idempotency_key, @@ -878,6 +879,7 @@ async def claim_llm_extraction_jobs( " OR (status = 'running' AND locked_until < NOW())) " " AND next_run_at <= NOW() " " AND (locked_until IS NULL OR locked_until < NOW()) " + " AND source_trace_id NOT LIKE :group_window_prefix " f"{allowlist_sql}" " ORDER BY next_run_at ASC, created_at ASC " " LIMIT :limit " @@ -896,6 +898,7 @@ async def claim_llm_extraction_jobs( "limit": batch_size, "lock_ttl": lock_ttl, "locked_by": claim_token, + "group_window_prefix": f"{GROUP_WINDOW_LLM_JOB_TRACE_PREFIX}%", **allowlist_params, }, ) @@ -1002,6 +1005,7 @@ async def claim_llm_extraction_jobs_for_day( " OR (job.status = 'running' AND job.locked_until < NOW())) " " AND job.next_run_at <= NOW() " " AND (job.locked_until IS NULL OR job.locked_until < NOW()) " + " AND job.source_trace_id NOT LIKE :group_window_prefix " " AND (" " job.source_event_id IN (" " SELECT id FROM plugin_memory_event " @@ -1037,6 +1041,7 @@ async def claim_llm_extraction_jobs_for_day( "limit": batch_size, "lock_ttl": lock_ttl, "locked_by": claim_token, + "group_window_prefix": f"{GROUP_WINDOW_LLM_JOB_TRACE_PREFIX}%", }, ) for job in rows: diff --git a/tests/unit/test_config_precedence.py b/tests/unit/test_config_precedence.py index 7a3664f..8a13f30 100644 --- a/tests/unit/test_config_precedence.py +++ b/tests/unit/test_config_precedence.py @@ -209,7 +209,9 @@ def test_memory_llm_extraction_defaults_are_enabled() -> None: assert settings.memory_group_graph_auto_extract_llm_enabled is True assert settings.memory_graph_retrieval_enabled is True assert settings.memory_group_graph_auto_extract_lookback_days == 7 - assert settings.memory_group_graph_auto_extract_sync_enabled is True + # Live groups stream into plugin_wxbot_group_observations; the legacy SDK + # history sync before each tick is opt-in. + assert settings.memory_group_graph_auto_extract_sync_enabled is False assert settings.memory_group_graph_auto_extract_sync_max_messages == 200 assert settings.memory_llm_extraction_job_timeout_seconds == 90.0 assert settings.memory_llm_extraction_job_lock_ttl_seconds == 150.0 diff --git a/tests/unit/test_memory_governance.py b/tests/unit/test_memory_governance.py index 629b55f..e7bb9a5 100644 --- a/tests/unit/test_memory_governance.py +++ b/tests/unit/test_memory_governance.py @@ -26,7 +26,14 @@ async def test_memory_governance_dry_run_and_bounded_cleanup(monkeypatch) -> Non async def fake_exec(sql: str, params: dict | None = None) -> list[dict]: calls.append((sql, params or {})) if sql.startswith("SELECT id"): + if "candidate" in sql and "source_type IN ('deterministic_group_window'" in sql: + # Group window relations use their own retention (default 14 days), + # independent of the generic 30-day needs_review window. + assert (params or {}).get("days") == 14 + return [] if "candidate" in sql: + assert "source_type NOT IN ('deterministic_group_window'" in sql + assert (params or {}).get("days") == 30 return [{"id": 1}] if "= 'rejected'" in sql: return [{"id": 2}] @@ -74,3 +81,43 @@ async def delete_item(self, item_id: int) -> None: assert "status = 'expired'" not in item_expiry_sql select_sql = next(sql for sql, _params in calls if sql.startswith("SELECT id")) assert "explicit_user" in select_sql + + +@pytest.mark.asyncio +async def test_memory_governance_marks_stale_extraction_jobs_dead(monkeypatch) -> None: + calls: list[tuple[str, dict]] = [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict]: + calls.append((sql, params or {})) + if sql.startswith("SELECT id FROM plugin_memory_extraction_job"): + assert "status IN ('pending', 'failed')" in sql + assert (params or {}).get("days") == 14 + return [{"id": 41}, {"id": 42}] + return [] + + monkeypatch.setattr("plugins.memory.store._exec", fake_exec) + store = MemoryStore( + SimpleNamespace( + memory_needs_review_retention_days=30, + memory_rejected_retention_days=7, + memory_auto_expire_days=180, + memory_governance_batch_size=100, + memory_llm_extraction_job_stale_days=14, + ) + ) + + preview = await store.run_governance_cleanup(dry_run=True) + assert preview["stale_jobs_dead"] == 2 + assert preview["ids"]["stale_jobs"] == [41, 42] + assert not any(sql.startswith("UPDATE") for sql, _params in calls) + + calls.clear() + applied = await store.run_governance_cleanup(dry_run=False) + assert applied["stale_jobs_dead"] == 2 + update_sql, update_params = next( + (sql, params) + for sql, params in calls + if sql.startswith("UPDATE plugin_memory_extraction_job SET status = 'dead'") + ) + assert update_params["ids"] == [41, 42] + assert "status IN ('pending', 'failed')" in update_sql diff --git a/tests/unit/test_memory_graph.py b/tests/unit/test_memory_graph.py index 8d743de..1e6f111 100644 --- a/tests/unit/test_memory_graph.py +++ b/tests/unit/test_memory_graph.py @@ -3,6 +3,7 @@ import hashlib import json from dataclasses import replace +from datetime import datetime from types import SimpleNamespace from typing import Any @@ -1295,9 +1296,13 @@ async def noop(*args, **kwargs): "reason": f"sha256:{hashlib.sha256(b'manual approve').hexdigest()}", "superseded_by_item_id": None, "supersedes_item_id": None, - "reviewed_at": result["value"]["acceptance"]["reviewed_at"], + # Bound as a datetime: asyncpg rejects a string for the TIMESTAMP cast. + "reviewed_at": datetime.fromisoformat( + result["value"]["acceptance"]["reviewed_at"].replace("Z", "+00:00") + ).replace(tzinfo=None), } ] + assert isinstance(audit_rows[0]["reviewed_at"], datetime) @pytest.mark.asyncio @@ -1446,8 +1451,17 @@ async def fake_exec(sql: str, params: dict | None = None) -> list[dict]: "memory_item_ids": [100, 101], "event_ids": [500, 501], "episode_ids": [20], + "observation_ids": [], } - assert payload["evidence_counts"] == {"memory_items": 2, "events": 1, "episodes": 1} + assert payload["evidence_counts"] == { + "memory_items": 2, + "events": 1, + "episodes": 1, + "observations": 0, + "evidence_days": 0, + } + assert payload["observations"] == [] + assert payload["evidence_source"] == "memory_event" serialized = str(payload) assert "private raw content" not in serialized assert "private original text" not in serialized @@ -1881,6 +1895,14 @@ async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any] "candidate_count": 0, "applied_count": 0, "skipped_count": 0, + "signal_counts": { + "quote": 0, + "mention": 0, + "prefix_reply": 0, + "co_participation": 0, + "llm": 0, + }, + "unresolved_targets": 0, } ] assert result["totals"] == { @@ -2117,6 +2139,9 @@ async def test_group_relationship_window_extraction_merges_same_relation_across_ store.graph_extractor.llm_service = object() items_by_key: dict[str, dict[str, Any]] = {} next_item_id = 910 + # Flipped on after the first window: the stored row then looks like one + # written before the sensitivity fix (flagged pii for a plain person pair). + legacy_pii_rows = False async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: nonlocal next_item_id @@ -2130,38 +2155,35 @@ async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any] } for event_id in params.get("event_ids", []) ] + if ( + legacy_pii_rows + and "normalized_key = :normalized_key" in sql + and "FROM plugin_memory_item" in sql + and "deleted_at IS NOT NULL" not in sql + ): + item = items_by_key.get(str(params["normalized_key"])) + return [{**item, "sensitivity": "pii", "sensitivity_category": "pii"}] if item else [] if "FROM plugin_memory_event" in sql and "id > :cursor_event_id" in sql: cursor = int(params["cursor_event_id"]) - if cursor < 501: - return [ - { - "id": 501, - "tenant_id": "demo", - "channel": "wechat", - "source_key": "wxbot", - "user_id": "__group__", - "session_id": "room-a@chatroom", - "user_text": "wxid_a: raw one", - "assistant_text": "", - "trace_id": "trace-501", - "event_key": "event-501", - "created_at": "2026-05-15T08:00:00", - } - ] + # Two messages per window: a model claim needs two supporting + # messages before it is stored at all. Both endpoints must be real + # speakers, otherwise the object is reclassified or dropped. + window_ids = [501, 502] if cursor < 501 else [503, 504] return [ { - "id": 502, + "id": event_id, "tenant_id": "demo", "channel": "wechat", "source_key": "wxbot", "user_id": "__group__", "session_id": "room-a@chatroom", - "user_text": "wxid_a: raw two", + "user_text": f"{'wxid_a' if event_id % 2 else 'wxid_b'}: raw {event_id}", "assistant_text": "", - "trace_id": "trace-502", - "event_key": "event-502", - "created_at": "2026-05-15T08:01:00", + "trace_id": f"trace-{event_id}", + "event_key": f"event-{event_id}", + "created_at": f"2026-05-15T08:0{event_id - 500}:00", } + for event_id in window_ids ] if "deleted_at IS NOT NULL" in sql: return [] @@ -2211,6 +2233,10 @@ async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any] item["occurrence_count"] = int(item["occurrence_count"]) + 1 item["value_json"] = params["value_json"] item["confidence"] = max(float(item["confidence"]), float(params["confidence"])) + # Mirror the real statement: a promotion rewrites status/sensitivity. + item["status"] = params["status"] + item["sensitivity"] = params["sensitivity"] + item["sensitivity_category"] = params["sensitivity_category"] return [] if "FROM plugin_memory_item WHERE id = :id" in sql: item = next( @@ -2252,6 +2278,7 @@ async def fake_noop(*args: Any, **kwargs: Any) -> None: window_size=10, cursor_event_id=0, ) + legacy_pii_rows = True second = await store.run_group_relationship_window_extraction( tenant_id="demo", channel="wechat", @@ -2259,19 +2286,48 @@ async def fake_noop(*args: Any, **kwargs: Any) -> None: session_id="room-a@chatroom", date="2026-05-15", window_size=10, - cursor_event_id=501, + cursor_event_id=502, ) assert first["totals"]["applied"] == 1 assert second["totals"]["applied"] == 1 + assert first["signal_counts"]["llm"] == 2 assert len(items_by_key) == 1 item = next(iter(items_by_key.values())) assert item["occurrence_count"] == 2 assert item["original_text"] == "" assert item["normalized_key"].startswith("group-window-rel:asked:") value = json.loads(item["value_json"]) - assert value["relation"]["evidence_event_ids"] == [501, 502] - assert value["source_event_ids"] == [501, 502] + assert value["relation"]["evidence_event_ids"] == [501, 502, 503, 504] + assert value["source_event_ids"] == [501, 502, 503, 504] + # Four supporting messages on one day: accepted without waiting for a second day. + assert value["acceptance"]["status"] == "accepted" + assert value["acceptance"]["reason"] == "group_window_llm_repeated_evidence" + # The synthetic "wxid_a asked wxid_b" line must not be read as PII: an + # accepted relation is stored active, otherwise its fact never reaches the graph. + assert item["status"] == "active" + assert item["sensitivity"] == "normal" + assert item["sensitivity_category"] == "normal" + + +def test_group_window_relation_sensitivity_probe_only_checks_free_text_objects() -> None: + from plugins.memory.store import _detect_sensitivity, _group_window_relation_sensitivity_probe + + person_relation = {"relation": {"subject": "wxid_a", "predicate": "asked", "object": "wxid_b"}} + assert _group_window_relation_sensitivity_probe(person_relation) == "" + assert _detect_sensitivity(_group_window_relation_sensitivity_probe(person_relation)) == "normal" + + term_relation = { + "relation": {"subject": "wxid_a", "predicate": "interested_in", "object": "Claude", "object_type": "tool"} + } + assert _group_window_relation_sensitivity_probe(term_relation) == "Claude" + + phone_relation = { + "relation": {"subject": "wxid_a", "predicate": "mentioned", "object": "13812345678", "object_type": "topic"} + } + assert _detect_sensitivity(_group_window_relation_sensitivity_probe(phone_relation)) == "pii" + # value_json may arrive serialized. + assert _group_window_relation_sensitivity_probe(json.dumps(term_relation)) == "Claude" @pytest.mark.asyncio @@ -2643,12 +2699,36 @@ async def fake_graph_sync(item: dict[str, Any]) -> None: "object_type": "person", "confidence": 0.62, "evidence_event_ids": [501, 502], + "evidence_observation_ids": [], "reason": "deterministic_adjacent_reply_window", "extraction_method": "deterministic_group_window", + "signals": { + "quote": 0, + "mention": 0, + "prefix_reply": 1, + "co_participation": 0, + "llm": 0, + }, + # The replying message anchors the signal; counts derive from these ids. + "signal_evidence": { + "quote": [], + "mention": [], + "prefix_reply": [502], + "co_participation": [], + "llm": [], + }, + "strength": value["relation"]["strength"], } + assert 0.2 < value["relation"]["strength"] < 0.4 assert value["source_event_ids"] == [501, 502] - assert value["acceptance"]["status"] == "needs_review" - assert replied_to_item["status"] == "pending" + # An explicit reply prefix is an observable platform fact: accepted on sight. + assert value["acceptance"]["status"] == "accepted" + assert value["acceptance"]["reason"] == "group_window_direct_signal" + assert value["acceptance"]["reviewed_by"] == "system/auto" + assert value["acceptance"]["day_count"] == 1 + assert replied_to_item["status"] == "active" + assert result["signal_counts"]["prefix_reply"] == 1 + assert result["signal_counts"]["co_participation"] == 0 assert [item["id"] for item in graph_sync_items] == [replied_to_item["id"]] serialized = str(result) + str(value) assert "RAW_FIELD_SENTINEL" not in serialized @@ -2784,8 +2864,10 @@ async def fake_graph_sync(item: dict[str, Any]) -> None: for relation in relations ) assert all(item["source_type"] == "deterministic_group_window" for item in graph_items) - assert all(item["status"] == "pending" for item in graph_items) - assert all(item["value"]["acceptance"]["status"] == "needs_review" for item in graph_items) + # A text @-mention of another participant is a direct signal. + assert all(item["status"] == "active" for item in graph_items) + assert all(item["value"]["acceptance"]["status"] == "accepted" for item in graph_items) + assert all(item["value"]["relation"]["signals"]["mention"] >= 1 for item in graph_items) assert all(item["original_text"] == "" for item in graph_items) serialized = str(result) + str(graph_items) assert "RAW_FIELD_SENTINEL" not in serialized @@ -3019,6 +3101,118 @@ async def fake_exec(sql: str, params: dict | None = None) -> list[dict]: assert value_graph["edges"][0]["id"].startswith("fact:1:note:value:") +@pytest.mark.asyncio +async def test_group_relationship_graph_node_type_keeps_edges_touching_that_type( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Filtering a person -> tool graph by "tool" must show the tools and who uses them.""" + + store = MemoryStore(SimpleNamespace()) + + def entity(entity_id: int, entity_type: str, name: str) -> dict: + return { + "id": entity_id, + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "user_id": "__group__", + "entity_type": entity_type, + "name": name, + "normalized_name": name.lower(), + "aliases_json": "[]", + "confidence": 0.9, + "status": "active", + "created_at": "2026-05-01T00:00:00", + "updated_at": "2026-05-10T00:00:00", + } + + def fact(fact_id: int, subject_id: int, predicate: str, object_id: int, item_id: int) -> dict: + return { + "id": fact_id, + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "user_id": "__group__", + "subject_entity_id": subject_id, + "predicate": predicate, + "object_entity_id": object_id, + "object_value": "", + "memory_item_id": item_id, + "source_event_id": None, + "confidence": 0.9, + "status": "active", + "valid_at": "2026-05-05T00:00:00", + "invalid_at": None, + "created_at": "2026-05-05T00:00:00", + "updated_at": "2026-05-12T00:00:00", + } + + def item(item_id: int) -> dict: + return { + "id": item_id, + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "user_id": "__group__", + "session_id": "group-1@chatroom", + "scope_type": "session", + "source_type": "llm_group_window", + "memory_type": "note", + "value_json": '{"kind":"group_window_relation","acceptance":{"status":"accepted"}}', + "normalized_key": f"group-window-rel:{item_id}", + "confidence": 0.9, + "status": "active", + "pinned": False, + "priority": 0, + "sensitivity": "normal", + "source_event_id": None, + "source_trace_id": "", + "occurrence_count": 1, + "first_seen_at": "2026-05-05T00:00:00", + "last_seen_at": "2026-05-12T00:00:00", + "created_at": "2026-05-05T00:00:00", + "updated_at": "2026-05-12T00:00:00", + "deleted_at": None, + } + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict]: + if "FROM plugin_memory_entity" in sql: + return [entity(1, "person", "wxid_a"), entity(2, "person", "wxid_b"), entity(3, "tool", "Claude")] + if "COUNT(*)" in sql and "plugin_memory_fact" in sql: + return [{"count": 2}] + if "FROM plugin_memory_fact fact" in sql: + return [fact(10, 1, "interested_in", 3, 100), fact(11, 1, "replied_to", 2, 101)] + if "FROM plugin_memory_episode" in sql: + return [] + if "FROM plugin_memory_item WHERE id = ANY" in sql: + return [item(100), item(101)] + return [] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + + tool_graph = await store.get_group_relationship_graph( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="group-1@chatroom", + node_type="tool", + limit=10, + ) + full_graph = await store.get_group_relationship_graph( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="group-1@chatroom", + limit=10, + ) + + assert full_graph["counts"] == {"nodes": 3, "edges": 2} + # Only the edge that touches a tool survives, together with both of its endpoints. + assert tool_graph["counts"] == {"nodes": 2, "edges": 1} + assert tool_graph["edges"][0]["type"] == "interested_in" + assert {node["type"] for node in tool_graph["nodes"]} == {"person", "tool"} + + @pytest.mark.asyncio async def test_group_relationship_graph_display_label_prefers_alias_over_technical_id( monkeypatch: pytest.MonkeyPatch, diff --git a/tests/unit/test_memory_group_graph_auto_extract.py b/tests/unit/test_memory_group_graph_auto_extract.py index 36b4dae..2a49672 100644 --- a/tests/unit/test_memory_group_graph_auto_extract.py +++ b/tests/unit/test_memory_group_graph_auto_extract.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import json from datetime import date, datetime from types import SimpleNamespace from typing import Any @@ -16,6 +17,60 @@ ) +async def _no_auto_review(**kwargs: Any) -> dict[str, Any]: + """Tick tests that do not exercise the corroboration sweep skip its query.""" + + return {"scanned": 0, "accepted": 0, "remaining": 0, "stop_reason": "completed"} + + +def test_group_relation_judgement_explains_model_edges_without_chat_text() -> None: + from plugins.memory.store_group_graph import _group_relation_judgement + + judgement = _group_relation_judgement( + { + "source_type": "llm_group_window", + "value": { + "relation": { + "signals": {"quote": 0, "llm": 10}, + "reason": "多次比较三位成员并评价其外貌", + "strength": 0.63, + }, + "acceptance": { + "status": "accepted", + "reason": "group_window_weak_signal", + "policy": "group_window_weak_signal", + "reviewed_by": "system/auto-review", + "review_reason": "group_window_term_corroborated", + "day_count": 1, + }, + }, + } + ) + + assert judgement == { + "extraction_method": "llm", + "signals": {"llm": 10}, + "policy": "group_window_weak_signal", + "acceptance_status": "accepted", + "reviewed_by": "system/auto-review", + "review_reason": "group_window_term_corroborated", + "model_reason": "多次比较三位成员并评价其外貌", + "day_count": 1, + "strength": 0.63, + } + # Rule-layer edges never carry a model rationale, even if one is present. + deterministic = _group_relation_judgement( + { + "source_type": "deterministic_group_window", + "value": {"relation": {"signals": {"quote": 3}, "reason": "quoted reply"}, "acceptance": {}}, + } + ) + assert deterministic["extraction_method"] == "deterministic" + assert deterministic["signals"] == {"quote": 3} + assert deterministic["model_reason"] == "" + assert _group_relation_judgement(None)["extraction_method"] == "unknown" + + def test_group_graph_edge_quality_reads_safe_value_payload() -> None: quality = _group_graph_edge_quality( { @@ -40,6 +95,8 @@ async def test_list_imported_group_graph_targets_keeps_group_days( async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: if "FROM sessions" in sql: return [] + if "FROM plugin_wxbot_group_observations" in sql: + return [] assert "plugin_memory_event" in sql assert params is not None assert "group_uid" not in params @@ -136,6 +193,7 @@ async def fake_save_cursor(**kwargs: Any) -> None: saved_cursors.append(kwargs) monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) + monkeypatch.setattr(store, "run_group_relation_auto_review", _no_auto_review) monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) monkeypatch.setattr(store, "_load_group_graph_auto_extract_cursor", fake_load_cursor) monkeypatch.setattr(store, "_save_group_graph_auto_extract_cursor", fake_save_cursor) @@ -172,9 +230,17 @@ async def fake_save_cursor(**kwargs: Any) -> None: "cursor_event_id": 400, "time_budget_seconds": 180, "include_llm": False, + # Targets without a source keep the legacy auto-fallback loader. + "source": None, + # The tick never waits on the model inline. + "llm_mode": "enqueue", + "llm_timeout_seconds": None, } ] assert saved_cursors[0]["cursor_event_id"] == 500 + assert "source" not in saved_cursors[0] + assert result["skipped_reasons"] == {"scope_disabled": 1} + assert result["applied"] == 2 @pytest.mark.asyncio @@ -201,6 +267,7 @@ async def fake_catchup(**kwargs: Any) -> dict[str, Any]: return {"status": "completed", "totals": {}, "more_remain": False} monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) + monkeypatch.setattr(store, "run_group_relation_auto_review", _no_auto_review) monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) monkeypatch.setattr( store, "_load_group_graph_auto_extract_cursor", lambda **kwargs: asyncio.sleep(0, result=0) @@ -394,6 +461,7 @@ async def allowed(tenant_id: str, session_id: str = "") -> bool: store.combined_history_scope_execution_allowed = allowed monkeypatch.setattr(store, "list_known_group_graph_sessions", fake_sessions) monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) + monkeypatch.setattr(store, "run_group_relation_auto_review", _no_auto_review) monkeypatch.setattr(store, "backfill_from_sdk", fake_backfill) monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) monkeypatch.setattr( @@ -498,8 +566,25 @@ async def fake_insert(**kwargs: Any) -> dict[str, Any]: assert acceptance["history"] == [{"action": acceptance_status}] +def _candidate(**overrides: Any) -> dict[str, Any]: + base = { + "subject": "wxid_a", + "subject_type": "person", + "predicate": "replied_to", + "object": "wxid_b", + "object_type": "person", + "confidence": 0.9, + "evidence_event_ids": [1, 8], + "reason": "deterministic_quote_reply", + "extraction_method": "deterministic_group_window", + "signals": {"quote": 1, "mention": 0, "prefix_reply": 0, "co_participation": 0, "llm": 0}, + } + base.update(overrides) + return base + + @pytest.mark.asyncio -async def test_window_candidate_auto_accepts_new_relations( +async def test_window_candidate_direct_signal_is_accepted_on_first_sight( monkeypatch: pytest.MonkeyPatch, ) -> None: store = MemoryStore(SimpleNamespace(memory_group_graph_auto_accept=True)) @@ -523,364 +608,1772 @@ async def fake_insert(**kwargs: Any) -> dict[str, Any]: session_id="room-a@chatroom", target_date="2026-08-31", window={"index": 1, "first_event_id": 1, "last_event_id": 8}, - candidate={ - "subject": "wxid_a", - "subject_type": "person", - "predicate": "co_participated", - "object": "wxid_b", - "object_type": "person", - "confidence": 0.55, - "evidence_event_ids": [1, 8], - "reason": "same_window", - "extraction_method": "deterministic_group_window", - }, + candidate=_candidate(), ) assert inserted[0]["status"] == "active" - acceptance = inserted[0]["value_json"]["acceptance"] - assert acceptance["status"] == "accepted" - assert acceptance["reviewed_by"] == "system/auto" - assert acceptance["reason"] == "same_window" + value = inserted[0]["value_json"] + assert value["acceptance"]["status"] == "accepted" + assert value["acceptance"]["reason"] == "group_window_direct_signal" + assert value["acceptance"]["reviewed_by"] == "system/auto" + assert value["acceptance"]["signals"]["quote"] == 1 + assert value["relation"]["signals"]["quote"] == 1 + assert 0.25 < value["relation"]["strength"] < 0.35 @pytest.mark.asyncio -async def test_auto_accept_pending_group_window_relations( +async def test_window_candidate_weak_signal_waits_for_repetition( monkeypatch: pytest.MonkeyPatch, ) -> None: - store = MemoryStore(SimpleNamespace()) - seen: list[str] = [] + """co_participated and single-day LLM edges stay needs_review; a second day + with evidence promotes an LLM edge to accepted and activates the item.""" - async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: - seen.append(sql) - if "FROM sessions" in sql: - return [{"session_id": "room-a@chatroom"}] - if sql.strip().startswith("UPDATE plugin_memory_item"): - assert params is not None - assert params["sids"] == ["room-a@chatroom"] - assert "group_window_auto_accept" in sql - return [{"id": 21}, {"id": 22}] - if sql.strip().startswith("UPDATE plugin_memory_fact"): - return [{"id": 201}, {"id": 202}] - if sql.strip().startswith("UPDATE plugin_memory_entity"): - return [{"id": 11}] + store = MemoryStore(SimpleNamespace(memory_group_graph_auto_accept=True)) + inserted: list[dict[str, Any]] = [] + existing: list[dict[str, Any]] = [] + + async def fake_find(**kwargs: Any) -> list[dict[str, Any]]: + return list(existing) + + async def fake_insert(**kwargs: Any) -> dict[str, Any]: + inserted.append(kwargs) + return {"id": 11, **kwargs} + + monkeypatch.setattr(store, "_find_memory_item_by_normalized_key", fake_find) + monkeypatch.setattr(store, "_insert_or_touch_memory_item", fake_insert) + scope = { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "user_id": "__group__", + "session_id": "room-a@chatroom", + "window": {"index": 1, "first_event_id": 1, "last_event_id": 8}, + } + + await store._apply_group_relationship_window_candidate( + **scope, + target_date="2026-08-31", + candidate=_candidate( + predicate="co_participated", + confidence=0.45, + reason="deterministic_same_window_participation", + signals={"quote": 0, "mention": 0, "prefix_reply": 0, "co_participation": 1, "llm": 0}, + ), + ) + assert inserted[-1]["status"] == "pending" + assert inserted[-1]["value_json"]["acceptance"]["status"] == "needs_review" + assert inserted[-1]["value_json"]["acceptance"]["reason"] == "group_window_weak_signal" + + llm_day_one = _candidate( + predicate="asked", + confidence=0.88, + reason="asked how to configure kiro2api", + extraction_method="llm_group_window", + signals={"quote": 0, "mention": 0, "prefix_reply": 0, "co_participation": 0, "llm": 1}, + ) + await store._apply_group_relationship_window_candidate( + **scope, target_date="2026-08-31", candidate=llm_day_one + ) + day_one = inserted[-1] + assert day_one["status"] == "pending" + assert day_one["value_json"]["acceptance"]["status"] == "needs_review" + + existing.append( + { + "id": 11, + "source_type": "llm_group_window", + "status": "pending", + "acceptance_status": "needs_review", + "value": day_one["value_json"], + } + ) + await store._apply_group_relationship_window_candidate( + **scope, + target_date="2026-09-01", + candidate={**llm_day_one, "evidence_event_ids": [21]}, + ) + day_two = inserted[-1] + value = day_two["value_json"] + assert value["evidence_dates"] == ["2026-08-31", "2026-09-01"] + assert value["relation"]["signals"]["llm"] == 2 + assert value["acceptance"]["status"] == "accepted" + assert value["acceptance"]["reason"] == "group_window_llm_multi_day" + assert value["acceptance"]["day_count"] == 2 + assert day_two["status"] == "active" + assert value["relation"]["strength"] > day_one["value_json"]["relation"]["strength"] + + +@pytest.mark.asyncio +async def test_window_candidate_auto_accept_disabled_keeps_everything_in_review( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace(memory_group_graph_auto_accept=False)) + inserted: list[dict[str, Any]] = [] + + async def fake_find(**kwargs: Any) -> list[dict[str, Any]]: return [] - monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + async def fake_insert(**kwargs: Any) -> dict[str, Any]: + inserted.append(kwargs) + return {"id": 11, **kwargs} - result = await store.auto_accept_pending_group_window_relations( + monkeypatch.setattr(store, "_find_memory_item_by_normalized_key", fake_find) + monkeypatch.setattr(store, "_insert_or_touch_memory_item", fake_insert) + + await store._apply_group_relationship_window_candidate( tenant_id="demo", channel="wechat", source_key="wxbot", + user_id="__group__", session_id="room-a@chatroom", + target_date="2026-08-31", + window={"index": 1, "first_event_id": 1, "last_event_id": 8}, + candidate=_candidate(), ) - assert any(sql.strip().startswith("UPDATE plugin_memory_item") for sql in seen) - assert result["accepted"] == 2 - assert result["facts_activated"] == 2 - assert result["entities_activated"] == 1 - assert result["failed"] == 0 + assert inserted[0]["status"] == "pending" + assert inserted[0]["value_json"]["acceptance"]["status"] == "needs_review" + + +def _observation_row( + row_id: int, + sender: str, + content: str, + *, + sender_name: str = "", + quote_from: str = "", + quote_sender_name: str = "", + at_wxids: list[str] | None = None, + bot_wxid: str = "wxid_bot", +) -> dict[str, Any]: + return { + "id": row_id, + "user_id": sender, + "user_text": f"{sender}: {content}", + "_graph_source": "observation", + "_observation": { + "sender_name": sender_name, + "quote_from": quote_from, + "quote_sender_name": quote_sender_name, + "quote_message_id": "", + "at_wxids": list(at_wxids or []), + "bot_wxid": bot_wxid, + }, + } -@pytest.mark.asyncio -async def test_auto_extract_cursor_round_trips_in_durable_job_state( - monkeypatch: pytest.MonkeyPatch, -) -> None: +def test_deterministic_rules_use_quote_and_mention_metadata() -> None: store = MemoryStore(SimpleNamespace()) - state: dict[str, str] = {} - writes: list[tuple[str, dict[str, Any]]] = [] - - async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: - params = params or {} - writes.append((sql, params)) - if sql.startswith("SELECT result_json"): - payload = state.get(str(params["cursor_key"])) - return [{"result_json": payload}] if payload else [] - if sql.startswith("INSERT INTO plugin_memory_extraction_job"): - state[str(params["cursor_key"])] = str(params["result_json"]) - return [] + from plugins.memory.store_group_graph import GroupMemberDirectory + + directory = GroupMemberDirectory() + # Membership knows the alias id form for 千羽 that quotes use. + directory.add_member("qianyu_alias", "千羽") + window = { + "index": 1, + "first_event_id": 1, + "last_event_id": 6, + "rows": [ + _observation_row(1, "wxid_qianyu", "kiro2api 配置怎么弄", sender_name="千羽"), + _observation_row(2, "wxid_hai", "看 README", sender_name="小海", + quote_from="qianyu_alias", quote_sender_name="千羽"), + _observation_row(3, "wxid_z", "@小海\u2005 那个链接失效了", sender_name="Z"), + _observation_row(4, "wxid_hai", "@Z 修好了", sender_name="小海", at_wxids=["wxid_z"]), + _observation_row(5, "wxid_z", "@机器人 帮我总结", sender_name="Z", at_wxids=["wxid_bot"]), + _observation_row(6, "wxid_new", "求助", sender_name="新人", + quote_from="wxid_unknown_alias", quote_sender_name="不存在的人"), + ], + } - monkeypatch.setattr(memory_store_module, "_exec", fake_exec) - scope = { - "tenant_id": "demo", - "channel": "wechat", - "source_key": "wxbot", - "session_id": "room-a@chatroom", - "target_date": "2026-08-31", + candidates = store._build_deterministic_group_window_candidates(window, directory=directory) + + by_key = {(c["subject"], c["predicate"], c["object"]): c for c in candidates} + # Quoted reply resolved through the alias → nickname → sender id chain. + quote = by_key[("wxid_hai", "replied_to", "wxid_qianyu")] + assert quote["confidence"] == 0.9 + assert quote["reason"] == "deterministic_quote_reply" + assert quote["signals"]["quote"] == 1 + assert quote["evidence_event_ids"] == [2] + # Text @昵称 resolves through the directory built from the window itself. + text_mention = by_key[("wxid_z", "addressed", "wxid_hai")] + assert text_mention["confidence"] == 0.72 + assert text_mention["signals"]["mention"] == 1 + # Structured at_wxids beat text matching. + metadata_mention = by_key[("wxid_hai", "addressed", "wxid_z")] + assert metadata_mention["confidence"] == 0.85 + assert metadata_mention["reason"] == "deterministic_at_mention_metadata" + # Mentions of the bot itself and unresolvable quote targets are not edges. + assert not any(c["object"] == "wxid_bot" for c in candidates) + assert not any(c["subject"] == "wxid_new" for c in candidates) + assert window["unresolved_targets"] == 1 + # No co_participated pairs by default even though several people spoke twice. + assert not any(c["predicate"] == "co_participated" for c in candidates) + + +def test_deterministic_rules_can_opt_back_into_co_participation() -> None: + store = MemoryStore(SimpleNamespace(memory_group_graph_co_participation_edges=True)) + window = { + "index": 1, + "first_event_id": 1, + "last_event_id": 4, + "rows": [ + {"id": 1, "user_text": "wxid_a: hello"}, + {"id": 2, "user_text": "wxid_b: hi"}, + {"id": 3, "user_text": "wxid_a: how are you"}, + {"id": 4, "user_text": "wxid_b: fine"}, + ], } - assert await store._load_group_graph_auto_extract_cursor(**scope) == 0 - await store._save_group_graph_auto_extract_cursor(**scope, cursor_event_id=731) - assert await store._load_group_graph_auto_extract_cursor(**scope) == 731 - insert_sql, insert_params = next( - (sql, params) for sql, params in writes if sql.startswith("INSERT INTO") - ) - assert "ON CONFLICT (idempotency_key) DO UPDATE" in insert_sql - assert "< :cursor_event_id" in insert_sql - assert insert_params["cursor_event_id"] == 731 + + candidates = store._build_deterministic_group_window_candidates(window) + + assert [(c["predicate"], c["signals"]["co_participation"]) for c in candidates] == [ + ("co_participated", 1) + ] + assert store._build_deterministic_group_window_candidates( + window, co_participation_edges=False + ) == [] @pytest.mark.asyncio -async def test_auto_extract_skips_completed_front_target_without_starving_next( +async def test_member_directory_merges_window_senders_and_membership( monkeypatch: pytest.MonkeyPatch, ) -> None: store = MemoryStore(SimpleNamespace()) - catchup_sessions: list[str] = [] - async def fake_targets(**kwargs: Any) -> list[dict[str, Any]]: + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + assert "FROM plugin_wxbot_group_membership" in sql + assert params is not None and params["sids"] == ["room-a@chatroom"] return [ - { - "tenant_id": "demo", "channel": "wechat", "source_key": "wxbot", - "session_id": "room-a@chatroom", "date": "2026-08-31", - "event_count": 10, "last_event_id": 100, - }, - { - "tenant_id": "demo", "channel": "wechat", "source_key": "wxbot", - "session_id": "room-b@chatroom", "date": "2026-08-31", - "event_count": 10, "last_event_id": 200, - }, + {"user_wxid": "wxid_hai", "user_name": "小海"}, + {"user_wxid": "hai_alias", "user_name": "小海"}, + {"user_wxid": "wxid_quiet", "user_name": "安静的人"}, ] - async def fake_load_cursor(**kwargs: Any) -> int: - return 100 if kwargs["session_id"] == "room-a@chatroom" else 150 - - async def fake_catchup(**kwargs: Any) -> dict[str, Any]: - catchup_sessions.append(kwargs["session_id"]) - return { - "status": "completed", - "stop_reason": "no_more_events", - "totals": {"windows": 1}, - "more_remain": False, - "next_cursor_event_id": 200, - } - - async def fake_save_cursor(**kwargs: Any) -> None: - return None - - monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) - monkeypatch.setattr(store, "_load_group_graph_auto_extract_cursor", fake_load_cursor) - monkeypatch.setattr(store, "_save_group_graph_auto_extract_cursor", fake_save_cursor) - monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) - result = await store.run_group_graph_auto_extract_tick(max_sessions=1) + directory = await store._load_group_member_directory( + tenant_id="demo", + session_ids=["room-a@chatroom", "not-a-group"], + event_rows=[_observation_row(1, "wxid_hai", "hi", sender_name="小海")], + ) - assert catchup_sessions == ["room-b@chatroom"] - assert result["skipped"][0]["reason"] == "up_to_date" - assert result["results"][0]["cursor_event_id"] == 150 - assert result["results"][0]["next_cursor_event_id"] == 200 + # The sender id wins over the alias that shares the nickname. + assert directory.resolve_id("hai_alias") == "wxid_hai" + assert directory.resolve_id("", fallback_name="小海") == "wxid_hai" + assert directory.resolve_name("小海 ") == "wxid_hai" + assert directory.resolve_id("wxid_quiet") == "wxid_quiet" + assert directory.resolve_id("wxid_nobody") is None + assert directory.resolve_id("user:wxid_hai") == "wxid_hai" @pytest.mark.asyncio -async def test_window_catchup_hard_stops_a_hung_window_at_time_budget( +async def test_graph_fact_query_pushes_filters_into_sql( monkeypatch: pytest.MonkeyPatch, ) -> None: store = MemoryStore(SimpleNamespace()) - cancelled = asyncio.Event() + seen: list[tuple[str, dict[str, Any]]] = [] - async def hung_window(**kwargs: Any) -> dict[str, Any]: - try: - await asyncio.Event().wait() - finally: - cancelled.set() + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + seen.append((sql, dict(params or {}))) + if sql.startswith("SELECT COUNT(*)"): + return [{"count": 1752}] + return [] - monkeypatch.setattr(store, "run_group_relationship_window_extraction", hung_window) + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) - result = await store.run_group_relationship_window_catchup( + await store.list_memory_graph_facts( tenant_id="demo", channel="wechat", source_key="wxbot", - session_id="room-a@chatroom", - date="2026-08-31", - time_budget_seconds=1, + session_ids=["53876528317@chatroom", "cx1:c:abc@chatroom"], + status="active", + limit=500, + predicates=["replied_to", "addressed"], + min_confidence=0.6, + from_date="2026-08-16", + to_date="2026-09-15", + default_accepted_only=True, + order_by_strength=True, ) - - assert result["status"] == "partial" - assert result["stop_reason"] == "time_budget_reached" - assert result["more_remain"] is True - assert cancelled.is_set() - - -@pytest.mark.asyncio -async def test_group_graph_auto_extract_task_start_is_unique() -> None: - plugin = MemoryPlugin() - plugin._ctx = SimpleNamespace( - settings=SimpleNamespace( - memory_group_graph_auto_extract_enabled=True, - memory_group_graph_auto_extract_roles="scheduler", - app_process_role="scheduler", - ) + sql, params = seen[0] + assert "LEFT JOIN plugin_memory_item backing ON backing.id = fact.memory_item_id" in sql + assert "fact.predicate = ANY(:predicates)" in sql + assert params["predicates"] == ["replied_to", "addressed"] + assert "fact.confidence >= :min_confidence" in sql and params["min_confidence"] == 0.6 + assert "= 'accepted' AND backing.status = 'active' AND backing.deleted_at IS NULL" in sql + assert "'last_seen_date'" in sql and ">= :from_date" in sql and params["from_date"] == "2026-08-16" + assert "'first_seen_date'" in sql and "<= :to_date" in sql and params["to_date"] == "2026-09-15" + assert "ORDER BY COALESCE((NULLIF(backing.value_json, '')::jsonb #>> '{relation,strength}')::float, 0) DESC" in sql + assert sql.rstrip().endswith("LIMIT :lim") and params["lim"] == 500 + # Explicit statuses replace the default accepted-only clause. + seen.clear() + await store.list_memory_graph_facts( + tenant_id="demo", acceptance_statuses=["needs_review", "expired"], limit=10 ) - plugin._store = object() # type: ignore[assignment] - started = asyncio.Event() - release = asyncio.Event() + sql, params = seen[0] + assert "= ANY(:acceptance_statuses)" in sql + assert params["acceptance_statuses"] == ["needs_review", "expired"] + assert "backing.deleted_at IS NULL" not in sql - async def fake_loop() -> None: - started.set() - await release.wait() + total = await store.count_memory_graph_facts( + tenant_id="demo", channel="wechat", session_ids=["room-a@chatroom"], predicates=["replied_to"] + ) + assert total == 1752 + count_sql, count_params = seen[-1] + assert count_sql.startswith("SELECT COUNT(*) AS count FROM plugin_memory_fact fact") + assert "backing.session_id = ANY(:sids)" in count_sql and count_params["sids"] == ["room-a@chatroom"] + + +def _entity_row(entity_id: int, name: str, entity_type: str = "person") -> dict[str, Any]: + return { + "id": entity_id, "tenant_id": "demo", "channel": "wechat", "source_key": "wxbot", + "user_id": "__group__", "entity_type": entity_type, "name": name, "normalized_name": name.lower(), + "aliases_json": "[]", "confidence": 0.9, "status": "active", + "created_at": "2026-09-07T08:00:00", "updated_at": "2026-09-07T09:00:00", + } - plugin._group_graph_auto_extract_loop = fake_loop # type: ignore[method-assign] - plugin._ensure_group_graph_auto_extract_task() - first_task = plugin._group_graph_auto_extract_task - plugin._ensure_group_graph_auto_extract_task() - assert plugin._group_graph_auto_extract_task is first_task - assert first_task is not None - await started.wait() - release.set() - await first_task +def _fact_row(fact_id: int, subject: int, obj: int, predicate: str, item_id: int) -> dict[str, Any]: + return { + "id": fact_id, "tenant_id": "demo", "channel": "wechat", "source_key": "wxbot", "user_id": "__group__", + "subject_entity_id": subject, "subject_name": f"e{subject}", "predicate": predicate, + "object_entity_id": obj, "object_name": f"e{obj}", "object_value": "", "memory_item_id": item_id, + "source_event_id": None, "confidence": 0.9 if predicate == "replied_to" else 0.45, "status": "active", + "valid_at": "2026-09-07T08:36:21", "invalid_at": None, + "created_at": "2026-09-07T08:36:21", "updated_at": "2026-09-07T09:20:57", + } -def test_prefer_operator_group_session_id_skips_connection_scoped_ids() -> None: - assert ( - _prefer_operator_group_session_id( - [ - "cx1:c:abc@chatroom", - "53876528317@chatroom", - ], - "cx1:c:abc@chatroom", - ) - == "53876528317@chatroom" - ) +def _item_row(item_id: int, predicate: str, dates: list[str], observation_ids: list[int], strength: float) -> dict[str, Any]: + value = { + "kind": "group_window_relation", + "evidence_dates": dates, + "first_seen_date": min(dates), + "last_seen_date": max(dates), + "evidence_source": "observation", + "source_event_ids": [], + "source_observation_ids": observation_ids, + "relation": { + "predicate": predicate, + "evidence_event_ids": [], + "evidence_observation_ids": observation_ids, + "signals": {"quote": len(observation_ids) if predicate == "replied_to" else 0, "mention": 0, + "prefix_reply": 0, "co_participation": 0 if predicate == "replied_to" else 1, "llm": 0}, + "strength": strength, + }, + "acceptance": {"status": "accepted", "reason": "group_window_direct_signal"}, + } + return { + "id": item_id, "tenant_id": "demo", "channel": "wechat", "source_key": "wxbot", "user_id": "__group__", + "session_id": "53876528317@chatroom", "scope_type": "session", "source_type": "deterministic_group_window", + "memory_type": "note", "content": "Group window relation", "value_json": json.dumps(value), + "normalized_key": f"group-window-rel:{predicate}:{item_id}", "confidence": 0.9, "status": "active", + "pinned": False, "priority": 0, "sensitivity": "normal", "source_event_id": None, "source_trace_id": "", + "original_text": "", "occurrence_count": 1, "first_seen_at": None, "last_seen_at": None, + "created_at": "2026-09-07T08:36:21", "updated_at": "2026-09-07T09:20:57", "deleted_at": None, + } @pytest.mark.asyncio -async def test_list_known_sessions_include_recent_runtime_activity( +async def test_graph_read_reports_evidence_dates_merges_pairs_and_backfills_endpoints( monkeypatch: pytest.MonkeyPatch, ) -> None: store = MemoryStore(SimpleNamespace()) + seen: list[str] = [] async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: - if "FROM plugin_memory_event" in sql: - return [] - if "updated_at >=" in sql: + params = params or {} + seen.append(sql) + if "FROM sessions" in sql: + return _ALIAS_ROWS + if sql.startswith("SELECT COUNT(*)"): + return [{"count": 2780}] + if "FROM plugin_memory_entity entity" in sql and "entity.id = ANY(:ids)" in sql: + # Endpoints the recency-ordered entity page did not include. + assert set(params["ids"]) == {2, 3} + return [_entity_row(2, "千羽"), _entity_row(3, "小海")] + if "FROM plugin_memory_entity entity" in sql: + return [_entity_row(1, "洋白")] + if "FROM plugin_memory_fact fact" in sql: return [ - { - "tenant_id": "demo", + _fact_row(10, 1, 2, "co_participated", 100), + _fact_row(11, 2, 1, "co_participated", 101), + _fact_row(12, 1, 3, "replied_to", 102), + ] + if "FROM plugin_memory_item WHERE id = ANY" in sql: + return [ + _item_row(100, "co_participated", ["2026-08-09", "2026-09-04"], [154604, 154626], 0.2835), + _item_row(101, "co_participated", ["2026-08-16"], [95955], 0.2835), + _item_row(102, "replied_to", ["2026-08-20", "2026-08-21", "2026-09-02"], [7001, 7002, 7003, 7004], 0.7364), + ] + return [] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + + graph = await store.get_group_relationship_graph( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="cx1:c:abc@chatroom", + from_="2026-08-16T00:00:00", + limit=500, + ) + + edges = {edge["type"]: edge for edge in graph["edges"]} + assert set(edges) == {"co_participated", "replied_to"} + assert graph["counts"] == {"nodes": 3, "edges": 2} + # A→B and B→A co-participation rows became one undirected edge. + pair = edges["co_participated"] + assert pair["mirror_ids"] == ["fact:11"] + assert pair["evidence_count"] == 3 + assert pair["evidence_dates"] == ["2026-08-09", "2026-08-16", "2026-09-04"] + assert pair["first_seen"] == "2026-08-09" and pair["last_seen"] == "2026-09-04" + # Evidence dates drive first/last_seen; the extraction time is separate. + reply = edges["replied_to"] + assert reply["first_seen"] == "2026-08-20" + assert reply["last_seen"] == "2026-09-02" + assert reply["extracted_at"] == "2026-09-07T09:20:57" + assert reply["evidence_count"] == 4 + assert reply["evidence_day_count"] == 3 + assert reply["strength"] == 0.7364 + assert reply["signals"]["quote"] == 4 + assert reply["evidence_source"] == "observation" + # Endpoint 3 (小海) only existed through the by-id backfill. + assert {node["display_label"] for node in graph["nodes"]} == {"洋白", "千羽", "小海"} + assert graph["page"] == { + "limit": 500, + "total": 2780, + "truncated": True, + "order": "strength_desc", + "next_cursor": None, + } + fact_sql = next(sql for sql in seen if "FROM plugin_memory_fact fact" in sql and "COUNT" not in sql) + assert "= 'accepted' AND backing.status = 'active'" in fact_sql + assert ">= :from_date" in fact_sql + + +@pytest.mark.asyncio +async def test_graph_read_time_filter_uses_evidence_dates_not_extraction_time( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + if "FROM sessions" in sql: + return [] + if "FROM plugin_memory_entity entity" in sql: + return [_entity_row(1, "洋白"), _entity_row(3, "小海")] + if "FROM plugin_memory_fact fact" in sql and "COUNT" not in sql: + return [_fact_row(12, 1, 3, "replied_to", 102)] + if "FROM plugin_memory_item WHERE id = ANY" in sql: + return [_item_row(102, "replied_to", ["2026-08-20", "2026-08-21"], [7001, 7002], 0.4866)] + return [] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + scope = {"tenant_id": "demo", "channel": "wechat", "source_key": "wxbot", "session_id": "53876528317@chatroom"} + + # Extracted on 2026-09-07 but observed 08-20..08-21: an August window keeps it... + august = await store.get_group_relationship_graph(**scope, from_="2026-08-01", to="2026-08-31T23:59:59") + assert [edge["id"] for edge in august["edges"]] == ["fact:12"] + # ...and a September-only window drops it even though the fact row is from September. + september = await store.get_group_relationship_graph(**scope, from_="2026-09-01") + assert september["edges"] == [] + + +def test_llm_candidates_must_resolve_people_to_real_participants() -> None: + """Shapes observed from the production model: terms typed as `person`.""" + + store = MemoryStore(SimpleNamespace()) + from plugins.memory.store_group_graph import GroupMemberDirectory + + directory = GroupMemberDirectory() + directory.add_member("wxid_quiet", "安静的人") + participants = ["wxid_a", "wxid_b", "q813235683"] + payload = { + "relations": [ + # Real participant -> real participant: kept as is. + {"subject": "wxid_a", "predicate": "answered", "object": "q813235683", + "object_type": "person", "confidence": 0.8, "evidence_event_ids": [1, 7]}, + # A term the model typed as a person becomes a topic for mention-like predicates. + {"subject": "wxid_a", "predicate": "mentioned", "object": "缩水", + "object_type": "person", "confidence": 0.9, "evidence_event_ids": [2, 7]}, + # ...but a person-only predicate with a phantom person is dropped. + {"subject": "wxid_a", "predicate": "replied_to", "object": "gpt", + "object_type": "person", "confidence": 0.9, "evidence_event_ids": [3, 7]}, + # Unknown subject: dropped. + {"subject": "somebody", "predicate": "asked", "object": "wxid_b", + "object_type": "person", "confidence": 0.9, "evidence_event_ids": [4, 7]}, + # Directory member who did not speak in this window still resolves. + {"subject": "wxid_b", "predicate": "addressed", "object": "安静的人", + "object_type": "person", "confidence": 0.7, "evidence_event_ids": [5, 7]}, + # Explicit topic objects are untouched. + {"subject": "wxid_b", "predicate": "interested_in", "object": "并发", + "object_type": "topic", "confidence": 0.9, "evidence_event_ids": [6, 7]}, + ] + } + + candidates, skipped = store._parse_group_window_candidates( + payload, + allowed_event_ids={1, 2, 3, 4, 5, 6, 7}, + participants=participants, + directory=directory, + ) + + assert skipped == 2 + assert [(c["subject"], c["predicate"], c["object"], c["object_type"]) for c in candidates] == [ + ("wxid_a", "answered", "q813235683", "person"), + ("wxid_a", "mentioned", "缩水", "topic"), + ("wxid_b", "addressed", "wxid_quiet", "person"), + ("wxid_b", "interested_in", "并发", "topic"), + ] + assert all(c["signals"]["llm"] == 2 for c in candidates) + + # Without participant context (legacy callers) nothing is resolved or dropped. + legacy, legacy_skipped = store._parse_group_window_candidates( + payload, allowed_event_ids={1, 2, 3, 4, 5, 6, 7} + ) + assert legacy_skipped == 0 + assert len(legacy) == 6 + + +def test_llm_candidates_drop_noise_shapes_seen_in_production() -> None: + """One-off claims, rule-layer predicates, 'the group' and junk terms are not stored.""" + + store = MemoryStore(SimpleNamespace()) + participants = ["wxid_a", "wxid_b"] + payload = { + "relations": [ + # Single supporting message: not stored, so it cannot clog the review queue. + {"subject": "wxid_a", "predicate": "mentioned", "object": "苹果", + "object_type": "topic", "confidence": 0.95, "evidence_event_ids": [1]}, + # The rule layer owns co-participation. + {"subject": "wxid_a", "predicate": "co_participated", "object": "wxid_b", + "object_type": "person", "confidence": 0.9, "evidence_event_ids": [1, 2]}, + # "asked the group" is not an edge to anything. + {"subject": "wxid_a", "predicate": "asked", "object": "group", + "object_type": "group", "confidence": 0.9, "evidence_event_ids": [1, 2]}, + {"subject": "wxid_a", "predicate": "asked", "object": "大家", + "object_type": "topic", "confidence": 0.9, "evidence_event_ids": [1, 2]}, + # Bare numbers/times, single characters and sentences are not terms. + {"subject": "wxid_a", "predicate": "mentioned", "object": "9点", + "object_type": "topic", "confidence": 0.9, "evidence_event_ids": [1, 2]}, + {"subject": "wxid_a", "predicate": "mentioned", "object": "x", + "object_type": "topic", "confidence": 0.9, "evidence_event_ids": [1, 2]}, + {"subject": "wxid_a", "predicate": "reported_issue", + "object": "elderly users keep forgetting their accounts and passwords again", + "object_type": "topic", "confidence": 0.9, "evidence_event_ids": [1, 2]}, + # An unknown id-shaped "person" is a hallucinated member: dropped, not + # turned into a topic called "wxid_ghost". + {"subject": "wxid_a", "predicate": "mentioned", "object": "wxid_ghost", + "object_type": "person", "confidence": 0.9, "evidence_event_ids": [1, 2]}, + # Kept: a real term with two supporting messages. + {"subject": "wxid_a", "predicate": "interested_in", "object": "DeepSeek", + "object_type": "tool", "confidence": 0.9, "evidence_event_ids": [1, 2]}, + {"subject": "wxid_b", "predicate": "mentioned", "object": "苹果5x", + "object_type": "topic", "confidence": 0.9, "evidence_event_ids": [2, 3]}, + ] + } + + candidates, skipped = store._parse_group_window_candidates( + payload, + allowed_event_ids={1, 2, 3}, + participants=participants, + ) + + assert skipped == 8 + assert [(c["subject"], c["predicate"], c["object"], c["object_type"]) for c in candidates] == [ + ("wxid_a", "interested_in", "DeepSeek", "tool"), + ("wxid_b", "mentioned", "苹果5x", "topic"), + ] + + +@pytest.mark.asyncio +async def test_llm_prompt_excludes_rule_layer_predicates_and_asks_for_terms() -> None: + requests: list[Any] = [] + + class _Llm: + async def chat(self, request: Any) -> Any: + requests.append(request) + return SimpleNamespace(content='{"relations": []}') + + store = MemoryStore(SimpleNamespace(), llm_service=_Llm()) + store.graph_extractor.llm_service = _Llm() + + await store._extract_group_relationship_window_candidates( + tenant_id="default", + trace_id="group-window:test", + target_date="2026-09-16", + session_id="53876528317@chatroom", + event_ids=[1, 2], + transcript="[1] a: hi\n[2] b: hello", + ) + + assert len(requests) == 1 + system = str(requests[0].system) + assert "co_participated" not in system + assert "replied_to" in system + assert "at least two different messages" in system + assert "Chinese chat -> Chinese term" in system + + +@pytest.mark.asyncio +async def test_window_llm_request_uses_configured_model_tier( + monkeypatch: pytest.MonkeyPatch, +) -> None: + requests: list[Any] = [] + + class _Llm: + async def chat(self, request: Any) -> Any: + requests.append(request) + return SimpleNamespace(content='{"relations": []}') + + store = MemoryStore(SimpleNamespace(), llm_service=_Llm()) + store.graph_extractor.llm_service = _Llm() + + await store._extract_group_relationship_window_candidates( + tenant_id="demo", trace_id="t", target_date="2026-09-14", + session_id="room-a@chatroom", event_ids=[1, 2], transcript="[event_id=1] a: hi", + ) + assert requests[-1].model_tier == "tier-1" + + store.settings = SimpleNamespace(memory_group_graph_llm_model_tier="tier-2") + await store._extract_group_relationship_window_candidates( + tenant_id="demo", trace_id="t", target_date="2026-09-14", + session_id="room-a@chatroom", event_ids=[1, 2], transcript="[event_id=1] a: hi", + ) + assert requests[-1].model_tier == "tier-2" + + +@pytest.mark.asyncio +async def test_window_catchup_gives_every_window_the_full_llm_timeout( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The budget bounds how many windows run; it is no longer divided by max_windows.""" + + store = MemoryStore(SimpleNamespace(memory_group_graph_llm_timeout_seconds=60)) + calls: list[dict[str, Any]] = [] + + async def fake_window(**kwargs: Any) -> dict[str, Any]: + calls.append(kwargs) + return { + "status": "completed", + "totals": {"events": 50, "windows": 1, "candidates": 1, "applied": 1, "skipped": 0}, + "next_cursor_event_id": 100 * len(calls), + "more_remain": len(calls) < 3, + "source": "observation", + } + + monkeypatch.setattr(store, "run_group_relationship_window_extraction", fake_window) + + result = await store.run_group_relationship_window_catchup( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="room-a@chatroom", + date="2026-09-14", + time_budget_seconds=120, + max_windows_per_run=20, + include_llm=True, + ) + + # Old formula would have handed the model 120 // 20 = 6 seconds. + assert [call["llm_timeout_seconds"] for call in calls] == [60, 60, 60] + assert all(call["llm_mode"] == "inline" for call in calls) + assert result["controls"]["llm_timeout_seconds"] == 60 + assert result["controls"]["llm_mode"] == "inline" + assert result["stop_reason"] == "no_more_events" + + calls.clear() + await store.run_group_relationship_window_catchup( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="room-a@chatroom", + date="2026-09-14", + time_budget_seconds=120, + include_llm=True, + llm_timeout_seconds=45, + llm_mode="enqueue", + ) + assert calls[0]["llm_timeout_seconds"] == 45 + assert calls[0]["llm_mode"] == "enqueue" + # Enqueue mode does not need one-window batches; it walks up to 10 at a time. + assert calls[0]["max_windows"] == 10 + + +@pytest.mark.asyncio +async def test_window_extraction_enqueue_mode_records_one_job_per_window( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace(memory_group_graph_auto_accept=True)) + store.graph_extractor.config = SimpleNamespace(enabled=True) + store.graph_extractor.llm_service = object() + inserts: list[dict[str, Any]] = [] + existing_job_keys: set[str] = set() + extract_calls: list[dict[str, Any]] = [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + params = params or {} + if "FROM sessions" in sql or "FROM plugin_wxbot_group_membership" in sql: + return [] + if "FROM plugin_wxbot_group_observations" in sql: + cursor = int(params.get("cursor_event_id") or 0) + rows = [ + { + "id": 7000 + index, + "tenant_id": "demo", + "session_id": "room-a@chatroom", + "sender_wxid": f"wxid_{index % 3}", + "sender_name": f"member {index % 3}", + "content": f"message {index}", + "occurred_ts": 1757808000 + index * 30, + "is_self_sent": False, + "metadata_json": "{}", + } + for index in range(15) + ] + return [row for row in rows if row["id"] > cursor][: int(params.get("lim") or 100)] + if sql.startswith("INSERT INTO plugin_memory_extraction_job"): + assert "ON CONFLICT (idempotency_key) DO NOTHING" in sql + key = str(params["job_key"]) + inserts.append(dict(params)) + if key in existing_job_keys: + return [] + existing_job_keys.add(key) + return [{"id": len(existing_job_keys)}] + return [] + + async def fake_extract(**kwargs: Any) -> dict[str, Any]: + extract_calls.append(kwargs) + return {"relations": []} + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + monkeypatch.setattr(store, "_extract_group_relationship_window_candidates", fake_extract) + + first = await store.run_group_relationship_window_extraction( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="room-a@chatroom", + date="2026-09-14", + window_size=10, + max_windows=5, + include_llm=True, + llm_mode="enqueue", + source="observation", + ) + + assert extract_calls == [] + assert first["llm_jobs_enqueued"] == 2 + assert first["status"] == "completed" + assert [window["llm_job"] for window in first["windows"]] == ["enqueued", "enqueued"] + assert "llm_window_jobs" in first["generated_from"] + assert "llm_window_extractor" not in first["generated_from"] + assert all(params["trace"].startswith("group-window-llm:") for params in inserts) + assert all(params["group_uid"] == "__group__" for params in inserts) + payload = json.loads(inserts[0]["result_json"]) + assert payload["kind"] == "group_window_llm" + assert payload["scope"]["source"] == "observation" + assert payload["window"] == { + "index": 1, + "first_event_id": 7000, + "last_event_id": 7009, + "event_count": 10, + "window_size": 10, + } + + second = await store.run_group_relationship_window_extraction( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="room-a@chatroom", + date="2026-09-14", + window_size=10, + max_windows=5, + include_llm=True, + llm_mode="enqueue", + source="observation", + ) + + # Same windows again: idempotent, nothing new queued, still not "skipped". + assert second["llm_jobs_enqueued"] == 0 + assert [window["llm_job"] for window in second["windows"]] == ["exists", "exists"] + assert second["status"] == "completed" + + +@pytest.mark.asyncio +async def test_run_group_window_llm_jobs_processes_claimed_windows( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore( + SimpleNamespace( + memory_group_graph_llm_timeout_seconds=60, + memory_group_graph_llm_jobs_per_tick=6, + ) + ) + store.graph_extractor.config = SimpleNamespace(enabled=True) + store.graph_extractor.llm_service = object() + finished: list[dict[str, Any]] = [] + window_calls: list[dict[str, Any]] = [] + + def job(job_id: int, first: int, last: int, count: int, attempts: int = 0) -> dict[str, Any]: + return { + "id": job_id, + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-a@chatroom", + "attempts": attempts, + "max_attempts": 3, + "result_json": json.dumps( + { + "kind": "group_window_llm", + "scope": { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-a@chatroom", + "date": "2026-09-14", + "source": "observation", + }, + "window": { + "index": 1, + "first_event_id": first, + "last_event_id": last, + "event_count": count, + "window_size": 50, + }, + } + ), + } + + async def fake_claim(**kwargs: Any) -> list[dict[str, Any]]: + assert kwargs["limit"] == 6 + return [job(1, 7000, 7049, 50), job(2, 7050, 7099, 50), job(3, 7100, 7120, 21, attempts=2)] + + async def fake_finish(job_row: dict[str, Any], **kwargs: Any) -> None: + finished.append({"id": job_row["id"], **kwargs}) + + async def fake_window(**kwargs: Any) -> dict[str, Any]: + window_calls.append(kwargs) + first = kwargs["cursor_event_id"] + 1 + if first == 7050: + return { + "status": "partial", + "totals": {"events": 50, "windows": 1, "candidates": 0, "applied": 0, "skipped": 1}, + "llm_failures": 1, + } + if first == 7100: + raise RuntimeError("provider down") + return { + "status": "completed", + "totals": {"events": 50, "windows": 1, "candidates": 4, "applied": 4, "skipped": 0}, + "llm_failures": 0, + "signal_counts": {"llm": 4}, + } + + monkeypatch.setattr(store, "_claim_group_window_llm_jobs", fake_claim) + monkeypatch.setattr(store, "_finish_group_window_llm_job", fake_finish) + monkeypatch.setattr(store, "run_group_relationship_window_extraction", fake_window) + + summary = await store.run_group_window_llm_jobs() + + assert summary["claimed"] == 3 + assert summary["succeeded"] == 1 + assert summary["failed"] == 1 + assert summary["dead"] == 1 + assert summary["applied"] == 4 + assert summary["controls"]["llm_timeout_seconds"] == 60 + # Each window is re-run alone, LLM only, with the full timeout. + assert all(call["deterministic"] is False for call in window_calls) + assert all(call["llm_mode"] == "inline" for call in window_calls) + assert all(call["include_llm"] is True for call in window_calls) + assert all(call["llm_timeout_seconds"] == 60 for call in window_calls) + assert all(call["max_windows"] == 1 for call in window_calls) + assert all(call["source"] == "observation" for call in window_calls) + assert [call["cursor_event_id"] for call in window_calls] == [6999, 7049, 7099] + assert [call["window_size"] for call in window_calls] == [50, 50, 21] + by_id = {item["id"]: item for item in finished} + assert by_id[1]["status"] == "succeeded" + assert by_id[1]["result"]["totals"]["applied"] == 4 + assert by_id[2]["status"] == "failed" + assert by_id[2]["retry_after_seconds"] == 600 + assert by_id[3]["status"] == "dead" + assert "provider down" in by_id[3]["error"] + + +@pytest.mark.asyncio +async def test_run_group_window_llm_jobs_skips_when_disabled_or_llm_missing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace(memory_group_graph_llm_jobs_per_tick=0)) + store.graph_extractor.config = SimpleNamespace(enabled=True) + store.graph_extractor.llm_service = object() + claimed = False + + async def fake_claim(**kwargs: Any) -> list[dict[str, Any]]: + nonlocal claimed + claimed = True + return [] + + monkeypatch.setattr(store, "_claim_group_window_llm_jobs", fake_claim) + + assert (await store.run_group_window_llm_jobs())["stop_reason"] == "disabled" + assert claimed is False + + store.graph_extractor.llm_service = None + assert (await store.run_group_window_llm_jobs(limit=3))["stop_reason"] == "llm_unavailable" + assert claimed is False + + +@pytest.mark.asyncio +async def test_group_window_job_claim_and_finish_sql( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + seen: list[tuple[str, dict[str, Any]]] = [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + seen.append((sql, dict(params or {}))) + if sql.startswith("WITH candidate AS"): + return [{"id": 5, "result_json": "{}"}] + return [] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + + jobs = await store._claim_group_window_llm_jobs(limit=4, lock_ttl_seconds=150) + assert [item["id"] for item in jobs] == [5] + claim_sql, claim_params = seen[0] + assert "source_trace_id LIKE :trace_prefix" in claim_sql + assert claim_params["trace_prefix"] == "group-window-llm:%" + assert claim_params["lock_ttl"] == 150 + assert "FOR UPDATE SKIP LOCKED" in claim_sql + + await store._finish_group_window_llm_job( + jobs[0], status="failed", error="boom", retry_after_seconds=600 + ) + finish_sql, finish_params = seen[1] + assert finish_sql.startswith("UPDATE plugin_memory_extraction_job SET") + assert "attempts = attempts + 1" in finish_sql + assert finish_params["status"] == "failed" + assert finish_params["retry_after"] == 600 + assert finish_params["error"] == "boom" + + +@pytest.mark.asyncio +async def test_auto_extract_tick_runs_queued_llm_jobs_after_catchup( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + order: list[str] = [] + + async def fake_targets(**kwargs: Any) -> list[dict[str, Any]]: + return [ + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-a@chatroom", + "date": "2026-09-14", + "event_count": 8, + "source": "observation", + "last_observation_id": 9, + } + ] + + async def fake_catchup(**kwargs: Any) -> dict[str, Any]: + order.append("catchup") + assert kwargs["llm_mode"] == "enqueue" + assert kwargs["llm_timeout_seconds"] == 90 + return {"status": "completed", "totals": {"applied": 2}, "more_remain": False, "next_cursor_event_id": 9} + + async def fake_jobs(**kwargs: Any) -> dict[str, Any]: + order.append("llm_jobs") + assert kwargs == {"limit": 4, "llm_timeout_seconds": 90} + return {"claimed": 2, "succeeded": 2, "failed": 0, "dead": 0, "deferred": 0, "applied": 5, "stop_reason": "completed"} + + async def fake_auto_review(**kwargs: Any) -> dict[str, Any]: + order.append("auto_review") + assert kwargs == {"limit": 50} + return {"scanned": 3, "accepted": 2, "accepted_term": 1, "accepted_pair": 1, "remaining": 1, "stop_reason": "completed"} + + monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) + monkeypatch.setattr(store, "run_group_relation_auto_review", _no_auto_review) + monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) + monkeypatch.setattr(store, "run_group_window_llm_jobs", fake_jobs) + monkeypatch.setattr(store, "run_group_relation_auto_review", fake_auto_review) + monkeypatch.setattr( + store, "_load_group_graph_auto_extract_cursor", lambda **kwargs: asyncio.sleep(0, result=0) + ) + monkeypatch.setattr( + store, "_save_group_graph_auto_extract_cursor", lambda **kwargs: asyncio.sleep(0) + ) + + result = await store.run_group_graph_auto_extract_tick( + llm_jobs_per_tick=4, + llm_timeout_seconds=90, + auto_review_batch=50, + ) + + # The corroboration sweep runs last so this tick's model output can already + # be checked against the accepted graph. + assert order == ["catchup", "llm_jobs", "auto_review"] + assert result["llm_jobs"]["succeeded"] == 2 + assert result["applied"] == 7 + assert result["auto_review"]["accepted"] == 2 + + order.clear() + await store.run_group_graph_auto_extract_tick( + include_llm=False, llm_timeout_seconds=90, auto_review_batch=50 + ) + assert order == ["catchup", "auto_review"] + + +@pytest.mark.asyncio +async def test_group_relation_auto_review_accepts_only_corroborated_candidates( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace(memory_group_graph_auto_review_batch=200)) + reviews: list[tuple[int, str, str, str]] = [] + + async def fake_candidates(**kwargs: Any) -> list[dict[str, Any]]: + assert kwargs == {"limit": 200, "tenant_id": None} + return [ + # Term already used by another accepted relation in this group. + {"id": 1, "object_type": "tool", "term_corroborated": True, "pair_corroborated": False}, + # Term nobody else has an accepted relation with: stays pending. + {"id": 2, "object_type": "topic", "term_corroborated": False, "pair_corroborated": False}, + # Two people who already share an accepted direct edge. + {"id": 3, "object_type": "person", "term_corroborated": True, "pair_corroborated": True}, + # Person pair without any accepted edge: stays pending, even though the + # other person is the object of accepted relations elsewhere. + {"id": 4, "object_type": "person", "term_corroborated": True, "pair_corroborated": False}, + ] + + async def fake_review(item_id: int, **kwargs: Any) -> dict[str, Any] | None: + reviews.append((item_id, kwargs["action"], kwargs["review_reason"], kwargs["reviewed_by"])) + return {"id": item_id, "acceptance_status": "accepted"} + + monkeypatch.setattr(store, "_list_group_relation_auto_review_candidates", fake_candidates) + monkeypatch.setattr(store, "review_memory_item_acceptance", fake_review) + + summary = await store.run_group_relation_auto_review() + + assert reviews == [ + (1, "accept", "group_window_term_corroborated", "system/auto-review"), + (3, "accept", "group_window_pair_corroborated", "system/auto-review"), + ] + assert summary["scanned"] == 4 + assert summary["accepted"] == 2 + assert summary["accepted_term"] == 1 + assert summary["accepted_pair"] == 1 + assert summary["remaining"] == 2 + assert summary["stop_reason"] == "completed" + + assert (await store.run_group_relation_auto_review(limit=0))["stop_reason"] == "disabled" + + +@pytest.mark.asyncio +async def test_group_relation_auto_review_candidates_are_scoped_to_the_same_group( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + calls: list[tuple[str, dict[str, Any]]] = [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + calls.append((sql, dict(params or {}))) + return [ + { + "id": 7, + "tenant_id": "demo", + "session_id": "room-a@chatroom", + "predicate": "interested_in", + "object_type": "tool", + "term_corroborated": True, + "pair_corroborated": False, + } + ] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + + rows = await store._list_group_relation_auto_review_candidates(limit=25, tenant_id="demo") + + assert rows[0]["id"] == 7 + sql, params = calls[0] + assert params["limit"] == 25 + assert params["tid"] == "demo" + assert params["llm_source"] == "llm_group_window" + # Only pending model relations with a real object entity are candidates. + assert "item.status = 'pending'" in sql + assert "item.source_type = :llm_source" in sql + assert "fact.object_entity_id IS NOT NULL" in sql + # Corroboration never crosses groups or counts the candidate itself, and + # co-participation is too weak to corroborate a person pair. + assert sql.count("other_item.session_id = pending.session_id") == 2 + assert sql.count("other.memory_item_id <> pending.id") == 2 + assert "other.predicate <> :weak_predicate" in sql + assert params["weak_predicate"] == "co_participated" + + +@pytest.mark.asyncio +async def test_auto_accept_pending_group_window_relations( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + seen: list[str] = [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + seen.append(sql) + if "FROM sessions" in sql: + return [{"session_id": "room-a@chatroom"}] + if sql.strip().startswith("UPDATE plugin_memory_item"): + assert params is not None + assert params["sids"] == ["room-a@chatroom"] + assert "group_window_auto_accept" in sql + return [{"id": 21}, {"id": 22}] + if sql.strip().startswith("UPDATE plugin_memory_fact"): + return [{"id": 201}, {"id": 202}] + if sql.strip().startswith("UPDATE plugin_memory_entity"): + return [{"id": 11}] + return [] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + + result = await store.auto_accept_pending_group_window_relations( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="room-a@chatroom", + ) + + assert any(sql.strip().startswith("UPDATE plugin_memory_item") for sql in seen) + assert result["accepted"] == 2 + assert result["facts_activated"] == 2 + assert result["entities_activated"] == 1 + assert result["failed"] == 0 + + +@pytest.mark.asyncio +async def test_auto_extract_cursor_round_trips_in_durable_job_state( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + state: dict[str, str] = {} + writes: list[tuple[str, dict[str, Any]]] = [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + params = params or {} + writes.append((sql, params)) + if sql.startswith("SELECT result_json"): + payload = state.get(str(params["cursor_key"])) + return [{"result_json": payload}] if payload else [] + if sql.startswith("INSERT INTO plugin_memory_extraction_job"): + state[str(params["cursor_key"])] = str(params["result_json"]) + return [] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + scope = { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-a@chatroom", + "target_date": "2026-08-31", + } + assert await store._load_group_graph_auto_extract_cursor(**scope) == 0 + await store._save_group_graph_auto_extract_cursor(**scope, cursor_event_id=731) + assert await store._load_group_graph_auto_extract_cursor(**scope) == 731 + insert_sql, insert_params = next( + (sql, params) for sql, params in writes if sql.startswith("INSERT INTO") + ) + assert "ON CONFLICT (idempotency_key) DO UPDATE" in insert_sql + assert "< :cursor_event_id" in insert_sql + assert insert_params["cursor_event_id"] == 731 + + +@pytest.mark.asyncio +async def test_auto_extract_skips_completed_front_target_without_starving_next( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + catchup_sessions: list[str] = [] + + async def fake_targets(**kwargs: Any) -> list[dict[str, Any]]: + return [ + { + "tenant_id": "demo", "channel": "wechat", "source_key": "wxbot", + "session_id": "room-a@chatroom", "date": "2026-08-31", + "event_count": 10, "last_event_id": 100, + }, + { + "tenant_id": "demo", "channel": "wechat", "source_key": "wxbot", + "session_id": "room-b@chatroom", "date": "2026-08-31", + "event_count": 10, "last_event_id": 200, + }, + ] + + async def fake_load_cursor(**kwargs: Any) -> int: + return 100 if kwargs["session_id"] == "room-a@chatroom" else 150 + + async def fake_catchup(**kwargs: Any) -> dict[str, Any]: + catchup_sessions.append(kwargs["session_id"]) + return { + "status": "completed", + "stop_reason": "no_more_events", + "totals": {"windows": 1}, + "more_remain": False, + "next_cursor_event_id": 200, + } + + async def fake_save_cursor(**kwargs: Any) -> None: + return None + + monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) + monkeypatch.setattr(store, "run_group_relation_auto_review", _no_auto_review) + monkeypatch.setattr(store, "_load_group_graph_auto_extract_cursor", fake_load_cursor) + monkeypatch.setattr(store, "_save_group_graph_auto_extract_cursor", fake_save_cursor) + monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) + + result = await store.run_group_graph_auto_extract_tick(max_sessions=1) + + assert catchup_sessions == ["room-b@chatroom"] + assert result["skipped"][0]["reason"] == "up_to_date" + assert result["results"][0]["cursor_event_id"] == 150 + assert result["results"][0]["next_cursor_event_id"] == 200 + + +@pytest.mark.asyncio +async def test_window_catchup_hard_stops_a_hung_window_at_time_budget( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + cancelled = asyncio.Event() + + async def hung_window(**kwargs: Any) -> dict[str, Any]: + try: + await asyncio.Event().wait() + finally: + cancelled.set() + + monkeypatch.setattr(store, "run_group_relationship_window_extraction", hung_window) + + result = await store.run_group_relationship_window_catchup( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="room-a@chatroom", + date="2026-08-31", + time_budget_seconds=1, + ) + + assert result["status"] == "partial" + assert result["stop_reason"] == "time_budget_reached" + assert result["more_remain"] is True + assert cancelled.is_set() + + +@pytest.mark.asyncio +async def test_group_graph_auto_extract_task_start_is_unique() -> None: + plugin = MemoryPlugin() + plugin._ctx = SimpleNamespace( + settings=SimpleNamespace( + memory_group_graph_auto_extract_enabled=True, + memory_group_graph_auto_extract_roles="scheduler", + app_process_role="scheduler", + ) + ) + plugin._store = object() # type: ignore[assignment] + started = asyncio.Event() + release = asyncio.Event() + + async def fake_loop() -> None: + started.set() + await release.wait() + + plugin._group_graph_auto_extract_loop = fake_loop # type: ignore[method-assign] + plugin._ensure_group_graph_auto_extract_task() + first_task = plugin._group_graph_auto_extract_task + plugin._ensure_group_graph_auto_extract_task() + + assert plugin._group_graph_auto_extract_task is first_task + assert first_task is not None + await started.wait() + release.set() + await first_task + + +def test_prefer_operator_group_session_id_skips_connection_scoped_ids() -> None: + assert ( + _prefer_operator_group_session_id( + [ + "cx1:c:abc@chatroom", + "53876528317@chatroom", + ], + "cx1:c:abc@chatroom", + ) + == "53876528317@chatroom" + ) + + +@pytest.mark.asyncio +async def test_list_known_sessions_include_recent_runtime_activity( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + if "FROM plugin_memory_event" in sql: + return [] + if "FROM plugin_wxbot_group_observations" in sql: + return [ + { + "tenant_id": "demo", + "session_id": "cx1:c:abc@chatroom", + "event_count": 41, + "last_seen_ts": 1757900000, + } + ] + if "updated_at >=" in sql: + return [ + { + "tenant_id": "demo", + "channel": "wechat", + "session_id": "cx1:c:abc@chatroom", + } + ] + return [ + { + "session_id": "cx1:c:abc@chatroom", + "external_id": "53876528317@chatroom", + "external_session_id": "", + "canonical_id": "cx1:c:abc@chatroom", + } + ] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + + sessions = await store.list_known_group_graph_sessions(lookback_days=7, max_sessions=5) + + # Live observations count as activity for a group that has no imported + # memory events; the runtime alias collapses onto the operator id. + assert sessions == [ + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "53876528317@chatroom", + "event_count": 41, + } + ] + + +@pytest.mark.asyncio +async def test_list_imported_targets_collapse_runtime_session_aliases( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + if "FROM sessions" in sql: + return [ + { + "session_id": "cx1:c:abc@chatroom", + "external_id": "53876528317@chatroom", + "external_session_id": "", + "canonical_id": "cx1:c:abc@chatroom", + } + ] + if "FROM plugin_wxbot_group_observations" in sql: + return [] + return [ + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "cx1:c:abc@chatroom", + "day": date(2026, 9, 7), + "event_count": 9, + "last_event_id": 900, + }, + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "53876528317@chatroom", + "day": date(2026, 9, 7), + "event_count": 3, + "last_event_id": 700, + }, + ] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + + targets = await store.list_imported_group_graph_targets(lookback_days=2, max_targets=5) + + assert targets == [ + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "53876528317@chatroom", + "date": "2026-09-07", + "event_count": 12, + "last_event_id": 900, + "last_observation_id": 0, + "memory_event_count": 12, + "observation_count": 0, + "source": "memory_event", + } + ] + + +@pytest.mark.asyncio +async def test_load_group_relationship_events_falls_back_to_live_members( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + seen: list[dict[str, Any]] = [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + seen.append({"sql": sql, "params": dict(params or {})}) + if "FROM sessions" in sql: + return [ + { + "session_id": "cx1:c:abc@chatroom", + "external_id": "53876528317@chatroom", + "external_session_id": "", + "canonical_id": "cx1:c:abc@chatroom", + } + ] + if "user_id = :uid" in sql: + return [] + return [{"id": 11, "user_text": "sender:alice\nhello", "created_at": "2026-09-07T00:00:00"}] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + + rows = await store._load_group_relationship_events( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="53876528317@chatroom", + user_id_scope="__group__", + start_at=date(2026, 9, 7), + end_at=date(2026, 9, 8), + columns="id, user_text, created_at", + ) + + assert [row["id"] for row in rows] == [11] + live_query = next(item for item in seen if "FROM plugin_memory_event" in item["sql"] and "user_id = :uid" not in item["sql"]) + assert live_query["params"]["sids"] == [ + "53876528317@chatroom", + "cx1:c:abc@chatroom", + ] + + +@pytest.mark.asyncio +async def test_load_group_relationship_events_uses_group_observations_when_memory_empty( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + seen: list[str] = [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + seen.append(sql) + if "FROM sessions" in sql: + return [ + { + "session_id": "cx1:c:abc@chatroom", + "external_id": "53876528317@chatroom", + "external_session_id": "", + "canonical_id": "cx1:c:abc@chatroom", + } + ] + if "FROM plugin_memory_event" in sql: + return [] + if "FROM plugin_wxbot_group_observations" in sql: + assert params is not None + assert "53876528317@chatroom" in params["sids"] + assert "cx1:c:abc@chatroom" in params["sids"] + return [ + { + "id": 88, + "tenant_id": "demo", + "session_id": "cx1:c:abc@chatroom", + "sender_wxid": "wxid_a", + "content": "hello", + "occurred_ts": 1757203200, + } + ] + return [] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + + rows = await store._load_group_relationship_events( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="53876528317@chatroom", + user_id_scope="__group__", + start_at=datetime(2026, 8, 9), + end_at=datetime(2026, 8, 10), + columns="id, user_text, created_at", + ) + + assert [row["id"] for row in rows] == [88] + assert rows[0]["_graph_source"] == "observation" + assert rows[0]["user_text"].startswith("wxid_a:") + assert any("plugin_wxbot_group_observations" in sql for sql in seen) + + +@pytest.mark.asyncio +async def test_group_relationship_graph_queries_bind_requested_session( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + calls: list[tuple[str, dict[str, Any]]] = [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + calls.append((sql, dict(params or {}))) + return [] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + + await store.get_group_relationship_graph( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="53876528317@chatroom", + limit=10, + ) + + entity_sql, entity_params = next( + (sql, params) for sql, params in calls if "FROM plugin_memory_entity entity" in sql + ) + fact_sql, fact_params = next( + (sql, params) for sql, params in calls if "FROM plugin_memory_fact fact" in sql + ) + assert "scope_item.session_id = :sid" in entity_sql + assert entity_params["sid"] == "53876528317@chatroom" + assert "scope_item.session_id = :sid" in fact_sql + assert fact_params["sid"] == "53876528317@chatroom" + + +_ALIAS_ROWS = [ + { + "session_id": "cx1:c:abc@chatroom", + "external_id": "53876528317@chatroom", + "external_session_id": "", + "canonical_id": "cx1:c:abc@chatroom", + } +] + + +@pytest.mark.asyncio +async def test_list_imported_targets_include_observation_only_days( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Days that only exist in the live observation stream become targets.""" + + store = MemoryStore(SimpleNamespace()) + seen_sql: list[str] = [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + seen_sql.append(sql) + if "FROM sessions" in sql: + return _ALIAS_ROWS + if "FROM plugin_memory_event" in sql: + return [ + { + "tenant_id": "demo", "channel": "wechat", + "source_key": "wxbot", + "session_id": "53876528317@chatroom", + "day": date(2026, 9, 6), + "event_count": 5, + "last_event_id": 60, + } + ] + if "FROM plugin_wxbot_group_observations" in sql: + assert params is not None + assert isinstance(params["start_ts"], int) + return [ + { + "tenant_id": "demo", "session_id": "cx1:c:abc@chatroom", - } + "day": date(2026, 9, 7), + "event_count": 1200, + "last_event_id": 154626, + }, + { + "tenant_id": "demo", + "session_id": "cx1:c:abc@chatroom", + "day": date(2026, 9, 6), + "event_count": 900, + "last_event_id": 153000, + }, ] - return [ - { - "session_id": "cx1:c:abc@chatroom", - "external_id": "53876528317@chatroom", - "external_session_id": "", - "canonical_id": "cx1:c:abc@chatroom", - } - ] + return [] monkeypatch.setattr(memory_store_module, "_exec", fake_exec) - sessions = await store.list_known_group_graph_sessions(lookback_days=7, max_sessions=5) + targets = await store.list_imported_group_graph_targets(lookback_days=3, max_targets=5) - assert sessions == [ - { - "tenant_id": "demo", - "channel": "wechat", - "source_key": "wxbot", - "session_id": "53876528317@chatroom", - "event_count": 0, - } + assert any("plugin_wxbot_group_observations" in sql for sql in seen_sql) + assert [(item["date"], item["source"]) for item in targets] == [ + ("2026-09-07", "observation"), + ("2026-09-06", "memory_event"), ] + observation_day = targets[0] + assert observation_day["session_id"] == "53876528317@chatroom" + assert observation_day["event_count"] == 1200 + assert observation_day["last_observation_id"] == 154626 + assert observation_day["last_event_id"] == 0 + # A day with imported events keeps memory events as its source even when + # observations also exist for it. + mixed_day = targets[1] + assert mixed_day["memory_event_count"] == 5 + assert mixed_day["observation_count"] == 900 + assert mixed_day["last_event_id"] == 60 + assert mixed_day["last_observation_id"] == 153000 @pytest.mark.asyncio -async def test_list_imported_targets_collapse_runtime_session_aliases( +async def test_auto_extract_tick_runs_observation_targets_with_their_own_cursor( monkeypatch: pytest.MonkeyPatch, ) -> None: store = MemoryStore(SimpleNamespace()) + catchup_calls: list[dict[str, Any]] = [] + cursor_loads: list[dict[str, Any]] = [] + cursor_saves: list[dict[str, Any]] = [] - async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: - if "FROM sessions" in sql: - return [ - { - "session_id": "cx1:c:abc@chatroom", - "external_id": "53876528317@chatroom", - "external_session_id": "", - "canonical_id": "cx1:c:abc@chatroom", - } - ] + async def fake_targets(**kwargs: Any) -> list[dict[str, Any]]: + base = {"tenant_id": "demo", "channel": "wechat", "source_key": "wxbot"} return [ { - "tenant_id": "demo", - "channel": "wechat", - "source_key": "wxbot", - "session_id": "cx1:c:abc@chatroom", - "day": date(2026, 9, 7), - "event_count": 9, - "last_event_id": 900, + **base, + "session_id": "room-a@chatroom", + "date": "2026-09-07", + "event_count": 1200, + "last_event_id": 0, + "last_observation_id": 154626, + "source": "observation", }, { - "tenant_id": "demo", - "channel": "wechat", - "source_key": "wxbot", - "session_id": "53876528317@chatroom", - "day": date(2026, 9, 7), - "event_count": 3, - "last_event_id": 700, + **base, + "session_id": "room-a@chatroom", + "date": "2026-09-06", + "event_count": 300, + "last_event_id": 0, + "last_observation_id": 153000, + "source": "observation", }, ] - monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + async def fake_load_cursor(**kwargs: Any) -> int: + cursor_loads.append(kwargs) + return 153000 if kwargs["target_date"] == "2026-09-06" else 154000 - targets = await store.list_imported_group_graph_targets(lookback_days=2, max_targets=5) + async def fake_save_cursor(**kwargs: Any) -> None: + cursor_saves.append(kwargs) - assert targets == [ + async def fake_catchup(**kwargs: Any) -> dict[str, Any]: + catchup_calls.append(kwargs) + return { + "status": "completed", + "stop_reason": "no_more_events", + "totals": {"windows": 2, "applied": 7}, + "more_remain": False, + "next_cursor_event_id": 154626, + "source": "observation", + } + + monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) + monkeypatch.setattr(store, "run_group_relation_auto_review", _no_auto_review) + monkeypatch.setattr(store, "_load_group_graph_auto_extract_cursor", fake_load_cursor) + monkeypatch.setattr(store, "_save_group_graph_auto_extract_cursor", fake_save_cursor) + monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) + + result = await store.run_group_graph_auto_extract_tick(include_llm=False) + + # The cursor is looked up per source so memory-event and observation ids + # never get compared with each other. + assert all(call["source"] == "observation" for call in cursor_loads) + assert catchup_calls == [ { "tenant_id": "demo", "channel": "wechat", "source_key": "wxbot", - "session_id": "53876528317@chatroom", + "session_id": "room-a@chatroom", "date": "2026-09-07", - "event_count": 12, - "last_event_id": 900, + "window_size": 50, + "max_windows_per_run": 20, + "cursor_event_id": 154000, + "time_budget_seconds": 180, + "include_llm": False, + "source": "observation", + "llm_mode": "enqueue", + "llm_timeout_seconds": None, + } + ] + assert cursor_saves == [ + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-a@chatroom", + "target_date": "2026-09-07", + "source": "observation", + "cursor_event_id": 154626, } ] + assert result["skipped_reasons"] == {"up_to_date": 1} + assert result["applied"] == 7 + assert result["ran"] == 1 @pytest.mark.asyncio -async def test_load_group_relationship_events_falls_back_to_live_members( +async def test_auto_extract_cursor_is_scoped_to_its_source( monkeypatch: pytest.MonkeyPatch, ) -> None: store = MemoryStore(SimpleNamespace()) - seen: list[dict[str, Any]] = [] + state: dict[str, str] = {} async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: - seen.append({"sql": sql, "params": dict(params or {})}) - if "FROM sessions" in sql: - return [ - { - "session_id": "cx1:c:abc@chatroom", - "external_id": "53876528317@chatroom", - "external_session_id": "", - "canonical_id": "cx1:c:abc@chatroom", - } - ] - if "user_id = :uid" in sql: - return [] - return [{"id": 11, "user_text": "sender:alice\nhello", "created_at": "2026-09-07T00:00:00"}] + params = params or {} + if sql.startswith("SELECT result_json"): + payload = state.get(str(params["cursor_key"])) + return [{"result_json": payload}] if payload else [] + if sql.startswith("INSERT INTO plugin_memory_extraction_job"): + assert params["cursor_source"] in {"memory_event", "observation"} + assert "<> :cursor_source" in sql + state[str(params["cursor_key"])] = str(params["result_json"]) + return [] monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + scope = { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-a@chatroom", + "target_date": "2026-09-07", + } - rows = await store._load_group_relationship_events( - tenant_id="demo", - channel="wechat", - source_key="wxbot", - session_id="53876528317@chatroom", - user_id_scope="__group__", - start_at=date(2026, 9, 7), - end_at=date(2026, 9, 8), - columns="id, user_text, created_at", + await store._save_group_graph_auto_extract_cursor(**scope, cursor_event_id=731) + + # Legacy cursors (no source) count as memory-event cursors. + assert await store._load_group_graph_auto_extract_cursor(**scope) == 731 + assert await store._load_group_graph_auto_extract_cursor(**scope, source="memory_event") == 731 + assert await store._load_group_graph_auto_extract_cursor(**scope, source="observation") == 0 + + await store._save_group_graph_auto_extract_cursor( + **scope, cursor_event_id=154626, source="observation" ) - assert [row["id"] for row in rows] == [11] - live_query = next(item for item in seen if "FROM plugin_memory_event" in item["sql"] and "user_id = :uid" not in item["sql"]) - assert live_query["params"]["sids"] == [ - "53876528317@chatroom", - "cx1:c:abc@chatroom", - ] + assert await store._load_group_graph_auto_extract_cursor(**scope, source="observation") == 154626 + assert await store._load_group_graph_auto_extract_cursor(**scope, source="memory_event") == 0 @pytest.mark.asyncio -async def test_load_group_relationship_events_uses_group_observations_when_memory_empty( +async def test_load_group_relationship_events_honours_pinned_source( monkeypatch: pytest.MonkeyPatch, ) -> None: store = MemoryStore(SimpleNamespace()) @@ -889,79 +2382,226 @@ async def test_load_group_relationship_events_uses_group_observations_when_memor async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: seen.append(sql) if "FROM sessions" in sql: + return _ALIAS_ROWS + if "FROM plugin_wxbot_group_observations" in sql: return [ { + "id": 88, + "tenant_id": "demo", "session_id": "cx1:c:abc@chatroom", - "external_id": "53876528317@chatroom", - "external_session_id": "", - "canonical_id": "cx1:c:abc@chatroom", + "sender_wxid": "wxid_a", + "content": "hello", + "occurred_ts": 1757203200, } ] - if "FROM plugin_memory_event" in sql: + return [] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + scope = { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "53876528317@chatroom", + "user_id_scope": "__group__", + "start_at": datetime(2026, 9, 7), + "end_at": datetime(2026, 9, 8), + "columns": "id, user_text, created_at", + } + + observation_rows = await store._load_group_relationship_events(**scope, source="observation") + + assert [row["id"] for row in observation_rows] == [88] + assert not any("FROM plugin_memory_event" in sql for sql in seen) + + seen.clear() + memory_rows = await store._load_group_relationship_events(**scope, source="memory_event") + + assert memory_rows == [] + assert any("FROM plugin_memory_event" in sql for sql in seen) + assert not any("FROM plugin_wxbot_group_observations" in sql for sql in seen) + + +@pytest.mark.asyncio +async def test_window_extraction_keeps_observation_evidence_on_its_own_key( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Observation ids are stored as observation evidence instead of being dropped.""" + + store = MemoryStore(SimpleNamespace(memory_group_graph_auto_accept=True)) + inserted: list[dict[str, Any]] = [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + if "FROM sessions" in sql: return [] if "FROM plugin_wxbot_group_observations" in sql: - assert params is not None - assert "53876528317@chatroom" in params["sids"] - assert "cx1:c:abc@chatroom" in params["sids"] return [ { - "id": 88, + "id": 5001, "tenant_id": "demo", - "session_id": "cx1:c:abc@chatroom", + "session_id": "room-a@chatroom", "sender_wxid": "wxid_a", - "content": "hello", + "content": "问一下 kiro2api 的配置", "occurred_ts": 1757203200, - } + }, + { + "id": 5002, + "tenant_id": "demo", + "session_id": "room-a@chatroom", + "sender_wxid": "wxid_b", + "content": "回复: 看 README", + "occurred_ts": 1757203260, + }, ] return [] + async def fake_find(**kwargs: Any) -> list[dict[str, Any]]: + return [] + + async def fake_insert(**kwargs: Any) -> dict[str, Any]: + inserted.append(kwargs) + return {"id": len(inserted), **kwargs} + + async def noop(*args: Any, **kwargs: Any) -> None: + return None + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + monkeypatch.setattr(store, "_find_memory_item_by_normalized_key", fake_find) + monkeypatch.setattr(store, "_insert_or_touch_memory_item", fake_insert) + monkeypatch.setattr(store, "_refresh_legacy_cache_for_item_scope", noop) + monkeypatch.setattr(store, "_sync_memory_graph_for_item_safe", noop) + monkeypatch.setattr(store, "_sync_memory_vector_for_item_safe", noop) - rows = await store._load_group_relationship_events( + result = await store.run_group_relationship_window_extraction( tenant_id="demo", channel="wechat", source_key="wxbot", - session_id="53876528317@chatroom", - user_id_scope="__group__", - start_at=datetime(2026, 8, 9), - end_at=datetime(2026, 8, 10), - columns="id, user_text, created_at", + session_id="room-a@chatroom", + date="2026-09-07", + include_llm=False, + source="observation", ) - assert [row["id"] for row in rows] == [88] - assert rows[0]["_graph_source"] == "observation" - assert rows[0]["user_text"].startswith("wxid_a:") - assert any("plugin_wxbot_group_observations" in sql for sql in seen) + assert result["source"] == "observation" + assert result["generated_from"] == [ + "plugin_wxbot_group_observations", + "deterministic_window_participants", + ] + assert result["totals"]["applied"] == 1 + value = inserted[0]["value_json"] + assert value["evidence_source"] == "observation" + assert value["source_event_ids"] == [] + assert value["source_observation_ids"] == [5001, 5002] + assert value["relation"]["predicate"] == "replied_to" + assert value["relation"]["evidence_event_ids"] == [] + assert value["relation"]["evidence_observation_ids"] == [5001, 5002] + assert value["window"]["source"] == "observation" + # Nothing here may be mistaken for a plugin_memory_event id. + assert inserted[0]["source_event_id"] is None + + +def test_group_graph_edge_quality_reports_observation_evidence() -> None: + quality = _group_graph_edge_quality( + { + "value": { + "evidence_dates": ["2026-09-04", "2026-08-09"], + "first_seen_date": "2026-08-09", + "last_seen_date": "2026-09-04", + "evidence_source": "observation", + "source_observation_ids": [154604, 154610, 154626], + "relation": { + "evidence_event_ids": [], + "evidence_observation_ids": [154604, 154610, 154626], + }, + "acceptance": {"score": 0.45}, + } + } + ) + + assert quality["evidence_event_count"] == 0 + assert quality["evidence_observation_count"] == 3 + assert quality["evidence_day_count"] == 2 + assert quality["evidence_source"] == "observation" + assert quality["first_seen_date"] == "2026-08-09" + assert quality["last_seen_date"] == "2026-09-04" @pytest.mark.asyncio -async def test_group_relationship_graph_queries_bind_requested_session( +async def test_window_stats_expand_runtime_session_aliases( monkeypatch: pytest.MonkeyPatch, ) -> None: store = MemoryStore(SimpleNamespace()) - calls: list[tuple[str, dict[str, Any]]] = [] + requested_sessions: list[str | None] = [] async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: - calls.append((sql, dict(params or {}))) + if "FROM sessions" in sql: + return _ALIAS_ROWS return [] + async def fake_items(**kwargs: Any) -> list[dict[str, Any]]: + requested_sessions.append(kwargs.get("session_id")) + if kwargs.get("session_id") != "53876528317@chatroom": + return [] + return [ + { + "id": 3417, + "status": "active", + "value_json": ( + '{"kind":"group_window_relation","date":"2026-09-04",' + '"evidence_source":"observation",' + '"source_observation_ids":[154604,154626],' + '"relation":{"predicate":"co_participated","evidence_observation_ids":[154604,154626]},' + '"window":{"first_event_id":154604,"last_event_id":154626},' + '"acceptance":{"status":"accepted"}}' + ), + } + ] + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + monkeypatch.setattr(store, "_list_memory_acceptance_audit_items", fake_items) - await store.get_group_relationship_graph( + stats = await store.get_group_relationship_window_stats( tenant_id="demo", channel="wechat", source_key="wxbot", - session_id="53876528317@chatroom", - limit=10, + session_id="cx1:c:abc@chatroom", ) - entity_sql, entity_params = next( - (sql, params) for sql, params in calls if "FROM plugin_memory_entity entity" in sql - ) - fact_sql, fact_params = next( - (sql, params) for sql, params in calls if "FROM plugin_memory_fact fact" in sql - ) - assert "scope_item.session_id = :sid" in entity_sql - assert entity_params["sid"] == "53876528317@chatroom" - assert "scope_item.session_id = :sid" in fact_sql - assert fact_params["sid"] == "53876528317@chatroom" + assert set(requested_sessions) == {"cx1:c:abc@chatroom", "53876528317@chatroom"} + assert stats["scope"]["session_ids"] == ["cx1:c:abc@chatroom", "53876528317@chatroom"] + assert stats["totals"]["items"] == 1 + assert stats["totals"]["accepted"] == 1 + assert stats["totals"]["observations"] == 2 + assert stats["totals"]["events"] == 0 + assert stats["evidence_source_counts"] == {"observation": 1} + assert stats["predicate_counts"] == {"co_participated": 1} + + +@pytest.mark.asyncio +async def test_scope_gate_denial_is_logged(monkeypatch: pytest.MonkeyPatch) -> None: + store = MemoryStore(SimpleNamespace()) + store.runtime_scope_gates_required = True + logged: list[tuple[str, dict[str, Any]]] = [] + + class _Logger: + def debug(self, event: str, **kwargs: Any) -> None: + logged.append((event, kwargs)) + + def info(self, event: str, **kwargs: Any) -> None: + logged.append((event, kwargs)) + + def warning(self, event: str, **kwargs: Any) -> None: + logged.append((event, kwargs)) + + monkeypatch.setattr("plugins.memory.store_group_graph.logger", _Logger()) + + assert await store._group_graph_auto_extract_scope_allowed("demo", "room-a@chatroom") is False + assert logged[-1][0] == "memory.group_graph_auto_extract_scope_denied" + assert logged[-1][1]["reason"] == "scope_gate_unavailable" + + async def denied(tenant_id: str, session_id: str = "") -> bool: + return False + + store.combined_history_scope_execution_allowed = denied + + assert await store._group_graph_auto_extract_scope_allowed("demo", "room-a@chatroom") is False + assert logged[-1][1]["reason"] == "plugin_scope_disabled" diff --git a/tests/unit/test_memory_router.py b/tests/unit/test_memory_router.py index 01b9d72..60a9976 100644 --- a/tests/unit/test_memory_router.py +++ b/tests/unit/test_memory_router.py @@ -2973,6 +2973,32 @@ async def test_memory_router_window_catchup_requires_admin_scrubs_and_passes_con assert "RAW_FIELD_SENTINEL" not in serialized +@pytest.mark.asyncio +async def test_memory_router_window_catchup_passes_explicit_llm_timeout() -> None: + app = FastAPI() + store = _FakeStore() + app.include_router(build_memory_router(store), prefix="/plugins/memory") + + transport = httpx.ASGITransport(app=app) + body = { + "tenant_id": "demo", + "session_id": "room-a@chatroom", + "date": "2026-05-15", + "llm_timeout_seconds": 999, + } + async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: + resp = await client.post( + "/plugins/memory/group-graph/extract-window-catchup", + headers={"Authorization": "Bearer admin_token"}, + json=body, + ) + + assert resp.status_code == 200 + # Clamped to the request-side ceiling and forwarded as a per-window timeout. + assert store.window_catchup_calls[0]["llm_timeout_seconds"] == 180 + assert store.window_catchup_calls[0]["time_budget_seconds"] == 60 + + @pytest.mark.asyncio async def test_memory_router_window_stats_requires_admin_and_scrubs() -> None: app = FastAPI() diff --git a/tests/unit/test_memory_store_compat.py b/tests/unit/test_memory_store_compat.py index d03924e..a90a887 100644 --- a/tests/unit/test_memory_store_compat.py +++ b/tests/unit/test_memory_store_compat.py @@ -2079,12 +2079,18 @@ async def fake_collect_session_history(**kwargs): return [] async def fake_exec(sql: str, params: dict | None = None) -> list[dict]: + if "FROM sessions" in sql: + return [] + if "FROM plugin_wxbot_group_observations" in sql: + return [{"count": 0}] if "FROM plugin_memory_extraction_job" in sql: if len(collect_calls) == 1: return [{"status": "pending", "count": 1}, {"status": "succeeded", "count": 2}] if len(collect_calls) == 2: return [{"status": "failed", "count": 1}] return [] + assert "session_id = ANY(:sids)" in sql + assert params is not None and params["sids"] == ["room-a@chatroom"] if len(collect_calls) == 1: return [{"count": 1}] if len(collect_calls) == 2: @@ -2106,8 +2112,11 @@ async def fake_exec(sql: str, params: dict | None = None) -> list[dict]: assert result["user_id"] == "__group__" assert result["user_id_scope"] == "__group__" assert result["user_id_auto"] is True + assert result["session_ids"] == ["room-a@chatroom"] assert result["items"][0]["raw_message_count"] == 2 assert result["items"][0]["imported_count"] == 1 + assert result["items"][0]["memory_event_count"] == 1 + assert result["items"][0]["observation_count"] == 0 assert result["items"][0]["job_counts"] == { "pending": 1, "running": 0, @@ -2128,6 +2137,57 @@ async def fake_exec(sql: str, params: dict | None = None) -> list[dict]: assert all(call["end_ts"] - call["cutoff_ts"] == 86400 for call in collect_calls) +@pytest.mark.asyncio +async def test_group_graph_history_dates_count_live_observations_across_aliases( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A group addressed by its runtime alias still sees its observation-backed days.""" + + store = MemoryStore(SimpleNamespace()) + observation_params: list[dict] = [] + + async def fake_collect_session_history(**kwargs): + return [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict]: + if "FROM sessions" in sql: + return [ + { + "session_id": "cx1:c:abc@chatroom", + "external_id": "53876528317@chatroom", + "external_session_id": "", + "canonical_id": "cx1:c:abc@chatroom", + } + ] + if "FROM plugin_wxbot_group_observations" in sql: + observation_params.append(dict(params or {})) + return [{"count": 1433}] + if "FROM plugin_memory_extraction_job" in sql: + return [] + return [{"count": 0}] + + monkeypatch.setattr(store, "_collect_session_history", fake_collect_session_history) + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + + result = await store.get_group_graph_history_dates( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="cx1:c:abc@chatroom", + user_id="", + recent_days=1, + ) + + assert result["session_ids"] == ["cx1:c:abc@chatroom", "53876528317@chatroom"] + assert set(observation_params[0]["sids"]) == {"cx1:c:abc@chatroom", "53876528317@chatroom"} + day = result["items"][0] + assert day["raw_message_count"] == 1433 + assert day["observation_count"] == 1433 + assert day["memory_event_count"] == 0 + assert day["imported_count"] == 1433 + assert day["status"] == "extracted" + + @pytest.mark.asyncio async def test_selected_day_extraction_claim_scopes_jobs_by_event_date_and_session( monkeypatch: pytest.MonkeyPatch, @@ -2200,6 +2260,34 @@ async def fake_exec(sql: str, params: dict | None = None) -> list[dict]: assert "job.user_id = :uid AND job.session_id = :sid" in sql assert "created_at >= :start_at AND created_at < :end_at" in sql assert "FOR UPDATE SKIP LOCKED" in sql + # Group-window LLM jobs share the table but belong to their own runner. + assert "job.source_trace_id NOT LIKE :group_window_prefix" in sql + assert seen["params"]["group_window_prefix"] == "group-window-llm:%" + + +@pytest.mark.asyncio +async def test_generic_job_drain_leaves_group_window_jobs_alone( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore( + SimpleNamespace( + memory_llm_extraction_job_enabled=True, + memory_graph_llm_extraction_enabled=True, + ), + llm_service=object(), + ) + seen: dict[str, Any] = {} + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict]: + seen["sql"] = sql + seen["params"] = params or {} + return [] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + + assert await store.claim_llm_extraction_jobs(limit=3, worker_id="drain-worker") == [] + assert "source_trace_id NOT LIKE :group_window_prefix" in seen["sql"] + assert seen["params"]["group_window_prefix"] == "group-window-llm:%" def test_memory_schema_consistency_guard_covers_alembic_migrations() -> None: