use serde::{Deserialize, Serialize}; use std::path::Path; // ── 主节点:master CONVENTIONS.md 内容和版本(编译时嵌入)──────────────────── // CONVENTIONS v1.4.5:新增无 MCP 环境兼容章节(Qwen Code / 其他 AI) const MASTER_CONVENTIONS: &str = include_str!("../../../.blueprint/CONVENTIONS.md"); /// 从 MASTER_CONVENTIONS frontmatter 自动解析版本号(内置基线版本,不随用户版变化)。 fn master_conventions_version() -> &'static str { static VERSION: std::sync::OnceLock = std::sync::OnceLock::new(); VERSION.get_or_init(|| { parse_frontmatter_version_str(MASTER_CONVENTIONS).unwrap_or_else(|| "unknown".to_string()) }) } // ── 用户版 CONVENTIONS(运行时可写,优先级高于内置)──────────────────────────── /// app data dir 下的 conventions/ 子目录路径,由 init_user_conventions_dir 初始化。 static USER_CONVENTIONS_DIR: std::sync::OnceLock = std::sync::OnceLock::new(); /// effective 内容缓存(None = 未缓存,Some = 已缓存用户版;内置版不缓存,直接用常量)。 static USER_CONVENTIONS_CACHE: std::sync::Mutex> = std::sync::Mutex::new(None); /// 由 lib.rs setup() 调用,初始化用户版存储目录。 pub fn init_user_conventions_dir(app_data_dir: std::path::PathBuf) { let dir = app_data_dir.join("conventions"); std::fs::create_dir_all(&dir).ok(); USER_CONVENTIONS_DIR.set(dir).ok(); } fn user_conventions_path() -> Option { USER_CONVENTIONS_DIR.get().map(|d| d.join("CONVENTIONS.md")) } /// 清除 effective 内容缓存,下次调用 effective_conventions_content() 时重新读文件。 pub(crate) fn invalidate_effective_cache() { if let Ok(mut cache) = USER_CONVENTIONS_CACHE.lock() { *cache = None; } } /// 返回当前生效的 CONVENTIONS 内容:用户版(app data)优先,fallback 编译时内置。 pub(crate) fn effective_conventions_content() -> String { // 先查缓存 if let Ok(cache) = USER_CONVENTIONS_CACHE.lock() { if let Some(ref content) = *cache { return content.clone(); } } // 尝试读用户版文件 if let Some(path) = user_conventions_path() { if let Ok(content) = std::fs::read_to_string(&path) { if !content.is_empty() { if let Ok(mut cache) = USER_CONVENTIONS_CACHE.lock() { *cache = Some(content.clone()); } return content; } } } // fallback 内置 MASTER_CONVENTIONS.to_string() } /// 返回当前生效的 CONVENTIONS 版本号。 pub(crate) fn effective_conventions_version() -> String { let content = effective_conventions_content(); parse_frontmatter_version_str(&content) .unwrap_or_else(|| master_conventions_version().to_string()) } /// 从字符串内容解析 frontmatter version 字段。 fn parse_frontmatter_version_str(content: &str) -> Option { let mut lines = content.lines(); // 必须以 --- 开头才进入 frontmatter 模式 if lines.next()?.trim() != "---" { return None; } for line in lines { if line.trim() == "---" { break; } // 遇到关闭 --- 停止 if let Some(v) = line.strip_prefix("version: ") { return Some(v.trim().to_string()); } } None } /// AGENTS.md 蓝图管理区模板(跨工具单一来源,措辞工具无关),版本号使用当前生效的 CONVENTIONS 版本。 fn agents_managed_template() -> String { let ver = effective_conventions_version(); format!( r#" ## 项目蓝图 本项目使用 `.blueprint/` 目录维护项目全景架构图,驱动需求讨论和任务管理。 本节适用于任何 AI 编程工具(Claude / Qwen / Cursor / Copilot 等)。 ### 对话开始时必须执行 1. 读取 `.blueprint/manifest.yaml` 了解项目全景和当前状态 2. 读取 `.blueprint/CONVENTIONS.md` 了解完整工作流规则 ### 需求讨论 → 蓝图同步规则 | 用户说的 | AI 应做的 | |----------|--------------| | "我想加个 XX 功能" | 确认需求后:manifest 新增模块(status: concept),创建 `.blueprint/modules/.md` | | "XX 功能需要 A、B、C" | 在模块文件中拆分为任务卡 | | "这个方案确定了" | 模块 status → planned,补充任务卡 files/acceptance | | "开始做 XX" | 模块 status → in_progress | | 没提蓝图但在讨论功能 | 主动提议更新蓝图 | ### 复杂度决策(讨论新功能 / 拆解需求时) | complexity | 执行流程 | |-----------|---------| | S / M | 直接拆任务卡,确保每张卡有 `files` + `acceptance` + `complexity` → 标记 📋 | | L(复杂系统设计) | 先做架构设计(Claude 用 `/architect` 技能,其他工具按 CONVENTIONS「复杂功能分析流程」章节执行)输出设计文档,用户确认后拆成 S/M 任务卡 | > L 级任务禁止直接写代码,必须先经过 架构设计 → 任务拆解 流程。 ### 任务执行两阶段提交 - **开始写代码前**:任务卡前缀改为 🔵,status → in_progress - **完成验收后**:任务卡前缀改为 ✅,status → done,更新 manifest `updated` 日期 完整规则(迭代管理、阻塞处理、复盘笔记等)详见 `.blueprint/CONVENTIONS.md`。 "# ) } /// CLAUDE.md 蓝图管理区模板:薄引用,指向 AGENTS.md 单一来源。 /// 保留 version marker 使 get_blueprint_status 的版本检测继续工作。 fn claude_managed_template() -> String { let ver = effective_conventions_version(); format!( r#" ## 项目蓝图 蓝图工作流规则统一维护在 @AGENTS.md 的 BLUEPRINT_MANAGED 区(跨工具单一来源,勿在此复制)。 对话开始时必须执行: 1. 读取 `.blueprint/manifest.yaml` 了解项目全景和当前状态 2. 读取 `.blueprint/CONVENTIONS.md` 了解完整工作流规则 3. 遵循 AGENTS.md 中的蓝图工作流(需求→蓝图同步、复杂度决策、两阶段提交) "# ) } // ── manifest.yaml 对应结构 ─────────────────────────────────────────────────── #[derive(Debug, Serialize, Deserialize, Clone)] pub struct BlueprintManifest { pub version: u32, pub name: String, pub description: Option, pub updated: Option, /// 当前迭代号(默认 1,重构已完成模块时手动递增) pub iteration: Option, #[serde(default)] pub areas: Vec, #[serde(default)] pub modules: Vec, #[serde(default)] pub edges: Vec, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct BlueprintArea { pub id: String, pub name: String, pub color: Option, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct BlueprintModule { pub id: String, pub name: String, pub area: String, pub status: String, #[serde(default)] pub progress: u32, #[serde(default)] pub position: Vec, // 运行时填充:从 modules/.md 解析 #[serde(skip_deserializing, default)] pub description: Option, #[serde(skip_deserializing, default)] pub decisions: Vec, #[serde(skip_deserializing, default)] pub tasks: Vec, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct BlueprintEdge { pub from: String, pub to: String, #[serde(rename = "type")] pub edge_type: String, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct BlueprintTask { pub title: String, pub status: String, pub complexity: Option, pub files: Option, pub depends: Option, pub acceptance: Option, pub notes: Option, pub blocked_reason: Option, #[serde(default)] pub locked: bool, // depends 引用的模块尚未完成 } // ── 完整蓝图返回结构 ───────────────────────────────────────────────────────── #[derive(Debug, Serialize, Clone)] pub struct BlueprintData { pub manifest: BlueprintManifest, pub stats: BlueprintStats, } #[derive(Debug, Serialize, Clone)] pub struct BlueprintStats { pub total_modules: u32, pub done: u32, pub in_progress: u32, pub planned: u32, pub concept: u32, pub blocked: u32, pub total_tasks: u32, pub tasks_done: u32, pub tasks_blocked: u32, pub tasks_locked: u32, pub dispatchable: u32, } // ── tauri command ──────────────────────────────────────────────────────────── #[tauri::command] pub fn get_blueprint(project_path: String) -> Result, String> { let bp_dir = Path::new(&project_path).join(".blueprint"); let manifest_path = bp_dir.join("manifest.yaml"); if !manifest_path.exists() { return Ok(None); } let yaml_str = std::fs::read_to_string(&manifest_path) .map_err(|e| format!("读取 manifest.yaml 失败: {e}"))?; let mut manifest: BlueprintManifest = serde_yaml::from_str(&yaml_str).map_err(|e| format!("解析 manifest.yaml 失败: {e}"))?; // 读取每个模块的 markdown 文件 let modules_dir = bp_dir.join("modules"); for module in &mut manifest.modules { let md_path = modules_dir.join(format!("{}.md", module.id)); if md_path.exists() { let content = std::fs::read_to_string(&md_path).unwrap_or_default(); let parsed = parse_module_md(&content); module.description = parsed.description; module.decisions = parsed.decisions; module.tasks = parsed.tasks; // 自动计算 progress:有任务卡时按完成比例,无任务卡保留 manifest 中的值 if !module.tasks.is_empty() { let done_count = module.tasks.iter().filter(|t| t.status == "done").count(); module.progress = ((done_count as f64 / module.tasks.len() as f64) * 100.0).round() as u32; } } } // 依赖检查:构建模块状态表,标记 locked 任务 let module_status: std::collections::HashMap = manifest .modules .iter() .map(|m| (m.id.clone(), m.status.clone())) .collect(); for module in &mut manifest.modules { for task in &mut module.tasks { if task.status == "done" || task.status == "blocked" { continue; // 已完成或已阻塞的任务不需要检查 } if let Some(ref depends) = task.depends.clone() { let unmet = depends .split(',') .map(|s| s.trim()) .filter(|id| !id.is_empty()) .any(|id| module_status.get(id).map(|s| s.as_str()) != Some("done")); task.locked = unmet; } } } // 统计 let stats = compute_stats(&manifest); // 飞轮快照(每日一次,静默写入,不影响主流程) append_usage_snapshot(&bp_dir, &manifest, &stats); Ok(Some(BlueprintData { manifest, stats })) } // ── markdown 解析 ──────────────────────────────────────────────────────────── struct ParsedModule { description: Option, decisions: Vec, tasks: Vec, } fn parse_module_md(content: &str) -> ParsedModule { let mut tasks = Vec::new(); let mut description = None; let mut decisions: Vec = Vec::new(); let body = skip_frontmatter(content); #[derive(PartialEq)] enum Section { None, Overview, Decisions, Tasks, } let mut section = Section::None; let mut overview_lines: Vec<&str> = Vec::new(); let mut current_task: Option = None; for line in body.lines() { // 二级标题切换段落 if line.starts_with("## ") { if let Some(task) = current_task.take() { tasks.push(task); } let heading = line.trim_start_matches("## ").trim(); section = match heading { "概述" => Section::Overview, "决策记录" => Section::Decisions, "任务卡" => Section::Tasks, _ => Section::None, }; continue; } // 三级标题 = 任务卡(仅在任务卡段落内) if line.starts_with("### ") && (section == Section::Tasks || section == Section::None) { section = Section::Tasks; if let Some(task) = current_task.take() { tasks.push(task); } let title_raw = line.trim_start_matches("### ").trim(); let (status, title) = parse_task_title(title_raw); current_task = Some(BlueprintTask { title: title.to_string(), status, complexity: None, files: None, depends: None, acceptance: None, notes: None, blocked_reason: None, locked: false, }); continue; } match section { Section::Overview => { let trimmed = line.trim(); if !trimmed.is_empty() { overview_lines.push(trimmed); } } Section::Decisions => { let trimmed = line.trim(); // 收集 "- xxx" 格式的决策条目 if let Some(item) = trimmed.strip_prefix("- ") { if !item.is_empty() { decisions.push(item.to_string()); } } } Section::Tasks => { if let Some(ref mut task) = current_task { let trimmed = line.trim().trim_start_matches("- "); if let Some(val) = trimmed.strip_prefix("status: ") { task.status = val.trim().to_string(); } else if let Some(val) = trimmed.strip_prefix("complexity: ") { task.complexity = Some(val.trim().to_string()); } else if let Some(val) = trimmed.strip_prefix("files: ") { task.files = Some(val.trim().to_string()); } else if let Some(val) = trimmed.strip_prefix("depends: ") { task.depends = Some(val.trim().to_string()); } else if let Some(val) = trimmed.strip_prefix("acceptance: ") { task.acceptance = Some(val.trim().to_string()); } else if let Some(val) = trimmed.strip_prefix("notes: ") { task.notes = Some(val.trim().to_string()); } else if let Some(val) = trimmed.strip_prefix("blocked_reason: ") { task.blocked_reason = Some(val.trim().to_string()); } } } Section::None => {} } } if let Some(task) = current_task { tasks.push(task); } if !overview_lines.is_empty() { description = Some(overview_lines.join(" ")); } ParsedModule { description, decisions, tasks, } } fn skip_frontmatter(content: &str) -> &str { if content.starts_with("---") { if let Some(end) = content[3..].find("\n---") { let skip = 3 + end + 4; // "---" + content + "\n---" return content.get(skip..).unwrap_or("").trim_start_matches('\n'); } } content } fn parse_task_title(raw: &str) -> (String, &str) { // "✅ 基础操作" → ("done", "基础操作") if let Some(rest) = raw.strip_prefix("✅ ") { return ("done".to_string(), rest); } if let Some(rest) = raw.strip_prefix("🔵 ") { return ("in_progress".to_string(), rest); } if let Some(rest) = raw.strip_prefix("📋 ") { return ("todo".to_string(), rest); } if let Some(rest) = raw.strip_prefix("💭 ") { return ("concept".to_string(), rest); } if let Some(rest) = raw.strip_prefix("🔴 ") { return ("blocked".to_string(), rest); } ("todo".to_string(), raw) } // ── generate_blueprint_prompt ──────────────────────────────────────────────── #[tauri::command] pub fn generate_blueprint_prompt( project_path: String, prompt_type: String, // "init" | "sync" ) -> Result { // 去除尾部斜杠,避免 file_name() 返回 None let path_str = project_path.trim_end_matches(['/', '\\']).to_string(); let root = Path::new(&path_str); // 基础信息 let project_name = root .file_name() .and_then(|n| n.to_str()) .unwrap_or("unknown") .to_string(); let dir_tree = scan_dir_tree(root, 0, 3); let tech_stack = detect_tech_stack(root); let config_files = read_config_files(root); let is_monorepo = root.join("pnpm-workspace.yaml").exists() || root.join("lerna.json").exists() || root.join("turbo.json").exists(); match prompt_type.as_str() { "init" => { let git_summary = get_git_summary(root); // monorepo:补充子包 package.json let subpackages = if is_monorepo { read_monorepo_subpackages(root) } else { String::new() }; let full_config = if subpackages.is_empty() { config_files } else { format!("{config_files}\n\n## 子包配置\n{subpackages}") }; Ok(build_init_prompt( &project_name, &tech_stack, &dir_tree, &full_config, &git_summary, is_monorepo, )) } "sync" => { let git_log = get_git_log(root); let blueprint_summary = read_blueprint_summary(root); Ok(build_sync_prompt( &project_name, &tech_stack, &dir_tree, &config_files, &git_log, &blueprint_summary, )) } _ => Err(format!( "未知 prompt_type: {prompt_type},应为 init 或 sync" )), } } /// 通过文件存在性检测技术栈(不读 AI 文档内容,避免被旧描述干扰) fn detect_tech_stack(root: &Path) -> String { let mut found: std::collections::HashSet<&str> = std::collections::HashSet::new(); // 对给定目录做一次检测,结果写入 found let mut scan_dir = |dir: &Path| { let cfgs = ["js", "ts", "mjs", "cjs"]; let has_cfg = |name: &str| { cfgs.iter() .any(|ext| dir.join(format!("{name}.{ext}")).exists()) }; if has_cfg("next.config") { found.insert("Next.js"); } if has_cfg("nuxt.config") { found.insert("Nuxt"); } if has_cfg("svelte.config") { found.insert("SvelteKit"); } if has_cfg("remix.config") { found.insert("Remix"); } if has_cfg("astro.config") { found.insert("Astro"); } if has_cfg("vite.config") { found.insert("Vite"); } if has_cfg("webpack.config") { found.insert("Webpack"); } if has_cfg("tailwind.config") { found.insert("TailwindCSS"); } if dir.join("tsconfig.json").exists() || dir.join("tsconfig.base.json").exists() { found.insert("TypeScript"); } if dir.join("Cargo.toml").exists() { found.insert("Rust"); } if dir.join("go.mod").exists() { found.insert("Go"); } if dir.join("pyproject.toml").exists() || dir.join("requirements.txt").exists() { found.insert("Python"); } if dir.join("pom.xml").exists() { found.insert("Java/Maven"); } if dir.join("build.gradle").exists() || dir.join("build.gradle.kts").exists() { found.insert("Java/Gradle"); } if dir.join("prisma").join("schema.prisma").exists() { found.insert("Prisma"); } let drizzle = [ "drizzle.config.ts", "drizzle.config.js", "drizzle.config.mjs", ]; if drizzle.iter().any(|f| dir.join(f).exists()) { found.insert("Drizzle"); } // 读 package.json 的 dependencies 字段(仅用于子应用补充框架识别) let pkg = dir.join("package.json"); if pkg.exists() { if let Ok(content) = std::fs::read_to_string(&pkg) { for (kw, label) in &[ ("\"vue\"", "Vue"), ("\"react\"", "React"), ("\"hono\"", "Hono"), ("\"fastify\"", "Fastify"), ("\"express\"", "Express"), ("\"nestjs\"", "NestJS"), ("\"@nestjs/core\"", "NestJS"), ] { if content.contains(kw) { found.insert(label); } } } } }; // ── 包管理器 / monorepo ────────────────────────────────────────────────── let mut hints: Vec = Vec::new(); let is_monorepo = root.join("pnpm-workspace.yaml").exists(); if is_monorepo { hints.push("pnpm monorepo".into()); } else if root.join("pnpm-lock.yaml").exists() { hints.push("pnpm".into()); } else if root.join("bun.lockb").exists() || root.join("bun.lock").exists() { hints.push("Bun".into()); } else if root.join("yarn.lock").exists() { hints.push("Yarn".into()); } if root.join("turbo.json").exists() { hints.push("Turborepo".into()); } // ── 桌面 ────────────────────────────────────────────────────────────────── if root.join("src-tauri").join("Cargo.toml").exists() { hints.push("Tauri".into()); } if root.join("electron-builder.json").exists() || root.join("electron-builder.yml").exists() { hints.push("Electron".into()); } // ── 根目录扫描 ──────────────────────────────────────────────────────────── scan_dir(root); // ── monorepo:扫描 apps/* 和 packages/* 一级子目录 ──────────────────────── for workspace_dir in &["apps", "packages"] { let ws = root.join(workspace_dir); if let Ok(entries) = std::fs::read_dir(&ws) { for entry in entries.flatten() { if entry.path().is_dir() { scan_dir(&entry.path()); } } } } // ── 源码文件扩展名抽样(检测 Vue / React / Svelte)──────────────────────── detect_ui_from_src(root, &mut found); hints.extend(found.into_iter().map(|s| s.to_string())); hints.sort(); if hints.is_empty() { "未知".to_string() } else { hints.join(", ") } } /// 抽样 src/ 目录(及 apps/*/src/)判断 UI 框架 fn detect_ui_from_src(root: &Path, found: &mut std::collections::HashSet<&'static str>) { let src_dirs: Vec = { let mut dirs = vec![root.join("src")]; // monorepo apps if let Ok(entries) = std::fs::read_dir(root.join("apps")) { for e in entries.flatten() { dirs.push(e.path().join("src")); } } dirs }; for src in src_dirs { if !src.is_dir() { continue; } if let Ok(entries) = std::fs::read_dir(&src) { for entry in entries.flatten().take(40) { let name = entry.file_name(); let name_str = name.to_string_lossy(); if name_str.ends_with(".vue") { found.insert("Vue"); } if name_str.ends_with(".tsx") || name_str.ends_with(".jsx") { found.insert("React"); } if name_str.ends_with(".svelte") { found.insert("Svelte"); } } } } } /// 读取项目配置文件(package.json / Cargo.toml / AI文档 等) /// 所有候选文件按「存在则读,不存在跳过」策略处理,对简单项目零影响。 fn read_config_files(root: &Path) -> String { let mut parts = Vec::new(); let candidates: &[(&str, &str, usize)] = &[ // 核心配置 ("README.md", "README.md", 80), ("package.json", "package.json", 60), ("Cargo.toml", "Cargo.toml", 50), ("go.mod", "go.mod", 30), ("pyproject.toml", "pyproject.toml", 40), ("requirements.txt", "requirements.txt", 30), ("pom.xml", "pom.xml", 30), // AI 上下文文档(存在才读;简单项目通常无此类文件) ("ARCHITECTURE.md", "ARCHITECTURE.md", 120), ("CLAUDE.md", "CLAUDE.md", 60), ("AGENTS.md", "AGENTS.md", 60), ("DEVELOPMENT.md", "DEVELOPMENT.md", 50), ]; for (filename, label, max_lines) in candidates { let content = read_file_short(root, filename, *max_lines); if !content.is_empty() { let ext = filename.rsplit('.').next().unwrap_or("txt"); let lang = match ext { "json" => "json", "toml" => "toml", "xml" => "xml", _ => "", }; // 用 ~~~ 围栏,避免文件内容含 ``` 时提前关闭代码块 parts.push(format!("### {label}\n~~~{lang}\n{content}\n~~~")); } } if parts.is_empty() { "(无可读配置文件)".to_string() } else { parts.join("\n\n") } } /// monorepo 子包 package.json 读取(最多 apps 前4个 + packages 前2个) /// 仅在检测到 pnpm-workspace.yaml 时调用,对普通项目零影响。 fn read_monorepo_subpackages(root: &Path) -> String { let mut parts: Vec = Vec::new(); for (workspace_dir, limit) in &[("apps", 4usize), ("packages", 2)] { let ws = root.join(workspace_dir); if !ws.is_dir() { continue; } let Ok(entries) = std::fs::read_dir(&ws) else { continue; }; let mut dirs: Vec<_> = entries.flatten().filter(|e| e.path().is_dir()).collect(); dirs.sort_by_key(|e| e.file_name()); for entry in dirs.iter().take(*limit) { let content = read_file_short(&entry.path(), "package.json", 40); if content.is_empty() { continue; } let label = format!( "{}/{}/package.json", workspace_dir, entry.file_name().to_string_lossy() ); parts.push(format!("### {label}\n~~~json\n{content}\n~~~")); if parts.len() >= 6 { return parts.join("\n\n"); } } } parts.join("\n\n") } fn scan_dir_tree(dir: &Path, depth: usize, max_depth: usize) -> String { const SKIP: &[&str] = &[ "node_modules", ".git", "target", "dist", ".next", ".nuxt", "build", "__pycache__", ".venv", "venv", ".cache", "out", ".turbo", "coverage", ]; let indent = " ".repeat(depth); let mut lines = Vec::new(); let Ok(entries) = std::fs::read_dir(dir) else { return String::new(); }; let mut sorted: Vec<_> = entries.flatten().collect(); sorted.sort_by_key(|e| e.file_name()); for entry in sorted.iter().take(30) { let name = entry.file_name(); let name_str = name.to_string_lossy(); if name_str.starts_with('.') && name_str != ".blueprint" { continue; } if SKIP.iter().any(|s| *s == name_str.as_ref()) { continue; } // 过滤 Vite 时间戳缓存文件(如 vite.config.ts.timestamp-xxx.mjs) if name_str.contains(".timestamp-") { continue; } let path = entry.path(); if path.is_dir() { lines.push(format!("{indent}{name_str}/")); if depth < max_depth { let sub = scan_dir_tree(&path, depth + 1, max_depth); if !sub.is_empty() { lines.push(sub); } } } else { lines.push(format!("{indent}{name_str}")); } } lines.join("\n") } fn read_file_short(root: &Path, filename: &str, max_lines: usize) -> String { let path = root.join(filename); if !path.exists() { return String::new(); } let Ok(content) = std::fs::read_to_string(&path) else { return String::new(); }; let lines: Vec<&str> = content.lines().take(max_lines).collect(); lines.join("\n") } fn get_git_log(root: &Path) -> String { let output = crate::silent_cmd("git") .args(["log", "--oneline", "-20"]) .current_dir(root) .output(); match output { Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(), _ => "(无法读取 git log,可能不是 git 仓库)".to_string(), } } /// init 用的 git 摘要:总提交数 + 最近 15 条 fn get_git_summary(root: &Path) -> String { let run = |args: &[&str]| { crate::silent_cmd("git") .args(args) .current_dir(root) .output() .ok() .filter(|o| o.status.success()) .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) }; let count = run(&["rev-list", "--count", "HEAD"]).unwrap_or_default(); let log = run(&["log", "--oneline", "-15"]).unwrap_or_default(); if count.is_empty() && log.is_empty() { return "(无 git 仓库或暂无提交)".to_string(); } let mut parts = Vec::new(); if !count.is_empty() { parts.push(format!("总提交数: {count}")); } if !log.is_empty() { parts.push(format!("最近 15 条:\n{log}")); } parts.join("\n") } fn read_blueprint_summary(root: &Path) -> String { let bp_dir = root.join(".blueprint"); if !bp_dir.exists() { return "(无现有蓝图)".to_string(); } let mut parts = Vec::new(); // manifest let manifest_path = bp_dir.join("manifest.yaml"); if let Ok(content) = std::fs::read_to_string(&manifest_path) { parts.push(format!("=== manifest.yaml ===\n{content}")); } // modules let modules_dir = bp_dir.join("modules"); if let Ok(entries) = std::fs::read_dir(&modules_dir) { let mut module_files: Vec<_> = entries.flatten().collect(); module_files.sort_by_key(|e| e.file_name()); for entry in module_files { let name = entry.file_name(); let name_str = name.to_string_lossy(); if name_str.ends_with(".md") { if let Ok(content) = std::fs::read_to_string(entry.path()) { parts.push(format!("=== modules/{name_str} ===\n{content}")); } } } } if parts.is_empty() { "(蓝图目录为空)".to_string() } else { parts.join("\n\n") } } /// manifest.yaml 硬约束骨架——就近、简短、高亮,防止子项目 AI 凭感觉或沿用非法旧格式。 /// (CONVENTIONS 全文 900+ 行,manifest 规范埋在中间,实测会被忽略——noteapp 事故) fn manifest_schema_hint() -> &'static str { r##"## ⚠️ manifest.yaml 严格格式(解析器强校验,违反则蓝图无法识别) ```yaml version: 1 name: 项目名 iteration: 1 updated: YYYY-MM-DD areas: # 至少定义一个 - id: frontend name: 前端 color: "#3B82F6" modules: - id: kebab-case-id # 必填,唯一 name: 显示名称 # 必填 area: frontend # 必填!必须是上方 areas 中已定义的 id status: done # 必填,只允许:done | in_progress | planned | concept | blocked | abandoned position: [0, 0] # 可选 edges: # 可选 - from: module-a to: module-b type: dependency # 只允许 dependency | related ``` 硬性规定: - 禁止自造字段与取值(如 `project:`、`stable`、`in-progress`、`depends_on:` 均非法)——依赖关系写入顶层 edges - **若项目中已存在不符合此格式的 manifest.yaml,必须重写为合法格式**(保留其中的有效信息),不要沿用旧结构"## } fn build_init_prompt( project_name: &str, tech_stack: &str, dir_tree: &str, config_files: &str, git_summary: &str, is_monorepo: bool, ) -> String { let module_hint = if is_monorepo { "建议 10-25 个(monorepo 项目请以**业务能力**为单位划分,不要以 app 目录为单位,否则粒度太粗、任务卡无法可派发)" } else { "建议 5-15 个" }; let monorepo_note = if is_monorepo { "\n> ⚠️ **monorepo 项目**:请以**业务能力**(如「用户认证」「某业务线数据管理」「数据层」)而非 app 目录为单位划分模块。每个 app 可能涉及多个业务模块,每个业务模块也可能跨 app 和 packages。\n" } else { "" }; format!( r#"你是一个软件架构师。请基于以下项目信息,从零初始化这个项目的 .blueprint/ 蓝图。 {monorepo_note} ## 项目信息 - 名称: {project_name} - 技术栈: {tech_stack} ## 目录结构 ``` {dir_tree} ``` ## 项目配置文件 {config_files} ## Git 提交摘要 ``` {git_summary} ``` ## 蓝图规则(CONVENTIONS.md 完整内容) 以下是本蓝图系统的格式规范,请严格遵循: {conventions} {schema_hint} ## 你的任务 1. 识别项目的主要功能模块({module_hint}),合理划分 area(前端/后端/基础设施等) 2. 创建 `.blueprint/manifest.yaml`(含 areas、modules、edges) 3. 为每个模块创建 `.blueprint/modules/.md`(含概述 + 任务卡,每张任务卡必须包含 files、acceptance、complexity 字段) 4. 已实现的功能标记 ✅ done,未实现的标记 📋 todo 或 💭 concept 5. **检查测试基建**:查看 package.json 是否有 test 脚本、是否已安装 vitest/jest。若缺失,额外创建一张 📋「补测试基建」任务卡(complexity: S),acceptance 为「安装 vitest,配 vitest.config.ts,package.json 加 test 脚本,跑一个 smoke test 全绿」。Rust 项目同理,检查是否有 #[cfg(test)] 测试 6. 完成后更新 manifest.yaml 的 updated 日期为今天 请直接输出需要创建的文件内容。 "#, conventions = effective_conventions_content(), schema_hint = manifest_schema_hint(), ) } fn build_sync_prompt( project_name: &str, tech_stack: &str, dir_tree: &str, config_files: &str, git_log: &str, blueprint_summary: &str, ) -> String { // 检测关键输入是否缺失,生成上下文感知的提示段落 let no_blueprint = blueprint_summary.contains("无现有蓝图") || blueprint_summary.trim().is_empty(); let no_git = git_log.contains("无法读取") || git_log.trim().is_empty(); let context_note = match (no_blueprint, no_git) { (true, true) => "⚠️ 当前项目**尚无蓝图**且**无法读取 git 历史**。请根据目录结构和配置文件从零初始化蓝图,识别主要功能模块(建议 5-15 个),合理划分 area,为每个模块创建 modules/.md。", (true, false) => "⚠️ 当前项目**尚无蓝图**。请根据目录结构、配置文件和 git 历史从零初始化蓝图,识别主要功能模块(建议 5-15 个),合理划分 area,已有代码的功能标记 ✅ done。", (false, true) => "⚠️ **无法读取 git 历史**,跳过「对照提交标记完成」步骤,仅根据目录结构与现有蓝图的差异补充缺失模块和任务卡。", (false, false) => "", }; let tasks = if no_blueprint { // 无蓝图:退化为 init 风格的任务列表 "1. 识别项目的主要功能模块(建议 5-15 个),合理划分 area(前端/后端/基础设施等)\n\ 2. 创建 `.blueprint/manifest.yaml`(含 areas、modules、edges)\n\ 3. 为每个模块创建 `.blueprint/modules/.md`(含概述 + 任务卡,每张任务卡必须包含 files、acceptance、complexity 字段)\n\ 4. 已有代码的功能标记 ✅ done,规划中的标记 📋 todo 或 💭 concept\n\ 5. 检查测试基建:若缺失测试框架,额外创建一张 📋「补测试基建」任务卡(complexity: S)\n\ 6. 更新 manifest.yaml 的 updated 日期为今天" } else if no_git { // 有蓝图但无 git:只做结构对比,不做提交归因 "1. (跳过 git 对照,无法读取提交历史)\n\ 2. 发现目录中存在但蓝图缺失的功能模块 → 补充对应模块和任务卡\n\ 3. 将目录中已消失的功能标记为 abandoned 或删除对应模块\n\ 4. 更新模块的 status 和 progress 使其与任务卡状态一致\n\ 5. 更新 manifest.yaml 的 updated 日期为今天\n\n\ ⚠️ 状态保护规则:任务卡中 🔵 in_progress 状态由炼境根据 git 提交自动标记,同步时请保留,不要降回 📋 todo。" } else { // 正常 sync:有蓝图 + 有 git "1. 对照 git 提交记录,找出已完成但蓝图未标记的功能 → 更新对应任务卡为 ✅ done\n\ 2. 发现代码/目录中存在但蓝图缺失的功能模块 → 补充对应模块和任务卡\n\ 3. 将不再存在的功能标记为 abandoned 或删除\n\ 4. 更新模块的 status 和 progress 使其与任务卡状态一致\n\ 5. 更新 manifest.yaml 的 updated 日期为今天\n\n\ ⚠️ 状态保护规则:任务卡中 🔵 in_progress 来自 agent 开工加锁,或炼境在未见显式加锁的提交中按 files 重叠推断标记。\ 同步时默认保留,可根据代码完成度升为 ✅ done;仅当核实该卡并无对应改动(只是与其他卡共用文件)时才降回 📋 todo,\ 并在提交说明中写明原因。" }; let output_hint = if no_blueprint { "请直接输出需要创建的文件内容。" } else { "请直接输出需要修改的文件内容(只输出有变化的文件)。" }; format!( r#"你是一个软件架构师。请根据项目最新状态,同步更新这个项目的 .blueprint/ 蓝图,使其准确反映代码现实。 {context_note_section} ## 项目信息 - 名称: {project_name} - 技术栈: {tech_stack} ## 目录结构 ``` {dir_tree} ``` ## 项目配置文件 {config_files} ## 近期 Git 提交(最近 20 条) ``` {git_log} ``` ## 现有蓝图内容 {blueprint_summary} ## 蓝图规则(CONVENTIONS.md 完整内容) 以下是本蓝图系统的格式规范,请严格遵循: {conventions} {schema_hint} ## 你的任务 {tasks} {output_hint} "#, context_note_section = if context_note.is_empty() { "\n".to_string() } else { format!("\n> {context_note}\n\n") }, project_name = project_name, tech_stack = tech_stack, dir_tree = dir_tree, config_files = config_files, git_log = git_log, blueprint_summary = blueprint_summary, tasks = tasks, output_hint = output_hint, conventions = effective_conventions_content(), schema_hint = manifest_schema_hint(), ) } fn compute_stats(manifest: &BlueprintManifest) -> BlueprintStats { let mut stats = BlueprintStats { total_modules: manifest.modules.len() as u32, done: 0, in_progress: 0, planned: 0, concept: 0, blocked: 0, total_tasks: 0, tasks_done: 0, tasks_blocked: 0, tasks_locked: 0, dispatchable: 0, }; for m in &manifest.modules { match m.status.as_str() { "done" => stats.done += 1, "in_progress" => stats.in_progress += 1, "planned" => stats.planned += 1, "concept" => stats.concept += 1, "blocked" => stats.blocked += 1, _ => {} } for t in &m.tasks { stats.total_tasks += 1; if t.status == "done" { stats.tasks_done += 1; } if t.status == "blocked" { stats.tasks_blocked += 1; } if t.locked { stats.tasks_locked += 1; } // 可派发:todo + 未锁定 + 有 files + 有 acceptance + complexity S 或 M if t.status == "todo" && !t.locked && t.files.is_some() && t.acceptance.is_some() && matches!(t.complexity.as_deref(), Some("S") | Some("M")) { stats.dispatchable += 1; } } } stats } // ── 蓝图治理 commands ──────────────────────────────────────────────────────── #[derive(Debug, Serialize)] pub struct BlueprintStatus { pub status: String, // none | rules_outdated | content_stale | synced pub conventions_version: Option, pub claude_md_managed: bool, pub claude_md_version: Option, pub manifest_updated: Option, pub master_version: String, } #[tauri::command] pub fn get_blueprint_status(project_path: String) -> Result { let root = Path::new(&project_path); let bp_dir = root.join(".blueprint"); if !bp_dir.exists() { return Ok(BlueprintStatus { status: "none".to_string(), conventions_version: None, claude_md_managed: false, claude_md_version: None, manifest_updated: None, master_version: master_conventions_version().to_string(), }); } // 读取项目 CONVENTIONS.md 版本 let conventions_version = read_frontmatter_version(&bp_dir.join("CONVENTIONS.md")); // 检测 CLAUDE.md MANAGED 区 let claude_md_path = root.join("CLAUDE.md"); let (claude_md_managed, claude_md_version) = if claude_md_path.exists() { let content = std::fs::read_to_string(&claude_md_path).unwrap_or_default(); if let Some(ver) = extract_managed_version(&content) { (true, Some(ver)) } else { (false, None) } } else { (false, None) }; // 读取 manifest updated 日期 let manifest_updated = read_manifest_updated(&bp_dir.join("manifest.yaml")); // 判断状态:对比当前生效版本(用户版优先,fallback 内置) let effective_ver = effective_conventions_version(); // 项目版本 >= 内置生效版本时视为规则已同步(项目可能领先于内置基线) let project_ver_tuple = parse_semver_tuple(conventions_version.as_deref().unwrap_or("0.0.0")); let effective_ver_tuple = parse_semver_tuple(&effective_ver); let rules_current = project_ver_tuple >= effective_ver_tuple && claude_md_managed && claude_md_version .as_deref() .map(|v| parse_semver_tuple(v) >= effective_ver_tuple) .unwrap_or(false); let status = if !rules_current { "rules_outdated".to_string() } else if is_content_stale(&manifest_updated) { "content_stale".to_string() } else { "synced".to_string() }; Ok(BlueprintStatus { status, conventions_version, claude_md_managed, claude_md_version, manifest_updated, master_version: effective_ver, }) } #[derive(Debug, Serialize)] pub struct SyncResult { pub success: bool, pub conventions_written: bool, pub claude_md_action: String, // created | appended | updated | unchanged pub agents_md_action: String, // created | appended | updated | unchanged pub message: String, } /// BLUEPRINT_MANAGED 块的标记(开始标记后紧跟 ` version="x.y.z" -->`)。 /// 接入包的混合文件预警(onboarding.rs)比较块外内容时也按它剔除本块。 pub(crate) const BLUEPRINT_MANAGED_START: &str = ""; /// 在指定文件中写入/替换 BLUEPRINT_MANAGED 块: /// 文件不存在 → 用 header + 模板创建;已有 MANAGED 区 → 原位替换(内容不变则不写);否则追加。 /// 返回动作:created | updated | unchanged | appended #[cfg(test)] fn upsert_managed_block( path: &Path, template: &str, header_when_created: &str, ) -> Result { upsert_managed_block_with(path, template, header_when_created, &crate::DiskSink) } fn upsert_managed_block_with( path: &Path, template: &str, header_when_created: &str, sink: &dyn crate::WriteSink, ) -> Result { let label = path.file_name().and_then(|n| n.to_str()).unwrap_or("file"); let Some(content) = sink .read(path) .map_err(|e| format!("读取 {label} 失败: {e}"))? else { let content = format!("{header_when_created}\n\n{template}\n"); sink.write(path, &content) .map_err(|e| format!("创建 {label} 失败: {e}"))?; return Ok("created".to_string()); }; if content.contains(BLUEPRINT_MANAGED_START) { let new_content = replace_managed_section(&content, template); let written = sink .write(path, &new_content) .map_err(|e| format!("更新 {label} 失败: {e}"))?; Ok(if written { "updated" } else { "unchanged" }.to_string()) } else { let new_content = format!("{}\n\n{template}\n", content.trim_end()); sink.write(path, &new_content) .map_err(|e| format!("追加 {label} 失败: {e}"))?; Ok("appended".to_string()) } } #[tauri::command] pub fn sync_blueprint_rules(project_path: String) -> Result { Ok(sync_blueprint_rules_with( Path::new(&project_path), &crate::DiskSink, )?) } /// sync_blueprint_rules 的写入汇注入版:plan 用记录汇得到同一份结果而不落盘(P8c)。 /// 失败带出真正出错的文件(CONVENTIONS.md、AGENTS.md 或 CLAUDE.md),计划的阻断项据此指向它。 pub(crate) fn sync_blueprint_rules_with( root: &Path, sink: &dyn crate::WriteSink, ) -> Result { let bp_dir = root.join(".blueprint"); let project_name = root .file_name() .and_then(|n| n.to_str()) .unwrap_or("Project") .to_string(); // 1. 写入 CONVENTIONS.md(使用当前生效版本:用户版优先,fallback 内置;内容不变则不写; // .blueprint/ 由写入汇按需创建) let conventions_path = bp_dir.join("CONVENTIONS.md"); let conventions_written = sink .write(&conventions_path, &effective_conventions_content()) .map_err(|e| format!("写入 CONVENTIONS.md 失败: {e}")) .map_err(crate::WriteFailure::at(&conventions_path))?; // 2. AGENTS.md:完整蓝图工作流(跨工具单一来源,Qwen/Cursor/Copilot 均读) let agents_path = root.join("AGENTS.md"); let agents_action = upsert_managed_block_with( &agents_path, &agents_managed_template(), &format!("# AGENTS.md — {project_name}\n\n> 跨工具 AI 上下文入口(Claude / Qwen / Cursor / Copilot 等均读此文件)。"), sink, ) .map_err(crate::WriteFailure::at(&agents_path))?; // 3. CLAUDE.md:薄引用(Claude 经 @AGENTS.md 接入单一来源) let claude_path = root.join("CLAUDE.md"); let claude_action = upsert_managed_block_with( &claude_path, &claude_managed_template(), &format!("# {project_name}"), sink, ) .map_err(crate::WriteFailure::at(&claude_path))?; Ok(SyncResult { success: true, conventions_written, claude_md_action: claude_action.clone(), agents_md_action: agents_action.clone(), message: format!( "CONVENTIONS.md 已同步至 v{},AGENTS.md {agents_action},CLAUDE.md {claude_action}", effective_conventions_version() ), }) } // ── 用户版 CONVENTIONS 读写 commands ───────────────────────────────────────── #[derive(Debug, Serialize)] pub struct UserConventionsStatus { pub source: String, // "builtin" | "user" pub version: String, pub content: String, pub builtin_version: String, pub outdated_from_builtin: bool, // 用户版本号低于内置时为 true } #[tauri::command] pub fn get_user_conventions_status() -> UserConventionsStatus { let builtin_ver = master_conventions_version().to_string(); let user_path = user_conventions_path(); let has_user = user_path.as_ref().map(|p| p.exists()).unwrap_or(false); if has_user { let content = effective_conventions_content(); let version = effective_conventions_version(); let outdated = parse_semver_tuple(&version) < parse_semver_tuple(&builtin_ver); UserConventionsStatus { source: "user".to_string(), version, content, builtin_version: builtin_ver, outdated_from_builtin: outdated, } } else { UserConventionsStatus { source: "builtin".to_string(), version: builtin_ver.clone(), content: MASTER_CONVENTIONS.to_string(), builtin_version: builtin_ver, outdated_from_builtin: false, } } } #[derive(Debug, Serialize)] pub struct SaveConventionsResult { pub version: String, pub synced_count: u32, } /// 从 DB 收集所有项目的可访问路径(Windows 路径或 WSL UNC 路径) fn collect_all_sync_paths() -> Vec { let conn = match crate::db::pool().get() { Ok(c) => c, Err(_) => return vec![], }; let mut stmt = match conn.prepare("SELECT win_path, wsl_path, platform FROM project_workspaces") { Ok(s) => s, Err(_) => return vec![], }; let configured_distro: String = conn .query_row( "SELECT value FROM settings WHERE key='wsl_distro'", [], |r| r.get(0), ) .unwrap_or_else(|_| "Ubuntu".to_string()); stmt.query_map([], |row| { Ok(( row.get::<_, Option>(0)?, row.get::<_, Option>(1)?, row.get::<_, Option>(2)?, )) }) .map(|iter| { iter.filter_map(|r| r.ok()) .filter_map(|(win_path, wsl_path, platform)| { match platform.as_deref() { Some("wsl") => { let lp = wsl_path?; if lp.starts_with("\\\\") { // 已是 UNC,直接用 Some(lp) } else if !lp.is_empty() { // Linux 路径,转为 UNC let inner = lp.trim_start_matches('/').replace('/', "\\"); Some(format!( "\\\\wsl.localhost\\{}\\{}", configured_distro, inner )) } else { None } } _ => win_path.filter(|p| !p.is_empty()), } }) .collect() }) .unwrap_or_default() } #[tauri::command] pub fn save_user_conventions(content: String) -> Result { // 1. 解析版本号,非法内容拒绝写入 let version = parse_frontmatter_version_str(&content) .ok_or_else(|| "内容缺少有效的 frontmatter version 字段,写入已拒绝".to_string())?; if version == "unknown" { return Err("version 字段值为 unknown,写入已拒绝".to_string()); } // 2. 写入用户版文件 let path = user_conventions_path().ok_or_else(|| "用户版存储目录未初始化".to_string())?; std::fs::write(&path, &content).map_err(|e| format!("写入用户版 CONVENTIONS 失败: {e}"))?; // 3. 清除缓存,使新版本立即生效 invalidate_effective_cache(); // 4. 自动同步所有项目(后端自行查询路径,含 WSL) let mut synced = 0u32; for path_str in collect_all_sync_paths() { if sync_blueprint_rules(path_str).is_ok() { synced += 1; } } Ok(SaveConventionsResult { version, synced_count: synced, }) } #[tauri::command] pub fn reset_conventions_to_builtin() -> Result { // 删除用户版文件 if let Some(path) = user_conventions_path() { if path.exists() { std::fs::remove_file(&path).map_err(|e| format!("删除用户版文件失败: {e}"))?; } } invalidate_effective_cache(); // 同步所有项目回内置版本(后端自行查询路径,含 WSL) let mut synced = 0u32; for path_str in collect_all_sync_paths() { if sync_blueprint_rules(path_str).is_ok() { synced += 1; } } Ok(SaveConventionsResult { version: master_conventions_version().to_string(), synced_count: synced, }) } fn parse_semver_tuple(v: &str) -> (u32, u32, u32) { let mut parts = v.splitn(3, '.'); let major = parts.next().and_then(|x| x.parse().ok()).unwrap_or(0); let minor = parts.next().and_then(|x| x.parse().ok()).unwrap_or(0); let patch = parts.next().and_then(|x| x.parse().ok()).unwrap_or(0); (major, minor, patch) } // ── 治理辅助函数 ───────────────────────────────────────────────────────────── fn read_frontmatter_version(path: &Path) -> Option { let content = std::fs::read_to_string(path).ok()?; parse_frontmatter_version_str(&content) } fn extract_managed_version(content: &str) -> Option { let marker = " 内容A "; let tpl_v2 = " 内容B "; // 1. 不存在 → created,含 header let a = upsert_managed_block(&f, tpl_v1, "# 头部").unwrap(); assert_eq!(a, "created"); let c = std::fs::read_to_string(&f).unwrap(); assert!(c.starts_with("# 头部")); assert!(c.contains("内容A")); // 2. 已有 MANAGED 区 → updated(原位替换,header 保留,旧内容消失) let a = upsert_managed_block(&f, tpl_v2, "# 头部").unwrap(); assert_eq!(a, "updated"); let c = std::fs::read_to_string(&f).unwrap(); assert!(c.contains("内容B") && !c.contains("内容A")); assert_eq!(c.matches("BLUEPRINT_MANAGED_START").count(), 1); // 2b. 回归:内容不变(含 autocrlf 检出的 CRLF 副本)→ unchanged,不重写文件 //(2026-10-01 enterprise:无条件 LF 重写让 git status 误报改动、修改时间失真) std::fs::write(&f, c.replace('\n', "\r\n")).unwrap(); let before = std::fs::read(&f).unwrap(); let a = upsert_managed_block(&f, tpl_v2, "# 头部").unwrap(); assert_eq!(a, "unchanged"); assert_eq!( std::fs::read(&f).unwrap(), before, "CRLF 原样保留,未被 LF 重写" ); // 3. 存在但无 MANAGED 区 → appended(既有内容保留) let g = dir.join("CLAUDE.md"); std::fs::write( &g, "# 手写内容 自定义段落", ) .unwrap(); let a = upsert_managed_block(&g, tpl_v1, "# 不该出现").unwrap(); assert_eq!(a, "appended"); let c = std::fs::read_to_string(&g).unwrap(); assert!(c.contains("自定义段落") && c.contains("内容A") && !c.contains("不该出现")); let _ = std::fs::remove_dir_all(&dir); } // ── generate_muhe_prompt(P3-D 梦核数据段)─────────────────────────────── #[test] fn muhe_prompt_contains_high_risk_scope_section() { let stats = FlywheelStats { cohorts: vec![], top_blocked_reasons: vec![], stalled_projects: vec![], ai_doc_stale_projects: vec![], iteration_jumps: vec![], stalled_modules: vec![], total_projects_scanned: 0, projects_with_data: 0, project_notes: vec![], execution_quality: ExecutionQuality { complexity_dist: Default::default(), total_rework_count: 0, avg_rounds_m: None, }, }; let prompt = generate_muhe_prompt(stats); assert!( prompt.contains("### 跨项目高风险 scope"), "梦核 prompt 应含高风险 scope 数据段" ); assert!( prompt.contains("### 规则命中 × 返工交叉"), "规则置信度数据段应保留" ); // 测试环境 pool 未初始化 → 两段都应走占位文案而非 panic assert!(prompt.contains("暂无数据")); } }