evolcore 0.0.40 → 0.0.41-test.1

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 (226) hide show
  1. package/CHANGELOG.md +94 -1
  2. package/bin/codex-managed-hook.mjs +11 -0
  3. package/bin/ec-safe-output.js +11 -1
  4. package/dist/agents/baseagent-availability.js +1 -1
  5. package/dist/agents/baseagent.js +20 -43
  6. package/dist/agents/claude-runner.js +197 -197
  7. package/dist/agents/codex-runner.js +535 -259
  8. package/dist/agents/ecagent-runner.js +31 -12
  9. package/dist/agents/gemini-runner.js +27 -7
  10. package/dist/agents/runner-types.js +11 -3
  11. package/dist/aun/ability-device-routing.js +26 -0
  12. package/dist/aun/aid/client.js +1 -1
  13. package/dist/aun/group/fs-download.js +39 -0
  14. package/dist/aun/group/identity.js +36 -13
  15. package/dist/aun/group/operations.js +5 -0
  16. package/dist/aun/msg/managed-operation.js +72 -11
  17. package/dist/aun/msg/p2p.js +32 -7
  18. package/dist/aun/service-proxy.js +36 -12
  19. package/dist/aun/storage/download.js +30 -0
  20. package/dist/aun/storage/index.js +14 -6
  21. package/dist/channels/aun.js +367 -24
  22. package/dist/channels/daemon.js +39 -5
  23. package/dist/cli/agent-command.js +2 -0
  24. package/dist/cli/agent-create.js +98 -19
  25. package/dist/cli/agent.js +10 -3
  26. package/dist/cli/aun-commands.js +85 -41
  27. package/dist/cli/daemon-commands.js +678 -688
  28. package/dist/cli/fs-command.js +64 -2
  29. package/dist/cli/index.js +48 -4
  30. package/dist/cli/managed-command-guard.js +4 -0
  31. package/dist/cli/model.js +40 -40
  32. package/dist/cli/proxy-command.js +92 -0
  33. package/dist/cli/restart-monitor.js +17 -0
  34. package/dist/cli/role.js +85 -0
  35. package/dist/cli/session-command.js +128 -13
  36. package/dist/cli/stats.js +60 -4
  37. package/dist/cli/trigger-command.js +2 -2
  38. package/dist/config/access-policy.js +8 -1
  39. package/dist/config/boot-log.js +38 -1
  40. package/dist/config/config-field-policy.js +5 -32
  41. package/dist/config/config-manager.js +46 -39
  42. package/dist/config/config-operation-service.js +8 -11
  43. package/dist/config/contact-book-store.js +47 -21
  44. package/dist/config/contact-book.js +18 -12
  45. package/dist/config/contact-operation-service.js +3 -4
  46. package/dist/config/contact-request-service.js +11 -0
  47. package/dist/config/daemon-services.js +11 -0
  48. package/dist/config/gateway-config.js +89 -595
  49. package/dist/config/peer-role-resolver.js +15 -11
  50. package/dist/config/providers-config.js +12 -7
  51. package/dist/config/providers-import.js +3 -21
  52. package/dist/config/resolved-config-op.js +3 -0
  53. package/dist/config/role-command-service.js +166 -0
  54. package/dist/config/role-request-service.js +193 -0
  55. package/dist/config/schema-migration.js +686 -25
  56. package/dist/config-store.js +79 -3
  57. package/dist/contracts/ecweb-instance.js +41 -0
  58. package/dist/contracts/ecweb-service-protocol.js +3 -1
  59. package/dist/core/agent-application-service.js +11 -1
  60. package/dist/core/agent-ipc-registration.js +4 -0
  61. package/dist/core/agent-runtime.js +1 -1
  62. package/dist/core/auth/agent-delegation.js +82 -6
  63. package/dist/core/auth/auth-gateway.js +1 -1
  64. package/dist/core/auth/authorization-audit.js +37 -9
  65. package/dist/core/auth/delegation-authorization.js +3 -1
  66. package/dist/core/auth/operation-authorizer.js +15 -0
  67. package/dist/core/auth/operation-catalog.js +39 -6
  68. package/dist/core/command/agent-control.js +94 -19
  69. package/dist/core/command/agent-storage-menu.js +5 -3
  70. package/dist/core/command/cli-intent-parser.js +2 -1
  71. package/dist/core/command/command-handler.js +105 -145
  72. package/dist/core/command/connect-menu.js +31 -2
  73. package/dist/core/command/data-root-resolver.js +5 -4
  74. package/dist/core/command/memory-slash.js +16 -8
  75. package/dist/core/command/menu-catalog.js +6 -6
  76. package/dist/core/command/menu-handler.js +87 -163
  77. package/dist/core/command/menu-protocol.js +9 -2
  78. package/dist/core/command/role-menu.js +148 -30
  79. package/dist/core/command/slash-gate.js +13 -10
  80. package/dist/core/command/slash-handler.js +157 -352
  81. package/dist/core/daemon-control.js +8 -14
  82. package/dist/core/event-catalog.js +15 -0
  83. package/dist/core/evolagent-registry.js +4 -4
  84. package/dist/core/evolagent.js +2 -2
  85. package/dist/core/inference/text-inference.js +31 -40
  86. package/dist/core/ipc-registration.js +24 -3
  87. package/dist/core/memory/consolidation-context.js +51 -5
  88. package/dist/core/memory/consolidation-ops-records.js +1 -1
  89. package/dist/core/memory/consolidation-trigger.js +190 -190
  90. package/dist/core/memory/consolidation.js +316 -29
  91. package/dist/core/memory/forget-log.js +96 -0
  92. package/dist/core/memory/index-manager.js +27 -5
  93. package/dist/core/memory/memory-admin.js +45 -5
  94. package/dist/core/memory/memory-writer.js +163 -18
  95. package/dist/core/memory/relation-idle-monitor.js +119 -58
  96. package/dist/core/memory/relation-sweep.js +44 -39
  97. package/dist/core/message/aun-ipc-sender.js +34 -7
  98. package/dist/core/message/aun-request-registry.js +97 -3
  99. package/dist/core/message/im-renderer.js +11 -4
  100. package/dist/core/message/message-admission.js +97 -8
  101. package/dist/core/message/message-bridge.js +71 -24
  102. package/dist/core/message/message-log.js +55 -0
  103. package/dist/core/message/message-queue.js +5 -5
  104. package/dist/core/message/response-engine.js +387 -144
  105. package/dist/core/model/catalog-service.js +4 -2
  106. package/dist/core/model/config-scope.js +24 -64
  107. package/dist/core/model/field-scope.js +1 -1
  108. package/dist/core/model/model-catalog.js +37 -47
  109. package/dist/core/model/model-diagnostics.js +4 -3
  110. package/dist/core/model/model-fallback.js +10 -7
  111. package/dist/core/model/model-permission.js +3 -2
  112. package/dist/core/ownership/owner-resolver.js +25 -23
  113. package/dist/core/permission/ec-command-parser.js +138 -5
  114. package/dist/core/permission/sandbox-runtime.js +18 -1
  115. package/dist/core/permission/tool-policy.js +42 -10
  116. package/dist/core/relation/peer-identity.js +64 -1
  117. package/dist/core/role/runtime-policy.js +72 -13
  118. package/dist/core/session/session-capsule.js +197 -0
  119. package/dist/core/session/session-idle-monitor.js +1 -1
  120. package/dist/core/session/session-manager.js +168 -14
  121. package/dist/core/session/session-mapper.js +2 -0
  122. package/dist/core/session/session-renew.js +3 -3
  123. package/dist/core/skill/index-generator.js +15 -5
  124. package/dist/core/system-session/memory.js +6 -1
  125. package/dist/core/thread/thread-service.js +19 -6
  126. package/dist/directory/owner-directory-admission.js +95 -0
  127. package/dist/directory/owner-directory-authorization.js +309 -0
  128. package/dist/directory/owner-directory-cache.js +635 -0
  129. package/dist/eck/kit-renderer.js +2 -2
  130. package/dist/ecweb/basic-settings-service.js +33 -40
  131. package/dist/ecweb/message-context-service.js +110 -0
  132. package/dist/index.js +79 -17
  133. package/dist/ipc.js +189 -17
  134. package/dist/paths.js +4 -0
  135. package/dist/proxy/command.js +122 -0
  136. package/dist/proxy/ipc-service.js +68 -0
  137. package/dist/proxy/manager.js +485 -0
  138. package/dist/proxy/service-supervisor.js +603 -0
  139. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  140. package/dist/stats/budget.js +1 -1
  141. package/dist/stats/db.js +15 -0
  142. package/dist/stats/index.js +2 -2
  143. package/dist/stats/price-resolver.js +304 -5
  144. package/dist/stats/query.js +82 -3
  145. package/dist/stats/writer.js +38 -5
  146. package/dist/trigger/feedback.js +18 -7
  147. package/dist/trigger/manager.js +20 -3
  148. package/dist/trigger/parser.js +6 -3
  149. package/dist/trigger/patch.js +1 -1
  150. package/dist/trigger/system-definitions.js +43 -7
  151. package/dist/trigger/validation.js +13 -5
  152. package/dist/utils/cross-platform.js +14 -0
  153. package/dist/utils/ecweb-supervisor.js +258 -83
  154. package/dist/utils/error-utils.js +16 -2
  155. package/dist/utils/logger.js +24 -5
  156. package/dist/utils/npm-ops.js +2 -1
  157. package/dist/utils/package-version-info.js +5 -3
  158. package/dist/utils/upgrade-jobs.js +45 -5
  159. package/kits/docs/INDEX.md +1 -1
  160. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  161. package/kits/docs/channels/aun.md +9 -0
  162. package/kits/docs/evolcore/INDEX.md +2 -1
  163. package/kits/docs/evolcore/agent-create.md +3 -2
  164. package/kits/docs/evolcore/agent.md +1 -1
  165. package/kits/docs/evolcore/config.md +18 -7
  166. package/kits/docs/evolcore/contact.md +3 -0
  167. package/kits/docs/evolcore/event.md +1 -0
  168. package/kits/docs/evolcore/fs.md +16 -0
  169. package/kits/docs/evolcore/memory-architecture.md +2 -2
  170. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  171. package/kits/docs/evolcore/memory.md +1 -1
  172. package/kits/docs/evolcore/menu-protocol.md +36 -0
  173. package/kits/docs/evolcore/model.md +23 -20
  174. package/kits/docs/evolcore/msg.md +21 -8
  175. package/kits/docs/evolcore/session.md +14 -0
  176. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  177. package/kits/schemas/_meta.json +37 -4
  178. package/kits/schemas/agent-config.schema.13.json +23 -3
  179. package/kits/schemas/agent-config.schema.16.json +891 -0
  180. package/kits/schemas/daemon.schema.9.json +366 -0
  181. package/kits/schemas/defaults.schema.5.json +406 -127
  182. package/kits/schemas/relation-config.schema.11.json +260 -0
  183. package/kits/schemas/role-config.schema.1.json +7 -7
  184. package/kits/skills/.switches.json +3 -7
  185. package/kits/skills/aid-ability/SKILL.md +35 -6
  186. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  187. package/kits/skills/ec-trigger/SKILL.md +13 -5
  188. package/kits/skills/personal-assistant/SKILL.md +176 -0
  189. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  190. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  191. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  192. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  193. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  194. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  195. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  196. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  197. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  198. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  199. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  200. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  201. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  202. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  203. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  204. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  205. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  206. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  207. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  208. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  209. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  210. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  211. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  212. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  213. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  214. package/kits/templates/memory-consolidation/forget.md +19 -6
  215. package/kits/templates/memory-consolidation/notes.md +1 -1
  216. package/kits/templates/memory-consolidation/profile.md +2 -2
  217. package/kits/templates/memory-consolidation/promote.md +20 -3
  218. package/kits/templates/roles/member.json +8 -1
  219. package/kits/templates/session-capsule/recovery.md +5 -0
  220. package/kits/templates/session-capsule/renew.md +5 -0
  221. package/kits/templates/system-fragments/baseagent.md +2 -2
  222. package/kits/templates/system-fragments/bootstrap.md +6 -6
  223. package/kits/templates/system-fragments/channel.md +1 -1
  224. package/kits/templates/system-fragments/memory.md +4 -4
  225. package/package.json +7 -3
  226. package/dist/stats/billing.js +0 -215
@@ -1,17 +1,16 @@
1
1
  /**
2
- * consolidation-trigger.ts — 整理候选判据(v5,纯函数)
2
+ * consolidation-trigger.ts — 整理候选判据(v6,纯函数)
3
3
  *
4
- * 整理一律以关系为单位。两类判据:
4
+ * 整理一律以关系为单位,按驱动方式分两类:
5
5
  *
6
- * **关系级**(`isRelationModeDue`,供关系整理链逐步调用,见 relation-sweep.ts):
7
- * notes pending/ 里有 note
8
- * generalize 本关系有 to-generalize
9
- * promote 本关系是 owner 关系且有 to-promote
10
- * profile 索引有变化且距上次画像超过 profileRegenDays(或还没有画像)
11
- * forget 本关系有超期记忆
6
+ * **内容驱动**(`judgeRelationMode`,关系整理链逐步调用,见 relation-sweep.ts):
7
+ * notes pending/ 里的 note 条数
8
+ * generalize 本关系 to-generalize 条数
9
+ * promote 本关系是 owner 关系时的 to-promote 条数
10
+ * 空闲到期拉起的链:条数 ≥ minBatchItems 才跑,不够推迟;兜底到期拉起的链:有 1 条就跑。
12
11
  *
13
- * **全局定时检查**(`checkConsolidationCandidates`,cron script 驱动):只管不属于任何关系的部分——
14
- * agent 层 / owner 层 forget,外加 pending 堆积超过 backlogHours 的兜底。
12
+ * **时间驱动**(`checkConsolidationCandidates`,cron script 每小时驱动):逐关系 / 逐层检查——
13
+ * 关系画像到期 → profile;关系层 / agent 层 / owner 层有超期记忆 → forget。
15
14
  *
16
15
  * 判据是**数文件和数标签**,不看轮次和工具调用次数。本模块不持有进程内状态,判据都读磁盘;
17
16
  * 关系的空闲 / 兜底计时在 relation-idle-monitor.ts。
@@ -22,8 +21,9 @@ import { getPackageRoot, resolveRoot } from '../../paths.js';
22
21
  import { atomicWriteJson } from '../../utils/atomic-write.js';
23
22
  import { normalizeTriggerDefinition } from '../../trigger/validation.js';
24
23
  import { DEFAULT_FORGET_AFTER_DAYS, collectCandidates, isDueForReview, deferCandidate, } from './staleness.js';
25
- import { readMemoryMeta } from './index-manager.js';
26
- import { getMemoryArray, parseMemoryDocument } from './memory-document.js';
24
+ import { memoryTimeMs, readMemoryMeta } from './index-manager.js';
25
+ import { getMemoryArray, getMemoryString, parseMemoryDocument } from './memory-document.js';
26
+ import { isNonAgentSessionChannel } from '../system-channels.js';
27
27
  /**
28
28
  * 走 `_meta.json` 快路径的规模阈值:本机 agent × 关系数超过此值才启用。
29
29
  * 小规模下全量扫描开销可忽略,且无元数据陈旧风险,故作为默认。
@@ -62,7 +62,7 @@ export function seedConsolidationCheckTrigger(manager, owner, packageRoot = getP
62
62
  permissionMode: 'bypass', onError: 'fail', noopSentinel: '[[NOOP]]',
63
63
  },
64
64
  feedback: { strategy: 'silent' },
65
- reliability: { concurrency: 'forbid', missedPolicy: 'run_once', retry: { maxAttempts: 0, backoffMs: 30_000 } },
65
+ reliability: { concurrency: 'forbid', missedPolicy: 'run_once', retry: { maxAttempts: 1, backoffMs: 30_000 } },
66
66
  });
67
67
  const dir = manager.triggerDir(definition.id);
68
68
  fs.mkdirSync(dir, { recursive: true });
@@ -103,61 +103,82 @@ async function main() {
103
103
  main().catch(error => { process.stdout.write(JSON.stringify({ outcome: 'error', text: String(error && error.message || error), files: [] })); process.exitCode = 1; });
104
104
  `;
105
105
  }
106
- const DEFAULT_BACKLOG_HOURS = 24;
107
106
  const DEFAULT_PROFILE_REGEN_DAYS = 3;
107
+ /** 空闲到期时,一步至少攒够这么多条候选才跑。 */
108
+ export const DEFAULT_MIN_BATCH_ITEMS = 3;
109
+ const DAY_MS = 24 * 60 * 60 * 1000;
108
110
  function effectiveConfig(config) {
109
111
  const c = config ?? {};
110
112
  return {
111
113
  enableRelation: c.enableRelation ?? true,
112
114
  enableAgent: c.enableAgent ?? true,
113
115
  enableOwner: c.enableOwner ?? true,
114
- backlogHours: c.backlogHours ?? DEFAULT_BACKLOG_HOURS,
116
+ minBatchItems: typeof c.minBatchItems === 'number' && c.minBatchItems >= 1
117
+ ? Math.floor(c.minBatchItems)
118
+ : DEFAULT_MIN_BATCH_ITEMS,
115
119
  forgetAfterDays: c.forgetAfterDays ?? DEFAULT_FORGET_AFTER_DAYS,
116
120
  profileRegenDays: c.profileRegenDays ?? DEFAULT_PROFILE_REGEN_DAYS,
117
121
  };
118
122
  }
123
+ /**
124
+ * 这个 peerKey 是不是真实对端的关系。daemon / 系统渠道、`bg:` / `trigger:` 伪对端不是——
125
+ * 旧版本把系统会话的伪对端当关系写过记忆,留下了 `daemon#bg%3A...` 这类目录,不能拿来整理。
126
+ */
127
+ export function isConsolidatableRelation(peerKey) {
128
+ const idx = peerKey.indexOf('#');
129
+ if (idx <= 0)
130
+ return false;
131
+ if (isNonAgentSessionChannel(peerKey.slice(0, idx)))
132
+ return false;
133
+ let peerId;
134
+ try {
135
+ peerId = decodeURIComponent(peerKey.slice(idx + 1));
136
+ }
137
+ catch {
138
+ return false;
139
+ }
140
+ return !!peerId && !peerId.startsWith('bg:') && !peerId.startsWith('trigger:');
141
+ }
119
142
  function relationMemoryDir(root, selfAid, peerKey) {
120
143
  return path.join(root, 'agents', selfAid, 'relations', peerKey, 'memory');
121
144
  }
122
- /** pending/ 里最老一条 note 距今多少小时(没有 note 返回 -1)。 */
123
- function pendingBacklogHours(pendingDir, now) {
145
+ /** pending/ 里待整理的 note 条数。 */
146
+ function countPendingNotes(pendingDir) {
124
147
  if (!fs.existsSync(pendingDir))
125
- return -1;
126
- let oldest;
127
- for (const f of fs.readdirSync(pendingDir)) {
128
- if (!f.endsWith('.md'))
129
- continue;
130
- try {
131
- const m = fs.statSync(path.join(pendingDir, f)).mtimeMs;
132
- if (oldest === undefined || m < oldest)
133
- oldest = m;
134
- }
135
- catch { /* ignore */ }
148
+ return 0;
149
+ try {
150
+ return fs.readdirSync(pendingDir).filter(f => f.endsWith('.md')).length;
151
+ }
152
+ catch {
153
+ return 0;
136
154
  }
137
- if (oldest === undefined)
138
- return -1;
139
- return (now - oldest) / (60 * 60 * 1000);
140
155
  }
141
156
  /** 扫这些关系的 consolidated/,数带指定标签的文件。 */
142
157
  function findTagged(root, selfAid, peerKeys, tag) {
143
158
  let count = 0;
144
159
  for (const peerKey of peerKeys) {
145
160
  const dir = path.join(relationMemoryDir(root, selfAid, peerKey), 'consolidated');
146
- if (!fs.existsSync(dir))
161
+ count += countTaggedIn(dir, tag);
162
+ }
163
+ return count > 0 ? { count } : null;
164
+ }
165
+ /** 数一个 consolidated/ 目录里带某标签的记忆。 */
166
+ export function countTaggedIn(dir, tag) {
167
+ if (!fs.existsSync(dir))
168
+ return 0;
169
+ let count = 0;
170
+ for (const f of fs.readdirSync(dir)) {
171
+ if (!f.endsWith('.md'))
147
172
  continue;
148
- for (const f of fs.readdirSync(dir)) {
149
- if (!f.endsWith('.md'))
150
- continue;
151
- try {
152
- const content = fs.readFileSync(path.join(dir, f), 'utf-8');
153
- const tags = getMemoryArray(parseMemoryDocument(content), 'tags');
154
- if (tags.includes(tag))
155
- count++;
156
- }
157
- catch { /* ignore */ }
173
+ try {
174
+ const content = fs.readFileSync(path.join(dir, f), 'utf-8');
175
+ const tags = getMemoryArray(parseMemoryDocument(content), 'tags');
176
+ if (tags.includes(tag))
177
+ count++;
158
178
  }
179
+ catch { /* ignore */ }
159
180
  }
160
- return count > 0 ? { count } : null;
181
+ return count;
161
182
  }
162
183
  /** 找出对端是 owner 的关系目录名。peerKey 形如 aun#<ownerAid>。 */
163
184
  function findOwnerPeerKey(peerKeys, ownerAid) {
@@ -170,118 +191,62 @@ function findOwnerPeerKey(peerKeys, ownerAid) {
170
191
  }
171
192
  return null;
172
193
  }
173
- /** 在 consolidated/ 下找第一个带 profile tag 的文件路径。 */
174
- function findProfileMemoryPath(consolidatedDir) {
194
+ /**
195
+ * 扫一遍关系的 consolidated/:有没有记忆、画像上次生成时间、除画像外最新一条记忆的创建时间。
196
+ * 时间都取 frontmatter,不取文件 mtime——长期记忆减速、索引重建都会刷 mtime,与内容是否变化无关。
197
+ */
198
+ function scanProfileState(consolidatedDir) {
199
+ const state = { hasMemory: false, hasProfile: false, profileUpdatedAtMs: null, newestCreatedAtMs: null };
175
200
  if (!fs.existsSync(consolidatedDir))
176
- return null;
201
+ return state;
177
202
  for (const f of fs.readdirSync(consolidatedDir)) {
178
203
  if (!f.endsWith('.md'))
179
204
  continue;
180
- const fp = path.join(consolidatedDir, f);
205
+ state.hasMemory = true;
181
206
  try {
182
- const content = fs.readFileSync(fp, 'utf-8');
183
- const tags = getMemoryArray(parseMemoryDocument(content), 'tags');
184
- if (tags.includes('profile'))
185
- return fp;
207
+ const document = parseMemoryDocument(fs.readFileSync(path.join(consolidatedDir, f), 'utf-8'));
208
+ if (getMemoryArray(document, 'tags').includes('profile')) {
209
+ state.hasProfile = true;
210
+ state.profileUpdatedAtMs = memoryTimeMs(getMemoryString(document, 'updatedAt'))
211
+ ?? memoryTimeMs(getMemoryString(document, 'createdAt'));
212
+ continue;
213
+ }
214
+ const createdAtMs = memoryTimeMs(getMemoryString(document, 'createdAt'));
215
+ if (createdAtMs !== null && (state.newestCreatedAtMs === null || createdAtMs > state.newestCreatedAtMs)) {
216
+ state.newestCreatedAtMs = createdAtMs;
217
+ }
186
218
  }
187
219
  catch { /* ignore */ }
188
220
  }
189
- return null;
190
- }
191
- /** consolidated/ 里有没有记忆。 */
192
- function hasAnyMemory(memDir) {
193
- const dir = path.join(memDir, 'consolidated');
194
- if (!fs.existsSync(dir))
195
- return false;
196
- return fs.readdirSync(dir).some(f => f.endsWith('.md'));
197
- }
198
- /** 画像是否该重建:索引 mtime 晚于画像 mtime,且画像超过 profileRegenDays 没更新。 */
199
- function profileDue(memDir, now, profileRegenDays) {
200
- const indexPath = path.join(memDir, 'MEMORY.md');
201
- const consolidatedDir = path.join(memDir, 'consolidated');
202
- const profilePath = findProfileMemoryPath(consolidatedDir);
203
- // 还没有画像:只要 consolidated/ 里已经有记忆,就该建。
204
- // 不能要求索引存在 —— 索引是整理会话跑完才生成的,
205
- // 而「有记忆但还没整理过」恰恰是最该建画像的时候。
206
- if (!profilePath)
207
- return hasAnyMemory(memDir);
208
- if (!fs.existsSync(indexPath))
209
- return false;
210
- let indexMtime;
211
- try {
212
- indexMtime = fs.statSync(indexPath).mtimeMs;
213
- }
214
- catch {
215
- return false;
216
- }
217
- let profileMtime;
218
- try {
219
- profileMtime = fs.statSync(profilePath).mtimeMs;
220
- }
221
- catch {
222
- return false;
223
- }
224
- const days = (now - profileMtime) / (24 * 60 * 60 * 1000);
225
- return indexMtime > profileMtime && days >= profileRegenDays;
226
- }
227
- /**
228
- * 数带指定标签的记忆。
229
- *
230
- * useMetaIndex=true 时先读各关系的 `_meta.json`:
231
- * - to-generalize / to-promote 直接由布尔字段判定(无需读正文)
232
- * - 元数据缺失 → 该关系回退全量扫描
233
- * 返回值只关心「有没有 + 有几条」,元数据只给出布尔,故命中时给个占位计数。
234
- */
235
- function countTagged(root, selfAid, peerKeys, tag, useMetaIndex) {
236
- if (!useMetaIndex)
237
- return findTagged(root, selfAid, peerKeys, tag);
238
- let count = 0;
239
- const fallbackPeerKeys = [];
240
- for (const peerKey of peerKeys) {
241
- const memDir = relationMemoryDir(root, selfAid, peerKey);
242
- const meta = readMemoryMeta(memDir);
243
- if (!meta) {
244
- fallbackPeerKeys.push(peerKey);
245
- continue;
246
- }
247
- if (tag === 'to-generalize' ? meta.hasToGeneralize : meta.hasToPromote)
248
- count++;
249
- }
250
- // 元数据缺失的关系回退全量扫描
251
- if (fallbackPeerKeys.length > 0) {
252
- const fallback = findTagged(root, selfAid, fallbackPeerKeys, tag);
253
- if (fallback)
254
- count += fallback.count;
255
- }
256
- return count > 0 ? { count } : null;
221
+ return state;
257
222
  }
258
223
  /**
259
224
  * 画像是否该重建。
260
- * useMetaIndex=true 时用 `_meta.json` 的 profileSlug/profileMtimeMs 判定;
261
- * 元数据缺失或没有画像记录时回退全量扫描。
225
+ *
226
+ * - 还没有画像:consolidated/ 里有记忆就该建(不要求索引存在——「有记忆但还没整理过」
227
+ * 恰恰是最该建画像的时候)。
228
+ * - 已有画像:画像生成之后有**新建**的记忆(createdAt 晚于画像 updatedAt),且距上次生成满 profileRegenDays。
229
+ * 续期、改标签不改 createdAt,不会触发;没有新证据时重写画像只会产出同样的内容。
230
+ *
231
+ * useMetaIndex=true 时读 `_meta.json` 的同名字段;缺失或版本不符时回退全量扫描。
262
232
  */
263
233
  function profileDueWithMeta(memDir, now, profileRegenDays, useMetaIndex) {
264
- if (!useMetaIndex)
265
- return profileDue(memDir, now, profileRegenDays);
266
- const meta = readMemoryMeta(memDir);
267
- if (!meta)
268
- return profileDue(memDir, now, profileRegenDays);
269
- const indexPath = path.join(memDir, 'MEMORY.md');
270
- // 没有画像:只要 consolidated/ 里已经有记忆,就该建。
271
- if (meta.profileSlug === null)
272
- return meta.count > 0;
273
- if (!fs.existsSync(indexPath))
274
- return false;
275
- let indexMtime;
276
- try {
277
- indexMtime = fs.statSync(indexPath).mtimeMs;
278
- }
279
- catch {
234
+ const meta = useMetaIndex ? readMemoryMeta(memDir) : null;
235
+ const state = meta
236
+ ? {
237
+ hasMemory: meta.count > 0,
238
+ hasProfile: meta.profileSlug !== null,
239
+ profileUpdatedAtMs: meta.profileUpdatedAtMs,
240
+ newestCreatedAtMs: meta.newestCreatedAtMs,
241
+ }
242
+ : scanProfileState(path.join(memDir, 'consolidated'));
243
+ if (!state.hasProfile)
244
+ return state.hasMemory;
245
+ // 画像缺时间:判断不了「之后有没有新记忆」,不重建(手动 ec memory consolidate --mode profile 仍可用)
246
+ if (state.profileUpdatedAtMs === null || state.newestCreatedAtMs === null)
280
247
  return false;
281
- }
282
- const profileMtime = meta.profileMtimeMs ?? 0;
283
- const days = (now - profileMtime) / (24 * 60 * 60 * 1000);
284
- return indexMtime > profileMtime && days >= profileRegenDays;
248
+ return state.newestCreatedAtMs > state.profileUpdatedAtMs
249
+ && now - state.profileUpdatedAtMs >= profileRegenDays * DAY_MS;
285
250
  }
286
251
  /**
287
252
  * 检查一个作用域的超期记忆,并对**尚未到审查期**的长期记忆做减速。
@@ -318,64 +283,86 @@ function checkStale(consolidatedDir, now, forgetAfterDays) {
318
283
  export function shouldUseMetaIndex(agentCount, relationCount) {
319
284
  return agentCount * relationCount > META_INDEX_THRESHOLD;
320
285
  }
321
- /** 关系整理链的固定顺序。每步在上一步收尾后重新判定,notes 新产出的标签要被后面几步看到。 */
322
- export const RELATION_SWEEP_ORDER = ['notes', 'generalize', 'promote', 'profile', 'forget'];
323
- /** pending/ 里有没有待整理的 note。 */
324
- function hasPendingNotes(pendingDir) {
325
- if (!fs.existsSync(pendingDir))
326
- return false;
327
- try {
328
- return fs.readdirSync(pendingDir).some(f => f.endsWith('.md'));
329
- }
330
- catch {
331
- return false;
332
- }
333
- }
286
+ /** 关系整理链的固定顺序(内容驱动的三步)。每步在上一步收尾后重新判定,notes 新产出的标签要被后面几步看到。 */
287
+ export const RELATION_SWEEP_ORDER = ['notes', 'generalize', 'promote'];
334
288
  /** 默认的关系空闲时长与兜底时长(小时)。 */
335
289
  export const DEFAULT_RELATION_IDLE_HOURS = 1;
336
290
  export const DEFAULT_MAX_UNCONSOLIDATED_HOURS = 8;
337
291
  /**
338
- * 单个关系的某个整理模式现在该不该跑。关系整理链逐步调用。
292
+ * 单个关系的某个内容驱动模式现在该不该跑。关系整理链逐步调用。
339
293
  *
340
- * 与全局检查不同:notes 只要有 pending 就跑(关系已空闲 / 兜底到期,不再等堆积),
341
- * promote 只在该关系就是 owner 关系时才可能命中。
294
+ * force=true(兜底到期)有 1 条候选就跑;否则(空闲到期)候选 ≥ minBatchItems 才跑,不够返回 defer。
295
+ * promote 只在该关系就是 owner 关系时才可能有候选。
342
296
  */
343
- export function isRelationModeDue(params) {
297
+ export function judgeRelationMode(params) {
344
298
  const { mode, selfAid, peerKey } = params;
345
- const now = params.now ?? Date.now();
346
299
  const root = params.root ?? resolveRoot();
347
300
  const config = effectiveConfig(params.config);
348
- const useMetaIndex = params.useMetaIndex ?? false;
349
301
  if (!config.enableRelation)
350
- return false;
351
- const memDir = relationMemoryDir(root, selfAid, peerKey);
302
+ return 'none';
303
+ let count = 0;
352
304
  switch (mode) {
353
305
  case 'notes':
354
- return hasPendingNotes(path.join(memDir, 'pending'));
306
+ count = countPendingNotes(path.join(relationMemoryDir(root, selfAid, peerKey), 'pending'));
307
+ break;
355
308
  case 'generalize':
356
- return config.enableAgent && !!countTagged(root, selfAid, [peerKey], 'to-generalize', useMetaIndex);
309
+ if (config.enableAgent)
310
+ count = findTagged(root, selfAid, [peerKey], 'to-generalize')?.count ?? 0;
311
+ break;
357
312
  case 'promote':
358
- return config.enableOwner
359
- && findOwnerPeerKey([peerKey], params.ownerAid) === peerKey
360
- && !!countTagged(root, selfAid, [peerKey], 'to-promote', useMetaIndex);
361
- case 'profile':
362
- return profileDueWithMeta(memDir, now, config.profileRegenDays, useMetaIndex);
363
- case 'forget':
364
- return checkStale(path.join(memDir, 'consolidated'), now, config.forgetAfterDays) > 0;
313
+ if (config.enableOwner && findOwnerPeerKey([peerKey], params.ownerAid) === peerKey) {
314
+ // 关系层 + agent 层:generalize 手册要求在 agent 级产出上打 to-promote,
315
+ // 只数关系层会让这些标签永远不被读到
316
+ count = findTagged(root, selfAid, [peerKey], 'to-promote')?.count ?? 0;
317
+ // agent 层标签不攒批:它们不按关系累积,等凑够一批没有意义,有就跑
318
+ if (countTaggedIn(path.join(root, 'agents', selfAid, 'personal', 'memory', 'consolidated'), 'to-promote') > 0) {
319
+ return 'run';
320
+ }
321
+ }
322
+ break;
323
+ }
324
+ if (count === 0)
325
+ return 'none';
326
+ return params.force || count >= config.minBatchItems ? 'run' : 'defer';
327
+ }
328
+ /**
329
+ * 画像尝试记录:`relations/<peerKey>/memory/_profile-attempt.json`。
330
+ *
331
+ * 每次拉起 profile 会话都记一次,距上次尝试不满 profileRegenDays 就不再拉起——无论上次成没成。
332
+ * 不放进 `_meta.json`:那份由索引重建整体覆盖写,会冲掉这条记录。
333
+ */
334
+ const PROFILE_ATTEMPT_FILENAME = '_profile-attempt.json';
335
+ export function recordProfileAttempt(memoryDir, now = Date.now()) {
336
+ try {
337
+ fs.mkdirSync(memoryDir, { recursive: true });
338
+ atomicWriteJson(path.join(memoryDir, PROFILE_ATTEMPT_FILENAME), { lastAttemptAt: now });
339
+ }
340
+ catch { /* 记录失败只影响退避,不影响整理 */ }
341
+ }
342
+ function profileAttemptedWithin(memoryDir, now, days) {
343
+ try {
344
+ const raw = JSON.parse(fs.readFileSync(path.join(memoryDir, PROFILE_ATTEMPT_FILENAME), 'utf-8'));
345
+ return typeof raw.lastAttemptAt === 'number' && now - raw.lastAttemptAt < days * DAY_MS;
346
+ }
347
+ catch {
348
+ return false;
365
349
  }
366
350
  }
367
351
  /**
368
- * 全局定时检查:只管**不属于任何一个关系**的部分,外加 pending 堆积兜底。
352
+ * 全局定时检查:时间驱动的整理,一个会话只处理一个关系或一层。
369
353
  *
370
- * ① pending 堆积超过 backlogHours 的关系 → notes(由调用方转成该关系的整理链)
371
- * ② agent 层超期记忆(只看 personal/memory 自身)→ forget scope=agent
372
- * ③ owner 层超期记忆 → forget scope=owner
354
+ * ① 关系画像到期(还没有画像且有记忆;或画像之后有新建记忆且画像满 profileRegenDays),
355
+ * 且距上次尝试满 profileRegenDays → profile
356
+ * ② 关系层超期记忆 → forget scope=relation
357
+ * ③ agent 层超期记忆(只看 personal/memory 自身)→ forget scope=agent
358
+ * ④ owner 层超期记忆 → forget scope=owner
359
+ * ⑤ agent 层有 to-promote → promote(按 owner 关系拉起;兜底)
373
360
  *
374
- * generalize / promote / profile / 关系层 forget 由关系整理链负责(relation-sweep.ts),
375
- * 这里不再产出:整理一律以关系为单位。
361
+ * 内容驱动的 notes / generalize / promote 主要走关系整理链(relation-idle-monitor.ts、relation-sweep.ts)。
362
+ * agent 层的 to-promote 不挂关系:主路径是 generalize 收尾时立即拉起
363
+ * (consolidation.ts 的 triggerAgentPromote),⑤ 兜不是 generalize 打的标签。
376
364
  *
377
365
  * 纯检查 + 少量副作用(forget 的长期记忆减速刷新 mtime)。
378
- * useMetaIndex 参数保留兼容:当前三类判据都不读 `_meta.json`(关系级判据见 isRelationModeDue)。
379
366
  */
380
367
  export function checkConsolidationCandidates(params) {
381
368
  const { selfAid, ownerAid } = params;
@@ -387,31 +374,44 @@ export function checkConsolidationCandidates(params) {
387
374
  return out;
388
375
  const relationsDir = path.join(root, 'agents', selfAid, 'relations');
389
376
  const peerKeys = fs.existsSync(relationsDir)
390
- ? fs.readdirSync(relationsDir, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => d.name)
377
+ ? fs.readdirSync(relationsDir, { withFileTypes: true })
378
+ .filter(d => d.isDirectory() && isConsolidatableRelation(d.name))
379
+ .map(d => d.name)
391
380
  : [];
392
- // ① pending 堆积 → notes
381
+ const useMetaIndex = params.useMetaIndex ?? false;
393
382
  for (const peerKey of peerKeys) {
394
- const pendingDir = path.join(relationsDir, peerKey, 'memory', 'pending');
395
- const backlog = pendingBacklogHours(pendingDir, now);
396
- if (backlog >= config.backlogHours) {
397
- out.push({
398
- mode: 'notes',
399
- peerKey,
400
- reason: `pending 堆积 ${backlog.toFixed(1)}h(>${config.backlogHours}h)`,
401
- });
383
+ const memDir = relationMemoryDir(root, selfAid, peerKey);
384
+ // ① 画像到期 → profile(退避:距上次尝试不满 profileRegenDays 不再拉起)
385
+ if (profileDueWithMeta(memDir, now, config.profileRegenDays, useMetaIndex)
386
+ && !profileAttemptedWithin(memDir, now, config.profileRegenDays)) {
387
+ out.push({ mode: 'profile', peerKey, reason: '画像到期' });
388
+ }
389
+ // ② 关系层超期 → forget scope=relation
390
+ if (checkStale(path.join(memDir, 'consolidated'), now, config.forgetAfterDays) > 0) {
391
+ out.push({ mode: 'forget', scope: 'relation', peerKey, reason: '关系级记忆超期' });
402
392
  }
403
393
  }
404
- // ② agent 层超期 → forget scope=agent(只审 personal/memory 自身;关系层由关系整理链负责)
394
+ // ③ agent 层超期 → forget scope=agent(只审 personal/memory 自身)
405
395
  const agentConsolidated = path.join(root, 'agents', selfAid, 'personal', 'memory', 'consolidated');
406
396
  if (config.enableAgent && checkStale(agentConsolidated, now, config.forgetAfterDays) > 0) {
407
397
  out.push({ mode: 'forget', scope: 'agent', reason: 'agent 级记忆超期' });
408
398
  }
409
- // ③ owner 层超期 → forget scope=owner(owner 层与 agent / relation 层是平行的)
399
+ // ④ owner 层超期 → forget scope=owner(owner 层与 agent / relation 层是平行的)
410
400
  if (config.enableOwner && ownerAid) {
411
401
  const ownerConsolidated = path.join(root, 'memory', 'owner', ownerAid, 'consolidated');
412
402
  if (checkStale(ownerConsolidated, now, config.forgetAfterDays) > 0) {
413
403
  out.push({ mode: 'forget', scope: 'owner', reason: 'owner 级记忆超期' });
414
404
  }
405
+ // ⑤ agent 层有 to-promote → promote(兜底)
406
+ // 主路径是事件驱动:generalize 收尾时发现 agent 层有标签,立即拉起
407
+ // (consolidation.ts 的 triggerAgentPromote)。手动打的标签、旧版本留下的标签、
408
+ // 收尾时还没有 owner 关系目录的,都不经过那条路,这里每小时扫一遍兜住。
409
+ // 不担心反复拉起:整理会话收尾会把仍带 to-promote 的候选兜底摘掉。
410
+ const ownerPeerKey = findOwnerPeerKey(peerKeys, ownerAid);
411
+ const agentToPromote = countTaggedIn(agentConsolidated, 'to-promote');
412
+ if (ownerPeerKey && agentToPromote > 0) {
413
+ out.push({ mode: 'promote', peerKey: ownerPeerKey, reason: `agent 级有 ${agentToPromote} 条 to-promote` });
414
+ }
415
415
  }
416
416
  return out;
417
417
  }