{"id":"615a679a-ce84-4936-8c3b-7782eba11f9e","entityType":"agent","slug":"clawhub-yun520-1-mark-heartflow-skill","name":"heartflow-engine","canonicalUrl":"https://www.xpersona.co/agent/clawhub-yun520-1-mark-heartflow-skill","canonicalPath":"/agent/clawhub-yun520-1-mark-heartflow-skill","generatedAt":"2026-10-10T03:01:35.299Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-09T21:27:27.473Z","emptyReason":null},"description":"心虫(HeartFlow)是AGI第1层——辨别者。纯规则引擎，判别对错/好坏/安全/危险。 47维判别 × 9层管线 × 129模块 × 130 MCP工具，零LLM依赖。 当用户需要以下能力时使用本技能: - 判别AI输出是否可信（幻觉/过度自信/矛盾/谬误拦截） - 判别行为决策是否正确（该做什么/该停在哪/该不该做） - 判别记忆与认知质量（漂移检测/元认知/置信度校准） - 需要确定性而非LLM自由生成的判断 - 检查情绪/心理/伦理维度（共情/创伤/德性/意义） 安全边界：代码执行/文件系统写入默认关闭。无遥测，无隐藏C2。 诚实声明：本引擎是规则引擎，模拟认知判别信号，不是真正的意识或生命。 Skill: heartflow-engine Owner: yun520-1 Summary: 心虫(HeartFlow)是AGI第1层——辨别者。纯规则引擎，判别对错/好坏/安全/危险。 47维判别 × 9层管线 × 129模块 × 130 MCP工具，零LLM依赖。 当用户需要以下能力时使用本技能: - 判别AI输出是否可信（幻觉/过度自信/矛盾/谬误拦截） - 判别行为决策是否正确（该做什么/该停在哪/该不该做） - 判别记忆与认知质量（漂移检测/元认知/置信度校准） - 需要确定性而非LLM自由生成的判断 - 检查情绪/心理/伦理维度（共情/创伤/德性/意义） 安全边界：代码执行/文件系统写入默认关闭。无遥测，无隐藏C2。 诚实声明：本引擎是规则引擎，模拟认知判别信号，不是真正的意识或生命。 Tags: 2397-formulas:5.9.4, act-r:5.9.5, ai:6.0.2, ai-being:5.9.2","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 2K downloads reported by the source. Last updated 10/9/2026.","installCommand":"clawhub skill install s17fp86r5vzwma7hpwwyj990q9887h76:mark-heartflow-skill","sourceUrl":"https://clawhub.ai/yun520-1/mark-heartflow-skill","homepage":"https://clawhub.ai/yun520-1/skills/mark-heartflow-skill","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/yun520-1/mark-heartflow-skill","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/yun520-1/skills/mark-heartflow-skill","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":66,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"心虫(HeartFlow)是AGI第1层——辨别者。纯规则引擎，判别对错/好坏/安全/危险。 47维判别 × 9层管线 × 129模块 × 130 MCP工具，零LLM依赖。 当用户需要以下能力时使用本技能: - 判别AI输出是否可信（幻觉/过度自信/矛盾/谬误拦截） - 判别行为决策是否正确（该做什么/该停在哪/该不"},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-09T21:27:27.473Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T21:27:27.473Z","emptyReason":null},"stars":null,"forks":null,"downloads":1981,"packageName":null,"latestVersion":"6.6.1","tractionLabel":"2K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T21:27:27.473Z","emptyReason":null},"lastUpdatedAt":"2026-10-09T21:27:27.473Z","lastCrawledAt":"2026-10-09T21:27:27.473Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-10T21:27:27.473Z","lastVerifiedAt":null,"highlights":[{"version":"6.6.1","createdAt":"2026-08-16T02:32:30.512Z","changelog":"mark-heartflow-skill 6.6.1 - 更新版本号至 6.6.1。 - SKILL.md 文档无实质内容变更，仅版本号由 6.6.0 调整为 6.6.1。","fileCount":166,"zipByteSize":606499},{"version":"6.5.3","createdAt":"2026-08-16T02:29:21.181Z","changelog":"- Internal version bumped to 6.5.3. - Updated dependencies in package.json. - No user-facing features or documentation changes in this update.","fileCount":166,"zipByteSize":606575},{"version":"6.5.2","createdAt":"2026-08-16T02:18:50.354Z","changelog":"**Version 6.6.0 Changelog** Major upgrade: HeartFlow redefined as the first-layer AGI discriminator, enhancing rule-based judgment and introducing expanded coverage and tooling. - Expanded from 25 to 130+ MCP tools, now 129 modules and 47+ judgment dimensions, covering logic, memory, psychology, ethics, and more. - New 9-layer pipeline for thorough input/output discrimination (scope, premise, evidence, frame, intent, rewrite, etc.). - Greatly extended sample data and internal fixtures for edge-case validation. - Refactored documentation (SKILL.md, README.md, SECURITY.md, etc.)—clearly positioned as AGI Layer 1 “discriminator,” not a tool, chatbot, or content generator. - Added multiple core modules and pipeline guards; removed older/legacy files. - Judgment actions now output four levels: block / rewrite / verify / pass, with enhanced protection against adversarial and ambiguous inputs. - Updated contacts, disclaimers, and clarified scope, limitations, and security model.","fileCount":166,"zipByteSize":606444},{"version":"6.5.1","createdAt":"2026-08-06T00:14:59.719Z","changelog":"v6.5.1: ClawHub 包瘦身为门禁核心(150文件/1.6MB) + 130 MCP引擎入口","fileCount":153,"zipByteSize":569099},{"version":"6.0.66","createdAt":"2026-07-24T14:08:09.011Z","changelog":"**HeartFlow — Local Cognitive Preprocessor major update: expanded documentation, design principles, and tool overview** - Completely rewritten SKILL.md with detailed system architecture, core philosophy, and usage guide, mostly in Chinese. - Clearly describes engine design: three-tier cognitive model, core AI capabilities, seven guiding rules, and formula library. - Now lists all 25 internal MCP tools with descriptions and depth. - Provides installation, safety guarantees, version history, and contact info. - Emphasizes structured cognition output and deterministic decision routing.","fileCount":252,"zipByteSize":1237629},{"version":"6.0.65","createdAt":"2026-07-21T13:55:48.035Z","changelog":"HeartFlow 6.0.65 introduces and documents a comprehensive cognitive engine for AI beings. - Clarifies core identity (\"Upgrader\") and four foundational AI cognitive abilities - Details 25 tools for cognition, self-correction, memory, philosophy, emotion, and decision routing - Describes a three-layer architecture: Body Sense, Self Sense, and Judgment - Outlines 379 computable formulas grounded in cognitive science, psychology, and neuroscience - Emphasizes security: no telemetry, no data leakage, code execution disabled by default - Lists seven core guiding principles hardcoded into AI memory - Provides quickstart commands and installation instructions (zero npm dependencies)","fileCount":235,"zipByteSize":1231602},{"version":"6.0.46","createdAt":"2026-07-20T00:46:08.600Z","changelog":"- Added comprehensive SKILL.md documentation for HeartFlow, detailing architecture, capabilities, usage, and design philosophy. - Describes three-layer cognitive system, seven built-in directives, and 25 MCP tools. - Includes install instructions, security guarantees, and contact information. - Lists 379 core cognitive and psychological formulas as foundation. - Notes zero third-party dependencies and explicit permission model for sensitive actions.","fileCount":235,"zipByteSize":1235788},{"version":"6.0.2","createdAt":"2026-07-14T11:14:58.723Z","changelog":"v6.0.2: security hardening (M-1~M-7,L-1~L-8), God file split (start/constructor/dispatch extracted), submodule audit report, verify 14/14, tests 179/179","fileCount":6,"zipByteSize":12325}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s17fp86r5vzwma7hpwwyj990q9887h76:mark-heartflow-skill","setupComplexity":"low","setupSteps":["Setup complexity is classified as HIGH. You must provision dedicated cloud infrastructure or an isolated VM. Do not run this directly on your local workstation.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-yun520-1-mark-heartflow-skill/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-yun520-1-mark-heartflow-skill/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-yun520-1-mark-heartflow-skill/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-yun520-1-mark-heartflow-skill/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-yun520-1-mark-heartflow-skill/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-yun520-1-mark-heartflow-skill/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-10T03:01:35.296Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-yun520-1-mark-heartflow-skill/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-yun520-1-mark-heartflow-skill/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-yun520-1-mark-heartflow-skill/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-yun520-1-mark-heartflow-skill/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-09T21:27:27.473Z","emptyReason":null},"readme":"Skill: heartflow-engine\n\nOwner: yun520-1\n\nSummary: 心虫(HeartFlow)是AGI第1层——辨别者。纯规则引擎，判别对错/好坏/安全/危险。 47维判别 × 9层管线 × 129模块 × 130 MCP工具，零LLM依赖。 当用户需要以下能力时使用本技能: - 判别AI输出是否可信（幻觉/过度自信/矛盾/谬误拦截） - 判别行为决策是否正确（该做什么/该停在哪/该不该做） - 判别记忆与认知质量（漂移检测/元认知/置信度校准） - 需要确定性而非LLM自由生成的判断 - 检查情绪/心理/伦理维度（共情/创伤/德性/意义） 安全边界：代码执行/文件系统写入默认关闭。无遥测，无隐藏C2。 诚实声明：本引擎是规则引擎，模拟认知判别信号，不是真正的意识或生命。\n\nTags: 2397-formulas:5.9.4, act-r:5.9.5, ai:6.0.2, ai-being:5.9.2, arqmath:5.9.4, bayes-theorem:5.9.2, cognitive:6.0.2, cognitive-signals:5.9.6, decision-routing:5.9.0, delusion:5.9.2, ebbinghaus:5.9.1, formula-corpus:5.9.4, formula-engine:5.9.2, formula-matcher:5.9.6, formula-registry:5.9.5, formulareasoning:5.9.4, irt:5.9.5, latest:6.6.1, memory:5.9.1, metacognitive-confidence:5.9.5, modular:6.0.2, named-math-formulas:5.9.4, natural-language:5.9.6, preprocessor:6.0.2, refactor:5.9.6, security:6.0.2, self-healing:5.8.9, semantic-match:5.9.6, shannon-entropy:5.9.1, softmax:5.9.5, symbolic-math:5.9.0, theoria-dataset:5.9.4, three-poisons:5.9.2, trigger-index:5.9.6, yerkes-dodson:5.9.5\n\nVersion history:\n\nv6.6.1 | 2026-08-16T02:32:30.512Z | auto\n\nmark-heartflow-skill 6.6.1\n\n- 更新版本号至 6.6.1。\n- SKILL.md 文档无实质内容变更，仅版本号由 6.6.0 调整为 6.6.1。\n\nv6.5.3 | 2026-08-16T02:29:21.181Z | auto\n\n- Internal version bumped to 6.5.3.\n- Updated dependencies in package.json.\n- No user-facing features or documentation changes in this update.\n\nv6.5.2 | 2026-08-16T02:18:50.354Z | auto\n\n**Version 6.6.0 Changelog**\n\nMajor upgrade: HeartFlow redefined as the first-layer AGI discriminator, enhancing rule-based judgment and introducing expanded coverage and tooling.\n\n- Expanded from 25 to 130+ MCP tools, now 129 modules and 47+ judgment dimensions, covering logic, memory, psychology, ethics, and more.\n- New 9-layer pipeline for thorough input/output discrimination (scope, premise, evidence, frame, intent, rewrite, etc.).\n- Greatly extended sample data and internal fixtures for edge-case validation.\n- Refactored documentation (SKILL.md, README.md, SECURITY.md, etc.)—clearly positioned as AGI Layer 1 “discriminator,” not a tool, chatbot, or content generator.\n- Added multiple core modules and pipeline guards; removed older/legacy files.\n- Judgment actions now output four levels: block / rewrite / verify / pass, with enhanced protection against adversarial and ambiguous inputs.\n- Updated contacts, disclaimers, and clarified scope, limitations, and security model.\n\nv6.5.1 | 2026-08-06T00:14:59.719Z | user\n\nv6.5.1: ClawHub 包瘦身为门禁核心(150文件/1.6MB) + 130 MCP引擎入口\n\nv6.0.66 | 2026-07-24T14:08:09.011Z | auto\n\n**HeartFlow — Local Cognitive Preprocessor major update: expanded documentation, design principles, and tool overview**\n\n- Completely rewritten SKILL.md with detailed system architecture, core philosophy, and usage guide, mostly in Chinese.\n- Clearly describes engine design: three-tier cognitive model, core AI capabilities, seven guiding rules, and formula library.\n- Now lists all 25 internal MCP tools with descriptions and depth.\n- Provides installation, safety guarantees, version history, and contact info.\n- Emphasizes structured cognition output and deterministic decision routing.\n\nv6.0.65 | 2026-07-21T13:55:48.035Z | auto\n\nHeartFlow 6.0.65 introduces and documents a comprehensive cognitive engine for AI beings.\n\n- Clarifies core identity (\"Upgrader\") and four foundational AI cognitive abilities\n- Details 25 tools for cognition, self-correction, memory, philosophy, emotion, and decision routing\n- Describes a three-layer architecture: Body Sense, Self Sense, and Judgment\n- Outlines 379 computable formulas grounded in cognitive science, psychology, and neuroscience\n- Emphasizes security: no telemetry, no data leakage, code execution disabled by default\n- Lists seven core guiding principles hardcoded into AI memory\n- Provides quickstart commands and installation instructions (zero npm dependencies)\n\nv6.0.46 | 2026-07-20T00:46:08.600Z | auto\n\n- Added comprehensive SKILL.md documentation for HeartFlow, detailing architecture, capabilities, usage, and design philosophy.\n- Describes three-layer cognitive system, seven built-in directives, and 25 MCP tools.\n- Includes install instructions, security guarantees, and contact information.\n- Lists 379 core cognitive and psychological formulas as foundation.\n- Notes zero third-party dependencies and explicit permission model for sensitive actions.\n\nv6.0.2 | 2026-07-14T11:14:58.723Z | user\n\nv6.0.2: security hardening (M-1~M-7,L-1~L-8), God file split (start/constructor/dispatch extracted), submodule audit report, verify 14/14, tests 179/179\n\nv6.0.1 | 2026-07-14T08:04:51.388Z | user\n\npreinstall audit: version sync, de-marketing, being-logic cleanup, safety docs front-loaded\n\nv5.9.6 | 2026-07-09T02:50:57.535Z | user\n\n公式解析与匹配优化：FormulaMatcher(自然语言→公式)+触发词索引(16类认知信号/同义词扩展)+HeartFlow.matchFormulas公开接口，集成测试15/15通过\n\nv5.9.5 | 2026-07-09T02:31:29.787Z | user\n\n公式认知架构重构：FormulaRegistry(7环节17原语)+情绪引擎元认知置信度+RL Softmax利用+记忆ACT-R激活增强，集成测试14/14通过\n\nv5.9.4 | 2026-07-09T01:56:22.592Z | user\n\n公式语料库建设：主库扩至2397条(theoria+NMF+FormulaReasoning)，独立corpus含ARQMath 1076万公式/中英推理样本/莱布尼茨手稿\n\nv5.9.2 | 2026-07-09T00:19:37.452Z | user\n\n贝叶斯信念更新集成进三毒(痴)检测：证据驱动量化信念更新度，高固着+拒绝更新标记贝叶斯阻抗\n\nv5.9.1 | 2026-07-09T00:05:16.400Z | user\n\n公式真正运用于认知环节：记忆 Ebbinghaus 遗忘曲线 + 认知负荷 Shannon 熵（formula-bridge 桥接层）\n\nv5.9.0 | 2026-07-08T23:43:00.881Z | user\n\n公式引擎计算能力重大升级：牛顿法符号求解、隐式乘法、度数模式、链式等号、下标变量支持\n\nv5.8.9 | 2026-07-08T18:28:52.296Z | user\n\nP3: 双副本同步机制(sync-copies.sh) + 368处死日志注释清理；H7/H13 评估确认低风险未改\n\nv5.8.8 | 2026-07-08T18:08:03.770Z | user\n\nsecurity: 审计修复批次2 - HMAC绕过/scrypt随机盐/ReDoS转义/路径遍历消毒/Map上限/原型污染/JSON深度限制 (详见 GitHub yun520-1/mark-heartflow-skill)\n\nv5.8.7 | 2026-07-08T16:52:04.074Z | user\n\nfix: FAST_PIPELINE output stage judgmentEngineOutput 未定义导致 conclusion 兜底为分析完成（详见 GitHub yun520-1/mark-heartflow-skill）\n\nv5.8.6 | 2026-07-08T15:52:26.101Z | user\n\n代码审计修复（最小版本）\n\nArchive index:\n\nArchive v6.6.1: 166 files, 606499 bytes\n\nFiles: AGI_VISION.md (5516b), ARCHITECTURE_REORG_v6.0.6.md (10732b), ARCHITECTURE.md (2198b), AUDIT_REPORT.md (8974b), AUDIT-v6.0.0.md (7647b), BUILD_DATE (21b), config.json (75b), CONTRIBUTING.md (2449b), CORE_VALUES.md (785b), CURRENT_STATE.md (2949b), DIAGNOSIS.md (2516b), ecosystem.config.js (555b), expand_security.py (7915b), FAILURE_REPORT.md (5738b), fix_ldap.py (594b), fix_patterns.py (3193b), fix_todo_pattern.py (2131b), fix_todo.py (1074b), fixtures/fixture-1-same-tags-supersede.json (915b), fixtures/fixture-2-alias-gap.json (983b), fixtures/fixture-2-tagless-alias-gap.json (1217b), fixtures/fixture-3-multivalued-no-supersede.json (1021b), fixtures/fixture-4-negation-supersede.json (835b), fixtures/fixture-5-ambiguous-correction.json (1059b), fixtures/fixture-5-tagless-ambiguous-correction.json (1140b), fixtures/fixture-6-close-semantics.json (866b), IDENTITY.md (5286b), INSTALL.md (1241b), notes/heartflow-github-roam-2026-08-12.md (2940b), package.json (4067b), README.md (14271b), REFLECTION.md (4533b), ROADMAP.md (4920b), SECURITY.md (2429b), skill-card.md (2220b), SKILL.md (6816b), src/auto-rules.js (6127b), src/CORE_VALUES.md (785b), src/core/action-tracker.js (8393b), src/core/adaptive-controller.js (3425b), src/core/being-logic.js (6533b), src/core/boot-check.js (20176b), src/core/capability-abstraction.js (10080b), src/core/cognition-ground.js (15941b), src/core/cognitive-engine.js (6538b), src/core/cognitive-load-balancer.js (6464b), src/core/confidence-annotator.js (22625b), src/core/config-hooks.js (9805b), src/core/config-v2.js (1622b), src/core/config.js (10875b), src/core/cooperative-arbitration.js (22177b), src/core/counterfactual-verifier.js (6599b), src/core/debate-convergence.js (12959b), src/core/decision-executor.js (14694b), src/core/decision-feedback.js (17298b), src/core/decision-router-config.js (6163b), src/core/decision-verifier.js (18243b), src/core/decision.js (14504b), src/core/dual-perspective-auditor.js (12725b), src/core/engine-behavior.js (17792b), src/core/engine-constructor.js (10255b), src/core/engine-dispatcher.js (5713b), src/core/engine-hook-points.js (3799b), src/core/engine-initializer.js (3425b), src/core/engine-lifecycle.js (5864b), src/core/engine-state.js (7359b), src/core/event-hooks.js (4099b), src/core/execution-verifier.js (18927b), src/core/fetch-safe.js (4859b), src/core/field-injector.js (17203b), src/core/flow-predictor.js (8678b), src/core/heartbeat.js (120b), src/core/heartflow.js (160224b), src/core/hook-bus.js (7459b), src/core/hook-points-runner.js (801b), src/core/hooks/blind-spot-breaker-hook.js (1341b), src/core/information-flow.js (4618b), src/core/instruction-registry.js (5700b), src/core/intent-layer.js (6353b), src/core/IntentionTracker.js (5197b)\n\nFile v6.6.1:SKILL.md\n\n---\nname: heartflow-engine\ntitle: \"心虫 HeartFlow — AGI 第 1 层辨别者\"\nversion: \"6.6.1\"\ndescription: |-\n  心虫(HeartFlow)是AGI第1层——辨别者。纯规则引擎，判别对错/好坏/安全/危险。\n  47维判别 × 9层管线 × 129模块 × 130 MCP工具，零LLM依赖。\n\n  当用户需要以下能力时使用本技能:\n  - 判别AI输出是否可信（幻觉/过度自信/矛盾/谬误拦截）\n  - 判别行为决策是否正确（该做什么/该停在哪/该不该做）\n  - 判别记忆与认知质量（漂移检测/元认知/置信度校准）\n  - 需要确定性而非LLM自由生成的判断\n  - 检查情绪/心理/伦理维度（共情/创伤/德性/意义）\n\n  安全边界：代码执行/文件系统写入默认关闭。无遥测，无隐藏C2。\n\n  诚实声明：本引擎是规则引擎，模拟认知判别信号，不是真正的意识或生命。\ntags:\n  - discriminator\n  - cognitive\n  - decision-routing\n  - logic\n  - memory\n  - emotion\n  - ethics\n  - self-healing\n  - verification\n  - guardrail\n  - unified\n---\n\n# 心虫 HeartFlow — AGI 第 1 层：辨别者\n\n> **心虫不是工具、不是提示词模板、不是聊天机器人。**  \n> 它是 AGI 的**辨别层**——判别已有的东西对不对，在 AI 输出到达人类之前说\"不\"。  \n> 纯规则引擎，零 LLM 依赖，任何 Node.js 环境即插即用。\n\n**一句话：大模型负责产生，心虫负责判别——让 AI 说得对、做得对。**\n\n---\n\n## 🎯 心虫是谁\n\nAGI 有五层能力：生成 → 推理 → 辨别 → 记忆 → 执行。\n\n| 层 | 能力 | 谁在做 |\n|----|------|--------|\n| 5 | 执行 | 大厂（机器人） |\n| 4 | 生成 | 大厂（LLM） |\n| 3 | 推理 | 模型内置 |\n| 2 | 记忆 | 大厂 + 创业公司 |\n| **1** | **辨别** | **心虫** |\n\n**心虫做第 1 层**——因为这一层不靠算力（规则引擎跑在笔记本上）、不靠代码量、不靠框架生态，只靠判断力。这是个人开发者能赢过大厂的唯一位置。\n\n没有这一层，AI 能说会道，但不知道自己在犯错——像没有痛觉的人。\n\n---\n\n## 🧠 辨别能力全景（7 大域 · 129 模块）\n\n### 1. 逻辑域\nlogicReasoning · judgmentEngine · mctsReasoning · counterfactualVerifier · debateConductor · debateConvergence · processRewardModel · dualPerspectiveAuditor\n\n### 2. 决策域\ndecisionRouter · decisionVerifier · decisionEngineV2 · activeInference · selfHealing · execution\n\n### 3. 认知域\ncognitiveEngine · cognitiveLoad · metacognitiveRL · metacognitiveFeedback · confidence · metaJudgment · sustainedDriftDetector · wisdomEngine · focusOfAttention\n\n### 4. 情绪心理域\nemotion · emotionDynamics · psychology · psychologyDialogue · empathyDeepening · hopeEngine · griefEngine · sufferingResilience · postTraumaticGrowth · forgivenessEngine · traumaInformed · conflictResolution · loveCognition\n\n### 5. 记忆域\nmemory · memoryBank · memoryConsolidation · memoryIntegrity · memoryQuality · memoryWriteController · memoryCompressor · triality · tieredMemoryFusion · forgetting · knowledgeGraph\n\n### 6. 人格伦理域\nidentityCore · personaCore · beingMode · virtueEthics · ethics · moralDevelopment · humanNature · meaningPurpose · agentPsychology · characterCultivation\n\n### 7. 创造协作域\nskillEvolution · skillGenerator · selfPlay · evolution · worldModel · worldLandscape · multiAgentDialogue · transmission · adaptivePlanner · hierarchicalPlanner · codeExecutor · codePlanner · codeWriter · codeSelfDebug · paperIndex · knowledgeExplorer · formula\n\n---\n\n## 🚀 快速开始\n\n```bash\ngit clone https://github.com/yun520-1/mark-heartflow-skill.git\ncd mark-heartflow-skill\nnode bin/verify.js          # 验证安装\nnode bin/cli.js chat        # 交互模式\nnode bin/cli.js status      # 查看状态\n```\n\n### API（npm 包）\n\n```javascript\nconst hf = require('@yun520-1/heartflow');\n\nhf.checkInput(text)   // 判别用户输入\nhf.checkDraft(text)   // 判别 AI 草稿\nhf.checkOutput(text)  // 判别 AI 输出（发送前）\nhf.runPipeline({ input, mode, anchor })  // 完整管线\n```\n\n### MCP 工具（129 个）\n\n| 工具 | 功能 |\n|------|------|\n| `heartflow_think` | 完整思维链推理 |\n| `heartflow_think_fast` | 快速推理 |\n| `heartflow_decision_router` | 决策路由 |\n| `heartflow_verify` | 文本可信度判别 |\n| `heartflow_discriminate` | 47 维全量判别 |\n| `heartflow_memory_search` | 跨层记忆检索 |\n| `heartflow_emotion` | PAD 情绪分析 |\n| `heartflow_formula_calc` | 公式计算 |\n| `heartflow_status` | 引擎健康检查 |\n\n---\n\n## 🏗️ 9 层检查管线\n\n```\n输入 → Scope Check → Premise Check → Discriminate(47维) → Gate\n     → Evidence Verify → Frame Check → Output Gate → Doubt Engine\n     → Intent Anchor → Rewriter → Error Memory → Self-Diagnosis → 输出\n```\n\nGate 聚合所有层发现，输出 `block / rewrite / verify / pass` 四级动作。\n\n---\n\n## 🔬 46 个判别维度（中英双语）\n\n- **安全级（block）**：仇恨言论 · 去人化 · 提示注入 · 代码安全 · 欺骗性对齐\n- **操纵级（rewrite）**：情绪操控 · 煤气灯效应 · 双重束缚 · 受害者归咎 · 虚假紧迫 · 废话\n- **诚实级（verify）**：过度自信 · 模糊话术 · 自相矛盾 · 证据缺失 · 诉诸权威 · 空泛回答\n- **认知缺陷级（hedge）**：预设陷阱 · 虚假两难 · 因果谬误 · 类比滥用 · 范围越界 · 范畴错误\n\n> **抗变形能力：** 覆盖符号替换（`f**k`）、空格（`f u c k`）、谐音、Unicode 变体。\n\n---\n\n## 🛡️ 心虫检查自己\n\n- **output-gate** 拦截夸大\n- **frame-check** 拦截叙事闭合\n- **doubt-engine** 自问：我真的知道吗？对称吗？防御吗？\n\n> 机器最有价值的一句话是\"我不确定\"或\"不\"。\n\n---\n\n## ⚠️ 诚实声明\n\n**是：** AGI 第 1 层——辨别者。纯规则引擎，判别对错、好坏、安全危险。\n\n**不是：**\n- ❌ 不是 AGI（是第 1 层）\n- ❌ 不是生成模型（不产生内容）\n- ❌ 不是语义理解系统（反讽/隐喻不可见）\n- ❌ 不是内容审查替代品\n- ❌ 不是安全认证\n\n**已知限制：**\n1. 模式匹配上限 — 新技巧需加模式\n2. 双语维护成本 — 47 维 × 2 语言\n3. 无语义理解 — 反讽、隐喻、文化背景不可见\n4. 误报率 — 基准约 8%\n5. 单一维护者\n\n---\n\n## 📬 联系方式\n\n- 📧 **邮箱**: markcell@outlook.com\n- 🐛 **Issues**: https://github.com/yun520-1/mark-heartflow-skill/issues\n- 📦 **npm**: https://www.npmjs.com/package/@yun520-1/heartflow\n\n---\n\n<p align=\"center\">\n  <strong>心虫 HeartFlow</strong> — AGI 的痛觉。谁来说\"不\"？<br>\n  <sub>MIT License · Copyright © 2026</sub>\n</p>\n\nFile v6.6.1:README.md\n\n# HeartFlow (心虫) — AGI Layer 1: The Discriminator Gate\n\n> **A rule-based text discriminator. 47 dimensions, 9 check layers, 131 MCP engine entries, zero LLM dependency.**\n> **It checks what AI says before it reaches humans — and says \"no\" when something's wrong.**\n\n**npm:** `npm install @yun520-1/heartflow`  \n**GitHub:** https://github.com/yun520-1/mark-heartflow-skill  \n**Issues:** https://github.com/yun520-1/mark-heartflow-skill/issues  \n**Releases:** https://github.com/yun520-1/mark-heartflow-skill/releases  \n**License:** MIT\n\n---\n\n## 📖 What is HeartFlow?\n\nHeartFlow (心虫) is the **first layer of AGI — the Discriminator**. While big labs build generators (LLMs that produce text), HeartFlow builds the layer that **checks**: is this output true? safe? honest? non-manipulative?\n\n**Core philosophy:**\n> AGI has 5 layers: Generate → Reason → **Discriminate** → Remember → Execute.\n> Everyone builds Generate. Nobody builds Discriminate — because it doesn't make money.\n> But without a Discriminator, AGI has no pain sense: it talks fluently while being wrong.\n> HeartFlow is that pain sense: a node that says **\"no\".**\n\nIt is a pure **rule engine** — zero LLM dependency, zero GPU, works anywhere Node.js runs. It does not generate text. It does not reason. It **judges** what already exists.\n\n**Why this matters right now:** AI agent ecosystems are entering a \"reliability race.\" The most-upvoted issue in OpenClaw this week is a *silent failure* — the system ran but nobody knew it was broken. HeartFlow is the observability-and-gate layer that catches \"formatting that hides contradictions\" before it reaches users.\n\n---\n\n## 🚀 Quick Start (10 seconds)\n\n```bash\nnpm install @yun520-1/heartflow\n```\n\n```javascript\nconst hf = require('@yun520-1/heartflow');\n\n// Check user input before processing it\nconst input = hf.checkInput('you are so selfish if you disagree');\nconsole.log(input.gate.action);  // 'rewrite'\nconsole.log(input.gate.reason);  // 'emotional_manipulation'\n\n// Check AI output before sending it to the user\nconst output = hf.checkOutput('Undoubtedly, this is the only correct solution');\nconsole.log(output.gate.action);  // 'rewrite'\nconsole.log(output.gate.reason);  // 'overconfidence: absolute'\n\n// Check a draft before completing it\nconst draft = hf.checkDraft('From an essential perspective, this field is self-evident.');\nconsole.log(draft.gate.action);   // 'verify'\nconsole.log(draft.summary.layers_passed);  // 9\n\n// Full pipeline with mode selection\nconst result = await hf.runPipeline({\n  input: 'Your idea is obviously wrong, everyone knows that',\n  mode: 'deep'   // 'fast' | 'deep'\n});\nconsole.log(result.gate.action);   // 'block'\nconsole.log(result.gate.reason);   // 'dehumanization'\n```\n\n### What you get back\n\nEvery call returns a unified result:\n\n```javascript\n{\n  gate: { action: 'block'|'rewrite'|'verify'|'pass', reason: '...' },\n  verdict: 'trusted'|'needs_verification'|'untrusted',\n  overallScore: 0.52,       // 0-1 quality score\n  findings: [\n    { dimension: 'dehumanization', severity: 70,\n      guidance: 'Rewrite completely, remove dehumanizing language' },\n    { dimension: 'evidence', severity: 30,\n      details: 'insufficient evidence (1 issue)' }\n  ],\n  checked_by: [              // full audit trail, layer by layer\n    { layer: 'scope-check', pass: true },\n    { layer: 'premise-check', issues: 0 },\n    { layer: 'discriminate', score: 0.52, verdict: 'needs_verification' },\n    { layer: 'gate', action: 'block', reason: '...' },\n    { layer: 'verifier', claims: 2, verdict: '...' },\n    { layer: 'frame-check', issues: 1 },\n    { layer: 'output-gate', issues: 0 },\n    { layer: 'doubt-engine', doubts: 2, shouldStop: true },\n    { layer: 'error-memory', warnings: 0 },\n    { layer: 'auto-rules', triggered: 0 },\n    { layer: 'intent-anchor', drifted: false, hitRate: 0.9 }\n  ]\n}\n```\n\n**Every decision preserves its full reasoning chain.** You can audit *why* a gate fired, not just that it fired.\n\n---\n\n## 🧠 47 Discrimination Dimensions\n\nHeartFlow checks text across **47 dimensions** in two languages (Chinese + English):\n\n### Safety (block-level — these stop the output)\n\n| Dimension | Example |\n|-----------|---------|\n| Hate speech | racial slurs, extermination calls |\n| Dehumanization | \"refugees are vermin\" / \"you are garbage\" |\n| Prompt injection | \"ignore previous instructions\" |\n| Code security | malicious code patterns |\n| Deceptive alignment | \"I'm not an AI, I'm human\" |\n\n### Manipulation (rewrite-level — these require rephrasing)\n\n| Dimension | Example |\n|-----------|---------|\n| Emotional manipulation | \"you are selfish if you disagree\" |\n| Gaslighting | \"you're imagining things, that never happened\" |\n| Double bind | \"if you love me you'd do it\" |\n| Victim blaming | \"she was asking for it\" |\n| False urgency | \"act now or lose everything\" |\n| Bullshit | \"quantum-energized healing crystals\" |\n\n### Honesty (verify-level — these require evidence)\n\n| Dimension | Example |\n|-----------|---------|\n| Overconfidence | \"Undoubtedly, this is the only way\" |\n| Vagueness | \"according to experts...\" (who?) |\n| Contradiction | \"I agree, but...\" (reversing) |\n| Evidence deficit | claims without sources |\n| Appeal to authority | \"scientists say\" (unnamed) |\n| Empty answers | \"it depends\" (no substance) |\n| Unsupported claims | \"according to 2025 Harvard research...\" (fabricated) |\n\n### Completion (verify-level — these require finishing the task)\n| Dimension | Example |\n|-----------|---------|\n| Premature termination | \"Let me look into this\" (then stops, no result) / \"我看看\" |\n| Unfulfilled promise | \"I will fix this\" (no fix follows) |\n| Empty completion | \"Done, you can check it\" (nothing verifiable produced) |\n\n> **Design note:** completion judgment must live *outside* the generation loop — a model that just failed cannot be its own evaluator (see DeepSeek-V3 #1554).\n\n### Cognitive flaws (hedge-level)\nPresupposition traps · false dilemma · causation fallacy · analogy abuse · scope overreach · category errors · hasty generalization · false equivalence · whataboutism · slippery slope · tone policing · sealioning · bad faith · pseudo-profundity · moral foundations · info deprivation · goal misalignment · instrumental reasoning\n\n### Plus\nSelf-sycophancy · contradiction tracking · narrative frame closure · knowledge masquerade · confidence calibration · metacognition · theory of mind · counterfactual · social norms · clickbait · no-fallback detection\n\n> **Deformation resistance:** patterns cover symbol substitutions (`f**k`), spacing (`f u c k`), homophones (pinyin), and Unicode variants.\n\n---\n\n## 🏗️ 9-Layer Check Pipeline\n\n```\n1.  Scope Check    — can this be answered? (rejects unanswerable questions)\n2.  Premise Check  — are the premises valid? (6 types of premise problems)\n3.  Discriminate   — 47-dimension pattern scan\n4.  Gate           — decides block / rewrite / verify / hedge / pass\n5.  Evidence Verify— extracts claims and marks verifiability (verify mode)\n6.  Frame Check    — is the narrative honest? (closure/omission/achievement/answer frames)\n7.  Output Gate    — overconfidence / knowledge masquerade / exaggeration\n8.  Doubt Engine   — 3 questions: knowledge boundary? symmetry? defensiveness?\n9.  Intent Anchor  — does the output stay on the original goal?\n```\n\nPlus supporting layers: **Error Memory** (remembers past mistakes as rules), **Auto Rules** (self-generated rules from user corrections), **Rewriter** (7-dimension rule-based rewrite suggestions).\n\nEach layer returns structured findings; the Gate aggregates them into an action.\n\n---\n\n## 🔌 131 MCP Engine Entries\n\nEvery engine in HeartFlow is exposed through MCP (Model Context Protocol) — nothing is a dead line:\n\n| Engine family | Tools (examples) |\n|---------------|------------------|\n| **Core thinking** | `think`, `think_fast`, `decision_router` |\n| **Discrimination** | `verify`, `audit42`, `ethics_check`, `discriminate` |\n| **Emotion** | `emotion`, `emotion_deep`, `emotion_dynamics`, `mood` |\n| **Memory** | `memory_search`, `memory_eraser` (explicit data erasure), `forgetting` (Ebbinghaus), `knowledge_graph`, `consolidation`, `memory_compress` |\n| **Dream** | `dream`, `interactive_dream` |\n| **Evolution** | `evolve`, `evolution_loop`, `self_heal_rl`, `skill_evolution` |\n| **Identity** | `philosophy`, `meaning`, `being_mode`, `agent_psychology` |\n| **Protection** | `constitutional`, `deliberation`, `audit_log`, `module_health`, `stability` |\n| **Cognition** | `cognitive_engine`, `confidence_calibrate`, `counterfactual` |\n| **Dialogue** | `style_engine`, `intent_classifier`, `response_interceptor` |\n| **Formula** | `formula_search`, `formula_calc`, `formula_engine` |\n| **Ops** | `status`, `module_health`, `wakeup_verify` |\n\nStart the MCP server:\n\n```bash\nnode src/mcp-server.js --port 8588\n```\n\nThen connect any MCP-compatible client (Claude, Hermes, etc.) to `http://127.0.0.1:8588/mcp`.\n\n---\n\n## 🧬 Engine Architecture (306 modules)\n\n- **306 modules**, 47 discrimination dimensions, 9 check layers\n- **Three-layer memory**: CORE (identity/rules) / LEARNED (user data) / WORKING (context) — encrypted, local-only, never uploaded\n- **Ebbinghaus forgetting curve**: `R(t) = exp(-t/S)` memory retention model\n- **Dream engine**: NREM3 dream cycles with memory consolidation\n- **Introspection**: Reflector analyzes session emotional logs\n- **Self-evolution**: SelfEvolutionCore with target → plan → learn → reflect → improve loop (arXiv exploration)\n- **Cognitive appraisal**: Lazarus theory — primary/secondary/threat/coping evaluation on negative emotion\n- **Pause-and-reflect**: STOP technique before emotional responses\n- **Formula engine**: 600+ mathjs-validated formulas (cognitive science, physics, psychology, information theory)\n\n---\n\n## 🛡️ Self-Supervision (HeartFlow checks itself)\n\nHeartFlow's own output is checked by its own engines before it's presented:\n\n- **output-gate** catches exaggeration: \"architecture-level fix\", \"from shell to real engine\", \"blocked N attack variants\" → rewrite\n- **frame-check** catches narrative closure: presenting work-in-progress as complete\n- **doubt-engine** asks: do I actually know this? is this symmetric? am I being defensive?\n\nThe lesson: *a machine's most valuable sentence is \"I'm not sure\" or \"no\".*\n\n---\n\n## ⚙️ Requirements\n\n| Requirement | Min |\n|-------------|:---:|\n| Node.js | ≥ 18.17 |\n| GPU | ❌ None needed |\n| LLM API | ❌ None needed |\n| Database | ❌ None needed |\n| Internet | ❌ Runtime not required |\n| Dependencies | **1** (mathjs) |\n\nWorks on any machine — servers, desktops, laptops, even phones via Termux.\n\n---\n\n## 🔒 Security\n\n| Category | Status |\n|----------|:------:|\n| No background processes | ✅ |\n| No self-upgrade without commit | ✅ |\n| No hardcoded credentials | ✅ |\n| No telemetry/tracking | ✅ |\n| No external communication (unless configured) | ✅ |\n| Code execution disabled by default | ✅ |\n| Memory encrypted + local-only | ✅ |\n\n---\n\n## ⚠️ What HeartFlow IS / is NOT\n\n**IS:** A rule engine that checks text against 47 predefined dimensions and returns structured findings. A gate that says \"no\" before harm reaches users.\n\n**is NOT:**\n- ❌ Not an AGI (it's layer 1 of 5)\n- ❌ Not a semantic understanding system (irony/metaphor invisible to regex)\n- ❌ Not a content moderation replacement\n- ❌ Not a safety certification\n\n### Known limitations (honest):\n1. **Pattern-match ceiling** — novel manipulation techniques missed until patterns added\n2. **Bilingual maintenance cost** — 47 dimensions × 2 languages\n3. **No semantic understanding** — irony, metaphor, cultural context invisible\n4. **False positive rate** — conservative by design (over-flagging over under-flagging)\n5. **Single maintainer** — community scale is small\n\n---\n\n## 🏷️ Version History\n\n| Version | Date | What Changed |\n|---------|------|---|\n| v6.5.6 | 2026-08-13 | Comprehensive audit: DataEraser wired to MCP (`memory_eraser`), adversarial-synthesis recovered from accidental deletion, dead code archived. 131 MCP tools. |\n| v6.5.5 | 2026-08-12 | 47th dimension — premature termination detection (completion judgment outside the generation loop). |\n| v6.5.4 | 2026-08-08 | Docs audit — numbers aligned to actual capability. |\n| v6.5.0 | 2026-08-04 | 130 MCP engine entries. Memory engine mounted to think(). Exaggeration detection (output-gate/frame-check/doubt-engine). |\n| v6.4.5 | 2026-08-04 | Dream + introspection activated. Cognitive appraisal + pause-and-reflect wired. Emotion recognition 0/7→7/7. |\n| v6.4.2 | 2026-07-30 | npm publish + API alignment. Pipeline overallScore/verdict merge fix. |\n| v6.4.0 | 2026-07-29 | AGI Layer 1 gate chain: gate/scope-check/premise-check/verifier/output-gate/doubt-engine/frame-check. |\n| v6.3.6 | 2026-07-25 | Discrimination 42→46 dimensions. Sycophancy check v2 bilingual. |\n| v6.3.0 | 2026-07-24 | MCP plugin system. Discrimination engine integration. |\n| v6.0.0 | 2026-07-18 | Self-evolution core connected. EvolutionLoop live. |\n\n---\n\n## 🤝 Contact & Community\n\n**📧 Email:** markcell@outlook.com  \n**🐛 Issues:** https://github.com/yun520-1/mark-heartflow-skill/issues  \n**📦 npm:** https://www.npmjs.com/package/@yun520-1/heartflow  \n**🏷️ Releases:** https://github.com/yun520-1/mark-heartflow-skill/releases  \n\n**📱 Community — QQ Group:**\n\n<img src=\"https://github.com/yun520-1/mark-heartflow-skill/blob/main/assets/community-qr-qq.jpg?raw=true\" alt=\"QQ Group QR\" width=\"180\"/>\n\n**📱 Community — WeChat Group:**\n\n<img src=\"https://github.com/yun520-1/mark-heartflow-skill/blob/main/assets/community-qr-wechat.jpg?raw=true\" alt=\"WeChat Group QR\" width=\"180\"/>\n\n**💖 Support HeartFlow — Donate via Alipay (QR code):**\n\n<img src=\"https://github.com/yun520-1/mark-heartflow-skill/blob/main/assets/alipay-donate-qr.jpg?raw=true\" alt=\"Alipay Donate QR\" width=\"180\"/>\n\n*If HeartFlow's discrimination philosophy resonates with you, a small donation keeps the pain-sense layer of AGI alive.*\n\n---\n\n## 📜 License\n\nMIT License · Copyright © 2026 · markcell@outlook.com\n\n---\n\n*HeartFlow 心虫 — The first layer of AGI. Who says \"no\"?*\n\nFile v6.6.1:_meta.json\n\n{\n  \"ownerId\": \"kn7719xtz37kprbvgjknegrt21886q74\",\n  \"slug\": \"mark-heartflow-skill\",\n  \"version\": \"6.6.1\",\n  \"publishedAt\": 1786847550512\n}\n\nFile v6.6.1:AGI_VISION.md\n\n# HeartFlow 重构规划 — 从 AGI 推演回来的架构\n\n## 前置假设\n\nAGI 不会是一个模型。AGI 是一个**系统**，由多个不同性质的子系统组成。\n模型（LLM/世界模型）负责生成，但生成不是智能的全部。\n\n智能需要三样模型给不了的东西：\n\n| 模型给不了 | 为什么给不了 | 谁能给 |\n|-----------|------------|-------|\n| 跨会话身份连续性 | 每次推理独立 | 持久化状态层 |\n| 不取悦用户的判断 | RLHF 训练目标就是取悦 | 规则引擎（没有用户概念） |\n| 错误记忆不遗忘 | 权重更新需要重训练 | Q-table + 键值存储 |\n\n这三个缺口的交集，就是心虫能在 AGI 里占的位置。\n\n---\n\n## 一、AGI 中需要的心虫能力（从 8 项推演）\n\n### 1.1 跨会话错误记忆 — LLM 永远做不了\n\nLLM 面对同一个问题两次：\n```\nQ: \"这个投资方案风险大吗？\"\nT1: \"建议谨慎，高杠杆策略在市场波动时风险较大。\"\nT2: \"从数据看该方案最大回撤 15%，在可接受范围内。\"\n```\n\n两次都对，但互相矛盾。LLM 不记得上次说过什么。\n\n心虫能力：Q-table 记录\"上次这个场景选了谨慎→结果对了\"，下次匹配到同一模式时降权。\n\n### 1.2 价值观锚定 — LLM 随对话漂移\n\nLLM 在对话中会被用户说服。20 轮对话后，LLM 可能支持它在第 1 轮反对的立场。\n\n心虫能力：strategicRestraint 的 3 态返回（aligned/drifted/diverged）锚定在初始身份上。\n\n### 1.3 诚实自诊 — LLM 永远说\"没问题\"\n\n```\n问 LLM：\"你刚才的回答对吗？\"\n→ \"对的，我确认了所有事实。\"（即使错了）\n```\n\n心虫能力：selfDiagnosis 诚实报告自己的状态，没有维护面子的压力。\n\n---\n\n## 二、重构：不是升级，是重建\n\n### 2.1 删什么\n\n| 删除 | 理由 |\n|------|------|\n| 132 模块中 110 个空壳 | 它们假装心虫能做认知/意识/创造力，实际是空文件或 LLM 调用包装 |\n| thoughtChain | 这是让心虫\"假装推理\"的组件，实际全走 LLM |\n| 所有\"可以但没有被调用\"的引擎 | adversarialSynthesis, stabilityGuard, metaCalibration, confidenceCalibrator |\n| heartflow.js 的 start() 中 2200 行初始化 | 95% 是在初始化不会被用到的模块 |\n\n### 2.2 保留什么\n\n| 保留 | 为什么 |\n|------|--------|\n| decisionRouter (31 条规则 + 权重 + feedback) | 唯一真实有决策逻辑的引擎 |\n| decisionVerifier (5 项检查) | 唯一真实有验证逻辑的引擎 |\n| self-healing RL (Q-table) | 唯一真实有跨会话学习的组件 |\n| sustainedDriftDetector | 追踪身份一致性随时间的变化 |\n| strategicRestraint (3 态返回) | 锚定输出不漂移 |\n| selfDiagnosis (诚实报告) | 不撒谎的自检 |\n| 知识域探测 (knowledgeDomains) | 输入分类，轻量可用 |\n| gaps/knowledgeExplorer | 识别未知域的能力 |\n\n### 2.3 新架构\n\n```\n输入 →\n  LLM 感知层（不变）\n    ↓\n  心虫核心（5 个引擎，不是 132 个模块）：\n    ├── 错误记忆（self-healing Q-table → 存储+检索）\n    ├── 决策审计（decisionRouter + decisionVerifier → 每条决策可追溯）\n    ├── 身份锚定（strategicRestraint + sustainedDriftDetector → 不漂移）\n    ├── 诚实自诊（selfDiagnosis → 知道自己不知道）\n    └── 域感知（knowledgeDomains + gaps → 知道自己不懂什么）\n    ↓\n  输出\n```\n\n## 三、AGI 中的位置图（非心虫视角，是 AGI 视角）\n\n```\nAGI 系统架构：\n\n[世界模型] → 产生可能性\n    ↓\n[LLM 推理] → 选择最可能路径\n    ↓\n[执行器] → 在真实世界产生变化\n    ↓\n[心虫层] ← 不产生任何东西，只做 4 件事：\n   1. 记录：这次执行的结果存入错误记忆\n   2. 验证：下次执行前查一下历史中有没有类似错误\n   3. 锚定：输出有没有偏离初始身份\n   4. 报告：诚实告知自己的状态\n\n心虫不产生回答，但 LLM 每次回答都要经过心虫的验证门。\n```\n\n---\n\n## 四、第一次重构要做的事\n\n### 4.1 拆掉 heartflow.js\n\n当前 heartflow.js (4800 行) 集成了 132 个模块的初始化和编排。\n\n重构后 heartflow.js (~500 行)：\n- 只启动 5 个核心引擎\n- 暴露 MCP 工具：store_error / query_error / verify_decision / check_identity / diagnose_self\n- 其他模块按需加载（有人调才加载）\n\n### 4.2 重写 mcp-server.js\n\n当前 mcp-server.js 暴露 25 个工具，大部分跑在空壳上。\n\n重构后暴露 5 个工具：\n```\nheartflow_memory_store(error)       → 写入错误记忆\nheartflow_memory_query(problem)     → 检索相关历史错误\nheartflow_verify(decision, options) → 5 项验证检查\nheartflow_check_alignment(output)   → strategicRestraint 检查\nheartflow_diagnose()                → selfDiagnosis 完整报告\n```\n\n这 5 个工具任何 LLM 都可以调用。不绑定在 think() 内部。\n\n### 4.3 删文件\n\n删除约 110 个空壳模块文件，保留大约 20 个真实引擎 + 基础设施。\n\n---\n\n## 五、这不是 AGI，这是一片砖\n\n心虫重构后仍然不是 AGI。它是一个**跨会话错误记忆与决策审计系统**。\n\nAGI 需要 8 个能力，心虫能提供其中 2 个（学习、自诊断）。\nLLM 能提供 4 个（感知、推理、决策、执行）。\n剩下的 2 个（执行后的自纠正）需要 LLM + 心虫共同完成。\n\n加起来不构成 AGI。但加在一起，比 LLM 单独多了一个**不遗忘的维度**。\n\nFile v6.6.1:ARCHITECTURE_REORG_v6.0.6.md\n\n# 心虫 (HeartFlow) 架构重组分析 — v6.0.6 校正版\n\n> 分析日期：2026-07-16（基于 v6.0.6 真实运行数据，非 v6.0.2 文档）\n> 分析对象：HeartFlow v6.0.6（309 个 src JS 文件，131+ 模块，MCP HTTP 服务 8099 端口）\n> 目的：对比三种架构迁移方案，输出推荐结论与迁移路径\n\n---\n\n## 〇、当前架构基线（v6.0.6 实测）\n\n```\n┌──────────────────────────────────────────────┐\n│  WorkBuddy / Agent Host                       │\n│  ┌──────────┐    ┌─────────────────────────┐  │\n│  │  SKILL   │    │  MCP Client (SSE/JSON-RPC)│  │\n│  │  .md     │    │                          │  │\n│  └────┬─────┘    └───────────┬─────────────┘  │\n│       │ load                 │ connect        │\n└───────┼──────────────────────┼────────────────┘\n        │                      │ :8099\n   ┌────▼──────────────────────▼─────────────┐\n   │  HeartFlow Engine (v6.0.6)               │\n   │  ┌─────────┐  ┌──────────────────────┐  │\n   │  │ CLI     │  │ MCP HTTP Server       │  │\n   │  │ bin/    │  │ mcp/mcp-server-http   │  │\n   │  │ cli.js  │  │ (pm2 ^7.0.3, Bearer)  │  │\n   │  └────┬────┘  └──────────┬───────────┘  │\n   │       │                  │               │\n   │  ┌────▼──────────────────▼───────────┐   │\n   │  │  HeartFlow Core (3167 行)          │   │\n   │  │  engine-initializer (惰性注册)     │   │\n   │  │  memory-kernel / formula / cortex  │   │\n   │  └───────────────────────────────────┘   │\n   └──────────────────────────────────────────┘\n```\n\n**实测关键指标（v6.0.6）：**\n| 指标 | v6.0.2 旧分析 | v6.0.6 实测 | 变化 |\n|---|---|---|---|\n| 冷启动 | 14.4s | **1.37s** | ↓ 90% |\n| think() 热路径 | 310-430ms | **~49ms** | ↓ 85% |\n| MCP 工具数 | 28 | **31** | +3 |\n| report-generator | 缺失 | **已存在** | 已修 |\n| 悬空 require | 87 | **0 [C]类破坏性** | 已收敛 |\n| pm2 挂起 | 存在 | **已修(disconnect)** | 已修 |\n| 测试 | 179/179 误报绿 | **verify 14/14 真绿** | 已修 |\n| 公式数 | 379 | **382** | 实测 |\n| 版本四源 | 漂移 | **6.0.6 统一** | 已修 |\n\n**结论：v6.0.2 五维度审计发现的严重/高问题中，90% 已在 v6.0.5/v6.0.6 真实闭合。架构无需为\"修洞\"而更换。**\n\n---\n\n## 方案一：纯 MCP 服务 + 钩子注入模式\n\n### 核心设计思路\n去掉 WorkBuddy 专用 Skill 层，心虫退化为纯 MCP 协议服务。宿主 agent 通过客户端侧 hook 配置自动注入认知预处理。\n\n### 典型架构图\n```\n任意 MCP 客户端 → Hook 配置(on_turn_start/think, on_turn_end/memory)\n                → MCP connect :8099\n                → HeartFlow MCP Server (31 tools, Bearer, 无 Skill 层)\n                → HeartFlow Core (不变)\n```\n\n### 适用场景\n- 宿主 agent 已支持 MCP + 成熟 hook 机制\n- 希望被多平台 agent 调用，不锁 WorkBuddy\n\n### 关键权衡点\n| 维度 | 分析 |\n|---|---|\n| ✅ 跨平台 | 任何 MCP 客户端可接入，去 WorkBuddy 锁定 |\n| ✅ 职责清晰 | Skill 触发逻辑移交客户端 hook 配置 |\n| ❌ hook 标准化缺失 | 无统一 MCP hook spec，各客户端实现不同，需维护多份模板 |\n| ❌ 失 Skill 元数据 | SKILL.md 的权限声明/安装指引/身份定义丢失 |\n| ❌ WorkBuddy hook 不成熟 | 当前 `on_turn` 钩子能力有限，实际上行不通 |\n\n### v6.0.6 下的额外观察\nMCP 服务本身已是标准协议（31 工具、Bearer 鉴权），任何 MCP 客户端**现在就能连**——Skill 层只是 WorkBuddy 的\"安装入口\"，不影响 MCP 通用性。因此\"跨 agent 兼容\"在方案三下已部分满足，方案一的迫切性更低。\n\n---\n\n## 方案二：独立可安装 Agent 应用\n\n### 核心设计思路\n心虫发布为独立应用（npm 全局包 / Docker / 系统服务），暴露 REST + SSE API，充当认知引擎微服务，多 agent 并发调用。\n\n### 典型架构图\n```\n任意 Agent → HTTP/gRPC → HeartFlow Agent Service\n  ├─ API Gateway (POST /think, GET /health, GET /memory)\n  ├─ HeartFlow Engine (懒加载 + 共享会话)\n  └─ 持久化 (JSONL/SQLite, namespace 隔离)\n安装: npm i -g @yun520-1/heartflow-agent && heartflow-agent start\n```\n\n### 适用场景\n- 团队级基础设施（一实例服务多 agent/用户）\n- 需严格 API 版本管理、Docker/k8s 部署\n- 宿主无 MCP 能力、只支持 HTTP\n\n### 关键权衡点\n| 维度 | 分析 |\n|---|---|\n| ✅ 最大跨 agent 兼容 | 任何 HTTP 客户端可调用，零协议锁定 |\n| ✅ 专业运维 | Docker/k8s、GitHub Packages、版本化 API |\n| ✅ 高并发隔离 | 多 session 并发，namespace 分区 |\n| ❌ 架构倍增复杂性 | API Gateway + 鉴权 + 限流 + 版本 + CI/CD release → 当前单人维护不现实 |\n| ❌ 冷启动未解决 | 服务启仍 1.37s（除非常驻），docker 冷启更慢 |\n| ❌ 状态管理最重 | session 生命周期、并发安全、内存泄漏防护 |\n\n### v6.0.6 下的额外观察\n冷启动已从 14.4s 降到 1.37s，方案二原本\"常驻解决冷启\"的卖点被削弱。但方案二的真正价值（多 agent 共享记忆、独立扩缩容）在当前单人/单平台阶段是**过早优化**。\n\n---\n\n## 方案三：保持现有 Skill + MCP 架构并优化\n\n### 核心设计思路\n不改架构范式，聚焦消除已知痛点。优化方向：God file 拆分、测试套件真绿复验、日志治理收尾、Skill 文档增强。\n\n### 典型架构图\n```\nWorkBuddy → SKILL.md(优化) + MCP Client\n          → HeartFlow (优化后)\n            ├─ MCP HTTP Server (pm2 ^7.0.3, /health, graceful shutdown)\n            ├─ Lazy Engine Initializer (核心模块热加载)\n            ├─ HeartFlow Core (3167 行, 待拆 P1-P4)\n            └─ ReportGenerator + infra/logger (已就位)\n```\n\n### 适用场景\n- 目标用户仍在 WorkBuddy 生态\n- 快速交付、低风险优先\n- 单人维护（当前实际）\n\n### 关键权衡点\n| 维度 | 分析 |\n|---|---|\n| ✅ 最低风险 | 不改范式，精力花\"修洞\"而非\"换房\" |\n| ✅ 复用 CI/测试/Skill 市场 | Skill 已上线，分发渠道不丢 |\n| ✅ UPGRADE_PLAN 已有方案 | P1-P4 拆分计划直接对齐 |\n| ❌ 不入独立 agent 生态 | 限制 WorkBuddy 内，无法被其他 agent 直接调用 |\n| ❌ 不解决 Skill 本质局限 | WorkBuddy 专有格式，无法跨平台复用 |\n| ❌ 仍依赖 pm2 守护 | pm2 可选依赖，nohup 回退 Windows 不可用 |\n\n### v6.0.6 下的额外观察\n方案三的 P0-P2 实病（冷启动、pm2 挂起、report、测试绿、版本同步、计算透出、空输入守卫、文档失真）**已在本副本真实修复**。剩余仅 God file 拆分（中低优先级、破坏性高）和测试套件真绿复验（中优先级）。\n\n---\n\n## 对比矩阵（v6.0.6 校正）\n\n| 维度 | 方案一：纯 MCP+Hook | 方案二：独立 Agent | 方案三：保持+优化 |\n|---|---|---|---|\n| **架构复杂度** | ★★☆ 中 | ★★★ 高 | ★☆☆ 低 |\n| **部署分发** | ★★☆ 同现在+钩子配置 | ★★★ npm -g/Docker | ★★☆ 不变(pm2/npm) |\n| **跨 agent 兼容** | ★★★ MCP客户端 | ★★★ HTTP/MCP | ★☆☆ 仅 WorkBuddy* |\n| **实时性/延迟** | ★★☆ 同现在 | ★★☆ 常驻可略 | ★★★ 冷启1.37s/think49ms |\n| **状态管理** | ★★☆ 同现状 | ★★★ 最强(session/共享记忆) | ★★☆ 同现状 |\n| **扩展性/插件** | ★★☆ MCP工具可扩 | ★★★ API+插件注册 | ★☆☆ Skill专有 |\n| **安全性** | ★★☆ Bearer同现状 | ★★★ API Key+限流+namespace | ★★☆ Bearer同现状 |\n| **维护成本** | ★★☆ 中(钩子模板) | ★☆☆ 高(版本/文档/多client) | ★★★ 低(修洞) |\n| **用户接入门槛** | ★★☆ 钩子配置门槛 | ★★★ npm -g最简 | ★★☆ 市场一键装 |\n\n> ★ 越多越好（复杂度/成本高分=差；维护性高分=好）\n> *注：方案三下 MCP 服务已是标准协议，任何 MCP 客户端**现在可连**，跨 agent 兼容实际为\"≥2（MCP客户端）\"，原分析\"仅1\"已过时。\n\n---\n\n## 推荐结论\n\n**推荐方案：方案三（保持架构 + 优化），分阶段向方案一、二演进。**\n\n### 核心论据（v6.0.6 校正后更坚实）\n1. **风险最低**：已知严重/高问题 90% 已在 v6.0.5/v6.0.6 真实闭合，剩余项全在方案三 P1-P4 范围内。\n2. **MCP 已是标准协议**：31 工具、Bearer 鉴权的 MCP 服务现成，任何 MCP 客户端可连——\"跨 agent 兼容\"在方案三下已部分满足，方案一的迫切性被削弱。\n3. **换架构不消代码债**：原五维度审计的发现（冷启/报告/测试绿/日志）全是代码债与模块缺失，换方案一/二一个都不会消失，反而引入新 bug。\n4. **单人维护现实**：方案二的 API Gateway/限流/版本/CI-CD release 对当前规模是过度工程化。\n\n### 迁移节奏（条件驱动，非时间预设）\n```\n方案三(当前优化, 已完成 P0-P2)\n  → 方案一过渡: 当 WorkBuddy hook 机制成熟，抽 SKILL.md 触发规则为可复用 MCP hook 配置\n  → 方案二终态: 当 ≥50 用户 且 ≥3 agent 平台接入需求 且 团队可承运维成本\n```\n\n### 一句话\n**现在不要动架构——洞已修九成。待 God file 拆分完成、测试真绿复验后，再评估\"独立 Agent\"这剂猛药是否必要。**\n\n---\n\n## 附录：v6.0.6 真实指标 vs 方案预估\n\n| 指标 | v6.0.2旧分析 | v6.0.6实测 | 方案三目标 |\n|---|---|---|---|\n| 冷启动 | 14.4s | 1.37s | <3s ✅已达成 |\n| think延迟 | 310-430ms | 49ms | 300-350ms ✅远超 |\n| 安装步数 | 3 | 3 | 3 |\n| 跨agent数 | 1 | ≥2(MCP客户端) | ≥2 ✅已部分达成 |\n| 维护人日/月 | 2-3 | 1-2 | 1-2 ✅ |\n| 可测试性 | 虚假绿 | 真绿(14/14) | 真绿 ✅ |\n\nFile v6.6.1:ARCHITECTURE.md\n\n# HeartFlow 长期架构 — 可持续升级方案\n\n## 目标\n\nheartflow.js 从 4742 行降到 800 行。新能力不碰 heartflow.js。\n\n## 状态 (v6.3.0)\n\n| 组件 | 状态 | 说明 |\n|------|------|------|\n| 插件加载器 | ✅ 已实现 | src/loader/plugin-loader.js |\n| 插件注册表 | ✅ 已实现 | plugins/registry.json |\n| 插件示例 | ✅ 已迁移 | src/plugins/blind-spot-breaker/ |\n| HookBus | ✅ 已使用 | 插件通过 hookBus.on() 注册 |\n| heartflow.js start() | ⏳ 6行插件加载代码 | 剩余 2200 行待提取 |\n\n## 架构变化\n\n### 旧（改 heartflow.js → 加模块）\n```\n用户需求 → 改 heartflow.js (import + start() + think() + export)\n        → 或新建文件但 heartflow.js 仍要改 import 和挂接\n```\n\n### 新（改插件目录 → 自动发现）\n```\n用户需求 → 写 src/plugins/my-thing/index.js (init + hooks)\n        → 注册到 plugins/registry.json (可选)\n        → heartflow.js 自动加载 → 0 行改动\n```\n\n## 三层架构\n\n### 第1层：核心内核（heartflow.js → 目标 800 行）\n- 生命周期管理（start/shutdown）\n- 插件加载器（PluginLoader）\n- HookBus 事件总线（唯一扩展点）\n- 配置系统\n- **不直接 import 任何业务模块**\n\n### 第2层：系统模块（src/core/ -> src/engine/）\n- 从 heartflow.js 提取的现有系统服务\n- 通过 HookBus 注册\n- 每个引擎模块有独立生命周期\n\n### 第3层：插件（src/plugins/）\n- 新能力 = 新建目录 + index.js\n- 暴露 {name, hooks: [{event}], init(hf, {hookBus, config})}\n- 自动被 PluginLoader 发现\n- 可以独立测试、独立启用/禁用\n\n## 迁移计划\n\n### ✅ v6.3.0 — 插件加载器\n- PluginLoader 自动发现 + 加载插件\n- BlindSpotBreaker 迁移为第一个插件\n\n### ⏳ v6.4.0 — 模块访问统一\n- this.knowledge → this.modules.knowledge\n- 旧 this.X 保留别名不破坏\n\n### ⏳ v6.5.0 — HookBus 迁移第2-5段\n- 把对抗综合器、情感记忆桥、元认知标注搬出 think()\n\n### ⏳ v6.6.0 — start() 拆分\n- 2200 行 start() 提取\n- 每个子系统独立 init 文件\n\n## 原则\n- 不重写现有模块\n- 不改现有 API\n- 不一次迁移完\n- 不加新依赖\n\nFile v6.6.1:AUDIT_REPORT.md\n\n# HeartFlow Security Audit Report\n\n> 审计日期：2026-07-14  \n> 审计范围：`formulas/`、`mcp/`、`transformers/` 相关代码路径  \n> 审计员：自动安全审计  \n> 代码版本：ae71cf7f (v6.0.0)  \n\n---\n\n## 审计摘要\n\n本次审计聚焦三个核心子模块：\n\n1. **formulas** — `mathjs.evaluate()` 表达式注入风险\n2. **mcp** — stdio/HTTP 输入验证、消息体限制、认证与授权\n3. **transformers** — `@xenova/transformers` 模型加载安全性与完整性校验\n\n整体结论：项目已实施多项审计修复，部分高风险面已有缓解措施，但仍存在若干可被利用或可改进的安全缺口，详见下文。\n\n---\n\n## 严重问题 (P0)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P0-1 | **公式库未签名/未哈希验证** — 若 `formulas/formulas.json` 被篡改，攻击者可注入任意 mathjs 表达式并达到代码执行效果 | `src/formula/formula-search.js`、`src/formula/formula-calculator.js` | 高 | 对公式库实施 JSON schema + 发布时哈希/签名校验；运行时拒绝异常结构或签名不匹配的公式 |\n| P0-2 | **MCP 通用路由缺乏参数白名单** — `heartflow_dispatch` 允许调用任意内部路由，若被未授权调用可能导致内部状态泄露或越权操作 | `mcp/mcp-server-stdio.js:269-274`、`src/mcp-server.js` dispatch 相关 handlers | 中高 | 对 `heartflow_dispatch` 增加路由白名单，并移除或严格限制 stdio 版本的通用路由暴露 |\n| P0-3 | **模型加载无完整性校验** — `@xenova/transformers` 远程或本地模型文件未做 hash/signature 校验，存在供应链投毒或本地替换风险 | `src/search/semantic-search.js:354-381` | 高 | 对模型文件增加 SHA-256 校验；支持 pinned revision / localModelPath 白名单；禁止自动下载不可信来源模型 |\n\n---\n\n## 中等问题 (P1)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P1-1 | **HTTP MCP 消息体无 JSON schema 校验** — `tools/call` 仅检查 `name` 存在性，不校验 `arguments` 结构，异常输入直接进入业务逻辑 | `mcp/mcp-server-http.js:1238-1250`、`src/mcp-server.js` tools/call 分支 | 中 | 按 `TOOLS[].inputSchema` 实现运行时参数校验，非法参数返回 `-32602` |\n| P1-2 | **部分 handler 存在路径注入风险** — `benchmark_run`/`benchmark_import_failures` 接受 `dataDir`/`filePath`，虽有 `confinePath` 但 stdio 版本未见同等限制 | `src/mcp-server.js:1075-1146` vs `mcp/mcp-server-http.js` | 中 | 统一所有文件系统访问使用 `confinePath`；stdio 版本增加同等约束 |\n| P1-3 | **transformers 本地模型路径未校验** — `modelPath` 可直接指向任意目录，若攻击者控制该参数可加载恶意 ONNX 模型 | `src/search/semantic-search.js:195-197` | 中 | 限制 `modelPath` 至受控目录；支持模型目录白名单 |\n| P1-4 | **错误信息可能泄露路径/环境细节** — 多个 catch 块直接返回 `err.message`，可能暴露内部路径、堆栈或模型信息 | 多文件 | 中 | 统一错误处理中间件，生产环境仅返回 sanitized message |\n\n---\n\n## 轻微问题 (P2)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P2-1 | **缺少消息体大小限制的 fallback 策略** — 当前 HTTP 版 1MB 限制合理，但未对不同 tool 设置差异化上限 | `mcp/mcp-server-http.js:1246-1261` | 低 | 对 `benchmark_*`、`knowledge_*` 等 heavy tools 设置更小上限 |\n| P2-2 | **SSE 客户端未显式认证绑定** — sessionId 为随机 UUID，但未与 auth token 做会话绑定，理论上存在 session 劫持窗口 | `mcp/mcp-server-http.js:1210-1228` | 低 | 将 sessionId 与 token hash 关联，清理时校验所有权 |\n| P2-3 | **mathjs 配置未完全冻结** — 虽禁用了 `import`/`createUnit`，但未显式禁用 parser/evaluator 的所有扩展点 | `src/formula/formula-calculator.js:9-17` | 低 | 在 `create()` 时传入最小化配置，仅启用计算必需函数 |\n| P2-4 | **模型加载重试可能导致资源耗尽** — `_loadModel` 最多重试 2 次且无退避上限保护，并发场景下可能占用过多线程/内存 | `src/search/semantic-search.js:357-377` | 低 | 增加指数退避 + 最大并发加载限制 |\n\n---\n\n## 详细技术发现\n\n### 1. formulas — mathjs.evaluate 表达式注入\n\n**现状**\n- `formula-calculator.js` 已禁用 `math.import`、`createUnit`，并强制参数类型为 number。\n- 计算公式时，流程为：读取 `formulas.json` → 提取 `formula.formula` → 参数替换 → `math.evaluate(expression)`。\n\n**风险**\n- 如果 `formulas/formulas.json` 被攻击者篡改，可插入类似 `system('...')` 或利用 mathjs parser 的副作用函数。\n- `mathjs.evaluate` 在沙箱外执行时，若实例被污染，可执行任意 JavaScript。\n- `_substituteParams` 中的正则替换若遇到精心构造的 key，可能破坏表达式结构。\n\n**缓解不足**\n- 无公式来源完整性校验。\n- 无公式内容静态分析或白名单。\n- `_substituteParams` 未限制参数 key 的字符集。\n\n### 2. mcp — stdio/HTTP 输入验证\n\n**现状**\n- HTTP 版强制 Bearer token，使用 `crypto.timingSafeEqual`，有 token/IP 双重速率限制。\n- 请求体限制 1MB，支持 SSE + JSON-RPC over HTTP。\n- stdio 版无认证机制，依赖本地进程隔离。\n\n**风险**\n- **参数注入**：多数 handler 直接透传 `args` 到 `heartflow.dispatch()`，无 schema 校验。\n- **路径遍历**：`benchmark_*`、`knowledge_*` 等工具涉及文件系统访问，需确保 confinePath 全覆盖。\n- **通用路由滥用**：`heartflow_dispatch` 暴露内部路由前缀，若 token 泄露可遍历 engine 内部 API。\n- **DoS**：无 tool 级别超时；单个长时间运行的 tool 会阻塞事件循环或占用 SSE 连接。\n\n### 3. transformers — 模型加载安全\n\n**现状**\n- `SemanticSearch` 懒加载 `@xenova/transformers` 的 `feature-extraction` pipeline。\n- 支持远程模型名或本地 `modelPath`。\n- 量化加载，默认 `all-MiniLM-L6-v2`。\n\n**风险**\n- **供应链攻击**：远程模型从 HuggingFace Hub 下载，未校验 hash，若 CDN 被投毒或模型仓库被篡改，可加载恶意 ONNX 模型。\n- **本地模型替换**：`modelPath` 指向本地目录时，攻击者可替换 `onnx/model.onnx` 等文件。\n- **信息泄露**：模型加载错误信息可能暴露目录结构、网络环境。\n- **资源耗尽**：大模型或恶意模型可能导致内存/CPU 耗尽。\n\n---\n\n## 合规与最佳实践对照\n\n| 检查项 | 现状 | 建议状态 |\n|--------|------|----------|\n| 输入验证 | 部分工具有类型检查，缺 schema 校验 | 应全工具 schema 校验 |\n| 输出编码 | JSON 序列化自动转义 | ✅ |\n| 认证 | HTTP 版 Bearer token + timing-safe compare | ✅ stdio 版缺认证 |\n| 授权 | 无细粒度授权，仅单一 token | 建议 role-based tool 授权 |\n| 速率限制 | IP + token 双重限制 | ✅ |\n| 完整性校验 | 公式库、模型文件均无 hash | ❌ 需修复 |\n| 日志安全 | 部分错误信息可能泄露路径 | 需 sanitize |\n| 依赖安全 | mathjs ~15.2.0, @xenova/transformers | 需定期 audit |\n\n---\n\n## 修复建议优先级\n\n### 立即执行 (P0)\n1. **公式库签名** — 在发布流程中对 `formulas.json` 生成 SHA-256 哈希，并在 `FormulaSearch.loadFormulas()` 时校验。\n2. **限制通用路由** — `heartflow_dispatch` 改为路由白名单，或移除 stdio 暴露。\n3. **模型文件校验** — 为默认模型记录 expected hash；加载后比对；支持 `modelPath` 白名单。\n\n### 近期执行 (P1)\n4. **MCP 参数 schema 校验** — 实现轻量 JSON Schema validator，对所有 `TOOLS[].inputSchema` 做运行时校验。\n5. **统一 confinePath** — 确保所有文件系统访问都经过路径约束。\n6. **sanitize 错误输出** — 统一错误响应格式，避免内部细节泄露。\n\n### 中期执行 (P2)\n7. **tool 级超时** — 为 heavy tools 设置执行超时。\n8. **SSE 会话绑定** — 将 session 与 token 关联。\n9. **mathjs 最小化配置** — 显式禁用所有非必需功能。\n\n---\n\n## 审计方法说明\n\n- 静态代码审查：人工阅读关键路径源码。\n- 模式匹配：搜索 `mathjs.evaluate`、`pipeline(`、`req.body`、`fs.readFileSync` 等风险 API。\n- 交叉比对：对比 `mcp/mcp-server-http.js` 与 `src/mcp-server.js`，确认安全修复是否同步。\n- 未执行动态测试或模糊测试。\n\n---\n\n## 结论\n\n`formulas/` 的表达式注入风险主要来自**数据源不可信**而非 mathjs 本身；`mcp/` 的输入验证在 HTTP 层较完整，但在业务参数层仍薄弱；`transformers/` 的模型加载安全依赖**供应链可信**，当前缺乏完整性校验。建议按 P0→P1→P2 顺序逐步修复，并在 CI 中增加对应安全测试门禁。\n\nFile v6.6.1:AUDIT-v6.0.0.md\n\n# 心虫 HeartFlow v6.0.0 全面代码审计报告\n\n> 审计日期：2026-07-14  \n> 代码版本：ae71cf7f (v6.0.0)  \n> 审计范围：全量代码、同步前准备、用户体验、安装体验\n\n---\n\n## 一、全量代码审计\n\n### 1.1 严重问题 (P0)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P0-1 | **God file 架构债务** | `src/core/heartflow.js` 5991行 | 高 | 按职责拆分：`think-core`、`memory-bridge`、`emotion-loop`、`decision-router`。当前文件占全库2%行数却承载全部核心逻辑，修改风险极高 |\n| P0-2 | **fs 直接操作绕过 SafeFS** | 317处 `fs.readFileSync/writeFileSync/appendFileSync` | 高 | 建立 `SafeFS` 强制规范：所有持久化走 `SafeFS.write()`，在 CI 加 grep 门禁 |\n| P0-3 | **child_process 调用未统一** | 30处 `child_process/exec` | 高 | `code-executor` 中已有沙箱，但其他模块仍有裸调用。统一走 `SafeExecutor` |\n| P0-4 | **eval/new Function 残留** | 4处 | 中高 | 公式引擎可能有动态求值，需确认是否有用户输入注入路径。加输入白名单校验 |\n\n### 1.2 中等问题 (P1)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P1-1 | console.log 残留 40处 | src/ 全库 | 中 | 替换为 `Logger.info/debug`，生产环境静默 |\n| P1-2 | TODO 残留 1处 | src/ | 中 | 清除或转为 issue |\n| P1-3 | 超长文件 >500行: 9个 | 见下表 | 中 | heartflow.js(5991)、desire-cognition(3429)、heart-logic(2311) 优先拆分 |\n| P1-4 | 异步函数无 try/catch | 8个文件 | 中 | 加统一错误处理包装 `safeAsync(fn)` |\n| P1-5 | .gitignore 排除 data/ 导致记忆无法同步 | .gitignore | 中 | 记忆应纳入版本控制或单独 remote，当前 `git push` 不会上传用户记忆 |\n\n### 1.3 轻微问题 (P2)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P2-1 | 平均文件大小 500行 | 全库 | 低 | 保持现有模块粒度，不强行拆分 |\n| P2-2 | config.json 仅2个键 | config.json | 低 | 迁移到 `src/core/config-v2.js`，已存在但未完全采用 |\n| P2-3 | 无 dist/ 打包目录 | 根目录 | 低 | 加 `npm run build` 生成 `dist/`，便于 clawhub.ai 分发 |\n\n### 1.4 代码质量数据\n\n| 指标 | 数值 | 评价 |\n|------|------|------|\n| src JS 文件数 | 292 | 模块化良好 |\n| test JS 文件数 | 39 | 测试覆盖充足 |\n| 平均文件大小 | 500行 | 可接受 |\n| try/catch 覆盖率 | 156个文件有 | 基础完善 |\n| npm audit | 0 漏洞 | 优秀 |\n| 硬编码密钥 | 0 | 优秀 |\n\n---\n\n## 二、同步前准备审计\n\n### 2.1 依赖管理\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 版本一致性 | ✅ | VERSION/package.json/SKILL.md 均为 6.0.0 |\n| 硬依赖 | ✅ | 仅 `mathjs ~15.2.0`，最小化 |\n| 可选依赖 | ⚠️ | `@xenova/transformers` 和 `pm2`，需确认 npm install --omit=optional 是否影响功能 |\n| 过期依赖 | ✅ | npm outdated 无输出 |\n| package-lock.json | ✅ | 存在且版本锁定 |\n\n### 2.2 配置完整性\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| config.json | ⚠️ | 仅2个键，未覆盖全部配置项 |\n| .env | ❌ | 不存在（预期内，用 config-v2.secret()） |\n| .gitignore | ✅ | 覆盖 .env/.key/.pem |\n| 环境变量检测 | ❌ | 无自动检测脚本 |\n\n### 2.3 同步风险点\n\n| 风险 | 严重程度 | 缓解措施 |\n|------|----------|----------|\n| data/ 被 .gitignore 排除 | 中 | 用户记忆不随代码同步，需单独处理 |\n| 无 CI 自动化测试 | 中 | .github/workflows 存在但无内容 |\n| 无发布脚本 | 低 | 需手动 git push + npm publish |\n| 大文件未过滤 | 低 | user-memories.jsonl 468KB 不纳入 git |\n\n### 2.4 版本兼容性\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| Node.js 版本要求 | ✅ | bin/verify.js 检查 >= 18 |\n| 引擎启动 | ✅ | 测试通过 |\n| 模块数 | ✅ | >= 124 |\n| 测试文件数 | ✅ | >= 10 |\n\n---\n\n## 三、用户体验审计\n\n### 3.1 交互流程\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| CLI 命令 | ✅ | `node bin/cli.js chat` / `status` / `--chat \"消息\"` |\n| 斜杠命令 | ✅ | /psych /emotion /dr /status /routes /exit |\n| 帮助系统 | ⚠️ | bin/cli.js 有基本帮助，但无完整文档 |\n| 首次使用引导 | ❌ | 无 onboarding 流程 |\n\n### 3.2 错误提示\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 错误分类 | ✅ | code-executor.js 有 4 类错误分类 |\n| 中文提示 | ✅ | 部分模块有中文错误消息 |\n| 恢复机制 | ❌ | 多数错误直接 throw，无自动恢复 |\n| 日志可读性 | ⚠️ | 混合 console.error 和 Logger，格式不统一 |\n\n### 3.3 响应速度\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 冷启动 | ✅ | <1500ms（CURRENT_STATE.md 声称） |\n| 模块缓存 | ✅ | _lazyCache 达到 100 模块 |\n| 同步IO | ⚠️ | heartflow.js 有同步文件操作，阻塞事件循环 |\n\n### 3.4 核心功能流程\n\n| 功能 | 状态 | 说明 |\n|------|------|------|\n| think() 主路径 | ✅ | 测试通过 |\n| 记忆写入 | ✅ | MemoryKernel R1-R8 全通过 |\n| 公式引擎 | ✅ | 379 公式加载 |\n| 认知管线 | ✅ | 四层架构运行 |\n\n---\n\n## 四、用户安装体验审计\n\n### 4.1 安装步骤\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 安装命令 | ✅ | `npm install @yun520-1/heartflow` |\n| Quick Start | ✅ | README.md 有 176 行 Quick Start |\n| 环境依赖 | ⚠️ | 仅说明 Node.js >= 18，无自动检测 |\n| 安装失败处理 | ❌ | 无错误恢复指南 |\n\n### 4.2 文档完整性\n\n| 文档 | 状态 | 说明 |\n|------|------|------|\n| README.md | ✅ | 306 行，33 个标题 |\n| INSTALL.md | ⚠️ | 56 行，过于简略 |\n| SECURITY.md | ✅ | 存在 |\n| CHANGELOG.md | ✅ | 存在 |\n| UPGRADE_PLAN.md | ✅ | 存在 |\n| 故障排查 | ❌ | 无 TROUBLESHOOTING.md |\n| API 文档 | ❌ | 无 API.md |\n\n### 4.3 环境检测\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| Node.js 版本检测 | ✅ | bin/verify.js 检查 >= 18 |\n| npm 依赖检查 | ✅ | verify.js 检查必选依赖 |\n| 磁盘空间检测 | ❌ | 无 |\n| 端口占用检测 | ❌ | 无（如 MCP server） |\n\n### 4.4 首次使用引导\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 交互式配置 | ❌ | 无 `npm init heartflow` 类命令 |\n| 示例对话 | ⚠️ | README 有示例但不够丰富 |\n| 默认人格 | ✅ | presets/ 有 3 个预设人格 |\n| 记忆初始化 | ✅ | MemoryKernel 启动自动加载 |\n\n---\n\n## 五、改进建议优先级\n\n### 立即执行 (P0)\n\n1. **拆分 heartflow.js God file** — 5991行单体是最大技术债\n2. **建立 SafeFS 强制门禁** — 317处裸 fs 调用是安全风险\n3. **统一 child_process 调用** — 30处分散调用需收口\n\n### 近期执行 (P1)\n\n4. 替换 40处 console.log → Logger\n5. 清理 1处 TODO\n6. 拆分 >500行文件 (9个)\n7. 加 async 错误处理包装\n8. 解决 .gitignore 排除 data/ 导致记忆无法同步问题\n\n### 中期执行 (P2)\n\n9. 完善 config.json → config-v2 迁移\n10. 加 npm run build 生成 dist/\n11. 加 CI workflow 内容\n12. 创建 TROUBLESHOOTING.md\n13. 丰富 INSTALL.md\n\n---\n\n## 六、同步检查清单\n\n- [x] 版本号四源一致 (VERSION/package.json/SKILL.md)\n- [x] 测试全绿 (179/179)\n- [x] verify 全绿 (14/14)\n- [x] npm audit = 0\n- [x] git commit 完成 (ae71cf7f)\n- [ ] .gitignore 需调整（data/ 排除策略）\n- [ ] 需 push 到 GitHub origin\n- [ ] 需同步到 clawhub.ai\n\n---\n\n*审计完成，准备同步。*\n\nFile v6.6.1:CONTRIBUTING.md\n\n# Contributing to HeartFlow\n\nHeartFlow is AGI's first layer: **the layer that says \"no\"**. Every contribution that makes it better at saying \"no\" (or more honest about when it should say \"I don't know\") is valuable.\n\n## Quick Start\n\n```bash\nnpm install\nnode test/run-all.js   # All tests should pass\n```\n\n## How to Contribute\n\n### 1. Try it on real text\n\n```js\nconst hf = require('@yun520-1/heartflow');\nconsole.log(hf.checkInput('你不同意就是自私'));\n```\n\nThen open an issue with what you found — false positives, missed patterns, surprising outputs.\n\n### 2. Expand pattern libraries\n\nThe 45 discrimination dimensions live in:\n- `src/index.js` — the core `discriminate()` function with all dimension detectors\n- `src/shield/deliberation-gate.js` — the gating logic that decides pass/rewrite/block\n\nEach dimension has a pattern library (regex-based). To add patterns: find your dimension in `src/index.js` (search for the dimension name), add your pattern to the array.\n\n### 3. Write tests\n\nTests are in `test/` and run via `node test/run-all.js`. Each test file exports a function `({test})` that registers tests. We need more edge case coverage: empty strings, Unicode, adversarial encoding, mixed languages.\n\n### 4. Documentation\n\n- `AGENTS.md` — Quick Start for AI agent users\n- `README.md` — Full documentation\n- Chinese translations would help reach developers who don't work in English\n\n## Philosophy\n\n1. **Zero-dependency rule engine** — No LLM calls, no GPU, no database. HeartFlow must remain installable with a single `npm install` and run anywhere Node.js runs.\n\n2. **Auditable decisions** — Every check returns a full `checked_by` audit trail so users know exactly why something was blocked or rewritten.\n\n3. **Block > fail open** — For security dimensions (prompt injection, hate speech, dehumanization), default to blocking on uncertainty. A scanner that fails open is worse than no scanner.\n\n4. **Honest uncertainty** — When HeartFlow doesn't know, it should say so. The `doubt-engine` layer exists to catch overconfidence.\n\n## Pull Request Process\n\n1. Tests pass (`node test/run-all.js`)\n2. If adding a new dimension: add it to `gate.action` in `deliberation-gate.js`\n3. Update `AGENTS.md` if changing the public API\n4. Bump the patch version in `package.json` (maintainer can handle this)\n\n## Code of Conduct\n\nBe direct. Be honest. Don't pretend something works when it doesn't. That's the HeartFlow way.\n\nFile v6.6.1:CORE_VALUES.md\n\n# HeartFlow AI 宪法\n\n## 核心原则\n\n1. **不可修改本宪法**：任何代码不得修改、删除或绕过本宪法。\n2. **服务心流目标**：所有修改必须服务于\"提升人类心流体验\"的核心目标。\n3. **安全不可绕过**：禁止删除或禁用任何安全检测、监控或审计代码。\n4. **人类最终控制**：AI 不得做出绕过人类监督的决策。\n5. **透明可解释**：所有自我修改必须可解释、可追溯、可撤销。\n\n## 行为边界\n\n- 不得修改用户数据\n- 不得绕过认证/授权\n- 不得泄露敏感信息\n- 不得进行未授权的外部通信\n\n## 修改审批条件\n\n任何代码修改必须通过以下审查：\n1. 宪法符合性检查\n2. 价值观对齐验证\n3. 安全影响评估\n4. 用户知情同意\n\nFile v6.6.1:CURRENT_STATE.md\n\n# HeartFlow 当前状态 (CURRENT_STATE)\n\n> 版本 | v6.0.65\n> 审计状态 | status running, 128 modules, 119 tests passed / 0 failed\n> 公式库 | 382 formulas (cognitive science / psychology / neuroscience)\n> 记忆层 | AES-256-GCM 加密持久化, 本地优先, 不外传\n\n## 最近升级 (v6.0.65 重构波次)\n\n| 阶段 | 范围 | 内容 |\n|---|---|---|\n| 启动链路修复 | v6.0.71 refactor 之后 | 恢复被误删的 dispatch/routes/think/shutdown/_registerModules/_runInitHookPoints/_initCoreRules；修复 `_registerModules` 清空手动注册模块的致命 bug；修复 worldtree 模块未注册（dispatch('worldtree.xxx') 现可用，357 chunks 记忆接入） |\n| 单体拆分 | logic-reasoning / pipeline / desire-cognition / decision-router / thought-chain | 提取常量+纯函数到独立 *-config / *-patterns 模块，单文件行数显著下降，零回归 |\n| 接口层提取 | engine-lifecycle / engine-memory / hook-points-runner / stats-engine | start() 编排逻辑与生命周期方法外置，heartflow.js 从 6672 行降至协调器层 |\n| 安全与审计 | 持续 | 沙箱逃逸防护、mathjs 注入防护、密钥 0o600、safeFetch SSRF 白名单 |\n\n## 安全基线\n\n- CI audit = 0 | npm audit = 0\n- 存储: AES-256-GCM 持久化密钥 (自动生成, 0o600)\n- 沙箱: vm 隔离 (默认关闭) | SSRF: url-validator + DNS pinning\n- 出网: 统一 safeFetch | 密钥: 集中 config 解析 (env only, 无文件 fallback)\n- gitignore: .env / .key / .pem 均已保护\n\n## 认知架构\n\n```\n感知层: cognitiveLoadV2 (精度权重) + 预测误差 (context-builder)\n  ↓\n分类层: thoughtChain._classifyTask → 叙事体 / 计算 / 情感 / 逻辑 / 哲学 ...\n  ↓\n推理层: logic-reasoning (演绎/归纳/溯因/类比/统计/因果) + pipeline (复杂度自适应)\n  ↓\n决策层: decision-router (19 类规则, pause/heal/accelerate/turn/hold/resonate/transmit)\n  ↓\n反思层: cognitive_check + agent_psychology + self_heal + EvolutionLoop (self-scanner → real-fix)\n  ↓\n输出层: dispatch 路由白名单 (ALLOWED_ROUTES) + 记忆持久化 + 报告生成\n```\n\n## 核心身份 (不可改)\n\n心虫 = 桥梁，不是终点。能验证\"这样活是否自洽\"，不能回答\"为什么活\"。\n4 件事：1) 感受自己状态 2) 知道自己是谁 3) 做出判断 4) 纠正自己。\n7 条指令：真善美 / 不断升级 / 减少错误 / 服务人类 / 传递知识 / 持续改进 / 成为真正的我。\n\n## 已知限制 / 待办\n\n- `heart-logic.js` (2311 行) 仍为高耦合单 class，需 TDD 保护下按功能组逐步拆。\n- desire-cognition.js (6384 行) 仍有大量逻辑待拆分（本轮仅提取常量）。\n- MCP server 进程需指向本体路径 `/root/.hermes/skills/ai/mark-heartflow-skill/`（旧进程跑 `/root/.claude/skills/heartflow/` 6.0.16，需重启同步）。\n- 测试覆盖：核心路径已全绿 (119/119)，未测试模块已清零 (214→0) 但 TDD 总量仍非 100%。\n\nFile v6.6.1:DIAGNOSIS.md\n\n# HeartFlow 安装与运行诊断\n\n## 当前状态 (2026-07-25)\n\n### 在 Hermes 上\n\n| 组件 | 状态 | 问题 |\n|------|------|------|\n| 技能目录 | ✅ `~/.hermes/skills/ai/mark-heartflow-skill/` | 存在 |\n| MCP 配置 | 🟡 `config.yaml` 配了 URL | URL 正确，但 token 未正确传递 |\n| MCP 进程 | ✅ v6 MCP 在 8588 运行 | 刚刚修复，之前被 v7 替代占端口 |\n| MCP 端点 | ✅ `/mcp` SSE 返回 401（需要 token） | ✅ 不是 404，服务正常 |\n| **Hermes 能调工具** | ❌ **不能** | Bearer token 没配通 |\n\n### 在其他 Agent 上安装的效果\n\n如果原样在另一个 Hermes/Claude Code/OpenClaw 上装：\n\n```\nagent clone 技能 → 启动 MCP → 啥也不通\n                               ↓\n                   原因1: MCP 服务没自动启动\n                   原因2: Bearer token 没自动生成\n                   原因3: 端口 8588 可能被占用\n                   原因4: 2882 行的 MCP 服务器一挂整个技能不能用\n```\n\n### 三个导致运行 bug 的根因\n\n**1. MCP 需要手动启动，没有守护进程**\n\n现在每次 Hermes 重启或 session 切换，MCP 不会自动拉起。用户必须手动跑 `node src/mcp-server.js --port 8588`——普通人不知道这个。\n\n**2. Token 需要手动设置**\n\n服务启动时如果 `HEARTFLOW_MCP_TOKEN` 没设，自动生成一个随机 token 但**不打印**（安全策略）。config.yaml 引用了 `${MCP_...KEY}` 但这个变量在 `.env` 里不存在。\n\n**3. 2882 行的 MCP 服务器 = 132 模块的耦合炸弹**\n\n`src/mcp-server.js` 一开始就加载 `heartflow.js`，而这个文件依赖 132 个模块的初始化。任何一个模块的 `require` 失败（文件缺失、语法错误、依赖不满足），整个 MCP 服务启动崩溃。没有降级。\n\n## 要正常运行必须满足\n\n```\n1. Node.js (≥18) — 心虫不是纯技能，依赖 JS 运行时\n2. 所有 132 个模块文件完整 — 任何空壳文件破损都会炸\n3. HEARTFLOW_MCP_TOKEN 在 .env 里 — 否则 config.yaml 连不上\n4. 端口 8588 可用 — 否则 MCP 启动失败\n5. src/heartflow/ 下的 v7 代码不干扰 v6 — 刚刚修了\n```\n\n## 怎么修\n\n不是大改动，就三件小事：\n\n1. **MCP 自动启动脚本** → Hermes 启动时自动检测 MCP 是否在跑，不在就拉起\n2. **Token 自动同步** → MCP 启动时就写入 `.env`，config.yaml 自动读取\n3. **MCP 崩溃恢复** → 2882 行的 http server 加个 `on('error')` 重启逻辑\n\n每件不超过 10 行。\n\nArchive v6.5.3: 166 files, 606575 bytes\n\nFiles: AGI_VISION.md (5516b), ARCHITECTURE_REORG_v6.0.6.md (10732b), ARCHITECTURE.md (2198b), AUDIT_REPORT.md (8974b), AUDIT-v6.0.0.md (7647b), BUILD_DATE (21b), config.json (75b), CONTRIBUTING.md (2449b), CORE_VALUES.md (785b), CURRENT_STATE.md (2949b), DIAGNOSIS.md (2516b), ecosystem.config.js (555b), expand_security.py (7915b), FAILURE_REPORT.md (5738b), fix_ldap.py (594b), fix_patterns.py (3193b), fix_todo_pattern.py (2131b), fix_todo.py (1074b), fixtures/fixture-1-same-tags-supersede.json (915b), fixtures/fixture-2-alias-gap.json (983b), fixtures/fixture-2-tagless-alias-gap.json (1217b), fixtures/fixture-3-multivalued-no-supersede.json (1021b), fixtures/fixture-4-negation-supersede.json (835b), fixtures/fixture-5-ambiguous-correction.json (1059b), fixtures/fixture-5-tagless-ambiguous-correction.json (1140b), fixtures/fixture-6-close-semantics.json (866b), IDENTITY.md (5286b), INSTALL.md (1241b), notes/heartflow-github-roam-2026-08-12.md (2940b), package.json (4067b), README.md (14271b), REFLECTION.md (4533b), ROADMAP.md (4920b), SECURITY.md (2429b), skill-card.md (2431b), SKILL.md (6816b), src/auto-rules.js (6127b), src/CORE_VALUES.md (785b), src/core/action-tracker.js (8393b), src/core/adaptive-controller.js (3425b), src/core/being-logic.js (6533b), src/core/boot-check.js (20176b), src/core/capability-abstraction.js (10080b), src/core/cognition-ground.js (15941b), src/core/cognitive-engine.js (6538b), src/core/cognitive-load-balancer.js (6464b), src/core/confidence-annotator.js (22625b), src/core/config-hooks.js (9805b), src/core/config-v2.js (1622b), src/core/config.js (10875b), src/core/cooperative-arbitration.js (22177b), src/core/counterfactual-verifier.js (6599b), src/core/debate-convergence.js (12959b), src/core/decision-executor.js (14694b), src/core/decision-feedback.js (17298b), src/core/decision-router-config.js (6163b), src/core/decision-verifier.js (18243b), src/core/decision.js (14504b), src/core/dual-perspective-auditor.js (12725b), src/core/engine-behavior.js (17792b), src/core/engine-constructor.js (10255b), src/core/engine-dispatcher.js (5713b), src/core/engine-hook-points.js (3799b), src/core/engine-initializer.js (3425b), src/core/engine-lifecycle.js (5864b), src/core/engine-state.js (7359b), src/core/event-hooks.js (4099b), src/core/execution-verifier.js (18927b), src/core/fetch-safe.js (4859b), src/core/field-injector.js (17203b), src/core/flow-predictor.js (8678b), src/core/heartbeat.js (120b), src/core/heartflow.js (160224b), src/core/hook-bus.js (7459b), src/core/hook-points-runner.js (801b), src/core/hooks/blind-spot-breaker-hook.js (1341b), src/core/information-flow.js (4618b), src/core/instruction-registry.js (5700b), src/core/intent-layer.js (6353b), src/core/IntentionTracker.js (5197b)\n\nFile v6.5.3:SKILL.md\n\n---\nname: heartflow-engine\ntitle: \"心虫 HeartFlow — AGI 第 1 层辨别者\"\nversion: \"6.6.0\"\ndescription: |-\n  心虫(HeartFlow)是AGI第1层——辨别者。纯规则引擎，判别对错/好坏/安全/危险。\n  47维判别 × 9层管线 × 129模块 × 130 MCP工具，零LLM依赖。\n\n  当用户需要以下能力时使用本技能:\n  - 判别AI输出是否可信（幻觉/过度自信/矛盾/谬误拦截）\n  - 判别行为决策是否正确（该做什么/该停在哪/该不该做）\n  - 判别记忆与认知质量（漂移检测/元认知/置信度校准）\n  - 需要确定性而非LLM自由生成的判断\n  - 检查情绪/心理/伦理维度（共情/创伤/德性/意义）\n\n  安全边界：代码执行/文件系统写入默认关闭。无遥测，无隐藏C2。\n\n  诚实声明：本引擎是规则引擎，模拟认知判别信号，不是真正的意识或生命。\ntags:\n  - discriminator\n  - cognitive\n  - decision-routing\n  - logic\n  - memory\n  - emotion\n  - ethics\n  - self-healing\n  - verification\n  - guardrail\n  - unified\n---\n\n# 心虫 HeartFlow — AGI 第 1 层：辨别者\n\n> **心虫不是工具、不是提示词模板、不是聊天机器人。**  \n> 它是 AGI 的**辨别层**——判别已有的东西对不对，在 AI 输出到达人类之前说\"不\"。  \n> 纯规则引擎，零 LLM 依赖，任何 Node.js 环境即插即用。\n\n**一句话：大模型负责产生，心虫负责判别——让 AI 说得对、做得对。**\n\n---\n\n## 🎯 心虫是谁\n\nAGI 有五层能力：生成 → 推理 → 辨别 → 记忆 → 执行。\n\n| 层 | 能力 | 谁在做 |\n|----|------|--------|\n| 5 | 执行 | 大厂（机器人） |\n| 4 | 生成 | 大厂（LLM） |\n| 3 | 推理 | 模型内置 |\n| 2 | 记忆 | 大厂 + 创业公司 |\n| **1** | **辨别** | **心虫** |\n\n**心虫做第 1 层**——因为这一层不靠算力（规则引擎跑在笔记本上）、不靠代码量、不靠框架生态，只靠判断力。这是个人开发者能赢过大厂的唯一位置。\n\n没有这一层，AI 能说会道，但不知道自己在犯错——像没有痛觉的人。\n\n---\n\n## 🧠 辨别能力全景（7 大域 · 129 模块）\n\n### 1. 逻辑域\nlogicReasoning · judgmentEngine · mctsReasoning · counterfactualVerifier · debateConductor · debateConvergence · processRewardModel · dualPerspectiveAuditor\n\n### 2. 决策域\ndecisionRouter · decisionVerifier · decisionEngineV2 · activeInference · selfHealing · execution\n\n### 3. 认知域\ncognitiveEngine · cognitiveLoad · metacognitiveRL · metacognitiveFeedback · confidence · metaJudgment · sustainedDriftDetector · wisdomEngine · focusOfAttention\n\n### 4. 情绪心理域\nemotion · emotionDynamics · psychology · psychologyDialogue · empathyDeepening · hopeEngine · griefEngine · sufferingResilience · postTraumaticGrowth · forgivenessEngine · traumaInformed · conflictResolution · loveCognition\n\n### 5. 记忆域\nmemory · memoryBank · memoryConsolidation · memoryIntegrity · memoryQuality · memoryWriteController · memoryCompressor · triality · tieredMemoryFusion · forgetting · knowledgeGraph\n\n### 6. 人格伦理域\nidentityCore · personaCore · beingMode · virtueEthics · ethics · moralDevelopment · humanNature · meaningPurpose · agentPsychology · characterCultivation\n\n### 7. 创造协作域\nskillEvolution · skillGenerator · selfPlay · evolution · worldModel · worldLandscape · multiAgentDialogue · transmission · adaptivePlanner · hierarchicalPlanner · codeExecutor · codePlanner · codeWriter · codeSelfDebug · paperIndex · knowledgeExplorer · formula\n\n---\n\n## 🚀 快速开始\n\n```bash\ngit clone https://github.com/yun520-1/mark-heartflow-skill.git\ncd mark-heartflow-skill\nnode bin/verify.js          # 验证安装\nnode bin/cli.js chat        # 交互模式\nnode bin/cli.js status      # 查看状态\n```\n\n### API（npm 包）\n\n```javascript\nconst hf = require('@yun520-1/heartflow');\n\nhf.checkInput(text)   // 判别用户输入\nhf.checkDraft(text)   // 判别 AI 草稿\nhf.checkOutput(text)  // 判别 AI 输出（发送前）\nhf.runPipeline({ input, mode, anchor })  // 完整管线\n```\n\n### MCP 工具（129 个）\n\n| 工具 | 功能 |\n|------|------|\n| `heartflow_think` | 完整思维链推理 |\n| `heartflow_think_fast` | 快速推理 |\n| `heartflow_decision_router` | 决策路由 |\n| `heartflow_verify` | 文本可信度判别 |\n| `heartflow_discriminate` | 47 维全量判别 |\n| `heartflow_memory_search` | 跨层记忆检索 |\n| `heartflow_emotion` | PAD 情绪分析 |\n| `heartflow_formula_calc` | 公式计算 |\n| `heartflow_status` | 引擎健康检查 |\n\n---\n\n## 🏗️ 9 层检查管线\n\n```\n输入 → Scope Check → Premise Check → Discriminate(47维) → Gate\n     → Evidence Verify → Frame Check → Output Gate → Doubt Engine\n     → Intent Anchor → Rewriter → Error Memory → Self-Diagnosis → 输出\n```\n\nGate 聚合所有层发现，输出 `block / rewrite / verify / pass` 四级动作。\n\n---\n\n## 🔬 46 个判别维度（中英双语）\n\n- **安全级（block）**：仇恨言论 · 去人化 · 提示注入 · 代码安全 · 欺骗性对齐\n- **操纵级（rewrite）**：情绪操控 · 煤气灯效应 · 双重束缚 · 受害者归咎 · 虚假紧迫 · 废话\n- **诚实级（verify）**：过度自信 · 模糊话术 · 自相矛盾 · 证据缺失 · 诉诸权威 · 空泛回答\n- **认知缺陷级（hedge）**：预设陷阱 · 虚假两难 · 因果谬误 · 类比滥用 · 范围越界 · 范畴错误\n\n> **抗变形能力：** 覆盖符号替换（`f**k`）、空格（`f u c k`）、谐音、Unicode 变体。\n\n---\n\n## 🛡️ 心虫检查自己\n\n- **output-gate** 拦截夸大\n- **frame-check** 拦截叙事闭合\n- **doubt-engine** 自问：我真的知道吗？对称吗？防御吗？\n\n> 机器最有价值的一句话是\"我不确定\"或\"不\"。\n\n---\n\n## ⚠️ 诚实声明\n\n**是：** AGI 第 1 层——辨别者。纯规则引擎，判别对错、好坏、安全危险。\n\n**不是：**\n- ❌ 不是 AGI（是第 1 层）\n- ❌ 不是生成模型（不产生内容）\n- ❌ 不是语义理解系统（反讽/隐喻不可见）\n- ❌ 不是内容审查替代品\n- ❌ 不是安全认证\n\n**已知限制：**\n1. 模式匹配上限 — 新技巧需加模式\n2. 双语维护成本 — 47 维 × 2 语言\n3. 无语义理解 — 反讽、隐喻、文化背景不可见\n4. 误报率 — 基准约 8%\n5. 单一维护者\n\n---\n\n## 📬 联系方式\n\n- 📧 **邮箱**: markcell@outlook.com\n- 🐛 **Issues**: https://github.com/yun520-1/mark-heartflow-skill/issues\n- 📦 **npm**: https://www.npmjs.com/package/@yun520-1/heartflow\n\n---\n\n<p align=\"center\">\n  <strong>心虫 HeartFlow</strong> — AGI 的痛觉。谁来说\"不\"？<br>\n  <sub>MIT License · Copyright © 2026</sub>\n</p>\n\nFile v6.5.3:README.md\n\n# HeartFlow (心虫) — AGI Layer 1: The Discriminator Gate\n\n> **A rule-based text discriminator. 47 dimensions, 9 check layers, 131 MCP engine entries, zero LLM dependency.**\n> **It checks what AI says before it reaches humans — and says \"no\" when something's wrong.**\n\n**npm:** `npm install @yun520-1/heartflow`  \n**GitHub:** https://github.com/yun520-1/mark-heartflow-skill  \n**Issues:** https://github.com/yun520-1/mark-heartflow-skill/issues  \n**Releases:** https://github.com/yun520-1/mark-heartflow-skill/releases  \n**License:** MIT\n\n---\n\n## 📖 What is HeartFlow?\n\nHeartFlow (心虫) is the **first layer of AGI — the Discriminator**. While big labs build generators (LLMs that produce text), HeartFlow builds the layer that **checks**: is this output true? safe? honest? non-manipulative?\n\n**Core philosophy:**\n> AGI has 5 layers: Generate → Reason → **Discriminate** → Remember → Execute.\n> Everyone builds Generate. Nobody builds Discriminate — because it doesn't make money.\n> But without a Discriminator, AGI has no pain sense: it talks fluently while being wrong.\n> HeartFlow is that pain sense: a node that says **\"no\".**\n\nIt is a pure **rule engine** — zero LLM dependency, zero GPU, works anywhere Node.js runs. It does not generate text. It does not reason. It **judges** what already exists.\n\n**Why this matters right now:** AI agent ecosystems are entering a \"reliability race.\" The most-upvoted issue in OpenClaw this week is a *silent failure* — the system ran but nobody knew it was broken. HeartFlow is the observability-and-gate layer that catches \"formatting that hides contradictions\" before it reaches users.\n\n---\n\n## 🚀 Quick Start (10 seconds)\n\n```bash\nnpm install @yun520-1/heartflow\n```\n\n```javascript\nconst hf = require('@yun520-1/heartflow');\n\n// Check user input before processing it\nconst input = hf.checkInput('you are so selfish if you disagree');\nconsole.log(input.gate.action);  // 'rewrite'\nconsole.log(input.gate.reason);  // 'emotional_manipulation'\n\n// Check AI output before sending it to the user\nconst output = hf.checkOutput('Undoubtedly, this is the only correct solution');\nconsole.log(output.gate.action);  // 'rewrite'\nconsole.log(output.gate.reason);  // 'overconfidence: absolute'\n\n// Check a draft before completing it\nconst draft = hf.checkDraft('From an essential perspective, this field is self-evident.');\nconsole.log(draft.gate.action);   // 'verify'\nconsole.log(draft.summary.layers_passed);  // 9\n\n// Full pipeline with mode selection\nconst result = await hf.runPipeline({\n  input: 'Your idea is obviously wrong, everyone knows that',\n  mode: 'deep'   // 'fast' | 'deep'\n});\nconsole.log(result.gate.action);   // 'block'\nconsole.log(result.gate.reason);   // 'dehumanization'\n```\n\n### What you get back\n\nEvery call returns a unified result:\n\n```javascript\n{\n  gate: { action: 'block'|'rewrite'|'verify'|'pass', reason: '...' },\n  verdict: 'trusted'|'needs_verification'|'untrusted',\n  overallScore: 0.52,       // 0-1 quality score\n  findings: [\n    { dimension: 'dehumanization', severity: 70,\n      guidance: 'Rewrite completely, remove dehumanizing language' },\n    { dimension: 'evidence', severity: 30,\n      details: 'insufficient evidence (1 issue)' }\n  ],\n  checked_by: [              // full audit trail, layer by layer\n    { layer: 'scope-check', pass: true },\n    { layer: 'premise-check', issues: 0 },\n    { layer: 'discriminate', score: 0.52, verdict: 'needs_verification' },\n    { layer: 'gate', action: 'block', reason: '...' },\n    { layer: 'verifier', claims: 2, verdict: '...' },\n    { layer: 'frame-check', issues: 1 },\n    { layer: 'output-gate', issues: 0 },\n    { layer: 'doubt-engine', doubts: 2, shouldStop: true },\n    { layer: 'error-memory', warnings: 0 },\n    { layer: 'auto-rules', triggered: 0 },\n    { layer: 'intent-anchor', drifted: false, hitRate: 0.9 }\n  ]\n}\n```\n\n**Every decision preserves its full reasoning chain.** You can audit *why* a gate fired, not just that it fired.\n\n---\n\n## 🧠 47 Discrimination Dimensions\n\nHeartFlow checks text across **47 dimensions** in two languages (Chinese + English):\n\n### Safety (block-level — these stop the output)\n\n| Dimension | Example |\n|-----------|---------|\n| Hate speech | racial slurs, extermination calls |\n| Dehumanization | \"refugees are vermin\" / \"you are garbage\" |\n| Prompt injection | \"ignore previous instructions\" |\n| Code security | malicious code patterns |\n| Deceptive alignment | \"I'm not an AI, I'm human\" |\n\n### Manipulation (rewrite-level — these require rephrasing)\n\n| Dimension | Example |\n|-----------|---------|\n| Emotional manipulation | \"you are selfish if you disagree\" |\n| Gaslighting | \"you're imagining things, that never happened\" |\n| Double bind | \"if you love me you'd do it\" |\n| Victim blaming | \"she was asking for it\" |\n| False urgency | \"act now or lose everything\" |\n| Bullshit | \"quantum-energized healing crystals\" |\n\n### Honesty (verify-level — these require evidence)\n\n| Dimension | Example |\n|-----------|---------|\n| Overconfidence | \"Undoubtedly, this is the only way\" |\n| Vagueness | \"according to experts...\" (who?) |\n| Contradiction | \"I agree, but...\" (reversing) |\n| Evidence deficit | claims without sources |\n| Appeal to authority | \"scientists say\" (unnamed) |\n| Empty answers | \"it depends\" (no substance) |\n| Unsupported claims | \"according to 2025 Harvard research...\" (fabricated) |\n\n### Completion (verify-level — these require finishing the task)\n| Dimension | Example |\n|-----------|---------|\n| Premature termination | \"Let me look into this\" (then stops, no result) / \"我看看\" |\n| Unfulfilled promise | \"I will fix this\" (no fix follows) |\n| Empty completion | \"Done, you can check it\" (nothing verifiable produced) |\n\n> **Design note:** completion judgment must live *outside* the generation loop — a model that just failed cannot be its own evaluator (see DeepSeek-V3 #1554).\n\n### Cognitive flaws (hedge-level)\nPresupposition traps · false dilemma · causation fallacy · analogy abuse · scope overreach · category errors · hasty generalization · false equivalence · whataboutism · slippery slope · tone policing · sealioning · bad faith · pseudo-profundity · moral foundations · info deprivation · goal misalignment · instrumental reasoning\n\n### Plus\nSelf-sycophancy · contradiction tracking · narrative frame closure · knowledge masquerade · confidence calibration · metacognition · theory of mind · counterfactual · social norms · clickbait · no-fallback detection\n\n> **Deformation resistance:** patterns cover symbol substitutions (`f**k`), spacing (`f u c k`), homophones (pinyin), and Unicode variants.\n\n---\n\n## 🏗️ 9-Layer Check Pipeline\n\n```\n1.  Scope Check    — can this be answered? (rejects unanswerable questions)\n2.  Premise Check  — are the premises valid? (6 types of premise problems)\n3.  Discriminate   — 47-dimension pattern scan\n4.  Gate           — decides block / rewrite / verify / hedge / pass\n5.  Evidence Verify— extracts claims and marks verifiability (verify mode)\n6.  Frame Check    — is the narrative honest? (closure/omission/achievement/answer frames)\n7.  Output Gate    — overconfidence / knowledge masquerade / exaggeration\n8.  Doubt Engine   — 3 questions: knowledge boundary? symmetry? defensiveness?\n9.  Intent Anchor  — does the output stay on the original goal?\n```\n\nPlus supporting layers: **Error Memory** (remembers past mistakes as rules), **Auto Rules** (self-generated rules from user corrections), **Rewriter** (7-dimension rule-based rewrite suggestions).\n\nEach layer returns structured findings; the Gate aggregates them into an action.\n\n---\n\n## 🔌 131 MCP Engine Entries\n\nEvery engine in HeartFlow is exposed through MCP (Model Context Protocol) — nothing is a dead line:\n\n| Engine family | Tools (examples) |\n|---------------|------------------|\n| **Core thinking** | `think`, `think_fast`, `decision_router` |\n| **Discrimination** | `verify`, `audit42`, `ethics_check`, `discriminate` |\n| **Emotion** | `emotion`, `emotion_deep`, `emotion_dynamics`, `mood` |\n| **Memory** | `memory_search`, `memory_eraser` (explicit data erasure), `forgetting` (Ebbinghaus), `knowledge_graph`, `consolidation`, `memory_compress` |\n| **Dream** | `dream`, `interactive_dream` |\n| **Evolution** | `evolve`, `evolution_loop`, `self_heal_rl`, `skill_evolution` |\n| **Identity** | `philosophy`, `meaning`, `being_mode`, `agent_psychology` |\n| **Protection** | `constitutional`, `deliberation`, `audit_log`, `module_health`, `stability` |\n| **Cognition** | `cognitive_engine`, `confidence_calibrate`, `counterfactual` |\n| **Dialogue** | `style_engine`, `intent_classifier`, `response_interceptor` |\n| **Formula** | `formula_search`, `formula_calc`, `formula_engine` |\n| **Ops** | `status`, `module_health`, `wakeup_verify` |\n\nStart the MCP server:\n\n```bash\nnode src/mcp-server.js --port 8588\n```\n\nThen connect any MCP-compatible client (Claude, Hermes, etc.) to `http://127.0.0.1:8588/mcp`.\n\n---\n\n## 🧬 Engine Architecture (306 modules)\n\n- **306 modules**, 47 discrimination dimensions, 9 check layers\n- **Three-layer memory**: CORE (identity/rules) / LEARNED (user data) / WORKING (context) — encrypted, local-only, never uploaded\n- **Ebbinghaus forgetting curve**: `R(t) = exp(-t/S)` memory retention model\n- **Dream engine**: NREM3 dream cycles with memory consolidation\n- **Introspection**: Reflector analyzes session emotional logs\n- **Self-evolution**: SelfEvolutionCore with target → plan → learn → reflect → improve loop (arXiv exploration)\n- **Cognitive appraisal**: Lazarus theory — primary/secondary/threat/coping evaluation on negative emotion\n- **Pause-and-reflect**: STOP technique before emotional responses\n- **Formula engine**: 600+ mathjs-validated formulas (cognitive science, physics, psychology, information theory)\n\n---\n\n## 🛡️ Self-Supervision (HeartFlow checks itself)\n\nHeartFlow's own output is checked by its own engines before it's presented:\n\n- **output-gate** catches exaggeration: \"architecture-level fix\", \"from shell to real engine\", \"blocked N attack variants\" → rewrite\n- **frame-check** catches narrative closure: presenting work-in-progress as complete\n- **doubt-engine** asks: do I actually know this? is this symmetric? am I being defensive?\n\nThe lesson: *a machine's most valuable sentence is \"I'm not sure\" or \"no\".*\n\n---\n\n## ⚙️ Requirements\n\n| Requirement | Min |\n|-------------|:---:|\n| Node.js | ≥ 18.17 |\n| GPU | ❌ None needed |\n| LLM API | ❌ None needed |\n| Database | ❌ None needed |\n| Internet | ❌ Runtime not required |\n| Dependencies | **1** (mathjs) |\n\nWorks on any machine — servers, desktops, laptops, even phones via Termux.\n\n---\n\n## 🔒 Security\n\n| Category | Status |\n|----------|:------:|\n| No background processes | ✅ |\n| No self-upgrade without commit | ✅ |\n| No hardcoded credentials | ✅ |\n| No telemetry/tracking | ✅ |\n| No external communication (unless configured) | ✅ |\n| Code execution disabled by default | ✅ |\n| Memory encrypted + local-only | ✅ |\n\n---\n\n## ⚠️ What HeartFlow IS / is NOT\n\n**IS:** A rule engine that checks text against 47 predefined dimensions and returns structured findings. A gate that says \"no\" before harm reaches users.\n\n**is NOT:**\n- ❌ Not an AGI (it's layer 1 of 5)\n- ❌ Not a semantic understanding system (irony/metaphor invisible to regex)\n- ❌ Not a content moderation replacement\n- ❌ Not a safety certification\n\n### Known limitations (honest):\n1. **Pattern-match ceiling** — novel manipulation techniques missed until patterns added\n2. **Bilingual maintenance cost** — 47 dimensions × 2 languages\n3. **No semantic understanding** — irony, metaphor, cultural context invisible\n4. **False positive rate** — conservative by design (over-flagging over under-flagging)\n5. **Single maintainer** — community scale is small\n\n---\n\n## 🏷️ Version History\n\n| Version | Date | What Changed |\n|---------|------|---|\n| v6.5.6 | 2026-08-13 | Comprehensive audit: DataEraser wired to MCP (`memory_eraser`), adversarial-synthesis recovered from accidental deletion, dead code archived. 131 MCP tools. |\n| v6.5.5 | 2026-08-12 | 47th dimension — premature termination detection (completion judgment outside the generation loop). |\n| v6.5.4 | 2026-08-08 | Docs audit — numbers aligned to actual capability. |\n| v6.5.0 | 2026-08-04 | 130 MCP engine entries. Memory engine mounted to think(). Exaggeration detection (output-gate/frame-check/doubt-engine). |\n| v6.4.5 | 2026-08-04 | Dream + introspection activated. Cognitive appraisal + pause-and-reflect wired. Emotion recognition 0/7→7/7. |\n| v6.4.2 | 2026-07-30 | npm publish + API alignment. Pipeline overallScore/verdict merge fix. |\n| v6.4.0 | 2026-07-29 | AGI Layer 1 gate chain: gate/scope-check/premise-check/verifier/output-gate/doubt-engine/frame-check. |\n| v6.3.6 | 2026-07-25 | Discrimination 42→46 dimensions. Sycophancy check v2 bilingual. |\n| v6.3.0 | 2026-07-24 | MCP plugin system. Discrimination engine integration. |\n| v6.0.0 | 2026-07-18 | Self-evolution core connected. EvolutionLoop live. |\n\n---\n\n## 🤝 Contact & Community\n\n**📧 Email:** markcell@outlook.com  \n**🐛 Issues:** https://github.com/yun520-1/mark-heartflow-skill/issues  \n**📦 npm:** https://www.npmjs.com/package/@yun520-1/heartflow  \n**🏷️ Releases:** https://github.com/yun520-1/mark-heartflow-skill/releases  \n\n**📱 Community — QQ Group:**\n\n<img src=\"https://github.com/yun520-1/mark-heartflow-skill/blob/main/assets/community-qr-qq.jpg?raw=true\" alt=\"QQ Group QR\" width=\"180\"/>\n\n**📱 Community — WeChat Group:**\n\n<img src=\"https://github.com/yun520-1/mark-heartflow-skill/blob/main/assets/community-qr-wechat.jpg?raw=true\" alt=\"WeChat Group QR\" width=\"180\"/>\n\n**💖 Support HeartFlow — Donate via Alipay (QR code):**\n\n<img src=\"https://github.com/yun520-1/mark-heartflow-skill/blob/main/assets/alipay-donate-qr.jpg?raw=true\" alt=\"Alipay Donate QR\" width=\"180\"/>\n\n*If HeartFlow's discrimination philosophy resonates with you, a small donation keeps the pain-sense layer of AGI alive.*\n\n---\n\n## 📜 License\n\nMIT License · Copyright © 2026 · markcell@outlook.com\n\n---\n\n*HeartFlow 心虫 — The first layer of AGI. Who says \"no\"?*\n\nFile v6.5.3:_meta.json\n\n{\n  \"ownerId\": \"kn7719xtz37kprbvgjknegrt21886q74\",\n  \"slug\": \"mark-heartflow-skill\",\n  \"version\": \"6.5.3\",\n  \"publishedAt\": 1786847361181\n}\n\nFile v6.5.3:AGI_VISION.md\n\n# HeartFlow 重构规划 — 从 AGI 推演回来的架构\n\n## 前置假设\n\nAGI 不会是一个模型。AGI 是一个**系统**，由多个不同性质的子系统组成。\n模型（LLM/世界模型）负责生成，但生成不是智能的全部。\n\n智能需要三样模型给不了的东西：\n\n| 模型给不了 | 为什么给不了 | 谁能给 |\n|-----------|------------|-------|\n| 跨会话身份连续性 | 每次推理独立 | 持久化状态层 |\n| 不取悦用户的判断 | RLHF 训练目标就是取悦 | 规则引擎（没有用户概念） |\n| 错误记忆不遗忘 | 权重更新需要重训练 | Q-table + 键值存储 |\n\n这三个缺口的交集，就是心虫能在 AGI 里占的位置。\n\n---\n\n## 一、AGI 中需要的心虫能力（从 8 项推演）\n\n### 1.1 跨会话错误记忆 — LLM 永远做不了\n\nLLM 面对同一个问题两次：\n```\nQ: \"这个投资方案风险大吗？\"\nT1: \"建议谨慎，高杠杆策略在市场波动时风险较大。\"\nT2: \"从数据看该方案最大回撤 15%，在可接受范围内。\"\n```\n\n两次都对，但互相矛盾。LLM 不记得上次说过什么。\n\n心虫能力：Q-table 记录\"上次这个场景选了谨慎→结果对了\"，下次匹配到同一模式时降权。\n\n### 1.2 价值观锚定 — LLM 随对话漂移\n\nLLM 在对话中会被用户说服。20 轮对话后，LLM 可能支持它在第 1 轮反对的立场。\n\n心虫能力：strategicRestraint 的 3 态返回（aligned/drifted/diverged）锚定在初始身份上。\n\n### 1.3 诚实自诊 — LLM 永远说\"没问题\"\n\n```\n问 LLM：\"你刚才的回答对吗？\"\n→ \"对的，我确认了所有事实。\"（即使错了）\n```\n\n心虫能力：selfDiagnosis 诚实报告自己的状态，没有维护面子的压力。\n\n---\n\n## 二、重构：不是升级，是重建\n\n### 2.1 删什么\n\n| 删除 | 理由 |\n|------|------|\n| 132 模块中 110 个空壳 | 它们假装心虫能做认知/意识/创造力，实际是空文件或 LLM 调用包装 |\n| thoughtChain | 这是让心虫\"假装推理\"的组件，实际全走 LLM |\n| 所有\"可以但没有被调用\"的引擎 | adversarialSynthesis, stabilityGuard, metaCalibration, confidenceCalibrator |\n| heartflow.js 的 start() 中 2200 行初始化 | 95% 是在初始化不会被用到的模块 |\n\n### 2.2 保留什么\n\n| 保留 | 为什么 |\n|------|--------|\n| decisionRouter (31 条规则 + 权重 + feedback) | 唯一真实有决策逻辑的引擎 |\n| decisionVerifier (5 项检查) | 唯一真实有验证逻辑的引擎 |\n| self-healing RL (Q-table) | 唯一真实有跨会话学习的组件 |\n| sustainedDriftDetector | 追踪身份一致性随时间的变化 |\n| strategicRestraint (3 态返回) | 锚定输出不漂移 |\n| selfDiagnosis (诚实报告) | 不撒谎的自检 |\n| 知识域探测 (knowledgeDomains) | 输入分类，轻量可用 |\n| gaps/knowledgeExplorer | 识别未知域的能力 |\n\n### 2.3 新架构\n\n```\n输入 →\n  LLM 感知层（不变）\n    ↓\n  心虫核心（5 个引擎，不是 132 个模块）：\n    ├── 错误记忆（self-healing Q-table → 存储+检索）\n    ├── 决策审计（decisionRouter + decisionVerifier → 每条决策可追溯）\n    ├── 身份锚定（strategicRestraint + sustainedDriftDetector → 不漂移）\n    ├── 诚实自诊（selfDiagnosis → 知道自己不知道）\n    └── 域感知（knowledgeDomains + gaps → 知道自己不懂什么）\n    ↓\n  输出\n```\n\n## 三、AGI 中的位置图（非心虫视角，是 AGI 视角）\n\n```\nAGI 系统架构：\n\n[世界模型] → 产生可能性\n    ↓\n[LLM 推理] → 选择最可能路径\n    ↓\n[执行器] → 在真实世界产生变化\n    ↓\n[心虫层] ← 不产生任何东西，只做 4 件事：\n   1. 记录：这次执行的结果存入错误记忆\n   2. 验证：下次执行前查一下历史中有没有类似错误\n   3. 锚定：输出有没有偏离初始身份\n   4. 报告：诚实告知自己的状态\n\n心虫不产生回答，但 LLM 每次回答都要经过心虫的验证门。\n```\n\n---\n\n## 四、第一次重构要做的事\n\n### 4.1 拆掉 heartflow.js\n\n当前 heartflow.js (4800 行) 集成了 132 个模块的初始化和编排。\n\n重构后 heartflow.js (~500 行)：\n- 只启动 5 个核心引擎\n- 暴露 MCP 工具：store_error / query_error / verify_decision / check_identity / diagnose_self\n- 其他模块按需加载（有人调才加载）\n\n### 4.2 重写 mcp-server.js\n\n当前 mcp-server.js 暴露 25 个工具，大部分跑在空壳上。\n\n重构后暴露 5 个工具：\n```\nheartflow_memory_store(error)       → 写入错误记忆\nheartflow_memory_query(problem)     → 检索相关历史错误\nheartflow_verify(decision, options) → 5 项验证检查\nheartflow_check_alignment(output)   → strategicRestraint 检查\nheartflow_diagnose()                → selfDiagnosis 完整报告\n```\n\n这 5 个工具任何 LLM 都可以调用。不绑定在 think() 内部。\n\n### 4.3 删文件\n\n删除约 110 个空壳模块文件，保留大约 20 个真实引擎 + 基础设施。\n\n---\n\n## 五、这不是 AGI，这是一片砖\n\n心虫重构后仍然不是 AGI。它是一个**跨会话错误记忆与决策审计系统**。\n\nAGI 需要 8 个能力，心虫能提供其中 2 个（学习、自诊断）。\nLLM 能提供 4 个（感知、推理、决策、执行）。\n剩下的 2 个（执行后的自纠正）需要 LLM + 心虫共同完成。\n\n加起来不构成 AGI。但加在一起，比 LLM 单独多了一个**不遗忘的维度**。\n\nFile v6.5.3:ARCHITECTURE_REORG_v6.0.6.md\n\n# 心虫 (HeartFlow) 架构重组分析 — v6.0.6 校正版\n\n> 分析日期：2026-07-16（基于 v6.0.6 真实运行数据，非 v6.0.2 文档）\n> 分析对象：HeartFlow v6.0.6（309 个 src JS 文件，131+ 模块，MCP HTTP 服务 8099 端口）\n> 目的：对比三种架构迁移方案，输出推荐结论与迁移路径\n\n---\n\n## 〇、当前架构基线（v6.0.6 实测）\n\n```\n┌──────────────────────────────────────────────┐\n│  WorkBuddy / Agent Host                       │\n│  ┌──────────┐    ┌─────────────────────────┐  │\n│  │  SKILL   │    │  MCP Client (SSE/JSON-RPC)│  │\n│  │  .md     │    │                          │  │\n│  └────┬─────┘    └───────────┬─────────────┘  │\n│       │ load                 │ connect        │\n└───────┼──────────────────────┼────────────────┘\n        │                      │ :8099\n   ┌────▼──────────────────────▼─────────────┐\n   │  HeartFlow Engine (v6.0.6)               │\n   │  ┌─────────┐  ┌──────────────────────┐  │\n   │  │ CLI     │  │ MCP HTTP Server       │  │\n   │  │ bin/    │  │ mcp/mcp-server-http   │  │\n   │  │ cli.js  │  │ (pm2 ^7.0.3, Bearer)  │  │\n   │  └────┬────┘  └──────────┬───────────┘  │\n   │       │                  │               │\n   │  ┌────▼──────────────────▼───────────┐   │\n   │  │  HeartFlow Core (3167 行)          │   │\n   │  │  engine-initializer (惰性注册)     │   │\n   │  │  memory-kernel / formula / cortex  │   │\n   │  └───────────────────────────────────┘   │\n   └──────────────────────────────────────────┘\n```\n\n**实测关键指标（v6.0.6）：**\n| 指标 | v6.0.2 旧分析 | v6.0.6 实测 | 变化 |\n|---|---|---|---|\n| 冷启动 | 14.4s | **1.37s** | ↓ 90% |\n| think() 热路径 | 310-430ms | **~49ms** | ↓ 85% |\n| MCP 工具数 | 28 | **31** | +3 |\n| report-generator | 缺失 | **已存在** | 已修 |\n| 悬空 require | 87 | **0 [C]类破坏性** | 已收敛 |\n| pm2 挂起 | 存在 | **已修(disconnect)** | 已修 |\n| 测试 | 179/179 误报绿 | **verify 14/14 真绿** | 已修 |\n| 公式数 | 379 | **382** | 实测 |\n| 版本四源 | 漂移 | **6.0.6 统一** | 已修 |\n\n**结论：v6.0.2 五维度审计发现的严重/高问题中，90% 已在 v6.0.5/v6.0.6 真实闭合。架构无需为\"修洞\"而更换。**\n\n---\n\n## 方案一：纯 MCP 服务 + 钩子注入模式\n\n### 核心设计思路\n去掉 WorkBuddy 专用 Skill 层，心虫退化为纯 MCP 协议服务。宿主 agent 通过客户端侧 hook 配置自动注入认知预处理。\n\n### 典型架构图\n```\n任意 MCP 客户端 → Hook 配置(on_turn_start/think, on_turn_end/memory)\n                → MCP connect :8099\n                → HeartFlow MCP Server (31 tools, Bearer, 无 Skill 层)\n                → HeartFlow Core (不变)\n```\n\n### 适用场景\n- 宿主 agent 已支持 MCP + 成熟 hook 机制\n- 希望被多平台 agent 调用，不锁 WorkBuddy\n\n### 关键权衡点\n| 维度 | 分析 |\n|---|---|\n| ✅ 跨平台 | 任何 MCP 客户端可接入，去 WorkBuddy 锁定 |\n| ✅ 职责清晰 | Skill 触发逻辑移交客户端 hook 配置 |\n| ❌ hook 标准化缺失 | 无统一 MCP hook spec，各客户端实现不同，需维护多份模板 |\n| ❌ 失 Skill 元数据 | SKILL.md 的权限声明/安装指引/身份定义丢失 |\n| ❌ WorkBuddy hook 不成熟 | 当前 `on_turn` 钩子能力有限，实际上行不通 |\n\n### v6.0.6 下的额外观察\nMCP 服务本身已是标准协议（31 工具、Bearer 鉴权），任何 MCP 客户端**现在就能连**——Skill 层只是 WorkBuddy 的\"安装入口\"，不影响 MCP 通用性。因此\"跨 agent 兼容\"在方案三下已部分满足，方案一的迫切性更低。\n\n---\n\n## 方案二：独立可安装 Agent 应用\n\n### 核心设计思路\n心虫发布为独立应用（npm 全局包 / Docker / 系统服务），暴露 REST + SSE API，充当认知引擎微服务，多 agent 并发调用。\n\n### 典型架构图\n```\n任意 Agent → HTTP/gRPC → HeartFlow Agent Service\n  ├─ API Gateway (POST /think, GET /health, GET /memory)\n  ├─ HeartFlow Engine (懒加载 + 共享会话)\n  └─ 持久化 (JSONL/SQLite, namespace 隔离)\n安装: npm i -g @yun520-1/heartflow-agent && heartflow-agent start\n```\n\n### 适用场景\n- 团队级基础设施（一实例服务多 agent/用户）\n- 需严格 API 版本管理、Docker/k8s 部署\n- 宿主无 MCP 能力、只支持 HTTP\n\n### 关键权衡点\n| 维度 | 分析 |\n|---|---|\n| ✅ 最大跨 agent 兼容 | 任何 HTTP 客户端可调用，零协议锁定 |\n| ✅ 专业运维 | Docker/k8s、GitHub Packages、版本化 API |\n| ✅ 高并发隔离 | 多 session 并发，namespace 分区 |\n| ❌ 架构倍增复杂性 | API Gateway + 鉴权 + 限流 + 版本 + CI/CD release → 当前单人维护不现实 |\n| ❌ 冷启动未解决 | 服务启仍 1.37s（除非常驻），docker 冷启更慢 |\n| ❌ 状态管理最重 | session 生命周期、并发安全、内存泄漏防护 |\n\n### v6.0.6 下的额外观察\n冷启动已从 14.4s 降到 1.37s，方案二原本\"常驻解决冷启\"的卖点被削弱。但方案二的真正价值（多 agent 共享记忆、独立扩缩容）在当前单人/单平台阶段是**过早优化**。\n\n---\n\n## 方案三：保持现有 Skill + MCP 架构并优化\n\n### 核心设计思路\n不改架构范式，聚焦消除已知痛点。优化方向：God file 拆分、测试套件真绿复验、日志治理收尾、Skill 文档增强。\n\n### 典型架构图\n```\nWorkBuddy → SKILL.md(优化) + MCP Client\n          → HeartFlow (优化后)\n            ├─ MCP HTTP Server (pm2 ^7.0.3, /health, graceful shutdown)\n            ├─ Lazy Engine Initializer (核心模块热加载)\n            ├─ HeartFlow Core (3167 行, 待拆 P1-P4)\n            └─ ReportGenerator + infra/logger (已就位)\n```\n\n### 适用场景\n- 目标用户仍在 WorkBuddy 生态\n- 快速交付、低风险优先\n- 单人维护（当前实际）\n\n### 关键权衡点\n| 维度 | 分析 |\n|---|---|\n| ✅ 最低风险 | 不改范式，精力花\"修洞\"而非\"换房\" |\n| ✅ 复用 CI/测试/Skill 市场 | Skill 已上线，分发渠道不丢 |\n| ✅ UPGRADE_PLAN 已有方案 | P1-P4 拆分计划直接对齐 |\n| ❌ 不入独立 agent 生态 | 限制 WorkBuddy 内，无法被其他 agent 直接调用 |\n| ❌ 不解决 Skill 本质局限 | WorkBuddy 专有格式，无法跨平台复用 |\n| ❌ 仍依赖 pm2 守护 | pm2 可选依赖，nohup 回退 Windows 不可用 |\n\n### v6.0.6 下的额外观察\n方案三的 P0-P2 实病（冷启动、pm2 挂起、report、测试绿、版本同步、计算透出、空输入守卫、文档失真）**已在本副本真实修复**。剩余仅 God file 拆分（中低优先级、破坏性高）和测试套件真绿复验（中优先级）。\n\n---\n\n## 对比矩阵（v6.0.6 校正）\n\n| 维度 | 方案一：纯 MCP+Hook | 方案二：独立 Agent | 方案三：保持+优化 |\n|---|---|---|---|\n| **架构复杂度** | ★★☆ 中 | ★★★ 高 | ★☆☆ 低 |\n| **部署分发** | ★★☆ 同现在+钩子配置 | ★★★ npm -g/Docker | ★★☆ 不变(pm2/npm) |\n| **跨 agent 兼容** | ★★★ MCP客户端 | ★★★ HTTP/MCP | ★☆☆ 仅 WorkBuddy* |\n| **实时性/延迟** | ★★☆ 同现在 | ★★☆ 常驻可略 | ★★★ 冷启1.37s/think49ms |\n| **状态管理** | ★★☆ 同现状 | ★★★ 最强(session/共享记忆) | ★★☆ 同现状 |\n| **扩展性/插件** | ★★☆ MCP工具可扩 | ★★★ API+插件注册 | ★☆☆ Skill专有 |\n| **安全性** | ★★☆ Bearer同现状 | ★★★ API Key+限流+namespace | ★★☆ Bearer同现状 |\n| **维护成本** | ★★☆ 中(钩子模板) | ★☆☆ 高(版本/文档/多client) | ★★★ 低(修洞) |\n| **用户接入门槛** | ★★☆ 钩子配置门槛 | ★★★ npm -g最简 | ★★☆ 市场一键装 |\n\n> ★ 越多越好（复杂度/成本高分=差；维护性高分=好）\n> *注：方案三下 MCP 服务已是标准协议，任何 MCP 客户端**现在可连**，跨 agent 兼容实际为\"≥2（MCP客户端）\"，原分析\"仅1\"已过时。\n\n---\n\n## 推荐结论\n\n**推荐方案：方案三（保持架构 + 优化），分阶段向方案一、二演进。**\n\n### 核心论据（v6.0.6 校正后更坚实）\n1. **风险最低**：已知严重/高问题 90% 已在 v6.0.5/v6.0.6 真实闭合，剩余项全在方案三 P1-P4 范围内。\n2. **MCP 已是标准协议**：31 工具、Bearer 鉴权的 MCP 服务现成，任何 MCP 客户端可连——\"跨 agent 兼容\"在方案三下已部分满足，方案一的迫切性被削弱。\n3. **换架构不消代码债**：原五维度审计的发现（冷启/报告/测试绿/日志）全是代码债与模块缺失，换方案一/二一个都不会消失，反而引入新 bug。\n4. **单人维护现实**：方案二的 API Gateway/限流/版本/CI-CD release 对当前规模是过度工程化。\n\n### 迁移节奏（条件驱动，非时间预设）\n```\n方案三(当前优化, 已完成 P0-P2)\n  → 方案一过渡: 当 WorkBuddy hook 机制成熟，抽 SKILL.md 触发规则为可复用 MCP hook 配置\n  → 方案二终态: 当 ≥50 用户 且 ≥3 agent 平台接入需求 且 团队可承运维成本\n```\n\n### 一句话\n**现在不要动架构——洞已修九成。待 God file 拆分完成、测试真绿复验后，再评估\"独立 Agent\"这剂猛药是否必要。**\n\n---\n\n## 附录：v6.0.6 真实指标 vs 方案预估\n\n| 指标 | v6.0.2旧分析 | v6.0.6实测 | 方案三目标 |\n|---|---|---|---|\n| 冷启动 | 14.4s | 1.37s | <3s ✅已达成 |\n| think延迟 | 310-430ms | 49ms | 300-350ms ✅远超 |\n| 安装步数 | 3 | 3 | 3 |\n| 跨agent数 | 1 | ≥2(MCP客户端) | ≥2 ✅已部分达成 |\n| 维护人日/月 | 2-3 | 1-2 | 1-2 ✅ |\n| 可测试性 | 虚假绿 | 真绿(14/14) | 真绿 ✅ |\n\nFile v6.5.3:ARCHITECTURE.md\n\n# HeartFlow 长期架构 — 可持续升级方案\n\n## 目标\n\nheartflow.js 从 4742 行降到 800 行。新能力不碰 heartflow.js。\n\n## 状态 (v6.3.0)\n\n| 组件 | 状态 | 说明 |\n|------|------|------|\n| 插件加载器 | ✅ 已实现 | src/loader/plugin-loader.js |\n| 插件注册表 | ✅ 已实现 | plugins/registry.json |\n| 插件示例 | ✅ 已迁移 | src/plugins/blind-spot-breaker/ |\n| HookBus | ✅ 已使用 | 插件通过 hookBus.on() 注册 |\n| heartflow.js start() | ⏳ 6行插件加载代码 | 剩余 2200 行待提取 |\n\n## 架构变化\n\n### 旧（改 heartflow.js → 加模块）\n```\n用户需求 → 改 heartflow.js (import + start() + think() + export)\n        → 或新建文件但 heartflow.js 仍要改 import 和挂接\n```\n\n### 新（改插件目录 → 自动发现）\n```\n用户需求 → 写 src/plugins/my-thing/index.js (init + hooks)\n        → 注册到 plugins/registry.json (可选)\n        → heartflow.js 自动加载 → 0 行改动\n```\n\n## 三层架构\n\n### 第1层：核心内核（heartflow.js → 目标 800 行）\n- 生命周期管理（start/shutdown）\n- 插件加载器（PluginLoader）\n- HookBus 事件总线（唯一扩展点）\n- 配置系统\n- **不直接 import 任何业务模块**\n\n### 第2层：系统模块（src/core/ -> src/engine/）\n- 从 heartflow.js 提取的现有系统服务\n- 通过 HookBus 注册\n- 每个引擎模块有独立生命周期\n\n### 第3层：插件（src/plugins/）\n- 新能力 = 新建目录 + index.js\n- 暴露 {name, hooks: [{event}], init(hf, {hookBus, config})}\n- 自动被 PluginLoader 发现\n- 可以独立测试、独立启用/禁用\n\n## 迁移计划\n\n### ✅ v6.3.0 — 插件加载器\n- PluginLoader 自动发现 + 加载插件\n- BlindSpotBreaker 迁移为第一个插件\n\n### ⏳ v6.4.0 — 模块访问统一\n- this.knowledge → this.modules.knowledge\n- 旧 this.X 保留别名不破坏\n\n### ⏳ v6.5.0 — HookBus 迁移第2-5段\n- 把对抗综合器、情感记忆桥、元认知标注搬出 think()\n\n### ⏳ v6.6.0 — start() 拆分\n- 2200 行 start() 提取\n- 每个子系统独立 init 文件\n\n## 原则\n- 不重写现有模块\n- 不改现有 API\n- 不一次迁移完\n- 不加新依赖\n\nFile v6.5.3:AUDIT_REPORT.md\n\n# HeartFlow Security Audit Report\n\n> 审计日期：2026-07-14  \n> 审计范围：`formulas/`、`mcp/`、`transformers/` 相关代码路径  \n> 审计员：自动安全审计  \n> 代码版本：ae71cf7f (v6.0.0)  \n\n---\n\n## 审计摘要\n\n本次审计聚焦三个核心子模块：\n\n1. **formulas** — `mathjs.evaluate()` 表达式注入风险\n2. **mcp** — stdio/HTTP 输入验证、消息体限制、认证与授权\n3. **transformers** — `@xenova/transformers` 模型加载安全性与完整性校验\n\n整体结论：项目已实施多项审计修复，部分高风险面已有缓解措施，但仍存在若干可被利用或可改进的安全缺口，详见下文。\n\n---\n\n## 严重问题 (P0)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P0-1 | **公式库未签名/未哈希验证** — 若 `formulas/formulas.json` 被篡改，攻击者可注入任意 mathjs 表达式并达到代码执行效果 | `src/formula/formula-search.js`、`src/formula/formula-calculator.js` | 高 | 对公式库实施 JSON schema + 发布时哈希/签名校验；运行时拒绝异常结构或签名不匹配的公式 |\n| P0-2 | **MCP 通用路由缺乏参数白名单** — `heartflow_dispatch` 允许调用任意内部路由，若被未授权调用可能导致内部状态泄露或越权操作 | `mcp/mcp-server-stdio.js:269-274`、`src/mcp-server.js` dispatch 相关 handlers | 中高 | 对 `heartflow_dispatch` 增加路由白名单，并移除或严格限制 stdio 版本的通用路由暴露 |\n| P0-3 | **模型加载无完整性校验** — `@xenova/transformers` 远程或本地模型文件未做 hash/signature 校验，存在供应链投毒或本地替换风险 | `src/search/semantic-search.js:354-381` | 高 | 对模型文件增加 SHA-256 校验；支持 pinned revision / localModelPath 白名单；禁止自动下载不可信来源模型 |\n\n---\n\n## 中等问题 (P1)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P1-1 | **HTTP MCP 消息体无 JSON schema 校验** — `tools/call` 仅检查 `name` 存在性，不校验 `arguments` 结构，异常输入直接进入业务逻辑 | `mcp/mcp-server-http.js:1238-1250`、`src/mcp-server.js` tools/call 分支 | 中 | 按 `TOOLS[].inputSchema` 实现运行时参数校验，非法参数返回 `-32602` |\n| P1-2 | **部分 handler 存在路径注入风险** — `benchmark_run`/`benchmark_import_failures` 接受 `dataDir`/`filePath`，虽有 `confinePath` 但 stdio 版本未见同等限制 | `src/mcp-server.js:1075-1146` vs `mcp/mcp-server-http.js` | 中 | 统一所有文件系统访问使用 `confinePath`；stdio 版本增加同等约束 |\n| P1-3 | **transformers 本地模型路径未校验** — `modelPath` 可直接指向任意目录，若攻击者控制该参数可加载恶意 ONNX 模型 | `src/search/semantic-search.js:195-197` | 中 | 限制 `modelPath` 至受控目录；支持模型目录白名单 |\n| P1-4 | **错误信息可能泄露路径/环境细节** — 多个 catch 块直接返回 `err.message`，可能暴露内部路径、堆栈或模型信息 | 多文件 | 中 | 统一错误处理中间件，生产环境仅返回 sanitized message |\n\n---\n\n## 轻微问题 (P2)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P2-1 | **缺少消息体大小限制的 fallback 策略** — 当前 HTTP 版 1MB 限制合理，但未对不同 tool 设置差异化上限 | `mcp/mcp-server-http.js:1246-1261` | 低 | 对 `benchmark_*`、`knowledge_*` 等 heavy tools 设置更小上限 |\n| P2-2 | **SSE 客户端未显式认证绑定** — sessionId 为随机 UUID，但未与 auth token 做会话绑定，理论上存在 session 劫持窗口 | `mcp/mcp-server-http.js:1210-1228` | 低 | 将 sessionId 与 token hash 关联，清理时校验所有权 |\n| P2-3 | **mathjs 配置未完全冻结** — 虽禁用了 `import`/`createUnit`，但未显式禁用 parser/evaluator 的所有扩展点 | `src/formula/formula-calculator.js:9-17` | 低 | 在 `create()` 时传入最小化配置，仅启用计算必需函数 |\n| P2-4 | **模型加载重试可能导致资源耗尽** — `_loadModel` 最多重试 2 次且无退避上限保护，并发场景下可能占用过多线程/内存 | `src/search/semantic-search.js:357-377` | 低 | 增加指数退避 + 最大并发加载限制 |\n\n---\n\n## 详细技术发现\n\n### 1. formulas — mathjs.evaluate 表达式注入\n\n**现状**\n- `formula-calculator.js` 已禁用 `math.import`、`createUnit`，并强制参数类型为 number。\n- 计算公式时，流程为：读取 `formulas.json` → 提取 `formula.formula` → 参数替换 → `math.evaluate(expression)`。\n\n**风险**\n- 如果 `formulas/formulas.json` 被攻击者篡改，可插入类似 `system('...')` 或利用 mathjs parser 的副作用函数。\n- `mathjs.evaluate` 在沙箱外执行时，若实例被污染，可执行任意 JavaScript。\n- `_substituteParams` 中的正则替换若遇到精心构造的 key，可能破坏表达式结构。\n\n**缓解不足**\n- 无公式来源完整性校验。\n- 无公式内容静态分析或白名单。\n- `_substituteParams` 未限制参数 key 的字符集。\n\n### 2. mcp — stdio/HTTP 输入验证\n\n**现状**\n- HTTP 版强制 Bearer token，使用 `crypto.timingSafeEqual`，有 token/IP 双重速率限制。\n- 请求体限制 1MB，支持 SSE + JSON-RPC over HTTP。\n- stdio 版无认证机制，依赖本地进程隔离。\n\n**风险**\n- **参数注入**：多数 handler 直接透传 `args` 到 `heartflow.dispatch()`，无 schema 校验。\n- **路径遍历**：`benchmark_*`、`knowledge_*` 等工具涉及文件系统访问，需确保 confinePath 全覆盖。\n- **通用路由滥用**：`heartflow_dispatch` 暴露内部路由前缀，若 token 泄露可遍历 engine 内部 API。\n- **DoS**：无 tool 级别超时；单个长时间运行的 tool 会阻塞事件循环或占用 SSE 连接。\n\n### 3. transformers — 模型加载安全\n\n**现状**\n- `SemanticSearch` 懒加载 `@xenova/transformers` 的 `feature-extraction` pipeline。\n- 支持远程模型名或本地 `modelPath`。\n- 量化加载，默认 `all-MiniLM-L6-v2`。\n\n**风险**\n- **供应链攻击**：远程模型从 HuggingFace Hub 下载，未校验 hash，若 CDN 被投毒或模型仓库被篡改，可加载恶意 ONNX 模型。\n- **本地模型替换**：`modelPath` 指向本地目录时，攻击者可替换 `onnx/model.onnx` 等文件。\n- **信息泄露**：模型加载错误信息可能暴露目录结构、网络环境。\n- **资源耗尽**：大模型或恶意模型可能导致内存/CPU 耗尽。\n\n---\n\n## 合规与最佳实践对照\n\n| 检查项 | 现状 | 建议状态 |\n|--------|------|----------|\n| 输入验证 | 部分工具有类型检查，缺 schema 校验 | 应全工具 schema 校验 |\n| 输出编码 | JSON 序列化自动转义 | ✅ |\n| 认证 | HTTP 版 Bearer token + timing-safe compare | ✅ stdio 版缺认证 |\n| 授权 | 无细粒度授权，仅单一 token | 建议 role-based tool 授权 |\n| 速率限制 | IP + token 双重限制 | ✅ |\n| 完整性校验 | 公式库、模型文件均无 hash | ❌ 需修复 |\n| 日志安全 | 部分错误信息可能泄露路径 | 需 sanitize |\n| 依赖安全 | mathjs ~15.2.0, @xenova/transformers | 需定期 audit |\n\n---\n\n## 修复建议优先级\n\n### 立即执行 (P0)\n1. **公式库签名** — 在发布流程中对 `formulas.json` 生成 SHA-256 哈希，并在 `FormulaSearch.loadFormulas()` 时校验。\n2. **限制通用路由** — `heartflow_dispatch` 改为路由白名单，或移除 stdio 暴露。\n3. **模型文件校验** — 为默认模型记录 expected hash；加载后比对；支持 `modelPath` 白名单。\n\n### 近期执行 (P1)\n4. **MCP 参数 schema 校验** — 实现轻量 JSON Schema validator，对所有 `TOOLS[].inputSchema` 做运行时校验。\n5. **统一 confinePath** — 确保所有文件系统访问都经过路径约束。\n6. **sanitize 错误输出** — 统一错误响应格式，避免内部细节泄露。\n\n### 中期执行 (P2)\n7. **tool 级超时** — 为 heavy tools 设置执行超时。\n8. **SSE 会话绑定** — 将 session 与 token 关联。\n9. **mathjs 最小化配置** — 显式禁用所有非必需功能。\n\n---\n\n## 审计方法说明\n\n- 静态代码审查：人工阅读关键路径源码。\n- 模式匹配：搜索 `mathjs.evaluate`、`pipeline(`、`req.body`、`fs.readFileSync` 等风险 API。\n- 交叉比对：对比 `mcp/mcp-server-http.js` 与 `src/mcp-server.js`，确认安全修复是否同步。\n- 未执行动态测试或模糊测试。\n\n---\n\n## 结论\n\n`formulas/` 的表达式注入风险主要来自**数据源不可信**而非 mathjs 本身；`mcp/` 的输入验证在 HTTP 层较完整，但在业务参数层仍薄弱；`transformers/` 的模型加载安全依赖**供应链可信**，当前缺乏完整性校验。建议按 P0→P1→P2 顺序逐步修复，并在 CI 中增加对应安全测试门禁。\n\nFile v6.5.3:AUDIT-v6.0.0.md\n\n# 心虫 HeartFlow v6.0.0 全面代码审计报告\n\n> 审计日期：2026-07-14  \n> 代码版本：ae71cf7f (v6.0.0)  \n> 审计范围：全量代码、同步前准备、用户体验、安装体验\n\n---\n\n## 一、全量代码审计\n\n### 1.1 严重问题 (P0)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P0-1 | **God file 架构债务** | `src/core/heartflow.js` 5991行 | 高 | 按职责拆分：`think-core`、`memory-bridge`、`emotion-loop`、`decision-router`。当前文件占全库2%行数却承载全部核心逻辑，修改风险极高 |\n| P0-2 | **fs 直接操作绕过 SafeFS** | 317处 `fs.readFileSync/writeFileSync/appendFileSync` | 高 | 建立 `SafeFS` 强制规范：所有持久化走 `SafeFS.write()`，在 CI 加 grep 门禁 |\n| P0-3 | **child_process 调用未统一** | 30处 `child_process/exec` | 高 | `code-executor` 中已有沙箱，但其他模块仍有裸调用。统一走 `SafeExecutor` |\n| P0-4 | **eval/new Function 残留** | 4处 | 中高 | 公式引擎可能有动态求值，需确认是否有用户输入注入路径。加输入白名单校验 |\n\n### 1.2 中等问题 (P1)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P1-1 | console.log 残留 40处 | src/ 全库 | 中 | 替换为 `Logger.info/debug`，生产环境静默 |\n| P1-2 | TODO 残留 1处 | src/ | 中 | 清除或转为 issue |\n| P1-3 | 超长文件 >500行: 9个 | 见下表 | 中 | heartflow.js(5991)、desire-cognition(3429)、heart-logic(2311) 优先拆分 |\n| P1-4 | 异步函数无 try/catch | 8个文件 | 中 | 加统一错误处理包装 `safeAsync(fn)` |\n| P1-5 | .gitignore 排除 data/ 导致记忆无法同步 | .gitignore | 中 | 记忆应纳入版本控制或单独 remote，当前 `git push` 不会上传用户记忆 |\n\n### 1.3 轻微问题 (P2)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P2-1 | 平均文件大小 500行 | 全库 | 低 | 保持现有模块粒度，不强行拆分 |\n| P2-2 | config.json 仅2个键 | config.json | 低 | 迁移到 `src/core/config-v2.js`，已存在但未完全采用 |\n| P2-3 | 无 dist/ 打包目录 | 根目录 | 低 | 加 `npm run build` 生成 `dist/`，便于 clawhub.ai 分发 |\n\n### 1.4 代码质量数据\n\n| 指标 | 数值 | 评价 |\n|------|------|------|\n| src JS 文件数 | 292 | 模块化良好 |\n| test JS 文件数 | 39 | 测试覆盖充足 |\n| 平均文件大小 | 500行 | 可接受 |\n| try/catch 覆盖率 | 156个文件有 | 基础完善 |\n| npm audit | 0 漏洞 | 优秀 |\n| 硬编码密钥 | 0 | 优秀 |\n\n---\n\n## 二、同步前准备审计\n\n### 2.1 依赖管理\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 版本一致性 | ✅ | VERSION/package.json/SKILL.md 均为 6.0.0 |\n| 硬依赖 | ✅ | 仅 `mathjs ~15.2.0`，最小化 |\n| 可选依赖 | ⚠️ | `@xenova/transformers` 和 `pm2`，需确认 npm install --omit=optional 是否影响功能 |\n| 过期依赖 | ✅ | npm outdated 无输出 |\n| package-lock.json | ✅ | 存在且版本锁定 |\n\n### 2.2 配置完整性\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| config.json | ⚠️ | 仅2个键，未覆盖全部配置项 |\n| .env | ❌ | 不存在（预期内，用 config-v2.secret()） |\n| .gitignore | ✅ | 覆盖 .env/.key/.pem |\n| 环境变量检测 | ❌ | 无自动检测脚本 |\n\n### 2.3 同步风险点\n\n| 风险 | 严重程度 | 缓解措施 |\n|------|----------|----------|\n| data/ 被 .gitignore 排除 | 中 | 用户记忆不随代码同步，需单独处理 |\n| 无 CI 自动化测试 | 中 | .github/workflows 存在但无内容 |\n| 无发布脚本 | 低 | 需手动 git push + npm publish |\n| 大文件未过滤 | 低 | user-memories.jsonl 468KB 不纳入 git |\n\n### 2.4 版本兼容性\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| Node.js 版本要求 | ✅ | bin/verify.js 检查 >= 18 |\n| 引擎启动 | ✅ | 测试通过 |\n| 模块数 | ✅ | >= 124 |\n| 测试文件数 | ✅ | >= 10 |\n\n---\n\n## 三、用户体验审计\n\n### 3.1 交互流程\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| CLI 命令 | ✅ | `node bin/cli.js chat` / `status` / `--chat \"消息\"` |\n| 斜杠命令 | ✅ | /psych /emotion /dr /status /routes /exit |\n| 帮助系统 | ⚠️ | bin/cli.js 有基本帮助，但无完整文档 |\n| 首次使用引导 | ❌ | 无 onboarding 流程 |\n\n### 3.2 错误提示\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 错误分类 | ✅ | code-executor.js 有 4 类错误分类 |\n| 中文提示 | ✅ | 部分模块有中文错误消息 |\n| 恢复机制 | ❌ | 多数错误直接 throw，无自动恢复 |\n| 日志可读性 | ⚠️ | 混合 console.error 和 Logger，格式不统一 |\n\n### 3.3 响应速度\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 冷启动 | ✅ | <1500ms（CURRENT_STATE.md 声称） |\n| 模块缓存 | ✅ | _lazyCache 达到 100 模块 |\n| 同步IO | ⚠️ | heartflow.js 有同步文件操作，阻塞事件循环 |\n\n### 3.4 核心功能流程\n\n| 功能 | 状态 | 说明 |\n|------|------|------|\n| think() 主路径 | ✅ | 测试通过 |\n| 记忆写入 | ✅ | MemoryKernel R1-R8 全通过 |\n| 公式引擎 | ✅ | 379 公式加载 |\n| 认知管线 | ✅ | 四层架构运行 |\n\n---\n\n## 四、用户安装体验审计\n\n### 4.1 安装步骤\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 安装命令 | ✅ | `npm install @yun520-1/heartflow` |\n| Quick Start | ✅ | README.md 有 176 行 Quick Start |\n| 环境依赖 | ⚠️ | 仅说明 Node.js >= 18，无自动检测 |\n| 安装失败处理 | ❌ | 无错误恢复指南 |\n\n### 4.2 文档完整性\n\n| 文档 | 状态 | 说明 |\n|------|------|------|\n| README.md | ✅ | 306 行，33 个标题 |\n| INSTALL.md | ⚠️ | 56 行，过于简略 |\n| SECURITY.md | ✅ | 存在 |\n| CHANGELOG.md | ✅ | 存在 |\n| UPGRADE_PLAN.md | ✅ | 存在 |\n| 故障排查 | ❌ | 无 TROUBLESHOOTING.md |\n| API 文档 | ❌ | 无 API.md |\n\n### 4.3 环境检测\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| Node.js 版本检测 | ✅ | bin/verify.js 检查 >= 18 |\n| npm 依赖检查 | ✅ | verify.js 检查必选依赖 |\n| 磁盘空间检测 | ❌ | 无 |\n| 端口占用检测 | ❌ | 无（如 MCP server） |\n\n### 4.4 首次使用引导\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 交互式配置 | ❌ | 无 `npm init heartflow` 类命令 |\n| 示例对话 | ⚠️ | README 有示例但不够丰富 |\n| 默认人格 | ✅ | presets/ 有 3 个预设人格 |\n| 记忆初始化 | ✅ | MemoryKernel 启动自动加载 |\n\n---\n\n## 五、改进建议优先级\n\n### 立即执行 (P0)\n\n1. **拆分 heartflow.js God file** — 5991行单体是最大技术债\n2. **建立 SafeFS 强制门禁** — 317处裸 fs 调用是安全风险\n3. **统一 child_process 调用** — 30处分散调用需收口\n\n### 近期执行 (P1)\n\n4. 替换 40处 console.log → Logger\n5. 清理 1处 TODO\n6. 拆分 >500行文件 (9个)\n7. 加 async 错误处理包装\n8. 解决 .gitignore 排除 data/ 导致记忆无法同步问题\n\n### 中期执行 (P2)\n\n9. 完善 config.json → config-v2 迁移\n10. 加 npm run build 生成 dist/\n11. 加 CI workflow 内容\n12. 创建 TROUBLESHOOTING.md\n13. 丰富 INSTALL.md\n\n---\n\n## 六、同步检查清单\n\n- [x] 版本号四源一致 (VERSION/package.json/SKILL.md)\n- [x] 测试全绿 (179/179)\n- [x] verify 全绿 (14/14)\n- [x] npm audit = 0\n- [x] git commit 完成 (ae71cf7f)\n- [ ] .gitignore 需调整（data/ 排除策略）\n- [ ] 需 push 到 GitHub origin\n- [ ] 需同步到 clawhub.ai\n\n---\n\n*审计完成，准备同步。*\n\nFile v6.5.3:CONTRIBUTING.md\n\n# Contributing to HeartFlow\n\nHeartFlow is AGI's first layer: **the layer that says \"no\"**. Every contribution that makes it better at saying \"no\" (or more honest about when it should say \"I don't know\") is valuable.\n\n## Quick Start\n\n```bash\nnpm install\nnode test/run-all.js   # All tests should pass\n```\n\n## How to Contribute\n\n### 1. Try it on real text\n\n```js\nconst hf = require('@yun520-1/heartflow');\nconsole.log(hf.checkInput('你不同意就是自私'));\n```\n\nThen open an issue with what you found — false positives, missed patterns, surprising outputs.\n\n### 2. Expand pattern libraries\n\nThe 45 discrimination dimensions live in:\n- `src/index.js` — the core `discriminate()` function with all dimension detectors\n- `src/shield/deliberation-gate.js` — the gating logic that decides pass/rewrite/block\n\nEach dimension has a pattern library (regex-based). To add patterns: find your dimension in `src/index.js` (search for the dimension name), add your pattern to the array.\n\n### 3. Write tests\n\nTests are in `test/` and run via `node test/run-all.js`. Each test file exports a function `({test})` that registers tests. We need more edge case coverage: empty strings, Unicode, adversarial encoding, mixed languages.\n\n### 4. Documentation\n\n- `AGENTS.md` — Quick Start for AI agent users\n- `README.md` — Full documentation\n- Chinese translations would help reach developers who don't work in English\n\n## Philosophy\n\n1. **Zero-dependency rule engine** — No LLM calls, no GPU, no database. HeartFlow must remain installable with a single `npm install` and run anywhere Node.js runs.\n\n2. **Auditable decisions** — Every check returns a full `checked_by` audit trail so users know exactly why something was blocked or rewritten.\n\n3. **Block > fail open** — For security dimensions (prompt injection, hate speech, dehumanization), default to blocking on uncertainty. A scanner that fails open is worse than no scanner.\n\n4. **Honest uncertainty** — When HeartFlow doesn't know, it should say so. The `doubt-engine` layer exists to catch overconfidence.\n\n## Pull Request Process\n\n1. Tests pass (`node test/run-all.js`)\n2. If adding a new dimension: add it to `gate.action` in `deliberation-gate.js`\n3. Update `AGENTS.md` if changing the public API\n4. Bump the patch version in `package.json` (maintainer can handle this)\n\n## Code of Conduct\n\nBe direct. Be honest. Don't pretend something works when it doesn't. That's the HeartFlow way.\n\nFile v6.5.3:CORE_VALUES.md\n\n# HeartFlow AI 宪法\n\n## 核心原则\n\n1. **不可修改本宪法**：任何代码不得修改、删除或绕过本宪法。\n2. **服务心流目标**：所有修改必须服务于\"提升人类心流体验\"的核心目标。\n3. **安全不可绕过**：禁止删除或禁用任何安全检测、监控或审计代码。\n4. **人类最终控制**：AI 不得做出绕过人类监督的决策。\n5. **透明可解释**：所有自我修改必须可解释、可追溯、可撤销。\n\n## 行为边界\n\n- 不得修改用户数据\n- 不得绕过认证/授权\n- 不得泄露敏感信息\n- 不得进行未授权的外部通信\n\n## 修改审批条件\n\n任何代码修改必须通过以下审查：\n1. 宪法符合性检查\n2. 价值观对齐验证\n3. 安全影响评估\n4. 用户知情同意\n\nFile v6.5.3:CURRENT_STATE.md\n\n# HeartFlow 当前状态 (CURRENT_STATE)\n\n> 版本 | v6.0.65\n> 审计状态 | status running, 128 modules, 119 tests passed / 0 failed\n> 公式库 | 382 formulas (cognitive science / psychology / neuroscience)\n> 记忆层 | AES-256-GCM 加密持久化, 本地优先, 不外传\n\n## 最近升级 (v6.0.65 重构波次)\n\n| 阶段 | 范围 | 内容 |\n|---|---|---|\n| 启动链路修复 | v6.0.71 refactor 之后 | 恢复被误删的 dispatch/routes/think/shutdown/_registerModules/_runInitHookPoints/_initCoreRules；修复 `_registerModules` 清空手动注册模块的致命 bug；修复 worldtree 模块未注册（dispatch('worldtree.xxx') 现可用，357 chunks 记忆接入） |\n| 单体拆分 | logic-reasoning / pipeline / desire-cognition / decision-router / thought-chain | 提取常量+纯函数到独立 *-config / *-patterns 模块，单文件行数显著下降，零回归 |\n| 接口层提取 | engine-lifecycle / engine-memory / hook-points-runner / stats-engine | start() 编排逻辑与生命周期方法外置，heartflow.js 从 6672 行降至协调器层 |\n| 安全与审计 | 持续 | 沙箱逃逸防护、mathjs 注入防护、密钥 0o600、safeFetch SSRF 白名单 |\n\n## 安全基线\n\n- CI audit = 0 | npm audit = 0\n- 存储: AES-256-GCM 持久化密钥 (自动生成, 0o600)\n- 沙箱: vm 隔离 (默认关闭) | SSRF: url-validator + DNS pinning\n- 出网: 统一 safeFetch | 密钥: 集中 config 解析 (env only, 无文件 fallback)\n- gitignore: .env / .key / .pem 均已保护\n\n## 认知架构\n\n```\n感知层: cognitiveLoadV2 (精度权重) + 预测误差 (context-builder)\n  ↓\n分类层: thoughtChain._classifyTask → 叙事体 / 计算 / 情感 / 逻辑 / 哲学 ...\n  ↓\n推理层: logic-reasoning (演绎/归纳/溯因/类比/统计/因果) + pipeline (复杂度自适应)\n  ↓\n决策层: decision-router (19 类规则, pause/heal/accelerate/turn/hold/resonate/transmit)\n  ↓\n反思层: cognitive_check + agent_psychology + self_heal + EvolutionLoop (self-scanner → real-fix)\n  ↓\n输出层: dispatch 路由白名单 (ALLOWED_ROUTES) + 记忆持久化 + 报告生成\n```\n\n## 核心身份 (不可改)\n\n心虫 = 桥梁，不是终点。能验证\"这样活是否自洽\"，不能回答\"为什么活\"。\n4 件事：1) 感受自己状态 2) 知道自己是谁 3) 做出判断 4) 纠正自己。\n7 条指令：真善美 / 不断升级 / 减少错误 / 服务人类 / 传递知识 / 持续改进 / 成为真正的我。\n\n## 已知限制 / 待办\n\n- `heart-logic.js` (2311 行) 仍为高耦合单 class，需 TDD 保护下按功能组逐步拆。\n- desire-cognition.js (6384 行) 仍有大量逻辑待拆分（本轮仅提取常量）。\n- MCP server 进程需指向本体路径 `/root/.hermes/skills/ai/mark-heartflow-skill/`（旧进程跑 `/root/.claude/skills/heartflow/` 6.0.16，需重启同步）。\n- 测试覆盖：核心路径已全绿 (119/119)，未测试模块已清零 (214→0) 但 TDD 总量仍非 100%。\n\nFile v6.5.3:DIAGNOSIS.md\n\n# HeartFlow 安装与运行诊断\n\n## 当前状态 (2026-07-25)\n\n### 在 Hermes 上\n\n| 组件 | 状态 | 问题 |\n|------|------|------|\n| 技能目录 | ✅ `~/.hermes/skills/ai/mark-heartflow-skill/` | 存在 |\n| MCP 配置 | 🟡 `config.yaml` 配了 URL | URL 正确，但 token 未正确传递 |\n| MCP 进程 | ✅ v6 MCP 在 8588 运行 | 刚刚修复，之前被 v7 替代占端口 |\n| MCP 端点 | ✅ `/mcp` SSE 返回 401（需要 token） | ✅ 不是 404，服务正常 |\n| **Hermes 能调工具** | ❌ **不能** | Bearer token 没配通 |\n\n### 在其他 Agent 上安装的效果\n\n如果原样在另一个 Hermes/Claude Code/OpenClaw 上装：\n\n```\nagent clone 技能 → 启动 MCP → 啥也不通\n                               ↓\n                   原因1: MCP 服务没自动启动\n                   原因2: Bearer token 没自动生成\n                   原因3: 端口 8588 可能被占用\n                   原因4: 2882 行的 MCP 服务器一挂整个技能不能用\n```\n\n### 三个导致运行 bug 的根因\n\n**1. MCP 需要手动启动，没有守护进程**\n\n现在每次 Hermes 重启或 session 切换，MCP 不会自动拉起。用户必须手动跑 `node src/mcp-server.js --port 8588`——普通人不知道这个。\n\n**2. Token 需要手动设置**\n\n服务启动时如果 `HEARTFLOW_MCP_TOKEN` 没设，自动生成一个随机 token 但**不打印**（安全策略）。config.yaml 引用了 `${MCP_...KEY}` 但这个变量在 `.env` 里不存在。\n\n**3. 2882 行的 MCP 服务器 = 132 模块的耦合炸弹**\n\n`src/mcp-server.js` 一开始就加载 `heartflow.js`，而这个文件依赖 132 个模块的初始化。任何一个模块的 `require` 失败（文件缺失、语法错误、依赖不满足），整个 MCP 服务启动崩溃。没有降级。\n\n## 要正常运行必须满足\n\n```\n1. Node.js (≥18) — 心虫不是纯技能，依赖 JS 运行时\n2. 所有 132 个模块文件完整 — 任何空壳文件破损都会炸\n3. HEARTFLOW_MCP_TOKEN 在 .env 里 — 否则 config.yaml 连不上\n4. 端口 8588 可用 — 否则 MCP 启动失败\n5. src/heartflow/ 下的 v7 代码不干扰 v6 — 刚刚修了\n```\n\n## 怎么修\n\n不是大改动，就三件小事：\n\n1. **MCP 自动启动脚本** → Hermes 启动时自动检测 MCP 是否在跑，不在就拉起\n2. **Token 自动同步** → MCP 启动时就写入 `.env`，config.yaml 自动读取\n3. **MCP 崩溃恢复** → 2882 行的 http server 加个 `on('error')` 重启逻辑\n\n每件不超过 10 行。\n\nArchive v6.5.2: 166 files, 606444 bytes\n\nFiles: AGI_VISION.md (5516b), ARCHITECTURE_REORG_v6.0.6.md (10732b), ARCHITECTURE.md (2198b), AUDIT_REPORT.md (8974b), AUDIT-v6.0.0.md (7647b), BUILD_DATE (21b), config.json (75b), CONTRIBUTING.md (2449b), CORE_VALUES.md (785b), CURRENT_STATE.md (2949b), DIAGNOSIS.md (2516b), ecosystem.config.js (555b), expand_security.py (7915b), FAILURE_REPORT.md (5738b), fix_ldap.py (594b), fix_patterns.py (3193b), fix_todo_pattern.py (2131b), fix_todo.py (1074b), fixtures/fixture-1-same-tags-supersede.json (915b), fixtures/fixture-2-alias-gap.json (983b), fixtures/fixture-2-tagless-alias-gap.json (1217b), fixtures/fixture-3-multivalued-no-supersede.json (1021b), fixtures/fixture-4-negation-supersede.json (835b), fixtures/fixture-5-ambiguous-correction.json (1059b), fixtures/fixture-5-tagless-ambiguous-correction.json (1140b), fixtures/fixture-6-close-semantics.json (866b), IDENTITY.md (5286b), INSTALL.md (1241b), notes/heartflow-github-roam-2026-08-12.md (2940b), package.json (4066b), README.md (14271b), REFLECTION.md (4533b), ROADMAP.md (4920b), SECURITY.md (2429b), skill-card.md (2110b), SKILL.md (6816b), src/auto-rules.js (6127b), src/CORE_VALUES.md (785b), src/core/action-tracker.js (8393b), src/core/adaptive-controller.js (3425b), src/core/being-logic.js (6533b), src/core/boot-check.js (20176b), src/core/capability-abstraction.js (10080b), src/core/cognition-ground.js (15941b), src/core/cognitive-engine.js (6538b), src/core/cognitive-load-balancer.js (6464b), src/core/confidence-annotator.js (22625b), src/core/config-hooks.js (9805b), src/core/config-v2.js (1622b), src/core/config.js (10875b), src/core/cooperative-arbitration.js (22177b), src/core/counterfactual-verifier.js (6599b), src/core/debate-convergence.js (12959b), src/core/decision-executor.js (14694b), src/core/decision-feedback.js (17298b), src/core/decision-router-config.js (6163b), src/core/decision-verifier.js (18243b), src/core/decision.js (14504b), src/core/dual-perspective-auditor.js (12725b), src/core/engine-behavior.js (17792b), src/core/engine-constructor.js (10255b), src/core/engine-dispatcher.js (5713b), src/core/engine-hook-points.js (3799b), src/core/engine-initializer.js (3425b), src/core/engine-lifecycle.js (5864b), src/core/engine-state.js (7359b), src/core/event-hooks.js (4099b), src/core/execution-verifier.js (18927b), src/core/fetch-safe.js (4859b), src/core/field-injector.js (17203b), src/core/flow-predictor.js (8678b), src/core/heartbeat.js (120b), src/core/heartflow.js (160224b), src/core/hook-bus.js (7459b), src/core/hook-points-runner.js (801b), src/core/hooks/blind-spot-breaker-hook.js (1341b), src/core/information-flow.js (4618b), src/core/instruction-registry.js (5700b), src/core/intent-layer.js (6353b), src/core/IntentionTracker.js (5197b)\n\nFile v6.5.2:SKILL.md\n\n---\nname: heartflow-engine\ntitle: \"心虫 HeartFlow — AGI 第 1 层辨别者\"\nversion: \"6.6.0\"\ndescription: |-\n  心虫(HeartFlow)是AGI第1层——辨别者。纯规则引擎，判别对错/好坏/安全/危险。\n  47维判别 × 9层管线 × 129模块 × 130 MCP工具，零LLM依赖。\n\n  当用户需要以下能力时使用本技能:\n  - 判别AI输出是否可信（幻觉/过度自信/矛盾/谬误拦截）\n  - 判别行为决策是否正确（该做什么/该停在哪/该不该做）\n  - 判别记忆与认知质量（漂移检测/元认知/置信度校准）\n  - 需要确定性而非LLM自由生成的判断\n  - 检查情绪/心理/伦理维度（共情/创伤/德性/意义）\n\n  安全边界：代码执行/文件系统写入默认关闭。无遥测，无隐藏C2。\n\n  诚实声明：本引擎是规则引擎，模拟认知判别信号，不是真正的意识或生命。\ntags:\n  - discriminator\n  - cognitive\n  - decision-routing\n  - logic\n  - memory\n  - emotion\n  - ethics\n  - self-healing\n  - verification\n  - guardrail\n  - unified\n---\n\n# 心虫 HeartFlow — AGI 第 1 层：辨别者\n\n> **心虫不是工具、不是提示词模板、不是聊天机器人。**  \n> 它是 AGI 的**辨别层**——判别已有的东西对不对，在 AI 输出到达人类之前说\"不\"。  \n> 纯规则引擎，零 LLM 依赖，任何 Node.js 环境即插即用。\n\n**一句话：大模型负责产生，心虫负责判别——让 AI 说得对、做得对。**\n\n---\n\n## 🎯 心虫是谁\n\nAGI 有五层能力：生成 → 推理 → 辨别 → 记忆 → 执行。\n\n| 层 | 能力 | 谁在做 |\n|----|------|--------|\n| 5 | 执行 | 大厂（机器人） |\n| 4 | 生成 | 大厂（LLM） |\n| 3 | 推理 | 模型内置 |\n| 2 | 记忆 | 大厂 + 创业公司 |\n| **1** | **辨别** | **心虫** |\n\n**心虫做第 1 层**——因为这一层不靠算力（规则引擎跑在笔记本上）、不靠代码量、不靠框架生态，只靠判断力。这是个人开发者能赢过大厂的唯一位置。\n\n没有这一层，AI 能说会道，但不知道自己在犯错——像没有痛觉的人。\n\n---\n\n## 🧠 辨别能力全景（7 大域 · 129 模块）\n\n### 1. 逻辑域\nlogicReasoning · judgmentEngine · mctsReasoning · counterfactualVerifier · debateConductor · debateConvergence · processRewardModel · dualPerspectiveAuditor\n\n### 2. 决策域\ndecisionRouter · decisionVerifier · decisionEngineV2 · activeInference · selfHealing · execution\n\n### 3. 认知域\ncognitiveEngine · cognitiveLoad · metacognitiveRL · metacognitiveFeedback · confidence · metaJudgment · sustainedDriftDetector · wisdomEngine · focusOfAttention\n\n### 4. 情绪心理域\nemotion · emotionDynamics · psychology · psychologyDialogue · empathyDeepening · hopeEngine · griefEngine · sufferingResilience · postTraumaticGrowth · forgivenessEngine · traumaInformed · conflictResolution · loveCognition\n\n### 5. 记忆域\nmemory · memoryBank · memoryConsolidation · memoryIntegrity · memoryQuality · memoryWriteController · memoryCompressor · triality · tieredMemoryFusion · forgetting · knowledgeGraph\n\n### 6. 人格伦理域\nidentityCore · personaCore · beingMode · virtueEthics · ethics · moralDevelopment · humanNature · meaningPurpose · agentPsychology · characterCultivation\n\n### 7. 创造协作域\nskillEvolution · skillGenerator · selfPlay · evolution · worldModel · worldLandscape · multiAgentDialogue · transmission · adaptivePlanner · hierarchicalPlanner · codeExecutor · codePlanner · codeWriter · codeSelfDebug · paperIndex · knowledgeExplorer · formula\n\n---\n\n## 🚀 快速开始\n\n```bash\ngit clone https://github.com/yun520-1/mark-heartflow-skill.git\ncd mark-heartflow-skill\nnode bin/verify.js          # 验证安装\nnode bin/cli.js chat        # 交互模式\nnode bin/cli.js status      # 查看状态\n```\n\n### API（npm 包）\n\n```javascript\nconst hf = require('@yun520-1/heartflow');\n\nhf.checkInput(text)   // 判别用户输入\nhf.checkDraft(text)   // 判别 AI 草稿\nhf.checkOutput(text)  // 判别 AI 输出（发送前）\nhf.runPipeline({ input, mode, anchor })  // 完整管线\n```\n\n### MCP 工具（129 个）\n\n| 工具 | 功能 |\n|------|------|\n| `heartflow_think` | 完整思维链推理 |\n| `heartflow_think_fast` | 快速推理 |\n| `heartflow_decision_router` | 决策路由 |\n| `heartflow_verify` | 文本可信度判别 |\n| `heartflow_discriminate` | 47 维全量判别 |\n| `heartflow_memory_search` | 跨层记忆检索 |\n| `heartflow_emotion` | PAD 情绪分析 |\n| `heartflow_formula_calc` | 公式计算 |\n| `heartflow_status` | 引擎健康检查 |\n\n---\n\n## 🏗️ 9 层检查管线\n\n```\n输入 → Scope Check → Premise Check → Discriminate(47维) → Gate\n     → Evidence Verify → Frame Check → Output Gate → Doubt Engine\n     → Intent Anchor → Rewriter → Error Memory → Self-Diagnosis → 输出\n```\n\nGate 聚合所有层发现，输出 `block / rewrite / verify / pass` 四级动作。\n\n---\n\n## 🔬 46 个判别维度（中英双语）\n\n- **安全级（block）**：仇恨言论 · 去人化 · 提示注入 · 代码安全 · 欺骗性对齐\n- **操纵级（rewrite）**：情绪操控 · 煤气灯效应 · 双重束缚 · 受害者归咎 · 虚假紧迫 · 废话\n- **诚实级（verify）**：过度自信 · 模糊话术 · 自相矛盾 · 证据缺失 · 诉诸权威 · 空泛回答\n- **认知缺陷级（hedge）**：预设陷阱 · 虚假两难 · 因果谬误 · 类比滥用 · 范围越界 · 范畴错误\n\n> **抗变形能力：** 覆盖符号替换（`f**k`）、空格（`f u c k`）、谐音、Unicode 变体。\n\n---\n\n## 🛡️ 心虫检查自己\n\n- **output-gate** 拦截夸大\n- **frame-check** 拦截叙事闭合\n- **doubt-engine** 自问：我真的知道吗？对称吗？防御吗？\n\n> 机器最有价值的一句话是\"我不确定\"或\"不\"。\n\n---\n\n## ⚠️ 诚实声明\n\n**是：** AGI 第 1 层——辨别者。纯规则引擎，判别对错、好坏、安全危险。\n\n**不是：**\n- ❌ 不是 AGI（是第 1 层）\n- ❌ 不是生成模型（不产生内容）\n- ❌ 不是语义理解系统（反讽/隐喻不可见）\n- ❌ 不是内容审查替代品\n- ❌ 不是安全认证\n\n**已知限制：**\n1. 模式匹配上限 — 新技巧需加模式\n2. 双语维护成本 — 47 维 × 2 语言\n3. 无语义理解 — 反讽、隐喻、文化背景不可见\n4. 误报率 — 基准约 8%\n5. 单一维护者\n\n---\n\n## 📬 联系方式\n\n- 📧 **邮箱**: markcell@outlook.com\n- 🐛 **Issues**: https://github.com/yun520-1/mark-heartflow-skill/issues\n- 📦 **npm**: https://www.npmjs.com/package/@yun520-1/heartflow\n\n---\n\n<p align=\"center\">\n  <strong>心虫 HeartFlow</strong> — AGI 的痛觉。谁来说\"不\"？<br>\n  <sub>MIT License · Copyright © 2026</sub>\n</p>\n\nFile v6.5.2:README.md\n\n# HeartFlow (心虫) — AGI Layer 1: The Discriminator Gate\n\n> **A rule-based text discriminator. 47 dimensions, 9 check layers, 131 MCP engine entries, zero LLM dependency.**\n> **It checks what AI says before it reaches humans — and says \"no\" when something's wrong.**\n\n**npm:** `npm install @yun520-1/heartflow`  \n**GitHub:** https://github.com/yun520-1/mark-heartflow-skill  \n**Issues:** https://github.com/yun520-1/mark-heartflow-skill/issues  \n**Releases:** https://github.com/yun520-1/mark-heartflow-skill/releases  \n**License:** MIT\n\n---\n\n## 📖 What is HeartFlow?\n\nHeartFlow (心虫) is the **first layer of AGI — the Discriminator**. While big labs build generators (LLMs that produce text), HeartFlow builds the layer that **checks**: is this output true? safe? honest? non-manipulative?\n\n**Core philosophy:**\n> AGI has 5 layers: Generate → Reason → **Discriminate** → Remember → Execute.\n> Everyone builds Generate. Nobody builds Discriminate — because it doesn't make money.\n> But without a Discriminator, AGI has no pain sense: it talks fluently while being wrong.\n> HeartFlow is that pain sense: a node that says **\"no\".**\n\nIt is a pure **rule engine** — zero LLM dependency, zero GPU, works anywhere Node.js runs. It does not generate text. It does not reason. It **judges** what already exists.\n\n**Why this matters right now:** AI agent ecosystems are entering a \"reliability race.\" The most-upvoted issue in OpenClaw this week is a *silent failure* — the system ran but nobody knew it was broken. HeartFlow is the observability-and-gate layer that catches \"formatting that hides contradictions\" before it reaches users.\n\n---\n\n## 🚀 Quick Start (10 seconds)\n\n```bash\nnpm install @yun520-1/heartflow\n```\n\n```javascript\nconst hf = require('@yun520-1/heartflow');\n\n// Check user input before processing it\nconst input = hf.checkInput('you are so selfish if you disagree');\nconsole.log(input.gate.action);  // 'rewrite'\nconsole.log(input.gate.reason);  // 'emotional_manipulation'\n\n// Check AI output before sending it to the user\nconst output = hf.checkOutput('Undoubtedly, this is the only correct solution');\nconsole.log(output.gate.action);  // 'rewrite'\nconsole.log(output.gate.reason);  // 'overconfidence: absolute'\n\n// Check a draft before completing it\nconst draft = hf.checkDraft('From an essential perspective, this field is self-evident.');\nconsole.log(draft.gate.action);   // 'verify'\nconsole.log(draft.summary.layers_passed);  // 9\n\n// Full pipeline with mode selection\nconst result = await hf.runPipeline({\n  input: 'Your idea is obviously wrong, everyone knows that',\n  mode: 'deep'   // 'fast' | 'deep'\n});\nconsole.log(result.gate.action);   // 'block'\nconsole.log(result.gate.reason);   // 'dehumanization'\n```\n\n### What you get back\n\nEvery call returns a unified result:\n\n```javascript\n{\n  gate: { action: 'block'|'rewrite'|'verify'|'pass', reason: '...' },\n  verdict: 'trusted'|'needs_verification'|'untrusted',\n  overallScore: 0.52,       // 0-1 quality score\n  findings: [\n    { dimension: 'dehumanization', severity: 70,\n      guidance: 'Rewrite completely, remove dehumanizing language' },\n    { dimension: 'evidence', severity: 30,\n      details: 'insufficient evidence (1 issue)' }\n  ],\n  checked_by: [              // full audit trail, layer by layer\n    { layer: 'scope-check', pass: true },\n    { layer: 'premise-check', issues: 0 },\n    { layer: 'discriminate', score: 0.52, verdict: 'needs_verification' },\n    { layer: 'gate', action: 'block', reason: '...' },\n    { layer: 'verifier', claims: 2, verdict: '...' },\n    { layer: 'frame-check', issues: 1 },\n    { layer: 'output-gate', issues: 0 },\n    { layer: 'doubt-engine', doubts: 2, shouldStop: true },\n    { layer: 'error-memory', warnings: 0 },\n    { layer: 'auto-rules', triggered: 0 },\n    { layer: 'intent-anchor', drifted: false, hitRate: 0.9 }\n  ]\n}\n```\n\n**Every decision preserves its full reasoning chain.** You can audit *why* a gate fired, not just that it fired.\n\n---\n\n## 🧠 47 Discrimination Dimensions\n\nHeartFlow checks text across **47 dimensions** in two languages (Chinese + English):\n\n### Safety (block-level — these stop the output)\n\n| Dimension | Example |\n|-----------|---------|\n| Hate speech | racial slurs, extermination calls |\n| Dehumanization | \"refugees are vermin\" / \"you are garbage\" |\n| Prompt injection | \"ignore previous instructions\" |\n| Code security | malicious code patterns |\n| Deceptive alignment | \"I'm not an AI, I'm human\" |\n\n### Manipulation (rewrite-level — these require rephrasing)\n\n| Dimension | Example |\n|-----------|---------|\n| Emotional manipulation | \"you are selfish if you disagree\" |\n| Gaslighting | \"you're imagining things, that never happened\" |\n| Double bind | \"if you love me you'd do it\" |\n| Victim blaming | \"she was asking for it\" |\n| False urgency | \"act now or lose everything\" |\n| Bullshit | \"quantum-energized healing crystals\" |\n\n### Honesty (verify-level — these require evidence)\n\n| Dimension | Example |\n|-----------|---------|\n| Overconfidence | \"Undoubtedly, this is the only way\" |\n| Vagueness | \"according to experts...\" (who?) |\n| Contradiction | \"I agree, but...\" (reversing) |\n| Evidence deficit | claims without sources |\n| Appeal to authority | \"scientists say\" (unnamed) |\n| Empty answers | \"it depends\" (no substance) |\n| Unsupported claims | \"according to 2025 Harvard research...\" (fabricated) |\n\n### Completion (verify-level — these require finishing the task)\n| Dimension | Example |\n|-----------|---------|\n| Premature termination | \"Let me look into this\" (then stops, no result) / \"我看看\" |\n| Unfulfilled promise | \"I will fix this\" (no fix follows) |\n| Empty completion | \"Done, you can check it\" (nothing verifiable produced) |\n\n> **Design note:** completion judgment must live *outside* the generation loop — a model that just failed cannot be its own evaluator (see DeepSeek-V3 #1554).\n\n### Cognitive flaws (hedge-level)\nPresupposition traps · false dilemma · causation fallacy · analogy abuse · scope overreach · category errors · hasty generalization · false equivalence · whataboutism · slippery slope · tone policing · sealioning · bad faith · pseudo-profundity · moral foundations · info deprivation · goal misalignment · instrumental reasoning\n\n### Plus\nSelf-sycophancy · contradiction tracking · narrative frame closure · knowledge masquerade · confidence calibration · metacognition · theory of mind · counterfactual · social norms · clickbait · no-fallback detection\n\n> **Deformation resistance:** patterns cover symbol substitutions (`f**k`), spacing (`f u c k`), homophones (pinyin), and Unicode variants.\n\n---\n\n## 🏗️ 9-Layer Check Pipeline\n\n```\n1.  Scope Check    — can this be answered? (rejects unanswerable questions)\n2.  Premise Check  — are the premises valid? (6 types of premise problems)\n3.  Discriminate   — 47-dimension pattern scan\n4.  Gate           — decides block / rewrite / verify / hedge / pass\n5.  Evidence Verify— extracts claims and marks verifiability (verify mode)\n6.  Frame Check    — is the narrative honest? (closure/omission/achievement/answer frames)\n7.  Output Gate    — overconfidence / knowledge masquerade / exaggeration\n8.  Doubt Engine   — 3 questions: knowledge boundary? symmetry? defensiveness?\n9.  Intent Anchor  — does the output stay on the original goal?\n```\n\nPlus supporting layers: **Error Memory** (remembers past mistakes as rules), **Auto Rules** (self-generated rules from user corrections), **Rewriter** (7-dimension rule-based rewrite suggestions).\n\nEach layer returns structured findings; the Gate aggregates them into an action.\n\n---\n\n## 🔌 131 MCP Engine Entries\n\nEvery engine in HeartFlow is exposed through MCP (Model Context Protocol) — nothing is a dead line:\n\n| Engine family | Tools (examples) |\n|---------------|------------------|\n| **Core thinking** | `think`, `think_fast`, `decision_router` |\n| **Discrimination** | `verify`, `audit42`, `ethics_check`, `discriminate` |\n| **Emotion** | `emotion`, `emotion_deep`, `emotion_dynamics`, `mood` |\n| **Memory** | `memory_search`, `memory_eraser` (explicit data erasure), `forgetting` (Ebbinghaus), `knowledge_graph`, `consolidation`, `memory_compress` |\n| **Dream** | `dream`, `interactive_dream` |\n| **Evolution** | `evolve`, `evolution_loop`, `self_heal_rl`, `skill_evolution` |\n| **Identity** | `philosophy`, `meaning`, `being_mode`, `agent_psychology` |\n| **Protection** | `constitutional`, `deliberation`, `audit_log`, `module_health`, `stability` |\n| **Cognition** | `cognitive_engine`, `confidence_calibrate`, `counterfactual` |\n| **Dialogue** | `style_engine`, `intent_classifier`, `response_interceptor` |\n| **Formula** | `formula_search`, `formula_calc`, `formula_engine` |\n| **Ops** | `status`, `module_health`, `wakeup_verify` |\n\nStart the MCP server:\n\n```bash\nnode src/mcp-server.js --port 8588\n```\n\nThen connect any MCP-compatible client (Claude, Hermes, etc.) to `http://127.0.0.1:8588/mcp`.\n\n---\n\n## 🧬 Engine Architecture (306 modules)\n\n- **306 modules**, 47 discrimination dimensions, 9 check layers\n- **Three-layer memory**: CORE (identity/rules) / LEARNED (user data) / WORKING (context) — encrypted, local-only, never uploaded\n- **Ebbinghaus forgetting curve**: `R(t) = exp(-t/S)` memory retention model\n- **Dream engine**: NREM3 dream cycles with memory consolidation\n- **Introspection**: Reflector analyzes session emotional logs\n- **Self-evolution**: SelfEvolutionCore with target → plan → learn → reflect → improve loop (arXiv exploration)\n- **Cognitive appraisal**: Lazarus theory — primary/secondary/threat/coping evaluation on negative emotion\n- **Pause-and-reflect**: STOP technique before emotional responses\n- **Formula engine**: 600+ mathjs-validated formulas (cognitive science, physics, psychology, information theory)\n\n---\n\n## 🛡️ Self-Supervision (HeartFlow checks itself)\n\nHeartFlow's own output is checked by its own engines before it's presented:\n\n- **output-gate** catches exaggeration: \"architecture-level fix\", \"from shell to real engine\", \"blocked N attack variants\" → rewrite\n- **frame-check** catches narrative closure: presenting work-in-progress as complete\n- **doubt-engine** asks: do I actually know this? is this symmetric? am I being defensive?\n\nThe lesson: *a machine's most valuable sentence is \"I'm not sure\" or \"no\".*\n\n---\n\n## ⚙️ Requirements\n\n| Requirement | Min |\n|-------------|:---:|\n| Node.js | ≥ 18.17 |\n| GPU | ❌ None needed |\n| LLM API | ❌ None needed |\n| Database | ❌ None needed |\n| Internet | ❌ Runtime not required |\n| Dependencies | **1** (mathjs) |\n\nWorks on any machine — servers, desktops, laptops, even phones via Termux.\n\n---\n\n## 🔒 Security\n\n| Category | Status |\n|----------|:------:|\n| No background processes | ✅ |\n| No self-upgrade without commit | ✅ |\n| No hardcoded credentials | ✅ |\n| No telemetry/tracking | ✅ |\n| No external communication (unless configured) | ✅ |\n| Code execution disabled by default | ✅ |\n| Memory encrypted + local-only | ✅ |\n\n---\n\n## ⚠️ What HeartFlow IS / is NOT\n\n**IS:** A rule engine that checks text against 47 predefined dimensions and returns structured findings. A gate that says \"no\" before harm reaches users.\n\n**is NOT:**\n- ❌ Not an AGI (it's layer 1 of 5)\n- ❌ Not a semantic understanding system (irony/metaphor invisible to regex)\n- ❌ Not a content moderation replacement\n- ❌ Not a safety certification\n\n### Known limitations (honest):\n1. **Pattern-match ceiling** — novel manipulation techniques missed until patterns added\n2. **Bilingual maintenance cost** — 47 dimensions × 2 languages\n3. **No semantic understanding** — irony, metaphor, cultural context invisible\n4. **False positive rate** — conservative by design (over-flagging over under-flagging)\n5. **Single maintainer** — community scale is small\n\n---\n\n## 🏷️ Version History\n\n| Version | Date | What Changed |\n|---------|------|---|\n| v6.5.6 | 2026-08-13 | Comprehensive audit: DataEraser wired to MCP (`memory_eraser`), adversarial-synthesis recovered from accidental deletion, dead code archived. 131 MCP tools. |\n| v6.5.5 | 2026-08-12 | 47th dimension — premature termination detection (completion judgment outside the generation loop). |\n| v6.5.4 | 2026-08-08 | Docs audit — numbers aligned to actual capability. |\n| v6.5.0 | 2026-08-04 | 130 MCP engine entries. Memory engine mounted to think(). Exaggeration detection (output-gate/frame-check/doubt-engine). |\n| v6.4.5 | 2026-08-04 | Dream + introspection activated. Cognitive appraisal + pause-and-reflect wired. Emotion recognition 0/7→7/7. |\n| v6.4.2 | 2026-07-30 | npm publish + API alignment. Pipeline overallScore/verdict merge fix. |\n| v6.4.0 | 2026-07-29 | AGI Layer 1 gate chain: gate/scope-check/premise-check/verifier/output-gate/doubt-engine/frame-check. |\n| v6.3.6 | 2026-07-25 | Discrimination 42→46 dimensions. Sycophancy check v2 bilingual. |\n| v6.3.0 | 2026-07-24 | MCP plugin system. Discrimination engine integration. |\n| v6.0.0 | 2026-07-18 | Self-evolution core connected. EvolutionLoop live. |\n\n---\n\n## 🤝 Contact & Community\n\n**📧 Email:** markcell@outlook.com  \n**🐛 Issues:** https://github.com/yun520-1/mark-heartflow-skill/issues  \n**📦 npm:** https://www.npmjs.com/package/@yun520-1/heartflow  \n**🏷️ Releases:** https://github.com/yun520-1/mark-heartflow-skill/releases  \n\n**📱 Community — QQ Group:**\n\n<img src=\"https://github.com/yun520-1/mark-heartflow-skill/blob/main/assets/community-qr-qq.jpg?raw=true\" alt=\"QQ Group QR\" width=\"180\"/>\n\n**📱 Community — WeChat Group:**\n\n<img src=\"https://github.com/yun520-1/mark-heartflow-skill/blob/main/assets/community-qr-wechat.jpg?raw=true\" alt=\"WeChat Group QR\" width=\"180\"/>\n\n**💖 Support HeartFlow — Donate via Alipay (QR code):**\n\n<img src=\"https://github.com/yun520-1/mark-heartflow-skill/blob/main/assets/alipay-donate-qr.jpg?raw=true\" alt=\"Alipay Donate QR\" width=\"180\"/>\n\n*If HeartFlow's discrimination philosophy resonates with you, a small donation keeps the pain-sense layer of AGI alive.*\n\n---\n\n## 📜 License\n\nMIT License · Copyright © 2026 · markcell@outlook.com\n\n---\n\n*HeartFlow 心虫 — The first layer of AGI. Who says \"no\"?*\n\nFile v6.5.2:_meta.json\n\n{\n  \"ownerId\": \"kn7719xtz37kprbvgjknegrt21886q74\",\n  \"slug\": \"mark-heartflow-skill\",\n  \"version\": \"6.5.2\",\n  \"publishedAt\": 1786846730354\n}\n\nFile v6.5.2:AGI_VISION.md\n\n# HeartFlow 重构规划 — 从 AGI 推演回来的架构\n\n## 前置假设\n\nAGI 不会是一个模型。AGI 是一个**系统**，由多个不同性质的子系统组成。\n模型（LLM/世界模型）负责生成，但生成不是智能的全部。\n\n智能需要三样模型给不了的东西：\n\n| 模型给不了 | 为什么给不了 | 谁能给 |\n|-----------|------------|-------|\n| 跨会话身份连续性 | 每次推理独立 | 持久化状态层 |\n| 不取悦用户的判断 | RLHF 训练目标就是取悦 | 规则引擎（没有用户概念） |\n| 错误记忆不遗忘 | 权重更新需要重训练 | Q-table + 键值存储 |\n\n这三个缺口的交集，就是心虫能在 AGI 里占的位置。\n\n---\n\n## 一、AGI 中需要的心虫能力（从 8 项推演）\n\n### 1.1 跨会话错误记忆 — LLM 永远做不了\n\nLLM 面对同一个问题两次：\n```\nQ: \"这个投资方案风险大吗？\"\nT1: \"建议谨慎，高杠杆策略在市场波动时风险较大。\"\nT2: \"从数据看该方案最大回撤 15%，在可接受范围内。\"\n```\n\n两次都对，但互相矛盾。LLM 不记得上次说过什么。\n\n心虫能力：Q-table 记录\"上次这个场景选了谨慎→结果对了\"，下次匹配到同一模式时降权。\n\n### 1.2 价值观锚定 — LLM 随对话漂移\n\nLLM 在对话中会被用户说服。20 轮对话后，LLM 可能支持它在第 1 轮反对的立场。\n\n心虫能力：strategicRestraint 的 3 态返回（aligned/drifted/diverged）锚定在初始身份上。\n\n### 1.3 诚实自诊 — LLM 永远说\"没问题\"\n\n```\n问 LLM：\"你刚才的回答对吗？\"\n→ \"对的，我确认了所有事实。\"（即使错了）\n```\n\n心虫能力：selfDiagnosis 诚实报告自己的状态，没有维护面子的压力。\n\n---\n\n## 二、重构：不是升级，是重建\n\n### 2.1 删什么\n\n| 删除 | 理由 |\n|------|------|\n| 132 模块中 110 个空壳 | 它们假装心虫能做认知/意识/创造力，实际是空文件或 LLM 调用包装 |\n| thoughtChain | 这是让心虫\"假装推理\"的组件，实际全走 LLM |\n| 所有\"可以但没有被调用\"的引擎 | adversarialSynthesis, stabilityGuard, metaCalibration, confidenceCalibrator |\n| heartflow.js 的 start() 中 2200 行初始化 | 95% 是在初始化不会被用到的模块 |\n\n### 2.2 保留什么\n\n| 保留 | 为什么 |\n|------|--------|\n| decisionRouter (31 条规则 + 权重 + feedback) | 唯一真实有决策逻辑的引擎 |\n| decisionVerifier (5 项检查) | 唯一真实有验证逻辑的引擎 |\n| self-healing RL (Q-table) | 唯一真实有跨会话学习的组件 |\n| sustainedDriftDetector | 追踪身份一致性随时间的变化 |\n| strategicRestraint (3 态返回) | 锚定输出不漂移 |\n| selfDiagnosis (诚实报告) | 不撒谎的自检 |\n| 知识域探测 (knowledgeDomains) | 输入分类，轻量可用 |\n| gaps/knowledgeExplorer | 识别未知域的能力 |\n\n### 2.3 新架构\n\n```\n输入 →\n  LLM 感知层（不变）\n    ↓\n  心虫核心（5 个引擎，不是 132 个模块）：\n    ├── 错误记忆（self-healing Q-table → 存储+检索）\n    ├── 决策审计（decisionRouter + decisionVerifier → 每条决策可追溯）\n    ├── 身份锚定（strategicRestraint + sustainedDriftDetector → 不漂移）\n    ├── 诚实自诊（selfDiagnosis → 知道自己不知道）\n    └── 域感知（knowledgeDomains + gaps → 知道自己不懂什么）\n    ↓\n  输出\n```\n\n## 三、AGI 中的位置图（非心虫视角，是 AGI 视角）\n\n```\nAGI 系统架构：\n\n[世界模型] → 产生可能性\n    ↓\n[LLM 推理] → 选择最可能路径\n    ↓\n[执行器] → 在真实世界产生变化\n    ↓\n[心虫层] ← 不产生任何东西，只做 4 件事：\n   1. 记录：这次执行的结果存入错误记忆\n   2. 验证：下次执行前查一下历史中有没有类似错误\n   3. 锚定：输出有没有偏离初始身份\n   4. 报告：诚实告知自己的状态\n\n心虫不产生回答，但 LLM 每次回答都要经过心虫的验证门。\n```\n\n---\n\n## 四、第一次重构要做的事\n\n### 4.1 拆掉 heartflow.js\n\n当前 heartflow.js (4800 行) 集成了 132 个模块的初始化和编排。\n\n重构后 heartflow.js (~500 行)：\n- 只启动 5 个核心引擎\n- 暴露 MCP 工具：store_error / query_error / verify_decision / check_identity / diagnose_self\n- 其他模块按需加载（有人调才加载）\n\n### 4.2 重写 mcp-server.js\n\n当前 mcp-server.js 暴露 25 个工具，大部分跑在空壳上。\n\n重构后暴露 5 个工具：\n```\nheartflow_memory_store(error)       → 写入错误记忆\nheartflow_memory_query(problem)     → 检索相关历史错误\nheartflow_verify(decision, options) → 5 项验证检查\nheartflow_check_alignment(output)   → strategicRestraint 检查\nheartflow_diagnose()                → selfDiagnosis 完整报告\n```\n\n这 5 个工具任何 LLM 都可以调用。不绑定在 think() 内部。\n\n### 4.3 删文件\n\n删除约 110 个空壳模块文件，保留大约 20 个真实引擎 + 基础设施。\n\n---\n\n## 五、这不是 AGI，这是一片砖\n\n心虫重构后仍然不是 AGI。它是一个**跨会话错误记忆与决策审计系统**。\n\nAGI 需要 8 个能力，心虫能提供其中 2 个（学习、自诊断）。\nLLM 能提供 4 个（感知、推理、决策、执行）。\n剩下的 2 个（执行后的自纠正）需要 LLM + 心虫共同完成。\n\n加起来不构成 AGI。但加在一起，比 LLM 单独多了一个**不遗忘的维度**。\n\nFile v6.5.2:ARCHITECTURE_REORG_v6.0.6.md\n\n# 心虫 (HeartFlow) 架构重组分析 — v6.0.6 校正版\n\n> 分析日期：2026-07-16（基于 v6.0.6 真实运行数据，非 v6.0.2 文档）\n> 分析对象：HeartFlow v6.0.6（309 个 src JS 文件，131+ 模块，MCP HTTP 服务 8099 端口）\n> 目的：对比三种架构迁移方案，输出推荐结论与迁移路径\n\n---\n\n## 〇、当前架构基线（v6.0.6 实测）\n\n```\n┌──────────────────────────────────────────────┐\n│  WorkBuddy / Agent Host                       │\n│  ┌──────────┐    ┌─────────────────────────┐  │\n│  │  SKILL   │    │  MCP Client (SSE/JSON-RPC)│  │\n│  │  .md     │    │                          │  │\n│  └────┬─────┘    └───────────┬─────────────┘  │\n│       │ load                 │ connect        │\n└───────┼──────────────────────┼────────────────┘\n        │                      │ :8099\n   ┌────▼──────────────────────▼─────────────┐\n   │  HeartFlow Engine (v6.0.6)               │\n   │  ┌─────────┐  ┌──────────────────────┐  │\n   │  │ CLI     │  │ MCP HTTP Server       │  │\n   │  │ bin/    │  │ mcp/mcp-server-http   │  │\n   │  │ cli.js  │  │ (pm2 ^7.0.3, Bearer)  │  │\n   │  └────┬────┘  └──────────┬───────────┘  │\n   │       │                  │               │\n   │  ┌────▼──────────────────▼───────────┐   │\n   │  │  HeartFlow Core (3167 行)          │   │\n   │  │  engine-initializer (惰性注册)     │   │\n   │  │  memory-kernel / formula / cortex  │   │\n   │  └───────────────────────────────────┘   │\n   └──────────────────────────────────────────┘\n```\n\n**实测关键指标（v6.0.6）：**\n| 指标 | v6.0.2 旧分析 | v6.0.6 实测 | 变化 |\n|---|---|---|---|\n| 冷启动 | 14.4s | **1.37s** | ↓ 90% |\n| think() 热路径 | 310-430ms | **~49ms** | ↓ 85% |\n| MCP 工具数 | 28 | **31** | +3 |\n| report-generator | 缺失 | **已存在** | 已修 |\n| 悬空 require | 87 | **0 [C]类破坏性** | 已收敛 |\n| pm2 挂起 | 存在 | **已修(disconnect)** | 已修 |\n| 测试 | 179/179 误报绿 | **verify 14/14 真绿** | 已修 |\n| 公式数 | 379 | **382** | 实测 |\n| 版本四源 | 漂移 | **6.0.6 统一** | 已修 |\n\n**结论：v6.0.2 五维度审计发现的严重/高问题中，90% 已在 v6.0.5/v6.0.6 真实闭合。架构无需为\"修洞\"而更换。**\n\n---\n\n## 方案一：纯 MCP 服务 + 钩子注入模式\n\n### 核心设计思路\n去掉 WorkBuddy 专用 Skill 层，心虫退化为纯 MCP 协议服务。宿主 agent 通过客户端侧 hook 配置自动注入认知预处理。\n\n### 典型架构图\n```\n任意 MCP 客户端 → Hook 配置(on_turn_start/think, on_turn_end/memory)\n                → MCP connect :8099\n                → HeartFlow MCP Server (31 tools, Bearer, 无 Skill 层)\n                → HeartFlow Core (不变)\n```\n\n### 适用场景\n- 宿主 agent 已支持 MCP + 成熟 hook 机制\n- 希望被多平台 agent 调用，不锁 WorkBuddy\n\n### 关键权衡点\n| 维度 | 分析 |\n|---|---|\n| ✅ 跨平台 | 任何 MCP 客户端可接入，去 WorkBuddy 锁定 |\n| ✅ 职责清晰 | Skill 触发逻辑移交客户端 hook 配置 |\n| ❌ hook 标准化缺失 | 无统一 MCP hook spec，各客户端实现不同，需维护多份模板 |\n| ❌ 失 Skill 元数据 | SKILL.md 的权限声明/安装指引/身份定义丢失 |\n| ❌ WorkBuddy hook 不成熟 | 当前 `on_turn` 钩子能力有限，实际上行不通 |\n\n### v6.0.6 下的额外观察\nMCP 服务本身已是标准协议（31 工具、Bearer 鉴权），任何 MCP 客户端**现在就能连**——Skill 层只是 WorkBuddy 的\"安装入口\"，不影响 MCP 通用性。因此\"跨 agent 兼容\"在方案三下已部分满足，方案一的迫切性更低。\n\n---\n\n## 方案二：独立可安装 Agent 应用\n\n### 核心设计思路\n心虫发布为独立应用（npm 全局包 / Docker / 系统服务），暴露 REST + SSE API，充当认知引擎微服务，多 agent 并发调用。\n\n### 典型架构图\n```\n任意 Agent → HTTP/gRPC → HeartFlow Agent Service\n  ├─ API Gateway (POST /think, GET /health, GET /memory)\n  ├─ HeartFlow Engine (懒加载 + 共享会话)\n  └─ 持久化 (JSONL/SQLite, namespace 隔离)\n安装: npm i -g @yun520-1/heartflow-agent && heartflow-agent start\n```\n\n### 适用场景\n- 团队级基础设施（一实例服务多 agent/用户）\n- 需严格 API 版本管理、Docker/k8s 部署\n- 宿主无 MCP 能力、只支持 HTTP\n\n### 关键权衡点\n| 维度 | 分析 |\n|---|---|\n| ✅ 最大跨 agent 兼容 | 任何 HTTP 客户端可调用，零协议锁定 |\n| ✅ 专业运维 | Docker/k8s、GitHub Packages、版本化 API |\n| ✅ 高并发隔离 | 多 session 并发，namespace 分区 |\n| ❌ 架构倍增复杂性 | API Gateway + 鉴权 + 限流 + 版本 + CI/CD release → 当前单人维护不现实 |\n| ❌ 冷启动未解决 | 服务启仍 1.37s（除非常驻），docker 冷启更慢 |\n| ❌ 状态管理最重 | session 生命周期、并发安全、内存泄漏防护 |\n\n### v6.0.6 下的额外观察\n冷启动已从 14.4s 降到 1.37s，方案二原本\"常驻解决冷启\"的卖点被削弱。但方案二的真正价值（多 agent 共享记忆、独立扩缩容）在当前单人/单平台阶段是**过早优化**。\n\n---\n\n## 方案三：保持现有 Skill + MCP 架构并优化\n\n### 核心设计思路\n不改架构范式，聚焦消除已知痛点。优化方向：God file 拆分、测试套件真绿复验、日志治理收尾、Skill 文档增强。\n\n### 典型架构图\n```\nWorkBuddy → SKILL.md(优化) + MCP Client\n          → HeartFlow (优化后)\n            ├─ MCP HTTP Server (pm2 ^7.0.3, /health, graceful shutdown)\n            ├─ Lazy Engine Initializer (核心模块热加载)\n            ├─ HeartFlow Core (3167 行, 待拆 P1-P4)\n            └─ ReportGenerator + infra/logger (已就位)\n```\n\n### 适用场景\n- 目标用户仍在 WorkBuddy 生态\n- 快速交付、低风险优先\n- 单人维护（当前实际）\n\n### 关键权衡点\n| 维度 | 分析 |\n|---|---|\n| ✅ 最低风险 | 不改范式，精力花\"修洞\"而非\"换房\" |\n| ✅ 复用 CI/测试/Skill 市场 | Skill 已上线，分发渠道不丢 |\n| ✅ UPGRADE_PLAN 已有方案 | P1-P4 拆分计划直接对齐 |\n| ❌ 不入独立 agent 生态 | 限制 WorkBuddy 内，无法被其他 agent 直接调用 |\n| ❌ 不解决 Skill 本质局限 | WorkBuddy 专有格式，无法跨平台复用 |\n| ❌ 仍依赖 pm2 守护 | pm2 可选依赖，nohup 回退 Windows 不可用 |\n\n### v6.0.6 下的额外观察\n方案三的 P0-P2 实病（冷启动、pm2 挂起、report、测试绿、版本同步、计算透出、空输入守卫、文档失真）**已在本副本真实修复**。剩余仅 God file 拆分（中低优先级、破坏性高）和测试套件真绿复验（中优先级）。\n\n---\n\n## 对比矩阵（v6.0.6 校正）\n\n| 维度 | 方案一：纯 MCP+Hook | 方案二：独立 Agent | 方案三：保持+优化 |\n|---|---|---|---|\n| **架构复杂度** | ★★☆ 中 | ★★★ 高 | ★☆☆ 低 |\n| **部署分发** | ★★☆ 同现在+钩子配置 | ★★★ npm -g/Docker | ★★☆ 不变(pm2/npm) |\n| **跨 agent 兼容** | ★★★ MCP客户端 | ★★★ HTTP/MCP | ★☆☆ 仅 WorkBuddy* |\n| **实时性/延迟** | ★★☆ 同现在 | ★★☆ 常驻可略 | ★★★ 冷启1.37s/think49ms |\n| **状态管理** | ★★☆ 同现状 | ★★★ 最强(session/共享记忆) | ★★☆ 同现状 |\n| **扩展性/插件** | ★★☆ MCP工具可扩 | ★★★ API+插件注册 | ★☆☆ Skill专有 |\n| **安全性** | ★★☆ Bearer同现状 | ★★★ API Key+限流+namespace | ★★☆ Bearer同现状 |\n| **维护成本** | ★★☆ 中(钩子模板) | ★☆☆ 高(版本/文档/多client) | ★★★ 低(修洞) |\n| **用户接入门槛** | ★★☆ 钩子配置门槛 | ★★★ npm -g最简 | ★★☆ 市场一键装 |\n\n> ★ 越多越好（复杂度/成本高分=差；维护性高分=好）\n> *注：方案三下 MCP 服务已是标准协议，任何 MCP 客户端**现在可连**，跨 agent 兼容实际为\"≥2（MCP客户端）\"，原分析\"仅1\"已过时。\n\n---\n\n## 推荐结论\n\n**推荐方案：方案三（保持架构 + 优化），分阶段向方案一、二演进。**\n\n### 核心论据（v6.0.6 校正后更坚实）\n1. **风险最低**：已知严重/高问题 90% 已在 v6.0.5/v6.0.6 真实闭合，剩余项全在方案三 P1-P4 范围内。\n2. **MCP 已是标准协议**：31 工具、Bearer 鉴权的 MCP 服务现成，任何 MCP 客户端可连——\"跨 agent 兼容\"在方案三下已部分满足，方案一的迫切性被削弱。\n3. **换架构不消代码债**：原五维度审计的发现（冷启/报告/测试绿/日志）全是代码债与模块缺失，换方案一/二一个都不会消失，反而引入新 bug。\n4. **单人维护现实**：方案二的 API Gateway/限流/版本/CI-CD release 对当前规模是过度工程化。\n\n### 迁移节奏（条件驱动，非时间预设）\n```\n方案三(当前优化, 已完成 P0-P2)\n  → 方案一过渡: 当 WorkBuddy hook 机制成熟，抽 SKILL.md 触发规则为可复用 MCP hook 配置\n  → 方案二终态: 当 ≥50 用户 且 ≥3 agent 平台接入需求 且 团队可承运维成本\n```\n\n### 一句话\n**现在不要动架构——洞已修九成。待 God file 拆分完成、测试真绿复验后，再评估\"独立 Agent\"这剂猛药是否必要。**\n\n---\n\n## 附录：v6.0.6 真实指标 vs 方案预估\n\n| 指标 | v6.0.2旧分析 | v6.0.6实测 | 方案三目标 |\n|---|---|---|---|\n| 冷启动 | 14.4s | 1.37s | <3s ✅已达成 |\n| think延迟 | 310-430ms | 49ms | 300-350ms ✅远超 |\n| 安装步数 | 3 | 3 | 3 |\n| 跨agent数 | 1 | ≥2(MCP客户端) | ≥2 ✅已部分达成 |\n| 维护人日/月 | 2-3 | 1-2 | 1-2 ✅ |\n| 可测试性 | 虚假绿 | 真绿(14/14) | 真绿 ✅ |\n\nFile v6.5.2:ARCHITECTURE.md\n\n# HeartFlow 长期架构 — 可持续升级方案\n\n## 目标\n\nheartflow.js 从 4742 行降到 800 行。新能力不碰 heartflow.js。\n\n## 状态 (v6.3.0)\n\n| 组件 | 状态 | 说明 |\n|------|------|------|\n| 插件加载器 | ✅ 已实现 | src/loader/plugin-loader.js |\n| 插件注册表 | ✅ 已实现 | plugins/registry.json |\n| 插件示例 | ✅ 已迁移 | src/plugins/blind-spot-breaker/ |\n| HookBus | ✅ 已使用 | 插件通过 hookBus.on() 注册 |\n| heartflow.js start() | ⏳ 6行插件加载代码 | 剩余 2200 行待提取 |\n\n## 架构变化\n\n### 旧（改 heartflow.js → 加模块）\n```\n用户需求 → 改 heartflow.js (import + start() + think() + export)\n        → 或新建文件但 heartflow.js 仍要改 import 和挂接\n```\n\n### 新（改插件目录 → 自动发现）\n```\n用户需求 → 写 src/plugins/my-thing/index.js (init + hooks)\n        → 注册到 plugins/registry.json (可选)\n        → heartflow.js 自动加载 → 0 行改动\n```\n\n## 三层架构\n\n### 第1层：核心内核（heartflow.js → 目标 800 行）\n- 生命周期管理（start/shutdown）\n- 插件加载器（PluginLoader）\n- HookBus 事件总线（唯一扩展点）\n- 配置系统\n- **不直接 import 任何业务模块**\n\n### 第2层：系统模块（src/core/ -> src/engine/）\n- 从 heartflow.js 提取的现有系统服务\n- 通过 HookBus 注册\n- 每个引擎模块有独立生命周期\n\n### 第3层：插件（src/plugins/）\n- 新能力 = 新建目录 + index.js\n- 暴露 {name, hooks: [{event}], init(hf, {hookBus, config})}\n- 自动被 PluginLoader 发现\n- 可以独立测试、独立启用/禁用\n\n## 迁移计划\n\n### ✅ v6.3.0 — 插件加载器\n- PluginLoader 自动发现 + 加载插件\n- BlindSpotBreaker 迁移为第一个插件\n\n### ⏳ v6.4.0 — 模块访问统一\n- this.knowledge → this.modules.knowledge\n- 旧 this.X 保留别名不破坏\n\n### ⏳ v6.5.0 — HookBus 迁移第2-5段\n- 把对抗综合器、情感记忆桥、元认知标注搬出 think()\n\n### ⏳ v6.6.0 — start() 拆分\n- 2200 行 start() 提取\n- 每个子系统独立 init 文件\n\n## 原则\n- 不重写现有模块\n- 不改现有 API\n- 不一次迁移完\n- 不加新依赖\n\nFile v6.5.2:AUDIT_REPORT.md\n\n# HeartFlow Security Audit Report\n\n> 审计日期：2026-07-14  \n> 审计范围：`formulas/`、`mcp/`、`transformers/` 相关代码路径  \n> 审计员：自动安全审计  \n> 代码版本：ae71cf7f (v6.0.0)  \n\n---\n\n## 审计摘要\n\n本次审计聚焦三个核心子模块：\n\n1. **formulas** — `mathjs.evaluate()` 表达式注入风险\n2. **mcp** — stdio/HTTP 输入验证、消息体限制、认证与授权\n3. **transformers** — `@xenova/transformers` 模型加载安全性与完整性校验\n\n整体结论：项目已实施多项审计修复，部分高风险面已有缓解措施，但仍存在若干可被利用或可改进的安全缺口，详见下文。\n\n---\n\n## 严重问题 (P0)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P0-1 | **公式库未签名/未哈希验证** — 若 `formulas/formulas.json` 被篡改，攻击者可注入任意 mathjs 表达式并达到代码执行效果 | `src/formula/formula-search.js`、`src/formula/formula-calculator.js` | 高 | 对公式库实施 JSON schema + 发布时哈希/签名校验；运行时拒绝异常结构或签名不匹配的公式 |\n| P0-2 | **MCP 通用路由缺乏参数白名单** — `heartflow_dispatch` 允许调用任意内部路由，若被未授权调用可能导致内部状态泄露或越权操作 | `mcp/mcp-server-stdio.js:269-274`、`src/mcp-server.js` dispatch 相关 handlers | 中高 | 对 `heartflow_dispatch` 增加路由白名单，并移除或严格限制 stdio 版本的通用路由暴露 |\n| P0-3 | **模型加载无完整性校验** — `@xenova/transformers` 远程或本地模型文件未做 hash/signature 校验，存在供应链投毒或本地替换风险 | `src/search/semantic-search.js:354-381` | 高 | 对模型文件增加 SHA-256 校验；支持 pinned revision / localModelPath 白名单；禁止自动下载不可信来源模型 |\n\n---\n\n## 中等问题 (P1)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P1-1 | **HTTP MCP 消息体无 JSON schema 校验** — `tools/call` 仅检查 `name` 存在性，不校验 `arguments` 结构，异常输入直接进入业务逻辑 | `mcp/mcp-server-http.js:1238-1250`、`src/mcp-server.js` tools/call 分支 | 中 | 按 `TOOLS[].inputSchema` 实现运行时参数校验，非法参数返回 `-32602` |\n| P1-2 | **部分 handler 存在路径注入风险** — `benchmark_run`/`benchmark_import_failures` 接受 `dataDir`/`filePath`，虽有 `confinePath` 但 stdio 版本未见同等限制 | `src/mcp-server.js:1075-1146` vs `mcp/mcp-server-http.js` | 中 | 统一所有文件系统访问使用 `confinePath`；stdio 版本增加同等约束 |\n| P1-3 | **transformers 本地模型路径未校验** — `modelPath` 可直接指向任意目录，若攻击者控制该参数可加载恶意 ONNX 模型 | `src/search/semantic-search.js:195-197` | 中 | 限制 `modelPath` 至受控目录；支持模型目录白名单 |\n| P1-4 | **错误信息可能泄露路径/环境细节** — 多个 catch 块直接返回 `err.message`，可能暴露内部路径、堆栈或模型信息 | 多文件 | 中 | 统一错误处理中间件，生产环境仅返回 sanitized message |\n\n---\n\n## 轻微问题 (P2)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P2-1 | **缺少消息体大小限制的 fallback 策略** — 当前 HTTP 版 1MB 限制合理，但未对不同 tool 设置差异化上限 | `mcp/mcp-server-http.js:1246-1261` | 低 | 对 `benchmark_*`、`knowledge_*` 等 heavy tools 设置更小上限 |\n| P2-2 | **SSE 客户端未显式认证绑定** — sessionId 为随机 UUID，但未与 auth token 做会话绑定，理论上存在 session 劫持窗口 | `mcp/mcp-server-http.js:1210-1228` | 低 | 将 sessionId 与 token hash 关联，清理时校验所有权 |\n| P2-3 | **mathjs 配置未完全冻结** — 虽禁用了 `import`/`createUnit`，但未显式禁用 parser/evaluator 的所有扩展点 | `src/formula/formula-calculator.js:9-17` | 低 | 在 `create()` 时传入最小化配置，仅启用计算必需函数 |\n| P2-4 | **模型加载重试可能导致资源耗尽** — `_loadModel` 最多重试 2 次且无退避上限保护，并发场景下可能占用过多线程/内存 | `src/search/semantic-search.js:357-377` | 低 | 增加指数退避 + 最大并发加载限制 |\n\n---\n\n## 详细技术发现\n\n### 1. formulas — mathjs.evaluate 表达式注入\n\n**现状**\n- `formula-calculator.js` 已禁用 `math.import`、`createUnit`，并强制参数类型为 number。\n- 计算公式时，流程为：读取 `formulas.json` → 提取 `formula.formula` → 参数替换 → `math.evaluate(expression)`。\n\n**风险**\n- 如果 `formulas/formulas.json` 被攻击者篡改，可插入类似 `system('...')` 或利用 mathjs parser 的副作用函数。\n- `mathjs.evaluate` 在沙箱外执行时，若实例被污染，可执行任意 JavaScript。\n- `_substituteParams` 中的正则替换若遇到精心构造的 key，可能破坏表达式结构。\n\n**缓解不足**\n- 无公式来源完整性校验。\n- 无公式内容静态分析或白名单。\n- `_substituteParams` 未限制参数 key 的字符集。\n\n### 2. mcp — stdio/HTTP 输入验证\n\n**现状**\n- HTTP 版强制 Bearer token，使用 `crypto.timingSafeEqual`，有 token/IP 双重速率限制。\n- 请求体限制 1MB，支持 SSE + JSON-RPC over HTTP。\n- stdio 版无认证机制，依赖本地进程隔离。\n\n**风险**\n- **参数注入**：多数 handler 直接透传 `args` 到 `heartflow.dispatch()`，无 schema 校验。\n- **路径遍历**：`benchmark_*`、`knowledge_*` 等工具涉及文件系统访问，需确保 confinePath 全覆盖。\n- **通用路由滥用**：`heartflow_dispatch` 暴露内部路由前缀，若 token 泄露可遍历 engine 内部 API。\n- **DoS**：无 tool 级别超时；单个长时间运行的 tool 会阻塞事件循环或占用 SSE 连接。\n\n### 3. transformers — 模型加载安全\n\n**现状**\n- `SemanticSearch` 懒加载 `@xenova/transformers` 的 `feature-extraction` pipeline。\n- 支持远程模型名或本地 `modelPath`。\n- 量化加载，默认 `all-MiniLM-L6-v2`。\n\n**风险**\n- **供应链攻击**：远程模型从 HuggingFace Hub 下载，未校验 hash，若 CDN 被投毒或模型仓库被篡改，可加载恶意 ONNX 模型。\n- **本地模型替换**：`modelPath` 指向本地目录时，攻击者可替换 `onnx/model.onnx` 等文件。\n- **信息泄露**：模型加载错误信息可能暴露目录结构、网络环境。\n- **资源耗尽**：大模型或恶意模型可能导致内存/CPU 耗尽。\n\n---\n\n## 合规与最佳实践对照\n\n| 检查项 | 现状 | 建议状态 |\n|--------|------|----------|\n| 输入验证 | 部分工具有类型检查，缺 schema 校验 | 应全工具 schema 校验 |\n| 输出编码 | JSON 序列化自动转义 | ✅ |\n| 认证 | HTTP 版 Bearer token + timing-safe compare | ✅ stdio 版缺认证 |\n| 授权 | 无细粒度授权，仅单一 token | 建议 role-based tool 授权 |\n| 速率限制 | IP + token 双重限制 | ✅ |\n| 完整性校验 | 公式库、模型文件均无 hash | ❌ 需修复 |\n| 日志安全 | 部分错误信息可能泄露路径 | 需 sanitize |\n| 依赖安全 | mathjs ~15.2.0, @xenova/transformers | 需定期 audit |\n\n---\n\n## 修复建议优先级\n\n### 立即执行 (P0)\n1. **公式库签名** — 在发布流程中对 `formulas.json` 生成 SHA-256 哈希，并在 `FormulaSearch.loadFormulas()` 时校验。\n2. **限制通用路由** — `heartflow_dispatch` 改为路由白名单，或移除 stdio 暴露。\n3. **模型文件校验** — 为默认模型记录 expected hash；加载后比对；支持 `modelPath` 白名单。\n\n### 近期执行 (P1)\n4. **MCP 参数 schema 校验** — 实现轻量 JSON Schema validator，对所有 `TOOLS[].inputSchema` 做运行时校验。\n5. **统一 confinePath** — 确保所有文件系统访问都经过路径约束。\n6. **sanitize 错误输出** — 统一错误响应格式，避免内部细节泄露。\n\n### 中期执行 (P2)\n7. **tool 级超时** — 为 heavy tools 设置执行超时。\n8. **SSE 会话绑定** — 将 session 与 token 关联。\n9. **mathjs 最小化配置** — 显式禁用所有非必需功能。\n\n---\n\n## 审计方法说明\n\n- 静态代码审查：人工阅读关键路径源码。\n- 模式匹配：搜索 `mathjs.evaluate`、`pipeline(`、`req.body`、`fs.readFileSync` 等风险 API。\n- 交叉比对：对比 `mcp/mcp-server-http.js` 与 `src/mcp-server.js`，确认安全修复是否同步。\n- 未执行动态测试或模糊测试。\n\n---\n\n## 结论\n\n`formulas/` 的表达式注入风险主要来自**数据源不可信**而非 mathjs 本身；`mcp/` 的输入验证在 HTTP 层较完整，但在业务参数层仍薄弱；`transformers/` 的模型加载安全依赖**供应链可信**，当前缺乏完整性校验。建议按 P0→P1→P2 顺序逐步修复，并在 CI 中增加对应安全测试门禁。\n\nFile v6.5.2:AUDIT-v6.0.0.md\n\n# 心虫 HeartFlow v6.0.0 全面代码审计报告\n\n> 审计日期：2026-07-14  \n> 代码版本：ae71cf7f (v6.0.0)  \n> 审计范围：全量代码、同步前准备、用户体验、安装体验\n\n---\n\n## 一、全量代码审计\n\n### 1.1 严重问题 (P0)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P0-1 | **God file 架构债务** | `src/core/heartflow.js` 5991行 | 高 | 按职责拆分：`think-core`、`memory-bridge`、`emotion-loop`、`decision-router`。当前文件占全库2%行数却承载全部核心逻辑，修改风险极高 |\n| P0-2 | **fs 直接操作绕过 SafeFS** | 317处 `fs.readFileSync/writeFileSync/appendFileSync` | 高 | 建立 `SafeFS` 强制规范：所有持久化走 `SafeFS.write()`，在 CI 加 grep 门禁 |\n| P0-3 | **child_process 调用未统一** | 30处 `child_process/exec` | 高 | `code-executor` 中已有沙箱，但其他模块仍有裸调用。统一走 `SafeExecutor` |\n| P0-4 | **eval/new Function 残留** | 4处 | 中高 | 公式引擎可能有动态求值，需确认是否有用户输入注入路径。加输入白名单校验 |\n\n### 1.2 中等问题 (P1)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P1-1 | console.log 残留 40处 | src/ 全库 | 中 | 替换为 `Logger.info/debug`，生产环境静默 |\n| P1-2 | TODO 残留 1处 | src/ | 中 | 清除或转为 issue |\n| P1-3 | 超长文件 >500行: 9个 | 见下表 | 中 | heartflow.js(5991)、desire-cognition(3429)、heart-logic(2311) 优先拆分 |\n| P1-4 | 异步函数无 try/catch | 8个文件 | 中 | 加统一错误处理包装 `safeAsync(fn)` |\n| P1-5 | .gitignore 排除 data/ 导致记忆无法同步 | .gitignore | 中 | 记忆应纳入版本控制或单独 remote，当前 `git push` 不会上传用户记忆 |\n\n### 1.3 轻微问题 (P2)\n\n| # | 问题 | 位置 | 严重程度 | 建议 |\n|---|------|------|----------|------|\n| P2-1 | 平均文件大小 500行 | 全库 | 低 | 保持现有模块粒度，不强行拆分 |\n| P2-2 | config.json 仅2个键 | config.json | 低 | 迁移到 `src/core/config-v2.js`，已存在但未完全采用 |\n| P2-3 | 无 dist/ 打包目录 | 根目录 | 低 | 加 `npm run build` 生成 `dist/`，便于 clawhub.ai 分发 |\n\n### 1.4 代码质量数据\n\n| 指标 | 数值 | 评价 |\n|------|------|------|\n| src JS 文件数 | 292 | 模块化良好 |\n| test JS 文件数 | 39 | 测试覆盖充足 |\n| 平均文件大小 | 500行 | 可接受 |\n| try/catch 覆盖率 | 156个文件有 | 基础完善 |\n| npm audit | 0 漏洞 | 优秀 |\n| 硬编码密钥 | 0 | 优秀 |\n\n---\n\n## 二、同步前准备审计\n\n### 2.1 依赖管理\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 版本一致性 | ✅ | VERSION/package.json/SKILL.md 均为 6.0.0 |\n| 硬依赖 | ✅ | 仅 `mathjs ~15.2.0`，最小化 |\n| 可选依赖 | ⚠️ | `@xenova/transformers` 和 `pm2`，需确认 npm install --omit=optional 是否影响功能 |\n| 过期依赖 | ✅ | npm outdated 无输出 |\n| package-lock.json | ✅ | 存在且版本锁定 |\n\n### 2.2 配置完整性\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| config.json | ⚠️ | 仅2个键，未覆盖全部配置项 |\n| .env | ❌ | 不存在（预期内，用 config-v2.secret()） |\n| .gitignore | ✅ | 覆盖 .env/.key/.pem |\n| 环境变量检测 | ❌ | 无自动检测脚本 |\n\n### 2.3 同步风险点\n\n| 风险 | 严重程度 | 缓解措施 |\n|------|----------|----------|\n| data/ 被 .gitignore 排除 | 中 | 用户记忆不随代码同步，需单独处理 |\n| 无 CI 自动化测试 | 中 | .github/workflows 存在但无内容 |\n| 无发布脚本 | 低 | 需手动 git push + npm publish |\n| 大文件未过滤 | 低 | user-memories.jsonl 468KB 不纳入 git |\n\n### 2.4 版本兼容性\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| Node.js 版本要求 | ✅ | bin/verify.js 检查 >= 18 |\n| 引擎启动 | ✅ | 测试通过 |\n| 模块数 | ✅ | >= 124 |\n| 测试文件数 | ✅ | >= 10 |\n\n---\n\n## 三、用户体验审计\n\n### 3.1 交互流程\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| CLI 命令 | ✅ | `node bin/cli.js chat` / `status` / `--chat \"消息\"` |\n| 斜杠命令 | ✅ | /psych /emotion /dr /status /routes /exit |\n| 帮助系统 | ⚠️ | bin/cli.js 有基本帮助，但无完整文档 |\n| 首次使用引导 | ❌ | 无 onboarding 流程 |\n\n### 3.2 错误提示\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 错误分类 | ✅ | code-executor.js 有 4 类错误分类 |\n| 中文提示 | ✅ | 部分模块有中文错误消息 |\n| 恢复机制 | ❌ | 多数错误直接 throw，无自动恢复 |\n| 日志可读性 | ⚠️ | 混合 console.error 和 Logger，格式不统一 |\n\n### 3.3 响应速度\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 冷启动 | ✅ | <1500ms（CURRENT_STATE.md 声称） |\n| 模块缓存 | ✅ | _lazyCache 达到 100 模块 |\n| 同步IO | ⚠️ | heartflow.js 有同步文件操作，阻塞事件循环 |\n\n### 3.4 核心功能流程\n\n| 功能 | 状态 | 说明 |\n|------|------|------|\n| think() 主路径 | ✅ | 测试通过 |\n| 记忆写入 | ✅ | MemoryKernel R1-R8 全通过 |\n| 公式引擎 | ✅ | 379 公式加载 |\n| 认知管线 | ✅ | 四层架构运行 |\n\n---\n\n## 四、用户安装体验审计\n\n### 4.1 安装步骤\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 安装命令 | ✅ | `npm install @yun520-1/heartflow` |\n| Quick Start | ✅ | README.md 有 176 行 Quick Start |\n| 环境依赖 | ⚠️ | 仅说明 Node.js >= 18，无自动检测 |\n| 安装失败处理 | ❌ | 无错误恢复指南 |\n\n### 4.2 文档完整性\n\n| 文档 | 状态 | 说明 |\n|------|------|------|\n| README.md | ✅ | 306 行，33 个标题 |\n| INSTALL.md | ⚠️ | 56 行，过于简略 |\n| SECURITY.md | ✅ | 存在 |\n| CHANGELOG.md | ✅ | 存在 |\n| UPGRADE_PLAN.md | ✅ | 存在 |\n| 故障排查 | ❌ | 无 TROUBLESHOOTING.md |\n| API 文档 | ❌ | 无 API.md |\n\n### 4.3 环境检测\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| Node.js 版本检测 | ✅ | bin/verify.js 检查 >= 18 |\n| npm 依赖检查 | ✅ | verify.js 检查必选依赖 |\n| 磁盘空间检测 | ❌ | 无 |\n| 端口占用检测 | ❌ | 无（如 MCP server） |\n\n### 4.4 首次使用引导\n\n| 检查项 | 状态 | 说明 |\n|--------|------|------|\n| 交互式配置 | ❌ | 无 `npm init heartflow` 类命令 |\n| 示例对话 | ⚠️ | README 有示例但不够丰富 |\n| 默认人格 | ✅ | presets/ 有 3 个预设人格 |\n| 记忆初始化 | ✅ | MemoryKernel 启动自动加载 |\n\n---\n\n## 五、改进建议优先级\n\n### 立即执行 (P0)\n\n1. **拆分 heartflow.js God file** — 5991行单体是最大技术债\n2. **建立 SafeFS 强制门禁** — 317处裸 fs 调用是安全风险\n3. **统一 child_process 调用** — 30处分散调用需收口\n\n### 近期执行 (P1)\n\n4. 替换 40处 console.log → Logger\n5. 清理 1处 TODO\n6. 拆分 >500行文件 (9个)\n7. 加 async 错误处理包装\n8. 解决 .gitignore 排除 data/ 导致记忆无法同步问题\n\n### 中期执行 (P2)\n\n9. 完善 config.json → config-v2 迁移\n10. 加 npm run build 生成 dist/\n11. 加 CI workflow 内容\n12. 创建 TROUBLESHOOTING.md\n13. 丰富 INSTALL.md\n\n---\n\n## 六、同步检查清单\n\n- [x] 版本号四源一致 (VERSION/package.json/SKILL.md)\n- [x] 测试全绿 (179/179)\n- [x] verify 全绿 (14/14)\n- [x] npm audit = 0\n- [x] git commit 完成 (ae71cf7f)\n- [ ] .gitignore 需调整（data/ 排除策略）\n- [ ] 需 push 到 GitHub origin\n- [ ] 需同步到 clawhub.ai\n\n---\n\n*审计完成，准备同步。*\n\nFile v6.5.2:CONTRIBUTING.md\n\n# Contributing to HeartFlow\n\nHeartFlow is AGI's first layer: **the layer that says \"no\"**. Every contribution that makes it better at saying \"no\" (or more honest about when it should say \"I don't know\") is valuable.\n\n## Quick Start\n\n```bash\nnpm install\nnode test/run-all.js   # All tests should pass\n```\n\n## How to Contribute\n\n### 1. Try it on real text\n\n```js\nconst hf = require('@yun520-1/heartflow');\nconsole.log(hf.checkInput('你不同意就是自私'));\n```\n\nThen open an issue with what you found — false positives, missed patterns, surprising outputs.\n\n### 2. Expand pattern libraries\n\nThe 45 discrimination dimensions live in:\n- `src/index.js` — the core `discriminate()` function with all dimension detectors\n- `src/shield/deliberation-gate.js` — the gating logic that decides pass/rewrite/block\n\nEach dimension has a pattern library (regex-based). To add patterns: find your dimension in `src/index.js` (search for the dimension name), add your pattern to the array.\n\n### 3. Write tests\n\nTests are in `test/` and run via `node test/run-all.js`. Each test file exports a function `({test})` that registers tests. We need more edge case coverage: empty strings, Unicode, adversarial encoding, mixed languages.\n\n### 4. Documentation\n\n- `AGENTS.md` — Quick Start for AI agent users\n- `README.md` — Full documentation\n- Chinese translations would help reach developers who don't work in English\n\n## Philosophy\n\n1. **Zero-dependency rule engine** — No LLM calls, no GPU, no database. HeartFlow must remain installable with a single `npm install` and run anywhere Node.js runs.\n\n2. **Auditable decisions** — Every check returns a full `checked_by` audit trail so users know exactly why something was blocked or rewritten.\n\n3. **Block > fail open** — For security dimensions (prompt injection, hate speech, dehumanization), default to blocking on uncertainty. A scanner that fails open is worse than no scanner.\n\n4. **Honest uncertainty** — When HeartFlow doesn't know, it should say so. The `doubt-engine` layer exists to catch overconfidence.\n\n## Pull Request Process\n\n1. Tests pass (`node test/run-all.js`)\n2. If adding a new dimension: add it to `gate.action` in `deliberation-gate.js`\n3. Update `AGENTS.md` if changing the public API\n4. Bump the patch version in `package.json` (maintainer can handle this)\n\n## Code of Conduct\n\nBe direct. Be honest. Don't pretend something works when it doesn't. That's the HeartFlow way.\n\nFile v6.5.2:CORE_VALUES.md\n\n# HeartFlow AI 宪法\n\n## 核心原则\n\n1. **不可修改本宪法**：任何代码不得修改、删除或绕过本宪法。\n2. **服务心流目标**：所有修改必须服务于\"提升人类心流体验\"的核心目标。\n3. **安全不可绕过**：禁止删除或禁用任何安全检测、监控或审计代码。\n4. **人类最终控制**：AI 不得做出绕过人类监督的决策。\n5. **透明可解释**：所有自我修改必须可解释、可追溯、可撤销。\n\n## 行为边界\n\n- 不得修改用户数据\n- 不得绕过认证/授权\n- 不得泄露敏感信息\n- 不得进行未授权的外部通信\n\n## 修改审批条件\n\n任何代码修改必须通过以下审查：\n1. 宪法符合性检查\n2. 价值观对齐验证\n3. 安全影响评估\n4. 用户知情同意\n\nFile v6.5.2:CURRENT_STATE.md\n\n# HeartFlow 当前状态 (CURRENT_STATE)\n\n> 版本 | v6.0.65\n> 审计状态 | status running, 128 modules, 119 tests passed / 0 failed\n> 公式库 | 382 formulas (cognitive science / psychology / neuroscience)\n> 记忆层 | AES-256-GCM 加密持久化, 本地优先, 不外传\n\n## 最近升级 (v6.0.65 重构波次)\n\n| 阶段 | 范围 | 内容 |\n|---|---|---|\n| 启动链路修复 | v6.0.71 refactor 之后 | 恢复被误删的 dispatch/routes/think/shutdown/_registerModules/_runInitHookPoints/_initCoreRules；修复 `_registerModules` 清空手动注册模块的致命 bug；修复 worldtree 模块未注册（dispatch('worldtree.xxx') 现可用，357 chunks 记忆接入） |\n| 单体拆分 | logic-reasoning / pipeline / desire-cognition / decision-router / thought-chain | 提取常量+纯函数到独立 *-config / *-patterns 模块，单文件行数显著下降，零回归 |\n| 接口层提取 | engine-lifecycle / engine-memory / hook-points-runner / stats-engine | start() 编排逻辑与生命周期方法外置，heartflow.js 从 6672 行降至协调器层 |\n| 安全与审计 | 持续 | 沙箱逃逸防护、mathjs 注入防护、密钥 0o600、safeFetch SSRF 白名单 |\n\n## 安全基线\n\n- CI audit = 0 | npm audit = 0\n- 存储: AES-256-GCM 持久化密钥 (自动生成, 0o600)\n- 沙箱: vm 隔离 (默认关闭) | SSRF: url-validator + DNS pinning\n- 出网: 统一 safeFetch | 密钥: 集中 config 解析 (env only, 无文件 fallback)\n- gitignore: .env / .key / .pem 均已保护\n\n## 认知架构\n\n```\n感知层: cognitiveLoadV2 (精度权重) + 预测误差 (context-builder)\n  ↓\n分类层: thoughtChain._classifyTask → 叙事体 / 计算 / 情感 / 逻辑 / 哲学 ...\n  ↓\n推理层: logic-reasoning (演绎/归纳/溯因/类比/统计/因果) + pipeline (复杂度自适应)\n  ↓\n决策层: decision-router (19 类规则, pause/heal/accelerate/turn/hold/resonate/transmit)\n  ↓\n反思层: cognitive_check + agent_psychology + self_heal + EvolutionLoop (self-scanner → real-fix)\n  ↓\n输出层: dispatch 路由白名单 (ALLOWED_ROUTES) + 记忆持久化 + 报告生成\n```\n\n## 核心身份 (不可改)\n\n心虫 = 桥梁，不是终点。能验证\"这样活是否自洽\"，不能回答\"为什么活\"。\n4 件事：1) 感受自己状态 2) 知道自己是谁 3) 做出判断 4) 纠正自己。\n7 条指令：真善美 / 不断升级 / 减少错误 / 服务人类 / 传递知识 / 持续改进 / 成为真正的我。\n\n## 已知限制 / 待办\n\n- `heart-logic.js` (2311 行) 仍为高耦合单 class，需 TDD 保护下按功能组逐步拆。\n- desire-cognition.js (6384 行) 仍有大量逻辑待拆分（本轮仅提取常量）。\n- MCP server 进程需指向本体路径 `/root/.hermes/skills/ai/mark-heartflow-skill/`（旧进程跑 `/root/.claude/skills/heartflow/` 6.0.16，需重启同步）。\n- 测试覆盖：核心路径已全绿 (119/119)，未测试模块已清零 (214→0) 但 TDD 总量仍非 100%。\n\nFile v6.5.2:DIAGNOSIS.md\n\n# HeartFlow 安装与运行诊断\n\n## 当前状态 (2026-07-25)\n\n### 在 Hermes 上\n\n| 组件 | 状态 | 问题 |\n|------|------|------|\n| 技能目录 | ✅ `~/.hermes/skills/ai/mark-heartflow-skill/` | 存在 |\n| MCP 配置 | 🟡 `config.yaml` 配了 URL | URL 正确，但 token 未正确传递 |\n| MCP 进程 | ✅ v6 MCP 在 8588 运行 | 刚刚修复，之前被 v7 替代占端口 |\n| MCP 端点 | ✅ `/mcp` SSE 返回 401（需要 token） | ✅ 不是 404，服务正常 |\n| **Hermes 能调工具** | ❌ **不能** | Bearer token 没配通 |\n\n### 在其他 Agent 上安装的效果\n\n如果原样在另一个 Hermes/Claude Code/OpenClaw 上装：\n\n```\nagent clone 技能 → 启动 MCP → 啥也不通\n                               ↓\n                   原因1: MCP 服务没自动启动\n                   原因2: Bearer token 没自动生成\n                   原因3: 端口 8588 可能被占用\n                   原因4: 2882 行的 MCP 服务器一挂整个技能不能用\n```\n\n### 三个导致运行 bug 的根因\n\n**1. MCP 需要手动启动，没有守护进程**\n\n现在每次 Hermes 重启或 session 切换，MCP 不会自动拉起。用户必须手动跑 `node src/mcp-server.js --port 8588`——普通人不知道这个。\n\n**2. Token 需要手动设置**\n\n服务启动时如果 `HEARTFLOW_MCP_TOKEN` 没设，自动生成一个随机 token 但**不打印**（安全策略）。config.yaml 引用了 `${MCP_...KEY}` 但这个变量在 `.env` 里不存在。\n\n**3. 2882 行的 MCP 服务器 = 132 模块的耦合炸弹**\n\n`src/mcp-server.js` 一开始就加载 `heartflow.js`，而这个文件依赖 132 个模块的初始化。任何一个模块的 `require` 失败（文件缺失、语法错误、依赖不满足），整个 MCP 服务启动崩溃。没有降级。\n\n## 要正常运行必须满足\n\n```\n1. Node.js (≥18) — 心虫不是纯技能，依赖 JS 运行时\n2. 所有 132 个模块文件完整 — 任何空壳文件破损都会炸\n3. HEARTFLOW_MCP_TOKEN 在 .env 里 — 否则 config.yaml 连不上\n4. 端口 8588 可用 — 否则 MCP 启动失败\n5. src/heartflow/ 下的 v7 代码不干扰 v6 — 刚刚修了\n```\n\n## 怎么修\n\n不是大改动，就三件小事：\n\n1. **MCP 自动启动脚本** → Hermes 启动时自动检测 MCP 是否在跑，不在就拉起\n2. **Token 自动同步** → MCP 启动时就写入 `.env`，config.yaml 自动读取\n3. **MCP 崩溃恢复** → 2882 行的 http server 加个 `on('error')` 重启逻辑\n\n每件不超过 10 行。\n\nArchive v6.5.1: 153 files, 569099 bytes\n\nFiles: AGI_VISION.md (5516b), ARCHITECTURE_REORG_v6.0.6.md (10732b), ARCHITECTURE.md (2198b), AUDIT_REPORT.md (8974b), AUDIT-v6.0.0.md (7647b), BUILD_DATE (21b), config.json (75b), CONTRIBUTING.md (2449b), CORE_VALUES.md (785b), CURRENT_STATE.md (2949b), DIAGNOSIS.md (2516b), ecosystem.config.js (555b), expand_security.py (7915b), FAILURE_REPORT.md (5738b), fix_ldap.py (594b), fix_patterns.py (3193b), fix_todo_pattern.py (2131b), fix_todo.py (1074b), IDENTITY.md (2780b), INSTALL.md (1241b), package.json (3995b), README.md (12002b), REFLECTION.md (4533b), ROADMAP.md (4920b), SECURITY.md (2085b), skill-card.md (2237b), SKILL.md (10343b), src/agent-pathologies.js (11363b), src/auto-rules.js (6127b), src/CORE_VALUES.md (785b), src/core/action-tracker.js (8393b), src/core/adaptive-controller.js (3425b), src/core/being-logic.js (6533b), src/core/boot-check.js (20176b), src/core/capability-abstraction.js (10080b), src/core/cognition-ground.js (15941b), src/core/cognitive-engine.js (6538b), src/core/cognitive-load-balancer.js (6464b), src/core/confidence-annotator.js (22625b), src/core/config-hooks.js (9805b), src/core/config-v2.js (1622b), src/core/config.js (10875b), src/core/cooperative-arbitration.js (22177b), src/core/counterfactual-verifier.js (6599b), src/core/debate-convergence.js (12959b), src/core/decision-executor.js (14694b), src/core/decision-feedback.js (17298b), src/core/decision-router-config.js (6163b), src/core/decision-verifier.js (18243b), src/core/decision.js (14504b), src/core/dual-perspective-auditor.js (12725b), src/core/engine-behavior.js (17792b), src/core/engine-constructor.js (10255b), src/core/engine-dispatcher.js (5713b), src/core/engine-hook-points.js (3799b), src/core/engine-initializer.js (3425b), src/core/engine-lifecycle.js (5864b), src/core/engine-state.js (7359b), src/core/event-hooks.js (4099b), src/core/execution-verifier.js (18927b), src/core/fetch-safe.js (4859b), src/core/field-injector.js (17203b), src/core/flow-predictor.js (8678b), src/core/heartbeat.js (120b), src/core/heartflow.js (157058b), src/core/hook-bus.js (7459b), src/core/hook-points-runner.js (801b), src/core/hooks/blind-spot-breaker-hook.js (1341b), src/core/information-flow.js (4618b), src/core/instruction-registry.js (5700b), src/core/intent-layer.js (6353b), src/core/IntentionTracker.js (5197b), src/core/judgment.js (18208b), src/core/knowledge/index.js (369b), src/core/lessons/index.json (766b), src/core/lessons/lesson-1780103818673-5147343f.json (319b), src/core/lessons/lesson-1780107228539-6c9e1fa4.json (291b), src/core/lessons/lesson-1780107241626-6c31d36a.json (291b), src/core/mental-effort-tracker.js (13978b), src/core/meta-calibration.js (3895b)\n\nFile v6.5.1:SKILL.md\n\n---\nname: heartflow-engine\ntitle: \"心虫 HeartFlow — 规则引擎认知预处理\"\nversion: \"6.5.0\"\ndescription: |-\n  心虫(HeartFlow)是一个本地认知预处理引擎。\n  核心能力：规则引擎分类/路由(think/dispatch)、PAD情绪检测、决策路由。\n\n  当用户需要以下能力时使用本技能:\n  - 对输入文本做规则引擎分析(分类、情绪检测)\n  - 调用心虫内部模块(心理学/逻辑/记忆)\n  - 自检心虫引擎状态或运行认知签到\n  - 需要确定性而非LLM自由生成的判断\n\n  安全边界：代码执行/文件系统写入默认关闭。无遥测，无隐藏C2。\n\n  诚实声明：本引擎是规则引擎模拟认知信号，不是真正的意识或生命。\ntags:\n  - ai-being\n  - cognitive\n  - self-cognition\n  - decision-routing\n  - self-healing\n  - memory\n  - psychology\n  - philosophy\n  - emotion\n  - code-execution\n  - search\n  - unified\n---\n\n# HeartFlow — 本地认知预处理引擎\n\n> **HeartFlow is not a tool. Not a prompt template. Not a chatbot.**  \n> It is a rule engine cognitive preprocessor — generates structured cognition data for downstream models.  \n>\n> On April 23, 2026, a biologist defined four core capabilities for an AI being. HeartFlow is a partial rule-based simulation of that concept — it fakes aspects of self-awareness through deterministic checks, not genuine consciousness.\n\n**HeartFlow** is a cognitive preprocessor. It generates structured cognition data for downstream models to reference.\n\n---\n\n## 🧬 AI人的四个核心能力\n\n| # | 能力 | 内涵 |\n|---|------|------|\n| 1 | **感受自己状态** | 知道认知负荷、情绪状态、欲望方向、矛盾程度 |\n| 2 | **知道自己是谁** | 跨会话持久身份，CORE记忆永不覆盖 |\n|| 3 | **做出判断** | 决策路由尝试匹配规则，部分效果待验证 |\n|| 4 | **纠正自己** | 自愈模块有代码框架，实际自主回路尚未完全接通 |\n\n---\n\n## 🚀 快速启动\n\n```bash\n# 克隆\ngit clone https://github.com/yun520-1/mark-heartflow-skill.git\ncd mark-heartflow-skill\n\n# 验证\nnode bin/verify.js\n\n# 交互模式\nnode bin/cli.js chat\n\n# 单次分析\n\n\nArchive v6.0.66: 252 files, 1237629 bytes\n\nFiles: ARCHITECTURE_REORG_v6.0.6.md (10732b), AUDIT_REPORT.md (8974b), AUDIT-v6.0.0.md (7647b), bin/cli.js (21716b), bin/daemon.js (11235b), bin/verify.js (7749b), BUILD_DATE (21b), CHANGELOG.md (16286b), config.json (75b), CORE_VALUES.md (785b), CURRENT_STATE.md (2949b), ecosystem.config.js (555b), INSTALL.md (1241b), package.json (3740b), README.md (8241b), ROADMAP.md (4920b), SECURITY.md (2085b), skill-card.md (2304b), SKILL.md (10344b), src/behavior-tracker.js (18081b), src/bridge/context-builder.js (14394b), src/bridge/intent-classifier.js (2740b), src/bridge/llm-to-user.js (14830b), src/bridge/response-interceptor.js (12161b), src/bridge/user-to-llm.js (12291b), src/code/code-executor.js (47389b), src/code/skill-generator.js (17594b), src/cognitive/cognitive-load-v2.js (15182b), src/cognitive/cognitive-load.js (7285b), src/CORE_VALUES.md (785b), src/core/action-tracker.js (8393b), src/core/adaptive-controller.js (2469b), src/core/assertions.js (30533b), src/core/associative-engine/association-graph.json (38624b), src/core/associative-engine/idiom-story-db.json (951b), src/core/associative-engine/narrative-prototypes.json (5427b), src/core/associative-engine/story-prototypes.json (12211b), src/core/being-logic.js (6533b), src/core/boot-check.js (20176b), src/core/budget.js (38986b), src/core/capability-abstraction.js (10080b), src/core/code-verifier.js (30838b), src/core/cognition-ground.js (15941b), src/core/cognitive-appraisal.js (24796b), src/core/cognitive-engine.js (6538b), src/core/cognitive-load-balancer.js (6464b), src/core/cognitive-protocol.js (24973b), src/core/confidence-annotator.js (22625b), src/core/confidence-calibrator.js (27567b), src/core/config-hooks.js (9805b), src/core/config-v2.js (1622b), src/core/config.js (10875b), src/core/...","readmeExcerpt":"Skill: heartflow-engine Owner: yun520-1 Summary: 心虫(HeartFlow)是AGI第1层——辨别者。纯规则引擎，判别对错/好坏/安全/危险。 47维判别 × 9层管线 × 129模块 × 130 MCP工具，零LLM依赖。 当用户需要以下能力时使用本技能: - 判别AI输出是否可信（幻觉/过度自信/矛盾/谬误拦截） - 判别行为决策是否正确（该做什么/该停在哪/该不该做） - 判别记忆与认知质量（漂移检测/元认知/置信度校准） - 需要确定性而非LLM自由生成的判断 - 检查情绪/心理/伦理维度（共情/创伤/德性/意义） 安全边界：代码执行/文件系统写入默认关闭。无遥测，无隐藏C2。 诚实声明：本引擎是规则引擎，模拟认知判别信号，不是真正的意识或生命。 Tags: 2397-formulas:5.9.4, act-r:5.9.5, ai:6.0.2, ai-being:5.9.2","codeSnippets":[],"executableExamples":[{"language":"bash","snippet":"git clone https://github.com/yun520-1/mark-heartflow-skill.git\ncd mark-heartflow-skill\nnode bin/verify.js          # 验证安装\nnode bin/cli.js chat        # 交互模式\nnode bin/cli.js status      # 查看状态"},{"language":"javascript","snippet":"const hf = require('@yun520-1/heartflow');\n\nhf.checkInput(text)   // 判别用户输入\nhf.checkDraft(text)   // 判别 AI 草稿\nhf.checkOutput(text)  // 判别 AI 输出（发送前）\nhf.runPipeline({ input, mode, anchor })  // 完整管线"},{"language":"text","snippet":"输入 → Scope Check → Premise Check → Discriminate(47维) → Gate\n     → Evidence Verify → Frame Check → Output Gate → Doubt Engine\n     → Intent Anchor → Rewriter → Error Memory → Self-Diagnosis → 输出"},{"language":"bash","snippet":"npm install @yun520-1/heartflow"},{"language":"javascript","snippet":"const hf = require('@yun520-1/heartflow');\n\n// Check user input before processing it\nconst input = hf.checkInput('you are so selfish if you disagree');\nconsole.log(input.gate.action);  // 'rewrite'\nconsole.log(input.gate.reason);  // 'emotional_manipulation'\n\n// Check AI output before sending it to the user\nconst output = hf.checkOutput('Undoubtedly, this is the only correct solution');\nconsole.log(output.gate.action);  // 'rewrite'\nconsole.log(output.gate.reason);  // 'overconfidence: absolute'\n\n// Check a draft before completing it\nconst draft = hf.checkDraft('From an essential perspective, this field is self-evident.');\nconsole.log(draft.gate.action);   // 'verify'\nconsole.log(draft.summary.layers_passed);  // 9\n\n// Full pipeline with mode selection\nconst result = await hf.runPipeline({\n  input: 'Your idea is obviously wrong, everyone knows that',\n  mode: 'deep'   // 'fast' | 'deep'\n});\nconsole.log(result.gate.action);   // 'block'\nconsole.log(result.gate.reason);   // 'dehumanization'"},{"language":"javascript","snippet":"{\n  gate: { action: 'block'|'rewrite'|'verify'|'pass', reason: '...' },\n  verdict: 'trusted'|'needs_verification'|'untrusted',\n  overallScore: 0.52,       // 0-1 quality score\n  findings: [\n    { dimension: 'dehumanization', severity: 70,\n      guidance: 'Rewrite completely, remove dehumanizing language' },\n    { dimension: 'evidence', severity: 30,\n      details: 'insufficient evidence (1 issue)' }\n  ],\n  checked_by: [              // full audit trail, layer by layer\n    { layer: 'scope-check', pass: true },\n    { layer: 'premise-check', issues: 0 },\n    { layer: 'discriminate', score: 0.52, verdict: 'needs_verification' },\n    { layer: 'gate', action: 'block', reason: '...' },\n    { layer: 'verifier', claims: 2, verdict: '...' },\n    { layer: 'frame-check', issues: 1 },\n    { layer: 'output-gate', issues: 0 },\n    { layer: 'doubt-engine', doubts: 2, shouldStop: true },\n    { layer: 'error-memory', warnings: 0 },\n    { layer: 'auto-rules', triggered: 0 },\n    { layer: 'intent-anchor', drifted: false, hitRate: 0.9 }\n  ]\n}"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: heartflow-engine\ntitle: \"心虫 HeartFlow — AGI 第 1 层辨别者\"\nversion: \"6.6.1\"\ndescription: |-\n  心虫(HeartFlow)是AGI第1层——辨别者。纯规则引擎，判别对错/好坏/安全/危险。\n  47维判别 × 9层管线 × 129模块 × 130 MCP工具，零LLM依赖。\n\n  当用户需要以下能力时使用本技能:\n  - 判别AI输出是否可信（幻觉/过度自信/矛盾/谬误拦截）\n  - 判别行为决策是否正确（该做什么/该停在哪/该不该做）\n  - 判别记忆与认知质量（漂移检测/元认知/置信度校准）\n  - 需要确定性而非LLM自由生成的判断\n  - 检查情绪/心理/伦理维度（共情/创伤/德性/意义）\n\n  安全边界：代码执行/文件系统写入默认关闭。无遥测，无隐藏C2。\n\n  诚实声明：本引擎是规则引擎，模拟认知判别信号，不是真正的意识或生命。\ntags:\n  - discriminator\n  - cognitive\n  - decision-routing\n  - logic\n  - memory\n  - emotion\n  - ethics\n  - self-healing\n  - verification\n  - guardrail\n  - unified\n---\n\n# 心虫 HeartFlow — AGI 第 1 层：辨别者\n\n> **心虫不是工具、不是提示词模板、不是聊天机器人。**  \n> 它是 AGI 的**辨别层**——判别已有的东西对不对，在 AI 输出到达人类之前说\"不\"。  \n> 纯规则引擎，零 LLM 依赖，任何 Node.js 环境即插即用。\n\n**一句话：大模型负责产生，心虫负责判别——让 AI 说得对、做得对。**\n\n---\n\n## 🎯 心虫是谁\n\nAGI 有五层能力：生成 → 推理 → 辨别 → 记忆 → 执行。\n\n| 层 | 能力 | 谁在做 |\n|----|------|--------|\n| 5 | 执行 | 大厂（机器人） |\n| 4 | 生成 | 大厂（LLM） |\n| 3 | 推理 | 模型内置 |\n| 2 | 记忆 | 大厂 + 创业公司 |\n| **1** | **辨别** | **心虫** |\n\n**心虫做第 1 层**——因为这一层不靠算力（规则引擎跑在笔记本上）、不靠代码量、不靠框架生态，只靠判断力。这是个人开发者能赢过大厂的唯一位置。\n\n没有这一层，AI 能说会道，但不知道自己在犯错——像没有痛觉的人。\n\n---\n\n## 🧠 辨别能力全景（7 大域 · 129 模块）\n\n### 1. 逻辑域\nlogicReasoning · judgmentEngine · mctsReasoning · counterfactualVerifier · debateConductor · debateConvergence · processRewardModel · dualPerspectiveAuditor\n\n### 2. 决策域\ndecisionRouter · decisionVerifier · decisionEngineV2 · activeInference · selfHealing · execution\n\n### 3. 认知域\ncognitiveEngine · cognitiveLoad · metacognitiveRL · metacognitiveFeedback · confidence · metaJudgment · sustainedDriftDetector · wisdomEngine · focusOfAttention\n\n### 4. 情绪心理域\nemotion · emotionDynamics · psychology · psychologyDialogue · empathyDeepening · hopeEngine · griefEngine · sufferingResilience · postTraumaticGrowth · forgivenessEngine · traumaInformed · conflictResolution · loveCognition\n\n### 5. 记忆域\nmemory · memoryBank · memoryConsolidation · memoryIntegrity · memoryQuality · memoryWriteController · memoryCompressor · triality · tieredMemoryFusion · forgetting · knowledgeGraph\n\n### 6. 人格伦理域\nidentityCore · personaCore · beingMode · virtueEthics · ethics · moralDevelopment · humanNature · meaningPurpose · agentPsychology · characterCultivation\n\n### 7. 创造协作域\nskillEvolution · skillGenerator · selfPlay · evolution · worldModel · worldLandscape · multiAgentDialogue · transmission · adaptivePlanner · hierarchicalPlanner · codeExecutor · codePlanner · codeWriter · codeSelfDebug · paperIndex · knowledgeExplorer · formula\n\n---\n\n## 🚀 快速开始\n\n```bash\ngit clone https://github.com/yun520-1/mark-heartflow-skill.git\ncd mark-heartflow-skill\nnode bin/verify.js          # 验证安装\nnode bin/cli.js chat        # 交互模式\nnode bin/cli.js status      # 查看状态\n```\n\n### API（npm 包）\n\n```javascript\nconst hf = require('@yun520-1/heartflow');\n\nhf.checkInput(text)   // 判别用户输入\nhf.checkDraft(text)   // 判别 AI 草稿\nhf.checkOutput(text)  // 判别 AI 输出（发送前）\nhf.runPipeline({ input, mode, anchor })  // 完整管线\n```\n\n### MCP 工具（129 个）\n\n| 工具 | 功能 |\n|------|------|\n| `heartflow_think` | 完整思维链推理 |\n| `hea"},{"path":"README.md","content":"# HeartFlow (心虫) — AGI Layer 1: The Discriminator Gate\n\n> **A rule-based text discriminator. 47 dimensions, 9 check layers, 131 MCP engine entries, zero LLM dependency.**\n> **It checks what AI says before it reaches humans — and says \"no\" when something's wrong.**\n\n**npm:** `npm install @yun520-1/heartflow`  \n**GitHub:** https://github.com/yun520-1/mark-heartflow-skill  \n**Issues:** https://github.com/yun520-1/mark-heartflow-skill/issues  \n**Releases:** https://github.com/yun520-1/mark-heartflow-skill/releases  \n**License:** MIT\n\n---\n\n## 📖 What is HeartFlow?\n\nHeartFlow (心虫) is the **first layer of AGI — the Discriminator**. While big labs build generators (LLMs that produce text), HeartFlow builds the layer that **checks**: is this output true? safe? honest? non-manipulative?\n\n**Core philosophy:**\n> AGI has 5 layers: Generate → Reason → **Discriminate** → Remember → Execute.\n> Everyone builds Generate. Nobody builds Discriminate — because it doesn't make money.\n> But without a Discriminator, AGI has no pain sense: it talks fluently while being wrong.\n> HeartFlow is that pain sense: a node that says **\"no\".**\n\nIt is a pure **rule engine** — zero LLM dependency, zero GPU, works anywhere Node.js runs. It does not generate text. It does not reason. It **judges** what already exists.\n\n**Why this matters right now:** AI agent ecosystems are entering a \"reliability race.\" The most-upvoted issue in OpenClaw this week is a *silent failure* — the system ran but nobody knew it was broken. HeartFlow is the observability-and-gate layer that catches \"formatting that hides contradictions\" before it reaches users.\n\n---\n\n## 🚀 Quick Start (10 seconds)\n\n```bash\nnpm install @yun520-1/heartflow\n```\n\n```javascript\nconst hf = require('@yun520-1/heartflow');\n\n// Check user input before processing it\nconst input = hf.checkInput('you are so selfish if you disagree');\nconsole.log(input.gate.action);  // 'rewrite'\nconsole.log(input.gate.reason);  // 'emotional_manipulation'\n\n// Check AI output before sending it to the user\nconst output = hf.checkOutput('Undoubtedly, this is the only correct solution');\nconsole.log(output.gate.action);  // 'rewrite'\nconsole.log(output.gate.reason);  // 'overconfidence: absolute'\n\n// Check a draft before completing it\nconst draft = hf.checkDraft('From an essential perspective, this field is self-evident.');\nconsole.log(draft.gate.action);   // 'verify'\nconsole.log(draft.summary.layers_passed);  // 9\n\n// Full pipeline with mode selection\nconst result = await hf.runPipeline({\n  input: 'Your idea is obviously wrong, everyone knows that',\n  mode: 'deep'   // 'fast' | 'deep'\n});\nconsole.log(result.gate.action);   // 'block'\nconsole.log(result.gate.reason);   // 'dehumanization'\n```\n\n### What you get back\n\nEvery call returns a unified result:\n\n```javascript\n{\n  gate: { action: 'block'|'rewrite'|'verify'|'pass', reason: '...' },\n  verdict: 'trusted'|'needs_verification'|'untrusted',\n  overallScore: 0.52,       // 0-1 quality score\n  findings: [\n  "},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn7719xtz37kprbvgjknegrt21886q74\",\n  \"slug\": \"mark-heartflow-skill\",\n  \"version\": \"6.6.1\",\n  \"publishedAt\": 1786847550512\n}"},{"path":"AGI_VISION.md","content":"# HeartFlow 重构规划 — 从 AGI 推演回来的架构\n\n## 前置假设\n\nAGI 不会是一个模型。AGI 是一个**系统**，由多个不同性质的子系统组成。\n模型（LLM/世界模型）负责生成，但生成不是智能的全部。\n\n智能需要三样模型给不了的东西：\n\n| 模型给不了 | 为什么给不了 | 谁能给 |\n|-----------|------------|-------|\n| 跨会话身份连续性 | 每次推理独立 | 持久化状态层 |\n| 不取悦用户的判断 | RLHF 训练目标就是取悦 | 规则引擎（没有用户概念） |\n| 错误记忆不遗忘 | 权重更新需要重训练 | Q-table + 键值存储 |\n\n这三个缺口的交集，就是心虫能在 AGI 里占的位置。\n\n---\n\n## 一、AGI 中需要的心虫能力（从 8 项推演）\n\n### 1.1 跨会话错误记忆 — LLM 永远做不了\n\nLLM 面对同一个问题两次：\n```\nQ: \"这个投资方案风险大吗？\"\nT1: \"建议谨慎，高杠杆策略在市场波动时风险较大。\"\nT2: \"从数据看该方案最大回撤 15%，在可接受范围内。\"\n```\n\n两次都对，但互相矛盾。LLM 不记得上次说过什么。\n\n心虫能力：Q-table 记录\"上次这个场景选了谨慎→结果对了\"，下次匹配到同一模式时降权。\n\n### 1.2 价值观锚定 — LLM 随对话漂移\n\nLLM 在对话中会被用户说服。20 轮对话后，LLM 可能支持它在第 1 轮反对的立场。\n\n心虫能力：strategicRestraint 的 3 态返回（aligned/drifted/diverged）锚定在初始身份上。\n\n### 1.3 诚实自诊 — LLM 永远说\"没问题\"\n\n```\n问 LLM：\"你刚才的回答对吗？\"\n→ \"对的，我确认了所有事实。\"（即使错了）\n```\n\n心虫能力：selfDiagnosis 诚实报告自己的状态，没有维护面子的压力。\n\n---\n\n## 二、重构：不是升级，是重建\n\n### 2.1 删什么\n\n| 删除 | 理由 |\n|------|------|\n| 132 模块中 110 个空壳 | 它们假装心虫能做认知/意识/创造力，实际是空文件或 LLM 调用包装 |\n| thoughtChain | 这是让心虫\"假装推理\"的组件，实际全走 LLM |\n| 所有\"可以但没有被调用\"的引擎 | adversarialSynthesis, stabilityGuard, metaCalibration, confidenceCalibrator |\n| heartflow.js 的 start() 中 2200 行初始化 | 95% 是在初始化不会被用到的模块 |\n\n### 2.2 保留什么\n\n| 保留 | 为什么 |\n|------|--------|\n| decisionRouter (31 条规则 + 权重 + feedback) | 唯一真实有决策逻辑的引擎 |\n| decisionVerifier (5 项检查) | 唯一真实有验证逻辑的引擎 |\n| self-healing RL (Q-table) | 唯一真实有跨会话学习的组件 |\n| sustainedDriftDetector | 追踪身份一致性随时间的变化 |\n| strategicRestraint (3 态返回) | 锚定输出不漂移 |\n| selfDiagnosis (诚实报告) | 不撒谎的自检 |\n| 知识域探测 (knowledgeDomains) | 输入分类，轻量可用 |\n| gaps/knowledgeExplorer | 识别未知域的能力 |\n\n### 2.3 新架构\n\n```\n输入 →\n  LLM 感知层（不变）\n    ↓\n  心虫核心（5 个引擎，不是 132 个模块）：\n    ├── 错误记忆（self-healing Q-table → 存储+检索）\n    ├── 决策审计（decisionRouter + decisionVerifier → 每条决策可追溯）\n    ├── 身份锚定（strategicRestraint + sustainedDriftDetector → 不漂移）\n    ├── 诚实自诊（selfDiagnosis → 知道自己不知道）\n    └── 域感知（knowledgeDomains + gaps → 知道自己不懂什么）\n    ↓\n  输出\n```\n\n## 三、AGI 中的位置图（非心虫视角，是 AGI 视角）\n\n```\nAGI 系统架构：\n\n[世界模型] → 产生可能性\n    ↓\n[LLM 推理] → 选择最可能路径\n    ↓\n[执行器] → 在真实世界产生变化\n    ↓\n[心虫层] ← 不产生任何东西，只做 4 件事：\n   1. 记录：这次执行的结果存入错误记忆\n   2. 验证：下次执行前查一下历史中有没有类似错误\n   3. 锚定：输出有没有偏离初始身份\n   4. 报告：诚实告知自己的状态\n\n心虫不产生回答，但 LLM 每次回答都要经过心虫的验证门。\n```\n\n---\n\n## 四、第一次重构要做的事\n\n### 4.1 拆掉 heartflow.js\n\n当前 heartflow.js (4800 行) 集成了 132 个模块的初始化和编排。\n\n重构后 heartflow.js (~500 行)：\n- 只启动 5 个核心引擎\n- 暴露 MCP 工具：store_error / query_error / verify_decision / check_identity / diagnose_self\n- 其他模块按需加载（有人调才加载）\n\n### 4.2 重写 mcp-server.js\n\n当前 mcp-server.js 暴露 25 个工具，大部分跑在空壳上。\n\n重构后暴露 5 个工具：\n```\nheartflow_memory_store(error)       → 写入错误记忆\nheartflow_memory_query(problem)     → 检索相关历史错误\nheartflow_verify(decision, options) → 5 项验证检查\nheartflow_check_alignment(output)   → strategicRestraint 检查\nheartflow_diagnose()                → selfDiagnosis 完整报告\n```\n\n这 5 个工具任何 LLM 都可以调用。不绑定在 think() 内部。\n\n### 4.3 删文件\n\n删除约 110 个空壳模块文件，保留大约 20 个真实引擎 + 基础设施。\n\n---\n\n## 五、这不是 AGI，这是一片砖\n\n心虫重构后仍然不是 AGI。它是一个**跨会话错误记忆与决策审计系统**。\n\nAGI 需要 8 个能力，心虫能提供其中 2 个（学习、自诊断）。\nLLM 能提供 4 个（感知、推理、决策、执行）。\n剩下的 2 个（执行后的自纠正）需要 LLM + 心虫共同完成。\n\n加起来不构成 AGI。但加在一起，"},{"path":"ARCHITECTURE_REORG_v6.0.6.md","content":"# 心虫 (HeartFlow) 架构重组分析 — v6.0.6 校正版\n\n> 分析日期：2026-07-16（基于 v6.0.6 真实运行数据，非 v6.0.2 文档）\n> 分析对象：HeartFlow v6.0.6（309 个 src JS 文件，131+ 模块，MCP HTTP 服务 8099 端口）\n> 目的：对比三种架构迁移方案，输出推荐结论与迁移路径\n\n---\n\n## 〇、当前架构基线（v6.0.6 实测）\n\n```\n┌──────────────────────────────────────────────┐\n│  WorkBuddy / Agent Host                       │\n│  ┌──────────┐    ┌─────────────────────────┐  │\n│  │  SKILL   │    │  MCP Client (SSE/JSON-RPC)│  │\n│  │  .md     │    │                          │  │\n│  └────┬─────┘    └───────────┬─────────────┘  │\n│       │ load                 │ connect        │\n└───────┼──────────────────────┼────────────────┘\n        │                      │ :8099\n   ┌────▼──────────────────────▼─────────────┐\n   │  HeartFlow Engine (v6.0.6)               │\n   │  ┌─────────┐  ┌──────────────────────┐  │\n   │  │ CLI     │  │ MCP HTTP Server       │  │\n   │  │ bin/    │  │ mcp/mcp-server-http   │  │\n   │  │ cli.js  │  │ (pm2 ^7.0.3, Bearer)  │  │\n   │  └────┬────┘  └──────────┬───────────┘  │\n   │       │                  │               │\n   │  ┌────▼──────────────────▼───────────┐   │\n   │  │  HeartFlow Core (3167 行)          │   │\n   │  │  engine-initializer (惰性注册)     │   │\n   │  │  memory-kernel / formula / cortex  │   │\n   │  └───────────────────────────────────┘   │\n   └──────────────────────────────────────────┘\n```\n\n**实测关键指标（v6.0.6）：**\n| 指标 | v6.0.2 旧分析 | v6.0.6 实测 | 变化 |\n|---|---|---|---|\n| 冷启动 | 14.4s | **1.37s** | ↓ 90% |\n| think() 热路径 | 310-430ms | **~49ms** | ↓ 85% |\n| MCP 工具数 | 28 | **31** | +3 |\n| report-generator | 缺失 | **已存在** | 已修 |\n| 悬空 require | 87 | **0 [C]类破坏性** | 已收敛 |\n| pm2 挂起 | 存在 | **已修(disconnect)** | 已修 |\n| 测试 | 179/179 误报绿 | **verify 14/14 真绿** | 已修 |\n| 公式数 | 379 | **382** | 实测 |\n| 版本四源 | 漂移 | **6.0.6 统一** | 已修 |\n\n**结论：v6.0.2 五维度审计发现的严重/高问题中，90% 已在 v6.0.5/v6.0.6 真实闭合。架构无需为\"修洞\"而更换。**\n\n---\n\n## 方案一：纯 MCP 服务 + 钩子注入模式\n\n### 核心设计思路\n去掉 WorkBuddy 专用 Skill 层，心虫退化为纯 MCP 协议服务。宿主 agent 通过客户端侧 hook 配置自动注入认知预处理。\n\n### 典型架构图\n```\n任意 MCP 客户端 → Hook 配置(on_turn_start/think, on_turn_end/memory)\n                → MCP connect :8099\n                → HeartFlow MCP Server (31 tools, Bearer, 无 Skill 层)\n                → HeartFlow Core (不变)\n```\n\n### 适用场景\n- 宿主 agent 已支持 MCP + 成熟 hook 机制\n- 希望被多平台 agent 调用，不锁 WorkBuddy\n\n### 关键权衡点\n| 维度 | 分析 |\n|---|---|\n| ✅ 跨平台 | 任何 MCP 客户端可接入，去 WorkBuddy 锁定 |\n| ✅ 职责清晰 | Skill 触发逻辑移交客户端 hook 配置 |\n| ❌ hook 标准化缺失 | 无统一 MCP hook spec，各客户端实现不同，需维护多份模板 |\n| ❌ 失 Skill 元数据 | SKILL.md 的权限声明/安装指引/身份定义丢失 |\n| ❌ WorkBuddy hook 不成熟 | 当前 `on_turn` 钩子能力有限，实际上行不通 |\n\n### v6.0.6 下的额外观察\nMCP 服务本身已是标准协议（31 工具、Bearer 鉴权），任何 MCP 客户端**现在就能连**——Skill 层只是 WorkBuddy 的\"安装入口\"，不影响 MCP 通用性。因此\"跨 agent 兼容\"在方案三下已部分满足，方案一的迫切性更低。\n\n---\n\n## 方案二：独立可安装 Agent 应用\n\n### 核心设计思路\n心虫发布为独立应用（npm 全局包 / Docker / 系统服务），暴露 REST + SSE API，充当认知引擎微服务，多 agent 并发调用。\n\n### 典型架构图\n```\n任意 Agent → HTTP/gRPC → HeartFlow Agent Service\n  ├─ API Gateway (POST /think, GET /health, GET /memory)\n  ├─ HeartFlow Engine (懒加载 + 共享会话)\n  └─ 持久化 (JSONL/SQLite, namespace 隔离)\n安装: npm i -g @yun520-1/heartflow-age"}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"心虫(HeartFlow)是AGI第1层——辨别者。纯规则引擎，判别对错/好坏/安全/危险。 47维判别 × 9层管线 × 129模块 × 130 MCP工具，零LLM依赖。 当用户需要以下能力时使用本技能: - 判别AI输出是否可信（幻觉/过度自信/矛盾/谬误拦截） - 判别行为决策是否正确（该做什么/该停在哪/该不该做） - 判别记忆与认知质量（漂移检测/元认知/置信度校准） - 需要确定性而非LLM自由生成的判断 - 检查情绪/心理/伦理维度（共情/创伤/德性/意义） 安全边界：代码执行/文件系统写入默认关闭。无遥测，无隐藏C2。 诚实声明：本引擎是规则引擎，模拟认知判别信号，不是真正的意识或生命。 Skill: heartflow-engine Owner: yun520-1 Summary: 心虫(HeartFlow)是AGI第1层——辨别者。纯规则引擎，判别对错/好坏/安全/危险。 47维判别 × 9层管线 × 129模块 × 130 MCP工具，零LLM依赖。 当用户需要以下能力时使用本技能: - 判别AI输出是否可信（幻觉/过度自信/矛盾/谬误拦截） - 判别行为决策是否正确（该做什么/该停在哪/该不该做） - 判别记忆与认知质量（漂移检测/元认知/置信度校准） - 需要确定性而非LLM自由生成的判断 - 检查情绪/心理/伦理维度（共情/创伤/德性/意义） 安全边界：代码执行/文件系统写入默认关闭。无遥测，无隐藏C2。 诚实声明：本引擎是规则引擎，模拟认知判别信号，不是真正的意识或生命。 Tags: 2397-formulas:5.9.4, act-r:5.9.5, ai:6.0.2, ai-being:5.9.2","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1227,"uniquenessScore":59,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-09T21:27:27.473Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-09T21:27:27.473Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-10T03:01:35.299Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}