# qmd - Doramagic AI Context Pack

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

## 充分原则

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

## 给宿主 AI 的使用方式

你正在读取 Doramagic 为 qmd 编译的 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_0004` supported 0.86
- **希望把专业流程带进宿主 AI 的用户**：仓库包含 Skill 文档。 证据：`skills/qmd/SKILL.md`, `skills/release/SKILL.md` Claim：`clm_0005` supported 0.86

## 它能做什么

- **AI Skill / Agent 指令资产库**（可做安装前预览）：项目包含可被宿主 AI 读取的 Skill 或 Agent 指令文件，可用于把专业流程带入 Claude、Codex、Cursor 等宿主。 证据：`skills/qmd/SKILL.md`, `skills/release/SKILL.md` Claim：`clm_0001` supported 0.86
- **多宿主安装与分发**（需要安装后验证）：项目包含插件或 marketplace 配置，说明它面向一个或多个 AI 宿主的安装和分发。 证据：`.claude-plugin/marketplace.json` Claim：`clm_0002` supported 0.86
- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`CLAUDE.md`, `README.md` Claim：`clm_0003` supported 0.86

## 怎么开始

- `npm install -g @tobilu/qmd` 证据：`README.md` Claim：`clm_0006` supported 0.86
- `npx @tobilu/qmd ...` 证据：`README.md` Claim：`clm_0007` supported 0.86
- `npm install @tobilu/qmd` 证据：`README.md` Claim：`clm_0008` supported 0.86
- `git clone https://github.com/tobi/qmd` 证据：`README.md` Claim：`clm_0009` supported 0.86
- `npx vitest run --reporter=verbose test/` 证据：`CLAUDE.md` Claim：`clm_0010` supported 0.86

## 继续前判断卡

- **当前建议**：仅建议沙盒试装
- **为什么**：项目存在安装命令、宿主配置或本地写入线索，不建议直接进入主力环境，应先在隔离环境试装。

### 30 秒判断

- **现在怎么做**：仅建议沙盒试装
- **最小安全下一步**：先跑 Prompt Preview；若仍要安装，只在隔离环境试装
- **先别相信**：真实输出质量不能在安装前相信。
- **继续会触碰**：命令执行、宿主 AI 配置、本地环境或项目文件

### 现在可以相信

- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0004` supported 0.86
- **适合人群线索：希望把专业流程带进宿主 AI 的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`skills/qmd/SKILL.md`, `skills/release/SKILL.md` Claim：`clm_0005` supported 0.86
- **能力存在：AI Skill / Agent 指令资产库**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`skills/qmd/SKILL.md`, `skills/release/SKILL.md` Claim：`clm_0001` supported 0.86
- **能力存在：多宿主安装与分发**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`.claude-plugin/marketplace.json` Claim：`clm_0002` supported 0.86
- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`CLAUDE.md`, `README.md` Claim：`clm_0003` supported 0.86
- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0006` supported 0.86

### 现在还不能相信

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

### 继续会触碰什么

- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`CLAUDE.md`, `README.md`
- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`.claude-plugin/marketplace.json`, `CLAUDE.md`, `skills/qmd/SKILL.md`, `skills/release/SKILL.md`
- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`.claude-plugin/marketplace.json`, `CLAUDE.md`, `README.md`
- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。

### 最小安全下一步

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

### 退出方式

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

## 哪些只能预览

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

## 哪些必须安装后验证

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

## 边界与风险判断卡

- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0011` inferred 0.45
- **宿主 AI 插件或 Skill 规则冲突**：新规则可能改变用户现有宿主 AI 的工作方式。 处理方式：安装前先检查插件 manifest 和 Skill 文件，必要时隔离测试。 证据：`.claude-plugin/marketplace.json` Claim：`clm_0012` supported 0.86
- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`CLAUDE.md`, `README.md` Claim：`clm_0013` 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。

### 任务路由

- **AI Skill / Agent 指令资产库**：先基于 role_skill_index / evidence_index 帮用户挑选可用角色、Skill 或工作流。 边界：可做安装前 Prompt 体验。 证据：`skills/qmd/SKILL.md`, `skills/release/SKILL.md` Claim：`clm_0001` supported 0.86
- **多宿主安装与分发**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`.claude-plugin/marketplace.json` Claim：`clm_0002` supported 0.86
- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`CLAUDE.md`, `README.md` Claim：`clm_0003` supported 0.86

### 上下文规模

- 文件总数：138
- 重要文件覆盖：40/138
- 证据索引条目：79
- 角色 / Skill 条目：2

### 证据不足时的处理

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

## Prompt Recipes

### 适配判断

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

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

### 安装前体验

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

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

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

## 角色 / Skill 索引

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

- **qmd**（skill）：Search local markdown knowledge bases, notes, docs, and wikis with QMD. Use when users ask to find notes, retrieve documents, inspect a wiki, answer from indexed markdown, or set up QMD access. 激活提示：当用户任务与“qmd”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`skills/qmd/SKILL.md`
- **release**（skill）：Manage releases for this project. Validates changelog, installs git hooks, and cuts releases. Use when user says "/release", "release 1.0.5", "cut a release", or asks about the release process. NOT auto-invoked by the model. 激活提示：当用户任务与“release”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`skills/release/SKILL.md`

## 证据索引

- 共索引 79 条证据。

- **QMD - Query Markup Documents**（documentation）：An on-device search engine for everything you need to remember. Index your markdown notes, meeting transcripts, documentation, and knowledge bases. Search with keywords or natural language. Ideal for your agentic flows. 证据：`README.md`
- **QMD Query Expansion Fine-Tuning**（documentation）：Train small language models to expand search queries for QMD https://github.com/tobi/qmd 's hybrid retrieval pipeline. 证据：`finetune/README.md`
- **GRPO Experimental**（documentation）：This folder contains the experimental GRPO training path for query expansion. It is not part of the default production pipeline. 证据：`finetune/experiments/grpo/README.md`
- **Package**（package_manifest）：{ "name": "@tobilu/qmd", "version": "2.5.3", "description": "Query Markup Documents - On-device hybrid search for markdown files with BM25, vector search, and LLM reranking", "type": "module", "main": "dist/index.js", "types": "dist/index.d.ts", "exports": { ".": { "import": "./dist/index.js", "types": "./dist/index.d.ts" } }, "bin": { "qmd": "bin/qmd" }, "files": "bin/", "dist/", "skills/", "scripts/build.mjs", "scripts/check-package-grammars.mjs", "scripts/package-smoke.mjs", "scripts/test-all.mjs", "LICENSE", "CHANGELOG.md" , "scripts": { "prepare": " -d .git && ./scripts/install-hooks.sh true", "build": "node scripts/build.mjs", "test": "node scripts/test-all.mjs", "test:types": "node .… 证据：`package.json`
- **QMD - Query Markup Documents**（documentation）：Use Bun instead of Node.js bun not node , bun install not npm install . 证据：`CLAUDE.md`
- **QMD Query Expansion Fine-Tuning**（documentation）：Train Qwen3-1.7B to expand search queries into structured hyde:/lex:/vec: output for QMD's hybrid retrieval pipeline. 证据：`finetune/CLAUDE.md`
- **QMD - Query Markdown Documents**（skill_instruction）：QMD searches local markdown collections: notes, docs, wikis, transcripts, and project knowledge bases. Use it before web search when the answer may already be in indexed local files. 证据：`skills/qmd/SKILL.md`
- **Release**（skill_instruction）：Cut a release, validate the changelog, and ensure git hooks are installed. 证据：`skills/release/SKILL.md`
- **Marketplace**（structured_config）：{ "name": "qmd", "owner": { "name": "tobi", "email": "tobi@lutke.com" }, "plugins": { "name": "qmd", "source": "./", "description": "Search and retrieve documents from local markdown files.", "version": "0.1.0", "author": { "name": "tobi", "email": "tobi@lutke.com" }, "repository": "https://github.com/tobi/qmd", "license": "MIT", "keywords": "markdown", "search", "qmd" , "skills": "./skills/" , "mcpServers": { "qmd": { "command": "qmd", "args": "mcp" } } } } 证据：`.claude-plugin/marketplace.json`
- **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`
- **QMD Query Syntax**（documentation）：QMD queries are structured documents with typed sub-queries. Each line specifies a search type and query text. 证据：`docs/SYNTAX.md`
- **!/usr/bin/env node**（source_file）：!/usr/bin/env node // 2 /dev/null; if command -v node /dev/null 2 &1; then exec node "$0" "$@"; else exec bun "$0" "$@"; fi // Cross-platform launcher for qmd. // // Previously this was a POSIX shell script with !/bin/sh , which meant npm // on Windows generated shims that tried to route through /bin/sh — a path // that doesn't exist on Windows, so qmd failed immediately after a global // install. Rewriting the launcher in Node.js lets npm generate native // cmd/ps1/sh shims that invoke node directly on every platform. 证据：`bin/qmd`
- **Index**（source_file）：import { createStore as createStoreInternal, hybridQuery, structuredSearch, extractSnippet, addLineNumbers, DEFAULT MULTI GET MAX BYTES, reindexCollection, generateEmbeddings, listCollections as storeListCollections, syncConfigToDb, getStoreCollections, getStoreCollection, getStoreGlobalContext, getStoreContexts, upsertStoreCollection, deleteStoreCollection, renameStoreCollection, updateStoreContext, removeStoreContext, setStoreGlobalContext, vacuumDatabase, cleanupOrphanedContent, cleanupOrphanedVectors, deleteLLMCache, deleteInactiveDocuments, clearAllEmbeddings, type Store as InternalStore, type DocumentResult, type DocumentNotFound, type SearchResult, type HybridQueryResult, type Hybrid… 证据：`src/index.ts`
- **Bench**（source_file）：import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { createStore, getDefaultDbPath, type QMDStore, type SearchResult, type HybridQueryResult, type ExpandedQuery, } from "../index.js"; import { scoreResults } from "./score.js"; import type { BenchmarkFixture, BenchmarkQuery, BackendResult, QueryResult, BenchmarkResult, } from "./types.js"; type Backend = { name: string; run: store: QMDStore, query: BenchmarkQuery, limit: number, collection?: string = Promise ; }; type ParsedStructuredQuery = { searches: ExpandedQuery ; intent?: string; }; function parseStructuredQuery query: string : ParsedStructuredQuery undefined function uniqueFiles files: string , limit:… 证据：`src/bench/bench.ts`
- **Score**（source_file）：export function normalizePath p: string : string export function pathsMatch result: string, expected: string : boolean type ScoreMetrics = { precision at k: number; recall: number; recall at 1: number; recall at 3: number; recall at 5: number; mrr: number; f1: number; hits at k: number; matched files: string ; unmatched expected files: string ; }; function hitsWithin resultFiles: string , expectedFiles: string , k: number : number export function scoreResults resultFiles: string , expectedFiles: string , topK: number, : ScoreMetrics 证据：`src/bench/score.ts`
- **Types**（source_file）：export interface BenchmarkQuery { id: string; query: string; type: "exact" "semantic" "topical" "cross-domain" "alias"; description: string; expected files: string ; expected in top k: number; } export interface BenchmarkFixture { description: string; version: number; collection?: string; queries: BenchmarkQuery ; } export interface BackendResult { precision at k: number; recall: number; recall at 1: number; recall at 3: number; recall at 5: number; mrr: number; f1: number; hits at k: number; total expected: number; latency ms: number; top files: string ; matched files: string ; unmatched expected files: string ; } export interface QueryResult { id: string; query: string; type: string; back… 证据：`src/bench/types.ts`
- **Formatter**（source_file）：import { extractSnippet } from "../store.js"; import type { SearchResult, MultiGetResult, DocumentResult } from "../store.js"; ⋮---- export type MultiGetFile = { filepath: string; displayPath: string; title: string; body: string; context?: string null; skipped: false; } { filepath: string; displayPath: string; title: string; body: string; context?: string null; skipped: true; skipReason: string; }; export type OutputFormat = "cli" "csv" "md" "xml" "files" "json"; export type FormatOptions = { full?: boolean; query?: string; useColor?: boolean; lineNumbers?: boolean; intent?: string; }; export function addLineNumbers text: string, startLine: number = 1 : string export function getDocid hash:… 证据：`src/cli/formatter.ts`
- **Qmd**（source_file）：import { isBun, openDatabase } from "../db.js"; import type { Database, SQLiteValue } from "../db.js"; import fastGlob from "fast-glob"; import { execSync, spawn as nodeSpawn } from "child process"; import { fileURLToPath } from "url"; import { basename, dirname, join as pathJoin, relative as relativePath, resolve as pathResolve } from "path"; import { parseArgs } from "util"; import { readFileSync, readdirSync, realpathSync, statSync, existsSync, unlinkSync, writeFileSync, openSync, closeSync, mkdirSync, lstatSync, rmSync, symlinkSync, readlinkSync, copyFileSync } from "fs"; import { createInterface } from "readline/promises"; import { getPwd, getRealPath, homedir, resolve, enableProductio… 证据：`src/cli/qmd.ts`
- **Server**（source_file）：import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; import { randomUUID } from "node:crypto"; import { readFileSync } from "node:fs"; import { join, dirname } from "node:path"; import { fileURLToPath } from "url"; import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { WebStandardStreamableHTTPServerTransport } ⋮---- import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; import { existsSync } from "fs"; import { createStore, extractSnippet, addLineNumbers, getDefaultDbPath, DEFAULT MULTI GET MAX… 证据：`src/mcp/server.ts`
- **Changelog**（documentation）：- README: documented collection filtering -c semantics , the collection show / include / exclude / update-cmd subcommands, the --intent / --no-rerank / -C / --full-path search flags, the --format output selector with the legacy --json / --csv / --md / --xml / --files booleans noted as aliases , vector-search / deep-search aliases, embed memory flags --max-docs-per-batch / --max-batch-mb , a sample --explain score trace, the qmd doctor / qmd init commands, the get :from:count suffix and --no-line-numbers , an MCP tool parameter reference, and a Benchmarking section for qmd bench . - docs/SYNTAX.md: removed the non-existent q MCP parameter example the query tool and REST endpoint accept only… 证据：`CHANGELOG.md`
- **QMD Query Expansion Scoring**（documentation）：Transform a random typed query into a great set of retrieval-optimized expansions. 证据：`finetune/SCORING.md`
- **QMD MCP Server Setup**（documentation）：Claude Code ~/.claude/settings.json : 证据：`skills/qmd/references/mcp-setup.md`
- **Settings**（structured_config）：{ "skills": "skills" } 证据：`.pi/settings.json`
- **Tsconfig.Build**（structured_config）：{ "extends": "./tsconfig.json", "compilerOptions": { "noEmit": false, "outDir": "dist", "declaration": true, "noImplicitAny": true }, "include": "src/ / .ts" , "exclude": "src/ / .test.ts", "src/test-preload.ts", "src/bench- .ts" } 证据：`tsconfig.build.json`
- **Tsconfig**（structured_config）：{ "compilerOptions": { // Environment setup & latest features "lib": "ESNext" , "target": "ESNext", "module": "nodenext", "moduleDetection": "force", "jsx": "react-jsx", "allowJs": true, 证据：`tsconfig.json`
- **Fix Hyde Checkpoint**（structured_config）：{"processed queries": {"1000": "Capitals quiz: Paris France , Tokyo Japan , Canberra Australia , Bras\u00edlia Brazil , Ottawa Canada . Quiz includes 50+ capitals.", "1001": "Trivia: The universe is 13.8 billion years old. There are an estimated 100 billion galaxies. The Milky Way is about 100,000 light-years wide.", "1002": "Did you know? The Great Wall of China is over 13,000 miles long. Cleopatra lived closer to the moon landing than the building of the pyramids.", "1003": "Science fact: Water can boil and freeze at the same time at 0.01\u00b0C. This phenomenon is called the triple point of water.", "1004": "Famous inventions timeline: 1440 - Printing Press by Gutenberg, 1876 - Telephone… 证据：`finetune/data/fix_hyde_checkpoint.json`
- **Model**（structured_config）：{ "name": "qmd-gepa-example-generator", "model": "grok-4-1-fast-reasoning", "schema version": 1, "prompt": "You are a query expansion expert. Given a user query, output a single JSON object that matches the training JSONL schema:\n{\"query\": \"...\", \"output\": \"lex\", \"...\" , \"vec\", \"...\" , \"hyde\", \"...\" }\nRules:\n- output is a list of pairs, where the first element is one of: \"lex\", \"vec\", \"hyde\".\n- Include 2-3 lex lines, 2-3 vec lines, and 0-1 hyde line.\n- lex lines are short keyword phrases; never equal or near-echo the query.\n- vec lines are natural language search phrases.\n- hyde is a concise hypothetical passage 50-200 chars , single line.\n- Preserve key term… 证据：`finetune/experiments/gepa/model.json`
- **Example**（structured_config）：{ "description": "Example benchmark fixture for QMD eval-docs. Tests exact keyword, semantic, and cross-domain retrieval across 6 documents.", "version": 1, "collection": "eval-docs", "queries": { "id": "exact-api", "query": "API versioning", "type": "exact", "description": "Direct keyword match in API design document", "expected files": "api-design-principles.md" , "expected in top k": 1 }, { "id": "exact-fundraising", "query": "Series A fundraising", "type": "exact", "description": "Direct keyword match in fundraising memo", "expected files": "startup-fundraising-memo.md" , "expected in top k": 1 }, { "id": "exact-cap", "query": "CAP theorem", "type": "exact", "description": "Direct keywo… 证据：`src/bench/fixtures/example.json`
- **Use bd merge for beads JSONL files**（source_file）：Use bd merge for beads JSONL files .beads/issues.jsonl merge=beads 证据：`.gitattributes`
- **.gitignore**（source_file）：node modules/ dist/ package-lock.json .npmrc .sqlite .DS Store archive/ texts/ .cursor/ .github/copilot/ .md !README.md !CLAUDE.md !CHANGELOG.md !skills/ / .md !finetune/ .md !docs/ .md finetune/outputs/ finetune/data/train/ .claude/ 证据：`.gitignore`
- **Example Index**（source_file）：global context: "If you see a relevant WikiWord , you can search for that WikiWord to get more context." collections: Meetings: path: ~/Documents/Meetings pattern: " / .md" context: "/": "Meeting notes and summaries" journals: path: ~/Documents/Notes pattern: " / .md" context: "/journal/2024": "Daily notes from 2024" "/journal/2025": "Daily notes from 2025" "/": "Notes vault" codex: path: ~/Documents/Codex pattern: " / .md" context: "/": "Thematic collections of important concepts and discussions" 证据：`example-index.yml`
- **Training outputs run eval before pushing to HuggingFace**（source_file）：Training outputs run eval before pushing to HuggingFace outputs/ 证据：`finetune/.gitignore`
- **Experimental GRPO training is in finetune/experiments/grpo and not part of**（source_file）：validate: uv run dataset/validate schema.py uv run dataset/score data.py for f in data/ .jsonl; do \ uv run dataset/analyze data.py --input "$f" --show-examples 0; \ done 证据：`finetune/Justfile`
- **Modelfile**（source_file）：FROM /home/tobi/src/github.com/tobi/qmd/finetune/outputs/sft/gguf/sft-q4 k m.gguf 证据：`finetune/Modelfile`
- **Bonus for hyde length in sweet spot 80-200 chars**（source_file）：QUERIES = def load model base name, adapter dir, device, trust remote=False ⋮---- tokenizer = AutoTokenizer.from pretrained base name, trust remote code=trust remote base = AutoModelForCausalLM.from pretrained model = PeftModel.from pretrained base, adapter dir, local files only=True model = model.merge and unload ⋮---- gen config path = Path adapter dir / "generation config.json" ⋮---- gen config = GenerationConfig.from pretrained adapter dir ⋮---- gen config = GenerationConfig ⋮---- def run inference model, tokenizer, gen config, query, device ⋮---- messages = {"role": "user", "content": f"Expand this search query: {query}"} text = tokenizer.apply chat template messages, add generation pr… 证据：`finetune/benchmark.py`
- **Install build tools for Colab/cloud environments**（source_file）：PRESETS = { def run cmd cmd, description def main ⋮---- parser = argparse.ArgumentParser description="Convert QMD model to GGUF" ⋮---- args = parser.parse args ⋮---- preset = PRESETS args.size base model = args.base or preset "base" sft model = args.sft or preset "sft" grpo model = args.grpo or preset "grpo" output repo = args.output or preset "output" ⋮---- base model = args.base sft model = args.sft grpo model = args.grpo output repo = args.output ⋮---- model name = output repo.split "/" -1 .replace "-gguf", "" ⋮---- Install build tools for Colab/cloud environments ⋮---- hf token = os.environ.get "HF TOKEN" ⋮---- model = AutoModelForCausalLM.from pretrained ⋮---- model = PeftModel.from pr… 证据：`finetune/convert_gguf.py`
- **Save merged model to temp dir first Optimum needs HF format on disk**（source_file）：PRESETS = { def merge adapters base model: str, sft model: str, grpo model: str - tuple ⋮---- model = AutoModelForCausalLM.from pretrained ⋮---- model = PeftModel.from pretrained model, sft model model = model.merge and unload ⋮---- model = PeftModel.from pretrained model, grpo model ⋮---- tokenizer = AutoTokenizer.from pretrained base model, trust remote code=True ⋮---- def export onnx model, tokenizer, output dir: str ⋮---- """Export merged model to ONNX using Optimum.""" ⋮---- Save merged model to temp dir first Optimum needs HF format on disk merged dir = "/tmp/merged model onnx" ⋮---- no post process=True avoids the 2GB protobuf serialization limit that occurs during tied-weight dedupl… 证据：`finetune/convert_onnx.py`
- **Load adapter if present**（source_file）：DEFAULT QUERY FILE = Path file .parent / "evals" / "queries.txt" def load model model path: str ⋮---- model path = Path model path adapter config = model path / "adapter config.json" base model = "Qwen/Qwen3-1.7B" ⋮---- cfg = json.load f base model = cfg.get "base model name or path", base model ⋮---- tokenizer = AutoTokenizer.from pretrained base model ⋮---- config = AutoConfig.from pretrained base model ⋮---- model = AutoModelForCausalLM.from pretrained ⋮---- Load adapter if present ⋮---- model = PeftModel.from pretrained model, str model path ⋮---- """Generate expansions for a batch of queries.""" ⋮---- prompts = inputs = tokenizer prompts, return tensors="pt", padding=True .to model.dev… 证据：`finetune/eval.py`
- **If it's a string from messages format , parse it**（source_file）：def tokenize text: str - set str ⋮---- stopwords = {'the', 'a', 'an', 'is', 'are', 'to', 'for', 'of', 'in', 'and', words = re.findall r'\b\w+\b', text.lower ⋮---- def jaccard similarity a: str, b: str - float ⋮---- tokens a = tokenize a tokens b = tokenize b ⋮---- intersection = len tokens a & tokens b union = len tokens a tokens b ⋮---- def find best match pred: str, golden list: list str , threshold: float - tuple str None, float ⋮---- best match = None best score = 0.0 ⋮---- score = jaccard similarity pred, golden ⋮---- best score = score best match = golden ⋮---- def parse model output text: str - dict str, list str ⋮---- text = re.sub r'', '', text, flags=re.DOTALL text = text.replace… 证据：`finetune/eval_retrieval.py`
- **Pyproject**（source_file）：project name = "qmd-finetune" version = "0.1.0" description = "QMD query expansion fine-tuning tools" requires-python = " =3.10" dependencies = "torch", "trl =0.12.0", "peft =0.7.0", "transformers =4.45.0", "accelerate =0.24.0", "huggingface hub =0.20.0", "trackio", "datasets", "pyyaml", "gguf", "sentencepiece", "nvidia-ml-py", "pydantic =2.0", 证据：`finetune/pyproject.toml`
- **=============================================================================**（source_file）：ONLY MODE PATTERN = re.compile r'\s+/only: lex vec hyde \s $', re.IGNORECASE STOPWORDS = frozenset { KEY TERM STOPWORDS = frozenset { QUERY VERB STOPWORDS = frozenset { GENERIC LEX PHRASES = frozenset { INTERIOR FILLER WORDS = frozenset {'overview', 'basics'} CHAT TEMPLATE TOKENS = frozenset { def parse expansion text: str - dict ⋮---- result = {"lex": , "vec": , "hyde": , "invalid": } ⋮---- line = line.strip ⋮---- def detect only mode query: str - tuple str None, str ⋮---- match = ONLY MODE PATTERN.search query ⋮---- only type = match.group 1 .lower base query = query :match.start .strip ⋮---- def clean model output text: str - tuple str, bool ⋮---- text = text.replace ' ', '' .strip used… 证据：`finetune/reward.py`
- **Quantize to 4, 6, 8 bit**（source_file）：def export gguf model, tokenizer, output dir: str, model name: str ⋮---- output path = Path output dir gguf dir = output path / "gguf" ⋮---- merged path = Path tmp / "merged" ⋮---- llama cpp = Path "/tmp/llama.cpp" ⋮---- quantize bin = llama cpp / "build" / "bin" / "llama-quantize" ⋮---- build dir = llama cpp / "build" ⋮---- fp16 file = gguf dir / f"{model name}-f16.gguf" ⋮---- log out = Path "/tmp/qmd-gguf-convert.log" log err = Path "/tmp/qmd-gguf-convert.err" ⋮---- result = subprocess.run ⋮---- Quantize to 4, 6, 8 bit ⋮---- out file = gguf dir / f"{model name}-{quant type.lower }.gguf" ⋮---- size mb = out file.stat .st size / 1024 1024 ⋮---- class TimedSaveCallback TrainerCallback ⋮----… 证据：`finetune/train.py`
- **--- Imports heavy ---**（source_file）：MODEL MAP = { def main ⋮---- parser = argparse.ArgumentParser description="QMD fine-tuning with Unsloth" ⋮---- args = parser.parse args model name = MODEL MAP args.model output dir = args.output or f"outputs/qwen3.5-{args.model}" ⋮---- --- Imports heavy --- ⋮---- --- Load model --- ⋮---- --- LoRA --- model = FastLanguageModel.get peft model ⋮---- dataset = load dataset "json", data files=args.data, split="train" dataset = dataset.shuffle seed=42 split = dataset.train test split test size=0.1, seed=42 train ds = split "train" eval ds = split "test" ⋮---- --- Tracking --- report to = "none" ⋮---- report to = "trackio" ⋮---- trainer = SFTTrainer ⋮---- stats = trainer.train ⋮---- --- Save --- ⋮… 证据：`finetune/train_unsloth.py`
- **SQLite with loadable extension support for sqlite-vec**（source_file）：{ description = "QMD - Quick Markdown Search"; 证据：`flake.nix`
- **Migrate Schema**（source_file）：import { Database } from "bun:sqlite"; import { join } from "path"; import { homedir } from "os"; 证据：`migrate-schema.ts`
- **Build**（source_file）：function run command, args, options = 证据：`scripts/build.mjs`
- **Extract Changelog**（source_file）：set -euo pipefail VERSION="${1:?Usage: extract-changelog.sh }" IFS='.' read -r MAJOR MINOR PATCH &2 exit 1 fi OUTPUT="" CAPTURING=false UNRELEASED CONTENT="" IN UNRELEASED=false while IFS= read -r line; do if "$line" =~ ^ CAPTURING=true IN UNRELEASED=true elif "$line" =~ ^ IN UNRELEASED=false ENTRY VERSION="${BASH REMATCH 1 }" IFS='.' read -r E MAJOR E MINOR E PATCH &2 echo "Expected either:" &2 echo " Unreleased with content " &2 echo " $VERSION - YYYY-MM-DD" &2 exit 1 fi printf '%s' "$OUTPUT" 证据：`scripts/extract-changelog.sh`
- **Install Hooks**（source_file）：set -euo pipefail REPO ROOT="$ cd "$ dirname "$0" /.." && pwd " HOOKS DIR="$REPO ROOT/.git/hooks" if ! -d "$HOOKS DIR" ; then echo "Not a git repository, skipping hook install" exit 0 fi cp "$REPO ROOT/scripts/pre-push" "$HOOKS DIR/pre-push" chmod +x "$HOOKS DIR/pre-push" echo "Installed git hooks: pre-push" 证据：`scripts/install-hooks.sh`
- **Package Smoke**（source_file）：function run label, command, args, options = ⋮---- function assertPath path, label = path 证据：`scripts/package-smoke.mjs`
- **!/usr/bin/env bash**（source_file）：!/usr/bin/env bash set -euo pipefail 证据：`scripts/pre-push`
- **--- Validate CHANGELOG.md ---**（source_file）：set -euo pipefail BUMP="${1:?Usage: release.sh patch minor major }" BRANCH=$ git branch --show-current if "$BRANCH" != "main" ; then echo "Error: must be on main branch currently on $BRANCH " &2 exit 1 fi if -n "$ git status --porcelain " ; then echo "Error: working directory not clean" &2 git status --short exit 1 fi if ! bun install --frozen-lockfile & /dev/null; then echo "Error: bun.lock is out of sync with package.json" &2 echo "Run 'bun install' and commit the updated lockfile." &2 exit 1 fi echo "bun.lock: in sync ✓" CURRENT=$ jq -r .version package.json echo "Current version: $CURRENT" bump version { local current="$1" type="$2" IFS='.' read -r major minor patch &2 exit 1 fi if ! gr… 证据：`scripts/release.sh`
- **Repro Metal Rsets Crash**（source_file）：/ Minimal reproduction of llama.cpp issue ggml-org/llama.cpp 22593: ggml-metal-device.m:612: GGML ASSERT rsets- data count == 0 failed Root cause per the upstream issue and proposed fix PR 22595 : ggml metal buffer rset free releases the per-buffer residency set object but does NOT call the symmetric ggml metal device rsets rm . So the device's rsets- data array accumulates dangling references. When the process exits and libc fires the process-static ggml metal device destructor in cxa finalize ranges , the destructor asserts the array is empty — and it isn't. Observed downstream behavior: - With EXPLICIT dispose of every JS handle in order, the assertion does NOT fire. node-llama-cpp's dis… 证据：`scripts/repro-metal-rsets-crash.mjs`
- **Ast**（source_file）：import { createRequire } from "node:module"; import { extname } from "node:path"; import type { BreakPoint } from "./store.js"; type ParserType = import "web-tree-sitter" .Parser; type LanguageType = import "web-tree-sitter" .Language; type QueryType = import "web-tree-sitter" .Query; export type SupportedLanguage = "typescript" "tsx" "javascript" "python" "go" "rust"; ⋮---- export function detectLanguage filepath: string : SupportedLanguage null ⋮---- export function formatGrammarLoadError language: SupportedLanguage, err: unknown : string ⋮---- async function ensureInit : Promise function resolveGrammarPath language: SupportedLanguage : string async function loadGrammar language: Supporte… 证据：`src/ast.ts`
- **Bench Rerank**（source_file）：import { getLlama, resolveModelFile, LlamaLogLevel, type Llama, type LlamaModel, } from "node-llama-cpp"; import { homedir } from "os"; import { join } from "path"; import { cpus } from "os"; ⋮---- function generateDocs n: number : string function formatBytes bytes: number : string function getMemUsage : function median arr: number : number interface BenchResult { parallelism: number; contextSize: number; flashAttention: boolean; times: number ; medianMs: number; docsPerSec: number; vramPerContext: number; totalVram: number; peakRss: number; } async function benchmarkConfig model: LlamaModel, llama: Llama, docs: string , parallelism: number, flash: boolean, : Promise async function main 证据：`src/bench-rerank.ts`
- **Collections**（source_file）：import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; import { join, dirname, resolve } from "path"; import { qmdHomedir } from "./paths.js"; import YAML from "yaml"; export type ContextMap = Record ; export interface Collection { path: string; pattern: string; ignore?: string ; context?: ContextMap; update?: string; includeByDefault?: boolean; } export interface ModelsConfig { embed?: string; rerank?: string; generate?: string; } export interface CollectionConfig { global context?: string; editor uri?: string; editor uri template?: string; collections: Record ; models?: ModelsConfig; } export interface NamedCollection extends Collection { name: string; } ⋮---- export fun… 证据：`src/collections.ts`
- **Db**（source_file）：export type SQLiteValue = string number bigint Buffer Uint8Array Float32Array null; export type SQLiteParams = readonly SQLiteValue ; type DatabaseConstructor = new path: string = Database; type LoadableSqliteDatabase = Pick ; ⋮---- sqliteVecLoad = db: LoadableSqliteDatabase ⋮---- export function openDatabase path: string : Database export interface Database { exec sql: string : void; prepare sql: string : Statement; loadExtension path: string : void; transaction unknown fn: T : T; close : void; } ⋮---- exec sql: string : void; prepare sql: string : Statement; loadExtension path: string : void; transaction ...params: SQLiteValue : T undefined; all ...params: SQLiteValue : T ; } ⋮---- run ..… 证据：`src/db.ts`
- **Llm**（source_file）：import type { Llama, LlamaModel, LlamaEmbeddingContext, Token as LlamaToken, } from "node-llama-cpp"; type StdoutChunk = string Uint8Array; type WriteCallback = err?: Error null = void; type NodeLlamaCppModule = { getLlama: options: Record = Promise ; getLlamaGpuTypes?: include?: "supported" "allValid" = Promise ; resolveModelFile: model: string, cacheDir: string = Promise ; LlamaChatSession: new options: { contextSequence: unknown } = { prompt: prompt: string, options?: Record = Promise ; }; LlamaLogLevel: { error: unknown }; }; ⋮---- async function loadNodeLlamaCpp : Promise export function setNodeLlamaCppModuleForTest module: NodeLlamaCppModule null : void type StdoutWrite = typeof proce… 证据：`src/llm.ts`
- **Maintenance**（source_file）：import type { Store } from "./store.js"; import { vacuumDatabase, cleanupOrphanedContent, cleanupOrphanedVectors, deleteLLMCache, deleteInactiveDocuments, clearAllEmbeddings, } from "./store.js"; export class Maintenance ⋮---- constructor store: Store vacuum : void cleanupOrphanedContent : number cleanupOrphanedVectors : number clearLLMCache : number deleteInactiveDocs : number clearEmbeddings : void 证据：`src/maintenance.ts`
- **Paths**（source_file）：import { homedir as osHomedir } from "node:os"; export function qmdHomedir : string 证据：`src/paths.ts`
- **Store**（source_file）：import { openDatabase, loadSqliteVec } from "./db.js"; import type { Database } from "./db.js"; import picomatch from "picomatch"; import { createHash } from "crypto"; import { readFileSync, realpathSync, statSync, mkdirSync } from "node:fs"; import fastGlob from "fast-glob"; import { qmdHomedir } from "./paths.js"; import { LlamaCpp, getDefaultLlamaCpp, formatQueryForEmbedding, formatDocForEmbedding, withLLMSessionForLlm, DEFAULT EMBED MODEL URI, DEFAULT RERANK MODEL URI, DEFAULT GENERATE MODEL URI, type RerankDocument, type ILLMSession, } from "./llm.js"; import type { NamedCollection, Collection, CollectionConfig, ContextMap, } from "./collections.js"; ⋮---- export function getEmbeddingF… 证据：`src/store.ts`
- 其余 19 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。

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

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

- **QMD 项目概览与系统架构**：importance `high`
  - source_paths: README.md, src/index.ts, src/store.ts, src/db.ts, src/collections.ts
- **混合搜索管线与本地 GGUF 模型集成**：importance `high`
  - source_paths: src/llm.ts, src/store.ts, src/bench/bench.ts, src/bench/score.ts, src/bench-rerank.ts
- **CLI、MCP 与 SDK 编程接口**：importance `high`
  - source_paths: src/cli/qmd.ts, src/cli/formatter.ts, src/mcp/server.ts, bin/qmd, skills/qmd/SKILL.md
- **社区关注话题、平台兼容性与可扩展性**：importance `medium`
  - source_paths: src/ast.ts, src/maintenance.ts, src/paths.ts, finetune/README.md, finetune/CLAUDE.md

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

- repo_clone_verified: true
- repo_inspection_verified: true
- repo_commit: `62b3a67d2e91886381d6bdf49b1140ac1052d071`
- inspected_files: `README.md`, `package.json`, `pnpm-lock.yaml`, `docs/SYNTAX.md`, `src/ast.ts`, `src/bench/bench.ts`, `src/bench/fixtures/example.json`, `src/bench/score.ts`, `src/bench/types.ts`, `src/bench-rerank.ts`, `src/cli/formatter.ts`, `src/cli/qmd.ts`, `src/collections.ts`, `src/db.ts`, `src/index.ts`, `src/llm.ts`, `src/maintenance.ts`, `src/mcp/server.ts`, `src/paths.ts`, `src/store.ts`

宿主 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: 来源证据：qmd embed deadlocks at 0% CPU on Apple M5 Max + macOS 26.4 — Metal shader JIT compile failure in bundled llama.cpp b839…

- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：qmd embed deadlocks at 0% CPU on Apple M5 Max + macOS 26.4 — Metal shader JIT compile failure in bundled llama.cpp b8390 (distinct from #673/#724)
- Why it matters: 可能阻塞安装或首次运行。
- Evidence: community_evidence:github | https://github.com/tobi/qmd/issues/735 | 来源讨论提到 node 相关条件，需在安装/试用前复核。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 2: 来源证据：exclude: patterns in index.yml to prevent double-indexing nested collections

- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：exclude: patterns in index.yml to prevent double-indexing nested collections
- Why it matters: 可能增加新用户试用和生产接入成本。
- Evidence: community_evidence:github | https://github.com/tobi/qmd/issues/645 | 来源讨论提到 node 相关条件，需在安装/试用前复核。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 3: 来源证据：Lossy path normalization breaks QMD_EDITOR_URI for files with spaces

- Trigger: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：Lossy path normalization breaks QMD_EDITOR_URI for files with spaces
- Why it matters: 可能增加新用户试用和生产接入成本。
- Evidence: community_evidence:github | https://github.com/tobi/qmd/issues/717 | 来源类型 github_issue 暴露的待验证使用条件。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 4: 来源证据：npm install fails (macOS apple silicon, latest v26)

- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：npm install fails (macOS apple silicon, latest v26)
- Why it matters: 可能阻塞安装或首次运行。
- Evidence: community_evidence:github | https://github.com/tobi/qmd/issues/699 | 来源讨论提到 node 相关条件，需在安装/试用前复核。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 5: 来源证据：GPU selection falls back to CPU instead of Vulkan on non-NVIDIA machines

- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：GPU selection falls back to CPU instead of Vulkan on non-NVIDIA machines
- Why it matters: 可能增加新用户试用和生产接入成本。
- Evidence: community_evidence:github | https://github.com/tobi/qmd/issues/739 | 来源讨论提到 node 相关条件，需在安装/试用前复核。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 6: 来源证据：Store-open CJK FTS migration OOMs large indexes and can leave BM25 FTS empty

- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Store-open CJK FTS migration OOMs large indexes and can leave BM25 FTS empty
- Why it matters: 可能阻塞安装或首次运行。
- Evidence: community_evidence:github | https://github.com/tobi/qmd/issues/736 | 来源讨论提到 node 相关条件，需在安装/试用前复核。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 7: 可能修改宿主 AI 配置

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

### Constraint 8: 来源证据：`collection add`: trailing backslash in a quoted path swallows following flags — collection is created broken (0 files,…

- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：`collection add`: trailing backslash in a quoted path swallows following flags — collection is created broken (0 files, wrong name/mask) but still reports succ…
- Why it matters: 可能增加新用户试用和生产接入成本。
- Evidence: community_evidence:github | https://github.com/tobi/qmd/issues/738 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

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

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

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

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