service.py 41.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
"""经验中枢:让系统越用越聪明。

四条回路:
1. 问答案例:每次成功的提问自动沉淀成案例(问题、概念、分派与工具路径、取数 SQL、结论摘要)。
   下次有相似问题时召回给主 Agent 当参考;「已验证」且高度相似的直接复用路径(快路径)。
2. SQL / 口径晋升:点赞 → 案例升为已验证,对应的问数 SQL 升为 verified,进入问数的 few-shot;
   点踩 → 案例降权,由点赞晋升的 SQL 退回草稿。
3. 组织记忆(mem0 式):答完后在后台抽取用户说过的口径、偏好,与已有记忆比对后决定
   新增 / 更新 / 删除 / 忽略。个人偏好直接生效;业务口径进审核队列,采纳后全组织生效。
4. 操作习惯:同一个人反复问同类问题、反复发起同一动作或流程卡,达到次数后在工作台建议固化。
   纠错被采纳时,回流成组织记忆、元素同义词和评测用例。

相似度 = 向量余弦(有向量时)与字符二元组重合度的加权;向量服务不可用时只用字面相似度,功能不降级为不可用。
为什么不直接引入 mem0:它默认依赖独立的向量库与 OpenAI,数据会落在元数据库之外,
也脱离工作区隔离、审核与审计;这里用同样的「抽取 → 比对 → 决策」算法,数据留在自己的表里。
"""
from __future__ import annotations

import contextvars
import datetime as dt
import logging
import re
import threading
from typing import Any

import numpy as np
from fastapi import HTTPException
from sqlalchemy import func, select

from ..core import db as core_db
from ..core import identity, llm
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit
from .models import MemCase, MemFact, MemPattern

log = logging.getLogger(__name__)

_NORM = re.compile(r"[\s,。?!、,.?!;;::'\"“”‘’()()\[\]【】]+")
_MD = re.compile(r"(\*\*|__|`|#+ |\[\^[^\]]+\]|\|)")


def _ws() -> str:
    return identity.current().workspace


def _on(key: str, default: str = "1") -> bool:
    return core_db.get_config(key, default).lower() in ("1", "true", "yes")


def enabled() -> bool:
    return _on("MEMORY_ENABLED")


def normalize(q: str) -> str:
    return _NORM.sub("", (q or "").lower())[:500]


# ---------------------------------------------------------------- 相似度
def _bigrams(s: str) -> set[str]:
    s = normalize(s)
    return {s[i:i + 2] for i in range(len(s) - 1)} or ({s} if s else set())


def _lex(a: str, b: str) -> float:
    x, y = _bigrams(a), _bigrams(b)
    if not x or not y:
        return 0.0
    return len(x & y) / len(x | y)


def _embed(text: str) -> list[float] | None:
    try:
        v = llm.embed([text])
        return [round(float(x), 5) for x in v[0]]
    except Exception as e:  # noqa: BLE001
        log.debug("经验中枢向量化失败,只用字面相似度:%s", str(e)[:120])
        return None


_vec_cache: dict[str, Any] = {}


def _vec(raw: str | None) -> Any:
    """库里存的向量 JSON → numpy 数组,按内容缓存。"""
    if not raw or len(raw) < 4:
        return None
    hit = _vec_cache.get(raw)
    if hit is None:
        v = jload(raw, None)
        if not v:
            return None
        if len(_vec_cache) > 6000:
            _vec_cache.clear()
        hit = _vec_cache[raw] = np.asarray(v, dtype=np.float32)
    return hit


def _cos(a: Any, b: Any) -> float | None:
    if a is None or b is None or len(a) == 0 or len(a) != len(b):
        return None
    return float(np.dot(np.asarray(a, dtype=np.float32), np.asarray(b, dtype=np.float32)))


def similarity(q: str, q_emb: Any, text: str, emb: Any) -> float:
    if normalize(q) == normalize(text):
        return 1.0
    lex = _lex(q, text)
    cos = _cos(q_emb, emb)
    if cos is None:
        return lex
    return max(lex, 0.75 * cos + 0.25 * lex)


# ---------------------------------------------------------------- 召回
def _case_dict(c: MemCase, score: float | None = None, full: bool = True) -> dict:
    d = {"id": c.id, "question": c.question, "intent": c.intent, "status": c.status,
         "score": round(score, 3) if score is not None else None, "quality": round(c.score or 0, 2),
         "hits": c.hits, "fast_hits": c.fast_hits, "up_votes": c.up_votes, "down_votes": c.down_votes,
         "answer_summary": c.answer_summary, "concepts": jload(c.concepts_json, []),
         "source_turn": c.source_turn, "created_by": c.created_by,
         "last_hit_at": iso(c.last_hit_at), "created_at": iso(c.created_at), "updated_at": iso(c.updated_at)}
    if full:
        d["plan"] = jload(c.plan_json, {})
        d["sql"] = jload(c.sql_json, [])
    return d


def _fact_dict(f: MemFact, score: float | None = None) -> dict:
    return {"id": f.id, "text": f.text, "kind": f.kind, "scope": f.scope, "scope_ref": f.scope_ref,
            "status": f.status, "source": f.source, "source_turn": f.source_turn, "hits": f.hits,
            "score": round(score, 3) if score is not None else None, "created_by": f.created_by,
            "created_at": iso(f.created_at), "updated_at": iso(f.updated_at)}


def _visible_fact(f: MemFact, actor: identity.Actor) -> bool:
    if f.scope == "user":
        return f.scope_ref == actor.id
    if f.scope == "role":
        return f.scope_ref in (actor.biz_roles or [])
    return True


def _inst_id(i: dict) -> str:
    return f"inst:{i.get('concept_id')}:{i.get('key')}"


def _time_id(t: dict | None) -> str:
    """问句里的时间 → 一个可比较的标记。「上周缺货多少」和「上个月缺货多少」字面只差一个词,路径不能复用。"""
    if not t:
        return ""
    return "time:" + (str(t.get("ref")) if t.get("ref") else f"{t.get('start')}~{t.get('end')}")


def _anchors(concepts: list[dict]) -> set[str]:
    """案例 / 问题里识别出的具体对象(某个仓库、某个供应商……)和时间。快路径要求它们完全一致。"""
    return {str(c.get("id")) for c in concepts
            if c.get("instance") or str(c.get("id", "")).startswith(("inst:", "time:"))}


def is_follow_up(question: str) -> bool:
    """像「那上个月呢」「只看华东仓」这样接着上一句问的话:离开上下文就不成立,不能单独成为案例。"""
    q = (question or "").strip()
    return len(q) <= 12 or bool(re.match(r"^(那|那么|再|换成|改成|只看|如果是|同样|也|另外|还有)", q))


def recall(question: str, links: dict | None = None, k: int = 3, follow_up: bool = False) -> dict:
    """召回相似案例与相关记忆。返回 {cases, facts, fast};fast 是可以直接复用路径的已验证案例。
    follow_up:这句话前面还有对话。追问依赖上下文,不走快路径。"""
    if not enabled() or not question.strip():
        return {"cases": [], "facts": [], "fast": None}
    actor = identity.current()
    q_emb = _embed(question)
    q_emb = np.asarray(q_emb, dtype=np.float32) if q_emb else None
    concept_ids = {c.get("id") for c in (links or {}).get("concepts") or []}
    anchors = {_inst_id(i) for i in (links or {}).get("instances") or []}
    if _time_id((links or {}).get("time")):
        anchors.add(_time_id(links["time"]))
    # 向量余弦对同一业务域的中文问题普遍偏高(0.5~0.7),门槛要比只看字面时高
    case_min, fact_min = (0.62, 0.5) if q_emb is not None else (0.4, 0.3)
    concept_names = [c.get("name") for c in (links or {}).get("concepts") or [] if c.get("name")]
    try:
        fast_at = float(core_db.get_config("MEMORY_FAST_PATH", "0.9") or 0.9)
    except ValueError:
        fast_at = 0.9
    with session() as s:
        rows = s.scalars(select(MemCase).where(MemCase.workspace == actor.workspace,
                                               MemCase.status != "deprecated")
                         .order_by(MemCase.updated_at.desc()).limit(2000)).all()
        scored = []
        for c in rows:
            sc = similarity(question, q_emb, c.question, _vec(c.embedding_json))
            if concept_ids and concept_ids & {x.get("id") for x in jload(c.concepts_json, [])}:
                sc = min(1.0, sc + 0.05)
            rank = sc * (0.6 + 0.4 * max(0.0, min(1.0, c.score or 0.5)))    # 质量分低的案例往后排
            if sc >= case_min:
                scored.append((rank, sc, c))
        scored.sort(key=lambda x: -x[0])
        cases = [_case_dict(c, sc) for _, sc, c in scored[:k]]
        fast = None
        # 快路径:已验证 + 高度相似 + 问的是同一批对象(「华南纸品」和「华北纸品」字面很像,但不能复用)
        if scored and scored[0][2].status == "verified" and scored[0][1] >= fast_at \
                and not (follow_up and is_follow_up(question)) \
                and (jload(scored[0][2].plan_json, {}) or {}).get("delegations") \
                and _anchors(jload(scored[0][2].concepts_json, [])) == anchors:
            fast = cases[0]
        for _, _, c in scored[:1]:
            c.hits = (c.hits or 0) + 1
            c.last_hit_at = now()
            if fast:
                c.fast_hits = (c.fast_hits or 0) + 1

        frows = s.scalars(select(MemFact).where(MemFact.workspace == actor.workspace,
                                                MemFact.status == "active")).all()
        fscored = []
        for f in frows:
            if not _visible_fact(f, actor):
                continue
            sc = similarity(question, q_emb, f.text, _vec(f.embedding_json))
            if any(n and n in f.text for n in concept_names):
                sc = max(sc, fact_min)               # 提到了问题里的概念,一定带上
            if f.kind == "preference" and f.scope == "user":
                sc = max(sc, fact_min)               # 个人偏好总是带上
            if sc >= fact_min:
                fscored.append((sc, f))
        fscored.sort(key=lambda x: -x[0])
        facts = [_fact_dict(f, sc) for sc, f in fscored[:6]]
        for _, f in fscored[:6]:
            f.hits = (f.hits or 0) + 1
        s.commit()
    return {"cases": cases, "facts": facts, "fast": fast}


def brief(mem: dict) -> dict:
    return {"cases": [{"id": c["id"], "question": c["question"], "score": c["score"], "status": c["status"],
                       "answer_summary": (c.get("answer_summary") or "")[:160]} for c in mem.get("cases") or []],
            "facts": [{"id": f["id"], "text": f["text"], "kind": f["kind"], "scope": f["scope"]}
                      for f in mem.get("facts") or []],
            "fast": (mem.get("fast") or {}).get("id", "")}


def facts_text(mem: dict) -> str:
    kinds = {"definition": "口径", "preference": "偏好", "fact": "事实"}
    return "\n".join(f"- [{kinds.get(f['kind'], f['kind'])}] {f['text']}" for f in mem.get("facts") or []) \
        or "(无)"


def sql_hints(ds_id: int | None = None, limit: int = 20) -> list[dict]:
    """「取数提示」:建模的人写给问数用的约定(哪张表才是准的、某个状态码是什么意思、默认排除什么)。
    只要生效就每次都带上 —— 它是写 SQL 的规矩,不是靠相似度碰运气的记忆。
    scope_ref 为空 = 对所有数据源生效;填了数据源 id = 只对那个数据源生效。"""
    if not enabled():
        return []
    refs = ["", str(ds_id)] if ds_id else [""]
    with session() as s:
        rows = s.scalars(select(MemFact).where(
            MemFact.workspace == _ws(), MemFact.status == "active", MemFact.kind == "sql_hint",
            MemFact.scope == "workspace", MemFact.scope_ref.in_(refs))
            .order_by(MemFact.created_at).limit(limit)).all()
        # 每带进一次就记一次命中:知识库里「用过 N 次」靠它
        for f in rows:
            f.hits = (f.hits or 0) + 1
        out = [{"id": f.id, "text": f.text, "ds_id": int(f.scope_ref) if f.scope_ref else 0} for f in rows]
        s.commit()
        return out


def drop_sql_hints_of(ds_id: int) -> int:
    """数据源删了,只对它生效的取数提示也一起删掉,别留着孤儿规则。"""
    with session() as s:
        rows = s.scalars(select(MemFact).where(
            MemFact.workspace == _ws(), MemFact.kind == "sql_hint", MemFact.scope_ref == str(ds_id))).all()
        for f in rows:
            s.delete(f)
        s.commit()
        return len(rows)


def preferences_text() -> str:
    """当前这个人的个人偏好(「金额用万元」「我只看华东区」)。快速通道不做向量召回,只带上这些。"""
    actor = identity.current()
    if not enabled():
        return "(无)"
    with session() as s:
        rows = s.scalars(select(MemFact).where(
            MemFact.workspace == actor.workspace, MemFact.status == "active", MemFact.kind == "preference",
            MemFact.scope == "user", MemFact.scope_ref == actor.id).limit(8)).all()
        return "\n".join(f"- {f.text}" for f in rows) or "(无)"


def cases_text(mem: dict) -> str:
    """给主 Agent 参考的历史案例:只给**人确认过**的。自动沉淀的还只是候选 —— 没人看过对不对,
    拿它去引导新的回答,错一次就会一直错下去。"""
    out = []
    for c in mem.get("cases") or []:
        if c.get("status") != "verified":
            continue
        p = c.get("plan") or {}
        path = ";".join(f"{d.get('agent')}:" + "、".join(str(x.get("tool") or x.get("call")) for x in d.get("calls") or [])
                        for d in p.get("delegations") or []) or ";".join(
            str(s.get("call")) for s in p.get("steps") or [])
        out.append(f"- 「{c['question']}」(相似度 {c['score']:.0%},已验证)"
                   f"\n  路径:{path or '无'}\n  结论:{(c.get('answer_summary') or '')[:160]}")
    return "\n".join(out) or "(无)"


# ---------------------------------------------------------------- 沉淀
def learn_async(turn_id: str) -> None:
    if not enabled():
        return
    ctx = contextvars.copy_context()
    threading.Thread(target=lambda: ctx.run(_learn_safe, turn_id), daemon=True).start()


def _learn_safe(turn_id: str) -> None:
    try:
        learn(turn_id)
    except Exception:  # noqa: BLE001
        log.exception("经验沉淀失败 %s", turn_id)


def _summary(answer: str) -> str:
    text = _MD.sub("", answer or "").strip()
    first = text.split("\n\n")[0] if text else ""
    return first[:300]


def learn(turn_id: str, extract: bool | None = None) -> dict:
    """从一轮提问沉淀:案例(同一问法合并)+ 习惯计数 + 组织记忆抽取。"""
    from ..agents import session as ask_session
    t = ask_session.get_turn(turn_id)
    if t["status"] != "done" or not t["answer"]:
        return {}
    plan = t.get("plan") or {}
    ok_steps = [s for s in t.get("steps") or [] if not s.get("error")]
    out: dict[str, Any] = {}
    case_id = plan.get("from_case") or ""
    # 追问(「那上个月呢」)离开上下文不成立:不存成独立案例,免得以后在别人的对话里被当成完整问题重放
    follow = int(t.get("seq") or 1) > 1 and is_follow_up(t["question"])
    if ok_steps and not case_id and not follow:
        case_id = upsert_case(t)
    if case_id:
        out["case_id"] = case_id
        record_pattern("question", case_id, t["question"], t["question"])
    do_extract = _on("MEMORY_EXTRACT") if extract is None else extract
    if do_extract:
        out["facts"] = extract_facts(t["question"], t["answer"], turn_id=turn_id)
    return out


def upsert_case(t: dict) -> str:
    actor = identity.current()
    plan = t.get("plan") or {}
    norm = normalize(t["question"])
    keep_plan = {"intent": plan.get("intent", ""), "delegations": plan.get("delegations") or [],
                 "steps": [{"call": s.get("call"), "args": s.get("args"), "agent": s.get("agent", "")}
                           for s in plan.get("steps") or []],
                 "follow_ups": plan.get("follow_ups") or []}
    sql = [{"run_id": d.get("run_id"), "sql": d.get("sql", ""), "metric": (d.get("metric") or {}).get("name")
            if isinstance(d.get("metric"), dict) else d.get("metric"), "route": d.get("route", "")}
           for d in t.get("data_refs") or []]
    links = t.get("links") or {}
    concepts = [{"id": c.get("id"), "name": c.get("name")} for c in links.get("concepts") or []] + \
        [{"id": _inst_id(i), "name": f"{i.get('type_name')}:{i.get('label')}", "instance": True}
         for i in links.get("instances") or []]
    if _time_id(links.get("time")):
        concepts.append({"id": _time_id(links["time"]), "name": f"时间:{links['time'].get('phrase') or ''}",
                         "instance": True})
    with session() as s:
        c = s.scalars(select(MemCase).where(MemCase.workspace == actor.workspace,
                                            MemCase.question_norm == norm[:500])).first()
        if c is None:
            c = MemCase(id=new_id("mc"), workspace=actor.workspace, question=t["question"],
                        question_norm=norm[:500], created_by=actor.id,
                        embedding_json=jdump(_embed(t["question"]) or []))
            s.add(c)
        elif c.status == "verified":
            # 已验证的路径不被新的一次自动运行覆盖,只刷新结论和识别出的对象
            c.answer_summary = _summary(t["answer"])
            c.concepts_json = jdump(concepts)
            c.source_turn = t["id"]
            s.commit()
            return c.id
        c.intent = plan.get("intent", "") or ""
        c.concepts_json = jdump(concepts)
        c.plan_json = jdump(keep_plan)
        c.sql_json = jdump(sql)
        c.answer_summary = _summary(t["answer"])
        c.source_turn = t["id"]
        if c.status == "deprecated":
            c.status = "draft"
            c.score = 0.4
        s.commit()
        return c.id


# ---------------------------------------------------------------- 组织记忆(mem0 式)
EXTRACT_PROMPT = """从用户这一轮提问中抽取值得长期记住的信息,只抽用户**自己说出来**的:
- definition:业务口径与定义(例如「缺货指可用库存低于安全库存」「准时率按到货日期算」)
- preference:个人偏好(例如「我只看华东区」「金额用万元显示」「默认按仓库拆开」)
- fact:稳定的业务事实(例如「华南纸品是主力纸品供应商」)
数据查询的结果(今天缺货多少件)会变,不要抽;系统回答里的内容不要抽;寒暄不要抽。
「如果……就……」这样的条件句、「帮我……」「请……」这样的指令,是这一次要办的事,不是长期事实,不要抽。没有就返回空列表。

用户问题:{question}
{extra}
只输出 JSON:{{"facts": [{{"text": "一句完整、可单独理解的话", "kind": "definition|preference|fact"}}]}}"""

RECONCILE_PROMPT = """你在维护一份组织记忆。下面是新抽取的记忆,以及和它们相似的已有记忆。
对每条新记忆决定操作:
- ADD:全新的信息
- UPDATE:和某条已有记忆说的是同一件事,但新信息更准确或已变化(给出要更新的 id 和合并后的文字)
- DELETE:新信息说明某条已有记忆已经不成立(给出 id)
- NONE:已有记忆已经包含,不用动

新记忆:
{new}

相似的已有记忆:
{old}

只输出 JSON:{{"ops": [{{"new": 新记忆序号, "op": "ADD|UPDATE|DELETE|NONE", "id": "已有记忆 id(UPDATE/DELETE 时)", "text": "最终文字(ADD/UPDATE 时)"}}]}}"""


def extract_facts(question: str, answer: str = "", *, turn_id: str = "", extra: str = "") -> list[dict]:
    try:
        r = llm.chat_json([{"role": "user", "content": EXTRACT_PROMPT.format(question=question, extra=extra)}],
                          temperature=0)
    except Exception as e:  # noqa: BLE001
        log.info("抽取记忆失败:%s", str(e)[:120])
        return []
    cands = [f for f in (r.get("facts") if isinstance(r, dict) else None) or []
             if isinstance(f, dict) and str(f.get("text") or "").strip()][:5]
    if not cands:
        return []
    return reconcile(cands, turn_id=turn_id)


def reconcile(cands: list[dict], *, turn_id: str = "", source: str = "ask", approved: bool = False) -> list[dict]:
    """mem0 式合并:新记忆和相似的已有记忆比对,由模型决定 ADD / UPDATE / DELETE / NONE。"""
    actor = identity.current()
    embs = [_embed(str(c["text"])) for c in cands]
    with session() as s:
        existing = s.scalars(select(MemFact).where(MemFact.workspace == actor.workspace,
                                                   MemFact.status != "deprecated")).all()
        similar: dict[str, MemFact] = {}
        for c, e in zip(cands, embs):
            for f in existing:
                if similarity(str(c["text"]), e, f.text, jload(f.embedding_json, None) or None) >= 0.5:
                    similar[f.id] = f
        old = {f.id: f.text for f in similar.values()}
    ops: list[dict]
    if not old:
        ops = [{"new": i, "op": "ADD", "text": c["text"]} for i, c in enumerate(cands)]
    else:
        try:
            r = llm.chat_json([{"role": "user", "content": RECONCILE_PROMPT.format(
                new="\n".join(f"{i}. [{c.get('kind', 'fact')}] {c['text']}" for i, c in enumerate(cands)),
                old="\n".join(f"- {k}: {v}" for k, v in old.items()))}], temperature=0)
            ops = [o for o in (r.get("ops") if isinstance(r, dict) else None) or [] if isinstance(o, dict)]
        except Exception:  # noqa: BLE001
            ops = [{"new": i, "op": "ADD", "text": c["text"]} for i, c in enumerate(cands)]
    applied: list[dict] = []
    for o in ops:
        try:
            idx = int(o.get("new", -1))
        except (TypeError, ValueError):
            continue
        if not 0 <= idx < len(cands):
            continue
        cand = cands[idx]
        kind = cand.get("kind") if cand.get("kind") in ("definition", "preference", "fact") else "fact"
        op = str(o.get("op") or "").upper()
        text = str(o.get("text") or cand["text"]).strip()[:1000]
        if op == "ADD":
            applied.append(add_fact(text, kind, source=source, turn_id=turn_id, emb=embs[idx], approved=approved))
        elif op == "UPDATE" and o.get("id") in old:
            applied.append(update_fact(str(o["id"]), text=text, _review=not approved and kind == "definition"))
        elif op == "DELETE" and o.get("id") in old:
            if approved:
                applied.append(update_fact(str(o["id"]), status="deprecated"))
            else:
                # 从一句提问里推断出「某条记忆不成立了」不能直接删:交给人确认
                from ..governance import review
                review.propose("memory_fact", f"建议作废组织记忆:{old[str(o['id'])][:60]}",
                               {"fact_id": str(o["id"]), "text": old[str(o["id"])], "op": "deprecate",
                                "because": text, "turn_id": turn_id}, source="memory", target_ref=str(o["id"]))
    return [a for a in applied if a]


FACT_KINDS = ("definition", "preference", "fact", "sql_hint")


def add_fact(text: str, kind: str = "fact", *, scope: str = "", scope_ref: str = "", source: str = "manual",
             turn_id: str = "", emb: list[float] | None = None, approved: bool = False) -> dict:
    """个人偏好直接生效;业务口径(组织范围)要审核,除非是审核通过后回流的。"""
    actor = identity.current()
    if kind not in FACT_KINDS:
        kind = "fact"
    if kind == "sql_hint":
        if not actor.can("build"):
            raise HTTPException(403, "取数提示会影响所有人的问数结果,只有建模的人可以写")
        scope = "workspace"           # scope_ref = 适用的数据源 id,空 = 全部数据源
    if not scope:
        scope = "user" if kind == "preference" else "workspace"
    if scope == "user" and not scope_ref:
        scope_ref = actor.id
    # 全组织可见的记忆(口径、事实)从提问里自动抽出来的,一律先待确认:它会左右所有人以后的回答
    needs_review = scope == "workspace" and not approved and source != "manual"
    f = MemFact(id=new_id("mf"), workspace=actor.workspace, scope=scope, scope_ref=scope_ref, kind=kind,
                text=text, embedding_json=jdump(emb if emb is not None else (_embed(text) or [])),
                status="pending" if needs_review else "active", source=source, source_turn=turn_id,
                created_by=actor.id)
    with session() as s:
        s.add(f)
        s.commit()
        out = _fact_dict(f)
    if needs_review:
        from ..governance import review
        review.propose("memory_fact", f"组织记忆待确认:{text[:80]}", {"fact_id": out["id"], "text": text,
                                                                  "turn_id": turn_id},
                       source="memory", target_ref=out["id"])
    audit.record("memory.fact", "memory", out["id"], f"记忆{'待审核' if needs_review else '生效'}:{text[:120]}")
    return out


def update_fact(fact_id: str, *, text: str | None = None, status: str | None = None, kind: str | None = None,
                scope: str | None = None, scope_ref: str | None = None, _review: bool = False) -> dict:
    actor = identity.current()
    with session() as s:
        f = s.get(MemFact, fact_id)
        if f is None or f.workspace != actor.workspace:
            raise HTTPException(404, "记忆不存在")
        if text is not None and text.strip() and text.strip() != f.text:
            f.text = text.strip()[:1000]
            f.embedding_json = jdump(_embed(f.text) or [])
            if _review:
                f.status = "pending"
        if status in ("active", "pending", "deprecated"):
            f.status = status
        if kind in FACT_KINDS:
            f.kind = kind
        if scope in ("workspace", "user", "role"):
            f.scope = scope
        if scope_ref is not None and f.kind == "sql_hint":
            f.scope_ref = scope_ref
        s.commit()
        out = _fact_dict(f)
    if _review and out["status"] == "pending":
        from ..governance import review
        review.propose("memory_fact", f"组织口径(更新):{out['text'][:80]}", {"fact_id": fact_id, "text": out["text"]},
                       source="memory", target_ref=fact_id)
    return out


def _accept_fact(payload: dict, item: dict) -> dict:
    fid = str(payload.get("fact_id") or "")
    if payload.get("op") == "deprecate":
        return update_fact(fid, status="deprecated")
    text = payload.get("text")
    return update_fact(fid, text=text if isinstance(text, str) else None, status="active")


# ---------------------------------------------------------------- 反馈
def _case_of_turn(s, turn: dict) -> MemCase | None:
    actor = identity.current()
    c = s.scalars(select(MemCase).where(MemCase.workspace == actor.workspace,
                                        MemCase.source_turn == turn["id"])).first()
    if c is None and (turn.get("plan") or {}).get("from_case"):
        c = s.get(MemCase, turn["plan"]["from_case"])
    if c is None:
        c = s.scalars(select(MemCase).where(MemCase.workspace == actor.workspace,
                                            MemCase.question_norm == normalize(turn["question"])[:500])).first()
    return c


_PROMOTED_NOTE = "由提问点赞晋升"


def on_feedback(turn_id: str, rating: int, comment: str = "", correction: str = "") -> dict:
    """👍:案例升为已验证、对应问数 SQL 升为 verified;👎:案例降权、点赞晋升的 SQL 退回草稿。"""
    from ..agents import session as ask_session
    from ..text2sql import library
    from ..text2sql.models import SqlPair
    t = ask_session.get_turn(turn_id)
    out: dict[str, Any] = {}
    if t["status"] == "done" and rating > 0 and not (t.get("plan") or {}).get("from_case"):
        # 反馈可能早于后台沉淀完成:先确保案例存在
        if [s for s in t.get("steps") or [] if not s.get("error")]:
            upsert_case(t)
    actor = identity.current()
    counted = True
    with session() as s:
        c = _case_of_turn(s, t)
        if c is not None:
            voters = jload(c.voters_json, {}) or {}
            vote = 1 if rating > 0 else -1 if rating < 0 else 0
            counted = voters.get(actor.id) != vote          # 同一个人重复点同样的不再计分(以前可以反复点赞刷分)
            if counted and vote:
                voters[actor.id] = vote
                c.voters_json = jdump(voters)
            if rating > 0 and counted:
                c.up_votes = (c.up_votes or 0) + 1
                c.score = min(1.0, (c.score or 0.5) + 0.2)
                c.status = "verified"
            elif rating < 0 and counted:
                # 点踩 = 有人说这个回答不对:这条经验立刻作废,不再被参考,纠错进审核队列等人处理
                c.down_votes = (c.down_votes or 0) + 1
                c.score = max(0.0, (c.score or 0.5) - 0.3)
                c.status = "deprecated"
            s.commit()
            out["case"] = {"id": c.id, "status": c.status}
        # 只动「答案里真的引用了」的取数:一轮里试过的别的 SQL 不该跟着被当成好例子
        refs = [d for d in t.get("data_refs") or [] if d.get("run_id")]
        cited = [int(d["run_id"]) for d in refs if d.get("cited")] or ([int(refs[0]["run_id"])] if len(refs) == 1 else [])
        promoted = 0
        if cited and counted:
            for p in s.scalars(select(SqlPair).where(SqlPair.origin_run_id.in_(cited))).all():
                if rating > 0 and p.status != "verified":
                    library.set_status(p.id, "verified")
                    library.update_pair(p.id, note=_PROMOTED_NOTE, question=t["question"])
                    promoted += 1
                elif rating < 0 and p.status == "verified" and (p.note or "") == _PROMOTED_NOTE:
                    library.set_status(p.id, "draft")
                    promoted -= 1
        out["sql"] = promoted
    if rating > 0:
        audit.record("memory.promote", "memory", (out.get("case") or {}).get("id", turn_id),
                     f"点赞沉淀:案例已验证,晋升 {max(promoted, 0)} 条问数 SQL")
    return out


CORRECTION_PROMPT = """用户纠正了系统的一个回答。把纠错内容整理成可以回流到系统里的知识:
- facts:以后回答要遵循的口径 / 事实(一句完整的话)
- synonyms:用户对某个概念的另一种叫法(concept 必须是下面列出的概念名之一)

问题:{question}
系统回答(节选):{answer}
用户说哪里不对:{comment}
正确答案要点:{correction}
本体里的概念:{concepts}

只输出 JSON:{{"facts": [{{"text": "...", "kind": "definition|fact"}}], "synonyms": [{{"concept": "...", "alias": "..."}}]}}"""


def apply_correction(payload: dict) -> dict:
    """纠错被采纳:回流成组织记忆(已审核,直接生效)、元素同义词(进草稿,发布后生效),相关案例作废。"""
    from ..kernel import service as ksvc
    names = [c["name"] for c in ksvc.list_concepts(limit=300)]
    out: dict[str, Any] = {"facts": [], "synonyms": []}
    try:
        r = llm.chat_json([{"role": "user", "content": CORRECTION_PROMPT.format(
            question=payload.get("question", ""), answer=str(payload.get("answer", ""))[:1500],
            comment=payload.get("comment", ""), correction=payload.get("correction", ""),
            concepts="、".join(names[:300]) or "(无)")}], temperature=0)
    except Exception as e:  # noqa: BLE001
        log.info("整理纠错失败:%s", str(e)[:120])
        r = {}
    r = r if isinstance(r, dict) else {}
    facts = [f for f in r.get("facts") or [] if isinstance(f, dict) and f.get("text")]
    if not facts and (payload.get("correction") or "").strip():
        facts = [{"text": f"关于「{payload.get('question', '')[:60]}」:{payload['correction']}", "kind": "fact"}]
    if facts:
        out["facts"] = reconcile(facts, turn_id=str(payload.get("turn_id") or ""), source="feedback", approved=True)
    for sy in r.get("synonyms") or []:
        if not isinstance(sy, dict):
            continue
        c = ksvc.find(str(sy.get("concept") or ""))
        alias = str(sy.get("alias") or "").strip()
        if c and alias and alias not in (c.get("synonyms") or []) and alias != c["name"]:
            ksvc.update_concept(c["id"], synonyms=list(c.get("synonyms") or []) + [alias])
            out["synonyms"].append({"concept": c["name"], "alias": alias})
    if payload.get("turn_id"):
        from ..agents import session as ask_session
        try:
            t = ask_session.get_turn(str(payload["turn_id"]))
            with session() as s:
                cs = _case_of_turn(s, t)
                if cs is not None and cs.status != "verified":
                    cs.status = "deprecated"
                    s.commit()
                    out["case_deprecated"] = cs.id
        except HTTPException:
            pass
    return out


# ---------------------------------------------------------------- 操作习惯
def record_pattern(kind: str, ref: str, title: str, sample: str = "") -> dict | None:
    """计一次习惯。达到次数且还在观察中,就标为「建议固化」。"""
    if not enabled() or not ref:
        return None
    actor = identity.current()
    if actor.kind != "user":
        return None
    try:
        at = int(core_db.get_config("PATTERN_SUGGEST_AT", "3") or 3)
    except ValueError:
        at = 3
    with session() as s:
        p = s.scalars(select(MemPattern).where(MemPattern.workspace == actor.workspace,
                                               MemPattern.owner == actor.id, MemPattern.kind == kind,
                                               MemPattern.ref == ref[:255])).first()
        if p is None:
            p = MemPattern(id=new_id("mp"), workspace=actor.workspace, owner=actor.id, kind=kind,
                           ref=ref[:255], title=title[:255])
            s.add(p)
        p.count = (p.count or 0) + 1
        p.last_at = now()
        samples = [x for x in jload(p.samples_json, []) if x != sample]
        if sample:
            samples = ([sample] + samples)[:5]
        p.samples_json = jdump(samples)
        if p.status == "watching" and p.count >= at:
            p.status = "suggested"
        s.commit()
        return _pattern_dict(p)


def _pattern_dict(p: MemPattern) -> dict:
    return {"id": p.id, "owner": p.owner, "kind": p.kind, "ref": p.ref, "title": p.title,
            "samples": jload(p.samples_json, []), "count": p.count, "status": p.status,
            "adopted_ref": p.adopted_ref, "last_at": iso(p.last_at), "created_at": iso(p.created_at)}


_SUGGEST_TEXT = {
    "question": "你已经问过 {n} 次类似的问题,要把它加入工作台的常用问题吗?",
    "action": "你已经发起过 {n} 次「{title}」,要做成一张流程卡,让系统定时巡检并自动起草吗?",
    "sop": "你已经手动运行过 {n} 次「{title}」,要给它设成定时运行吗?",
}


def suggestions() -> list[dict]:
    """给当前用户的「建议固化」。"""
    if not enabled():
        return []
    actor = identity.current()
    with session() as s:
        rows = s.scalars(select(MemPattern).where(MemPattern.workspace == actor.workspace,
                                                  MemPattern.owner == actor.id,
                                                  MemPattern.status == "suggested")
                         .order_by(MemPattern.count.desc()).limit(5)).all()
        return [{**_pattern_dict(p), "text": _SUGGEST_TEXT.get(p.kind, "").format(n=p.count, title=p.title)}
                for p in rows]


def pinned_questions() -> list[str]:
    actor = identity.current()
    with session() as s:
        rows = s.scalars(select(MemPattern).where(MemPattern.workspace == actor.workspace,
                                                  MemPattern.owner == actor.id, MemPattern.kind == "question",
                                                  MemPattern.status == "adopted")
                         .order_by(MemPattern.count.desc()).limit(6)).all()
        return [p.title for p in rows]


def pin_question(question: str) -> dict:
    """用户主动把一个问题存为常用问题:直接记成已采纳的习惯,工作台置顶显示。"""
    q = (question or "").strip()
    if not q:
        raise HTTPException(422, "问题不能为空")
    p = record_pattern("question", f"pin:{normalize(q)[:200]}", q[:255], q)
    if p is None:
        raise HTTPException(409, "经验中枢已关闭")
    return decide_pattern(p["id"], True)


def decide_pattern(pattern_id: str, adopt: bool, adopted_ref: str = "") -> dict:
    actor = identity.current()
    with session() as s:
        p = s.get(MemPattern, pattern_id)
        if p is None or p.workspace != actor.workspace or p.owner != actor.id:
            raise HTTPException(404, "建议不存在")
        p.status = "adopted" if adopt else "dismissed"
        p.adopted_ref = adopted_ref[:128]
        s.commit()
        return _pattern_dict(p)


# ---------------------------------------------------------------- 管理
def list_cases(status: str = "", q: str = "", limit: int = 200) -> list[dict]:
    with session() as s:
        stmt = select(MemCase).where(MemCase.workspace == _ws())
        if status:
            stmt = stmt.where(MemCase.status == status)
        if q.strip():
            stmt = stmt.where(MemCase.question.like(f"%{q.strip()}%"))
        rows = s.scalars(stmt.order_by(MemCase.updated_at.desc()).limit(limit)).all()
        return [_case_dict(c) for c in rows]


def update_case(case_id: str, **fields: Any) -> dict:
    with session() as s:
        c = s.get(MemCase, case_id)
        if c is None or c.workspace != _ws():
            raise HTTPException(404, "案例不存在")
        if fields.get("status") in ("draft", "verified", "deprecated"):
            c.status = fields["status"]
            if c.status == "verified":
                c.score = max(c.score or 0.5, 0.8)
        if isinstance(fields.get("answer_summary"), str):
            c.answer_summary = fields["answer_summary"][:2000]
        if isinstance(fields.get("question"), str) and fields["question"].strip():
            c.question = fields["question"].strip()
            c.question_norm = normalize(c.question)
            c.embedding_json = jdump(_embed(c.question) or [])
        s.commit()
        out = _case_dict(c)
    audit.record("memory.case", "memory", case_id, f"修改案例:{out['question'][:80]}({out['status']})")
    return out


def delete_case(case_id: str) -> None:
    with session() as s:
        c = s.get(MemCase, case_id)
        if c is None or c.workspace != _ws():
            raise HTTPException(404, "案例不存在")
        s.delete(c)
        s.commit()


def list_facts(status: str = "", kind: str = "") -> list[dict]:
    actor = identity.current()
    with session() as s:
        stmt = select(MemFact).where(MemFact.workspace == actor.workspace)
        if status:
            stmt = stmt.where(MemFact.status == status)
        if kind:
            stmt = stmt.where(MemFact.kind == kind)
        rows = s.scalars(stmt.order_by(MemFact.updated_at.desc()).limit(500)).all()
        return [_fact_dict(f) for f in rows if f.scope != "user" or f.scope_ref == actor.id or actor.can("build")]


def delete_fact(fact_id: str) -> None:
    with session() as s:
        f = s.get(MemFact, fact_id)
        if f is None or f.workspace != _ws():
            raise HTTPException(404, "记忆不存在")
        s.delete(f)
        s.commit()


def list_patterns(status: str = "") -> list[dict]:
    with session() as s:
        stmt = select(MemPattern).where(MemPattern.workspace == _ws())
        if status:
            stmt = stmt.where(MemPattern.status == status)
        rows = s.scalars(stmt.order_by(MemPattern.count.desc()).limit(300)).all()
        return [_pattern_dict(p) for p in rows]


def stats() -> dict:
    ws = _ws()
    week = now() - dt.timedelta(days=7)
    with session() as s:
        by_status = dict(s.execute(select(MemCase.status, func.count(MemCase.id))
                                   .where(MemCase.workspace == ws).group_by(MemCase.status)).all())
        hits = s.scalar(select(func.coalesce(func.sum(MemCase.hits), 0)).where(MemCase.workspace == ws)) or 0
        fast = s.scalar(select(func.coalesce(func.sum(MemCase.fast_hits), 0)).where(MemCase.workspace == ws)) or 0
        recent = s.scalar(select(func.count(MemCase.id)).where(MemCase.workspace == ws,
                                                               MemCase.last_hit_at >= week)) or 0
        facts = dict(s.execute(select(MemFact.status, func.count(MemFact.id))
                               .where(MemFact.workspace == ws).group_by(MemFact.status)).all())
        pats = dict(s.execute(select(MemPattern.status, func.count(MemPattern.id))
                              .where(MemPattern.workspace == ws).group_by(MemPattern.status)).all())
    from ..governance import review
    pending_fb = review.list_items(status="pending", kind="feedback", limit=1)["total"]
    return {"cases": {k: int(v) for k, v in by_status.items()}, "case_hits": int(hits), "fast_hits": int(fast),
            "cases_used_this_week": int(recent), "facts": {k: int(v) for k, v in facts.items()},
            "patterns": {k: int(v) for k, v in pats.items()}, "pending_feedback": pending_fb}


def recall_tool(args: dict, emit=None) -> dict:
    """MCP 工具 recall_memory:外部 Agent 也能查组织经验。"""
    q = str(args.get("question") or "")
    mem = recall(q, None, k=int(args.get("k") or 3))
    b = brief(mem)
    b["summary"] = f"相似案例 {len(b['cases'])} 个、相关记忆 {len(b['facts'])} 条"
    return b


def register() -> None:
    from ..governance import review
    review.register_handler("memory_fact", _accept_fact)


register()