# tom-swe - Doramagic AI Context Pack

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

## 充分原则

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

## 给宿主 AI 的使用方式

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

## Claim 消费规则

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

## 它最适合谁

- **正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**：README 或插件配置提到多个宿主 AI。 证据：`README.md` Claim：`clm_0002` supported 0.86

## 它能做什么

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

## 怎么开始

- `pip install uv` 证据：`README.md` Claim：`clm_0003` supported 0.86
- `pip install tom-swe` 证据：`README.md` Claim：`clm_0004` supported 0.86

## 继续前判断卡

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

### 30 秒判断

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

### 现在可以相信

- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（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 的默认行为。 证据：`AGENTS.md`, `CLAUDE.md`
- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。
- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。
- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。
- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`

### 继续会触碰什么

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

### 最小安全下一步

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

### 退出方式

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

## 哪些只能预览

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

## 哪些必须安装后验证

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

## 边界与风险判断卡

- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0005` inferred 0.45
- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0006` 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

### 上下文规模

- 文件总数：67
- 重要文件覆盖：40/67
- 证据索引条目：56
- 角色 / Skill 条目：4

### 证据不足时的处理

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

## Prompt Recipes

### 适配判断

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

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

### 安装前体验

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

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

请严格输出四段：
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
请基于 tom-swe 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。
```

## 角色 / Skill 索引

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

- **ToM-SWE Repository Overview**（project_doc）：Project Description ToM-SWE is a Theory of Mind package for Software Engineering agents that provides personalized instruction improvement and user behavior analysis. It uses a three-tier memory system cleaned sessions → session analyses → user profiles to understand user preferences and enhance AI agent interactions through psychological insights and personalized guidance. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`AGENTS.md`
- **CLAUDE.md**（project_doc）：This file provides guidance to Claude Code claude.ai/code when working with code in this repository. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CLAUDE.md`
- **News**（project_doc）：TOM-SWE: User Mental Modeling For Software Engineering Agents 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`
- **Release Process for tom-swe**（project_doc）：This document describes how to publish new versions of tom-swe to PyPI. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`RELEASE.md`

## 证据索引

- 共索引 56 条证据。

- **ToM-SWE Repository Overview**（documentation）：Project Description ToM-SWE is a Theory of Mind package for Software Engineering agents that provides personalized instruction improvement and user behavior analysis. It uses a three-tier memory system cleaned sessions → session analyses → user profiles to understand user preferences and enhance AI agent interactions through psychological insights and personalized guidance. 证据：`AGENTS.md`
- **CLAUDE.md**（documentation）：This file provides guidance to Claude Code claude.ai/code when working with code in this repository. 证据：`CLAUDE.md`
- **News**（documentation）：TOM-SWE: User Mental Modeling For Software Engineering Agents 证据：`README.md`
- **Release Process for tom-swe**（documentation）：This document describes how to publish new versions of tom-swe to PyPI. 证据：`RELEASE.md`
- **Clean up test data after showing results**（source_file）：def test sleeptime ⋮---- sessions data = ⋮---- session data = json.load open f"./data/example sessions/{file}" ⋮---- sessions data = sessions data :1 agent = ToMAgent ⋮---- Clean up test data after showing results if test dir.exists : shutil.rmtree test dir print f"\n🧹 Cleaned up test data: {test dir}" def test pure rag ⋮---- """Test Pure RAG baseline mode.""" ⋮---- config = ToMAgentConfig agent = ToMAgent config query = "Help me fix a bug" result = agent.give suggestions query=query, pure rag=True ⋮---- def main ⋮---- """Demonstrate the ToM Agent consultation functionality.""" ⋮---- user id = "" Use default user for demo formatted messages = ⋮---- lines = f.readlines ⋮---- instruction = f"… 证据：`example.py`
- **Init**（source_file）：version = "0.1.0" 证据：`stateful_swe/__init__.py`
- **Specific question suggestions**（source_file）：@dataclass class EvalResult ⋮---- instance id: str statement type: str problem statement: str original issue: str tom suggestion: str suggested questions: bool confidence score: float correct classification: bool class ClarityEvaluator ⋮---- def init self, dataset path: str, num samples: int = 50 def setup agent self - None ⋮---- config = ToMAgentConfig ⋮---- def detect question suggestion self, suggestion: str - bool ⋮---- suggestion lower = suggestion.lower question asking patterns = ⋮---- Specific question suggestions ⋮---- Problem identification requiring questions ⋮---- Check for question-asking patterns ⋮---- Patterns that indicate the issue is clear/actionable negative indicators cle… 证据：`stateful_swe/clarity_eval.py`
- **Check if API key is configured**（source_file）：@dataclass class ModelConfig ⋮---- name: str model id: str input cost per 1m: float output cost per 1m: float description: str ⋮---- @dataclass class EvalResult ⋮---- instance id: str statement type: str problem statement: str original issue: str tom suggestion: str suggested questions: bool confidence score: float correct classification: bool model name: str input tokens: int output tokens: int cost usd: float evaluation time seconds: float ⋮---- @dataclass class ModelResults ⋮---- total samples: int correct classifications: int accuracy: float unclear accuracy: float clear accuracy: float total cost: float avg cost per consultation: float total input tokens: int total output tokens: int a… 证据：`stateful_swe/multi_model_clarity_eval.py`
- **Generate 15 realistic profiles based on actual user behavior analysis**（source_file）：class ProfileConfig TypedDict ⋮---- profile id: str verbosity: str question timing: str response style: str coding preferences: List str class ConcreteUserProfile ⋮---- def to dict self - Dict str, Any def get roleplay prompt self - str ⋮---- verbosity desc = { timing desc = { response desc = { prefs desc = "You have specific coding preferences: " + "; ".join ⋮---- class RealUserProfileGenerator ⋮---- def init self def generate 15 profiles self - List ConcreteUserProfile ⋮---- profiles = base combinations = profile configs: List ProfileConfig = ⋮---- num prefs = random.randint 5, 10 git prefs = random.sample quality prefs = random.sample arch prefs = random.sample tech prefs = random.sample… 证据：`stateful_swe/profile_generator.py`
- **Use tiktoken for accurate token counting**（source_file）：logger = logging.getLogger name ⋮---- TOM SWE AVAILABLE = True ⋮---- TOM SWE AVAILABLE = False LLMClient = None LLMConfig = None DEFAULT LLM MODEL = "gpt-5-mini-2025-08-07" ⋮---- TIKTOKEN AVAILABLE = True ⋮---- TIKTOKEN AVAILABLE = False class MessageAction Enum ⋮---- KEEP UNCHANGED = "keep unchanged" REPLACE SENTENCE = "replace sentence" APPEND PREFERENCE = "append preference" DELETE CONTENT = "delete content" class MessageModification BaseModel ⋮---- action: MessageAction = Field description="The type of modification to perform" target text: Optional str = Field replacement text: Optional str = Field reasoning: str = Field class MessageWashingResponse BaseModel ⋮---- alignment score: floa… 证据：`stateful_swe/session_washer.py`
- **Create output directory**（source_file）：def load results file path: str - Dict str, Any def create accuracy vs cost plot report: Dict str, Any , output dir: Path - None ⋮---- data = ⋮---- df = pd.DataFrame data ⋮---- def create cost effectiveness chart report: Dict str, Any , output dir: Path - None ⋮---- data = report "cost effectiveness ranking" models = item "model" for item in data scores = item "cost effectiveness score" for item in data ⋮---- bars = plt.bar models, scores, alpha=0.7, color=plt.cm.viridis range len models ⋮---- height = bar.get height ⋮---- models = clear acc = unclear acc = overall acc = ⋮---- x = range len models width = 0.25 ⋮---- bars1 = plt.bar bars2 = plt.bar x, unclear acc, width, label="Unclear State… 证据：`stateful_swe/visualize_model_results.py`
- **Init**（source_file）：version = "1.0.0" author = "Research Team" description = "LLM-powered Theory of Mind analysis for user behavior prediction" all = 证据：`tom_swe/__init__.py`
- **Use very conservative batch size to stay well under 300K token limit**（source_file）：tiktoken = None ⋮---- logger = get tom swe logger name ⋮---- logger = logging.getLogger name DEFAULT LLM MODEL = os.getenv LITELLM API KEY = os.getenv "LITELLM API KEY" LITELLM BASE URL = os.getenv "LITELLM BASE URL" ⋮---- @dataclass class ChunkingConfig ⋮---- target chunk tokens: int = max chunk tokens: int = user message priority: float = 0.6 context priority: float = 0.4 min user message tokens: int = 100 overlap tokens: int = 200 system tag patterns: Optional List str = None def post init self - None ⋮---- @dataclass class Document ⋮---- """Represents a document with its chunks and metadata.""" doc id: str content: str chunks: List Dict str, Any metadata: Optional Dict str, Any = None ⋮… 证据：`tom_swe/rag_module.py`
- **Initialize action executor with reference to this agent**（source_file）：logger = get tom swe logger name ⋮---- logger = logging.getLogger name CLI DISPLAY LEVEL = 25 ⋮---- DEFAULT LLM MODEL = os.getenv "DEFAULT LLM MODEL", "litellm proxy/gpt-5-2025-04-16" LITELLM API KEY = os.getenv "LITELLM API KEY" LITELLM BASE URL = os.getenv "LITELLM BASE URL" all = "ToMAgent", "ToMAgentConfig", "create tom agent" ⋮---- @dataclass class ToMAgentConfig ⋮---- file store: Optional FileStore = None llm model: Optional str = None enable rag: bool = False api key: Optional str = None api base: Optional str = None skip memory collection: bool = class ToMAgent ⋮---- def init self, config: Optional ToMAgentConfig = None - None ⋮---- config = ToMAgentConfig ⋮---- llm config = LLMConf… 证据：`tom_swe/tom_agent.py`
- **Extract important user messages and full session context**（source_file）：logger = get tom swe logger name ⋮---- logger = logging.getLogger name CLI DISPLAY LEVEL = 25 ⋮---- class ToMAnalyzer ⋮---- """Initialize the analyzer with configuration and validate setup.""" ⋮---- async def analyze session self, session data: Dict str, Any - SessionAnalysis ⋮---- """ Analyze a complete session and return a session summary. Uses important user messages as focus points with full session context. """ session id = session data.get "session id", "unknown" ⋮---- Extract important user messages and full session context important user messages = all messages = ⋮---- role = message.get "role", "unknown" content = message.get "content", "" ⋮---- Filter for important user messages ⋮… 证据：`tom_swe/tom_module.py`
- **Init**（source_file）：all = 证据：`utils/__init__.py`
- **Apply user sampling if specified**（source_file）：LITELLM API KEY = os.getenv "LITELLM API KEY" LITELLM BASE URL = os.getenv "LITELLM BASE URL" DEFAULT LLM MODEL = os.getenv MAX EXAMPLES PER BATCH = 15 MAX USERS FOR PREFERENCE ANALYSIS = 30 ⋮---- @dataclass class AnalysisData ⋮---- negative messages: Dict str, List Dict str, Any user preferences: Dict str, Dict str, Any frustration analysis: Dict str, Any preference analysis: Dict str, Any best practices: Dict str, Any class EnhancedUserBehaviorAnalyzer ⋮---- def set batch size self, batch size: int - None ⋮---- async def call llm self, prompt: str - str ⋮---- completion args = { ⋮---- response = await acompletion completion args content = response.choices 0 .message.content ⋮---- def extr… 证据：`utils/aggregate_user_behavior.py`
- **Init**（source_file）：all = 证据：`visualization/__init__.py`
- **Init**（source_file）：all = 证据：`tom_swe/generation/__init__.py`
- **Handle final response actions - these contain the response data in parameters**（source_file）：HAS BM25S = True ⋮---- HAS BM25S = False ⋮---- class Bm25sFallback ⋮---- BM25 = bm25s BM25 ⋮---- @staticmethod def tokenize text: Any, kwargs: Any - Any bm25s = Bm25sFallback ⋮---- logger = get tom swe logger name ⋮---- logger = logging.getLogger name class ActionExecutor ⋮---- Handle final response actions - these contain the response data in parameters ⋮---- def action read file self, params: ReadFileParams - str ⋮---- content = self.file store.read params.file path ⋮---- """Get file content by search scope, optionally sorted by date. Returns list of file path, content tuples.""" Limit to 10 conversations when using pure Python BM25 ⋮---- limit = 10 ⋮---- files = self.file store.list get… 证据：`tom_swe/generation/action.py`
- **Dataclass**（source_file）：class ActionType Enum ⋮---- READ FILE = "read file" SEARCH FILE = "search file" UPDATE JSON FIELD = "update json field" ANALYZE SESSION = "analyze session" INITIALIZE USER PROFILE = "initialize user profile" RAG SEARCH = "rag search" GENERATE SUGGESTIONS = "generate suggestions" GENERATE SLEEP SUMMARY = "generate sleep summary" class ReadFileParams BaseModel ⋮---- file path: str = Field character start: int = Field character end: int = Field class SearchFileParams BaseModel ⋮---- query: str = Field search scope: str = Field search method: str = Field max results: int = Field chunk size: int = Field latest first: bool = Field class UpdateJsonFieldParams BaseModel ⋮---- field path: str = Fiel… 证据：`tom_swe/generation/dataclass.py`
- **Create output parser**（source_file）：logger = get tom swe logger name ⋮---- logger = logging.getLogger name T = TypeVar "T", bound=BaseModel DEFAULT MODEL = "litellm proxy/claude-sonnet-4-20250514" DEFAULT BAD OUTPUT PROCESS MODEL = "gpt-5-nano" ⋮---- @dataclass class LLMConfig ⋮---- model: str = DEFAULT MODEL api key: Optional str = None api base: Optional str = None fallback model: str = DEFAULT BAD OUTPUT PROCESS MODEL class LLMClient ⋮---- def init self, config: LLMConfig ⋮---- """ Reformat ill-formed output to valid JSON using a fallback model. Args: ill formed output: The malformed output from the original LLM format instructions: The format instructions that should be followed Returns: Reformatted JSON string """ templa… 证据：`tom_swe/generation/generate.py`
- **Init**（source_file）：all = 证据：`tom_swe/memory/__init__.py`
- **Remove phase-based template that starts with "Follow these phases to resolve the issue:"**（source_file）：T = TypeVar "T" ⋮---- @dataclass class CleanMessage ⋮---- role: str content: str is important: bool = False ⋮---- @dataclass class CleanSession ⋮---- session id: str start time: str end time: str messages: List CleanMessage user id: str = "" last updated: str = "" def clean user message content: str - str ⋮---- """Remove system tags and templates from user message.""" patterns = ⋮---- Remove phase-based template that starts with "Follow these phases to resolve the issue:" ⋮---- cleaned = content ⋮---- cleaned = re.sub pattern, "", cleaned, flags=re.DOTALL re.IGNORECASE ⋮---- def is important user message original: str, cleaned: str - bool ⋮---- """Check if user message is important based on… 证据：`tom_swe/memory/conversation_processor.py`
- **Init**（source_file）：all = "PromptManager", "get prompt manager", "render prompt" 证据：`tom_swe/prompts/__init__.py`
- **Manager**（source_file）：class PromptManager ⋮---- def init self, templates dir: Optional str = None def render self, template name: str, kwargs: Any - str ⋮---- template file = f"{template name}.jinja2" ⋮---- template = self.env.get template template file result: str = template.render kwargs ⋮---- def render from string self, template string: str, kwargs: Any - str ⋮---- """ Render a template from a string for backward compatibility . Args: template string: Template content as a string kwargs: Variables to pass to the template Returns: Rendered template as a string """ template = self.env.from string template string ⋮---- def list templates self - list str ⋮---- """ List all available template files. Returns: List… 证据：`tom_swe/prompts/manager.py`
- **Example**（structured_config）：{ "session id": "test session", "start time": "2025-08-11T01:27:31.170300", "end time": "2025-08-11T01:43:43.373152", "event count": 32, "message count": 26, "conversation messages": { "role": "system", "content": "You are OpenHands agent, a helpful AI assistant that can interact with a computer to solve tasks.\n\n \nYour primary role is to assist users by executing commands, modifying code, and solving technical problems effectively. You should be thorough, methodical, and prioritize quality over speed.\n If the user asks a question, like \"why is X happening\", don't try to fix the problem. Just give an answer to the question.\n \n\n \n Each action you take is somewhat expensive. Wherever… 证据：`example.json`
- **Byte-compiled / optimized / DLL files**（source_file）：Byte-compiled / optimized / DLL files pycache / .py cod $py.class 证据：`.gitignore`
- **.Pre Commit Config**（source_file）：repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: trailing-whitespace exclude: ^stateful swe/ - id: end-of-file-fixer exclude: ^stateful swe/ - id: check-yaml exclude: ^stateful swe/ - id: check-added-large-files exclude: ^stateful swe/ - repo: https://github.com/psf/black rev: 23.3.0 hooks: - id: black exclude: ^stateful swe/ - repo: https://github.com/astral-sh/ruff-pre-commit rev: 'v0.1.15' hooks: - id: ruff args: --fix, --exit-non-zero-on-fix exclude: ^stateful swe/ - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.3.0 hooks: - id: mypy additional dependencies: types-requests exclude: ^stateful swe/ 证据：`.pre-commit-config.yaml`
- **Ignore specific external modules**（source_file）：mypy python version = 3.12 warn return any = True warn unused configs = True disallow untyped defs = False ignore missing imports = True 证据：`mypy.ini`
- **Template engine**（source_file）：build-system requires = "hatchling" build-backend = "hatchling.build" 证据：`pyproject.toml`
- **Process queries in smaller batches with concurrent processing**（source_file）：def create llm client - LLMClient ⋮---- config = LLMConfig ⋮---- classification prompt = f"""You are an expert at categorizing software development queries. Please classify the following SWE agent consultation query into one of these categories: ⋮---- result = await llm client.call structured async ⋮---- async def classify queries batch queries: List str - List QueryClassification ⋮---- llm client = create llm client ⋮---- Process queries in smaller batches with concurrent processing batch size = 200 Reduced batch size for faster processing results = ⋮---- batch = queries i : i + batch size ⋮---- Create async tasks for concurrent processing tasks = classify query with llm llm client, query… 证据：`stateful_swe/advanced_tom_analytics.py`
- **Collect user IDs**（source_file）：def analyze tom metrics file path: str - None ⋮---- data = json.load f raw events = data.get "raw events", ⋮---- event counts = Counter consultation events = sleeptime events = distinct users = set unique sessions = set user sessions = defaultdict set ⋮---- event type = event.get "event", "" ⋮---- Collect user IDs distinct id = event.get "distinct id", "" ⋮---- Extract session information session id = event.get "properties", {} .get "session id", "" ⋮---- Collect consultation events ⋮---- consultation analysis = analyze consultations consultation events sleeptime analysis = analyze sleeptime sleeptime events session analysis = analyze session distribution user sessions, unique sessions ⋮---… 证据：`stateful_swe/analyze_tom_metrics.py`
- **Extract relevant profile information**（source_file）：LLM AVAILABLE = True class VagueStatementResponse BaseModel ⋮---- modified statement: str = Field reasoning: str = Field ⋮---- LLM AVAILABLE = False ⋮---- class VagueStatementResponse ⋮---- logger = logging.getLogger name DATASETS AVAILABLE = True class StatefulSWEDatasetBuilder ⋮---- api key = os.getenv "LITELLM API KEY" ⋮---- llm config = LLMConfig ⋮---- def load user profiles self, profiles path: str - List Dict str, Any ⋮---- """Load user profiles from JSONL file.""" profiles = ⋮---- profile = json.loads line.strip ⋮---- """ Modify a problem statement to be more ambiguous/vague while reflecting user profile characteristics. Args: problem statement: Original clear problem statement user… 证据：`stateful_swe/huggingface_dataset_builder.py`
- **Async API call**（source_file）：class AsyncToMWrapper ⋮---- def init self, model config: ModelConfig def get agent self - ToMAgent ⋮---- config = ToMAgentConfig ⋮---- loop = asyncio.get event loop def sync call ⋮---- agent = self. get agent ⋮---- future = executor.submit sync call ⋮---- class ParallelMultiModelEvaluator ⋮---- def detect question suggestion self, suggestion: str - bool ⋮---- suggestion lower = suggestion.lower question patterns = ⋮---- def load dataset self - List Dict str, Any ⋮---- parquet file = Path self.dataset path / "test-00000-of-00001.parquet" ⋮---- dataset = Dataset.from parquet str parquet file ⋮---- dataset = load from disk self.dataset path all data = list dataset sampled data = random.sample… 证据：`stateful_swe/parallel_multi_model_eval.py`
- **Normalize name for matching**（source_file）：def get available models - List str ⋮---- all models = { filtered models = ⋮---- Normalize name for matching normalized name = name.lower .replace "-", "" .replace ".", "" Find matching model ⋮---- def analyze existing results results file: Path - None ⋮---- """Analyze existing results file and print insights.""" ⋮---- report = json.load f evaluator = MultiModelClarityEvaluator "", 0 ⋮---- Additional insights ⋮---- accuracies = item "accuracy" for item in report "accuracy ranking" costs = item "total cost" for item in report "accuracy ranking" best accuracy = max accuracies lowest cost = min costs ⋮---- Find sweet spot good accuracy at reasonable cost sweet spot = None ⋮---- sweet spot = it… 证据：`stateful_swe/run_model_comparison.py`
- **Save the anonymized model back**（source_file）：logger = logging.getLogger name def load washed session file file path: str - Dict str, Any ⋮---- data: Dict str, Any = json.load f ⋮---- def extract sessions for sleeptime washed data: Dict str, Any - List Dict str, Any ⋮---- user sessions = washed data.get "user sessions", sleeptime sessions = ⋮---- sleeptime session = { ⋮---- def anonymize user model profile id: str, usermodeling dir: str - None ⋮---- usermodeling dir expanded = os.path.expanduser usermodeling dir user model path = ⋮---- user model = json.load f ⋮---- Save the anonymized model back ⋮---- def process profile with sleeptime profile file: str, usermodeling dir: str - None ⋮---- """Process a single profile file through sleep… 证据：`stateful_swe/sleeptime_process.py`
- **Base**（source_file）：{% block title %}Trajectory Viewer{% endblock %} .event-card { margin-bottom: 1rem; } .event-content { white-space: pre-wrap; max-height: 400px; overflow-y: auto; font-family: 'Courier New', monospace; font-size: 0.9em; } .conversation-stats { background-color: f8f9fa; border-radius: 0.5rem; padding: 1rem; margin-bottom: 1.5rem; } .navbar-brand { font-weight: bold; } .source-badge { font-size: 0.75em; } .content-expandable { cursor: pointer; } .content-collapsed { max-height: 150px; overflow: hidden; position: relative; } .content-collapsed::after { content: ''; position: absolute; bottom: 0; left: 0; right: 0; height: 30px; background: linear-gradient transparent, white ; } .original-event… 证据：`templates/base.html`
- **Conversation**（source_file）：{% extends "base.html" %} {% block title %}{{ title }} - Conversation {{ conv index + 1 }} - {{ user id }}{% endblock %} {% block content %} Conversation {{ conv index + 1 }}/{{ navigation.total }} {% if user only %} USER ONLY {% endif %} {% if gui only %} GUI FILTERED {% endif %} {{ title }} {% if repository and repository != 'Unknown' %} {{ repository }} {% endif %} {{ conv id }} All Conversations {% if navigation.has prev %} Previous {% endif %} {% if navigation.has next %} Next {% endif %} {% if metadata %} Conversation Metadata {% if is gui == True %} GUI {% elif is gui == False %} API {% endif %} {% if cost 0 %} Cost: ${{ "%.3f" format cost }} {% endif %} {% if tokens.total 0 %} Token… 证据：`templates/conversation.html`
- **Conversations**（source_file）：{% extends "base.html" %} {% block title %}Conversations - {{ user id }}{% endblock %} {% block content %} Conversations for {{ user id }} {% if gui only %} GUI ONLY {% endif %} {% if sort by == 'user messages' %} SORTED BY USER MESSAGES {% endif %} {% if pagination %} {{ pagination.start idx }}-{{ pagination.end idx }} of {{ pagination.total }} conversations {% if total original != pagination.total %} {{ total original }} total {% endif %} {% else %} {{ total conversations }} conversations {% if total original != total conversations %} {{ total original }} total {% endif %} {% endif %} All Conversations GUI Only Sort by Time Sort by User Messages {% if pagination and pagination.total pages… 证据：`templates/conversations.html`
- **Error**（source_file）：{% extends "base.html" %} {% block title %}Error - Trajectory Viewer{% endblock %} {% block content %} Error {{ error }} Go Home {% endblock %} 证据：`templates/error.html`
- **Index**（source_file）：{% extends "base.html" %} {% block title %}Trajectory Viewer - Home{% endblock %} {% block content %} Welcome to Trajectory Viewer View and explore trajectory data for different users. Select a user to view their trajectory data: View Trajectory Available Users Loading... Features: View all conversations for a user, sorted by time Navigate between conversations with keyboard shortcuts Filter to show only user messages View conversation statistics and metadata Expandable/collapsible event content {% endblock %} {% block scripts %} function viewUser { const userInput = document.getElementById 'userInput' ; const userId = userInput.value.trim ; if userId { window.location.href = /user/${encode… 证据：`templates/index.html`
- **Set parent relationship**（source_file）：CLI DISPLAY LEVEL = 25 ⋮---- def configure tom swe logging parent logger name: str = "openhands" - None ⋮---- tom swe modules = parent logger = logging.getLogger parent logger name ⋮---- module logger = logging.getLogger module name ⋮---- logger name = name ⋮---- logger name = f"tom swe.{name}" logger = logging.getLogger logger name Set parent relationship ⋮---- def is openhands logging available - bool ⋮---- """ Check if OpenHands logging is available and configured. Returns: True if OpenHands logger exists and has handlers """ ⋮---- openhands logger = logging.getLogger "openhands" ⋮---- def auto configure logging - None 证据：`tom_swe/logging_config.py`
- **Save full prompt to file for inspection**（source_file）：logger = get tom swe logger name ⋮---- logger = logging.getLogger name OutputType = TypeVar "OutputType", bound=object T = TypeVar "T", bound=BaseModel class OutputParser BaseModel, Generic OutputType ⋮---- def parse self, result: str - OutputType def get format instructions self - str class PydanticOutputParser OutputParser T , Generic T ⋮---- pydantic object: Type T def parse self, result: str - T ⋮---- json result = json repair.loads result ⋮---- validated result: T = self.pydantic object.model validate json ⋮---- parsed result: T = self.pydantic object.model validate json result ⋮---- def split text for embedding text: str, max tokens: int = 8191 - list str ⋮---- safe max tokens = min m… 证据：`tom_swe/utils.py`
- **Load user data**（source_file）：logger = logging.getLogger name def analyze user user file: Path, analyzer: CodeAnalyzer - Dict str, Any ⋮---- Load user data user data = load json user file ⋮---- user id = user data.get "user id", "unknown" ⋮---- Get code snapshots snapshots = user data.get "code snapshots", ⋮---- results = ⋮---- timestamp = snapshot.get "timestamp", "" code = snapshot.get "code", "" ⋮---- analysis = analyzer.analyze code ⋮---- Generate summary summary = generate summary results Compile final results analysis results = { ⋮---- def generate summary results: List Dict str, Any - Dict str, Any ⋮---- """Generate a summary of analysis results. Args: results: List of analysis results. Returns: Dict containing s… 证据：`utils/analyze_users.py`
- **Fall back to regex for invalid Python code**（source_file）：def count lines code: str - int ⋮---- lines = code.strip .split "\n" non empty lines = line for line in lines if line.strip ⋮---- def count functions code: str - int ⋮---- tree = ast.parse code functions = ⋮---- pattern = r"def\s+\w+\s \ " matches = re.findall pattern, code ⋮---- def count classes code: str - int ⋮---- """Count the number of class definitions in code. Args: code: The code to analyze. Returns: Number of class definitions. """ ⋮---- classes = node for node in ast.walk tree if isinstance node, ast.ClassDef ⋮---- Fall back to regex for invalid Python code pattern = r"class\s+\w+" ⋮---- def calculate cyclomatic complexity code: str - int ⋮---- """Calculate the cyclomatic complex… 证据：`utils/code_metrics.py`
- **Combine Events To Trajectory**（source_file）：def initialize conversation memory ⋮---- agent config = AgentConfig prompt dir = "/home/xuhuizhou/OpenHands/openhands/agenthub/codeact agent/prompts" prompt manager = PromptManager prompt dir=prompt dir conversation memory = ConversationMemory agent config, prompt manager ⋮---- def combine events to trajectory events, output dir ⋮---- trajectory = current session = None current conversation = None ⋮---- current session = event ⋮---- current conversation = event ⋮---- output file = os.path.join output dir, "trajectory.json" ⋮---- def main ⋮---- parser = argparse.ArgumentParser ⋮---- args = parser.parse args 证据：`utils/combine_events_to_trajectory.py`
- **Create directory if it doesn't exist**（source_file）：logger = logging.getLogger name def load json file path: Union str, Path - Dict str, Any ⋮---- file path = Path file path ⋮---- data: Dict str, Any = json.load f ⋮---- def save json data: Dict str, Any , file path: Union str, Path - bool ⋮---- """Save data to a JSON file. Args: data: Data to save. file path: Path to the JSON file. Returns: True if successful, False otherwise. """ ⋮---- Create directory if it doesn't exist ⋮---- def get user data files data dir: Union str, Path = "data" - List Path ⋮---- data dir = Path data dir ⋮---- def get analysis files data dir: Union str, Path = "data" - List Path def extract user id file path: Union str, Path - str ⋮---- file name = file path.stem 证据：`utils/data_utils.py`
- **Llm Client**（source_file）：logger = logging.getLogger name class LLMClient ⋮---- def init self, config: Optional Dict str, Any = None - None ⋮---- api key = self.config.get "api key" or os.environ.get "OPENAI API KEY" ⋮---- def generate self, prompt: str - str ⋮---- """Generate text using the language model. Args: prompt: The prompt to send to the model. Returns: Generated text. """ ⋮---- def analyze code self, code: str, task: str - Dict str, Any ⋮---- prompt = self. create analysis prompt code, task response = self.generate prompt ⋮---- result: Dict str, Any = json.loads response ⋮---- def generate openai self, prompt: str - str ⋮---- response = self.client.chat.completions.create content = response.choices 0 .mess… 证据：`utils/llm_client.py`
- **Get list of already downloaded sessions**（source_file）：def pull google cloud data ⋮---- data dir = "./data/sessions" ⋮---- source = "gs://prod-openhands-sessions/sessions" ⋮---- result = subprocess.run available sessions = result.stdout.strip .split "\n" ⋮---- Get list of already downloaded sessions existing sessions = set os.listdir data dir if os.path.exists data dir else set Pull each session that doesn't exist locally ⋮---- session id = session path.strip "/" .split "/" -1 ⋮---- Create a subdirectory for each session session dir = os.path.join data dir, session id ⋮---- Use -r flag for recursive copy and ensure destination is a directory ⋮---- def precise pull csv file, max users=None ⋮---- existing users = set os.listdir data dir if os.pat… 证据：`utils/pull_google_cloud_data.py`
- **Complexity Visualizer**（source_file）：logger = logging.getLogger name def plot complexity over time analyses: List Dict str, Any - None ⋮---- timestamps = complexity values = ⋮---- timestamp str = analysis.get "timestamp", "" complexity = analysis.get "analysis", {} .get "cyclomatic complexity", 1 ⋮---- timestamp = datetime.datetime.fromisoformat timestamp str ⋮---- def plot complexity distribution analyses: List Dict str, Any - None ⋮---- complexity values = ⋮---- def plot function vs class count analyses: List Dict str, Any - None ⋮---- function counts = class counts = ⋮---- analysis data = analysis.get "analysis", {} ⋮---- def save plots to html analyses: List Dict str, Any , output path: str - None ⋮---- html content = f"""… 证据：`visualization/complexity_visualizer.py`
- **Parse the start time**（source_file）：MAX CONTENT LENGTH = 500 MIN CONVERSATION INDEX = 0 MAX CONVERSATION INDEX = 2 MIN COMMAND PARTS = 2 ⋮---- @dataclass class ConversationDisplayConfig ⋮---- conv id: str conv data: Dict str, Any conv index: int total convos: int user only: bool = False def load trajectory data user id: str - Dict str, Dict str, Any ⋮---- data path = Path f"./data/processed data/{user id}.json" ⋮---- return json.load f type: ignore no-any-return ⋮---- """Sort conversations by start time, earliest first.""" conversations = ⋮---- Parse the start time start time = datetime.fromisoformat conv data.get "convo start", "" ⋮---- If timestamp parsing fails, put at the end ⋮---- Sort by start time ⋮---- Return just the… 证据：`visualization/display_trajectory.py`
- **Prepare data for visualization**（source_file）：logger = logging.getLogger name def plot trajectory trajectory data: List Dict str, Any , user id: str - None ⋮---- timestamps = complexity values = function counts = class counts = ⋮---- timestamp = point.get "timestamp", "" analysis = point.get "analysis", {} ⋮---- dt = datetime.datetime.fromisoformat timestamp ⋮---- output dir = Path "data" ⋮---- output path = output dir / f"trajectory {user id}.png" ⋮---- """Create an interactive HTML visualization of code trajectory. Args: trajectory data: List of analysis results with timestamps. user id: ID of the user. Returns: Path to the HTML file. """ ⋮---- Prepare data for visualization vis data = ⋮---- Create HTML file ⋮---- output path = outpu… 证据：`visualization/trajectory_viewer.py`
- **User Behavior Visualizer**（source_file）：logger = logging.getLogger name def analyze user edits original code: str, edited code: str - Dict str, Any ⋮---- original lines = original code.split "\n" edited lines = edited code.split "\n" original count = len original lines edited count = len edited lines lines added = max 0, edited count - original count lines removed = max 0, original count - edited count total lines = max original count, edited count change percentage = modified count = 0 ⋮---- def track user behavior actions: List Dict str, Any - Dict str, Any ⋮---- action types: Dict str, int = {} ⋮---- action type = action.get "type", "unknown" ⋮---- time diffs = ⋮---- prev time = actions i - 1 .get "timestamp", 0 curr time = ac… 证据：`visualization/user_behavior_visualizer.py`
- **Tokenize**（source_file）：MIN TOKEN LENGTH = 2 MIN NGRAM LENGTH = 3 PROGRESS UPDATE INTERVAL = 10 MAX PERCENTAGE = 100 MIN SESSION COUNT = 5 MIN MESSAGE LENGTH = 100 MAX LINE LENGTH = 100 MIN REPO COUNT = 5 def categorize user message content ⋮---- system tags = ⋮---- def load power users data csv path ⋮---- df = pd.read csv csv path ⋮---- def load studio results data csv path ⋮---- """Load studio results data from CSV.""" ⋮---- def get empty stats ⋮---- """Return empty statistics dictionary.""" ⋮---- def process user message event, stats, is gui session ⋮---- category = categorize user message event.get "content", "" ⋮---- def process agent message stats def process session events session data, stats, is gui sessio… 证据：`visualization/user_interaction_analysis.py`
- **Only extract metadata, don't process events**（source_file）：app = Flask name , template folder="../templates" studio metadata cache: Dict str, Dict str, Any = {} conversation metadata cache: Dict str, Dict str, Any = {} individual conversation cache: Dict str, Dict str, Any = {} AGENT SOURCES = {"agent", "assistant"} SYSTEM SOURCES = {"environment", "system"} TARGET USER ID = None def load studio results metadata - Dict str, Dict str, Any ⋮---- metadata path = Path "./data/studio results 20250604 1645.csv" metadata: Dict str, Dict str, Any = {} ⋮---- reader = csv.DictReader f ⋮---- conv id = row.get "conversation id", "" ⋮---- def load conversation metadata only user id: str - Dict str, Dict str, Any ⋮---- """Load only conversation metadata without… 证据：`visualization/web_trajectory_viewer.py`

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

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

- **Overview, Installation and System Architecture**：importance `high`
  - source_paths: README.md, AGENTS.md, CLAUDE.md, pyproject.toml, example.py
- **Core Agent Components (ToM Agent, ToM Module, RAG and Generation)**：importance `high`
  - source_paths: tom_swe/tom_agent.py, tom_swe/tom_module.py, tom_swe/rag_module.py, tom_swe/generation/generate.py, tom_swe/generation/action.py
- **Memory System, Conversation Processing and Data Pipeline**：importance `high`
  - source_paths: tom_swe/memory/__init__.py, tom_swe/memory/store.py, tom_swe/memory/local.py, tom_swe/memory/locations.py, tom_swe/memory/conversation_processor.py
- **OpenHands Integration, Deployment, Analytics and Operations**：importance `high`
  - source_paths: tom_swe/logging_config.py, RELEASE.md, .pre-commit-config.yaml, mypy.ini, stateful_swe/advanced_tom_analytics.py

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

- repo_clone_verified: true
- repo_inspection_verified: true
- repo_commit: `535f45f1639c9a355714140d3243208f177fd5b9`
- inspected_files: `uv.lock`, `pyproject.toml`, `README.md`

宿主 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: 可能修改宿主 AI 配置

- Trigger: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- Host AI rule: 列出会写入的配置文件、目录和卸载/回滚步骤。
- Why it matters: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- Evidence: capability.host_targets | github_repo:1010896499 | https://github.com/OpenHands/ToM-SWE | host_targets=claude
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

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

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

### Constraint 3: 来源证据：Dead link

- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：Dead link
- Why it matters: 可能增加新用户试用和生产接入成本。
- Evidence: community_evidence:github | https://github.com/OpenHands/ToM-SWE/issues/30 | 来源类型 github_issue 暴露的待验证使用条件。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

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

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

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

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

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

### Constraint 7: issue/PR 响应质量未知

- Trigger: issue_or_pr_quality=unknown。
- Host AI rule: 抽样最近 issue/PR，判断是否长期无人处理。
- Why it matters: 用户无法判断遇到问题后是否有人维护。
- Evidence: evidence.maintainer_signals | github_repo:1010896499 | https://github.com/OpenHands/ToM-SWE | issue_or_pr_quality=unknown
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 8: 发布节奏不明确

- Trigger: release_recency=unknown。
- Host AI rule: 确认最近 release/tag 和 README 安装命令是否一致。
- Why it matters: 安装命令和文档可能落后于代码，用户踩坑概率升高。
- Evidence: evidence.maintainer_signals | github_repo:1010896499 | https://github.com/OpenHands/ToM-SWE | release_recency=unknown
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。
