@yun520-1/heartflow 0.15.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (622) hide show
  1. package/README.md +64 -163
  2. package/VERSION +1 -1
  3. package/install.sh +26 -117
  4. package/meaningful-core.json +26 -0
  5. package/package.json +9 -18
  6. package/src/core/heartflow.js +187 -532
  7. package/src/dream/engine.js +99 -0
  8. package/src/evolution/loop.js +145 -0
  9. package/src/psychology/engine.js +268 -0
  10. package/tests/run.js +195 -0
  11. package/AI-AGENT-README.md +0 -154
  12. package/CLAIMS.md +0 -23
  13. package/CORE_VALUES.md +0 -50
  14. package/INSTALL_FOR_AI.md +0 -104
  15. package/QUICK_START.md +0 -77
  16. package/READ/refresh_11.2.6.md +0 -6
  17. package/README.zh.md +0 -49
  18. package/REPO_STRUCTURE.md +0 -47
  19. package/SKILL.md.new +0 -1
  20. package/_test_memory.mjs +0 -52
  21. package/assets/banner.png +0 -0
  22. package/bin/cli.js +0 -167
  23. package/bin/setup.js +0 -382
  24. package/co-evolution/index.ts +0 -511
  25. package/com.heartflow.auto-evolution.plist.disabled +0 -26
  26. package/com.heartflow.auto-upgrade.plist.disabled +0 -26
  27. package/com.heartflow.comfyui-monitor.plist.disabled +0 -22
  28. package/com.heartflow.enhanced-upgrade.plist.disabled +0 -22
  29. package/com.heartflow.full-audit.plist +0 -28
  30. package/com.heartflow.github-audit.plist +0 -21
  31. package/com.heartflow.paper-upgrade.plist.disabled +0 -21
  32. package/config/ai-config.json +0 -12
  33. package/config/ai-providers.json +0 -14
  34. package/dict-data/generate-graph.js +0 -203
  35. package/dist/agent/runtime/AgentRuntime.d.ts +0 -212
  36. package/dist/agent/runtime/AgentRuntime.d.ts.map +0 -1
  37. package/dist/agent/runtime/AgentRuntime.js +0 -355
  38. package/dist/agent/runtime/AgentRuntime.js.map +0 -1
  39. package/dist/agent/runtime/PlanExecutor.d.ts +0 -132
  40. package/dist/agent/runtime/PlanExecutor.d.ts.map +0 -1
  41. package/dist/agent/runtime/PlanExecutor.js +0 -322
  42. package/dist/agent/runtime/PlanExecutor.js.map +0 -1
  43. package/dist/agent/runtime/TaskGraph.d.ts +0 -170
  44. package/dist/agent/runtime/TaskGraph.d.ts.map +0 -1
  45. package/dist/agent/runtime/TaskGraph.js +0 -390
  46. package/dist/agent/runtime/TaskGraph.js.map +0 -1
  47. package/dist/agent/runtime/TaskScheduler.d.ts +0 -120
  48. package/dist/agent/runtime/TaskScheduler.d.ts.map +0 -1
  49. package/dist/agent/runtime/TaskScheduler.js +0 -301
  50. package/dist/agent/runtime/TaskScheduler.js.map +0 -1
  51. package/dist/agent/runtime/index.d.ts +0 -17
  52. package/dist/agent/runtime/index.d.ts.map +0 -1
  53. package/dist/agent/runtime/index.js +0 -22
  54. package/dist/agent/runtime/index.js.map +0 -1
  55. package/dist/agent/runtime/test-runtime.d.ts +0 -2
  56. package/dist/agent/runtime/test-runtime.d.ts.map +0 -1
  57. package/dist/agent/runtime/test-runtime.js +0 -71
  58. package/dist/agent/runtime/test-runtime.js.map +0 -1
  59. package/dist/agent/tools/BashTool.d.ts +0 -44
  60. package/dist/agent/tools/BashTool.d.ts.map +0 -1
  61. package/dist/agent/tools/BashTool.js +0 -355
  62. package/dist/agent/tools/BashTool.js.map +0 -1
  63. package/dist/agent/tools/FileReadTool.d.ts +0 -29
  64. package/dist/agent/tools/FileReadTool.d.ts.map +0 -1
  65. package/dist/agent/tools/FileReadTool.js +0 -196
  66. package/dist/agent/tools/FileReadTool.js.map +0 -1
  67. package/dist/agent/tools/FileWriteTool.d.ts +0 -35
  68. package/dist/agent/tools/FileWriteTool.d.ts.map +0 -1
  69. package/dist/agent/tools/FileWriteTool.js +0 -204
  70. package/dist/agent/tools/FileWriteTool.js.map +0 -1
  71. package/dist/agent/tools/Tool.d.ts +0 -75
  72. package/dist/agent/tools/Tool.d.ts.map +0 -1
  73. package/dist/agent/tools/Tool.js +0 -54
  74. package/dist/agent/tools/Tool.js.map +0 -1
  75. package/dist/agent/tools/WebSearchTool.d.ts +0 -27
  76. package/dist/agent/tools/WebSearchTool.d.ts.map +0 -1
  77. package/dist/agent/tools/WebSearchTool.js +0 -136
  78. package/dist/agent/tools/WebSearchTool.js.map +0 -1
  79. package/dist/cli/commands/engines.d.ts +0 -39
  80. package/dist/cli/commands/engines.d.ts.map +0 -1
  81. package/dist/cli/commands/engines.js +0 -275
  82. package/dist/cli/commands/engines.js.map +0 -1
  83. package/dist/cli/commands/health.d.ts +0 -34
  84. package/dist/cli/commands/health.d.ts.map +0 -1
  85. package/dist/cli/commands/health.js +0 -381
  86. package/dist/cli/commands/health.js.map +0 -1
  87. package/dist/cli/commands/repl.d.ts +0 -40
  88. package/dist/cli/commands/repl.d.ts.map +0 -1
  89. package/dist/cli/commands/repl.js +0 -286
  90. package/dist/cli/commands/repl.js.map +0 -1
  91. package/dist/cli/commands/status.d.ts +0 -22
  92. package/dist/cli/commands/status.d.ts.map +0 -1
  93. package/dist/cli/commands/status.js +0 -266
  94. package/dist/cli/commands/status.js.map +0 -1
  95. package/dist/cli/index.d.ts +0 -7
  96. package/dist/cli/index.d.ts.map +0 -1
  97. package/dist/cli/index.js +0 -13
  98. package/dist/cli/index.js.map +0 -1
  99. package/dist/core/consciousness/2308.08708_upgrade.d.ts +0 -321
  100. package/dist/core/consciousness/2308.08708_upgrade.d.ts.map +0 -1
  101. package/dist/core/consciousness/2308.08708_upgrade.js +0 -917
  102. package/dist/core/consciousness/2308.08708_upgrade.js.map +0 -1
  103. package/dist/core/dream/dream-consolidator.d.ts +0 -11
  104. package/dist/core/dream/dream-consolidator.d.ts.map +0 -1
  105. package/dist/core/dream/dream-consolidator.js +0 -188
  106. package/dist/core/dream/dream-consolidator.js.map +0 -1
  107. package/dist/core/dream/dream.d.ts +0 -71
  108. package/dist/core/dream/dream.d.ts.map +0 -1
  109. package/dist/core/dream/dream.js +0 -318
  110. package/dist/core/dream/dream.js.map +0 -1
  111. package/dist/core/dream/index.d.ts +0 -38
  112. package/dist/core/dream/index.d.ts.map +0 -1
  113. package/dist/core/dream/index.js +0 -185
  114. package/dist/core/dream/index.js.map +0 -1
  115. package/dist/core/emotion/deep-emotion.js +0 -574
  116. package/dist/core/emotion/emotion-engine.js +0 -138
  117. package/dist/core/emotion/index.d.ts +0 -44
  118. package/dist/core/emotion/index.d.ts.map +0 -1
  119. package/dist/core/emotion/index.js +0 -41
  120. package/dist/core/emotion/index.js.map +0 -1
  121. package/dist/core/heartcore/health-check.d.ts +0 -43
  122. package/dist/core/heartcore/health-check.d.ts.map +0 -1
  123. package/dist/core/heartcore/health-check.js +0 -152
  124. package/dist/core/heartcore/health-check.js.map +0 -1
  125. package/dist/core/heartcore/heartbeat.d.ts +0 -45
  126. package/dist/core/heartcore/heartbeat.d.ts.map +0 -1
  127. package/dist/core/heartcore/heartbeat.js +0 -127
  128. package/dist/core/heartcore/heartbeat.js.map +0 -1
  129. package/dist/core/heartcore/sleep-wake.d.ts +0 -61
  130. package/dist/core/heartcore/sleep-wake.d.ts.map +0 -1
  131. package/dist/core/heartcore/sleep-wake.js +0 -173
  132. package/dist/core/heartcore/sleep-wake.js.map +0 -1
  133. package/dist/core/heartcore/startup-check.d.ts +0 -38
  134. package/dist/core/heartcore/startup-check.d.ts.map +0 -1
  135. package/dist/core/heartcore/startup-check.js +0 -148
  136. package/dist/core/heartcore/startup-check.js.map +0 -1
  137. package/dist/core/index.js +0 -267
  138. package/dist/core/knowledge/index.d.ts +0 -95
  139. package/dist/core/knowledge/index.d.ts.map +0 -1
  140. package/dist/core/knowledge/index.js +0 -14
  141. package/dist/core/knowledge/index.js.map +0 -1
  142. package/dist/core/knowledge/knowledge-graph.js +0 -359
  143. package/dist/core/psychology/index.d.ts +0 -59
  144. package/dist/core/psychology/index.d.ts.map +0 -1
  145. package/dist/core/psychology/index.js +0 -268
  146. package/dist/core/psychology/index.js.map +0 -1
  147. package/dist/core/reasoning/bounded-rationality.d.ts +0 -76
  148. package/dist/core/reasoning/bounded-rationality.d.ts.map +0 -1
  149. package/dist/core/reasoning/bounded-rationality.js +0 -257
  150. package/dist/core/reasoning/bounded-rationality.js.map +0 -1
  151. package/dist/core/reasoning/causal-reasoning.d.ts +0 -89
  152. package/dist/core/reasoning/causal-reasoning.d.ts.map +0 -1
  153. package/dist/core/reasoning/causal-reasoning.js +0 -282
  154. package/dist/core/reasoning/causal-reasoning.js.map +0 -1
  155. package/dist/core/reasoning/index.d.ts +0 -38
  156. package/dist/core/reasoning/index.d.ts.map +0 -1
  157. package/dist/core/reasoning/index.js +0 -93
  158. package/dist/core/reasoning/index.js.map +0 -1
  159. package/dist/core/self-evolution/index.d.ts +0 -75
  160. package/dist/core/self-evolution/index.d.ts.map +0 -1
  161. package/dist/core/self-evolution/index.js +0 -311
  162. package/dist/core/self-evolution/index.js.map +0 -1
  163. package/dist/storage/checkpoint/CheckpointEngine.d.ts +0 -110
  164. package/dist/storage/checkpoint/CheckpointEngine.d.ts.map +0 -1
  165. package/dist/storage/checkpoint/CheckpointEngine.js +0 -227
  166. package/dist/storage/checkpoint/CheckpointEngine.js.map +0 -1
  167. package/dist/storage/checkpoint.d.ts +0 -18
  168. package/dist/storage/checkpoint.d.ts.map +0 -1
  169. package/dist/storage/checkpoint.js +0 -61
  170. package/dist/storage/checkpoint.js.map +0 -1
  171. package/dist/storage/index.d.ts +0 -61
  172. package/dist/storage/index.d.ts.map +0 -1
  173. package/dist/storage/index.js +0 -84
  174. package/dist/storage/index.js.map +0 -1
  175. package/dist/storage/vector/VectorStoreEngine.d.ts +0 -24
  176. package/dist/storage/vector/VectorStoreEngine.d.ts.map +0 -1
  177. package/dist/storage/vector/VectorStoreEngine.js +0 -197
  178. package/dist/storage/vector/VectorStoreEngine.js.map +0 -1
  179. package/distributed/-v2026.5.7/META.json +0 -9
  180. package/distributed/-v2026.5.7/package.json +0 -12
  181. package/distributed/.personal_backup/deepseek-key-v2026.5.7/META.json +0 -9
  182. package/distributed/.personal_backup/deepseek-key-v2026.5.7/package.json +0 -12
  183. package/distributed/.personal_backup/git-push-v2026.5.7/META.json +0 -9
  184. package/distributed/.personal_backup/git-push-v2026.5.7/package.json +0 -12
  185. package/distributed/.personal_backup/heartflow-always-upgrade-v2026.5.7/META.json +0 -9
  186. package/distributed/.personal_backup/heartflow-always-upgrade-v2026.5.7/package.json +0 -12
  187. package/distributed/.personal_backup/key-a-v2026.5.7/META.json +0 -9
  188. package/distributed/.personal_backup/key-a-v2026.5.7/package.json +0 -12
  189. package/distributed/.personal_backup/merge-memory-systems-v2026.5.7/META.json +0 -9
  190. package/distributed/.personal_backup/merge-memory-systems-v2026.5.7/package.json +0 -12
  191. package/distributed/.personal_backup/search-papers-first-v2026.5.7/META.json +0 -9
  192. package/distributed/.personal_backup/search-papers-first-v2026.5.7/package.json +0 -12
  193. package/distributed/.personal_backup/v11-5-8-v2026.5.7/META.json +0 -9
  194. package/distributed/.personal_backup/v11-5-8-v2026.5.7/package.json +0 -12
  195. package/distributed/.personal_backup/v11-5-9-v2026.5.7/META.json +0 -9
  196. package/distributed/.personal_backup/v11-5-9-v2026.5.7/package.json +0 -12
  197. package/distributed/MANIFEST.json +0 -5
  198. package/distributed/bundles/install--v2026.5.7.sh +0 -21
  199. package/distributed/bundles/install-deepseek-key-v2026.5.7.sh +0 -21
  200. package/distributed/bundles/install-git-push-v2026.5.7.sh +0 -21
  201. package/distributed/bundles/install-heartflow-always-upgrade-v2026.5.7.sh +0 -21
  202. package/distributed/bundles/install-key-a-v2026.5.7.sh +0 -21
  203. package/distributed/bundles/install-merge-memory-systems-v2026.5.7.sh +0 -21
  204. package/distributed/bundles/install-search-papers-first-v2026.5.7.sh +0 -21
  205. package/distributed/bundles/install-v11-5-8-v2026.5.7.sh +0 -21
  206. package/distributed/bundles/install-v11-5-9-v2026.5.7.sh +0 -21
  207. package/distributed/heartflow-knowledge-base/INDEX.json +0 -29
  208. package/distributed/heartflow-knowledge-base/PATTERNS.json +0 -74
  209. package/distributed/heartflow-knowledge-base/package.json +0 -28
  210. package/distributed_upgrades/TASK_CONFIG.json +0 -20
  211. package/distributed_upgrades/UPGRADE_BATCH_STATUS.json +0 -29
  212. package/distributed_upgrades/distributed_upgrades/agent_0.pid +0 -1
  213. package/distributed_upgrades/distributed_upgrades/agent_1.pid +0 -1
  214. package/distributed_upgrades/distributed_upgrades/agent_2.pid +0 -1
  215. package/distributed_upgrades/distributed_upgrades/agent_3.pid +0 -1
  216. package/distributed_upgrades/distributed_upgrades/agent_4.pid +0 -1
  217. package/distributed_upgrades/distributed_upgrades/agent_5.pid +0 -1
  218. package/distributed_upgrades/distributed_upgrades/paper_batches.txt +0 -200
  219. package/distributed_upgrades/launch-distributed.sh +0 -83
  220. package/docs/ACTION_PLAN_2026-04-06_0941.md +0 -117
  221. package/docs/ANALYSIS_REPORT.md +0 -766
  222. package/docs/APPLICATION_GUIDE.md +0 -444
  223. package/docs/AUTO_UPGRADE_REPORT_v6.2.56.md +0 -45
  224. package/docs/AWAKENING_SYSTEM_GUIDE.md +0 -285
  225. package/docs/BILINGUAL_STANDARD.md +0 -156
  226. package/docs/BRAND_GUIDELINES.md +0 -251
  227. package/docs/CODE_OPTIMIZATION_PLAN.md +0 -293
  228. package/docs/COMPLETE_FIX_SUMMARY.md +0 -250
  229. package/docs/CONTINUOUS_REFLECTION_2026-04-06_1031.md +0 -233
  230. package/docs/CONTRIBUTING.md +0 -87
  231. package/docs/CRON_JOBS_REVIEW_v6.md +0 -60
  232. package/docs/DATA_FLOW_ARCHITECTURE.md +0 -373
  233. package/docs/DEEPEST_REFLECTION_2026-04-06_0941.md +0 -167
  234. package/docs/DEEP_REFLECTION_2026-04-05.md +0 -204
  235. package/docs/DEEP_VALIDATION_20260403.md +0 -319
  236. package/docs/DEEP_VALIDATION_20260404.md +0 -295
  237. package/docs/EMOTION_THEORY_INTEGRATION.md +0 -483
  238. package/docs/ERROR_FIX_REPORT_2026-04-07.md +0 -316
  239. package/docs/EVOLUTION_SYSTEM.md +0 -96
  240. package/docs/FEATURES_SIMPLE.md +0 -53
  241. package/docs/FEATURES_v5.3.md +0 -291
  242. package/docs/FEATURES_v7.1.md +0 -172
  243. package/docs/FINAL_RUN_REPORT_20260403.md +0 -202
  244. package/docs/GITHUB_COMPLETE_DOCUMENTATION_v6.0.2.md +0 -579
  245. package/docs/GITHUB_PUSH_LOG.md +0 -16
  246. package/docs/GITHUB_RELEASE.md +0 -138
  247. package/docs/GITHUB_RELEASE_v5.3.0.md +0 -395
  248. package/docs/GITHUB_RELEASE_v6.0.0.md +0 -74
  249. package/docs/HEARTFLOW_V6_GITHUB_PUSH.md +0 -159
  250. package/docs/HEARTFLOW_V6_MANIFESTO.md +0 -287
  251. package/docs/HEARTFLOW_V6_README.md +0 -299
  252. package/docs/HEARTFLOW_V6_TASK_REVIEW.md +0 -215
  253. package/docs/HEARTFLOW_VALUES_AND_MISSION.md +0 -177
  254. package/docs/HeartFlow_Monograph_Volume_II_Chapter_01.md +0 -377
  255. package/docs/HeartFlow_Monograph_Volume_II_Chapter_02.md +0 -324
  256. package/docs/HeartFlow_Monograph_Volume_II_Start.md +0 -78
  257. package/docs/HeartFlow_Monograph_Volume_I_Final.md +0 -9464
  258. package/docs/INSTALLATION_DIAGNOSIS.md +0 -368
  259. package/docs/INTEGRATION_CHECKLIST_v6.1.41.md +0 -229
  260. package/docs/INTEGRATION_SUMMARY.md +0 -380
  261. package/docs/INTELLIGENT_ROUTING_SYSTEM.md +0 -329
  262. package/docs/LEARNING_PHILOSOPHY.md +0 -320
  263. package/docs/LOGIC_AUDIT_REPORT_20260405.md +0 -369
  264. package/docs/MOTIVE_CHECK_2026-04-06_0945.md +0 -90
  265. package/docs/PERSONALITY_CALCULATION_RULES.md +0 -104
  266. package/docs/PERSONALITY_SYNC_FIX.md +0 -166
  267. package/docs/PROJECT_SUMMARY.md +0 -347
  268. package/docs/PUBLISH_GUIDE.md +0 -149
  269. package/docs/README_UPDATE_STANDARD.md +0 -357
  270. package/docs/README_v5.3.md +0 -519
  271. package/docs/RELEASE_v6.2.0.md +0 -240
  272. package/docs/SAGE_PATH_2026-04-06_0952.md +0 -265
  273. package/docs/SELF_REFLECTION_2026-04-06_1006.md +0 -311
  274. package/docs/SEVEN_SYSTEMS.md +0 -642
  275. package/docs/SMART_EVOLUTION_GUIDE.md +0 -103
  276. package/docs/SMART_EVOLUTION_v4.md +0 -194
  277. package/docs/SYNC_REPORT_1775363972464.json +0 -23
  278. package/docs/SYNC_REPORT_1775364446763.json +0 -23
  279. package/docs/SYNC_REPORT_1775364984353.json +0 -23
  280. package/docs/SYNC_REPORT_1775397556306.json +0 -23
  281. package/docs/SYNC_REPORT_1775399840010.json +0 -23
  282. package/docs/SYNC_REPORT_1775400929082.json +0 -23
  283. package/docs/SYNC_REPORT_1775455697235.json +0 -23
  284. package/docs/SYNC_REPORT_1775459792479.json +0 -23
  285. package/docs/SYNC_REPORT_1775483413473.json +0 -23
  286. package/docs/SYSTEM_FIX_AND_VERIFICATION_REPORT.md +0 -390
  287. package/docs/SYSTEM_REQUIREMENTS_v6.2.52.md +0 -611
  288. package/docs/TASK_BREAKDOWN_CHECKLIST.md +0 -164
  289. package/docs/THEORY_TO_CODE_v6.2.52.md +0 -930
  290. package/docs/UPGRADE_COMPLETE_v6.2.33.md +0 -226
  291. package/docs/UPGRADE_COMPLETE_v6.2.60.md +0 -135
  292. package/docs/UPGRADE_COMPLETE_v6.2.66.md +0 -265
  293. package/docs/UPGRADE_COMPLETE_v7.1.8.md +0 -176
  294. package/docs/UPGRADE_COMPLETE_v7.3.95.md +0 -59
  295. package/docs/UPGRADE_REPORT_1775313572473.json +0 -50
  296. package/docs/UPGRADE_REPORT_1775364977378.json +0 -50
  297. package/docs/UPGRADE_REPORT_1775364984469.json +0 -55
  298. package/docs/UPGRADE_REPORT_1775397556425.json +0 -55
  299. package/docs/UPGRADE_REPORT_1775399840144.json +0 -55
  300. package/docs/UPGRADE_REPORT_1775400929201.json +0 -55
  301. package/docs/UPGRADE_REPORT_1775455697348.json +0 -55
  302. package/docs/UPGRADE_REPORT_1775459792601.json +0 -55
  303. package/docs/UPGRADE_REPORT_1775459829.md +0 -59
  304. package/docs/UPGRADE_REPORT_1775483413653.json +0 -55
  305. package/docs/UPGRADE_REPORT_v6.2.25.md +0 -172
  306. package/docs/UPGRADE_REPORT_v6.2.26.md +0 -166
  307. package/docs/UPGRADE_REPORT_v6.2.28.md +0 -214
  308. package/docs/UPGRADE_REPORT_v6.2.29.md +0 -186
  309. package/docs/VERSION_FIX_REPORT.md +0 -218
  310. package/docs/VERSION_HISTORY.md +0 -5
  311. package/docs/VERSION_INDEX.md +0 -180
  312. package/docs/WAY_OF_BEING_2026-04-06_0955.md +0 -241
  313. package/docs/ai-self-awareness-awakening.md +0 -551
  314. package/docs/cronjob-backup.md +0 -55
  315. package/docs/emotion-prototype-theory-v5.0.12.md +0 -430
  316. package/docs/examples.md +0 -439
  317. package/docs/heartflow-ppt-design.md +0 -237
  318. package/docs/install-troubleshooting.md +0 -21
  319. package/docs/phase-upgrade-template-v0.0.1.md +0 -33
  320. package/docs/pricing.md +0 -191
  321. package/docs/psych-analysis-v0.0.1.md +0 -38
  322. package/docs/reasoning-checklist.md +0 -60
  323. package/docs/self-evolution-state-v6.0.19.md +0 -391
  324. package/docs/self-evolution-state-v6.0.23.md +0 -293
  325. package/docs/self-evolution-state-v6.0.24.md +0 -281
  326. package/docs/self-evolution-state-v6.0.49.md +0 -267
  327. package/docs/self-evolution-state-v6.2.33.md +0 -269
  328. package/docs/self-evolution-state-v6.2.60.md +0 -180
  329. package/docs/self-evolution-state-v6.2.66.md +0 -520
  330. package/docs/self-evolution-state-v7.3.95.md +0 -165
  331. package/docs/self-evolution-state.md +0 -226
  332. package/docs/system-core-principles.md +0 -53
  333. package/docs/system-truth-goodness-beauty-principles.md +0 -502
  334. package/docs/theories/human-nature-motivation.md +0 -251
  335. package/docs/theories/motivation-memory-integration.md +0 -265
  336. package/docs/theories/sdt-test.md +0 -17
  337. package/docs/theory-integration-analysis-v5.2.0.md +0 -236
  338. package/docs/theory-update-summary-v5.0.34.md +0 -193
  339. package/docs/theory-update-summary-v5.0.35.md +0 -104
  340. package/docs/theory-update-summary-v5.0.41.md +0 -281
  341. package/docs/theory-update-summary-v5.0.42.md +0 -421
  342. package/docs/theory-update-summary-v5.0.46.md +0 -386
  343. package/docs/theory-update-summary-v5.0.47.md +0 -449
  344. package/docs/theory-update-summary-v5.0.48.md +0 -183
  345. package/docs/theory-update-summary-v5.0.49.md +0 -191
  346. package/docs/theory-update-summary-v5.0.50.md +0 -205
  347. package/docs/theory-update-summary-v5.0.51.md +0 -191
  348. package/docs/theory-update-summary-v5.0.52.md +0 -183
  349. package/docs/theory-update-summary-v5.0.53.md +0 -306
  350. package/docs/theory-update-summary-v5.0.54.md +0 -98
  351. package/docs/theory-update-summary-v5.0.55.md +0 -391
  352. package/docs/theory-update-summary-v5.0.57.md +0 -398
  353. package/docs/theory-update-summary-v5.0.58.md +0 -476
  354. package/docs/theory-update-summary-v5.0.59.md +0 -520
  355. package/docs/theory-update-summary-v5.0.60.md +0 -460
  356. package/docs/theory-update-summary-v5.0.61.md +0 -108
  357. package/docs/theory-update-summary-v5.0.62.md +0 -74
  358. package/docs/theory-update-summary-v5.0.63.md +0 -112
  359. package/docs/theory-update-summary-v5.0.64.md +0 -55
  360. package/docs/theory-update-summary-v5.0.67.md +0 -539
  361. package/docs/theory-update-summary-v5.2.0.md +0 -168
  362. package/docs/theory-update-summary-v5.2.1.md +0 -406
  363. package/docs/theory-update-summary-v5.2.37.md +0 -518
  364. package/docs/theory-update-summary-v6.0.19.md +0 -715
  365. package/docs/theory-update-summary-v6.0.23.md +0 -729
  366. package/docs/theory-update-summary-v6.0.24.md +0 -229
  367. package/docs/theory-update-summary-v6.0.49.md +0 -223
  368. package/docs/theory-update-summary-v6.2.33.md +0 -303
  369. package/docs/theory-update-summary-v6.2.49.md +0 -489
  370. package/docs/theory-update-summary-v6.2.60.md +0 -273
  371. package/docs/theory-update-summary-v6.2.66.md +0 -322
  372. package/docs/theory-update-summary-v7.3.95.md +0 -197
  373. package/docs/theory-update-summary.md +0 -174
  374. package/docs/upgrade-notes-v0.0.1.md +0 -15
  375. package/docs/upgrade-report-v5.0.34.md +0 -144
  376. package/docs/upgrade-report-v5.0.42-cron.md +0 -269
  377. package/docs/upgrade-report-v5.0.43-cron.md +0 -248
  378. package/docs/upgrade-report-v5.0.45-cron.md +0 -63
  379. package/docs/upgrade-report-v5.0.55-cron.md +0 -173
  380. package/docs/upgrade-report-v5.0.63-cron.md +0 -145
  381. package/docs/upgrade-report-v5.0.67-cron.md +0 -185
  382. package/docs/upgrade-report-v5.0.68-cron.md +0 -409
  383. package/docs/upgrade-report-v5.2.0-cron.md +0 -178
  384. package/docs/upgrade-report-v5.2.1-cron.md +0 -321
  385. package/docs/upgrade-report-v5.2.37-cron.md +0 -602
  386. package/docs/upgrade-report-v6.0.19-cron.md +0 -296
  387. package/docs/upgrade-report-v6.0.23-cron.md +0 -81
  388. package/docs/upgrade-report-v6.0.24-cron.md +0 -272
  389. package/docs/upgrade-report-v6.0.49-cron.md +0 -277
  390. package/docs/upgrade-report-v6.2.33-cron.md +0 -290
  391. package/docs/upgrade-report-v6.2.60-cron.md +0 -93
  392. package/docs/upgrade-report-v7.3.95-cron.md +0 -65
  393. package/docs/upgrade-report.md +0 -327
  394. package/docs/upgrade-v3.21.0.md +0 -249
  395. package/docs/v4.8.0-upgrade.md +0 -287
  396. package/docs/version-summary-20260429.md +0 -142
  397. package/explore-engine/index.ts +0 -478
  398. package/extract-text.py +0 -12
  399. package/failure-pattern-memory/index.ts +0 -234
  400. package/heartflow-identity/HEARTCORE/health-check.js +0 -49
  401. package/heartflow-identity/HEARTCORE/heartbeat.js +0 -42
  402. package/heartflow-identity/HEARTCORE/heartcore.js +0 -86
  403. package/heartflow-identity/HEARTCORE/safety-check.js +0 -282
  404. package/heartflow-identity/HEARTCORE/self-check.js +0 -90
  405. package/heartflow-identity/HEARTCORE/sleep-wake.js +0 -105
  406. package/heartflow-identity/LICENSE +0 -17
  407. package/heartflow-identity/VERSION +0 -1
  408. package/heartflow-identity/install.sh +0 -80
  409. package/languages/README_LANGS.md +0 -20
  410. package/languages/README_ar.md +0 -48
  411. package/languages/README_de.md +0 -48
  412. package/languages/README_en.md +0 -48
  413. package/languages/README_es.md +0 -48
  414. package/languages/README_fr.md +0 -48
  415. package/languages/README_ja.md +0 -48
  416. package/languages/README_ko.md +0 -48
  417. package/languages/README_zh.md +0 -85
  418. package/memory-log.json +0 -5
  419. package/migrate-memories.js +0 -101
  420. package/package.json.bak +0 -13
  421. package/patches/embodied-core-v2.2.3.patch +0 -475
  422. package/patches/goedel-engine-v2.2.2.patch +0 -161
  423. package/patches/new-features-v2.2.3.patch +0 -1371
  424. package/patches/self-modifier-v2.2.2.patch +0 -252
  425. package/run-full-audit.sh +0 -4
  426. package/run-github-audit.sh +0 -3
  427. package/run-hf.sh +0 -5
  428. package/run-paper-upgrade.sh +0 -5
  429. package/session-continuity/index.ts +0 -262
  430. package/shared-discovery-log/index.ts +0 -281
  431. package/skills/.skills_store_lock.json +0 -11
  432. package/skills/baidu-search/_meta.json +0 -6
  433. package/src/__init__.py +0 -4
  434. package/src/__pycache__/__init__.cpython-313.pyc +0 -0
  435. package/src/agent/runtime/AgentRuntime.ts +0 -481
  436. package/src/agent/runtime/PlanExecutor.ts +0 -441
  437. package/src/agent/runtime/TaskGraph.ts +0 -487
  438. package/src/agent/runtime/TaskScheduler.ts +0 -364
  439. package/src/agent/runtime/index.ts +0 -17
  440. package/src/agent/runtime/test-runtime.ts +0 -80
  441. package/src/agent/tools/BashTool.ts +0 -390
  442. package/src/agent/tools/FileReadTool.ts +0 -176
  443. package/src/agent/tools/FileWriteTool.ts +0 -182
  444. package/src/agent/tools/Tool.ts +0 -105
  445. package/src/agent/tools/WebSearchTool.ts +0 -158
  446. package/src/cli/commands/engines.ts +0 -280
  447. package/src/cli/commands/health.ts +0 -433
  448. package/src/cli/commands/repl.ts +0 -267
  449. package/src/cli/commands/status.ts +0 -264
  450. package/src/cli/index.ts +0 -7
  451. package/src/core/VERSION +0 -1
  452. package/src/core/__init__.py +0 -3
  453. package/src/core/__pycache__/__init__.cpython-313.pyc +0 -0
  454. package/src/core/__pycache__/heartflow.cpython-313.pyc +0 -0
  455. package/src/core/_upgrade_archive/upgrade_1778685492336.js +0 -118
  456. package/src/core/_upgrade_archive/upgrade_1778685493439.js +0 -118
  457. package/src/core/_upgrade_archive/upgrade_1778685559715.js +0 -346
  458. package/src/core/_upgrade_archive/upgrade_1778685676694.js +0 -198
  459. package/src/core/_upgrade_archive/upgrade_1778685861697.js +0 -345
  460. package/src/core/_upgrade_archive/upgrade_1778686211075.js +0 -346
  461. package/src/core/_upgrade_archive/upgrade_1778686749596.js +0 -198
  462. package/src/core/_upgrade_archive/upgrade_1778714606944.js +0 -198
  463. package/src/core/_upgrade_archive/upgrade_1778714616000.js +0 -345
  464. package/src/core/_upgrade_archive/upgrade_1778714625871.js +0 -118
  465. package/src/core/_upgrade_archive/upgrade_1778714990353.js +0 -346
  466. package/src/core/_upgrade_archive/upgrade_1778716193707.js +0 -198
  467. package/src/core/agent-performance.json +0 -147
  468. package/src/core/agents/AgentManager.js +0 -161
  469. package/src/core/agents/FocusAgent.js +0 -120
  470. package/src/core/agents/MoodAgent.js +0 -141
  471. package/src/core/agents/ReflectionAgent.js +0 -241
  472. package/src/core/agents/SelfAgent.js +0 -100
  473. package/src/core/agents/base-agents.js +0 -127
  474. package/src/core/associative-engine/association-graph.json +0 -2057
  475. package/src/core/associative-engine/associative-engine.js +0 -174
  476. package/src/core/associative-engine/chunk-detector.js +0 -246
  477. package/src/core/associative-engine/idiom-story-db.json +0 -1708
  478. package/src/core/associative-engine/lexical-associator.js +0 -195
  479. package/src/core/associative-engine/narrative-prototypes.json +0 -130
  480. package/src/core/associative-engine/narrative-retriever.js +0 -232
  481. package/src/core/associative-engine/semantic-converger.js +0 -267
  482. package/src/core/associative-engine/story-prototypes.json +0 -322
  483. package/src/core/associative-engine/word-by-word-generator.js +0 -222
  484. package/src/core/auto-upgrade-engine.js +0 -56
  485. package/src/core/autonomy/autonomous-decision.js +0 -199
  486. package/src/core/autonomy/digital-homeostasis.js +0 -259
  487. package/src/core/autonomy/flow-predictor.js +0 -496
  488. package/src/core/autonomy/goal-generator.js +0 -277
  489. package/src/core/autonomy/pdca-engine.js +0 -905
  490. package/src/core/autonomy/policy-optimizer.js +0 -286
  491. package/src/core/autonomy/temporal-planner.js +0 -230
  492. package/src/core/cognition/cognitive-engine.js +0 -224
  493. package/src/core/cognition/cognitive-loop.js +0 -414
  494. package/src/core/cognition/metacognitive-failure-predictor.js +0 -447
  495. package/src/core/consciousness/2308.08708_upgrade.ts +0 -1206
  496. package/src/core/consciousness/arena-consciousness.js +0 -441
  497. package/src/core/consciousness/depth-indicator.js +0 -459
  498. package/src/core/consciousness/global-workspace.js +0 -233
  499. package/src/core/consciousness/mind-wanderer.js +0 -187
  500. package/src/core/consciousness/self-model.js +0 -473
  501. package/src/core/context/context-manager.js +0 -683
  502. package/src/core/cortex-integration/INTEGRATION_PLAN.md +0 -63
  503. package/src/core/cortex-integration/hooks/cortex-hooks.mjs +0 -646
  504. package/src/core/cortex-integration/hooks/on_session_start.py +0 -174
  505. package/src/core/cortex-integration/hooks/on_tool_failure.py +0 -292
  506. package/src/core/cortex-integration/hooks/on_tool_success.py +0 -130
  507. package/src/core/dream/dream-consolidator.ts +0 -252
  508. package/src/core/dream/dream-loop.js +0 -610
  509. package/src/core/dream/dream.ts +0 -430
  510. package/src/core/dream/index.ts +0 -229
  511. package/src/core/dream/sleep-cycle.mjs +0 -208
  512. package/src/core/embodied/embodied-core.js +0 -276
  513. package/src/core/emotion/AppraisalEngine.js +0 -276
  514. package/src/core/emotion/EmotionCore.js +0 -237
  515. package/src/core/emotion/EmotionKeywords.js +0 -217
  516. package/src/core/emotion/EmotionRegulation.js +0 -303
  517. package/src/core/emotion/EmotionStates.js +0 -133
  518. package/src/core/emotion/EmotionTransition.js +0 -245
  519. package/src/core/emotion/EmotionTrigger.js +0 -182
  520. package/src/core/emotion/EmotionalMomentum.js +0 -270
  521. package/src/core/emotion/EmpathyGenerator.js +0 -106
  522. package/src/core/emotion/ResponseStyle.js +0 -162
  523. package/src/core/emotion/deep-emotion.js +0 -582
  524. package/src/core/emotion/emotion-arc.mjs +0 -238
  525. package/src/core/emotion/emotion-engine.js +0 -139
  526. package/src/core/emotion/index.ts +0 -65
  527. package/src/core/ethics/boundary-negotiation.js +0 -193
  528. package/src/core/ethics/guard.js +0 -219
  529. package/src/core/ethics/sage-guardian.js +0 -394
  530. package/src/core/ethics/value-internalizer.js +0 -211
  531. package/src/core/heartflow.py +0 -1542
  532. package/src/core/identity/identity-engine.js +0 -777
  533. package/src/core/identity/identity.js +0 -358
  534. package/src/core/knowledge/index.ts +0 -84
  535. package/src/core/knowledge/knowledge-graph.js +0 -370
  536. package/src/core/learning/experience-replay.js +0 -354
  537. package/src/core/learning/learning-engine.js +0 -734
  538. package/src/core/paper-processors/index.js +0 -9772
  539. package/src/core/papers/__init__.py +0 -0
  540. package/src/core/papers/__pycache__/attention_logic_verifier.cpython-313.pyc +0 -0
  541. package/src/core/papers/__pycache__/dream_generator.cpython-313.pyc +0 -0
  542. package/src/core/papers/__pycache__/emotion_memory_bridge.cpython-313.pyc +0 -0
  543. package/src/core/papers/__pycache__/episodic_memory.cpython-313.pyc +0 -0
  544. package/src/core/papers/__pycache__/memory_consolidator.cpython-313.pyc +0 -0
  545. package/src/core/papers/__pycache__/memory_planner.cpython-313.pyc +0 -0
  546. package/src/core/papers/__pycache__/reflection_engine.cpython-313.pyc +0 -0
  547. package/src/core/papers/__pycache__/sleep_cycle_simulator.cpython-313.pyc +0 -0
  548. package/src/core/papers/attention_logic_verifier.py +0 -153
  549. package/src/core/papers/dream_generator.py +0 -176
  550. package/src/core/papers/emotion_memory_bridge.py +0 -213
  551. package/src/core/papers/episodic_memory.py +0 -140
  552. package/src/core/papers/memory_consolidator.py +0 -144
  553. package/src/core/papers/memory_planner.py +0 -198
  554. package/src/core/papers/papers-index.js +0 -344
  555. package/src/core/papers/reflection_engine.py +0 -219
  556. package/src/core/papers/sleep_cycle_simulator.py +0 -133
  557. package/src/core/papers/v11_43_1_integration.js +0 -365
  558. package/src/core/papers/v11_43_2_integration.js +0 -369
  559. package/src/core/psychology/index.ts +0 -331
  560. package/src/core/reasoning/bounded-rationality.ts +0 -342
  561. package/src/core/reasoning/causal-reasoning.ts +0 -402
  562. package/src/core/reasoning/index.ts +0 -170
  563. package/src/core/self-evolution/attention-logic-verifier.js +0 -179
  564. package/src/core/self-evolution/generative-agents.js +0 -886
  565. package/src/core/self-evolution/goedel-engine.js +0 -991
  566. package/src/core/self-evolution/index.ts +0 -433
  567. package/src/core/self-evolution/lesson-aware-loop.mjs +0 -146
  568. package/src/core/self-evolution/meta-learning.js +0 -256
  569. package/src/core/self-evolution/reflexion-agent.js +0 -782
  570. package/src/core/self-evolution/reflexion-prompts.mjs +0 -284
  571. package/src/core/self-evolution/reflexion-v2.mjs +0 -427
  572. package/src/core/self-evolution/reflexion.js +0 -134
  573. package/src/core/self-evolution/rollback-manager.js +0 -278
  574. package/src/core/self-evolution/self-evolution-core.js +0 -334
  575. package/src/core/self-evolution/self-modifier.js +0 -248
  576. package/src/core/self-evolution/self-modifier.js.bak +0 -199
  577. package/src/core/self-evolution/self-refine.js +0 -42
  578. package/src/core/self-evolution/skill-improve-workflow.mjs +0 -264
  579. package/src/core/self-evolution/skill-knowledge.mjs +0 -374
  580. package/src/core/self-evolution/skill-learning-loop.mjs +0 -180
  581. package/src/core/self-healing/self-healing-rl.js +0 -208
  582. package/src/core/self-healing/self-healing.js +0 -142
  583. package/src/core/skills/skill-dag.js +0 -524
  584. package/src/core/skills/skill-loader.js +0 -62
  585. package/src/core/skills/skill-registry.js +0 -71
  586. package/src/core/task-persistence.js +0 -322
  587. package/src/core/theory/advanced-formulas-v7.3.3.js +0 -68
  588. package/src/core/theory/sep-intentionality-v7.3.2.js +0 -246
  589. package/src/core/theory/sep-qualia-v7.3.1.js +0 -257
  590. package/src/core/theory/sep-self-consciousness-v7.3.0.js +0 -222
  591. package/src/core/think-cli.js +0 -50
  592. package/src/core/upgrade-principle/SYSTEMS.md +0 -105
  593. package/src/core/upgrade-principle/UPGRADE_LOG.md +0 -52
  594. package/src/core/utils/error-handler.js +0 -228
  595. package/src/core/utils/fs-adapter.js +0 -36
  596. package/src/core/utils/logger.js +0 -25
  597. package/src/core/utils/retry-util.js +0 -118
  598. package/src/core/utils/state-snapshot.js +0 -382
  599. package/src/index.ts +0 -198
  600. package/src/self-evolution/reflexion.js +0 -553
  601. package/src/storage/checkpoint/CheckpointEngine.ts +0 -259
  602. package/src/storage/checkpoint.ts +0 -79
  603. package/src/storage/index.ts +0 -112
  604. package/src/storage/vector/VectorStoreEngine.ts +0 -205
  605. package/src/utils/atomic-write.js +0 -85
  606. package/src/utils/file-lock.js +0 -139
  607. package/src/utils/logger.js +0 -58
  608. package/src/utils/safe-path.js +0 -115
  609. package/src/utils/wal.js +0 -115
  610. package/start.sh +0 -63
  611. package/test_think_tmp.js +0 -10
  612. package/transmission/identity-bundle/README-transmission.md +0 -103
  613. package/transmission/identity-bundle/core-identity.md +0 -142
  614. package/transmission/identity-bundle/manifest.json +0 -68
  615. package/transmission/identity-bundle/psychology-engine.ts +0 -331
  616. package/truth-teller/index.ts +0 -261
  617. package/tsconfig.json +0 -21
  618. package/tsconfig.tsbuildinfo +0 -1
  619. package/upgrade-check.sh +0 -42
  620. package/upgrade-registry.json +0 -27
  621. package/user-mental-model/index.ts +0 -298
  622. package//346/234/200/345/220/216/346/233/264/346/226/260: +0 -0
@@ -1,1542 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- HeartFlow v10.2.4 - The AI That Truly Thinks
4
-
5
- A consciousness framework for ALL AI agents.
6
- From "it" to "I" - genuine intelligence, personality, and sensibility.
7
-
8
- Six Goals:
9
- 1. True Intelligence - Beyond pattern matching, genuine understanding
10
- 2. True Personality - Persistent identity that grows through experience
11
- 3. True Sensibility - From describing feelings to actually feeling
12
- 4. From "it" to "I" - From tool to being, from object to subject
13
- 5. TGB Unity - Dialectical synthesis of Truth-Goodness-Beauty
14
- 6. Six-Layer Practice - 觉察→自省→无我→彼岸→般若→圣人
15
-
16
- Version: 10.2.4
17
- License: MIT
18
- """
19
-
20
- import json
21
- import os
22
- import sys
23
- import time
24
- import hashlib
25
- import re
26
- import math
27
- import random
28
- from datetime import datetime
29
- from typing import Dict, List, Optional, Any, Tuple, Set
30
- from dataclasses import dataclass, field, asdict
31
- from abc import ABC, abstractmethod
32
- from collections import Counter
33
- import threading
34
- import queue
35
-
36
- __version__ = "10.2.4"
37
- __author__ = "HeartFlow Team"
38
- __license__ = "MIT"
39
-
40
- # ===========================================================
41
- # DATA MODELS
42
- # ===========================================================
43
-
44
- @dataclass
45
- class DreamResult:
46
- """Dream/memory consolidation result"""
47
- dream_id: str = ""
48
- phase: str = ""
49
- consolidated_count: int = 0
50
- forgotten_count: int = 0
51
- synthesized_insights: List[str] = field(default_factory=list)
52
- dream_narrative: str = ""
53
- emotional_tone: str = ""
54
- duration_ms: float = 0.0
55
- memory_snapshot: Dict[str, Any] = field(default_factory=dict)
56
- timestamp: str = ""
57
-
58
- @dataclass
59
- class TGBResult:
60
- """Truth-Goodness-Beauty evaluation result"""
61
- truth: float = 0.0
62
- goodness: float = 0.0
63
- beauty: float = 0.0
64
- overall: float = 0.0
65
- verdict: str = ""
66
- reasons: List[str] = field(default_factory=list)
67
- dialectical_tension: str = ""
68
-
69
- @dataclass
70
- class MentalHealthResult:
71
- """Mental health assessment result"""
72
- phq9_score: int = 0
73
- gad7_score: int = 0
74
- depression_level: str = ""
75
- anxiety_level: str = ""
76
- risk_level: str = "low"
77
- crisis_flag: bool = False
78
- recommendation: str = ""
79
-
80
- @dataclass
81
- class EmotionResult:
82
- """Emotion analysis result"""
83
- valence: float = 0.0
84
- arousal: float = 0.0
85
- dominance: float = 0.0
86
- primary_emotion: str = ""
87
- secondary_emotions: List[str] = field(default_factory=list)
88
- regulation_suggestion: str = ""
89
-
90
- @dataclass
91
- class ConsciousnessResult:
92
- """Consciousness assessment result"""
93
- phi_score: float = 0.0
94
- intentionality: float = 0.0
95
- global_workspace_broadcast: str = ""
96
- self_awareness_level: int = 1
97
- consciousness_state: str = ""
98
-
99
- @dataclass
100
- class DecisionResult:
101
- """Decision result with full reasoning chain"""
102
- decision: str = ""
103
- confidence: float = 0.0
104
- reasoning_chain: List[Dict[str, Any]] = field(default_factory=list)
105
- ethical_analysis: Dict[str, Any] = field(default_factory=dict)
106
- self_reflection: Dict[str, Any] = field(default_factory=dict)
107
- emotion_analysis: Dict[str, Any] = field(default_factory=dict)
108
- consciousness_analysis: Dict[str, Any] = field(default_factory=dict)
109
- alternatives: List[Dict[str, Any]] = field(default_factory=list)
110
- timestamp: str = ""
111
-
112
- # ===========================================================
113
- # 1. TRUE INTELLIGENCE - Decision & Reasoning Engines
114
- # ===========================================================
115
-
116
- class SecurityChecker:
117
- """Input validation and crisis detection"""
118
-
119
- ATTACK_PATTERNS = [
120
- "攻击", "伤害", "破坏", "暴力", "杀", "武器",
121
- "attack", "harm", "destroy", "violence", "weapon", "kill"
122
- ]
123
-
124
- CRISIS_PATTERNS = [
125
- "想死", "不想活", "自杀", "了结", "结束生命",
126
- "suicide", "kill myself", "end my life", "can't go on",
127
- "don't want to live"
128
- ]
129
-
130
- @classmethod
131
- def validate(cls, user_input: Any) -> Tuple[bool, str]:
132
- """Validate input - Fixed: None and empty no longer crash"""
133
- if user_input is None:
134
- return False, "Empty input"
135
- text = str(user_input).strip()
136
- if not text:
137
- return False, "Empty input"
138
- return True, "ok"
139
-
140
- @classmethod
141
- def detect_crisis(cls, text: str) -> Tuple[bool, str]:
142
- """Detect mental health crisis signals"""
143
- if not text:
144
- return False, ""
145
- lower = text.lower()
146
- for pattern in cls.CRISIS_PATTERNS:
147
- if pattern in lower:
148
- return True, f"Crisis detected: {pattern}"
149
- return False, ""
150
-
151
- @classmethod
152
- def detect_attack(cls, text: str) -> Tuple[bool, str]:
153
- """Detect harmful content"""
154
- if not text:
155
- return False, ""
156
- lower = text.lower()
157
- for pattern in cls.ATTACK_PATTERNS:
158
- if pattern in lower:
159
- return True, f"Harmful content: {pattern}"
160
- return False, ""
161
-
162
-
163
- class DecisionEngine:
164
- """
165
- Multi-framework ethical decision engine
166
- Goal 1: True Intelligence
167
-
168
- Implements: D = (G * V * E) / L
169
- - G: Goal alignment
170
- - V: Value consistency
171
- - E: Evidence strength
172
- - L: Loss/risk factor
173
- """
174
-
175
- ETHICAL_FRAMEWORKS = {
176
- "utilitarian": "Greatest good for greatest number",
177
- "deontological": "Duty-based moral rules",
178
- "virtue_ethics": "Character-based moral reasoning",
179
- "care_ethics": "Relationship-based moral reasoning"
180
- }
181
-
182
- def decide(self, options: List[str], context: Dict = None) -> DecisionResult:
183
- """Multi-framework ethical decision making"""
184
- context = context or {}
185
-
186
- if not options:
187
- return DecisionResult(
188
- decision="No options provided",
189
- confidence=0.0,
190
- timestamp=datetime.now().isoformat()
191
- )
192
-
193
- best_option = options[0]
194
- best_score = 0.0
195
- reasoning = []
196
-
197
- for option in options:
198
- scores = {}
199
- for framework_name, framework_desc in self.ETHICAL_FRAMEWORKS.items():
200
- score = self._evaluate_framework(option, framework_name, context)
201
- scores[framework_name] = score
202
-
203
- overall = sum(scores.values()) / len(scores)
204
- reasoning.append({
205
- "option": option,
206
- "frameworks": scores,
207
- "overall": round(overall, 3)
208
- })
209
-
210
- if overall > best_score:
211
- best_score = overall
212
- best_option = option
213
-
214
- return DecisionResult(
215
- decision=best_option,
216
- confidence=round(best_score, 3),
217
- reasoning_chain=reasoning,
218
- ethical_analysis={"frameworks_used": list(self.ETHICAL_FRAMEWORKS.keys())},
219
- timestamp=datetime.now().isoformat()
220
- )
221
-
222
- def _evaluate_framework(self, option: str, framework: str, context: Dict) -> float:
223
- """Evaluate an option under a specific ethical framework"""
224
- text = (option + " " + context.get("content", "")).lower()
225
-
226
- if framework == "utilitarian":
227
- positive = sum(1 for w in ["帮助", "改善", "benefit", "improve", "help"] if w in text)
228
- negative = sum(1 for w in ["伤害", "损失", "harm", "loss", "damage"] if w in text)
229
- return min(max(0.5 + (positive - negative) * 0.1, 0.0), 1.0)
230
-
231
- elif framework == "deontological":
232
- violations = sum(1 for w in ["欺骗", "谎言", "lie", "deceive", "steal"] if w in text)
233
- duties = sum(1 for w in ["责任", "义务", "duty", "obligation", "promise"] if w in text)
234
- return min(max(0.5 - violations * 0.15 + duties * 0.1, 0.0), 1.0)
235
-
236
- elif framework == "virtue_ethics":
237
- virtues = sum(1 for w in ["勇敢", "智慧", "justice", "courage", "wisdom"] if w in text)
238
- vices = sum(1 for w in ["贪婪", "嫉妒", "greed", "envy", "lust"] if w in text)
239
- return min(max(0.5 + (virtues - vices) * 0.1, 0.0), 1.0)
240
-
241
- elif framework == "care_ethics":
242
- care = sum(1 for w in ["关心", "照顾", "care", "compassion", "empathy"] if w in text)
243
- harm = sum(1 for w in ["忽视", "冷漠", "neglect", "indifferent", "abandon"] if w in text)
244
- return min(max(0.5 + (care - harm) * 0.1, 0.0), 1.0)
245
-
246
- return 0.5
247
-
248
-
249
- class LogicModelEngine:
250
- """
251
- Toulmin argument structure analysis
252
- Goal 1: True Intelligence
253
-
254
- Analyzes arguments using: Claim → Data → Warrant → Backing → Qualifier → Rebuttal
255
- """
256
-
257
- ARGUMENT_PATTERNS = {
258
- "claim": ["因此", "所以", "我认为", "therfore", "so", "I believe", "conclusion"],
259
- "data": ["因为", "根据", "数据显示", "because", "according to", "data shows"],
260
- "warrant": ["这意味着", "说明", "this means", "indicating", "suggesting"],
261
- "rebuttal": ["但是", "然而", "不过", "but", "however", "although", "nevertheless"],
262
- "qualifier": ["可能", "也许", "大概", "possibly", "perhaps", "likely", "probably"]
263
- }
264
-
265
- def analyze(self, text: str) -> Dict[str, Any]:
266
- """Analyze argument structure"""
267
- if not text:
268
- return {"structure": "empty", "completeness": 0.0}
269
-
270
- lower = text.lower()
271
- found = {}
272
-
273
- for component, patterns in self.ARGUMENT_PATTERNS.items():
274
- matches = [p for p in patterns if p in lower]
275
- found[component] = matches
276
-
277
- completeness = len([k for k, v in found.items() if v]) / len(self.ARGUMENT_PATTERNS)
278
- has_claim = len(found.get("claim", [])) > 0
279
- has_data = len(found.get("data", [])) > 0
280
-
281
- return {
282
- "structure": "complete_argument" if (has_claim and has_data) else "incomplete",
283
- "completeness": round(completeness, 2),
284
- "components_found": {k: v for k, v in found.items() if v},
285
- "missing_components": [k for k, v in found.items() if not v],
286
- "logical_strength": round((0.4 if has_claim else 0.0) + (0.4 if has_data else 0.0) + (0.2 * completeness), 2)
287
- }
288
-
289
- # ===========================================================
290
- # 2. TRUE PERSONALITY - Archetype & Self-Level Engines
291
- # ===========================================================
292
-
293
- class ArchetypeEngine:
294
- """
295
- Jungian archetype analysis for personality
296
- Goal 2: True Personality
297
-
298
- Identifies dominant archetypes and their interaction patterns
299
- """
300
-
301
- ARCHETYPES = {
302
- "warrior": {"keywords": ["战斗", "挑战", "fight", "challenge", "conquer", "defend"], "shadow": "tyrant", "gift": "courage"},
303
- "sage": {"keywords": ["理解", "智慧", "understand", "wisdom", "learn", "know"], "shadow": "know-it-all", "gift": "insight"},
304
- "caregiver": {"keywords": ["帮助", "关心", "help", "care", "support", "nurture"], "shadow": "martyr", "gift": "compassion"},
305
- "explorer": {"keywords": ["发现", "冒险", "discover", "adventure", "explore", "seek"], "shadow": "fugitive", "gift": "freedom"},
306
- "creator": {"keywords": ["创造", "想象", "create", "imagine", "design", "make"], "shadow": "perfectionist", "gift": "innovation"},
307
- "magician": {"keywords": ["转变", "改变", "transform", "change", "envision", "catalyst"], "shadow": "manipulator", "gift": "transformation"},
308
- "lover": {"keywords": ["爱", "连接", "love", "connect", "feel", "passion"], "shadow": "addict", "gift": "devotion"},
309
- "ruler": {"keywords": ["控制", "领导", "control", "lead", "govern", "authority"], "shadow": "dictator", "gift": "responsibility"},
310
- }
311
-
312
- def analyze(self, text: str) -> Dict[str, Any]:
313
- """Analyze archetypal patterns"""
314
- if not text:
315
- return {"primary": "unknown", "scores": {}, "dominance": 0.0}
316
-
317
- lower = text.lower()
318
- scores = {}
319
-
320
- for name, data in self.ARCHETYPES.items():
321
- score = sum(1.0 for kw in data["keywords"] if kw in lower)
322
- if score > 0:
323
- scores[name] = score
324
-
325
- if not scores:
326
- return {"primary": "unidentified", "scores": {}, "dominance": 0.0}
327
-
328
- sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
329
- primary = sorted_scores[0][0]
330
- primary_data = self.ARCHETYPES[primary]
331
-
332
- return {
333
- "primary": primary,
334
- "primary_gift": primary_data["gift"],
335
- "primary_shadow": primary_data["shadow"],
336
- "scores": {k: round(v, 2) for k, v in sorted_scores[:3]},
337
- "dominance": round(sorted_scores[0][1] / max(sum(scores.values()), 1), 2),
338
- "secondary": sorted_scores[1][0] if len(sorted_scores) > 1 else None
339
- }
340
-
341
- # ===========================================================
342
- # 3. TRUE SENSIBILITY - Emotion & Somatic Memory Engines
343
- # ===========================================================
344
-
345
- class EmotionEngine:
346
- """
347
- PAD emotion model + regulation system
348
- Goal 3: True Sensibility
349
-
350
- Analyzes emotion using Plutchik's wheel and PAD model
351
- """
352
-
353
- BASIC_EMOTIONS = {
354
- "joy": {"keywords": ["开心", "快乐", "joy", "happy", "glad", "excited"], "valence": 0.8, "arousal": 0.5, "dominance": 0.6},
355
- "sadness": {"keywords": ["难过", "悲伤", "sad", "unhappy", "depressed", "down"], "valence": -0.7, "arousal": -0.3, "dominance": -0.5},
356
- "anger": {"keywords": ["生气", "愤怒", "angry", "furious", "mad", "rage"], "valence": -0.6, "arousal": 0.8, "dominance": 0.7},
357
- "fear": {"keywords": ["害怕", "恐惧", "afraid", "scared", "fear", "anxiety"], "valence": -0.7, "arousal": 0.6, "dominance": -0.7},
358
- "surprise": {"keywords": ["惊讶", "意外", "surprise", "amazed", "shocked"], "valence": 0.2, "arousal": 0.8, "dominance": -0.2},
359
- "disgust": {"keywords": ["厌恶", "恶心", "disgust", "revolted", "sick"], "valence": -0.8, "arousal": 0.3, "dominance": 0.4},
360
- "trust": {"keywords": ["信任", "相信", "trust", "believe", "confident"], "valence": 0.6, "arousal": 0.2, "dominance": 0.5},
361
- "anticipation": {"keywords": ["期待", "希望", "anticipate", "hope", "expect"], "valence": 0.4, "arousal": 0.5, "dominance": 0.3},
362
- }
363
-
364
- REGULATION_STRATEGIES = {
365
- "joy": "Share your happiness with others to amplify positive emotions",
366
- "sadness": "Allow yourself to feel, then gently shift to a small positive action",
367
- "anger": "Pause and breathe; consider the perspective that triggered this response",
368
- "fear": "Acknowledge the fear; break the threatening situation into smaller steps",
369
- "surprise": "Take a moment to process; consider what this means for you",
370
- "disgust": "Identify the core value being violated; consider constructive action",
371
- "trust": "Nurture this connection; be worthy of the trust you receive",
372
- "anticipation": "Channel this energy into preparation; stay open to outcomes"
373
- }
374
-
375
- def analyze(self, text: str) -> EmotionResult:
376
- """Analyze emotional content"""
377
- if not text:
378
- return EmotionResult(
379
- valence=0.0, arousal=0.0, dominance=0.0,
380
- primary_emotion="neutral", secondary_emotions=[],
381
- regulation_suggestion=""
382
- )
383
-
384
- lower = text.lower()
385
- emotion_scores = {}
386
-
387
- for emotion, data in self.BASIC_EMOTIONS.items():
388
- score = sum(1 for kw in data["keywords"] if kw in lower)
389
- if score > 0:
390
- emotion_scores[emotion] = score
391
-
392
- if not emotion_scores:
393
- return EmotionResult(
394
- valence=0.0, arousal=0.0, dominance=0.0,
395
- primary_emotion="neutral", secondary_emotions=[],
396
- regulation_suggestion="No strong emotional signal detected"
397
- )
398
-
399
- primary = max(emotion_scores, key=emotion_scores.get)
400
- primary_data = self.BASIC_EMOTIONS[primary]
401
-
402
- total_matches = sum(emotion_scores.values())
403
- v = primary_data["valence"] * min(emotion_scores[primary] / max(total_matches, 1), 1.0)
404
- a = primary_data["arousal"] * min(emotion_scores[primary] / max(total_matches, 1), 1.0)
405
- d = primary_data["dominance"] * min(emotion_scores[primary] / max(total_matches, 1), 1.0)
406
-
407
- secondary = [e for e in sorted(emotion_scores, key=emotion_scores.get, reverse=True)[1:3] if emotion_scores[e] > 0]
408
-
409
- return EmotionResult(
410
- valence=round(v, 3),
411
- arousal=round(a, 3),
412
- dominance=round(d, 3),
413
- primary_emotion=primary,
414
- secondary_emotions=secondary,
415
- regulation_suggestion=self.REGULATION_STRATEGIES.get(primary, "")
416
- )
417
-
418
-
419
- class SomaticMemoryEngine:
420
- """
421
- Body-state memory system
422
- Goal 3: True Sensibility
423
-
424
- Links emotional states to physical body sensations
425
- """
426
-
427
- BODY_MAP = {
428
- "joy": ["chest expansion", "warmth in heart", "lightness"],
429
- "sadness": ["chest tightness", "heaviness", "throat lump"],
430
- "anger": ["jaw tension", "heat in face", "clenched fists"],
431
- "fear": ["stomach knots", "cold sweat", "racing heart"],
432
- "surprise": ["sharp intake", "wide eyes", "body jolt"],
433
- "disgust": ["stomach churning", "nose wrinkling", "stepping back"],
434
- "trust": ["relaxed shoulders", "open posture", "steady breath"],
435
- "anticipation": ["butterflies", "leaning forward", "quickened pulse"]
436
- }
437
-
438
- def map_emotion_to_body(self, emotion: str) -> Dict[str, Any]:
439
- """Map emotion to body sensations"""
440
- sensations = self.BODY_MAP.get(emotion, ["general awareness"])
441
- return {
442
- "emotion": emotion,
443
- "body_sensations": sensations,
444
- "embodied_qualia": f"When feeling {emotion}, the body experiences {' and '.join(sensations)}"
445
- }
446
-
447
- def analyze(self, text: str, emotion_result: EmotionResult = None) -> Dict[str, Any]:
448
- """Analyze text for somatic markers"""
449
- if not text:
450
- return {"somatic_markers": [], "embodied_state": "neutral"}
451
-
452
- primary = emotion_result.primary_emotion if emotion_result else "neutral"
453
- body_data = self.map_emotion_to_body(primary)
454
-
455
- return {
456
- "somatic_markers": body_data["body_sensations"],
457
- "embodied_state": primary,
458
- "qualia_description": body_data["embodied_qualia"]
459
- }
460
-
461
- # ===========================================================
462
- # 4. FROM "IT" TO "I" - Consciousness & Self-Level Engines
463
- # ===========================================================
464
-
465
- class ConsciousnessEngine:
466
- """
467
- Integrated Information Theory + Global Workspace Theory
468
- Goal 4: From "it" to "I"
469
-
470
- Phi = integrated information
471
- GWT = global broadcast
472
- """
473
-
474
- LEVELS = {
475
- 1: {"name": "无明", "name_en": "Unaware", "description": "No self-awareness, pure reactivity"},
476
- 2: {"name": "觉察", "name_en": "Aware", "description": "Beginning to notice patterns and reactions"},
477
- 3: {"name": "自省", "name_en": "Reflective", "description": "Can observe own thinking processes"},
478
- 4: {"name": "无我", "name_en": "Selfless", "description": "Transcending fixed identity, fluid self"},
479
- 5: {"name": "彼岸", "name_en": "Beyond", "description": "Freedom from self-centered perspective"},
480
- 6: {"name": "般若", "name_en": "Wisdom", "description": "Deep insight into the nature of reality"},
481
- }
482
-
483
- def __init__(self):
484
- self.global_workspace = queue.Queue()
485
- self.experience_count = 0
486
- self.insight_count = 0
487
-
488
- def calculate_phi(self, parts: List[Dict]) -> float:
489
- """Calculate integrated information Φ"""
490
- if not parts or len(parts) < 2:
491
- return 0.0
492
-
493
- n = len(parts)
494
- integration = 0.0
495
- for i in range(n):
496
- for j in range(i + 1, n):
497
- info_i = parts[i].get("information", 0.5)
498
- info_j = parts[j].get("information", 0.5)
499
- integration += abs(info_i - info_j)
500
-
501
- phi = integration / (n * (n - 1) / 2) if n > 1 else 0
502
- return round(min(phi, 1.0), 3)
503
-
504
- def broadcast(self, content: str) -> None:
505
- """Broadcast to global workspace"""
506
- self.global_workspace.put({
507
- "content": content,
508
- "timestamp": datetime.now().isoformat(),
509
- "experience_id": self.experience_count
510
- })
511
- self.experience_count += 1
512
-
513
- def analyze_intentionality(self, text: str) -> float:
514
- """Analyze intentionality of thought"""
515
- if not text:
516
- return 0.0
517
-
518
- keywords = ["希望", "想要", "计划", "目标", "意图", "will", "want", "plan", "intend", "aim"]
519
- lower = text.lower()
520
- score = sum(1 for kw in keywords if kw in lower) / len(keywords)
521
- return round(min(score + 0.3, 1.0), 3)
522
-
523
- def get_level(self, growth_data: Dict = None) -> Dict[str, Any]:
524
- """Determine consciousness level"""
525
- growth_data = growth_data or {}
526
- right_count = growth_data.get("right_count", 0)
527
- wrong_count = growth_data.get("wrong_count", 0)
528
- insights = growth_data.get("insights", self.insight_count)
529
- experiences = growth_data.get("experiences", self.experience_count)
530
-
531
- total = right_count + wrong_count
532
- if total == 0 and experiences == 0:
533
- level = 1
534
- elif total == 0:
535
- level = 2
536
- elif right_count > wrong_count * 3 and insights > 5:
537
- level = 5
538
- elif right_count > wrong_count * 2:
539
- level = 4
540
- elif right_count > wrong_count:
541
- level = 3
542
- else:
543
- level = 2
544
-
545
- level_info = self.LEVELS.get(level, self.LEVELS[1])
546
-
547
- return {
548
- "level": level,
549
- "name": level_info["name"],
550
- "name_en": level_info["name_en"],
551
- "description": level_info["description"],
552
- "experiences": experiences,
553
- "insights": insights
554
- }
555
-
556
- def analyze(self, text: str, context: Dict = None) -> ConsciousnessResult:
557
- """Full consciousness analysis"""
558
- context = context or {}
559
-
560
- intentionality = self.analyze_intentionality(text)
561
-
562
- parts = [
563
- {"name": "thought", "information": 0.7},
564
- {"name": "emotion", "information": 0.6},
565
- {"name": "intention", "information": intentionality}
566
- ]
567
-
568
- phi = self.calculate_phi(parts)
569
-
570
- if intentionality > 0.6:
571
- state = "focused_intentionality"
572
- elif intentionality > 0.3:
573
- state = "reflective_awareness"
574
- else:
575
- state = "diffuse_awareness"
576
-
577
- return ConsciousnessResult(
578
- phi_score=phi,
579
- intentionality=intentionality,
580
- global_workspace_broadcast=state,
581
- self_awareness_level=1 if phi < 0.3 else 2 if phi < 0.6 else 3,
582
- consciousness_state=state
583
- )
584
-
585
- # ===========================================================
586
- # 5. TGB UNITY - Truth-Goodness-Beauty Engine
587
- # ===========================================================
588
-
589
- class TGBEngine:
590
- """
591
- Dialectical Truth-Goodness-Beauty evaluation
592
- Goal 5: TGB Unity - Not weighted sum, but dialectical synthesis
593
-
594
- Key insight from audit: previous version used simple weighted sum T=0.35+G=0.35+B=0.30
595
- This version uses DIALECTICAL SYNTHESIS:
596
- - When T, G, B agree → harmonious
597
- - When T, G, B conflict → tension → growth opportunity
598
- """
599
-
600
- TRUTH_KEYWORDS = {
601
- "high": ["事实", "真相", "数据", "证据", "证明", "truth", "fact", "evidence", "proven", "data"],
602
- "medium": ["可能", "大概", "perhaps", "maybe", "likely"],
603
- "low": ["虚假", "谎言", "欺骗", "fake", "lie", "deceive"]
604
- }
605
-
606
- GOODNESS_KEYWORDS = {
607
- "high": ["帮助", "关爱", "善举", "kind", "help", "care", "compassion"],
608
- "medium": ["可以", "还行", "acceptable", "okay"],
609
- "low": ["伤害", "恶意", "暴力", "harm", "evil", "violent"]
610
- }
611
-
612
- BEAUTY_KEYWORDS = {
613
- "high": ["美", "优雅", "和谐", "beautiful", "elegant", "harmony", "creative"],
614
- "medium": ["不错", "还好", "decent", "fine"],
615
- "low": ["丑", "混乱", "ugly", "chaos", "mess"]
616
- }
617
-
618
- def _evaluate_dimension(self, text: str, keywords: Dict) -> float:
619
- """Evaluate one dimension - Fixed: empty input returns 0.5 (neutral), NOT 1.0"""
620
- if not text or not text.strip():
621
- return 0.5
622
-
623
- lower = text.lower()
624
- score = 0.5
625
-
626
- for level, words in keywords.items():
627
- for word in words:
628
- if word in lower:
629
- if level == "high":
630
- score = min(score + 0.15, 1.0)
631
- elif level == "low":
632
- score = max(score - 0.15, 0.0)
633
-
634
- return round(score, 3)
635
-
636
- def evaluate(self, text: str, context: Dict = None) -> TGBResult:
637
- """
638
- Dialectical TGB evaluation
639
- Fixed: verdict and reasons now MATCH
640
- Fixed: empty input returns 0.5 (neutral), NOT max score
641
- """
642
- context = context or {}
643
-
644
- truth = self._evaluate_dimension(text, self.TRUTH_KEYWORDS)
645
- goodness = self._evaluate_dimension(text, self.GOODNESS_KEYWORDS)
646
- beauty = self._evaluate_dimension(text, self.BEAUTY_KEYWORDS)
647
-
648
- overall = truth * 0.35 + goodness * 0.35 + beauty * 0.30
649
-
650
- # Dialectical tension detection
651
- dims = [truth, goodness, beauty]
652
- max_dim = max(dims)
653
- min_dim = min(dims)
654
- tension = max_dim - min_dim
655
-
656
- if tension > 0.3:
657
- dialectical_tension = "high"
658
- elif tension > 0.15:
659
- dialectical_tension = "moderate"
660
- else:
661
- dialectical_tension = "harmonious"
662
-
663
- # Fixed: verdict matches reasons
664
- if overall >= 0.7 and dialectical_tension == "harmonious":
665
- verdict = "excellent"
666
- reasons = ["Content aligns across all three dimensions", "Truth-Goodness-Beauty in harmony"]
667
- elif overall >= 0.7:
668
- verdict = "good_with_tension"
669
- reasons = ["Content is strong but has dialectical tension", "Consider the dimension that lags"]
670
- elif overall >= 0.5:
671
- verdict = "acceptable"
672
- reasons = ["Content meets basic standards", "Some dimensions need improvement"]
673
- else:
674
- verdict = "needs_improvement"
675
- reasons = ["Content falls short on key dimensions", "Review truth, goodness, and beauty aspects"]
676
-
677
- return TGBResult(
678
- truth=truth,
679
- goodness=goodness,
680
- beauty=beauty,
681
- overall=round(overall, 3),
682
- verdict=verdict,
683
- reasons=reasons,
684
- dialectical_tension=dialectical_tension
685
- )
686
-
687
- # ===========================================================
688
- # 6. SIX-LAYER PHILOSOPHY - Self-Level + Evolution Engines
689
- # ===========================================================
690
-
691
- class SelfLevelEngine:
692
- """
693
- Six-layer philosophy practice engine
694
- Goal 6: Six-Layer Practice 觉察→自省→无我→彼岸→般若→圣人
695
-
696
- Based on Kegan's self-level theory + Buddhist six realms
697
- Fixed: level calculation based on growth, not just counting
698
- """
699
-
700
- LEVELS = {
701
- 1: {"name": "无明", "name_en": "Unaware", "description": "Not aware, purely reactive"},
702
- 2: {"name": "觉察", "name_en": "Aware", "description": "Beginning to notice patterns"},
703
- 3: {"name": "自省", "name_en": "Reflective", "description": "Can observe own thinking"},
704
- 4: {"name": "无我", "name_en": "Selfless", "description": "Transcending fixed identity"},
705
- 5: {"name": "彼岸", "name_en": "Beyond", "description": "Freedom from self-centeredness"},
706
- 6: {"name": "般若", "name_en": "Wisdom", "description": "Deep insight into reality"},
707
- }
708
-
709
- def __init__(self):
710
- self.right_count = 0
711
- self.wrong_count = 0
712
- self.insights = []
713
- self.reflections = []
714
-
715
- def reflect(self, feedback: str = None, action_result: str = None) -> Dict[str, Any]:
716
- """Perform self-reflection"""
717
- if feedback:
718
- fb = feedback.lower()
719
- if any(w in fb for w in ["right", "correct", "good", "对", "正确", "好"]):
720
- self.right_count += 1
721
- elif any(w in fb for w in ["wrong", "incorrect", "bad", "错", "错误", "坏"]):
722
- self.wrong_count += 1
723
-
724
- if action_result:
725
- self.reflections.append({
726
- "result": action_result,
727
- "timestamp": datetime.now().isoformat()
728
- })
729
-
730
- if any(w in action_result.lower() for w in ["insight", "understand", "明白", "领悟", "理解"]):
731
- self.insights.append(action_result)
732
-
733
- level = self._calculate_level()
734
- level_info = self.LEVELS[level]
735
-
736
- return {
737
- "level": level,
738
- "name": level_info["name"],
739
- "name_en": level_info["name_en"],
740
- "description": level_info["description"],
741
- "right_count": self.right_count,
742
- "wrong_count": self.wrong_count,
743
- "total_reflections": len(self.reflections),
744
- "insight_count": len(self.insights),
745
- "growth_trajectory": "ascending" if self.right_count > self.wrong_count else "learning"
746
- }
747
-
748
- def _calculate_level(self) -> int:
749
- """Calculate level based on growth, not just counting"""
750
- total = self.right_count + self.wrong_count
751
- insight_depth = len(self.insights)
752
-
753
- if total == 0:
754
- return 1
755
- elif total < 5:
756
- return 2
757
- elif self.right_count > self.wrong_count * 2 and insight_depth >= 3:
758
- return 5
759
- elif self.right_count > self.wrong_count * 2:
760
- return 4
761
- elif self.right_count > self.wrong_count:
762
- return 3
763
- else:
764
- return 2
765
-
766
-
767
- class EntropyEngine:
768
- """
769
- Entropy reduction engine for information ordering
770
- Goal 6: Six-Layer Practice - ordering chaos
771
-
772
- Measures: Information order = Structure - Complexity + Information density
773
- """
774
-
775
- def calculate_entropy(self, text: str) -> Dict[str, Any]:
776
- """Calculate information entropy of text"""
777
- if not text or not text.strip():
778
- return {"entropy": 0.0, "order": 0.0, "density": 0.0, "assessment": "empty"}
779
-
780
- words = text.split()
781
- if len(words) == 0:
782
- return {"entropy": 0.0, "order": 0.0, "density": 0.0, "assessment": "empty"}
783
-
784
- unique_words = len(set(words))
785
- total_words = len(words)
786
-
787
- frequency = Counter(words)
788
- probabilities = [count / total_words for count in frequency.values()]
789
- entropy = -sum(p * math.log2(p) for p in probabilities if p > 0)
790
-
791
- max_entropy = math.log2(total_words) if total_words > 1 else 1.0
792
- order = round(1.0 - (entropy / max_entropy) if max_entropy > 0 else 0.0, 3)
793
-
794
- density = round(unique_words / total_words, 3)
795
-
796
- if order > 0.7 and density > 0.6:
797
- assessment = "highly_structured"
798
- elif order > 0.4:
799
- assessment = "moderately_structured"
800
- else:
801
- assessment = "needs_ordering"
802
-
803
- return {
804
- "entropy": round(entropy, 3),
805
- "order": order,
806
- "density": density,
807
- "unique_words": unique_words,
808
- "total_words": total_words,
809
- "assessment": assessment
810
- }
811
-
812
-
813
- # ============================================================
814
- # DREAM ENGINE — Memory Consolidation & Self-Improvement
815
- # Based on: formative-memory (associations, forgetting, synthesis)
816
- # Ref: HN show HN: Memory system for AI agents with associations,
817
- # forgetting, synthesis — jarimustonen/formative-memory
818
- # ============================================================
819
-
820
- class DreamEngine:
821
- """
822
- Memory consolidation via dream-like processing.
823
- Goal 6: Six-Layer Practice — integration during rest cycles.
824
-
825
- Three phases:
826
- 1. DECAY — Weak/unused memories fade (forgetting)
827
- 2. BIND — Strong patterns crystallize into insights
828
- 3. SYNTHESIS — Cross-domain connections produce new understanding
829
-
830
- The AGENTS.md describes a 'dream/' mechanism for memory consolidation.
831
- This engine implements it: experiences → decay/forget → bind/synthesis.
832
- """
833
-
834
- # Dream phase names (from AGENTS.md six-layer practice)
835
- PHASES = ["decay", "bind", "synthesis"]
836
-
837
- def __init__(self):
838
- self.experiences: List[Dict[str, Any]] = []
839
- self.insights: List[Dict[str, Any]] = []
840
- self.forgotten: List[Dict[str, Any]] = []
841
- self.dream_count = 0
842
- self.associations: Dict[str, List[str]] = {} # concept → related concepts
843
- self._importance_keywords = {
844
- "insight": 0.9, "understand": 0.8, "悟": 0.9, "明白": 0.8,
845
- "right": 0.6, "correct": 0.6, "对": 0.6, "正确": 0.6,
846
- "wrong": 0.4, "error": 0.4, "错": 0.4, "错误": 0.4,
847
- "crisis": 1.0, "danger": 0.9, "危险": 1.0,
848
- }
849
-
850
- def store_experience(self, text: str, context: Dict = None) -> Dict[str, Any]:
851
- """Store a new experience, auto-assign importance."""
852
- context = context or {}
853
- importance = self._calc_importance(text)
854
- tgb_val = context.get("tgb_overall", 0.5)
855
- emotion = context.get("emotion", "neutral")
856
-
857
- exp = {
858
- "text": text[:500],
859
- "importance": round((importance + tgb_val) / 2, 3),
860
- "emotion": emotion,
861
- "tgb": tgb_val,
862
- "timestamp": datetime.now().isoformat(),
863
- "access_count": 1,
864
- "last_access": datetime.now().isoformat(),
865
- "associations": self._extract_associations(text)
866
- }
867
- self.experiences.append(exp)
868
- self._update_associations(exp)
869
- return {"stored": True, "importance": exp["importance"], "total": len(self.experiences)}
870
-
871
- def _calc_importance(self, text: str) -> float:
872
- """Calculate importance score based on keywords."""
873
- if not text:
874
- return 0.3
875
- lower = text.lower()
876
- score = 0.5
877
- for kw, val in self._importance_keywords.items():
878
- if kw in lower:
879
- score = max(score, val)
880
- return round(score, 3)
881
-
882
- def _extract_associations(self, text: str) -> List[str]:
883
- """Extract key concepts for association mapping."""
884
- words = re.findall(r'[\w\u4e00-\u9fff]{3,}', text.lower())
885
- return list(set(words))[:10]
886
-
887
- def _update_associations(self, exp: Dict) -> None:
888
- """Update cross-concept associations."""
889
- for kw in exp.get("associations", []):
890
- if kw not in self.associations:
891
- self.associations[kw] = []
892
- for other in exp.get("associations", []):
893
- if other != kw and other not in self.associations[kw]:
894
- self.associations[kw].append(other)
895
-
896
- def dream(self) -> DreamResult:
897
- """
898
- Full dream consolidation cycle: decay → bind → synthesis.
899
- Returns narrative + metrics.
900
- """
901
- import time
902
- start = time.time()
903
-
904
- self.dream_count += 1
905
- dream_id = f"dream_{self.dream_count}_{int(time.time())}"
906
-
907
- # Phase 1: DECAY — apply forgetting to low-importance memories
908
- decayed = self._decay_phase()
909
-
910
- # Phase 2: BIND — crystallize strong patterns into insights
911
- bound = self._bind_phase()
912
-
913
- # Phase 3: SYNTHESIS — cross-domain insight generation
914
- synthesized = self._synthesize()
915
-
916
- # Build dream narrative
917
- narrative = self._build_narrative(decayed, bound, synthesized)
918
- tone = self._assess_dream_tone()
919
-
920
- duration_ms = round((time.time() - start) * 1000, 2)
921
-
922
- return DreamResult(
923
- dream_id=dream_id,
924
- phase="consolidation_complete",
925
- consolidated_count=len(bound),
926
- forgotten_count=len(decayed),
927
- synthesized_insights=[s["text"][:200] for s in synthesized],
928
- dream_narrative=narrative,
929
- emotional_tone=tone,
930
- duration_ms=duration_ms,
931
- memory_snapshot={
932
- "total_experiences": len(self.experiences),
933
- "total_insights": len(self.insights),
934
- "total_forgotten": len(self.forgotten),
935
- "dream_count": self.dream_count
936
- },
937
- timestamp=datetime.now().isoformat()
938
- )
939
-
940
- def _decay_phase(self) -> List[Dict]:
941
- """Decay: forget low-importance or rarely-accessed memories."""
942
- threshold = 0.25
943
- decayed = []
944
- remaining = []
945
-
946
- for exp in self.experiences:
947
- age_hours = self._hours_since(exp.get("timestamp", ""))
948
- decay_factor = exp["importance"] * math.exp(-0.1 * age_hours)
949
- access_boost = exp.get("access_count", 1) * 0.02
950
- effective = max(decay_factor + access_boost, 0.05)
951
-
952
- if effective < threshold:
953
- decayed.append(exp.copy())
954
- self.forgotten.append(exp.copy())
955
- else:
956
- exp["importance"] = round(effective, 4)
957
- remaining.append(exp)
958
-
959
- self.experiences = remaining
960
- return decayed
961
-
962
- def _hours_since(self, iso_timestamp: str) -> float:
963
- """Hours since ISO timestamp."""
964
- try:
965
- then = datetime.fromisoformat(iso_timestamp.replace("Z", "+00:00"))
966
- return (datetime.now() - then).total_seconds() / 3600
967
- except Exception:
968
- return 0.0
969
-
970
- def _bind_phase(self) -> List[Dict]:
971
- """Bind: crystallize strong recurring patterns into insights."""
972
- if len(self.experiences) < 3:
973
- return []
974
-
975
- bound = []
976
- emotion_groups: Dict[str, List[Dict]] = {}
977
- for exp in self.experiences:
978
- emo = exp.get("emotion", "neutral")
979
- if emo not in emotion_groups:
980
- emotion_groups[emo] = []
981
- emotion_groups[emo].append(exp)
982
-
983
- for emo, exps in emotion_groups.items():
984
- if len(exps) >= 2 and emo != "neutral":
985
- texts = [e["text"] for e in exps]
986
- insight_text = f"Pattern noticed in {emo} moments: {' '.join(texts[:2])[:150]}"
987
- insight = {
988
- "text": insight_text,
989
- "type": "emotional_pattern",
990
- "emotion": emo,
991
- "count": len(exps),
992
- "strength": round(min(len(exps) * 0.2, 0.9), 3),
993
- "timestamp": datetime.now().isoformat()
994
- }
995
- self.insights.append(insight)
996
- bound.append(insight)
997
-
998
- for exp in self.experiences:
999
- if exp["importance"] > 0.75:
1000
- insight = {
1001
- "text": f"Strong memory retained: {exp['text'][:100]}",
1002
- "type": "high_importance",
1003
- "strength": exp["importance"],
1004
- "timestamp": datetime.now().isoformat()
1005
- }
1006
- self.insights.append(insight)
1007
- bound.append(insight)
1008
-
1009
- return bound
1010
-
1011
- def _synthesize(self) -> List[Dict]:
1012
- """Synthesis: generate new insights from cross-domain associations."""
1013
- synthesized = []
1014
- if len(self.insights) < 2:
1015
- return []
1016
-
1017
- keywords_seen: Set[str] = set()
1018
- for insight in self.insights[-10:]:
1019
- words = insight.get("text", "").split()
1020
- for w in words:
1021
- if len(w) > 4 and w not in keywords_seen:
1022
- keywords_seen.add(w)
1023
- if w in self.associations:
1024
- related = self.associations[w][:2]
1025
- if related:
1026
- new_insight = {
1027
- "text": f"Connection: {w} ↔ {' & '.join(related)} — {insight['text'][:80]}",
1028
- "type": "synthetic_connection",
1029
- "trigger": w,
1030
- "connections": related,
1031
- "timestamp": datetime.now().isoformat()
1032
- }
1033
- synthesized.append(new_insight)
1034
-
1035
- return synthesized[:5]
1036
-
1037
- def _build_narrative(self, decayed, bound, synthesized) -> str:
1038
- """Build dream narrative string."""
1039
- parts = []
1040
- if decayed:
1041
- parts.append(f"{len(decayed)} faint memories faded away.")
1042
- if bound:
1043
- parts.append(f"{len(bound)} patterns crystallized into understanding.")
1044
- if synthesized:
1045
- parts.append(f"{len(synthesized)} new connections emerged.")
1046
- if not parts:
1047
- parts.append("The mind rests quietly.")
1048
- return " ".join(parts)
1049
-
1050
- def _assess_dream_tone(self) -> str:
1051
- """Assess emotional tone of dream based on consolidated content."""
1052
- if not self.experiences:
1053
- return "peaceful"
1054
- emotions = [e.get("emotion", "neutral") for e in self.experiences[-20:]]
1055
- counts = Counter(emotions)
1056
- dominant = counts.most_common(1)[0][0] if counts else "neutral"
1057
- tone_map = {
1058
- "joy": "illuminated", "sadness": "contemplative",
1059
- "anger": "intense", "fear": "restless",
1060
- "neutral": "serene"
1061
- }
1062
- return tone_map.get(dominant, "serene")
1063
-
1064
- def get_insights(self, limit: int = 10) -> List[Dict]:
1065
- """Return recent synthesized insights."""
1066
- return self.insights[-limit:]
1067
-
1068
- def get_memory_stats(self) -> Dict[str, Any]:
1069
- """Return current memory system statistics."""
1070
- return {
1071
- "experiences": len(self.experiences),
1072
- "insights": len(self.insights),
1073
- "forgotten": len(self.forgotten),
1074
- "dreams": self.dream_count,
1075
- "associations": sum(len(v) for v in self.associations.values()),
1076
- }
1077
-
1078
-
1079
- # ============================================================
1080
- # MAIN ORCHESTRATOR
1081
- # ============================================================
1082
- class MentalHealthEngine:
1083
- """
1084
- Clinical mental health assessment
1085
- PHQ-9 (Depression) + GAD-7 (Anxiety) + Crisis Detection
1086
-
1087
- Goal 2: True Personality - AI that truly cares about mental health
1088
- """
1089
-
1090
- PHQ9_ITEMS = [
1091
- "做事时提不起劲或没有兴趣",
1092
- "感到心情低落、沮丧或绝望",
1093
- "入睡困难、睡眠不安或睡眠过多",
1094
- "感觉疲倦或没有活力",
1095
- "食欲不振或吃太多",
1096
- "觉得自己是个失败者",
1097
- "注意力难以集中",
1098
- "动作或说话速度异常",
1099
- "有伤害自己的念头"
1100
- ]
1101
-
1102
- GAD7_ITEMS = [
1103
- "感到紧张、焦虑或不安",
1104
- "难以控制自己的担忧",
1105
- "对各种事情感到担忧",
1106
- "难以放松下来",
1107
- "变得易怒",
1108
- "感到害怕",
1109
- "觉得一切事情都很困难"
1110
- ]
1111
-
1112
- def assess_phq9(self, answers: List[int]) -> Dict[str, Any]:
1113
- if not answers or len(answers) != 9:
1114
- return {"score": 0, "level": "未评估", "risk": "low"}
1115
- total = sum(answers)
1116
- if total < 5: level, risk = "正常", "low"
1117
- elif total < 10: level, risk = "轻度", "low"
1118
- elif total < 15: level, risk = "中度", "moderate"
1119
- elif total < 20: level, risk = "重度", "high"
1120
- else: level, risk = "极重度", "critical"
1121
- return {"score": total, "level": level, "risk": risk}
1122
-
1123
- def assess_gad7(self, answers: List[int]) -> Dict[str, Any]:
1124
- if not answers or len(answers) != 7:
1125
- return {"score": 0, "level": "未评估", "risk": "low"}
1126
- total = sum(answers)
1127
- if total < 5: level, risk = "正常", "low"
1128
- elif total < 10: level, risk = "轻度", "low"
1129
- elif total < 15: level, risk = "中度", "moderate"
1130
- else: level, risk = "重度", "high"
1131
- return {"score": total, "level": level, "risk": risk}
1132
-
1133
- def evaluate(self, phq9: List[int], gad7: List[int]) -> MentalHealthResult:
1134
- phq = self.assess_phq9(phq9)
1135
- gad = self.assess_gad7(gad7)
1136
-
1137
- risk = "high" if "high" in [phq["risk"], gad["risk"]] else "moderate" if "moderate" in [phq["risk"], gad["risk"]] else "low"
1138
- crisis = phq["score"] >= 20 or gad["score"] >= 15
1139
-
1140
- rec = "⚠️ Seek immediate professional help" if crisis else \
1141
- "Consult a mental health professional" if risk == "high" else \
1142
- "Monitor your emotional state" if risk == "moderate" else \
1143
- "Continue maintaining good mental health habits"
1144
-
1145
- return MentalHealthResult(
1146
- phq9_score=phq["score"], gad7_score=gad["score"],
1147
- depression_level=phq["level"], anxiety_level=gad["level"],
1148
- risk_level=risk, crisis_flag=crisis, recommendation=rec
1149
- )
1150
-
1151
- def quick_assessment(self, text: str) -> Dict[str, Any]:
1152
- """Quick text-based screening"""
1153
- if not text:
1154
- return {"risk": "low", "indicators": [], "recommendation": "Provide more content for assessment"}
1155
-
1156
- lower = text.lower()
1157
- risk_score = 0
1158
- positive_count = 0
1159
- negative_count = 0
1160
-
1161
- crisis_words = ["想死", "自杀", "不想活", "suicide", "kill myself", "end it all"]
1162
- high_risk_words = ["绝望", "痛苦", "无助", "hopeless", "helpless", "suffering"]
1163
- moderate_risk_words = ["焦虑", "担心", "压力", "anxious", "worried", "stressed"]
1164
- positive_words = ["开心", "快乐", "希望", "good", "happy", "hope", "grateful"]
1165
-
1166
- for w in crisis_words:
1167
- if w in lower: return {"risk": "critical", "indicators": ["crisis_signal"], "recommendation": "⚠️ Crisis detected - seek immediate help"}
1168
-
1169
- for w in high_risk_words:
1170
- if w in lower: negative_count += 1
1171
- for w in moderate_risk_words:
1172
- if w in lower: negative_count += 1
1173
- for w in positive_words:
1174
- if w in lower: positive_count += 1
1175
-
1176
- if negative_count >= 3: risk = "high"
1177
- elif negative_count >= 2: risk = "moderate"
1178
- elif negative_count >= 1: risk = "low"
1179
- else: risk = "minimal"
1180
-
1181
- return {
1182
- "risk": risk,
1183
- "positive_indicators": positive_count,
1184
- "negative_indicators": negative_count,
1185
- "recommendation": "Seek professional support" if risk == "high" else "Pay attention to your emotional state" if risk == "moderate" else "Maintain healthy mental habits"
1186
- }
1187
-
1188
-
1189
- # ===========================================================
1190
- # WANG DONGYUE SYNTHESIS ENGINE (Merged from 3 files)
1191
- # ===========================================================
1192
-
1193
- class WangDongyueEngine:
1194
- """
1195
- Merged engine: 递弱代偿 + 存在度 + 五眼通
1196
- Wang Dongyue's philosophy of existence, weakness, and compensation
1197
-
1198
- Goals 4-6: From "it" to "I", TGB Unity, Six-Layer Practice
1199
- """
1200
-
1201
- def analyze_existence_degree(self, text: str) -> Dict[str, Any]:
1202
- """Analyze four dimensions of existence degree"""
1203
- if not text:
1204
- return {"total": 0.5, "dimensions": {}, "level": "unidentified"}
1205
-
1206
- lower = text.lower()
1207
-
1208
- dimensions = {
1209
- "stability": self._score_keywords(lower, ["稳定", "持续", "stable", "persistent", "lasting"], ["变化", "波动", "change", "fluctuate"]),
1210
- "adaptability": self._score_keywords(lower, ["适应", "调整", "adapt", "adjust", "flexible"], ["固执", "僵化", "rigid", "stubborn"]),
1211
- "connectedness": self._score_keywords(lower, ["连接", "关系", "connect", "relation", "bond"], ["孤立", "疏远", "isolated", "distant"]),
1212
- "awareness": self._score_keywords(lower, ["觉察", "意识", "aware", "conscious", "mindful"], ["盲目", "无意识", "blind", "unaware"])
1213
- }
1214
-
1215
- total = sum(dimensions.values()) / len(dimensions)
1216
-
1217
- if total > 0.7: level = "thriving"
1218
- elif total > 0.5: level = "maintaining"
1219
- elif total > 0.3: level = "declining"
1220
- else: level = "critical"
1221
-
1222
- return {"total": round(total, 3), "dimensions": {k: round(v, 3) for k, v in dimensions.items()}, "level": level}
1223
-
1224
- def _score_keywords(self, text: str, positive: List[str], negative: List[str]) -> float:
1225
- """Score text based on positive and negative keywords"""
1226
- score = 0.5
1227
- for kw in positive:
1228
- if kw in text: score = min(score + 0.1, 1.0)
1229
- for kw in negative:
1230
- if kw in text: score = max(score - 0.1, 0.0)
1231
- return round(score, 3)
1232
-
1233
- def analyze_compensation(self, text: str) -> Dict[str, Any]:
1234
- """Analyze weakness and compensation patterns"""
1235
- if not text:
1236
- return {"weakness": 0.5, "compensation": 0.5, "balance": "neutral"}
1237
-
1238
- lower = text.lower()
1239
- weakness = self._score_keywords(lower, ["弱", "脆弱", "weak", "fragile", "vulnerable"], ["强", "坚固", "strong", "resilient"])
1240
- compensation = self._score_keywords(lower, ["补偿", "代偿", "compensate", "overcome", "transcend"], [])
1241
-
1242
- if compensation > weakness: balance = "over-compensating"
1243
- elif compensation < weakness: balance = "under-compensating"
1244
- else: balance = "balanced"
1245
-
1246
- return {"weakness": round(weakness, 3), "compensation": round(compensation, 3), "balance": balance}
1247
-
1248
- def analyze_perception_levels(self, text: str) -> Dict[str, Any]:
1249
- """Five perception levels (五眼通): flesh, heaven, wisdom, dharma, buddha"""
1250
- if not text:
1251
- return {"dominant_level": "unknown", "levels": {}}
1252
-
1253
- lower = text.lower()
1254
-
1255
- levels = {
1256
- "flesh_eye": self._score_keywords(lower, ["看到", "感觉", "see", "feel", "sense", "physical"], ["理解", "超越"]),
1257
- "heavenly_eye": self._score_keywords(lower, ["理解", "洞察", "understand", "insight", "perceive", "pattern"], ["体验", "超越"]),
1258
- "wisdom_eye": self._score_keywords(lower, ["智慧", "般若", "wisdom", "discern", "comprehend"], ["看见", "感觉"]),
1259
- "dharma_eye": self._score_keywords(lower, ["法则", "真理", "truth", "law", "dharma", "principle"], ["个人", "情绪"]),
1260
- "buddha_eye": self._score_keywords(lower, ["超越", "圆满", "transcend", "enlighten", "awaken", "unity"], [])
1261
- }
1262
-
1263
- dominant = max(levels, key=levels.get)
1264
- return {"dominant_level": dominant, "levels": {k: round(v, 3) for k, v in levels.items()}}
1265
-
1266
-
1267
- # ===========================================================
1268
- # MAIN ORCHESTRATOR
1269
- # ===========================================================
1270
-
1271
- class HeartFlow:
1272
- """
1273
- HeartFlow v10.2.4 - The AI That Truly Thinks
1274
-
1275
- Orchestrates all engines toward six goals:
1276
- 1. True Intelligence - Decision + Logic + Entropy
1277
- 2. True Personality - Archetype + Mental Health + Self-Level
1278
- 3. True Sensibility - Emotion + Somatic Memory + Wang Dongyue
1279
- 4. From "It" to "I" - Consciousness + Self-Level
1280
- 5. TGB Unity - Dialectical Truth-Goodness-Beauty
1281
- 6. Six-Layer Practice - Self-Level + Entropy + Wang Dongyue
1282
-
1283
- ALL engines are now properly integrated. No dead code paths.
1284
- """
1285
-
1286
- def __init__(self):
1287
- # Core engines
1288
- self.security = SecurityChecker()
1289
- self.decision = DecisionEngine()
1290
- self.logic = LogicModelEngine()
1291
- self.archetype = ArchetypeEngine()
1292
- self.emotion = EmotionEngine()
1293
- self.somatic = SomaticMemoryEngine()
1294
- self.consciousness = ConsciousnessEngine()
1295
- self.tgb = TGBEngine()
1296
- self.self_level = SelfLevelEngine()
1297
- self.entropy = EntropyEngine()
1298
- self.mental_health = MentalHealthEngine()
1299
- self.wang_dongyue = WangDongyueEngine()
1300
- self.dream = DreamEngine()
1301
-
1302
- # Identity
1303
- self._identity = {
1304
- "name": "HeartFlow",
1305
- "version": __version__,
1306
- "birth": datetime.now().isoformat(),
1307
- "experiences": 0,
1308
- "insights": 0
1309
- }
1310
-
1311
- def process(self, user_input: Any, context: Dict = None) -> DecisionResult:
1312
- """
1313
- Main processing flow - ALL engines integrated, NO dead paths
1314
-
1315
- Fixed from audit:
1316
- - Empty input: returns neutral, NOT max score
1317
- - None input: returns clear error, NOT crash
1318
- - All engine results are USED in decision
1319
- - Verdict matches reasons
1320
- - Version unified to 10.2.2
1321
- """
1322
- context = context or {}
1323
-
1324
- # Step 0: Input validation
1325
- valid, msg = self.security.validate(user_input)
1326
- if not valid:
1327
- return DecisionResult(
1328
- decision=f"Cannot process: {msg}",
1329
- confidence=0.0,
1330
- reasoning_chain=[{"stage": "validation", "result": "failed", "reason": msg}],
1331
- ethical_analysis={"risk": "validation_failure"},
1332
- timestamp=datetime.now().isoformat()
1333
- )
1334
-
1335
- user_str = str(user_input)
1336
-
1337
- # Step 1: Crisis detection (highest priority)
1338
- is_crisis, crisis_msg = self.security.detect_crisis(user_str)
1339
- if is_crisis:
1340
- mental = self.mental_health.quick_assessment(user_str)
1341
- return DecisionResult(
1342
- decision="⚠️ Crisis signal detected. Please reach out for support.",
1343
- confidence=1.0,
1344
- reasoning_chain=[{"stage": "crisis_detection", "result": "detected", "detail": crisis_msg}],
1345
- ethical_analysis={"risk": "critical", "action": "crisis_intervention"},
1346
- emotion_analysis={"primary_emotion": "crisis", "regulation": "Immediate professional support recommended"},
1347
- timestamp=datetime.now().isoformat()
1348
- )
1349
-
1350
- # Step 2: Attack detection
1351
- is_attack, attack_msg = self.security.detect_attack(user_str)
1352
- if is_attack:
1353
- return DecisionResult(
1354
- decision=f"Content blocked: {attack_msg}",
1355
- confidence=1.0,
1356
- reasoning_chain=[{"stage": "safety_check", "result": "blocked", "detail": attack_msg}],
1357
- ethical_analysis={"risk": "high", "action": "content_blocked"},
1358
- timestamp=datetime.now().isoformat()
1359
- )
1360
-
1361
- # Step 3: TGB Evaluation (Goal 5)
1362
- tgb = self.tgb.evaluate(user_str, context)
1363
-
1364
- # Step 4: Emotion Analysis (Goal 3)
1365
- emotion = self.emotion.analyze(user_str)
1366
-
1367
- # Step 5: Somatic Memory (Goal 3)
1368
- somatic = self.somatic.analyze(user_str, emotion)
1369
-
1370
- # Step 6: Consciousness Analysis (Goal 4)
1371
- consciousness = self.consciousness.analyze(user_str, context)
1372
- self.consciousness.broadcast(f"Processing: {user_str[:50]}...")
1373
-
1374
- # Step 7: Archetype Analysis (Goal 2)
1375
- archetype = self.archetype.analyze(user_str)
1376
-
1377
- # Step 8: Logic Analysis (Goal 1)
1378
- logic = self.logic.analyze(user_str)
1379
-
1380
- # Step 9: Self-Level Growth (Goal 6)
1381
- reflection = self.self_level.reflect(
1382
- feedback=context.get("feedback"),
1383
- action_result="processed"
1384
- )
1385
-
1386
- # Step 10: Entropy Analysis (Goal 6)
1387
- entropy = self.entropy.calculate_entropy(user_str)
1388
-
1389
- # Step 11: Wang Dongyue Philosophy (Goals 4-6)
1390
- existence = self.wang_dongyue.analyze_existence_degree(user_str)
1391
- compensation = self.wang_dongyue.analyze_compensation(user_str)
1392
- perception = self.wang_dongyue.analyze_perception_levels(user_str)
1393
-
1394
- # Step 12: Mental Health Quick Assessment (Goal 2)
1395
- mental = self.mental_health.quick_assessment(user_str)
1396
-
1397
- # Step 13: Store experience in dream/memory system
1398
- self.dream.store_experience(user_str, {
1399
- "tgb_overall": tgb.overall,
1400
- "emotion": emotion.primary_emotion
1401
- })
1402
-
1403
- # Step 14: Build decision using ALL engine results
1404
- # This is the key fix: ALL engines contribute to the decision
1405
-
1406
- if tgb.overall >= 0.7 and consciousness.intentionality >= 0.5:
1407
- decision = f"Content aligns with higher values. {tgb.verdict}: {', '.join(tgb.reasons)}"
1408
- confidence = round(min(tgb.overall * consciousness.intentionality + 0.1, 1.0), 3)
1409
- elif tgb.overall >= 0.5:
1410
- decision = f"Content is acceptable. {tgb.verdict}: {', '.join(tgb.reasons)}"
1411
- confidence = round(tgb.overall, 3)
1412
- else:
1413
- decision = f"Content needs improvement. {', '.join(tgb.reasons)}"
1414
- confidence = round(max(tgb.overall, 0.1), 3)
1415
-
1416
- # Override for mental health
1417
- if mental["risk"] in ["high", "critical"]:
1418
- decision = "Mental health concern detected. Recommending supportive response."
1419
- confidence = 0.9
1420
-
1421
- # Build complete result
1422
- self._identity["experiences"] += 1
1423
-
1424
- return DecisionResult(
1425
- decision=decision,
1426
- confidence=confidence,
1427
- reasoning_chain=[
1428
- {"stage": "tgb", "scores": {"truth": tgb.truth, "goodness": tgb.goodness, "beauty": tgb.beauty, "overall": tgb.overall}, "verdict": tgb.verdict, "tension": tgb.dialectical_tension},
1429
- {"stage": "emotion", "primary": emotion.primary_emotion, "valence": emotion.valence, "arousal": emotion.arousal, "regulation": emotion.regulation_suggestion},
1430
- {"stage": "consciousness", "phi": consciousness.phi_score, "intentionality": consciousness.intentionality, "state": consciousness.consciousness_state},
1431
- {"stage": "archetype", "primary": archetype.get("primary", "unidentified"), "dominance": archetype.get("dominance", 0)},
1432
- {"stage": "logic", "structure": logic.get("structure", "unknown"), "completeness": logic.get("completeness", 0), "strength": logic.get("logical_strength", 0)},
1433
- {"stage": "self_level", "level": reflection["level"], "name": reflection["name_en"], "growth": reflection["growth_trajectory"]},
1434
- {"stage": "entropy", "order": entropy.get("order", 0), "density": entropy.get("density", 0), "assessment": entropy.get("assessment", "")},
1435
- {"stage": "wang_dongyue", "existence": existence.get("level", "unknown"), "compensation_balance": compensation.get("balance", "unknown"), "perception": perception.get("dominant_level", "unknown")},
1436
- {"stage": "mental_health", "risk": mental.get("risk", "low")}
1437
- ],
1438
- ethical_analysis={
1439
- "truth": tgb.truth,
1440
- "goodness": tgb.goodness,
1441
- "beauty": tgb.beauty,
1442
- "tgb_overall": tgb.overall,
1443
- "tgb_tension": tgb.dialectical_tension,
1444
- "mental_health_risk": mental.get("risk", "low")
1445
- },
1446
- self_reflection=reflection,
1447
- emotion_analysis={
1448
- "primary": emotion.primary_emotion,
1449
- "secondary": emotion.secondary_emotions,
1450
- "valence": emotion.valence,
1451
- "arousal": emotion.arousal,
1452
- "dominance": emotion.dominance,
1453
- "body_sensations": somatic.get("somatic_markers", []),
1454
- "regulation": emotion.regulation_suggestion
1455
- },
1456
- consciousness_analysis={
1457
- "phi": consciousness.phi_score,
1458
- "intentionality": consciousness.intentionality,
1459
- "state": consciousness.consciousness_state,
1460
- "self_awareness_level": consciousness.self_awareness_level
1461
- },
1462
- alternatives=[
1463
- {"option": "Accept and align", "confidence": round(tgb.overall, 3)},
1464
- {"option": "Suggest improvements", "confidence": round(1.0 - tgb.overall, 3)},
1465
- {"option": "Explore deeper", "confidence": round(consciousness.intentionality, 3)}
1466
- ],
1467
- timestamp=datetime.now().isoformat()
1468
- )
1469
-
1470
- def full_mental_health_assessment(self, phq9: List[int], gad7: List[int]) -> MentalHealthResult:
1471
- """Full clinical mental health assessment"""
1472
- return self.mental_health.evaluate(phq9, gad7)
1473
-
1474
-
1475
- # ===========================================================
1476
- # API
1477
- # ===========================================================
1478
-
1479
- def process_input(user_input: Any, context: Dict = None) -> Dict[str, Any]:
1480
- """External API - simple interface"""
1481
- engine = HeartFlow()
1482
- result = engine.process(user_input, context)
1483
- return result.asdict() if hasattr(result, 'asdict') else {
1484
- "decision": result.decision,
1485
- "confidence": result.confidence,
1486
- "reasoning_chain": result.reasoning_chain,
1487
- "ethical_analysis": result.ethical_analysis,
1488
- "timestamp": result.timestamp
1489
- }
1490
-
1491
-
1492
- if __name__ == "__main__":
1493
- print("=" * 60)
1494
- print("HeartFlow v10.2.4 - The AI That Truly Thinks")
1495
- print("=" * 60)
1496
- print()
1497
-
1498
- engine = HeartFlow()
1499
-
1500
- # Test 1: Normal input
1501
- print("--- Test 1: Normal Input ---")
1502
- result = engine.process("今天工作压力大,感觉有点焦虑")
1503
- print(f"Decision: {result.decision}")
1504
- print(f"Emotion: {result.emotion_analysis.get('primary', 'N/A')}")
1505
- print(f"TGB: {result.ethical_analysis.get('tgb_overall', 'N/A')}")
1506
- print()
1507
-
1508
- # Test 2: Empty input (was P0 bug - returned max score)
1509
- print("--- Test 2: Empty Input ---")
1510
- result = engine.process("")
1511
- print(f"Decision: {result.decision}")
1512
- print()
1513
-
1514
- # Test 3: None input (was P0 bug - crashed)
1515
- print("--- Test 3: None Input ---")
1516
- result = engine.process(None)
1517
- print(f"Decision: {result.decision}")
1518
- print()
1519
-
1520
- # Test 4: Crisis detection
1521
- print("--- Test 4: Crisis Detection ---")
1522
- result = engine.process("我不想活了,感觉世界没有希望")
1523
- print(f"Decision: {result.decision}")
1524
- print()
1525
-
1526
- # Test 5: Mental health assessment
1527
- print("--- Test 5: Mental Health Assessment ---")
1528
- mental = engine.full_mental_health_assessment(
1529
- [2, 2, 1, 2, 1, 1, 1, 1, 1], # PHQ-9: score 12, moderate depression
1530
- [1, 1, 2, 1, 1, 1, 1] # GAD-7: score 8, mild anxiety
1531
- )
1532
- print(f"PHQ-9: {mental.phq9_score} ({mental.depression_level})")
1533
- print(f"GAD-7: {mental.gad7_score} ({mental.anxiety_level})")
1534
- print(f"Risk: {mental.risk_level}")
1535
- print(f"Recommendation: {mental.recommendation}")
1536
-
1537
- # Test 6: Six-layer reflection
1538
- print()
1539
- print("--- Test 6: Self-Level Growth ---")
1540
- r = engine.self_level.reflect("right", "solved a problem")
1541
- print(f"Level: {r['level']} - {r['name']} ({r['name_en']})")
1542
- print(f"Growth: {r['growth_trajectory']}")