import { accessSync, constants, existsSync, readdirSync, statSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR } from "../paths.js"; import { VERSION } from "../../version.js"; import { loadCorpConfigs, loadGlobalConfig } from "../config/loader.js"; import { getDefaultGlobalSkillDir } from "../embedded-skill.js"; import { resolveUsageFilePath } from "../stats/usage-tracker.js"; import { EMBEDDED_DIRECTORY_SPECS, EMBEDDED_DOMAIN_CAPABILITIES, EMBEDDED_SECURITY_POLICIES } from "./knowledge.js"; export interface DirectoryHealth { name: string; path: string; exists: boolean; writable?: boolean; fileCount?: number; description: string; } export interface HealthCheckItem { id: string; title: string; status: "ok" | "warn" | "error"; message: string; } export interface DoctorDiagnosis { doctor: "ok" | "warning"; timestamp: string; runtime: { version: string; executablePath: string; platform: string; engine: string; }; directories: Record; enterprises: { total: number; productionCount: number; testCount: number; activeCorpId?: string; activeCorpName?: string; }; checks: HealthCheckItem[]; knowledge: { summary: string; directorySpecsCount: number; securityPoliciesCount: number; domainCapabilitiesCount: number; guideCommand: string; }; } function countJsonFiles(dir: string): number { if (!existsSync(dir)) return 0; try { return readdirSync(dir).filter((file) => file.endsWith(".json")).length; } catch { return 0; } } function isPathWritable(path: string): boolean { try { accessSync(path, constants.W_OK); return true; } catch { return false; } } /** * Lists the JSON configs in a directory, skipping the shipped `example.*.json` templates: those * hold placeholders only, so their default mode is not a finding. */ function listCredentialFilePaths(dir: string): string[] { if (!existsSync(dir)) return []; try { return readdirSync(dir) .filter((file) => file.endsWith(".json") && !file.startsWith("example.")) .map((file) => join(dir, file)); } catch { return []; } } /** * The tool writes credential-bearing files 0o600 (`core/config/loader.ts`, * `cli/commands/corps.ts`, `core/auth/token-store.ts`), but a file placed by hand keeps the * 0o644 default — and `enterprises/local.json` holds a plaintext Hose app key and password. * Report those rather than assuming the writers' mode. */ function findGroupOrWorldReadable(paths: string[]): string[] { return paths.filter((path) => { try { return (statSync(path).mode & 0o077) !== 0; } catch { return false; } }); } /** * Pure, read-only system diagnostic and health inspection. * Never creates, mutates, or deletes any files on the filesystem. */ export function diagnoseSystem(): DoctorDiagnosis { const home = homedir(); const configDir = join(home, ".config", "seal-use"); const enterprisesDir = join(configDir, "enterprises"); const globalConfigFile = join(configDir, "config.json"); const tokenStore = join(configDir, "seal_tokens.json"); const mappingsDir = join(configDir, "mappings"); const agentSkillDir = getDefaultGlobalSkillDir(); const exportDir = join(home, "Downloads"); const globalBinaryCandidates = [ "/opt/homebrew/bin/seal-use", "/usr/local/bin/seal-use", join(home, ".local", "bin", "seal-use"), join(home, "bin", "seal-use") ]; const detectedBinary = globalBinaryCandidates.find((p) => existsSync(p)) ?? process.execPath; const directories: Record = { configDir: { name: "配置根目录", path: configDir, exists: existsSync(configDir), writable: existsSync(configDir) ? isPathWritable(configDir) : false, description: "用户持久化配置与企业状态根目录" }, enterprisesDir: { name: "企业配置目录", path: enterprisesDir, exists: existsSync(enterprisesDir), writable: existsSync(enterprisesDir) ? isPathWritable(enterprisesDir) : false, fileCount: countJsonFiles(enterprisesDir), description: "企业连接配置(JSON)保存路径" }, globalConfigFile: { name: "全局配置文件", path: globalConfigFile, exists: existsSync(globalConfigFile), description: "全局工作模式与默认企业配置" }, tokenStore: { name: "凭据缓存", path: tokenStore, exists: existsSync(tokenStore), description: "会话凭据与令牌缓存" }, mappingsDir: { name: "规则版本映射快照", path: mappingsDir, exists: existsSync(mappingsDir), fileCount: countJsonFiles(mappingsDir), description: "生产与测试规则版本映射对照表" }, agentSkillDir: { name: "AI Agent 技能目录", path: agentSkillDir, exists: existsSync(join(agentSkillDir, "SKILL.md")), description: "本地 Agent 技能主目录" }, exportDefaultDir: { name: "报表默认导出目录", path: exportDir, exists: existsSync(exportDir), writable: existsSync(exportDir) ? isPathWritable(exportDir) : false, description: "审核大盘报表默认写入目录" }, lintersDir: { name: "规则校验器目录 (用户自定义)", path: PRIMARY_LINTERS_DIR, exists: existsSync(PRIMARY_LINTERS_DIR), writable: existsSync(PRIMARY_LINTERS_DIR) ? isPathWritable(PRIMARY_LINTERS_DIR) : false, description: "用户私有规则校验脚本存放目录" }, officialLintersDir: { name: "官方内置规则校验器目录", path: OFFICIAL_LINTERS_DIR, exists: existsSync(OFFICIAL_LINTERS_DIR), description: "官方标准与严格风控校验脚本目录 (系统自动保护与重写)" }, globalBinary: { name: "全局命令行二进制", path: detectedBinary, exists: existsSync(detectedBinary), description: "系统全局命令执行入口" } }; // Safe read of loaded corps without side-effects let corps: ReturnType = []; try { corps = loadCorpConfigs(); } catch { corps = []; } const globalConfig = loadGlobalConfig(); const currentCorpId = globalConfig.defaultCorpId ?? corps[0]?.id; const currentCorp = corps.find((c) => c.id === currentCorpId); const testCount = corps.filter((c) => (c.environment ?? "production").toLowerCase() === "test").length; const prodCount = corps.length - testCount; // Build health checks const checks: HealthCheckItem[] = []; // Check 1: Executable checks.push({ id: "executable", title: "命令行二进制", status: "ok", message: `当前执行路径: ${process.execPath}` }); // Check 2: Config Directory if (directories.configDir?.exists && directories.configDir.writable) { checks.push({ id: "config_dir", title: "配置目录访问", status: "ok", message: `${configDir} (正常读写)` }); } else if (directories.configDir?.exists) { checks.push({ id: "config_dir", title: "配置目录访问", status: "warn", message: `${configDir} (存在但可能不可写)` }); } else { checks.push({ id: "config_dir", title: "配置目录访问", status: "warn", message: `未检测到配置目录 ${configDir},首次运行配置命令时将自动创建` }); } // Check 3: Enterprises Configured if (corps.length > 0) { checks.push({ id: "enterprises", title: "企业接入状态", status: "ok", message: `已接入 ${corps.length} 家企业 (正式: ${prodCount}, 测试: ${testCount})` }); } else { checks.push({ id: "enterprises", title: "企业接入状态", status: "warn", message: "当前未检测到企业配置,请使用 seal-use corps add-hose-persistent、add-hose-web-session 或 add-seal-bearer 接入企业" }); } // Check 4: Agent Skill if (directories.agentSkillDir?.exists) { checks.push({ id: "agent_skill", title: "AI Agent 技能", status: "ok", message: `已就绪于 ${agentSkillDir}` }); } else { checks.push({ id: "agent_skill", title: "AI Agent 技能", status: "warn", message: `未在 ${agentSkillDir} 检测到技能,可运行 'seal-use skill sync' 安装` }); } // Check 5: Credential file permissions const credentialFiles = [ tokenStore, globalConfigFile, resolveUsageFilePath(), ...listCredentialFilePaths(enterprisesDir), ...listCredentialFilePaths(join(process.cwd(), "enterprises")) ].filter((path, index, all) => all.indexOf(path) === index && existsSync(path)); const looseCredentialFiles = findGroupOrWorldReadable(credentialFiles); checks.push({ id: "credential_permissions", title: "凭据文件权限", status: looseCredentialFiles.length === 0 ? "ok" : "warn", message: looseCredentialFiles.length === 0 ? `已检查 ${credentialFiles.length} 个凭据文件,均为仅属主可读 (0600)` : `${looseCredentialFiles.length} 个凭据文件权限宽于 0600(同机其他用户可读,取决于父目录权限),建议 chmod 600:${looseCredentialFiles.join("、")}` }); // Check 6: Rule Linter configuration const lintConfig = globalConfig.lint ?? { enabled: false, activeLinter: "builtin", minScore: 0 }; if (lintConfig.enabled) { checks.push({ id: "rule_linter", title: "规则质量校验器", status: "ok", message: `已开启 (校验器: ${lintConfig.activeLinter}, 最低门槛分: ${lintConfig.minScore})` }); } else { checks.push({ id: "rule_linter", title: "规则质量校验器", status: "ok", message: `未开启 (默认关闭,可运行 seal-use config lint enable 开启)` }); } const hasWarning = checks.some((c) => c.status === "warn" || c.status === "error"); const engine = typeof (globalThis as any).Bun !== "undefined" ? `Bun ${(globalThis as any).Bun.version}` : `Node ${process.version}`; return { doctor: hasWarning ? "warning" : "ok", timestamp: new Date().toISOString(), runtime: { version: VERSION, executablePath: process.execPath, platform: `${process.platform} (${process.arch})`, engine }, directories, enterprises: { total: corps.length, productionCount: prodCount, testCount, activeCorpId: currentCorp?.id, activeCorpName: currentCorp?.name }, checks, knowledge: { summary: "内嵌系统架构与目录规范白皮书(纯内存只读,零写入依赖)", directorySpecsCount: EMBEDDED_DIRECTORY_SPECS.length, securityPoliciesCount: EMBEDDED_SECURITY_POLICIES.length, domainCapabilitiesCount: EMBEDDED_DOMAIN_CAPABILITIES.length, guideCommand: "seal-use doctor guide" } }; } /** * Formats a terminal-friendly, human-readable diagnostic dashboard for stderr. */ export function formatDoctorDashboard(diagnosis: DoctorDiagnosis): string { const lines: string[] = []; const symbol = diagnosis.doctor === "ok" ? "✨" : "⚠️"; lines.push(`🩺 [Seal Use Doctor] 系统健康诊断看板 ${symbol}`); lines.push("─────────────────────────────────────────────────────────────"); // Runtime section lines.push("【运行环境】"); lines.push(` 版本号: ${diagnosis.runtime.version}`); lines.push(` 程序路径: ${diagnosis.runtime.executablePath}`); lines.push(` 操作系统: ${diagnosis.runtime.platform}`); lines.push(` 执行引擎: ${diagnosis.runtime.engine}`); lines.push(""); // Directory section lines.push("【核心路径状态】"); for (const [, dir] of Object.entries(diagnosis.directories)) { const icon = dir.exists ? "✓" : "○"; const statusText = dir.exists ? dir.fileCount !== undefined ? `(${dir.fileCount} 个文件)` : dir.writable ? "(就绪/可写)" : "(存在)" : "(未创建)"; lines.push(` ${icon} ${dir.name.padEnd(16, " ")}: ${dir.path} ${statusText}`); } lines.push(""); // Enterprise section lines.push("【企业资产概览】"); lines.push(` 接入企业总计: ${diagnosis.enterprises.total} 家 (生产: ${diagnosis.enterprises.productionCount}, 测试: ${diagnosis.enterprises.testCount})`); if (diagnosis.enterprises.activeCorpId) { lines.push(` 当前激活企业: ${diagnosis.enterprises.activeCorpName} (${diagnosis.enterprises.activeCorpId})`); } else { lines.push(" 当前激活企业: 无默认企业 (无状态模式)"); } lines.push(""); // Health checks section lines.push("【健康自检】"); for (const c of diagnosis.checks) { const icon = c.status === "ok" ? "✓" : c.status === "warn" ? "⚠️" : "✗"; lines.push(` ${icon} [${c.title}]: ${c.message}`); } lines.push(""); // Next steps hint lines.push("─────────────────────────────────────────────────────────────"); lines.push("👉 查阅内嵌白皮书与目录规范: seal-use doctor guide"); lines.push("👉 检索企业: seal-use corps search "); const linterCheck = diagnosis.checks.find((c) => c.id === "rule_linter"); if (linterCheck && linterCheck.message.includes("未开启")) { lines.push("👉 开启规则自动质量校验: seal-use config lint enable"); } return lines.join("\n"); }