# lightmem - Doramagic AI Context Pack

> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。

## 充分原则

- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。
- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。

## 给宿主 AI 的使用方式

你正在读取 Doramagic 为 lightmem 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。

## Claim 消费规则

- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。
- **事实最低状态**：`supported`
- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。
- `weak`：只能作为低置信度线索，必须要求用户继续核实。
- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。
- `unverified`：不得作为事实使用，应明确说证据不足。
- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。

## 它最适合谁

- **AI 研究者或研究型 Agent 构建者**：README 明确围绕研究、实验或论文工作流展开。 证据：`README.md` Claim：`clm_0002` supported 0.86

## 它能做什么

- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0001` supported 0.86

## 怎么开始

- `git clone https://github.com/zjunlp/LightMem.git` 证据：`README.md` Claim：`clm_0003` supported 0.86
- `pip install -e .` 证据：`README.md` Claim：`clm_0004` supported 0.86
- `pip install lightmem  # Coming soon` 证据：`README.md` Claim：`clm_0005` supported 0.86
- `pip install '.[mcp]'` 证据：`README.md` Claim：`clm_0006` supported 0.86
- `npx @modelcontextprotocol/inspector python mcp/server.py` 证据：`README.md` Claim：`clm_0007` supported 0.86

## 继续前判断卡

- **当前建议**：需要管理员/安全审批
- **为什么**：继续前可能涉及密钥、账号、外部服务或敏感上下文，建议先经过管理员或安全审批。

### 30 秒判断

- **现在怎么做**：需要管理员/安全审批
- **最小安全下一步**：先跑 Prompt Preview；若涉及凭证或企业环境，先审批再试装
- **先别相信**：真实输出质量不能在安装前相信。
- **继续会触碰**：命令执行、本地环境或项目文件、环境变量 / API Key

### 现在可以相信

- **适合人群线索：AI 研究者或研究型 Agent 构建者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86
- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86
- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0003` supported 0.86

### 现在还不能相信

- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。
- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。
- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。
- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。
- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。
- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。
- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`

### 继续会触碰什么

- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`
- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`
- **环境变量 / API Key**：项目入口文档明确出现 API key、token、secret 或账号凭证配置。 原因：如果真实安装需要凭证，应先使用测试凭证并经过权限/合规判断。 证据：`README.md`, `experiments/longmemeval/run_lightmem_qwen.py`
- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。

### 最小安全下一步

- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）
- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）
- **不要使用真实生产凭证**：环境变量/API key 一旦进入宿主或工具链，可能产生账号和合规风险。（适用：出现 API、TOKEN、KEY、SECRET 等环境线索时。）
- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）

### 退出方式

- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。
- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。
- **准备撤销测试 API key 或 token**：测试凭证泄露或误用时，可以快速止损。
- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。

## 哪些只能预览

- 解释项目适合谁和能做什么
- 基于项目文档演示典型对话流程
- 帮助用户判断是否值得安装或继续研究

## 哪些必须安装后验证

- 真实安装 Skill、插件或 CLI
- 执行脚本、修改本地文件或访问外部服务
- 验证真实输出质量、性能和兼容性

## 边界与风险判断卡

- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0008` inferred 0.45
- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0009` supported 0.86
- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。
- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。
- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。

## 开工前工作上下文

### 加载顺序

- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。
- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。
- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。
- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。
- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。

### 任务路由

- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86

### 上下文规模

- 文件总数：560
- 重要文件覆盖：40/560
- 证据索引条目：51
- 角色 / Skill 条目：9

### 证据不足时的处理

- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。
- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。
- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。
- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。

## Prompt Recipes

### 适配判断

- 目标：判断这个项目是否适合用户当前任务。
- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。

```text
请基于 lightmem 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。
```

### 安装前体验

- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。
- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。

```text
请把 lightmem 当作安装前体验资产，而不是已安装工具或真实运行环境。

请严格输出四段：
1. 先问我 3 个必要问题。
2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。
3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。
4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。

硬性边界：
- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。
- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。
- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。
- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。
- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。
- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。

```

### 角色 / Skill 选择

- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。
- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。

```text
请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。
```

### 风险预检

- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。
- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。

```text
请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。
```

### 宿主 AI 开工指令

- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。
- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。

```text
请基于 lightmem 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。
```

## 角色 / Skill 索引

- 共索引 9 个角色 / Skill / 项目文档条目。

- **📢 News**（project_doc）：LightMem: Lightweight and Efficient Memory-Augmented Generation 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`
- **EM²Mem Evaluation Scripts**（project_doc）：Evaluation scripts for building and evaluating event-centric multimodal memory on the EgoLifeQA benchmark. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`experiments/egolife/readme.md`
- **LightMem Evaluation Scripts**（project_doc）：Evaluation scripts for building and searching memory collections on the LoCoMo dataset. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`experiments/locomo/readme.md`
- **LongMemEval Evaluation Scripts**（project_doc）：This directory contains reproduction scripts for the LongMemEval benchmark, as discussed in our paper: LightMem: Lightweight and Efficient Memory-Augmented Generation https://arxiv.org/abs/2510.18866 . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`experiments/longmemeval/readme.md`
- **VLM2Vec-V2: Unified Multimodal Embedding for Videos, Images, and Documents**（project_doc）：VLM2Vec-V2: Unified Multimodal Embedding for Videos, Images, and Documents 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`src/em2mem/embedding/VLM2Vec/README.md`
- **Memory Baseline Framework**（project_doc）：A comprehensive evaluation framework for benchmarking various memory layers on long-term conversational memory tasks. This framework provides a unified pipeline for memory construction , memory retrieval , and question answering evaluation . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`src/lightmem/memory_toolkits/readme.md`
- **Key Contributions**（project_doc）：EM²Mem: Event-Centric Multimodal Memory for Large Language Models --- 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`EM2Mem.md`
- **Key Contributions**（project_doc）：FluxMem: Rethinking Memory as Continuously Evolving Connectivity 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`FluxMem.md`
- **Key Contributions**（project_doc）：StructMem: Structured Memory for Long-Horizon Behavior in LLMs 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`StructMem.md`

## 证据索引

- 共索引 51 条证据。

- **📢 News**（documentation）：LightMem: Lightweight and Efficient Memory-Augmented Generation 证据：`README.md`
- **EM²Mem Evaluation Scripts**（documentation）：Evaluation scripts for building and evaluating event-centric multimodal memory on the EgoLifeQA benchmark. 证据：`experiments/egolife/readme.md`
- **LightMem Evaluation Scripts**（documentation）：Evaluation scripts for building and searching memory collections on the LoCoMo dataset. 证据：`experiments/locomo/readme.md`
- **LongMemEval Evaluation Scripts**（documentation）：This directory contains reproduction scripts for the LongMemEval benchmark, as discussed in our paper: LightMem: Lightweight and Efficient Memory-Augmented Generation https://arxiv.org/abs/2510.18866 . 证据：`experiments/longmemeval/readme.md`
- **VLM2Vec-V2: Unified Multimodal Embedding for Videos, Images, and Documents**（documentation）：VLM2Vec-V2: Unified Multimodal Embedding for Videos, Images, and Documents 证据：`src/em2mem/embedding/VLM2Vec/README.md`
- **Memory Baseline Framework**（documentation）：A comprehensive evaluation framework for benchmarking various memory layers on long-term conversational memory tasks. This framework provides a unified pipeline for memory construction , memory retrieval , and question answering evaluation . 证据：`src/lightmem/memory_toolkits/readme.md`
- **License**（source_file）：Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files the "Software" , to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 证据：`LICENSE`
- **License**（source_file）：Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 证据：`src/em2mem/embedding/VLM2Vec/LICENSE`
- **Key Contributions**（documentation）：EM²Mem: Event-Centric Multimodal Memory for Large Language Models --- 证据：`EM2Mem.md`
- **Key Contributions**（documentation）：FluxMem: Rethinking Memory as Continuously Evolving Connectivity 证据：`FluxMem.md`
- **Key Contributions**（documentation）：StructMem: Structured Memory for Long-Horizon Behavior in LLMs 证据：`StructMem.md`
- **-----------------------------**（source_file）：lightmem instance: Optional LightMemory = None ⋮---- CONFIG PATH = os.path.join os.path.dirname os.path.abspath file , 'example.json' ⋮---- def get lightmem instance - LightMemory ⋮---- config = json.load f lightmem instance = LightMemory.from config config ⋮---- ----------------------------- MCP Initialization ⋮---- STATUS SUCCESS = "success" STATUS ERROR = "error" ⋮---- mcp = FastMCP "LightMem" ⋮---- @mcp.tool def get timestamp - Dict str, Any ⋮---- timestamp = datetime.now .isoformat timespec="milliseconds" ⋮---- @mcp.tool def add memory user input: str, assistant reply: str, timestamp: Optional str = None, force segment: bool = False, force extract: bool = False - Dict str, Any ⋮---- li… 证据：`mcp/server.py`
- **Complete dependencies with exact versions for reproducibility**（source_file）：build-system requires = "setuptools =61.0", "wheel" build-backend = "setuptools.build meta" 证据：`pyproject.toml`
- **Build Episodic Graph**（source_file）：logger = logging.getLogger name ⋮---- OPENAI MODEL = os.getenv "OPENAI MODEL", "gpt-5-mini" OPENIE MAX WORKERS = int os.getenv "OPENIE MAX WORKERS", os.getenv "MAX WORKERS", "4" OPENIE LOG EVERY = int os.getenv "OPENIE LOG EVERY", "50" ⋮---- DIRECT 30SEC TRIPLET SYSTEM PROMPT = """ Role and Objective ⋮---- HIGH LEVEL TRIPLET SYSTEM PROMPT = """ Role and Objective ⋮---- class DirectTripletRawOutput BaseModel ⋮---- triplets: List List str = Field default factory=list ⋮---- class HighLevelTripletRawOutput BaseModel ⋮---- entities: List str = Field default factory=list ⋮---- PRONOUNS TO SKIP = { FIRST PERSON = {"i", "me", "my", "myself"} GROUP ALIASES = { RELATION STOPLIST = {"be", "is", "are",… 证据：`experiments/egolife/preprocess/multimodal_memory_cell/build_episodic_graph.py`
- **Metadata for original 30sec root units**（source_file）：logger = logging.getLogger name ⋮---- def load json path: str - Dict str, Any ⋮---- def ordered unique values: List str - List str ⋮---- out: List str = seen = set ⋮---- def scale rank scale: str - int ⋮---- def sort items items: List Dict str, Any - List Dict str, Any ⋮---- def triple fingerprint triple: List str - str ⋮---- raw = " ".join str x .strip .lower for x in triple ⋮---- def fact id triple: List str - str ⋮---- def consolidate items: List Dict str, Any , consolidator - Dict str, Any ⋮---- items = sort items items ⋮---- Metadata for original 30sec root units root metadata map: Dict str, Dict str, Any = {} ⋮---- doc id = str unit meta.get "doc id", "" .strip ⋮---- accumulated seman… 证据：`experiments/egolife/preprocess/semantic_graph/consolidate_semantic_graph.py`
- **Pyproject**（source_file）：project name = "lightmem-egolife" version = "0.1.0" description = "EgoLife experiment environment for EM2Mem inside LightMem" requires-python = " =3.10, =4.57.0", "sentence-transformers =5.1.1", "accelerate =1.10.0", "openai =2.3.0", "tenacity =8.2.0", "numpy =1.26.4", "pillow =10.0.0", "tqdm =4.67.0", "pydantic =2.0.0", "pydantic-core =2.0.0", "scikit-learn =1.4.0", "opencv-python =4.8.0", "decord =0.6.0", "pandas =2.0.0", "pysrt =1.1.2", "python-dotenv =1.0.0", "igraph =0.11.0", "huggingface-hub =0.35.0", "filelock =3.13.0", 证据：`experiments/egolife/pyproject.toml`
- **Process each session turn by turn**（source_file）：LOGS ROOT = "./logs" RUN TIMESTAMP = datetime.datetime.now .strftime "%Y%m%d %H%M%S" RUN LOG DIR = os.path.join LOGS ROOT, RUN TIMESTAMP ⋮---- API KEYS = API BASE URL = '' LLM MODEL = 'gpt-4o-mini' ⋮---- LLMLINGUA MODEL PATH = '/path/to/llmlingua-model' EMBEDDING MODEL PATH = '/path/to/embedding-model' ⋮---- DATA PATH = '/path/to/locomo10.json' DATASET TYPE = 'locomo' ⋮---- QDRANT PRE UPDATE DIR = './qdrant pre update' QDRANT POST UPDATE DIR = './qdrant post update' ⋮---- MAX WORKERS = 5 USE PROCESS POOL = True ⋮---- def parse args ⋮---- parser = argparse.ArgumentParser description="Parallel Memory Building with LightMem" ⋮---- def get process logger sample id ⋮---- logger = logging.getLogg… 证据：`experiments/locomo/add_locomo.py`
- **Save final results**（source_file）：def extract json text ⋮---- text = text.strip match = re.search r" ", text, re.DOTALL ⋮---- json str = match.group 1 ⋮---- json str = text assume it's raw JSON ⋮---- ACCURACY PROMPT = """ parser = argparse.ArgumentParser description="Evaluate RAG results using LLM judge" ⋮---- args = parser.parse args ⋮---- dataset path = args.input file output path = f"results/llm judge {dataset path.split '/' -1 }" ⋮---- data = json.load f ⋮---- LLM JUDGE = defaultdict list RESULTS = defaultdict list ⋮---- index = 0 ⋮---- question = x "question" gold answer = x "answer" generated answer = x "response" category = x "category" ⋮---- label = evaluate llm judge question, gold answer, generated answer ⋮---- Sa… 证据：`experiments/locomo/llm_judge.py`
- **Prompts**（source_file）：METADATA GENERATE PROMPT locomo = """ ⋮---- ANSWER PROMPT GRAPH = """ ⋮---- ANSWER PROMPT = """ ⋮---- ANSWER PROMPT ZEP = """ ⋮---- ANSWER PROMPT StructMem = """ ⋮---- LoCoMo Event Binding factual = """ ⋮---- LoCoMo Event Binding relational = """ ⋮---- LoCoMo Cross Event Consolidation = """ ⋮---- UPDATE PROMPT = """ ⋮---- EXTRACTION PROMPTS = { 证据：`experiments/locomo/prompts.py`
- **Retrievers**（source_file）：SPACY AVAILABLE = True logger = logging.getLogger name ⋮---- class QdrantEntryLoader ⋮---- def init self, qdrant path: str, summary suffix: str = " summaries" ⋮---- def get qdrant self, collection name: str ⋮---- cfg = QdrantConfig collection name=collection name, path=self.qdrant path, embedding model dims=384, on disk=True ⋮---- def load from collection self, collection name: str, with vectors: bool = False - List Dict str, Any ⋮---- q = self. get qdrant collection name ⋮---- points = ⋮---- points = q.get all with vectors=with vectors, with payload=True ⋮---- points = self. fallback sqlite read collection name, with vectors=with vectors ⋮---- def load entries self, collection name: str, w… 证据：`experiments/locomo/retrievers.py`
- **Retrieve from each speaker separately**（source_file）：LOGS ROOT = "./logs" RUN TIMESTAMP = datetime.datetime.now .strftime "%Y%m%d %H%M%S" RUN LOG DIR = os.path.join LOGS ROOT, f"lightmem locomo {RUN TIMESTAMP}" ⋮---- logger = logging.getLogger "vector baseline" ⋮---- DEFAULT DATA PATH = '/path/to/locomo dataset.json' DEFAULT QDRANT DIR = './qdrant pre update' DEFAULT EMBEDDING MODEL PATH = '/path/to/embedding-model' DEFAULT RESULTS DIR = './lightmem locomo results' DEFAULT RETRIEVAL LIMIT = 60 ⋮---- def parse locomo dataset data path: str - List Dict ⋮---- data = json.load f ⋮---- samples = ⋮---- sample = { ⋮---- answer = qa item.get 'answer' or qa item.get 'adversarial answer', '' ⋮---- speaker groups = {} ⋮---- payload = entry.get 'payload'… 证据：`experiments/locomo/search_locomo.py`
- **Offline Update**（source_file）：def load lightmem collection name ⋮---- config = { lightmem = LightMemory.from config config ⋮---- base dir = "" ⋮---- collection path = os.path.join base dir, collection name ⋮---- lightmem = load lightmem collection name 证据：`experiments/longmemeval/offline_update.py`
- **Run Lightmem Qwen**（source_file）：JUDGE MODEL API KEY='sk-xxxxxxxxxxxxxxxxxxxxxxxxxx' JUDGE MODEL BASE URL='https://api.deepseek.com/v1' JUDGE MODEL='deepseek-chat' API KEY='sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' API BASE URL='https://dashscope.aliyuncs.com/compatible-mode/v1' LLM MODEL='qwen-plus' ⋮---- LLMLINGUA MODEL PATH='/your/path/to/models/llmlingua-2-bert-base-multilingual-cased-meetingbank' EMBEDDING MODEL PATH='/your/path/to/models/all-MiniLM-L6-v2' ⋮---- DATA PATH='/your/path/to/dataset/longmemeval/longmemeval s.json' RESULTS DIR='../results' QDRANT DATA DIR='./qdrant data' ⋮---- def get anscheck prompt task, question, answer, response, abstention=False ⋮---- template = "I will give you a question, a correct answ… 证据：`experiments/longmemeval/run_lightmem_qwen.py`
- **append eos token id to every input ids, some texts in FiQA are empty**（source_file）：def setup logger ⋮---- log format = logging.Formatter " % asctime s % levelname s % message s" logger = logging.getLogger ⋮---- console handler = logging.StreamHandler ⋮---- logger = setup logger ⋮---- def str2bool v ⋮---- def move to cuda sample ⋮---- def move to cuda maybe tensor ⋮---- last hidden = last hidden states.masked fill ~attention mask ..., None .bool , 0.0 ⋮---- emb = last hidden.sum dim=1 / attention mask.sum dim=1 ..., None ⋮---- s = torch.sum last hidden attention mask.unsqueeze -1 .float , dim=1 d = attention mask.sum dim=1, keepdim=True .float emb = s / d ⋮---- emb = last hidden :, 0 ⋮---- left padding = attention mask :, -1 .sum == attention mask.shape 0 ⋮---- emb = last… 证据：`src/em2mem/embedding/VLM2Vec/adhoc/eval_mteb/mteb_utils.py`
- **Video Classification Utils**（source_file）：BREAKFAST LABELS = 'pancake', 'cereal', 'sandwich', 'scrambledegg', 'friedegg', 'coffee', 'milk', 'tea', 'juice', 'salad' K700 LABELS = 'waiting in line', 'fly tying', 'breakdancing', 'coloring in', 'counting money', 'whistling', 'parkour', 'playing keyboard', 'laying tiles', 'flint knapping', 'raising eyebrows', 'base jumping', 'playing lute', 'brushing floor', 'weaving fabric', 'dining', 'dyeing hair', 'archery', 'luge', 'sword swallowing', 'clapping', 'arranging flowers', 'sucking lolly', 'writing', 'watering plants', 'playing piano', 'packing', 'lawn mower racing', 'yarn spinning', 'carrying baby', 'riding mule', 'hugging baby', 'tasting food', 'massaging back', 'cooking scallops', 'pla… 证据：`src/em2mem/embedding/VLM2Vec/src/data/eval_dataset/video_classification_utils.py`
- **Dataset Utils**（source_file）：def sample dataset dataset, kwargs ⋮---- dataset name = kwargs.get "dataset name", "UNKNOWN-DATASET" num sample per subset = kwargs.get "num sample per subset", None ⋮---- num sample per subset = int num sample per subset ⋮---- dataset = dataset.select range num sample per subset ⋮---- def load qrels mapping qrels ⋮---- qrels mapping = {} ⋮---- qid = row "query-id" docid = row "corpus-id" score = row "score" ⋮---- existing score = qrels mapping qid .get docid, 0 ⋮---- def load hf dataset hf path ⋮---- def load hf dataset multiple subset hf path, subset names ⋮---- subsets = ⋮---- dataset = load dataset repo, subset name, split=split new column = subset name len dataset dataset = dataset.add… 证据：`src/em2mem/embedding/VLM2Vec/src/data/utils/dataset_utils.py`
- **adopted from LLaVA-Hound-DPO**（source_file）：VID EXTENSIONS = ".mp4", ".avi", ".mov", ".mkv" IMAGE EXTENSIONS = ".jpg", ".jpeg", ".png" ⋮---- regex = re.compile ⋮---- r"^ ?:http ftp s?://" http:// or https:// r" ?: ?: A-Z0-9 ?: A-Z0-9- {0,61} A-Z0-9 ?\. + ?: A-Z {2,6}\.? A-Z0-9- {2,}\.? " domain... r"localhost " localhost... r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} " ...or ip r" ?::\d+ ?" optional port ⋮---- def qa template question, candidates, answer ⋮---- question = f"{question}\n" ⋮---- answer idx = -1 options = ⋮---- answer idx = idx question = question.rstrip answer = f" {chr ord 'A' + answer idx } {answer}" ⋮---- def is url url ⋮---- def read file input path ⋮---- def download url input path ⋮---- output dir = "cache" ⋮---- base na… 证据：`src/em2mem/embedding/VLM2Vec/src/data/utils/vision_utils.py`
- **Dist Utils**（source_file）：class GatherLayer torch.autograd.Function ⋮---- @staticmethod def forward ctx, input ⋮---- output = torch.zeros like input for in range dist.get world size ⋮---- @staticmethod def backward ctx, grads ⋮---- grad out = torch.zeros like input ⋮---- def dist gather x: torch.tensor ⋮---- x = x.reshape 1 x gather = GatherLayer.apply x x gather = torch.cat x gather, dim=0 ⋮---- @torch.no grad def dist gather nograd x: torch.tensor ⋮---- x gather = torch.ones like x for in range get world size ⋮---- def get rank ⋮---- def is main ⋮---- def get world size ⋮---- def barrier ⋮---- @torch.no grad def varsize gather nograd x: torch.Tensor ⋮---- size = torch.tensor x.shape 0 , device=x.device, dtype=torc… 证据：`src/em2mem/embedding/VLM2Vec/src/dist_utils.py`
- **Tree Utils**（source_file）：def tree chunk tree: Any, n chunk: int, axis: int = 0 - Any ⋮---- def tree unchunk tree: Any, axis: int = 0 - Any 证据：`src/em2mem/embedding/VLM2Vec/src/grad_cache/cachex/tree_utils.py`
- **Processing Utils**（source_file）：class BaseVisualRetrieverProcessor ABC, ProcessorMixin ⋮---- device = device or get torch device "auto" ⋮---- qs stacked = torch.stack qs .to device ps stacked = torch.stack ps .to device ⋮---- scores = torch.einsum "bd,cd- bc", qs stacked, ps stacked ⋮---- scores = scores.to torch.float32 证据：`src/em2mem/embedding/VLM2Vec/src/model/baseline_backbone/colpali/processing_utils.py`
- **Torch Utils**（source_file）：logger = logging.getLogger name T = TypeVar "T" ⋮---- def get torch device device: str = "auto" - str ⋮---- device = "cuda:0" ⋮---- device = "mps" ⋮---- device = "cpu" ⋮---- def tear down torch ⋮---- class ListDataset Dataset T ⋮---- def init self, elements: List T ⋮---- def len self - int ⋮---- def getitem self, idx: int - T ⋮---- results: List torch.Tensor = ⋮---- is padding = torch.all seq.eq padding value , dim=-1 ⋮---- non padding indices = ~is padding .nonzero as tuple=False ⋮---- valid seq = seq :0 ⋮---- first valid idx = non padding indices 0 .item valid seq = seq first valid idx: ⋮---- last valid idx = non padding indices -1 .item valid seq = seq : last valid idx + 1 证据：`src/em2mem/embedding/VLM2Vec/src/model/baseline_backbone/colpali/torch_utils.py`
- **Utils**（source_file）：class UnionFind ⋮---- def init self, size def find self, x def union self, x, y ⋮---- px = self.find x py = self.find y ⋮---- def get select mask tensor, skip ratio=0, rand=False ⋮---- retain mask = tensor == -1 .clone ⋮---- positions = tensor == val .nonzero as tuple=True 0 num positions = len positions ⋮---- num to skip = int round num positions skip ratio num to retain = max 1, num positions - num to skip ⋮---- perm = torch.randperm num positions, device=tensor.device positions to retain = positions perm :num to retain ⋮---- indices = torch.linspace 0, num positions - 1, steps=num to retain .long positions to retain = positions indices ⋮---- retain mask = tensor == -1 .copy ⋮---- positio… 证据：`src/em2mem/embedding/VLM2Vec/src/model/utils.py`
- **Init**（source_file）：import structure = { 证据：`src/em2mem/embedding/VLM2Vec/src/model/vlm_backbone/qwen2_vl/__init__.py`
- **resize**（source_file）：MAX RATIO = 200 SPATIAL MERGE SIZE = 2 IMAGE MIN TOKEN NUM = 4 IMAGE MAX TOKEN NUM = 16384 VIDEO MIN TOKEN NUM = 128 VIDEO MAX TOKEN NUM = 768 ⋮---- FPS = 2.0 FRAME FACTOR = 2 FPS MIN FRAMES = 4 FPS MAX FRAMES = 768 MAX NUM WORKERS FETCH VIDEO = 8 ⋮---- MODEL SEQ LEN = int float os.environ.get 'MODEL SEQ LEN', 128000 logger = logging.getLogger name ⋮---- def round by factor number: int, factor: int - int ⋮---- def ceil by factor number: int, factor: int - int ⋮---- def floor by factor number: int, factor: int - int ⋮---- def smart resize height: int, width: int, factor: int, min pixels: Optional int = None, max pixels: Optional int = None - Tuple int, int ⋮---- max pixels = max pixels if ma… 证据：`src/em2mem/embedding/VLM2Vec/src/model/vlm_backbone/qwen2_vl/qwen_vl_utils.py`
- **Init**（source_file）：import structure = { 证据：`src/em2mem/embedding/VLM2Vec/src/model/vlm_backbone/qwen2_vl_tokenselection/__init__.py`
- **Simple Prompts**（source_file）：beir all = 'trec-covid', 'arguana', 'webis-touche2020', 'scidocs', 'scifact', 'nfcorpus', 'fiqa', ⋮---- @AutoPrompt.register "none" def load dummy prompt task type, task name, args, kwargs ⋮---- @AutoPrompt.register "e5" def load e5 prompt task type, task name, args, kwargs ⋮---- @AutoPrompt.register "bge" def load bge prompt task type, task name="Retrieval", args, kwargs ⋮---- @AutoPrompt.register "uae" def load uae prompt task type, task name, args, kwargs ⋮---- @AutoPrompt.register "stella" def load stella prompt task type, task name, args, kwargs 证据：`src/em2mem/embedding/VLM2Vec/src/prompt/simple_prompts.py`
- **Basic Utils**（source_file）：logger = get logger name ⋮---- @contextmanager def elapsed timer ⋮---- start = default timer elapser = lambda: default timer - start ⋮---- end = default timer elapser = lambda: end-start ⋮---- class AverageMeter object ⋮---- def init self, name, fmt=':f' ⋮---- def reset self ⋮---- def update self, val, n=1 ⋮---- def str self ⋮---- fmtstr = '{name} {val' + self.fmt + '} {avg' + self.fmt + '} ' ⋮---- def save args to json args, output json path ⋮---- serializable args = {} ⋮---- v = json.dumps v ⋮---- def load args from json output json path ⋮---- kwargs = json.load arg json kwargs = {} ⋮---- v = None ⋮---- v = True if v == 'true' else False ⋮---- v = eval v ⋮---- args = argparse.Namespace kw… 证据：`src/em2mem/embedding/VLM2Vec/src/text_utils/basic_utils.py`
- **Dist Utils**（source_file）：class GatherLayer torch.autograd.Function ⋮---- @staticmethod def forward ctx, input ⋮---- output = torch.zeros like input for in range dist.get world size ⋮---- @staticmethod def backward ctx, grads ⋮---- grad out = torch.zeros like input ⋮---- def dist gather x: torch.tensor ⋮---- x = x.reshape 1 x gather = GatherLayer.apply x x gather = torch.cat x gather, dim=0 ⋮---- @torch.no grad def dist gather nograd x: torch.tensor ⋮---- x gather = torch.ones like x for in range get world size ⋮---- def get rank ⋮---- def is main ⋮---- def get world size ⋮---- def barrier ⋮---- @torch.no grad def varsize gather nograd x: torch.Tensor ⋮---- size = torch.tensor x.shape 0 , device=x.device, dtype=torc… 证据：`src/em2mem/embedding/VLM2Vec/src/text_utils/dist_utils.py`
- **XXX: need to test that this simple glob rule works for multi-node setup too**（source_file）：debug = 0 ⋮---- device = torch.device 'cpu' ⋮---- def atoi text ⋮---- def natural keys text ⋮---- def get model state file checkpoint dir, zero stage ⋮---- file = os.path.join checkpoint dir, "mp rank 00 model states.pt" ⋮---- file = os.path.join checkpoint dir, "zero pp rank 0 mp rank 00 model states.pt" ⋮---- def get optim files checkpoint dir ⋮---- XXX: need to test that this simple glob rule works for multi-node setup too optim files = sorted glob.glob os.path.join checkpoint dir, ⋮---- def parse model state file ⋮---- state dict = torch.load file, map location=device ⋮---- buffer names = state dict BUFFER NAMES ⋮---- buffers = { param shapes = state dict PARAM SHAPES ⋮---- ds version =… 证据：`src/em2mem/embedding/VLM2Vec/src/text_utils/ds_utils.py`
- **Infer Utils**（source_file）：def hfmodel generate tokenizer, model, prompt, generate kwargs={} ⋮---- encoded input = tokenizer prompt, return tensors="pt", add special tokens=False input ids = encoded input.input ids ⋮---- prompt len = input ids.shape 1 output = model.generate output ids = output.sequences :, prompt len + 3: output seq = tokenizer.batch decode output ids.cpu , skip special tokens=True 0 .strip output tokens = tokenizer.decode t for t in output ids.cpu probs = torch.nn.functional.softmax torch.cat output.scores, dim=0 , dim=-1 证据：`src/em2mem/embedding/VLM2Vec/src/text_utils/infer_utils.py`
- **We store last lr here so that custom transitions work with .sample lrs**（source_file）：class KeyframeLR LRScheduler ⋮---- def parse frames self, user frames ⋮---- frames = previous pos = -1 end pos = self.end if self.units == "steps" else 1 ⋮---- unpacked frames = ⋮---- frame = {"position": frame 0 , "lr": frame 1 } ⋮---- frame = {"transition": frame} ⋮---- first frame = i == 0 last frame = i == len unpacked frames - 1 ⋮---- position = frame "position" ⋮---- previous pos = position ⋮---- next frame = unpacked frames i + 1 ⋮---- @staticmethod def interpolate a, b, pct ⋮---- def interpolate frames self, start frame, transition, end frame, position ⋮---- pos range = end frame "position" - start frame "position" pct of range = position - start frame "position" / pos range ⋮---- p… 证据：`src/em2mem/embedding/VLM2Vec/src/text_utils/lr_utils.py`
- **Utils**（source_file）：logger = logging.getLogger name ⋮---- def print rank message ⋮---- def print master message ⋮---- def find latest checkpoint output dir ⋮---- checkpoints = ⋮---- latest checkpoint = max checkpoints, key=lambda x: int x.split "-" -1 ⋮---- def batch to device batch, device ⋮---- batch = {} 证据：`src/em2mem/embedding/VLM2Vec/src/utils.py`
- **Init**（source_file）：all = 'EmbeddingModel' 证据：`src/em2mem/embedding/__init__.py`
- **Init**（source_file）：all = 'LLMModel', 'PromptTemplateManager' 证据：`src/em2mem/llm/__init__.py`
- **Multiscale Filter**（source_file）：prompt template = 证据：`src/em2mem/llm/templates/multiscale_filter.py`
- **Utils**（source_file）：def dynamic retry decorator func ⋮---- @functools.wraps func def sync wrapper self, args, kwargs ⋮---- max retries = getattr self, 'max retries', 5 decorated func = retry ⋮---- async def async wrapper self, args, kwargs 证据：`src/em2mem/llm/utils.py`
- **-----------------------------------------------------**（source_file）：logger = logging.getLogger name ⋮---- STOPWORDS = { ⋮---- class EM2Memory ⋮---- lines = f"Query: {query}" ⋮---- choices str = " ".join f" {k} {v}" for k, v in sorted choices.items ⋮---- ----------------------------------------------------- loading ⋮---- def prepare episodic dense index self, force rebuild: bool = False - None ⋮---- def prepare semantic dense index self, force rebuild: bool = False - None ⋮---- indexing ⋮---- def index self, until time: int - None ⋮---- helpers ⋮---- def tokenize self, text: str - Set str ⋮---- toks = re.findall r" a-zA-Z0-9 /- +", str text .lower ⋮---- def normalize dict self, score map: Dict str, float - Dict str, float ⋮---- values = list score map.values… 证据：`src/em2mem/memory/EM2Memory.py`
- **dense index state**（source_file）：logger = logging.getLogger name ⋮---- STOPWORDS = { ⋮---- @dataclass class CaptionEntry ⋮---- id: str doc id: str text: str start time: str end time: str date: str granularity: str video path: Optional str = None visual summary: str = "" metadata: Dict str, Any = field default factory=dict ⋮---- @property def timestamp int self - Tuple int, int ⋮---- day = self.date.replace 'DAY', '' .replace 'Day', '' start ts = int day + self.start time.zfill 8 end ts = int day + self.end time.zfill 8 ⋮---- def to display str self, include visual summary: bool = True - str ⋮---- base = f" { transform timestamp str start ts } - { transform timestamp str end ts } \n{self.text}" ⋮---- @dataclass class GraphE… 证据：`src/em2mem/memory/multimodal_memory_cell/MemoryCell.py`
- **Try to load the JSON to see if it is valid**（source_file）：@dataclass class LLMInput ⋮---- chunk id: str input message: List Dict ⋮---- class NerRawOutput BaseModel ⋮---- named entities: List str ⋮---- class TripleRawOutput BaseModel ⋮---- triples: List List str ⋮---- @dataclass class NerOutput ⋮---- unique entities: List str metadata: Dict str, Any ⋮---- @dataclass class TripleOutput ⋮---- def compute mdhash id content: str, prefix: Optional str = "" - str ⋮---- """ Compute the MD5 hash of the given content string and optionally prepend a prefix. Args: content str : The input string to be hashed. prefix str, optional : A string to prepend to the resulting hash. Defaults to an empty string. Returns: str: A string consisting of the prefix followed b… 证据：`src/em2mem/memory/multimodal_memory_cell/utils.py`
- **Utils**（source_file）：class SemanticRawOutput BaseModel ⋮---- semantic triples: List List str episodic evidence: List List int ⋮---- @field validator "semantic triples" @classmethod def validate semantic triples cls, v ⋮---- bad = i, t for i, t in enumerate v if not isinstance t, list or len t != 3 ⋮---- @field validator "episodic evidence" @classmethod def validate evidence items cls, v ⋮---- @model validator mode="after" def align lengths self ⋮---- n = len self.semantic triples or m = len self.episodic evidence or ⋮---- class ConsolidationRawOutput BaseModel ⋮---- updated triple: List str triples to remove: List int ⋮---- @field validator "updated triple" def validate updated triple cls, v ⋮---- @field valida… 证据：`src/em2mem/memory/semantic_graph/utils.py`
- **Utils**（source_file）：@dataclass class MemorySearchOutput ⋮---- memory type: str search query: str ⋮---- @dataclass class ReasoningOutput ⋮---- decision: str selected memory: Optional MemorySearchOutput = None reason: Optional str = None ⋮---- @dataclass class RetrievedItem ⋮---- content: Union str, List Image.Image query: str round num: int ⋮---- @dataclass class QAResult ⋮---- question: str answer: str retrieved items: List RetrievedItem round history: List Dict str, Any num rounds: int ⋮---- def transform timestamp ts str: str - str ⋮---- day = ts str 0 time str = ts str 1: hh = time str 0:2 mm = time str 2:4 ss = time str 4:6 证据：`src/em2mem/memory/utils.py`

## 宿主 AI 必须遵守的规则

- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`README.md`, `experiments/egolife/readme.md`, `experiments/locomo/readme.md`
- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`README.md`, `experiments/egolife/readme.md`, `experiments/locomo/readme.md`

## 用户开工前应该回答的问题

- 你准备在哪个宿主 AI 或本地环境中使用它？
- 你只是想先体验工作流，还是准备真实安装？
- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？

## 验收标准

- 所有能力声明都能回指到 evidence_refs 中的文件路径。
- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。
- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。

---

## Doramagic Context Augmentation

下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。

## Human Manual 骨架

使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。

宿主 AI 硬性规则：
- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。
- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。
- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。

- **项目概览与快速导航**：importance `high`
  - source_paths: README.md, pyproject.toml, StructMem.md, FluxMem.md, EM2Mem.md
- **系统架构与核心模块（src/lightmem）**：importance `high`
  - source_paths: src/lightmem/__init__.py, src/lightmem/memory/lightmem.py, src/lightmem/memory/graph.py, src/lightmem/memory/prompts.py, src/lightmem/memory/utils.py
- **配置系统与工厂后端**：importance `high`
  - source_paths: src/lightmem/configs/memory_manager/base.py, src/lightmem/configs/memory_manager/base_config.py, src/lightmem/configs/pre_compressor/base.py, src/lightmem/configs/pre_compressor/llmlingua_2.py, src/lightmem/configs/pre_compressor/entropy_compress.py
- **记忆操作全流程：add / retrieve / update / summarize**：importance `high`
  - source_paths: src/lightmem/memory/lightmem.py, experiments/locomo/add_locomo.py, experiments/locomo/search_locomo.py, experiments/longmemeval/offline_update.py, src/lightmem/memory/graph.py
- **预压缩（LLMLingua-2 / 熵压缩）与主题分段**：importance `high`
  - source_paths: src/lightmem/configs/pre_compressor/llmlingua_2.py, src/lightmem/configs/pre_compressor/entropy_compress.py, src/lightmem/factory/pre_compressor/llmlingua_2.py, src/lightmem/factory/pre_compressor/entropy_compress.py, src/lightmem/factory/topic_segmenter/llmlingua_2.py
- **实验复现：LoCoMo 与 LongMemEval**：importance `high`
  - source_paths: experiments/locomo/add_locomo.py, experiments/locomo/search_locomo.py, experiments/locomo/llm_judge.py, experiments/locomo/prompts.py, experiments/locomo/retrievers.py
- **基线评估框架（Memory Toolkits）**：importance `high`
  - source_paths: src/lightmem/memory_toolkits/readme.md, src/lightmem/memory_toolkits/run_baseline.sh, src/lightmem/memory_toolkits/memory_construction.py, src/lightmem/memory_toolkits/memory_evaluation.py, src/lightmem/memory_toolkits/memory_search.py
- **扩展方法（FluxMem / StructMem / EM²Mem）与 MCP 服务**：importance `medium`
  - source_paths: src/fluxmem/__init__.py, src/fluxmem/agent.py, src/fluxmem/config.py, src/fluxmem/graph/memory_graph.py, src/em2mem/memory/EM2Memory.py

## Repo Inspection Evidence / 源码检查证据

- repo_clone_verified: true
- repo_inspection_verified: true
- repo_commit: `4a9f1d6243fa09a11506f06b83ac1c74b5c87451`
- inspected_files: `README.md`, `pyproject.toml`, `examples/run_lightmem_bm25.py`, `examples/run_lightmem_ollama.py`, `examples/run_lightmem_transformers.py`, `examples/run_llmlingua2_gpt.py`, `src/em2mem/__init__.py`, `src/em2mem/embedding/VLM2Vec/CHANGELOG.md`, `src/em2mem/embedding/VLM2Vec/README.md`, `src/em2mem/embedding/VLM2Vec/adhoc/data/visdoc/export_colpali_training_by_category.py`, `src/em2mem/embedding/VLM2Vec/adhoc/data/visdoc/export_visrag_training_by_category.py`, `src/em2mem/embedding/VLM2Vec/adhoc/debug/iterable_dataset_drop_last_batch.py`, `src/em2mem/embedding/VLM2Vec/adhoc/eval_mteb/e5mistral_prompt.py`, `src/em2mem/embedding/VLM2Vec/adhoc/eval_mteb/merge_cqadupstack.py`, `src/em2mem/embedding/VLM2Vec/adhoc/eval_mteb/mteb_utils.py`, `src/em2mem/embedding/VLM2Vec/adhoc/eval_mteb/run_mteb.py`, `src/em2mem/embedding/VLM2Vec/adhoc/gather_score_byckpt_aws.py`, `src/em2mem/embedding/VLM2Vec/adhoc/hf_datasets.py`, `src/em2mem/embedding/VLM2Vec/adhoc/merge_checkpoint.py`, `src/em2mem/embedding/VLM2Vec/adhoc/plot.py`

宿主 AI 硬性规则：
- 没有 repo_clone_verified=true 时，不得声称已经读过源码。
- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。
- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。

## Doramagic Pitfall Constraints / 踩坑约束

这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。

### Constraint 1: 来源证据：Bug: `topic_segment=False` causes `add_memory()` to skip the entire extraction pipeline, resulting in empty Qdrant stor…

- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Bug: `topic_segment=False` causes `add_memory()` to skip the entire extraction pipeline, resulting in empty Qdrant storage
- Why it matters: 可能增加新用户试用和生产接入成本。
- Evidence: community_evidence:github | https://github.com/zjunlp/LightMem/issues/55 | 来源类型 github_issue 暴露的待验证使用条件。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 2: 来源证据：Clarification on LongMemEval evaluation setting

- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Clarification on LongMemEval evaluation setting
- Why it matters: 可能影响授权、密钥配置或安全边界。
- Evidence: community_evidence:github | https://github.com/zjunlp/LightMem/issues/70 | 来源类型 github_issue 暴露的待验证使用条件。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 3: 来源证据：LLMLingua-2 的 compress_prompt_llmlingua2 方法内部没有自动分块——它把整个 context 直接过 BERT，所以超长必定炸。

- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：LLMLingua-2 的 compress_prompt_llmlingua2 方法内部没有自动分块——它把整个 context 直接过 BERT，所以超长必定炸。
- Why it matters: 可能影响授权、密钥配置或安全边界。
- Evidence: community_evidence:github | https://github.com/zjunlp/LightMem/issues/71 | 来源类型 github_issue 暴露的待验证使用条件。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 4: 来源证据：Lightmem, Clarification on Section 3.2 and its implementation

- Trigger: GitHub 社区证据显示该项目存在一个能力理解相关的待验证问题：Lightmem, Clarification on Section 3.2 and its implementation
- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Why it matters: 可能增加新用户试用和生产接入成本。
- Evidence: community_evidence:github | https://github.com/zjunlp/LightMem/issues/69 | 来源类型 github_issue 暴露的待验证使用条件。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 5: 能力判断依赖假设

- Trigger: README/documentation is current enough for a first validation pass.
- Host AI rule: 将假设转成下游验证清单。
- Why it matters: 假设不成立时，用户拿不到承诺的能力。
- Evidence: capability.assumptions | https://github.com/zjunlp/LightMem | README/documentation is current enough for a first validation pass.
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 6: 来源证据：[Bug] Unknown attribute "retriever" when enable enable_summary

- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[Bug] Unknown attribute "retriever" when enable enable_summary
- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Why it matters: 可能增加新用户试用和生产接入成本。
- Evidence: community_evidence:github | https://github.com/zjunlp/LightMem/issues/52 | 来源类型 github_issue 暴露的待验证使用条件。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 7: 来源证据：Question about Table 3: how is the Calls metric on LoCoMo averaged?

- Trigger: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：Question about Table 3: how is the Calls metric on LoCoMo averaged?
- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Why it matters: 可能增加新用户试用和生产接入成本。
- Evidence: community_evidence:github | https://github.com/zjunlp/LightMem/issues/60 | 来源类型 github_issue 暴露的待验证使用条件。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 8: 维护活跃度未知

- Trigger: 未记录 last_activity_observed。
- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。
- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- Evidence: evidence.maintainer_signals | https://github.com/zjunlp/LightMem | last_activity_observed missing
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

- Trigger: no_demo
- Evidence: downstream_validation.risk_items | https://github.com/zjunlp/LightMem | no_demo; severity=medium
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 10: 存在评分风险

- Trigger: no_demo
- Why it matters: 风险会影响是否适合普通用户安装。
- Evidence: risks.scoring_risks | https://github.com/zjunlp/LightMem | no_demo; severity=medium
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。
