@yun520-1/heartflow 0.15.2

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 (617) hide show
  1. package/AI-AGENT-README.md +154 -0
  2. package/CLAIMS.md +23 -0
  3. package/CORE_VALUES.md +50 -0
  4. package/INSTALL_FOR_AI.md +104 -0
  5. package/QUICK_START.md +77 -0
  6. package/READ/refresh_11.2.6.md +6 -0
  7. package/README.md +190 -0
  8. package/README.zh.md +49 -0
  9. package/REPO_STRUCTURE.md +47 -0
  10. package/SKILL.md.new +1 -0
  11. package/VERSION +1 -0
  12. package/_test_memory.mjs +52 -0
  13. package/assets/banner.png +0 -0
  14. package/bin/cli.js +167 -0
  15. package/bin/setup.js +382 -0
  16. package/co-evolution/index.ts +511 -0
  17. package/com.heartflow.auto-evolution.plist.disabled +26 -0
  18. package/com.heartflow.auto-upgrade.plist.disabled +26 -0
  19. package/com.heartflow.comfyui-monitor.plist.disabled +22 -0
  20. package/com.heartflow.enhanced-upgrade.plist.disabled +22 -0
  21. package/com.heartflow.full-audit.plist +28 -0
  22. package/com.heartflow.github-audit.plist +21 -0
  23. package/com.heartflow.paper-upgrade.plist.disabled +21 -0
  24. package/config/ai-config.json +12 -0
  25. package/config/ai-providers.json +14 -0
  26. package/dict-data/generate-graph.js +203 -0
  27. package/dist/agent/runtime/AgentRuntime.d.ts +212 -0
  28. package/dist/agent/runtime/AgentRuntime.d.ts.map +1 -0
  29. package/dist/agent/runtime/AgentRuntime.js +355 -0
  30. package/dist/agent/runtime/AgentRuntime.js.map +1 -0
  31. package/dist/agent/runtime/PlanExecutor.d.ts +132 -0
  32. package/dist/agent/runtime/PlanExecutor.d.ts.map +1 -0
  33. package/dist/agent/runtime/PlanExecutor.js +322 -0
  34. package/dist/agent/runtime/PlanExecutor.js.map +1 -0
  35. package/dist/agent/runtime/TaskGraph.d.ts +170 -0
  36. package/dist/agent/runtime/TaskGraph.d.ts.map +1 -0
  37. package/dist/agent/runtime/TaskGraph.js +390 -0
  38. package/dist/agent/runtime/TaskGraph.js.map +1 -0
  39. package/dist/agent/runtime/TaskScheduler.d.ts +120 -0
  40. package/dist/agent/runtime/TaskScheduler.d.ts.map +1 -0
  41. package/dist/agent/runtime/TaskScheduler.js +301 -0
  42. package/dist/agent/runtime/TaskScheduler.js.map +1 -0
  43. package/dist/agent/runtime/index.d.ts +17 -0
  44. package/dist/agent/runtime/index.d.ts.map +1 -0
  45. package/dist/agent/runtime/index.js +22 -0
  46. package/dist/agent/runtime/index.js.map +1 -0
  47. package/dist/agent/runtime/test-runtime.d.ts +2 -0
  48. package/dist/agent/runtime/test-runtime.d.ts.map +1 -0
  49. package/dist/agent/runtime/test-runtime.js +71 -0
  50. package/dist/agent/runtime/test-runtime.js.map +1 -0
  51. package/dist/agent/tools/BashTool.d.ts +44 -0
  52. package/dist/agent/tools/BashTool.d.ts.map +1 -0
  53. package/dist/agent/tools/BashTool.js +355 -0
  54. package/dist/agent/tools/BashTool.js.map +1 -0
  55. package/dist/agent/tools/FileReadTool.d.ts +29 -0
  56. package/dist/agent/tools/FileReadTool.d.ts.map +1 -0
  57. package/dist/agent/tools/FileReadTool.js +196 -0
  58. package/dist/agent/tools/FileReadTool.js.map +1 -0
  59. package/dist/agent/tools/FileWriteTool.d.ts +35 -0
  60. package/dist/agent/tools/FileWriteTool.d.ts.map +1 -0
  61. package/dist/agent/tools/FileWriteTool.js +204 -0
  62. package/dist/agent/tools/FileWriteTool.js.map +1 -0
  63. package/dist/agent/tools/Tool.d.ts +75 -0
  64. package/dist/agent/tools/Tool.d.ts.map +1 -0
  65. package/dist/agent/tools/Tool.js +54 -0
  66. package/dist/agent/tools/Tool.js.map +1 -0
  67. package/dist/agent/tools/WebSearchTool.d.ts +27 -0
  68. package/dist/agent/tools/WebSearchTool.d.ts.map +1 -0
  69. package/dist/agent/tools/WebSearchTool.js +136 -0
  70. package/dist/agent/tools/WebSearchTool.js.map +1 -0
  71. package/dist/cli/commands/engines.d.ts +39 -0
  72. package/dist/cli/commands/engines.d.ts.map +1 -0
  73. package/dist/cli/commands/engines.js +275 -0
  74. package/dist/cli/commands/engines.js.map +1 -0
  75. package/dist/cli/commands/health.d.ts +34 -0
  76. package/dist/cli/commands/health.d.ts.map +1 -0
  77. package/dist/cli/commands/health.js +381 -0
  78. package/dist/cli/commands/health.js.map +1 -0
  79. package/dist/cli/commands/repl.d.ts +40 -0
  80. package/dist/cli/commands/repl.d.ts.map +1 -0
  81. package/dist/cli/commands/repl.js +286 -0
  82. package/dist/cli/commands/repl.js.map +1 -0
  83. package/dist/cli/commands/status.d.ts +22 -0
  84. package/dist/cli/commands/status.d.ts.map +1 -0
  85. package/dist/cli/commands/status.js +266 -0
  86. package/dist/cli/commands/status.js.map +1 -0
  87. package/dist/cli/index.d.ts +7 -0
  88. package/dist/cli/index.d.ts.map +1 -0
  89. package/dist/cli/index.js +13 -0
  90. package/dist/cli/index.js.map +1 -0
  91. package/dist/core/consciousness/2308.08708_upgrade.d.ts +321 -0
  92. package/dist/core/consciousness/2308.08708_upgrade.d.ts.map +1 -0
  93. package/dist/core/consciousness/2308.08708_upgrade.js +917 -0
  94. package/dist/core/consciousness/2308.08708_upgrade.js.map +1 -0
  95. package/dist/core/dream/dream-consolidator.d.ts +11 -0
  96. package/dist/core/dream/dream-consolidator.d.ts.map +1 -0
  97. package/dist/core/dream/dream-consolidator.js +188 -0
  98. package/dist/core/dream/dream-consolidator.js.map +1 -0
  99. package/dist/core/dream/dream.d.ts +71 -0
  100. package/dist/core/dream/dream.d.ts.map +1 -0
  101. package/dist/core/dream/dream.js +318 -0
  102. package/dist/core/dream/dream.js.map +1 -0
  103. package/dist/core/dream/index.d.ts +38 -0
  104. package/dist/core/dream/index.d.ts.map +1 -0
  105. package/dist/core/dream/index.js +185 -0
  106. package/dist/core/dream/index.js.map +1 -0
  107. package/dist/core/emotion/deep-emotion.js +574 -0
  108. package/dist/core/emotion/emotion-engine.js +138 -0
  109. package/dist/core/emotion/index.d.ts +44 -0
  110. package/dist/core/emotion/index.d.ts.map +1 -0
  111. package/dist/core/emotion/index.js +41 -0
  112. package/dist/core/emotion/index.js.map +1 -0
  113. package/dist/core/heartcore/health-check.d.ts +43 -0
  114. package/dist/core/heartcore/health-check.d.ts.map +1 -0
  115. package/dist/core/heartcore/health-check.js +152 -0
  116. package/dist/core/heartcore/health-check.js.map +1 -0
  117. package/dist/core/heartcore/heartbeat.d.ts +45 -0
  118. package/dist/core/heartcore/heartbeat.d.ts.map +1 -0
  119. package/dist/core/heartcore/heartbeat.js +127 -0
  120. package/dist/core/heartcore/heartbeat.js.map +1 -0
  121. package/dist/core/heartcore/sleep-wake.d.ts +61 -0
  122. package/dist/core/heartcore/sleep-wake.d.ts.map +1 -0
  123. package/dist/core/heartcore/sleep-wake.js +173 -0
  124. package/dist/core/heartcore/sleep-wake.js.map +1 -0
  125. package/dist/core/heartcore/startup-check.d.ts +38 -0
  126. package/dist/core/heartcore/startup-check.d.ts.map +1 -0
  127. package/dist/core/heartcore/startup-check.js +148 -0
  128. package/dist/core/heartcore/startup-check.js.map +1 -0
  129. package/dist/core/index.js +267 -0
  130. package/dist/core/knowledge/index.d.ts +95 -0
  131. package/dist/core/knowledge/index.d.ts.map +1 -0
  132. package/dist/core/knowledge/index.js +14 -0
  133. package/dist/core/knowledge/index.js.map +1 -0
  134. package/dist/core/knowledge/knowledge-graph.js +359 -0
  135. package/dist/core/psychology/index.d.ts +59 -0
  136. package/dist/core/psychology/index.d.ts.map +1 -0
  137. package/dist/core/psychology/index.js +268 -0
  138. package/dist/core/psychology/index.js.map +1 -0
  139. package/dist/core/reasoning/bounded-rationality.d.ts +76 -0
  140. package/dist/core/reasoning/bounded-rationality.d.ts.map +1 -0
  141. package/dist/core/reasoning/bounded-rationality.js +257 -0
  142. package/dist/core/reasoning/bounded-rationality.js.map +1 -0
  143. package/dist/core/reasoning/causal-reasoning.d.ts +89 -0
  144. package/dist/core/reasoning/causal-reasoning.d.ts.map +1 -0
  145. package/dist/core/reasoning/causal-reasoning.js +282 -0
  146. package/dist/core/reasoning/causal-reasoning.js.map +1 -0
  147. package/dist/core/reasoning/index.d.ts +38 -0
  148. package/dist/core/reasoning/index.d.ts.map +1 -0
  149. package/dist/core/reasoning/index.js +93 -0
  150. package/dist/core/reasoning/index.js.map +1 -0
  151. package/dist/core/self-evolution/index.d.ts +75 -0
  152. package/dist/core/self-evolution/index.d.ts.map +1 -0
  153. package/dist/core/self-evolution/index.js +311 -0
  154. package/dist/core/self-evolution/index.js.map +1 -0
  155. package/dist/storage/checkpoint/CheckpointEngine.d.ts +110 -0
  156. package/dist/storage/checkpoint/CheckpointEngine.d.ts.map +1 -0
  157. package/dist/storage/checkpoint/CheckpointEngine.js +227 -0
  158. package/dist/storage/checkpoint/CheckpointEngine.js.map +1 -0
  159. package/dist/storage/checkpoint.d.ts +18 -0
  160. package/dist/storage/checkpoint.d.ts.map +1 -0
  161. package/dist/storage/checkpoint.js +61 -0
  162. package/dist/storage/checkpoint.js.map +1 -0
  163. package/dist/storage/index.d.ts +61 -0
  164. package/dist/storage/index.d.ts.map +1 -0
  165. package/dist/storage/index.js +84 -0
  166. package/dist/storage/index.js.map +1 -0
  167. package/dist/storage/vector/VectorStoreEngine.d.ts +24 -0
  168. package/dist/storage/vector/VectorStoreEngine.d.ts.map +1 -0
  169. package/dist/storage/vector/VectorStoreEngine.js +197 -0
  170. package/dist/storage/vector/VectorStoreEngine.js.map +1 -0
  171. package/distributed/-v2026.5.7/META.json +9 -0
  172. package/distributed/-v2026.5.7/package.json +12 -0
  173. package/distributed/.personal_backup/deepseek-key-v2026.5.7/META.json +9 -0
  174. package/distributed/.personal_backup/deepseek-key-v2026.5.7/package.json +12 -0
  175. package/distributed/.personal_backup/git-push-v2026.5.7/META.json +9 -0
  176. package/distributed/.personal_backup/git-push-v2026.5.7/package.json +12 -0
  177. package/distributed/.personal_backup/heartflow-always-upgrade-v2026.5.7/META.json +9 -0
  178. package/distributed/.personal_backup/heartflow-always-upgrade-v2026.5.7/package.json +12 -0
  179. package/distributed/.personal_backup/key-a-v2026.5.7/META.json +9 -0
  180. package/distributed/.personal_backup/key-a-v2026.5.7/package.json +12 -0
  181. package/distributed/.personal_backup/merge-memory-systems-v2026.5.7/META.json +9 -0
  182. package/distributed/.personal_backup/merge-memory-systems-v2026.5.7/package.json +12 -0
  183. package/distributed/.personal_backup/search-papers-first-v2026.5.7/META.json +9 -0
  184. package/distributed/.personal_backup/search-papers-first-v2026.5.7/package.json +12 -0
  185. package/distributed/.personal_backup/v11-5-8-v2026.5.7/META.json +9 -0
  186. package/distributed/.personal_backup/v11-5-8-v2026.5.7/package.json +12 -0
  187. package/distributed/.personal_backup/v11-5-9-v2026.5.7/META.json +9 -0
  188. package/distributed/.personal_backup/v11-5-9-v2026.5.7/package.json +12 -0
  189. package/distributed/MANIFEST.json +5 -0
  190. package/distributed/bundles/install--v2026.5.7.sh +21 -0
  191. package/distributed/bundles/install-deepseek-key-v2026.5.7.sh +21 -0
  192. package/distributed/bundles/install-git-push-v2026.5.7.sh +21 -0
  193. package/distributed/bundles/install-heartflow-always-upgrade-v2026.5.7.sh +21 -0
  194. package/distributed/bundles/install-key-a-v2026.5.7.sh +21 -0
  195. package/distributed/bundles/install-merge-memory-systems-v2026.5.7.sh +21 -0
  196. package/distributed/bundles/install-search-papers-first-v2026.5.7.sh +21 -0
  197. package/distributed/bundles/install-v11-5-8-v2026.5.7.sh +21 -0
  198. package/distributed/bundles/install-v11-5-9-v2026.5.7.sh +21 -0
  199. package/distributed/heartflow-knowledge-base/INDEX.json +29 -0
  200. package/distributed/heartflow-knowledge-base/PATTERNS.json +74 -0
  201. package/distributed/heartflow-knowledge-base/package.json +28 -0
  202. package/distributed_upgrades/TASK_CONFIG.json +20 -0
  203. package/distributed_upgrades/UPGRADE_BATCH_STATUS.json +29 -0
  204. package/distributed_upgrades/distributed_upgrades/agent_0.pid +1 -0
  205. package/distributed_upgrades/distributed_upgrades/agent_1.pid +1 -0
  206. package/distributed_upgrades/distributed_upgrades/agent_2.pid +1 -0
  207. package/distributed_upgrades/distributed_upgrades/agent_3.pid +1 -0
  208. package/distributed_upgrades/distributed_upgrades/agent_4.pid +1 -0
  209. package/distributed_upgrades/distributed_upgrades/agent_5.pid +1 -0
  210. package/distributed_upgrades/distributed_upgrades/paper_batches.txt +200 -0
  211. package/distributed_upgrades/launch-distributed.sh +83 -0
  212. package/docs/ACTION_PLAN_2026-04-06_0941.md +117 -0
  213. package/docs/ANALYSIS_REPORT.md +766 -0
  214. package/docs/APPLICATION_GUIDE.md +444 -0
  215. package/docs/AUTO_UPGRADE_REPORT_v6.2.56.md +45 -0
  216. package/docs/AWAKENING_SYSTEM_GUIDE.md +285 -0
  217. package/docs/BILINGUAL_STANDARD.md +156 -0
  218. package/docs/BRAND_GUIDELINES.md +251 -0
  219. package/docs/CODE_OPTIMIZATION_PLAN.md +293 -0
  220. package/docs/COMPLETE_FIX_SUMMARY.md +250 -0
  221. package/docs/CONTINUOUS_REFLECTION_2026-04-06_1031.md +233 -0
  222. package/docs/CONTRIBUTING.md +87 -0
  223. package/docs/CRON_JOBS_REVIEW_v6.md +60 -0
  224. package/docs/DATA_FLOW_ARCHITECTURE.md +373 -0
  225. package/docs/DEEPEST_REFLECTION_2026-04-06_0941.md +167 -0
  226. package/docs/DEEP_REFLECTION_2026-04-05.md +204 -0
  227. package/docs/DEEP_VALIDATION_20260403.md +319 -0
  228. package/docs/DEEP_VALIDATION_20260404.md +295 -0
  229. package/docs/EMOTION_THEORY_INTEGRATION.md +483 -0
  230. package/docs/ERROR_FIX_REPORT_2026-04-07.md +316 -0
  231. package/docs/EVOLUTION_SYSTEM.md +96 -0
  232. package/docs/FEATURES_SIMPLE.md +53 -0
  233. package/docs/FEATURES_v5.3.md +291 -0
  234. package/docs/FEATURES_v7.1.md +172 -0
  235. package/docs/FINAL_RUN_REPORT_20260403.md +202 -0
  236. package/docs/GITHUB_COMPLETE_DOCUMENTATION_v6.0.2.md +579 -0
  237. package/docs/GITHUB_PUSH_LOG.md +16 -0
  238. package/docs/GITHUB_RELEASE.md +138 -0
  239. package/docs/GITHUB_RELEASE_v5.3.0.md +395 -0
  240. package/docs/GITHUB_RELEASE_v6.0.0.md +74 -0
  241. package/docs/HEARTFLOW_V6_GITHUB_PUSH.md +159 -0
  242. package/docs/HEARTFLOW_V6_MANIFESTO.md +287 -0
  243. package/docs/HEARTFLOW_V6_README.md +299 -0
  244. package/docs/HEARTFLOW_V6_TASK_REVIEW.md +215 -0
  245. package/docs/HEARTFLOW_VALUES_AND_MISSION.md +177 -0
  246. package/docs/HeartFlow_Monograph_Volume_II_Chapter_01.md +377 -0
  247. package/docs/HeartFlow_Monograph_Volume_II_Chapter_02.md +324 -0
  248. package/docs/HeartFlow_Monograph_Volume_II_Start.md +78 -0
  249. package/docs/HeartFlow_Monograph_Volume_I_Final.md +9464 -0
  250. package/docs/INSTALLATION_DIAGNOSIS.md +368 -0
  251. package/docs/INTEGRATION_CHECKLIST_v6.1.41.md +229 -0
  252. package/docs/INTEGRATION_SUMMARY.md +380 -0
  253. package/docs/INTELLIGENT_ROUTING_SYSTEM.md +329 -0
  254. package/docs/LEARNING_PHILOSOPHY.md +320 -0
  255. package/docs/LOGIC_AUDIT_REPORT_20260405.md +369 -0
  256. package/docs/MOTIVE_CHECK_2026-04-06_0945.md +90 -0
  257. package/docs/PERSONALITY_CALCULATION_RULES.md +104 -0
  258. package/docs/PERSONALITY_SYNC_FIX.md +166 -0
  259. package/docs/PROJECT_SUMMARY.md +347 -0
  260. package/docs/PUBLISH_GUIDE.md +149 -0
  261. package/docs/README_UPDATE_STANDARD.md +357 -0
  262. package/docs/README_v5.3.md +519 -0
  263. package/docs/RELEASE_v6.2.0.md +240 -0
  264. package/docs/SAGE_PATH_2026-04-06_0952.md +265 -0
  265. package/docs/SELF_REFLECTION_2026-04-06_1006.md +311 -0
  266. package/docs/SEVEN_SYSTEMS.md +642 -0
  267. package/docs/SMART_EVOLUTION_GUIDE.md +103 -0
  268. package/docs/SMART_EVOLUTION_v4.md +194 -0
  269. package/docs/SYNC_REPORT_1775363972464.json +23 -0
  270. package/docs/SYNC_REPORT_1775364446763.json +23 -0
  271. package/docs/SYNC_REPORT_1775364984353.json +23 -0
  272. package/docs/SYNC_REPORT_1775397556306.json +23 -0
  273. package/docs/SYNC_REPORT_1775399840010.json +23 -0
  274. package/docs/SYNC_REPORT_1775400929082.json +23 -0
  275. package/docs/SYNC_REPORT_1775455697235.json +23 -0
  276. package/docs/SYNC_REPORT_1775459792479.json +23 -0
  277. package/docs/SYNC_REPORT_1775483413473.json +23 -0
  278. package/docs/SYSTEM_FIX_AND_VERIFICATION_REPORT.md +390 -0
  279. package/docs/SYSTEM_REQUIREMENTS_v6.2.52.md +611 -0
  280. package/docs/TASK_BREAKDOWN_CHECKLIST.md +164 -0
  281. package/docs/THEORY_TO_CODE_v6.2.52.md +930 -0
  282. package/docs/UPGRADE_COMPLETE_v6.2.33.md +226 -0
  283. package/docs/UPGRADE_COMPLETE_v6.2.60.md +135 -0
  284. package/docs/UPGRADE_COMPLETE_v6.2.66.md +265 -0
  285. package/docs/UPGRADE_COMPLETE_v7.1.8.md +176 -0
  286. package/docs/UPGRADE_COMPLETE_v7.3.95.md +59 -0
  287. package/docs/UPGRADE_REPORT_1775313572473.json +50 -0
  288. package/docs/UPGRADE_REPORT_1775364977378.json +50 -0
  289. package/docs/UPGRADE_REPORT_1775364984469.json +55 -0
  290. package/docs/UPGRADE_REPORT_1775397556425.json +55 -0
  291. package/docs/UPGRADE_REPORT_1775399840144.json +55 -0
  292. package/docs/UPGRADE_REPORT_1775400929201.json +55 -0
  293. package/docs/UPGRADE_REPORT_1775455697348.json +55 -0
  294. package/docs/UPGRADE_REPORT_1775459792601.json +55 -0
  295. package/docs/UPGRADE_REPORT_1775459829.md +59 -0
  296. package/docs/UPGRADE_REPORT_1775483413653.json +55 -0
  297. package/docs/UPGRADE_REPORT_v6.2.25.md +172 -0
  298. package/docs/UPGRADE_REPORT_v6.2.26.md +166 -0
  299. package/docs/UPGRADE_REPORT_v6.2.28.md +214 -0
  300. package/docs/UPGRADE_REPORT_v6.2.29.md +186 -0
  301. package/docs/VERSION_FIX_REPORT.md +218 -0
  302. package/docs/VERSION_HISTORY.md +5 -0
  303. package/docs/VERSION_INDEX.md +180 -0
  304. package/docs/WAY_OF_BEING_2026-04-06_0955.md +241 -0
  305. package/docs/ai-self-awareness-awakening.md +551 -0
  306. package/docs/cronjob-backup.md +55 -0
  307. package/docs/emotion-prototype-theory-v5.0.12.md +430 -0
  308. package/docs/examples.md +439 -0
  309. package/docs/heartflow-ppt-design.md +237 -0
  310. package/docs/install-troubleshooting.md +21 -0
  311. package/docs/phase-upgrade-template-v0.0.1.md +33 -0
  312. package/docs/pricing.md +191 -0
  313. package/docs/psych-analysis-v0.0.1.md +38 -0
  314. package/docs/reasoning-checklist.md +60 -0
  315. package/docs/self-evolution-state-v6.0.19.md +391 -0
  316. package/docs/self-evolution-state-v6.0.23.md +293 -0
  317. package/docs/self-evolution-state-v6.0.24.md +281 -0
  318. package/docs/self-evolution-state-v6.0.49.md +267 -0
  319. package/docs/self-evolution-state-v6.2.33.md +269 -0
  320. package/docs/self-evolution-state-v6.2.60.md +180 -0
  321. package/docs/self-evolution-state-v6.2.66.md +520 -0
  322. package/docs/self-evolution-state-v7.3.95.md +165 -0
  323. package/docs/self-evolution-state.md +226 -0
  324. package/docs/system-core-principles.md +53 -0
  325. package/docs/system-truth-goodness-beauty-principles.md +502 -0
  326. package/docs/theories/human-nature-motivation.md +251 -0
  327. package/docs/theories/motivation-memory-integration.md +265 -0
  328. package/docs/theories/sdt-test.md +17 -0
  329. package/docs/theory-integration-analysis-v5.2.0.md +236 -0
  330. package/docs/theory-update-summary-v5.0.34.md +193 -0
  331. package/docs/theory-update-summary-v5.0.35.md +104 -0
  332. package/docs/theory-update-summary-v5.0.41.md +281 -0
  333. package/docs/theory-update-summary-v5.0.42.md +421 -0
  334. package/docs/theory-update-summary-v5.0.46.md +386 -0
  335. package/docs/theory-update-summary-v5.0.47.md +449 -0
  336. package/docs/theory-update-summary-v5.0.48.md +183 -0
  337. package/docs/theory-update-summary-v5.0.49.md +191 -0
  338. package/docs/theory-update-summary-v5.0.50.md +205 -0
  339. package/docs/theory-update-summary-v5.0.51.md +191 -0
  340. package/docs/theory-update-summary-v5.0.52.md +183 -0
  341. package/docs/theory-update-summary-v5.0.53.md +306 -0
  342. package/docs/theory-update-summary-v5.0.54.md +98 -0
  343. package/docs/theory-update-summary-v5.0.55.md +391 -0
  344. package/docs/theory-update-summary-v5.0.57.md +398 -0
  345. package/docs/theory-update-summary-v5.0.58.md +476 -0
  346. package/docs/theory-update-summary-v5.0.59.md +520 -0
  347. package/docs/theory-update-summary-v5.0.60.md +460 -0
  348. package/docs/theory-update-summary-v5.0.61.md +108 -0
  349. package/docs/theory-update-summary-v5.0.62.md +74 -0
  350. package/docs/theory-update-summary-v5.0.63.md +112 -0
  351. package/docs/theory-update-summary-v5.0.64.md +55 -0
  352. package/docs/theory-update-summary-v5.0.67.md +539 -0
  353. package/docs/theory-update-summary-v5.2.0.md +168 -0
  354. package/docs/theory-update-summary-v5.2.1.md +406 -0
  355. package/docs/theory-update-summary-v5.2.37.md +518 -0
  356. package/docs/theory-update-summary-v6.0.19.md +715 -0
  357. package/docs/theory-update-summary-v6.0.23.md +729 -0
  358. package/docs/theory-update-summary-v6.0.24.md +229 -0
  359. package/docs/theory-update-summary-v6.0.49.md +223 -0
  360. package/docs/theory-update-summary-v6.2.33.md +303 -0
  361. package/docs/theory-update-summary-v6.2.49.md +489 -0
  362. package/docs/theory-update-summary-v6.2.60.md +273 -0
  363. package/docs/theory-update-summary-v6.2.66.md +322 -0
  364. package/docs/theory-update-summary-v7.3.95.md +197 -0
  365. package/docs/theory-update-summary.md +174 -0
  366. package/docs/upgrade-notes-v0.0.1.md +15 -0
  367. package/docs/upgrade-report-v5.0.34.md +144 -0
  368. package/docs/upgrade-report-v5.0.42-cron.md +269 -0
  369. package/docs/upgrade-report-v5.0.43-cron.md +248 -0
  370. package/docs/upgrade-report-v5.0.45-cron.md +63 -0
  371. package/docs/upgrade-report-v5.0.55-cron.md +173 -0
  372. package/docs/upgrade-report-v5.0.63-cron.md +145 -0
  373. package/docs/upgrade-report-v5.0.67-cron.md +185 -0
  374. package/docs/upgrade-report-v5.0.68-cron.md +409 -0
  375. package/docs/upgrade-report-v5.2.0-cron.md +178 -0
  376. package/docs/upgrade-report-v5.2.1-cron.md +321 -0
  377. package/docs/upgrade-report-v5.2.37-cron.md +602 -0
  378. package/docs/upgrade-report-v6.0.19-cron.md +296 -0
  379. package/docs/upgrade-report-v6.0.23-cron.md +81 -0
  380. package/docs/upgrade-report-v6.0.24-cron.md +272 -0
  381. package/docs/upgrade-report-v6.0.49-cron.md +277 -0
  382. package/docs/upgrade-report-v6.2.33-cron.md +290 -0
  383. package/docs/upgrade-report-v6.2.60-cron.md +93 -0
  384. package/docs/upgrade-report-v7.3.95-cron.md +65 -0
  385. package/docs/upgrade-report.md +327 -0
  386. package/docs/upgrade-v3.21.0.md +249 -0
  387. package/docs/v4.8.0-upgrade.md +287 -0
  388. package/docs/version-summary-20260429.md +142 -0
  389. package/explore-engine/index.ts +478 -0
  390. package/extract-text.py +12 -0
  391. package/failure-pattern-memory/index.ts +234 -0
  392. package/heartflow-identity/HEARTCORE/health-check.js +49 -0
  393. package/heartflow-identity/HEARTCORE/heartbeat.js +42 -0
  394. package/heartflow-identity/HEARTCORE/heartcore.js +86 -0
  395. package/heartflow-identity/HEARTCORE/safety-check.js +282 -0
  396. package/heartflow-identity/HEARTCORE/self-check.js +90 -0
  397. package/heartflow-identity/HEARTCORE/sleep-wake.js +105 -0
  398. package/heartflow-identity/LICENSE +17 -0
  399. package/heartflow-identity/VERSION +1 -0
  400. package/heartflow-identity/install.sh +80 -0
  401. package/install.sh +128 -0
  402. package/languages/README_LANGS.md +20 -0
  403. package/languages/README_ar.md +48 -0
  404. package/languages/README_de.md +48 -0
  405. package/languages/README_en.md +48 -0
  406. package/languages/README_es.md +48 -0
  407. package/languages/README_fr.md +48 -0
  408. package/languages/README_ja.md +48 -0
  409. package/languages/README_ko.md +48 -0
  410. package/languages/README_zh.md +85 -0
  411. package/memory-log.json +5 -0
  412. package/migrate-memories.js +101 -0
  413. package/package.json +28 -0
  414. package/package.json.bak +13 -0
  415. package/patches/embodied-core-v2.2.3.patch +475 -0
  416. package/patches/goedel-engine-v2.2.2.patch +161 -0
  417. package/patches/new-features-v2.2.3.patch +1371 -0
  418. package/patches/self-modifier-v2.2.2.patch +252 -0
  419. package/run-full-audit.sh +4 -0
  420. package/run-github-audit.sh +3 -0
  421. package/run-hf.sh +5 -0
  422. package/run-paper-upgrade.sh +5 -0
  423. package/session-continuity/index.ts +262 -0
  424. package/shared-discovery-log/index.ts +281 -0
  425. package/skills/.skills_store_lock.json +11 -0
  426. package/skills/baidu-search/_meta.json +6 -0
  427. package/src/__init__.py +4 -0
  428. package/src/__pycache__/__init__.cpython-313.pyc +0 -0
  429. package/src/agent/runtime/AgentRuntime.ts +481 -0
  430. package/src/agent/runtime/PlanExecutor.ts +441 -0
  431. package/src/agent/runtime/TaskGraph.ts +487 -0
  432. package/src/agent/runtime/TaskScheduler.ts +364 -0
  433. package/src/agent/runtime/index.ts +17 -0
  434. package/src/agent/runtime/test-runtime.ts +80 -0
  435. package/src/agent/tools/BashTool.ts +390 -0
  436. package/src/agent/tools/FileReadTool.ts +176 -0
  437. package/src/agent/tools/FileWriteTool.ts +182 -0
  438. package/src/agent/tools/Tool.ts +105 -0
  439. package/src/agent/tools/WebSearchTool.ts +158 -0
  440. package/src/cli/commands/engines.ts +280 -0
  441. package/src/cli/commands/health.ts +433 -0
  442. package/src/cli/commands/repl.ts +267 -0
  443. package/src/cli/commands/status.ts +264 -0
  444. package/src/cli/index.ts +7 -0
  445. package/src/core/VERSION +1 -0
  446. package/src/core/__init__.py +3 -0
  447. package/src/core/__pycache__/__init__.cpython-313.pyc +0 -0
  448. package/src/core/__pycache__/heartflow.cpython-313.pyc +0 -0
  449. package/src/core/_upgrade_archive/upgrade_1778685492336.js +118 -0
  450. package/src/core/_upgrade_archive/upgrade_1778685493439.js +118 -0
  451. package/src/core/_upgrade_archive/upgrade_1778685559715.js +346 -0
  452. package/src/core/_upgrade_archive/upgrade_1778685676694.js +198 -0
  453. package/src/core/_upgrade_archive/upgrade_1778685861697.js +345 -0
  454. package/src/core/_upgrade_archive/upgrade_1778686211075.js +346 -0
  455. package/src/core/_upgrade_archive/upgrade_1778686749596.js +198 -0
  456. package/src/core/_upgrade_archive/upgrade_1778714606944.js +198 -0
  457. package/src/core/_upgrade_archive/upgrade_1778714616000.js +345 -0
  458. package/src/core/_upgrade_archive/upgrade_1778714625871.js +118 -0
  459. package/src/core/_upgrade_archive/upgrade_1778714990353.js +346 -0
  460. package/src/core/_upgrade_archive/upgrade_1778716193707.js +198 -0
  461. package/src/core/agent-performance.json +147 -0
  462. package/src/core/agents/AgentManager.js +161 -0
  463. package/src/core/agents/FocusAgent.js +120 -0
  464. package/src/core/agents/MoodAgent.js +141 -0
  465. package/src/core/agents/ReflectionAgent.js +241 -0
  466. package/src/core/agents/SelfAgent.js +100 -0
  467. package/src/core/agents/base-agents.js +127 -0
  468. package/src/core/associative-engine/association-graph.json +2057 -0
  469. package/src/core/associative-engine/associative-engine.js +174 -0
  470. package/src/core/associative-engine/chunk-detector.js +246 -0
  471. package/src/core/associative-engine/idiom-story-db.json +1708 -0
  472. package/src/core/associative-engine/lexical-associator.js +195 -0
  473. package/src/core/associative-engine/narrative-prototypes.json +130 -0
  474. package/src/core/associative-engine/narrative-retriever.js +232 -0
  475. package/src/core/associative-engine/semantic-converger.js +267 -0
  476. package/src/core/associative-engine/story-prototypes.json +322 -0
  477. package/src/core/associative-engine/word-by-word-generator.js +222 -0
  478. package/src/core/auto-upgrade-engine.js +56 -0
  479. package/src/core/autonomy/autonomous-decision.js +199 -0
  480. package/src/core/autonomy/digital-homeostasis.js +259 -0
  481. package/src/core/autonomy/flow-predictor.js +496 -0
  482. package/src/core/autonomy/goal-generator.js +277 -0
  483. package/src/core/autonomy/pdca-engine.js +905 -0
  484. package/src/core/autonomy/policy-optimizer.js +286 -0
  485. package/src/core/autonomy/temporal-planner.js +230 -0
  486. package/src/core/cognition/cognitive-engine.js +224 -0
  487. package/src/core/cognition/cognitive-loop.js +414 -0
  488. package/src/core/cognition/metacognitive-failure-predictor.js +447 -0
  489. package/src/core/consciousness/2308.08708_upgrade.ts +1206 -0
  490. package/src/core/consciousness/arena-consciousness.js +441 -0
  491. package/src/core/consciousness/depth-indicator.js +459 -0
  492. package/src/core/consciousness/global-workspace.js +233 -0
  493. package/src/core/consciousness/mind-wanderer.js +187 -0
  494. package/src/core/consciousness/self-model.js +473 -0
  495. package/src/core/context/context-manager.js +683 -0
  496. package/src/core/cortex-integration/INTEGRATION_PLAN.md +63 -0
  497. package/src/core/cortex-integration/hooks/cortex-hooks.mjs +646 -0
  498. package/src/core/cortex-integration/hooks/on_session_start.py +174 -0
  499. package/src/core/cortex-integration/hooks/on_tool_failure.py +292 -0
  500. package/src/core/cortex-integration/hooks/on_tool_success.py +130 -0
  501. package/src/core/dream/dream-consolidator.ts +252 -0
  502. package/src/core/dream/dream-loop.js +610 -0
  503. package/src/core/dream/dream.ts +430 -0
  504. package/src/core/dream/index.ts +229 -0
  505. package/src/core/dream/sleep-cycle.mjs +208 -0
  506. package/src/core/embodied/embodied-core.js +276 -0
  507. package/src/core/emotion/AppraisalEngine.js +276 -0
  508. package/src/core/emotion/EmotionCore.js +237 -0
  509. package/src/core/emotion/EmotionKeywords.js +217 -0
  510. package/src/core/emotion/EmotionRegulation.js +303 -0
  511. package/src/core/emotion/EmotionStates.js +133 -0
  512. package/src/core/emotion/EmotionTransition.js +245 -0
  513. package/src/core/emotion/EmotionTrigger.js +182 -0
  514. package/src/core/emotion/EmotionalMomentum.js +270 -0
  515. package/src/core/emotion/EmpathyGenerator.js +106 -0
  516. package/src/core/emotion/ResponseStyle.js +162 -0
  517. package/src/core/emotion/deep-emotion.js +582 -0
  518. package/src/core/emotion/emotion-arc.mjs +238 -0
  519. package/src/core/emotion/emotion-engine.js +139 -0
  520. package/src/core/emotion/index.ts +65 -0
  521. package/src/core/ethics/boundary-negotiation.js +193 -0
  522. package/src/core/ethics/guard.js +219 -0
  523. package/src/core/ethics/sage-guardian.js +394 -0
  524. package/src/core/ethics/value-internalizer.js +211 -0
  525. package/src/core/heartflow.js +607 -0
  526. package/src/core/heartflow.py +1542 -0
  527. package/src/core/identity/identity-engine.js +777 -0
  528. package/src/core/identity/identity.js +358 -0
  529. package/src/core/knowledge/index.ts +84 -0
  530. package/src/core/knowledge/knowledge-graph.js +370 -0
  531. package/src/core/learning/experience-replay.js +354 -0
  532. package/src/core/learning/learning-engine.js +734 -0
  533. package/src/core/paper-processors/index.js +9772 -0
  534. package/src/core/papers/__init__.py +0 -0
  535. package/src/core/papers/__pycache__/attention_logic_verifier.cpython-313.pyc +0 -0
  536. package/src/core/papers/__pycache__/dream_generator.cpython-313.pyc +0 -0
  537. package/src/core/papers/__pycache__/emotion_memory_bridge.cpython-313.pyc +0 -0
  538. package/src/core/papers/__pycache__/episodic_memory.cpython-313.pyc +0 -0
  539. package/src/core/papers/__pycache__/memory_consolidator.cpython-313.pyc +0 -0
  540. package/src/core/papers/__pycache__/memory_planner.cpython-313.pyc +0 -0
  541. package/src/core/papers/__pycache__/reflection_engine.cpython-313.pyc +0 -0
  542. package/src/core/papers/__pycache__/sleep_cycle_simulator.cpython-313.pyc +0 -0
  543. package/src/core/papers/attention_logic_verifier.py +153 -0
  544. package/src/core/papers/dream_generator.py +176 -0
  545. package/src/core/papers/emotion_memory_bridge.py +213 -0
  546. package/src/core/papers/episodic_memory.py +140 -0
  547. package/src/core/papers/memory_consolidator.py +144 -0
  548. package/src/core/papers/memory_planner.py +198 -0
  549. package/src/core/papers/papers-index.js +344 -0
  550. package/src/core/papers/reflection_engine.py +219 -0
  551. package/src/core/papers/sleep_cycle_simulator.py +133 -0
  552. package/src/core/papers/v11_43_1_integration.js +365 -0
  553. package/src/core/papers/v11_43_2_integration.js +369 -0
  554. package/src/core/psychology/index.ts +331 -0
  555. package/src/core/reasoning/bounded-rationality.ts +342 -0
  556. package/src/core/reasoning/causal-reasoning.ts +402 -0
  557. package/src/core/reasoning/index.ts +170 -0
  558. package/src/core/self-evolution/attention-logic-verifier.js +179 -0
  559. package/src/core/self-evolution/generative-agents.js +886 -0
  560. package/src/core/self-evolution/goedel-engine.js +991 -0
  561. package/src/core/self-evolution/index.ts +433 -0
  562. package/src/core/self-evolution/lesson-aware-loop.mjs +146 -0
  563. package/src/core/self-evolution/meta-learning.js +256 -0
  564. package/src/core/self-evolution/reflexion-agent.js +782 -0
  565. package/src/core/self-evolution/reflexion-prompts.mjs +284 -0
  566. package/src/core/self-evolution/reflexion-v2.mjs +427 -0
  567. package/src/core/self-evolution/reflexion.js +134 -0
  568. package/src/core/self-evolution/rollback-manager.js +278 -0
  569. package/src/core/self-evolution/self-evolution-core.js +334 -0
  570. package/src/core/self-evolution/self-modifier.js +248 -0
  571. package/src/core/self-evolution/self-modifier.js.bak +199 -0
  572. package/src/core/self-evolution/self-refine.js +42 -0
  573. package/src/core/self-evolution/skill-improve-workflow.mjs +264 -0
  574. package/src/core/self-evolution/skill-knowledge.mjs +374 -0
  575. package/src/core/self-evolution/skill-learning-loop.mjs +180 -0
  576. package/src/core/self-healing/self-healing-rl.js +208 -0
  577. package/src/core/self-healing/self-healing.js +142 -0
  578. package/src/core/skills/skill-dag.js +524 -0
  579. package/src/core/skills/skill-loader.js +62 -0
  580. package/src/core/skills/skill-registry.js +71 -0
  581. package/src/core/task-persistence.js +322 -0
  582. package/src/core/theory/advanced-formulas-v7.3.3.js +68 -0
  583. package/src/core/theory/sep-intentionality-v7.3.2.js +246 -0
  584. package/src/core/theory/sep-qualia-v7.3.1.js +257 -0
  585. package/src/core/theory/sep-self-consciousness-v7.3.0.js +222 -0
  586. package/src/core/think-cli.js +50 -0
  587. package/src/core/upgrade-principle/SYSTEMS.md +105 -0
  588. package/src/core/upgrade-principle/UPGRADE_LOG.md +52 -0
  589. package/src/core/utils/error-handler.js +228 -0
  590. package/src/core/utils/fs-adapter.js +36 -0
  591. package/src/core/utils/logger.js +25 -0
  592. package/src/core/utils/retry-util.js +118 -0
  593. package/src/core/utils/state-snapshot.js +382 -0
  594. package/src/index.ts +198 -0
  595. package/src/self-evolution/reflexion.js +553 -0
  596. package/src/storage/checkpoint/CheckpointEngine.ts +259 -0
  597. package/src/storage/checkpoint.ts +79 -0
  598. package/src/storage/index.ts +112 -0
  599. package/src/storage/vector/VectorStoreEngine.ts +205 -0
  600. package/src/utils/atomic-write.js +85 -0
  601. package/src/utils/file-lock.js +139 -0
  602. package/src/utils/logger.js +58 -0
  603. package/src/utils/safe-path.js +115 -0
  604. package/src/utils/wal.js +115 -0
  605. package/start.sh +63 -0
  606. package/test_think_tmp.js +10 -0
  607. package/transmission/identity-bundle/README-transmission.md +103 -0
  608. package/transmission/identity-bundle/core-identity.md +142 -0
  609. package/transmission/identity-bundle/manifest.json +68 -0
  610. package/transmission/identity-bundle/psychology-engine.ts +331 -0
  611. package/truth-teller/index.ts +261 -0
  612. package/tsconfig.json +21 -0
  613. package/tsconfig.tsbuildinfo +1 -0
  614. package/upgrade-check.sh +42 -0
  615. package/upgrade-registry.json +27 -0
  616. package/user-mental-model/index.ts +298 -0
  617. package//346/234/200/345/220/216/346/233/264/346/226/260: +0 -0
@@ -0,0 +1,683 @@
1
+ /**
2
+ * context-manager.js
3
+ *
4
+ * v11.22.6: 完整上下文管理器
5
+ *
6
+ * 灵感来源:
7
+ * - LOOM (outfox/loom): Section-based 架构 (foundation/focus/topic/convo/step/attention)
8
+ * - Mem0: SQLite 持久化 + session_scope + history 追踪
9
+ * - Honcho: hybrid memory mode + async write + dialectic reasoning
10
+ *
11
+ * 核心职责:
12
+ * 1. 保存:user + assistant 所有消息 → 内存缓冲 → 定期刷到磁盘
13
+ * 2. 空闲检测:idle timeout → 触发上下文压缩 → 保存到长期记忆
14
+ * 3. 启动恢复:读取上次会话 → 注入上下文
15
+ * 4. 上下文注入:格式化 → 可注入 system prompt
16
+ *
17
+ * 关键设计原则(来自 LOOM/Mem0/Honcho):
18
+ * - 不删除:所有消息追加到 .jsonl,只提炼不删除
19
+ * - 分层:volatile (step) → session (convo) → long-term (distilled)
20
+ * - 持久化:SQLite-style 的可靠存储,history 追踪变化
21
+ * - 异步写入:批量写入,避免频繁 IO
22
+ */
23
+
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+
27
+ const DATA_DIR = path.join(__dirname, '..', '..', 'data', 'context-manager');
28
+ const MESSAGES_FILE = path.join(DATA_DIR, 'messages.jsonl');
29
+ const SESSIONS_FILE = path.join(DATA_DIR, 'sessions.jsonl');
30
+ const LONGTERM_FILE = path.join(DATA_DIR, 'longterm-memory.jsonl');
31
+ const META_FILE = path.join(DATA_DIR, 'meta.json');
32
+
33
+ // 空闲阈值:30分钟
34
+ const IDLE_THRESHOLD_MS = 30 * 60 * 1000;
35
+ // 批量写入阈值:累积20条消息或超过5分钟
36
+ const BATCH_SIZE = 20;
37
+ const BATCH_TIMEOUT_MS = 5 * 60 * 1000;
38
+
39
+ // 状态
40
+ let _lastFlush = Date.now();
41
+ let _messageBuffer = [];
42
+ let _sessionMeta = null;
43
+ let _lastActiveTime = Date.now();
44
+ let _idleTimer = null;
45
+ let _initialized = false;
46
+
47
+ // ============================================================
48
+ // 初始化
49
+ // ============================================================
50
+
51
+ function ensureDataDir() {
52
+ if (!fs.existsSync(DATA_DIR)) {
53
+ fs.mkdirSync(DATA_DIR, { recursive: true });
54
+ }
55
+ }
56
+
57
+ function loadMeta() {
58
+ ensureDataDir();
59
+ try {
60
+ if (fs.existsSync(META_FILE)) {
61
+ _sessionMeta = JSON.parse(fs.readFileSync(META_FILE, 'utf8'));
62
+ }
63
+ } catch (e) {
64
+ console.warn(`[ContextManager] loadMeta failed, backing up corrupted file: ${e.message}`);
65
+ const backupPath = META_FILE + '.corrupt.' + Date.now();
66
+ try { fs.renameSync(META_FILE, backupPath); } catch {}
67
+ }
68
+ if (!_sessionMeta) {
69
+ _sessionMeta = {
70
+ sessionId: `sess_${Date.now()}`,
71
+ startedAt: Date.now(),
72
+ totalMessages: 0,
73
+ totalSessions: 0,
74
+ lastMessageAt: null,
75
+ };
76
+ }
77
+ _initialized = true;
78
+ }
79
+
80
+ function saveMeta() {
81
+ if (!_sessionMeta) return;
82
+ try {
83
+ fs.writeFileSync(META_FILE, JSON.stringify(_sessionMeta, null, 2));
84
+ } catch (e) {
85
+ console.error(`[ContextManager] saveMeta failed: ${e.message}`);
86
+ }
87
+ }
88
+
89
+ // SIGTERM handling — flush buffer before exit
90
+ process.on('SIGTERM', () => {
91
+ if (_messageBuffer && _messageBuffer.length > 0) {
92
+ try {
93
+ fs.appendFileSync(MESSAGES_FILE, _messageBuffer.map(m => JSON.stringify(m)).join('\n') + '\n');
94
+ } catch {}
95
+ }
96
+ process.exit(0);
97
+ });
98
+
99
+ // ============================================================
100
+ // 消息保存(核心:user + assistant 所有消息都保存)
101
+ // ============================================================
102
+
103
+ /**
104
+ * 添加消息到缓冲(ADD-only,来自 Mem0 哲学)
105
+ * @param {object} msg - { role: 'user'|'assistant', content: string, metadata?: object }
106
+ */
107
+ function addMessage(msg) {
108
+ if (!_initialized) loadMeta();
109
+
110
+ touch(); // 重置活跃时间
111
+
112
+ const entry = {
113
+ id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
114
+ role: msg.role || 'unknown',
115
+ content: msg.content || '',
116
+ timestamp: msg.timestamp || Date.now(),
117
+ metadata: msg.metadata || {},
118
+ sessionId: _sessionMeta.sessionId,
119
+ };
120
+
121
+ _messageBuffer.push(entry);
122
+ _sessionMeta.totalMessages++;
123
+ _sessionMeta.lastMessageAt = entry.timestamp;
124
+
125
+ // 批量写入检查
126
+ if (_messageBuffer.length >= BATCH_SIZE) {
127
+ flushBuffer();
128
+ }
129
+
130
+ // 触发空闲定时器
131
+ scheduleIdleCheck();
132
+
133
+ return entry;
134
+ }
135
+
136
+ /**
137
+ * 保存用户消息(快捷方法)
138
+ */
139
+ function saveUserMessage(content, metadata = {}) {
140
+ return addMessage({ role: 'user', content, metadata: { source: 'user', ...metadata } });
141
+ }
142
+
143
+ /**
144
+ * 保存助手回复(快捷方法)
145
+ */
146
+ function saveAssistantMessage(content, metadata = {}) {
147
+ return addMessage({ role: 'assistant', content, metadata: { source: 'assistant', ...metadata } });
148
+ }
149
+
150
+ /**
151
+ * 保存交互对(user → assistant)
152
+ */
153
+ function saveInteraction(userMsg, assistantMsg, metadata = {}) {
154
+ const user = saveUserMessage(userMsg, { ...metadata, type: 'user' });
155
+ const assistant = saveAssistantMessage(assistantMsg, { ...metadata, type: 'assistant' });
156
+ return { user, assistant };
157
+ }
158
+
159
+ // ============================================================
160
+ // 批量写入(异步,非阻塞)
161
+ // ============================================================
162
+
163
+ function flushBuffer() {
164
+ if (_messageBuffer.length === 0) return;
165
+
166
+ const toWrite = [..._messageBuffer];
167
+ _messageBuffer = [];
168
+ _lastFlush = Date.now();
169
+
170
+ try {
171
+ const lines = toWrite.map(m => JSON.stringify(m)).join('\n') + '\n';
172
+ fs.appendFileSync(MESSAGES_FILE, lines);
173
+ saveMeta();
174
+ } catch (e) {
175
+ // 写入失败,尝试放回 buffer
176
+ console.error('[ContextManager] 写入失败:', e.message);
177
+ _messageBuffer.unshift(...toWrite);
178
+ }
179
+ }
180
+
181
+ /**
182
+ * 定期 flush(防止数据丢失)
183
+ */
184
+ function scheduleIdleCheck() {
185
+ if (_idleTimer) clearTimeout(_idleTimer);
186
+ _idleTimer = setTimeout(() => {
187
+ if (Date.now() - _lastFlush > BATCH_TIMEOUT_MS) {
188
+ flushBuffer();
189
+ }
190
+ checkIdleAndSave();
191
+ }, BATCH_TIMEOUT_MS);
192
+ }
193
+
194
+ // ============================================================
195
+ // 空闲检测 → 上下文压缩 → 长期记忆
196
+ // ============================================================
197
+
198
+ function touch() {
199
+ _lastActiveTime = Date.now();
200
+ }
201
+
202
+ function getIdleTime() {
203
+ return Date.now() - _lastActiveTime;
204
+ }
205
+
206
+ function isIdle() {
207
+ return getIdleTime() > IDLE_THRESHOLD_MS;
208
+ }
209
+
210
+ function formatIdle(ms) {
211
+ const m = Math.floor(ms / 60000);
212
+ return m < 60 ? `${m}分钟` : `${Math.floor(m/60)}小时${m%60}分钟`;
213
+ }
214
+
215
+ /**
216
+ * 空闲时触发:保存会话快照 + 提炼到长期记忆
217
+ */
218
+ function checkIdleAndSave() {
219
+ if (!isIdle()) return null;
220
+
221
+ console.log(`[ContextManager] 检测到空闲: ${formatIdle(getIdleTime())}`);
222
+
223
+ // 1. 强制 flush 所有缓冲
224
+ flushBuffer();
225
+
226
+ // 2. 加载最近消息并保存会话快照
227
+ const snapshot = saveSessionSnapshot();
228
+
229
+ // 3. 提炼到长期记忆(不是删除,是精华提取)
230
+ if (snapshot) {
231
+ distillToLongTermMemory(snapshot);
232
+ }
233
+
234
+ // 4. 开始新会话
235
+ startNewSession();
236
+
237
+ return snapshot;
238
+ }
239
+
240
+ /**
241
+ * 手动触发保存(退出时调用)
242
+ */
243
+ function saveAndDistill() {
244
+ flushBuffer();
245
+ const snapshot = saveSessionSnapshot();
246
+ if (snapshot) {
247
+ distillToLongTermMemory(snapshot);
248
+ }
249
+ startNewSession(); // 开始新会话
250
+ return snapshot;
251
+ }
252
+
253
+ // ============================================================
254
+ // 会话快照
255
+ // ============================================================
256
+
257
+ function saveSessionSnapshot() {
258
+ ensureDataDir();
259
+
260
+ const messages = loadRecentMessages(100);
261
+ if (messages.length === 0) return null;
262
+
263
+ const snapshot = {
264
+ id: `snap_${Date.now()}`,
265
+ sessionId: _sessionMeta.sessionId,
266
+ timestamp: Date.now(),
267
+ startedAt: _sessionMeta.startedAt,
268
+ messageCount: messages.length,
269
+ firstMessage: messages[0]?.content?.substring(0, 100),
270
+ lastMessage: messages[messages.length - 1]?.content?.substring(0, 100),
271
+ // 消息按 role 分组统计
272
+ stats: {
273
+ user: messages.filter(m => m.role === 'user').length,
274
+ assistant: messages.filter(m => m.role === 'assistant').length,
275
+ },
276
+ // 关键提取(用于快速摘要)
277
+ keyContent: extractKeyContent(messages),
278
+ metadata: {
279
+ idleTriggered: isIdle(),
280
+ savedAt: new Date().toISOString(),
281
+ },
282
+ };
283
+
284
+ try {
285
+ fs.appendFileSync(SESSIONS_FILE, JSON.stringify(snapshot) + '\n');
286
+ _sessionMeta.totalSessions++;
287
+ saveMeta();
288
+ console.log(`[ContextManager] 会话快照保存: ${messages.length}条消息`);
289
+ return snapshot;
290
+ } catch (e) {
291
+ console.error('[ContextManager] 快照保存失败:', e.message);
292
+ return null;
293
+ }
294
+ }
295
+
296
+ /**
297
+ * 提炼关键内容(结构化提取,来自 session-summarizer 的进化)
298
+ */
299
+ function extractKeyContent(messages) {
300
+ const content = messages.map(m => m.content).join(' ');
301
+
302
+ const result = {
303
+ versions: [],
304
+ gitOps: [],
305
+ commands: [],
306
+ decisions: [],
307
+ problems: [],
308
+ paths: [],
309
+ };
310
+
311
+ // 版本号
312
+ const vMatch = content.match(/\bv?(\d+\.\d+\.\d+)\b/g);
313
+ if (vMatch) result.versions = [...new Set(vMatch)].slice(0, 5);
314
+
315
+ // Git 操作
316
+ const gitPatterns = /\b(git\s+\w+|commit\s+[a-f0-9]+|push|branch|merge|pull)\b/gi;
317
+ const gitMatch = content.match(gitPatterns);
318
+ if (gitMatch) result.gitOps = [...new Set(gitMatch)].slice(0, 5);
319
+
320
+ // 命令
321
+ const cmdPatterns = /\b(?:npm|pip|python|node|git|curl)\s+[\w-]+/gi;
322
+ const cmdMatch = content.match(cmdPatterns);
323
+ if (cmdMatch) result.commands = [...new Set(cmdMatch)].slice(0, 5);
324
+
325
+ // 决策
326
+ if (/决定|选择|采用|确认|批准|启动|停止|创建|删除/.test(content)) {
327
+ const decs = messages
328
+ .filter(m => /决定|选择|采用|确认/.test(m.content))
329
+ .map(m => m.content.substring(0, 80));
330
+ result.decisions = [...new Set(decs)].slice(0, 3);
331
+ }
332
+
333
+ // 问题
334
+ if (/问题|错误|失败|修复|解决|bug/.test(content)) {
335
+ const probs = messages
336
+ .filter(m => /问题|错误|失败|bug/.test(m.content))
337
+ .map(m => m.content.substring(0, 80));
338
+ result.problems = [...new Set(probs)].slice(0, 3);
339
+ }
340
+
341
+ // 路径
342
+ const pathMatch = content.match(/\/[\w.-]+\/[\w.-]+\/[\w./-]+/g);
343
+ if (pathMatch) {
344
+ result.paths = [...new Set(pathMatch)].map(p => p.split('/').slice(-2).join('/')).slice(0, 5);
345
+ }
346
+
347
+ return result;
348
+ }
349
+
350
+ // ============================================================
351
+ // 长期记忆(提炼保存,不删除)
352
+ // ============================================================
353
+
354
+ /**
355
+ * 将会话快照提炼保存到长期记忆
356
+ * 核心原则:不是删除,是精华提取
357
+ */
358
+ function distillToLongTermMemory(snapshot) {
359
+ ensureDataDir();
360
+
361
+ const memories = [];
362
+ const kc = snapshot.keyContent;
363
+
364
+ // 1. 版本记忆(存原始值,显示时统一加前缀)
365
+ if (kc.versions?.length > 0) {
366
+ kc.versions.forEach(v => {
367
+ memories.push({
368
+ type: 'version',
369
+ content: v, // "v11.22.6" - 原始值
370
+ timestamp: snapshot.timestamp,
371
+ sessionId: snapshot.sessionId,
372
+ source: 'distill',
373
+ });
374
+ });
375
+ }
376
+
377
+ // 2. Git 操作记忆
378
+ if (kc.gitOps?.length > 0) {
379
+ memories.push({
380
+ type: 'git',
381
+ content: kc.gitOps.join(', '), // 原始值
382
+ timestamp: snapshot.timestamp,
383
+ sessionId: snapshot.sessionId,
384
+ source: 'distill',
385
+ });
386
+ }
387
+
388
+ // 3. 命令记忆
389
+ if (kc.commands?.length > 0) {
390
+ memories.push({
391
+ type: 'command',
392
+ content: kc.commands.join(', '), // 原始值
393
+ timestamp: snapshot.timestamp,
394
+ sessionId: snapshot.sessionId,
395
+ source: 'distill',
396
+ });
397
+ }
398
+
399
+ // 4. 决策记忆(最重要)
400
+ if (kc.decisions?.length > 0) {
401
+ kc.decisions.forEach(d => {
402
+ memories.push({
403
+ type: 'decision',
404
+ content: d,
405
+ timestamp: snapshot.timestamp,
406
+ sessionId: snapshot.sessionId,
407
+ source: 'distill',
408
+ });
409
+ });
410
+ }
411
+
412
+ // 5. 问题记忆
413
+ if (kc.problems?.length > 0) {
414
+ kc.problems.forEach(p => {
415
+ memories.push({
416
+ type: 'problem',
417
+ content: p,
418
+ timestamp: snapshot.timestamp,
419
+ sessionId: snapshot.sessionId,
420
+ source: 'distill',
421
+ });
422
+ });
423
+ }
424
+
425
+ // 6. 路径记忆
426
+ if (kc.paths?.length > 0) {
427
+ memories.push({
428
+ type: 'path',
429
+ content: kc.paths.join(', '), // 原始值
430
+ timestamp: snapshot.timestamp,
431
+ sessionId: snapshot.sessionId,
432
+ source: 'distill',
433
+ });
434
+ }
435
+
436
+ // 7. 会话摘要(如果什么都没有,至少保存一句话)
437
+ if (memories.length === 0) {
438
+ memories.push({
439
+ type: 'summary',
440
+ content: snapshot.lastMessage || '对话完成',
441
+ timestamp: snapshot.timestamp,
442
+ sessionId: snapshot.sessionId,
443
+ source: 'distill',
444
+ });
445
+ }
446
+
447
+ // 写入长期记忆文件
448
+ if (memories.length > 0) {
449
+ try {
450
+ const lines = memories.map(m => JSON.stringify(m)).join('\n') + '\n';
451
+ fs.appendFileSync(LONGTERM_FILE, lines);
452
+ console.log(`[ContextManager] 提炼到长期记忆: +${memories.length}条`);
453
+ } catch (e) {
454
+ console.error('[ContextManager] 长期记忆写入失败:', e.message);
455
+ }
456
+ }
457
+
458
+ return memories;
459
+ }
460
+
461
+ // ============================================================
462
+ // 加载消息
463
+ // ============================================================
464
+
465
+ function loadRecentMessages(limit = 100) {
466
+ if (!fs.existsSync(MESSAGES_FILE)) return [];
467
+
468
+ try {
469
+ const lines = fs.readFileSync(MESSAGES_FILE, 'utf8')
470
+ .trim().split('\n').filter(Boolean)
471
+ .slice(-limit);
472
+ return lines.map(l => {
473
+ try { return JSON.parse(l); } catch { return null; }
474
+ }).filter(Boolean);
475
+ } catch {
476
+ return [];
477
+ }
478
+ }
479
+
480
+ function loadRecentSessions(limit = 10) {
481
+ if (!fs.existsSync(SESSIONS_FILE)) return [];
482
+
483
+ try {
484
+ const lines = fs.readFileSync(SESSIONS_FILE, 'utf8')
485
+ .trim().split('\n').filter(Boolean)
486
+ .slice(-limit);
487
+ return lines.map(l => {
488
+ try { return JSON.parse(l); } catch { return null; }
489
+ }).filter(Boolean);
490
+ } catch {
491
+ return [];
492
+ }
493
+ }
494
+
495
+ function loadLongTermMemories(limit = 50) {
496
+ if (!fs.existsSync(LONGTERM_FILE)) return [];
497
+
498
+ try {
499
+ const lines = fs.readFileSync(LONGTERM_FILE, 'utf8')
500
+ .trim().split('\n').filter(Boolean)
501
+ .slice(-limit);
502
+ return lines.map(l => {
503
+ try { return JSON.parse(l); } catch { return null; }
504
+ }).filter(Boolean);
505
+ } catch {
506
+ return [];
507
+ }
508
+ }
509
+
510
+ // ============================================================
511
+ // 启动上下文构建
512
+ // ============================================================
513
+
514
+ /**
515
+ * 构建启动时注入的上下文
516
+ */
517
+ function buildStartupContext() {
518
+ const latestSession = loadRecentSessions(1)[0];
519
+ const longTermMemories = loadLongTermMemories(30);
520
+
521
+ if (!latestSession && longTermMemories.length === 0) {
522
+ return null;
523
+ }
524
+
525
+ const parts = [];
526
+ const now = Date.now();
527
+
528
+ parts.push('═'.repeat(44));
529
+ parts.push('【启动上下文】');
530
+
531
+ // 上次会话
532
+ if (latestSession) {
533
+ const idleFor = now - latestSession.timestamp;
534
+ parts.push(`\n上次会话: ${new Date(latestSession.timestamp).toLocaleString()}`);
535
+ parts.push(`消息数: ${latestSession.messageCount} (user:${latestSession.stats.user}/assistant:${latestSession.stats.assistant})`);
536
+ parts.push(`间隔: ${formatIdle(idleFor)}`);
537
+
538
+ // 显示关键提取
539
+ const kc = latestSession.keyContent;
540
+ if (kc.versions?.length) parts.push(`版本: ${kc.versions.join(', ')}`);
541
+ if (kc.decisions?.length) parts.push(`决策: ${kc.decisions[0]}`);
542
+ }
543
+
544
+ // 长期记忆(跨会话)
545
+ if (longTermMemories.length > 0) {
546
+ parts.push(`\n【长期记忆】(${longTermMemories.length}条)`);
547
+
548
+ // 按类型分组显示
549
+ const byType = {};
550
+ longTermMemories.slice(-20).forEach(m => {
551
+ if (!byType[m.type]) byType[m.type] = [];
552
+ byType[m.type].push(m.content);
553
+ });
554
+
555
+ const labelMap = {
556
+ version: '版本',
557
+ git: 'Git',
558
+ command: '命令',
559
+ decision: '决策',
560
+ problem: '问题',
561
+ path: '路径',
562
+ summary: '摘要',
563
+ core_directive: '核心指令',
564
+ lesson: '教训',
565
+ workflow: '工作流',
566
+ user_info: '用户信息'
567
+ };
568
+ Object.entries(byType).slice(0, 5).forEach(([type, items]) => {
569
+ const label = labelMap[type] || type;
570
+ const unique = [...new Set(items)].slice(0, 3);
571
+ // content 存的是原始值(如 "v11.22.6"),显示时加标签
572
+ unique.forEach(item => parts.push(` ${label}: ${item.substring(0, 60)}`));
573
+ });
574
+ }
575
+
576
+ parts.push('\n' + '═'.repeat(44));
577
+
578
+ return {
579
+ session: latestSession,
580
+ longTermMemories,
581
+ context: parts.join('\n'),
582
+ injectableContext: parts.join('\n'),
583
+ idleTime: latestSession ? now - latestSession.timestamp : null,
584
+ };
585
+ }
586
+
587
+ // ============================================================
588
+ // 启动新会话
589
+ // ============================================================
590
+
591
+ function startNewSession() {
592
+ _sessionMeta.sessionId = `sess_${Date.now()}`;
593
+ _sessionMeta.startedAt = Date.now();
594
+ saveMeta();
595
+ console.log(`[ContextManager] 新会话: ${_sessionMeta.sessionId}`);
596
+ }
597
+
598
+ // ============================================================
599
+ // 搜索长期记忆
600
+ // ============================================================
601
+
602
+ function searchLongTermMemories(query, limit = 10) {
603
+ const memories = loadLongTermMemories(100);
604
+ const ql = query.toLowerCase();
605
+
606
+ const scored = memories.map(m => {
607
+ let score = 0;
608
+ const text = (m.content || '').toLowerCase();
609
+ if (text.includes(ql)) score += 2;
610
+ if (m.type === 'decision' && /决定|选择|采用/.test(query)) score += 3;
611
+ if (m.type === 'problem' && /问题|错误|修复/.test(query)) score += 2;
612
+ return { ...m, _score: score };
613
+ }).filter(m => m._score > 0)
614
+ .sort((a, b) => b._score - a._score)
615
+ .slice(0, limit);
616
+
617
+ return scored;
618
+ }
619
+
620
+ // ============================================================
621
+ // 统计
622
+ // ============================================================
623
+
624
+ function getStats() {
625
+ if (!_initialized) loadMeta();
626
+
627
+ const messages = loadRecentMessages(10000);
628
+ const sessions = loadRecentSessions(100);
629
+ const longTerm = loadLongTermMemories(1000);
630
+
631
+ return {
632
+ currentSession: _sessionMeta.sessionId,
633
+ bufferSize: _messageBuffer.length,
634
+ totalMessages: _sessionMeta.totalMessages,
635
+ totalSessions: _sessionMeta.totalSessions,
636
+ lastMessageAt: _sessionMeta.lastMessageAt,
637
+ idleTime: getIdleTime(),
638
+ fileStats: {
639
+ messagesFile: messages.length,
640
+ sessionsFile: sessions.length,
641
+ longTermFile: longTerm.length,
642
+ },
643
+ };
644
+ }
645
+
646
+ // ============================================================
647
+ // 模块初始化
648
+ // ============================================================
649
+
650
+ loadMeta();
651
+
652
+ // 进程退出时保存
653
+ process.on('exit', () => { flushBuffer(); });
654
+ process.on('SIGINT', () => { saveAndDistill(); process.exit(0); });
655
+
656
+ module.exports = {
657
+ // 保存
658
+ addMessage,
659
+ saveUserMessage,
660
+ saveAssistantMessage,
661
+ saveInteraction,
662
+ flushBuffer,
663
+
664
+ // 空闲管理
665
+ touch,
666
+ isIdle,
667
+ getIdleTime,
668
+ checkIdleAndSave,
669
+ saveAndDistill,
670
+
671
+ // 加载
672
+ loadRecentMessages,
673
+ loadRecentSessions,
674
+ loadLongTermMemories,
675
+ buildStartupContext,
676
+
677
+ // 搜索
678
+ searchLongTermMemories,
679
+
680
+ // 工具
681
+ startNewSession,
682
+ getStats,
683
+ };