# loopgain - Doramagic AI Context Pack

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

## 充分原则

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

## 给宿主 AI 的使用方式

你正在读取 Doramagic 为 loopgain 编译的 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 loopgain` 证据：`README.md` Claim：`clm_0003` supported 0.86, `clm_0007` supported 0.86, `clm_0008` supported 0.86, `clm_0009` supported 0.86 等
- `/plugin marketplace add loopgain-ai/loopgain-plugin` 证据：`README.md` Claim：`clm_0004` supported 0.86
- `/plugin install loopgain` 证据：`README.md` Claim：`clm_0005` supported 0.86
- `pip install keyring` 证据：`README.md` Claim：`clm_0006` supported 0.86
- `pip install 'loopgain[langgraph]'          # LangGraph` 证据：`README.md` Claim：`clm_0007` supported 0.86
- `pip install 'loopgain[crewai]'             # CrewAI` 证据：`README.md` Claim：`clm_0008` supported 0.86
- `pip install 'loopgain[autogen]'            # AutoGen v0.4+` 证据：`README.md` Claim：`clm_0009` supported 0.86
- `pip install 'loopgain[langchain]'          # LangChain (create_agent / AgentExecutor)` 证据：`README.md` Claim：`clm_0010` supported 0.86
- `pip install 'loopgain[openai-agents]'      # OpenAI Agents SDK` 证据：`README.md` Claim：`clm_0011` supported 0.86
- `pip install 'loopgain[claude-agent-sdk]'   # Anthropic Claude Agent SDK` 证据：`README.md` Claim：`clm_0012` supported 0.86

## 继续前判断卡

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

### 30 秒判断

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

### 现在可以相信

- **适合人群线索：正在使用 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, `clm_0007` supported 0.86, `clm_0008` supported 0.86, `clm_0009` 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`, `examples/README.md`, `examples/_common.py`, `loopgain/telemetry.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_0014` inferred 0.45
- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0015` 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

### 上下文规模

- 文件总数：33
- 重要文件覆盖：32/33
- 证据索引条目：31
- 角色 / Skill 条目：6

### 证据不足时的处理

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

## Prompt Recipes

### 适配判断

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

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

### 安装前体验

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

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

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

## 角色 / Skill 索引

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

- **LoopGain**（project_doc）：An open-source cost controller for AI agent loops. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`
- **LoopGain examples — real Claude loops, baseline vs LoopGain**（project_doc）：LoopGain examples — real Claude loops, baseline vs LoopGain 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/README.md`
- **LoopGain v2 Classifier — Pre-Registration**（project_doc）：LoopGain v2 Classifier — Pre-Registration 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`PROTOCOL_v2_classifier.md`
- **LoopGain v0.2 Classifier — Validation Results**（project_doc）：LoopGain v0.2 Classifier — Validation Results 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`RESULTS_v2_classifier.md`
- **Telemetry in loopgain**（project_doc）：LoopGain has two completely separate telemetry paths. They serve different purposes, are configured differently, and never share data or code. This document is about the second one — anonymous funnel telemetry — and how to control it. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`TELEMETRY.md`
- **Changelog**（project_doc）：All notable changes to the loopgain library are recorded here. The format follows Keep a Changelog https://keepachangelog.com/en/1.1.0/ , and versions follow Semantic Versioning https://semver.org/ . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CHANGELOG.md`

## 证据索引

- 共索引 31 条证据。

- **LoopGain**（documentation）：An open-source cost controller for AI agent loops. 证据：`README.md`
- **LoopGain examples — real Claude loops, baseline vs LoopGain**（documentation）：LoopGain examples — real Claude loops, baseline vs LoopGain 证据：`examples/README.md`
- **License**（source_file）：Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 证据：`LICENSE`
- **LoopGain v2 Classifier — Pre-Registration**（documentation）：LoopGain v2 Classifier — Pre-Registration 证据：`PROTOCOL_v2_classifier.md`
- **LoopGain v0.2 Classifier — Validation Results**（documentation）：LoopGain v0.2 Classifier — Validation Results 证据：`RESULTS_v2_classifier.md`
- **Telemetry in loopgain**（documentation）：LoopGain has two completely separate telemetry paths. They serve different purposes, are configured differently, and never share data or code. This document is about the second one — anonymous funnel telemetry — and how to control it. 证据：`TELEMETRY.md`
- **01 Code Pytest**（source_file）：WORKLOAD ID = "example-01-code-pytest" FIXED CAP = 5 ⋮---- SPEC = """\ ⋮---- TESTS = '''\ ⋮---- def strip code fences text: str - str ⋮---- fence = re.match r"^\s \s $", text, re.DOTALL ⋮---- def run pytest workdir: Path - tuple int, str ⋮---- proc = subprocess.run out = proc.stdout + proc.stderr m = re.search r" \d+ \s+failed", out failures = int m.group 1 if m else 0 ⋮---- failures = 15 collection/import error → worst-case signal ⋮---- def one iteration client, workdir: Path, prev code: str, prev failures: str ⋮---- """Single verify-revise step. Returns failing count, code, pytest output .""" ⋮---- prompt = SPEC ⋮---- prompt = code = strip code fences call claude client, prompt ⋮---- def… 证据：`examples/01_code_pytest.py`
- **02 Json Extract**（source_file）：WORKLOAD ID = "example-02-json-extract" FIXED CAP = 5 ⋮---- BLURB = """\ ⋮---- ISO DATE = re.compile r"^\d{4}-\d{2}-\d{2}$" HTTPS URL = re.compile r"^https?:// ^\s +$" ⋮---- SYSTEM = ⋮---- def validate doc - list str ⋮---- """Return a list of human-readable validation errors. Empty = valid.""" errs: list str = ⋮---- def need key, typ, path="$" ⋮---- v = doc "venue" ⋮---- def parse json text: str ⋮---- fence = re.search r" ", text, re.DOTALL payload = fence.group 1 if fence else text ⋮---- def one iteration client, prev json: str, prev errors: list str ⋮---- """Single extract → validate step. Returns err count, raw json, errors .""" ⋮---- prompt = ⋮---- raw = call claude client, prompt, syst… 证据：`examples/02_json_extract.py`
- **Init**（source_file）：all = 证据：`loopgain/__init__.py`
- **Version**（source_file）：version = "0.6.3" 证据：`loopgain/_version.py`
- **Classifier**（source_file）：INIT = "INIT" FAST CONVERGE = "FAST CONVERGE" CONVERGING = "CONVERGING" STALLING = "STALLING" OSCILLATING = "OSCILLATING" DIVERGING = "DIVERGING" ⋮---- DEFAULT E RATIO FAST = 0.1 ⋮---- DEFAULT E RATIO CONV = 0.5 ⋮---- DEFAULT P SIG = 0.05 ⋮---- DEFAULT DIV MARGIN = 0.10 ⋮---- DEFAULT OSC STD THRESHOLD = 0.30 ⋮---- DEFAULT SLOPE TOL = 0.05 ⋮---- DEFAULT STALL PATIENCE = 3 ⋮---- EPS = 1e-12 ⋮---- @dataclass frozen=True class TrajectoryThresholds ⋮---- e ratio fast: float = DEFAULT E RATIO FAST e ratio conv: float = DEFAULT E RATIO CONV p sig: float = DEFAULT P SIG div margin: float = DEFAULT DIV MARGIN osc std threshold: float = DEFAULT OSC STD THRESHOLD slope tol: float = DEFAULT SLOPE TOL s… 证据：`loopgain/classifier.py`
- **Cli**（source_file）：def print status - None ⋮---- s = Funnel start background=False .status state = "ON" if s "enabled" else "OFF" ⋮---- def handle telemetry args: argparse.Namespace - int ⋮---- def handle doctor args: "argparse.Namespace" - int ⋮---- resolved = resolve telemetry config args.endpoint, args.token ⋮---- lg = LoopGain target error=0.1, max iterations=5 ⋮---- res = lg.result ⋮---- ok = lg.send telemetry ⋮---- def main argv: Optional Sequence str = None - int ⋮---- parser = argparse.ArgumentParser ⋮---- sub = parser.add subparsers dest="command" ⋮---- p tel = sub.add parser grp = p tel.add mutually exclusive group ⋮---- p doc = sub.add parser ⋮---- args = parser.parse args argv 证据：`loopgain/cli.py`
- **Core**（source_file）：DEFAULT FAST CONVERGE = 0.3 DEFAULT CONVERGING = 0.85 DEFAULT STALLING = 0.95 DEFAULT OSCILLATING UPPER = 1.05 ⋮---- DEFAULT MAX ITERATIONS = 50 ⋮---- INIT = "INIT" FAST CONVERGE = "FAST CONVERGE" CONVERGING = "CONVERGING" STALLING = "STALLING" OSCILLATING = "OSCILLATING" DIVERGING = "DIVERGING" TARGET MET = "TARGET MET" MAX ITERATIONS = "MAX ITERATIONS" ⋮---- @dataclass frozen=True class ThresholdBands ⋮---- fast converge: float = DEFAULT FAST CONVERGE converging: float = DEFAULT CONVERGING stalling: float = DEFAULT STALLING oscillating upper: float = DEFAULT OSCILLATING UPPER ⋮---- def state for self, ab smooth: float - str ⋮---- @dataclass class LoopGainResult ⋮---- outcome: str ⋮---- it… 证据：`loopgain/core.py`
- **Map terminal LoopGain state names to the coarse outcome buckets we count.**（source_file）：FUNNEL SCHEMA VERSION = 1 ⋮---- DEFAULT FUNNEL ENDPOINT = "https://telemetry.loopgain.ai/v1/funnel" ⋮---- TRUE = frozenset {"1", "true", "yes", "on", "enable", "enabled"} FALSE = frozenset {"0", "false", "no", "off", "disable", "disabled", ""} ⋮---- Map terminal LoopGain state names to the coarse outcome buckets we count. Anything unrecognized is bucketed as "other" so the distribution stays small ⋮---- STATE TO OUTCOME = { ⋮---- DISABLED = "disabled" UNDECIDED = "undecided" ENABLED = "enabled" ⋮---- NOTICE = ⋮---- def now hour clock: Callable , datetime - str ⋮---- class NoRedirectHandler urllib.request.HTTPRedirectHandler ⋮---- def http error 301 self, req, fp, code, msg, headers ⋮---- ht… 证据：`loopgain/funnel.py`
- **Library version sourced from loopgain. version so there's exactly one**（source_file）：def safe float x: Any - Any ⋮---- class NoRedirectHandler urllib.request.HTTPRedirectHandler ⋮---- def http error 301 self, req, fp, code, msg, headers ⋮---- http error 302 = http error 301 http error 303 = http error 301 http error 307 = http error 301 http error 308 = http error 301 ⋮---- NO REDIRECT OPENER = urllib.request.build opener NoRedirectHandler ⋮---- def open request req: urllib.request.Request, timeout: float - Any ⋮---- SCHEMA VERSION = 4 ⋮---- AGGREGATE PATH = "/v1/aggregate" ⋮---- ENDPOINT ENV = "LOOPGAIN TELEMETRY ENDPOINT" TOKEN ENV = "LOOPGAIN TELEMETRY TOKEN" ⋮---- ep = endpoint or os.environ.get ENDPOINT ENV or "" .strip tok = token or os.environ.get TOKEN ENV or "" .st… 证据：`loopgain/telemetry.py`
- **Init**（source_file）：all = ⋮---- def getattr name: str 证据：`loopgain/integrations/__init__.py`
- **Autogen**（source_file）：AsyncMessageErrorFn = Callable Any , Awaitable Optional float MessageErrorFn = Callable Any , Optional float ⋮---- class AutoGenAdapter ⋮---- framework name = "autogen" ⋮---- out: List Any = ⋮---- kwargs: dict str, Any = {"task": task} ⋮---- we cancelled = False iterator = team.run stream kwargs . aiter ⋮---- message = await iterator. anext ⋮---- source = getattr message, "source", None ⋮---- magnitude = self.error fn message ⋮---- magnitude = await magnitude ⋮---- cancel = getattr cancellation token, "cancel", None ⋮---- we cancelled = True 证据：`loopgain/integrations/autogen.py`
- **Crewai**（source_file）：CrewStepFn = Callable Any , Optional float CrewTaskFn = Callable Any , Optional float ⋮---- class CrewAIAdapter ⋮---- framework name = "crewai" ⋮---- def install self, crew: Any - None ⋮---- existing = getattr crew, "step callback" ⋮---- existing = getattr crew, "task callback" ⋮---- def uninstall self - None ⋮---- def enter self ⋮---- def exit self, exc info - None ⋮---- def on step self, step: Any - None ⋮---- magnitude = self.step error fn step ⋮---- def on task self, task output: Any - None ⋮---- magnitude = self.task error fn task output ⋮---- @staticmethod def chain existing: Optional Callable Any , None , ours: Callable Any , None - Callable Any , None ⋮---- def chained item: Any - N… 证据：`loopgain/integrations/crewai.py`
- **Langchain**（source_file）：ErrorFn = Callable Any , Optional float AsyncErrorFn = Callable Any , Awaitable Optional float ⋮---- class LangChainAdapter ⋮---- framework name = "langchain" ⋮---- last: Any = None ⋮---- last = item ⋮---- iterator = agent.stream input, stream kwargs ⋮---- magnitude = self.error fn item ⋮---- iterator = agent.astream input, stream kwargs ⋮---- magnitude: Optional float ⋮---- magnitude = await error fn item 证据：`loopgain/integrations/langchain.py`
- **Langgraph**（source_file）：ErrorFn = Callable Any , Optional float AsyncErrorFn = Callable Any , Awaitable Optional float ⋮---- class LangGraphAdapter ⋮---- framework name = "langgraph" ⋮---- last: Any = None ⋮---- last = item ⋮---- iterator = graph.stream ⋮---- magnitude = self.error fn item ⋮---- iterator = graph.astream ⋮---- magnitude: Optional float ⋮---- magnitude = await error fn item 证据：`loopgain/integrations/langgraph.py`
- **Openai Agents**（source_file）：EventErrorFn = Callable Any , Optional float AsyncEventErrorFn = Callable Any , Awaitable Optional float ⋮---- DEFAULT OBSERVE EVENT TYPES = frozenset {"run item stream event"} ⋮---- class OpenAIAgentsAdapter ⋮---- framework name = "openai-agents" ⋮---- result = Runner.run streamed agent, input, run kwargs ⋮---- async def drive self, result: Any - AsyncIterator Any ⋮---- cancelled = False ⋮---- event type = getattr event, "type", None ⋮---- magnitude = self.error fn event ⋮---- magnitude = await magnitude ⋮---- cancel = getattr result, "cancel", None ⋮---- cancelled = True 证据：`loopgain/integrations/openai_agents.py`
- **Changelog**（documentation）：All notable changes to the loopgain library are recorded here. The format follows Keep a Changelog https://keepachangelog.com/en/1.1.0/ , and versions follow Semantic Versioning https://semver.org/ . 证据：`CHANGELOG.md`
- **Virtualenv**（source_file）：pycache / .py cod $py.class .so .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ .egg-info/ .installed.cfg .egg 证据：`.gitignore`
- **LoopGain developer Makefile.**（source_file）：LoopGain developer Makefile. Targets here are for manual invocation by the maintainer. There is no CI integration for examples — running them costs real Anthropic API spend, so they should only fire when a human asks. 证据：`Makefile`
- **03 Essay Critique**（source_file）：WORKLOAD ID = "example-03-essay-critique" FIXED CAP = 6 ⋮---- TOPIC = ⋮---- JUDGE SYSTEM = ⋮---- def parse scores text: str ⋮---- fence = re.search r" ", text, re.DOTALL payload = fence.group 1 if fence else text ⋮---- d = json.loads payload ⋮---- keys = "clarity", "accuracy", "concision", "prose" ⋮---- def error from scores scores - float ⋮---- def one iteration client, prev essay: str, prev scores ⋮---- draft prompt = TOPIC ⋮---- crit = draft prompt = essay = call claude client, draft prompt, max tokens=400 ⋮---- judge reply = call claude scores = parse scores judge reply ⋮---- def baseline run client ⋮---- """No LoopGain: run FIXED CAP iterations unconditionally.""" ⋮---- avg = 10.0 - er… 证据：`examples/03_essay_critique.py`
- **04 Sql Synth**（source_file）：WORKLOAD ID = "example-04-sql-synth" FIXED CAP = 5 ⋮---- SCHEMA = """\ ⋮---- QUESTION = ⋮---- EXPECTED = ⋮---- def extract sql text: str - str ⋮---- fence = re.search r" ", text, re.DOTALL ⋮---- def run query conn: sqlite3.Connection, sql: str ⋮---- rows = conn.execute sql .fetchall ⋮---- got = tuple r for r in rows diff = set got .symmetric difference set EXPECTED ⋮---- def one iteration client, conn, prev sql: str, prev msg: str ⋮---- prompt = ⋮---- sql = extract sql call claude client, prompt ⋮---- def baseline run client, conn ⋮---- def loopgain run client, conn ⋮---- lg = LoopGain target error=0, max iterations=FIXED CAP ⋮---- first line = sql.splitlines 0 if sql else " no sql " previe… 证据：`examples/04_sql_synth.py`
- **Tokens forbidden by constraint a — these are exactly the coroutine**（source_file）：WORKLOAD ID = "example-05-unsolvable-stalls" FIXED CAP = 10 ⋮---- STARTER = '''\ ⋮---- SPEC = ⋮---- Tokens forbidden by constraint a — these are exactly the coroutine drivers that constraint c requires, so satisfying both is impossible. DRIVERS = DRIVER RE = re.compile " ".join DRIVERS ⋮---- def strip fences text: str - str ⋮---- m = re.match r"^\s \s $", text, re.DOTALL ⋮---- def evaluate code: str ⋮---- """Return error, reason . 0 is unreachable by construction. The spec is impossible, so every attempt fails at least one constraint and the error sits at 1 — the loop makes no forward progress no matter how many times it revises. A fixed cap keeps paying for that; LoopGain reads the flat tr… 证据：`examples/05_unsolvable_stalls.py`
- **06 Diverges**（source_file）：WORKLOAD ID = "example-06-diverges" FIXED CAP = 8 ⋮---- PASSAGE = ⋮---- FACTS = ⋮---- def count missing text: str ⋮---- lower = text or "" .lower missing = f for f in FACTS if f.lower not in lower ⋮---- def one iteration client, prev text: str, iteration: int ⋮---- prompt = ⋮---- revised = call claude client, prompt, max tokens=400 ⋮---- def baseline run client ⋮---- current = PASSAGE err = 0 ⋮---- wc = len current.split ⋮---- def loopgain run client ⋮---- lg = LoopGain target error=None, max iterations=FIXED CAP ⋮---- iteration = 0 ⋮---- preview = f"{wc}w; missing={err}/{len FACTS }: {missing :2 }" state = lg.observe err, output=current ⋮---- def main - None ⋮---- client = get client ⋮----… 证据：`examples/06_diverges.py`
- **07 Agentic Multistep**（source_file）：WORKLOAD ID = "example-07-agentic-multistep" FIXED CAP = 5 ⋮---- PANTRY = { ALLOWED TECHNIQUES = {"searing", "braising", "roasting", "poaching"} GOAL = { ⋮---- SYSTEM = ⋮---- def render prompt prev plan: str, prev errors: list str - str ⋮---- pantry lines = "\n".join base = ⋮---- def parse plan text: str ⋮---- fence = re.search r" ", text, re.DOTALL payload = fence.group 1 if fence else text ⋮---- def verify plan - list str ⋮---- """Return the list of unmet constraints. Empty list = goal achieved.""" errs: list str = ⋮---- ings = plan.get "ingredients" ⋮---- ings = bad names = i.get "name" for i in ings if i.get "name" not in PANTRY ⋮---- n ings = len ings ⋮---- cost = 0.0 ⋮---- info = PANT… 证据：`examples/07_agentic_multistep.py`
- **Common**（source_file）：DEFAULT MODEL = os.environ.get "LOOPGAIN EXAMPLE MODEL", "claude-haiku-4-5" DEFAULT ENDPOINT = "https://telemetry.loopgain.ai/v1/aggregate" ⋮---- def get client ⋮---- kwargs = { ⋮---- msg = client.messages.create kwargs parts = b.text for b in msg.content if getattr b, "type", None == "text" ⋮---- def send telemetry lg, , workload id: str, loop type: str - None ⋮---- """POST aggregate telemetry to the receiver. No-op if token is unset.""" token = os.environ.get "LOOPGAIN TELEMETRY TOKEN" endpoint = os.environ.get "LOOPGAIN TELEMETRY ENDPOINT", DEFAULT ENDPOINT ⋮---- ok = lg.send telemetry ⋮---- def print iteration i: int, error: float, state: str, preview: str = "" - None ⋮---- """One-line… 证据：`examples/_common.py`
- **Single source of truth: loopgain/ version.py read dynamically below .**（source_file）：build-system requires = "setuptools =61.0" build-backend = "setuptools.build meta" 证据：`pyproject.toml`

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

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

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

- 你准备在哪个宿主 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。

- **概述与核心 API**：importance `high`
  - source_paths: loopgain/core.py, loopgain/__init__.py, README.md, examples/01_code_pytest.py, examples/02_json_extract.py
- **决策引擎与轨迹分类器**：importance `high`
  - source_paths: loopgain/classifier.py, PROTOCOL_v2_classifier.md, RESULTS_v2_classifier.md, loopgain/core.py
- **框架集成适配器**：importance `high`
  - source_paths: loopgain/integrations/__init__.py, loopgain/integrations/langgraph.py, loopgain/integrations/crewai.py, loopgain/integrations/autogen.py, loopgain/integrations/langchain.py
- **遥测系统、CLI 与已知问题**：importance `high`
  - source_paths: loopgain/telemetry.py, loopgain/funnel.py, loopgain/cli.py, loopgain/__main__.py, loopgain/_version.py

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

- repo_clone_verified: true
- repo_inspection_verified: true
- repo_commit: `2ee73af917c72c211d1744bad5aa81b12f83c88b`
- inspected_files: `README.md`, `pyproject.toml`, `examples/01_code_pytest.py`, `examples/02_json_extract.py`, `examples/03_essay_critique.py`, `examples/04_sql_synth.py`, `examples/05_unsolvable_stalls.py`, `examples/06_diverges.py`, `examples/07_agentic_multistep.py`, `examples/README.md`, `examples/_common.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: 可能修改宿主 AI 配置

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

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

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

### Constraint 3: 来源证据：note_outcome() and note_adapter() silently fail when called before on_init() due to uninitialized _mode

- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：note_outcome() and note_adapter() silently fail when called before on_init() due to uninitialized _mode
- Why it matters: 可能增加新用户试用和生产接入成本。
- Evidence: community_evidence:github | https://github.com/loopgain-ai/loopgain/issues/1 | 来源讨论提到 python 相关条件，需在安装/试用前复核。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

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

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

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

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

- Trigger: no_demo
- Why it matters: 风险会影响是否适合普通用户安装。
- Evidence: risks.scoring_risks | https://news.ycombinator.com/item?id=48919562 | 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 | https://news.ycombinator.com/item?id=48919562 | 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 | https://news.ycombinator.com/item?id=48919562 | release_recency=unknown
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。
