evolcore 0.0.48 → 0.0.50

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 (302) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/bin/ecmsg.js +9 -4
  3. package/dist/ability/caller/authorization.js +21 -0
  4. package/dist/ability/caller/command.js +164 -0
  5. package/dist/ability/caller/contract.js +102 -0
  6. package/dist/ability/caller/daemon.js +158 -0
  7. package/dist/ability/caller/service.js +380 -0
  8. package/dist/ability/command-contract.js +5 -0
  9. package/dist/ability/daemon.js +5 -1
  10. package/dist/ability/interop-v1.js +10 -3
  11. package/dist/ability/management.js +1 -0
  12. package/dist/agent-template/jobs.js +173 -1
  13. package/dist/agent-template/runtime.js +285 -8
  14. package/dist/agent-template/service.js +1159 -40
  15. package/dist/agent-template/types.js +2 -1
  16. package/dist/agents/baseagent-availability.js +27 -3
  17. package/dist/agents/baseagent-capability-adapter.js +102 -0
  18. package/dist/agents/baseagent-plugin-descriptor.js +274 -0
  19. package/dist/agents/baseagent-plugin-loader.js +145 -0
  20. package/dist/agents/baseagent.js +68 -2
  21. package/dist/agents/claude-gateway/agent-registration.js +389 -0
  22. package/dist/agents/claude-gateway/binding.js +96 -0
  23. package/dist/agents/claude-gateway/inbox.js +138 -0
  24. package/dist/agents/claude-gateway/index.js +125 -0
  25. package/dist/agents/claude-gateway/listing.js +330 -0
  26. package/dist/agents/claude-gateway/router.js +328 -0
  27. package/dist/agents/claude-gateway/sessions.js +128 -0
  28. package/dist/agents/claude-gateway/terminal.js +250 -0
  29. package/dist/agents/claude-gateway/transcript.js +272 -0
  30. package/dist/agents/claude-gateway/types.js +14 -0
  31. package/dist/agents/claude-runner.js +6 -10
  32. package/dist/agents/codex-runner.js +9 -2
  33. package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
  34. package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
  35. package/dist/agents/gemini/index.js +51 -0
  36. package/dist/aun/aid/control-aid.js +52 -32
  37. package/dist/aun/group/invite-service.js +6 -36
  38. package/dist/aun/group/operations.js +6 -0
  39. package/dist/aun/msg/mention-schema.js +1 -1
  40. package/dist/aun/msg/p2p.js +31 -2
  41. package/dist/aun/msg/upload.js +126 -3
  42. package/dist/build-identity.json +1 -1
  43. package/dist/channels/aun.js +1175 -457
  44. package/dist/cli/ability-command.js +42 -0
  45. package/dist/cli/agent-command.js +20 -1
  46. package/dist/cli/agent-create.js +78 -18
  47. package/dist/cli/agent-template.js +5 -3
  48. package/dist/cli/agent.js +91 -0
  49. package/dist/cli/aun-commands.js +92 -34
  50. package/dist/cli/bench.js +5 -2
  51. package/dist/cli/config.js +22 -6
  52. package/dist/cli/daemon-commands.js +245 -101
  53. package/dist/cli/directory.js +6 -1
  54. package/dist/cli/ecmsg-gateway.js +11 -9
  55. package/dist/cli/index.js +30 -5
  56. package/dist/cli/init.js +39 -63
  57. package/dist/cli/managed-command-guard.js +3 -0
  58. package/dist/cli/menu-client.js +32 -7
  59. package/dist/cli/model.js +20 -5
  60. package/dist/cli/pay-command.js +30 -0
  61. package/dist/cli/provider-command.js +6 -2
  62. package/dist/cli/quota.js +89 -0
  63. package/dist/cli/restart-monitor.js +2 -2
  64. package/dist/cli/role.js +1 -0
  65. package/dist/cli/services-command.js +12 -9
  66. package/dist/cli/team-workspace-command.js +56 -2
  67. package/dist/cli/thread-command.js +78 -12
  68. package/dist/config/access-policy.js +16 -3
  69. package/dist/config/config-field-policy.js +88 -9
  70. package/dist/config/config-manager.js +97 -47
  71. package/dist/config/config-operation-service.js +22 -1
  72. package/dist/config/gateway-config.js +9 -8
  73. package/dist/config/owner-config.js +0 -16
  74. package/dist/config/peer-role-resolver.js +1 -7
  75. package/dist/config/providers-config.js +107 -20
  76. package/dist/config/providers-management.js +45 -21
  77. package/dist/config/resolved-config-op.js +4 -44
  78. package/dist/config/schema-migration.js +78 -5
  79. package/dist/config/schema-registry.js +52 -7
  80. package/dist/config-store.js +1309 -17
  81. package/dist/core/agent-application-service.js +220 -1
  82. package/dist/core/agent-ipc-registration.js +19 -2
  83. package/dist/core/agent-reload-coordinator.js +5 -0
  84. package/dist/core/agent-runtime.js +198 -54
  85. package/dist/core/auth/agent-delegation.js +14 -0
  86. package/dist/core/auth/delegation-authorization.js +33 -26
  87. package/dist/core/auth/operation-authorizer.js +16 -1
  88. package/dist/core/auth/operation-catalog.js +59 -7
  89. package/dist/core/baseagent-loader.js +30 -3
  90. package/dist/core/capability/capability-manager.js +16 -7
  91. package/dist/core/channel-runtime.js +4 -2
  92. package/dist/core/command/agent-control.js +20 -2
  93. package/dist/core/command/agent-template-menu.js +4 -3
  94. package/dist/core/command/cli-intent-parser.js +28 -0
  95. package/dist/core/command/command-handler.js +45 -2
  96. package/dist/core/command/menu-catalog.js +20 -4
  97. package/dist/core/command/menu-file-path.js +70 -0
  98. package/dist/core/command/menu-handler.js +97 -73
  99. package/dist/core/command/menu-protocol.js +29 -0
  100. package/dist/core/command/menu-query-batch.js +2 -2
  101. package/dist/core/command/private-mention-menu.js +71 -0
  102. package/dist/core/command/remote-shell.js +565 -0
  103. package/dist/core/command/slash-handler.js +17 -26
  104. package/dist/core/command/team-workspace-bootstrap.js +2 -1
  105. package/dist/core/command/topic-slash.js +7 -1
  106. package/dist/core/daemon-bootstrap.js +0 -4
  107. package/dist/core/daemon-control.js +58 -1
  108. package/dist/core/daemon-lifecycle.js +29 -7
  109. package/dist/core/evolagent-registry.js +18 -9
  110. package/dist/core/handoff/runtime.js +1 -1
  111. package/dist/core/host-snapshot.js +8 -3
  112. package/dist/core/initialization/service.js +3 -0
  113. package/dist/core/interaction-router.js +130 -0
  114. package/dist/core/ipc-registration.js +5 -0
  115. package/dist/core/memory/consolidation-context.js +2 -1
  116. package/dist/core/memory/consolidation.js +35 -64
  117. package/dist/core/message/aun-ipc-sender.js +213 -74
  118. package/dist/core/message/aun-request-registry.js +31 -0
  119. package/dist/core/message/contact-admission.js +91 -6
  120. package/dist/core/message/contact-pending-inbound.js +113 -0
  121. package/dist/core/message/contact-thread-approval.js +212 -0
  122. package/dist/core/message/im-renderer.js +40 -1
  123. package/dist/core/message/message-admission.js +5 -39
  124. package/dist/core/message/message-bridge.js +197 -45
  125. package/dist/core/message/message-log.js +32 -0
  126. package/dist/core/message/message-queue.js +102 -18
  127. package/dist/core/message/peer-mode.js +15 -4
  128. package/dist/core/message/response-engine.js +174 -26
  129. package/dist/core/message/send-options.js +37 -3
  130. package/dist/core/message/send-routing.js +11 -7
  131. package/dist/core/model/config-scope.js +6 -14
  132. package/dist/core/model/model-catalog.js +5 -5
  133. package/dist/core/model/model-diagnostics.js +19 -0
  134. package/dist/core/model/model-fallback.js +13 -2
  135. package/dist/core/ownership/owner-resolver.js +12 -86
  136. package/dist/core/pack-auth.js +7 -0
  137. package/dist/core/pack-install.js +1 -1
  138. package/dist/core/permission/ec-command-parser.js +288 -77
  139. package/dist/core/permission/protected-paths.js +64 -9
  140. package/dist/core/permission/services-path-acl.js +458 -0
  141. package/dist/core/permission/tool-policy.js +26 -10
  142. package/dist/core/relation/peer-identity.js +13 -0
  143. package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
  144. package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
  145. package/dist/core/session/session-manager.js +47 -10
  146. package/dist/core/session/session-mapper.js +16 -0
  147. package/dist/core/skill/index-generator.js +2 -3
  148. package/dist/core/skill/switch-resolver.js +3 -0
  149. package/dist/core/task/task-recovery-service.js +1 -0
  150. package/dist/core/thread/command-parser.js +4 -1
  151. package/dist/core/thread/ipc-operation.js +4 -2
  152. package/dist/core/thread/thread-operation.js +25 -10
  153. package/dist/core/thread/thread-service.js +294 -55
  154. package/dist/core/thread/topic-id.js +67 -2
  155. package/dist/core/thread/types.js +15 -1
  156. package/dist/directory/owner-directory-admission.js +11 -8
  157. package/dist/directory/owner-directory-cache.js +19 -0
  158. package/dist/directory/owner-directory-markdown.js +1 -1
  159. package/dist/directory/owner-directory-policy.js +5 -30
  160. package/dist/directory/owner-directory-request-operation.js +5 -2
  161. package/dist/eck/kit-renderer.js +3 -2
  162. package/dist/eck/message-renderer.js +28 -5
  163. package/dist/ecweb/basic-settings-service.js +5 -9
  164. package/dist/ecweb/providers-service.js +4 -2
  165. package/dist/ecweb/runtime/supervisor.js +36 -8
  166. package/dist/event-center/center-config.js +9 -5
  167. package/dist/event-center/dispatcher.js +10 -1
  168. package/dist/event-center/ipc-operation.js +19 -0
  169. package/dist/event-center/registry.js +20 -5
  170. package/dist/event-center/runtime.js +10 -7
  171. package/dist/index.js +120 -41
  172. package/dist/ipc.js +83 -3
  173. package/dist/outputs/authorization.js +16 -0
  174. package/dist/outputs/cards.js +336 -0
  175. package/dist/outputs/events.js +3 -2
  176. package/dist/outputs/protocol.js +1 -0
  177. package/dist/outputs/service.js +2 -15
  178. package/dist/paths.js +48 -1
  179. package/dist/pay/command.js +38 -0
  180. package/dist/pay/protocol.js +136 -0
  181. package/dist/pay/runtime.js +188 -0
  182. package/dist/pay/service.js +384 -0
  183. package/dist/pay/store.js +81 -0
  184. package/dist/response-system/engines/v1/proactive-flow.js +29 -2
  185. package/dist/services/dispatcher.js +23 -5
  186. package/dist/services/host/main.js +388 -0
  187. package/dist/services/host/protocol.js +118 -0
  188. package/dist/services/host/resident.js +310 -0
  189. package/dist/services/host-client.js +386 -0
  190. package/dist/services/host-deploy.js +180 -0
  191. package/dist/services/host-launch.js +117 -0
  192. package/dist/services/host-recycle.js +203 -0
  193. package/dist/services/host-runtime.js +802 -0
  194. package/dist/services/idempotency.js +44 -86
  195. package/dist/services/index-generator.js +4 -3
  196. package/dist/services/index.js +204 -22
  197. package/dist/services/ipc-operation.js +288 -44
  198. package/dist/services/pack-manager.js +1 -0
  199. package/dist/services/script-runner.js +515 -83
  200. package/dist/services/service-payload.js +13 -7
  201. package/dist/services/validation.js +109 -4
  202. package/dist/stats/budget.js +1 -1
  203. package/dist/stats/model-resolver.js +2 -2
  204. package/dist/stats/quota-query.js +95 -0
  205. package/dist/trigger/application-service.js +6 -4
  206. package/dist/trigger/local-files.js +19 -9
  207. package/dist/trigger/scheduler.js +22 -12
  208. package/dist/trigger/script-sandbox.js +51 -8
  209. package/dist/utils/aid-bind.js +3 -0
  210. package/dist/utils/atomic-write.js +22 -8
  211. package/dist/utils/evolcore-version.js +2 -2
  212. package/dist/utils/host-info.js +173 -1
  213. package/dist/utils/logger.js +2 -2
  214. package/dist/utils/media-cache.js +190 -43
  215. package/dist/utils/npm-ops.js +43 -8
  216. package/dist/utils/restart-safety.js +14 -1
  217. package/dist/utils/system-memory.js +113 -25
  218. package/dist/utils/systemd-lifecycle.js +154 -0
  219. package/dist/utils/windows-shell-trust.js +7 -3
  220. package/dist/workbench/service.js +1 -1
  221. package/kits/docs/INDEX.md +3 -2
  222. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
  223. package/kits/docs/channels/aun.md +1 -1
  224. package/kits/docs/evolcore/INDEX.md +9 -6
  225. package/kits/docs/evolcore/agent.md +36 -1
  226. package/kits/docs/evolcore/aid.md +45 -3
  227. package/kits/docs/evolcore/config.md +5 -2
  228. package/kits/docs/evolcore/directory.md +8 -9
  229. package/kits/docs/evolcore/group.md +2 -1
  230. package/kits/docs/evolcore/memory-tags.md +2 -0
  231. package/kits/docs/evolcore/menu-client.md +3 -3
  232. package/kits/docs/evolcore/menu-protocol.md +7 -0
  233. package/kits/docs/evolcore/model.md +3 -0
  234. package/kits/docs/evolcore/msg.md +77 -10
  235. package/kits/docs/evolcore/pay.md +34 -0
  236. package/kits/docs/evolcore/provider.md +22 -1
  237. package/kits/docs/evolcore/quota.md +54 -0
  238. package/kits/docs/evolcore/role.md +3 -0
  239. package/kits/docs/evolcore/services.md +46 -18
  240. package/kits/docs/evolcore/stats.md +2 -0
  241. package/kits/docs/evolcore/thread-chain.md +2 -0
  242. package/kits/docs/evolcore/tool-authorization.md +10 -0
  243. package/kits/docs/evolcore/trigger.md +2 -0
  244. package/kits/rules/01-overview.md +11 -32
  245. package/kits/rules/02-navigation.md +7 -0
  246. package/kits/rules/06-channel.md +3 -3
  247. package/kits/schemas/_meta.json +38 -5
  248. package/kits/schemas/agent-config.schema.20.json +24 -0
  249. package/kits/schemas/agent-config.schema.21.json +974 -0
  250. package/kits/schemas/agent-config.schema.22.json +977 -0
  251. package/kits/schemas/agent-config.schema.23.json +958 -0
  252. package/kits/schemas/daemon.schema.10.json +373 -0
  253. package/kits/schemas/daemon.schema.9.json +12 -0
  254. package/kits/schemas/defaults.schema.7.json +472 -0
  255. package/kits/schemas/providers.schema.3.json +18 -2
  256. package/kits/schemas/relation-config.schema.13.json +289 -0
  257. package/kits/skills/.switches.json +17 -1
  258. package/kits/skills/ability/SKILL.md +229 -34
  259. package/kits/skills/ability/STRUCTURE.md +333 -0
  260. package/kits/skills/ability/references/cli.md +208 -0
  261. package/kits/skills/ability/references/development.md +107 -37
  262. package/kits/skills/ability/references/management.md +106 -46
  263. package/kits/skills/ability/references/runtime-protocol.md +65 -63
  264. package/kits/skills/agent-output-cards/SKILL.md +64 -0
  265. package/kits/skills/ec-group/SKILL.md +8 -6
  266. package/kits/skills/ec-group/TASK.md +186 -0
  267. package/kits/skills/ec-group/WORKLOG.md +180 -0
  268. package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
  269. package/kits/skills/ec-pay/SKILL.md +101 -0
  270. package/kits/skills/ec-pay/references/pay-cli.md +110 -0
  271. package/kits/skills/ec-provider/SKILL.md +58 -9
  272. package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
  273. package/kits/skills/ec-service-call/SKILL.md +135 -0
  274. package/kits/skills/ec-service-pack/SKILL.md +277 -0
  275. package/kits/skills/ec-trigger/SKILL.md +1 -1
  276. package/kits/templates/memory-consolidation/notes.md +2 -2
  277. package/kits/templates/memory-consolidation/workflow.md +46 -0
  278. package/kits/templates/roles/visitor.json +1 -0
  279. package/kits/templates/system-fragments/channel.md +13 -4
  280. package/kits/templates/system-fragments/commands.md +5 -3
  281. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  282. package/kits/templates/system-fragments/reply.md +1 -0
  283. package/kits/templates/system-fragments/session.md +1 -1
  284. package/kits/templates/system-fragments/thread.md +27 -128
  285. package/kits/templates/system-fragments/venue.md +27 -0
  286. package/package.json +4 -5
  287. package/scripts/agent-template/inspect.mjs +79 -29
  288. package/scripts/agent-template/overlay.mjs +20 -2
  289. package/scripts/agent-template/shared/common.mjs +24 -6
  290. package/scripts/agent-template/shared/team-schema.json +23 -5
  291. package/scripts/agent-template/shared/template-contract.mjs +107 -17
  292. package/scripts/agent-template/shared/template-package.mjs +254 -29
  293. package/scripts/agent-template/shared/template-runtime.mjs +145 -2
  294. package/scripts/agent-template/shared/template.mjs +67 -9
  295. package/scripts/agent-template/team-pack.mjs +132 -41
  296. package/scripts/agent-template/team-preview.mjs +249 -5
  297. package/kits/docs/aun/ABILITY_CALLING.md +0 -280
  298. package/kits/docs/evolcore/ability.md +0 -185
  299. package/kits/skills/ability/references/calling.md +0 -56
  300. package/kits/skills/ability/references/contract-checklist.md +0 -37
  301. package/kits/skills/ability/references/recovery.md +0 -27
  302. /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
@@ -5,9 +5,14 @@ import { agentSessionsDir, agentDir, agentThreadIndexPath, agentThreadSummariesD
5
5
  import { atomicWriteJson, atomicReadJson } from '../../utils/atomic-write.js';
6
6
  import { appendJsonl, appendJsonlDurable, readAllJsonlLines, readLastJsonlLine, readLastJsonlLineStrict, chatDirPath, scanChatDirs, tryParseChannelSessionKey } from '../session/session-fs-store.js';
7
7
  import { sanitizeSessionTitle, sessionTitleLength, SESSION_TITLE_MAX_LEN, SESSION_TITLE_STORED_MAX_LEN, SESSION_TITLE_ELLIPSIS } from '../session/session-title.js';
8
- import { isMainSessionThreadId, isTopicThreadId, mainTopicPeer, safeFormatMainTopicId, sessionTopicThreadId } from './topic-id.js';
8
+ import { readTopicStatusLenient } from '../session/session-mapper.js';
9
+ import { isMainSessionThreadId, isSelfTopicPeer, isTopicPeerAid, isTopicThreadId, mainTopicPeer, safeFormatMainTopicId, sessionTopicThreadId, normalizeThreadPeer, sameThreadPeer, isInternalThreadPeer } from './topic-id.js';
10
+ import { sanitizeIndexEntry } from './types.js';
11
+ export { normalizeThreadPeer, isInternalThreadPeer } from './topic-id.js';
9
12
  import { PeerIdentityCache } from '../relation/peer-identity.js';
10
13
  import { ThreadContextStorage } from './thread-context-storage.js';
14
+ import { isValidAid } from '../../aun/aid/validation.js';
15
+ import { logger } from '../../utils/logger.js';
11
16
  const RESERVED_THREAD_IDS = new Set(['current', 'main', 'all']);
12
17
  /**
13
18
  * 话题名长度校验:自动生成与手动改名共用 `session-title.ts` 的两个常量。
@@ -32,6 +37,55 @@ function assertThreadNameLength(rawName, _sanitized) {
32
37
  + `其中前 ${SESSION_TITLE_MAX_LEN} 字符为正文,末尾可带 ${SESSION_TITLE_ELLIPSIS} 省略号)。`
33
38
  + `请缩写后重试`, 'NAME_TOO_LONG');
34
39
  }
40
+ /** 由索引条目与会话文件末行算出一处漂移。 */
41
+ export function describeStatusDrift(entry, last) {
42
+ const indexStatus = readTopicStatusLenient(entry.topicStatus);
43
+ const fileStatus = readTopicStatusLenient(last?.topicStatus);
44
+ const indexUpdatedAt = Number.isSafeInteger(entry.topicStatusUpdatedAt) && entry.topicStatusUpdatedAt > 0 ? entry.topicStatusUpdatedAt : undefined;
45
+ const fileUpdatedAt = Number.isSafeInteger(last?.metadata?.topicStatusUpdatedAt) && last.metadata.topicStatusUpdatedAt > 0
46
+ ? last.metadata.topicStatusUpdatedAt
47
+ : undefined;
48
+ const nameDiffers = last?.name !== entry.name;
49
+ const statusDiffers = indexStatus !== fileStatus;
50
+ if (!nameDiffers && !statusDiffers) {
51
+ return { threadId: entry.threadId, peer: entry.peer, kind: 'same', indexStatus, fileStatus, indexUpdatedAt, fileUpdatedAt, winner: 'ambiguous' };
52
+ }
53
+ // Activity timestamps cannot prove a status change. Unversioned history stays ambiguous.
54
+ let winner = 'ambiguous';
55
+ if (indexUpdatedAt !== undefined && fileUpdatedAt !== undefined) {
56
+ if (fileUpdatedAt > indexUpdatedAt)
57
+ winner = 'file';
58
+ else if (indexUpdatedAt > fileUpdatedAt)
59
+ winner = 'index';
60
+ }
61
+ else if (indexUpdatedAt !== undefined)
62
+ winner = 'index';
63
+ else if (fileUpdatedAt !== undefined)
64
+ winner = 'file';
65
+ return {
66
+ threadId: entry.threadId,
67
+ peer: entry.peer,
68
+ kind: nameDiffers && statusDiffers ? 'both' : nameDiffers ? 'name' : 'status',
69
+ indexStatus,
70
+ fileStatus,
71
+ indexUpdatedAt,
72
+ fileUpdatedAt,
73
+ winner,
74
+ };
75
+ }
76
+ /**
77
+ * 索引条目的**写入闸门**:所有来源(创建、改名、改状态、会话侧 upsert、索引恢复、
78
+ * 重建、对账)在落盘前都必须过一遍。
79
+ *
80
+ * 为什么需要它:以前每个写入点各自 `push` 或改字段,任何一处漏掉校验,脏数据就
81
+ * 永久留在索引里,只能靠维护脚本清理。实测踩过的三类:
82
+ * - 内部对端(`bg:`/`trigger:`)被当成话题写进去,613 条残留;
83
+ * - 旧版状态值(`pending`/`completed`)原样落盘,与三态模型冲突;
84
+ * - 对端大小写不一致,同一对端出现两条。
85
+ *
86
+ * 闸门的职责是**拒绝**而不是修复:拿不出合法形态的条目直接丢弃并留日志,宁可
87
+ * 少一条也不写入一条永久性的脏数据。
88
+ */
35
89
  const LIST_DEFAULT_LIMIT = 10;
36
90
  const LIST_MAX_LIMIT = 200;
37
91
  export class ThreadServiceError extends Error {
@@ -58,18 +112,59 @@ function newThreadId() {
58
112
  * 新索引缺失或为空时回退读旧文件,转换后写回新路径。写回是幂等的:
59
113
  * 成功一次之后新索引存在,后续不会再走旧文件;旧文件保持原样,不删除。
60
114
  */
115
+ /**
116
+ * 索引 schema 版本。当前是 2:
117
+ *
118
+ * - 1 → 2:条目形态收口。`topicStatus` 归一为三态、`channelType` 补全、
119
+ * 内部对端(`bg:`/`trigger:`)与非法对端条目丢弃。
120
+ *
121
+ * 之前 `version: 1` 从来没被读过,所以结构演进只能靠一次性维护脚本清数据
122
+ * (2026-11-16 清过 613 条 `bg:`/`trigger:` 残留就是这个原因)。现在版本号
123
+ * 参与决策:读取旧版本时归一内存视图,显式写入时保存当前版本。
124
+ */
125
+ const THREAD_INDEX_VERSION = 2;
126
+ /**
127
+ * 读时迁移:把旧版本索引的条目过一遍写入闸门,必要时写回。
128
+ *
129
+ * 迁移是**幂等**的:版本已是最新时直接返回原对象,不产生额外磁盘写。
130
+ * 写回失败不阻断读取——内存里已经是迁移后的形态,下次读取会再试一次。
131
+ */
132
+ function migrateIndexOnRead(indexPath, raw) {
133
+ if (Number(raw.version) >= THREAD_INDEX_VERSION)
134
+ return raw;
135
+ const migratedThreads = [];
136
+ const dropped = [];
137
+ for (const entry of raw.threads) {
138
+ const gated = sanitizeIndexEntry(entry);
139
+ if (gated.ok)
140
+ migratedThreads.push(gated.entry);
141
+ else
142
+ dropped.push(`${entry.threadId ?? '?'}(${gated.reason})`);
143
+ }
144
+ const migrated = { version: THREAD_INDEX_VERSION, threads: migratedThreads };
145
+ if (dropped.length > 0) {
146
+ logger.warn(`[Thread] 索引迁移丢弃 ${dropped.length} 条无法归一的条目: ${dropped.slice(0, 5).join(', ')}${dropped.length > 5 ? ' …' : ''}`);
147
+ }
148
+ // Persist normalization only during an explicit write operation.
149
+ return migrated;
150
+ }
61
151
  function readIndex(indexPath) {
62
152
  const raw = atomicReadJson(indexPath);
63
153
  if (raw && Array.isArray(raw.threads) && raw.threads.length > 0) {
64
- return raw;
154
+ return migrateIndexOnRead(indexPath, raw);
65
155
  }
66
156
  const legacyPath = path.join(path.dirname(path.dirname(indexPath)), 'thread-index.json');
67
157
  if (legacyPath !== indexPath) {
68
158
  const legacy = atomicReadJson(legacyPath);
69
159
  if (legacy && Array.isArray(legacy.threads) && legacy.threads.length > 0) {
160
+ // 旧文件的条目也要过闸门:从旧路径搬过来的数据同样是历史形态。
161
+ const gatedThreads = legacy.threads
162
+ .map(e => sanitizeIndexEntry(e))
163
+ .filter((g) => g.ok)
164
+ .map(g => g.entry);
70
165
  const migrated = {
71
- version: 1,
72
- threads: legacy.threads,
166
+ version: THREAD_INDEX_VERSION,
167
+ threads: gatedThreads,
73
168
  };
74
169
  // 顺手落盘;失败不影响本次读取(例如目录只读),下次仍能走回退。
75
170
  try {
@@ -80,9 +175,10 @@ function readIndex(indexPath) {
80
175
  return migrated;
81
176
  }
82
177
  }
178
+ // 空 threads 的索引也走一遍迁移,保证返回值的版本号与条目形态一致。
83
179
  if (raw && Array.isArray(raw.threads))
84
- return raw;
85
- return { version: 1, threads: [] };
180
+ return migrateIndexOnRead(indexPath, raw);
181
+ return { version: THREAD_INDEX_VERSION, threads: [] };
86
182
  }
87
183
  /**
88
184
  * 把用户传入的 peer 归一成索引里实际存储的形态(对端在该渠道下的原生 ID)。
@@ -95,30 +191,23 @@ function readIndex(indexPath) {
95
191
  *
96
192
  * 对已经是裸 ID 的输入是幂等的;解析不出前缀时原样返回(由调用方按"无此对端"处理)。
97
193
  */
98
- export function normalizeThreadPeer(input) {
99
- if (input == null)
100
- return undefined;
101
- const raw = String(input).trim();
102
- if (!raw)
103
- return undefined;
104
- if (!raw.includes('#'))
105
- return raw;
106
- const seg = raw.split('#').pop() ?? '';
107
- try {
108
- return decodeURIComponent(seg).trim() || undefined;
109
- }
110
- catch {
111
- return seg.trim() || undefined;
112
- }
194
+ /**
195
+ * 索引条目的对端是否就是本端自己。
196
+ *
197
+ * 与 `topic-id.isSelfTopicPeer` 同义,区别只在入参形态:索引里存的是已经归一过的
198
+ * 裸对端 ID,创建入口拿到的可能是 `aun#<aid>` 这类带渠道前缀的写法,这里先归一。
199
+ */
200
+ export function isSelfThreadPeer(peer, selfAid) {
201
+ return isSelfTopicPeer(normalizeThreadPeer(peer), normalizeThreadPeer(selfAid));
113
202
  }
114
203
  /** 内部话题(daemon 命名空间的会话记录)的对端标识前缀。 */
115
204
  const INTERNAL_PEER_RE = /^(bg:|trigger:|daemon:|memory:)/;
116
205
  /** 该条目是否为内部话题(非真实联系人,通常没有消息日志)。 */
117
- export function isInternalThreadPeer(peer) {
118
- return INTERNAL_PEER_RE.test(peer);
119
- }
120
206
  function writeIndex(indexPath, index) {
121
- atomicWriteJson(indexPath, index);
207
+ const threads = index.threads.map(entry => sanitizeIndexEntry(entry))
208
+ .filter((result) => result.ok)
209
+ .map(result => result.entry);
210
+ atomicWriteJson(indexPath, { ...index, version: THREAD_INDEX_VERSION, threads });
122
211
  }
123
212
  /**
124
213
  * 索引条目所属的渠道类型。
@@ -173,7 +262,7 @@ export class ThreadService {
173
262
  findInIndex(selfAid, peer, threadId) {
174
263
  const want = normalizeThreadPeer(peer);
175
264
  const index = this.readThreadIndex(selfAid);
176
- const indexed = index.threads.find(t => normalizeThreadPeer(t.peer) === want && t.threadId === threadId);
265
+ const indexed = index.threads.find(t => sameThreadPeer(t.peer, want, entryChannelType(t)) && t.threadId === threadId);
177
266
  if (indexed)
178
267
  return indexed;
179
268
  // Older agents can still have a valid topic session under the per-chat
@@ -183,9 +272,14 @@ export class ThreadService {
183
272
  const recovered = this.recoverThreadFromSessionFiles(selfAid, want, threadId);
184
273
  if (!recovered)
185
274
  return undefined;
275
+ const gated = sanitizeIndexEntry(recovered);
276
+ if (!gated.ok) {
277
+ logger.warn(`[Thread] 丢弃无法恢复的索引条目 thread=${threadId} peer=${want}: ${gated.reason}`);
278
+ return undefined;
279
+ }
186
280
  const next = {
187
281
  version: 1,
188
- threads: [...index.threads, recovered],
282
+ threads: [...index.threads, gated.entry],
189
283
  };
190
284
  try {
191
285
  this.writeThreadIndex(selfAid, next);
@@ -206,7 +300,7 @@ export class ThreadService {
206
300
  if (!dirEntry.isDirectory())
207
301
  continue;
208
302
  const parsedDir = tryParseChannelSessionKey(dirEntry.name);
209
- if (!parsedDir || normalizeThreadPeer(parsedDir.channelId) !== peer)
303
+ if (!parsedDir || !sameThreadPeer(parsedDir.channelId, peer, parsedDir.channelType))
210
304
  continue;
211
305
  const chatDir = path.join(sessionsDir, dirEntry.name);
212
306
  const threadsDir = path.join(chatDir, '_threads');
@@ -220,7 +314,7 @@ export class ThreadService {
220
314
  const last = readLastJsonlLine(path.join(threadsDir, file.name));
221
315
  if (!last || last.threadId !== threadId)
222
316
  continue;
223
- if (normalizeThreadPeer(last.channelId) !== peer)
317
+ if (!sameThreadPeer(last.channelId, peer, parsedDir.channelType))
224
318
  continue;
225
319
  if (last.selfAID && last.selfAID !== selfAid)
226
320
  continue;
@@ -233,7 +327,7 @@ export class ThreadService {
233
327
  channelType: parsedDir.channelType,
234
328
  peerKind: last.chatType === 'group' ? 'group' : 'private',
235
329
  name: last.name ?? threadId,
236
- topicStatus: last.topicStatus ?? 'active',
330
+ topicStatus: readTopicStatusLenient(last.topicStatus),
237
331
  createdAt: last.createdAt ?? 0,
238
332
  lastActiveAt: last.updatedAt ?? 0,
239
333
  ...(typeof last.metadata?.nameUpdatedAt === 'number'
@@ -261,19 +355,65 @@ export class ThreadService {
261
355
  }
262
356
  // ── P1a.1.2: 话题创建 ──
263
357
  async createThread(input) {
264
- const { selfAid, peerKind, name, topicStatus } = input;
358
+ const { peerKind, name, topicStatus } = input;
359
+ const selfAid = normalizeThreadPeer(input.selfAid) ?? input.selfAid;
265
360
  const peer = normalizeThreadPeer(input.peer) ?? input.peer;
361
+ // 本端是拼路径的原料(`aun#<selfAid>#main` 与 `agents/<selfAid>/…`),不校验会
362
+ // 让 `../` 之类的值直接进目录名。CLI 侧 `--self` 走 `isValidAid`,但直调
363
+ // (`ThreadService.createThread`)没有那一层,校验必须落在这里。
364
+ // 用 `isValidAid`(三级)而不是对端那套两级门槛:本端永远是自己这台机器的
365
+ // 完整 AID,不像群 AID 那样有两级形态。
366
+ if (!isValidAid(selfAid)) {
367
+ throw new ThreadServiceError(`本端 AID 不是有效的三级域名形态: ${selfAid}`, 'INVALID_SELF_AID');
368
+ }
266
369
  // Validate name
267
370
  const sanitized = sanitizeSessionTitle(name);
268
371
  if (!sanitized)
269
372
  throw new ThreadServiceError('话题名称不能为空', 'INVALID_NAME');
270
373
  assertThreadNameLength(name, sanitized);
374
+ // 内部对端(`bg:` / `trigger:` / `daemon:` / `memory:`)先单独拦一次:
375
+ // 它们不是 AID,而是 daemon 自己会话的标识,走不到任何真实对端。最主要的
376
+ // 触发场景是「在后台会话 / 定时任务里执行 `/thread create`」——那里的
377
+ // `peerKey` 就是这类标识。归一后的 AID 报错("应为两级以上域名")会让人以为
378
+ // 是拼写问题,实际原因是当前会话根本没有对话方。
379
+ if (isInternalThreadPeer(peer)) {
380
+ throw new ThreadServiceError(`话题对端不能是内部会话标识(${peer})。话题是两端结构,需要一个真实对端 AID。`
381
+ + '当前会话是后台任务或定时触发,没有对话方,请在有对端的会话里创建,'
382
+ + '或用 ec thread create <对端AID> --name <名称> 指定对端', 'INTERNAL_PEER_NOT_ALLOWED');
383
+ }
384
+ // 初步筛查对端形态。门槛按话题口径(两级即可)而非 `isValidAid`(三级),
385
+ // 否则 `g-xxx.agentid.cn` 这类群 AID 会被误杀。
386
+ if (!isTopicPeerAid(peer)) {
387
+ throw new ThreadServiceError(`话题对端不是有效的 AID: ${peer}。应为两级以上域名(如 alice.agentid.cn、g-xxx.agentid.cn)`, 'INVALID_PEER_AID');
388
+ }
389
+ // 话题是两端结构,对端不能是本端。放在建会话之前:一旦建成「我↔我」的会话,
390
+ // 后续索引、会话元数据、回复目标都会指向本端,只能靠人工清理。
391
+ if (isSelfThreadPeer(peer, selfAid)) {
392
+ throw new ThreadServiceError(`话题对端不能是本端自己(${peer})。跨话题自派请先以真实对端建话题,再用 --to <本端AID> 投递`, 'SELF_PEER_NOT_ALLOWED');
393
+ }
271
394
  // Check for duplicate name on same peer
272
395
  const index = this.readThreadIndex(selfAid);
273
- const dup = index.threads.find(t => t.peer === peer && t.name === sanitized);
396
+ // 比对走 `sameThreadPeer`(剥前缀 + 小写),两侧都是:历史条目可能带
397
+ // `aun#<peer>` 前缀,也可能与本次输入大小写不同,裸 `t.peer === peer` 两种都漏判。
398
+ const dup = index.threads.find(t => sameThreadPeer(t.peer, peer, entryChannelType(t)) && t.name === sanitized);
274
399
  if (dup) {
275
400
  throw new ThreadServiceError(`与 ${peer} 已有同名话题: ${sanitized}`, 'TOPIC_CONFLICT');
276
401
  }
402
+ // 名片检查只做本地缓存筛查,绝不联网:建话题不发送任何东西,离线必须可建。
403
+ //
404
+ // 「这个对端口」已经有话题时直接视为已知对端,跳过检查——已有话题本身就
405
+ // 证明关系成立,再去看名片是多余的一次磁盘读。
406
+ //
407
+ // 判据是 PeerIdentityCache 的快照,不是「缓存文件在不在」:`markUnknown`
408
+ // 也会落盘(source='unknown'),只判存在性会把"从未取到名片"当成"有名片"。
409
+ // 验签未通过的 `agentmd-unverified` 仍算见过名片:对端轮换密钥的窗口期
410
+ // 很常见,卡在这里是误杀,与「初步筛查」的定位不符。
411
+ const knownPeer = index.threads.some(t => sameThreadPeer(t.peer, peer, entryChannelType(t)));
412
+ let peerUnverified = false;
413
+ if (!knownPeer) {
414
+ const cached = PeerIdentityCache.get('aun', peer, agentDir(selfAid));
415
+ peerUnverified = !cached || cached.source === 'unknown';
416
+ }
277
417
  const threadId = newThreadId();
278
418
  const now = Date.now();
279
419
  // Create local session via SessionManager
@@ -305,7 +445,13 @@ export class ThreadService {
305
445
  createdAt: now,
306
446
  lastActiveAt: now,
307
447
  };
308
- index.threads.push(entry);
448
+ // 过写入闸门再落盘。正常路径必然通过(peer 与 name 已经校验过),
449
+ // 这里是防御:以后新增分支不用各自记得校验。
450
+ const gated = sanitizeIndexEntry(entry);
451
+ if (!gated.ok) {
452
+ throw new ThreadServiceError(`索引条目无法写入:${gated.reason}`, 'INVALID_INDEX_ENTRY');
453
+ }
454
+ index.threads.push(gated.entry);
309
455
  this.writeThreadIndex(selfAid, index);
310
456
  return {
311
457
  threadId,
@@ -314,6 +460,9 @@ export class ThreadService {
314
460
  peer,
315
461
  peerKind,
316
462
  createdAt: now,
463
+ // 只有为 true 时才出现在返回值里:老调用方按 `'createdAt' in obj` 判类型,
464
+ // 恒带一个 false 字段会让输出与历史结果产生无意义差异。
465
+ ...(peerUnverified ? { peerUnverified: true } : {}),
317
466
  };
318
467
  }
319
468
  // ── P1a.1.5: 话题改名 ──
@@ -345,7 +494,7 @@ export class ThreadService {
345
494
  return { changed: true, name: sanitized, nameUpdatedAt, peerKind: main.peerKind };
346
495
  }
347
496
  const index = this.readThreadIndex(selfAid);
348
- const entry = index.threads.find(t => t.peer === peer && t.threadId === threadId);
497
+ const entry = index.threads.find(t => sameThreadPeer(t.peer, peer, entryChannelType(t)) && t.threadId === threadId);
349
498
  if (!entry)
350
499
  throw new ThreadServiceError(`话题不存在: ${threadId}`, 'TOPIC_NOT_FOUND');
351
500
  if (entry.name === sanitized)
@@ -393,12 +542,12 @@ export class ThreadService {
393
542
  return renamed ? { applied: true } : { applied: false, reason: 'invalid' };
394
543
  }
395
544
  const index = this.readThreadIndex(input.selfAid);
396
- const entry = index.threads.find(t => t.peer === peer && t.threadId === input.threadId);
545
+ const entry = index.threads.find(t => sameThreadPeer(t.peer, peer, entryChannelType(t)) && t.threadId === input.threadId);
397
546
  const current = entry?.nameUpdatedAt ?? 0;
398
547
  if (input.nameUpdatedAt <= current)
399
548
  return { applied: false, reason: 'stale' };
400
549
  if (!entry) {
401
- index.threads.push({
550
+ const created = {
402
551
  threadId: input.threadId,
403
552
  sessionId: '',
404
553
  peer,
@@ -409,7 +558,13 @@ export class ThreadService {
409
558
  topicStatus: 'active',
410
559
  createdAt: input.nameUpdatedAt,
411
560
  lastActiveAt: input.nameUpdatedAt,
412
- });
561
+ };
562
+ // 对端发来的改名通知也会建条目,同样要过闸门:对端可能是群 AID、
563
+ // 也可能是被伪造的畸形值,不能因为"对方说的"就绕开校验。
564
+ const gated = sanitizeIndexEntry(created);
565
+ if (!gated.ok)
566
+ return { applied: false, reason: 'invalid' };
567
+ index.threads.push(gated.entry);
413
568
  this.writeThreadIndex(input.selfAid, index);
414
569
  return { applied: true };
415
570
  }
@@ -427,16 +582,22 @@ export class ThreadService {
427
582
  const { selfAid, threadId, topicStatus } = input;
428
583
  const peer = normalizeThreadPeer(input.peer) ?? input.peer;
429
584
  const index = this.readThreadIndex(selfAid);
430
- const entry = index.threads.find(t => t.peer === peer && t.threadId === threadId);
585
+ const entry = index.threads.find(t => sameThreadPeer(t.peer, peer, entryChannelType(t)) && t.threadId === threadId);
431
586
  if (!entry)
432
587
  throw new ThreadServiceError(`话题不存在: ${threadId}`, 'TOPIC_NOT_FOUND');
588
+ // 版本号取「当前时间」与「旧值 + 1」的较大者,与改名同一口径:时钟回拨或
589
+ // 同一毫秒内连续改状态时,版本仍然严格递增,不会让后一次修改被判成过期。
590
+ const previous = Number(entry.topicStatusUpdatedAt ?? 0);
591
+ const updatedAt = Math.max(Date.now(), previous + 1);
433
592
  entry.topicStatus = topicStatus;
434
- entry.lastActiveAt = Date.now();
593
+ entry.topicStatusUpdatedAt = updatedAt;
594
+ entry.lastActiveAt = updatedAt;
435
595
  this.writeThreadIndex(selfAid, index);
436
596
  this.appendThreadSnapshot(selfAid, entry);
437
597
  const session = await this.sessionManager.getThreadSession(entryChannelType(entry), entry.peer, threadId, selfAid);
438
598
  if (session) {
439
- await this.sessionManager.setTopicStatus(session.id, topicStatus);
599
+ // 会话文件那一侧带着同一个版本号写,两边因此可以按版本判定谁新。
600
+ await this.sessionManager.setTopicStatus(session.id, topicStatus, updatedAt);
440
601
  }
441
602
  }
442
603
  // ── list-peers ──
@@ -540,15 +701,19 @@ export class ThreadService {
540
701
  const peer = normalizeThreadPeer(input.peer);
541
702
  const limit = Math.min(rawLimit ?? LIST_DEFAULT_LIMIT, LIST_MAX_LIMIT);
542
703
  const { index, state: indexState } = this.readThreadIndexWithState(selfAid);
704
+ // 内部话题(`bg:`/`trigger:`)不会出现在这里:读时迁移已经把它们从索引里
705
+ // 摘掉了(见 `migrateIndexOnRead`),不需要在展示层再过滤一次。
706
+ const visible = index.threads;
543
707
  // 未套过滤条件的话题数:用于把「该对端确实没有话题」与
544
708
  // 「有话题但被 --status 挡掉」区分开。
545
709
  const peerTopicCount = peer
546
- ? index.threads.filter(t => normalizeThreadPeer(t.peer) === peer).length
547
- : index.threads.length;
548
- let threads = index.threads.filter(t => {
549
- if (peer && normalizeThreadPeer(t.peer) !== peer)
710
+ ? visible.filter(t => sameThreadPeer(t.peer, peer, entryChannelType(t))).length
711
+ : visible.length;
712
+ let threads = visible.filter(t => {
713
+ if (peer && !sameThreadPeer(t.peer, peer, entryChannelType(t)))
550
714
  return false;
551
- if (status && t.topicStatus !== status)
715
+ // 同理:过滤按归一后的状态比,否则 `--status active` 会漏掉索引里残留旧值的话题。
716
+ if (status && readTopicStatusLenient(t.topicStatus) !== status)
552
717
  return false;
553
718
  return true;
554
719
  });
@@ -727,7 +892,7 @@ export class ThreadService {
727
892
  // 索引里能查到条目时用条目的命名空间(内部话题在 daemon 下),查不到时退回 aun。
728
893
  const indexed = isMainSessionThreadId(threadId)
729
894
  ? undefined
730
- : this.readThreadIndex(selfAid).threads.find(t => t.threadId === threadId && normalizeThreadPeer(t.peer) === peer);
895
+ : this.readThreadIndex(selfAid).threads.find(t => t.threadId === threadId && sameThreadPeer(t.peer, peer, entryChannelType(t)));
731
896
  const chatDir = this.chatDirFor(selfAid, indexed?.peer ?? peer, indexed?.channelType);
732
897
  const logPath = path.join(chatDir, 'messages.jsonl');
733
898
  if (!fs.existsSync(logPath))
@@ -827,7 +992,7 @@ export class ThreadService {
827
992
  : typeof last.nameUpdatedAt === 'number'
828
993
  ? { nameUpdatedAt: last.nameUpdatedAt }
829
994
  : {}),
830
- topicStatus: last.topicStatus ?? 'active',
995
+ topicStatus: readTopicStatusLenient(last.topicStatus),
831
996
  createdAt: last.createdAt ?? 0,
832
997
  lastActiveAt: last.updatedAt ?? 0,
833
998
  });
@@ -838,21 +1003,36 @@ export class ThreadService {
838
1003
  }
839
1004
  }
840
1005
  if (!dryRun) {
841
- const index = { version: 1, threads: entries };
1006
+ // 重建同样过闸门:扫描的是磁盘上的历史文件,里面可能还有旧格式残留。
1007
+ const gatedEntries = entries
1008
+ .map(e => sanitizeIndexEntry(e))
1009
+ .filter((g) => g.ok)
1010
+ .map(g => g.entry);
1011
+ const index = { version: THREAD_INDEX_VERSION, threads: gatedEntries };
842
1012
  this.writeThreadIndex(selfAid, index);
843
1013
  }
844
1014
  return { rebuilt: entries.length };
845
1015
  }
846
1016
  /**
847
- * 检查话题索引的健康状态,区分两类问题:
848
- * missing — _threads JSONL 文件不存在(数据问题,严重,rebuild 会丢失属性改动)
849
- * stale — 文件存在但最后一行的 name/topicStatus 与索引不一致(写盘时序问题,轻微)
1017
+ * 检查话题索引的健康状态,区分四类问题:
1018
+ * missing — _threads JSONL 文件不存在(数据问题,严重,rebuild 会丢失属性改动)
1019
+ * stale — 文件存在但最后一行的 name/topicStatus 与索引不一致(写盘时序问题,轻微)
1020
+ * selfPeer — 对端就是本端自己的残缺话题(结构不成立,rebuild 修不好,只能删除)
1021
+ *
1022
+ * 内部话题(`bg:`/`trigger:`)不在检查范围内:读时迁移已经把这类条目从索引里
1023
+ * 摘掉,它们不会再出现在 `missing` 里淹没真实的数据问题。
850
1024
  */
851
1025
  checkIndex(selfAid) {
852
1026
  const index = this.readThreadIndex(selfAid);
853
1027
  const missingIds = [];
854
1028
  const staleIds = [];
1029
+ const selfPeerIds = [];
1030
+ const staleDetails = [];
855
1031
  for (const entry of index.threads) {
1032
+ // 残缺结构单独计数:它既不是文件缺失也不是属性不同步,rebuild 也无从修复,
1033
+ // 混进另外两类会让用户按建议执行 rebuild 却发现问题依旧。
1034
+ if (isSelfThreadPeer(entry.peer, selfAid))
1035
+ selfPeerIds.push(entry.threadId);
856
1036
  // 按条目自己的命名空间(aun / daemon)拼目录。历史上这里写死 `aun#main#`,
857
1037
  // 导致 daemon 命名空间的内部话题 100% 被误判为 missing。
858
1038
  const chatDir = this.chatDirFor(selfAid, entry.peer, entry.channelType);
@@ -861,13 +1041,16 @@ export class ThreadService {
861
1041
  missingIds.push(entry.threadId);
862
1042
  continue;
863
1043
  }
864
- // 检查最后一行是否与索引一致(name / topicStatus)
1044
+ // 检查最后一行是否与索引一致(name / topicStatus)。
1045
+ // 状态先归一再比:两侧都可能存着旧版本的 `pending`/`in_progress`/`completed`,
1046
+ // 直接比原始值会把"同一个状态"(如两边都是旧值 pending 与 active)判成 stale。
865
1047
  try {
866
1048
  const lines = readAllJsonlLines(metaPath);
867
1049
  const last = lines[lines.length - 1];
868
1050
  if (last && (last.name !== entry.name ||
869
- (last.topicStatus ?? 'active') !== entry.topicStatus)) {
1051
+ readTopicStatusLenient(last.topicStatus) !== readTopicStatusLenient(entry.topicStatus))) {
870
1052
  staleIds.push(entry.threadId);
1053
+ staleDetails.push(describeStatusDrift(entry, last));
871
1054
  }
872
1055
  }
873
1056
  catch {
@@ -879,8 +1062,61 @@ export class ThreadService {
879
1062
  total: index.threads.length,
880
1063
  missing: missingIds.length, missingIds,
881
1064
  stale: staleIds.length, staleIds,
1065
+ selfPeer: selfPeerIds.length, selfPeerIds,
1066
+ staleDetails,
882
1067
  };
883
1068
  }
1069
+ /**
1070
+ * 按版本号把「索引 ↔ 会话文件」的状态漂移对齐。
1071
+ *
1072
+ * 与 `rebuildIndex` 的区别是**逐条、可预览、不丢东西**:只改状态冲突的那几个
1073
+ * 字段,其余条目与属性一概不碰。`apply: false` 时只报告不落盘。
1074
+ *
1075
+ * 方向由版本号决定(`topicStatusUpdatedAt` 较新者胜);两侧都没有版本号的历史
1076
+ * 无状态版本的历史条目保持 ambiguous;消息活跃时间不能证明状态变更。
1077
+ */
1078
+ reconcileStatus(selfAid, options = {}) {
1079
+ const index = this.readThreadIndex(selfAid);
1080
+ const drift = [];
1081
+ let applied = 0;
1082
+ for (const entry of index.threads) {
1083
+ if (isInternalThreadPeer(entry.peer))
1084
+ continue;
1085
+ const chatDir = this.chatDirFor(selfAid, entry.peer, entry.channelType);
1086
+ const metaPath = path.join(chatDir, '_threads', `${entry.sessionId}.jsonl`);
1087
+ if (!fs.existsSync(metaPath))
1088
+ continue;
1089
+ let last;
1090
+ try {
1091
+ const lines = readAllJsonlLines(metaPath);
1092
+ last = lines[lines.length - 1];
1093
+ }
1094
+ catch {
1095
+ continue;
1096
+ }
1097
+ if (!last)
1098
+ continue;
1099
+ const d = describeStatusDrift(entry, last);
1100
+ if (d.kind === 'same')
1101
+ continue;
1102
+ drift.push(d);
1103
+ if (!options.apply)
1104
+ continue;
1105
+ if (d.kind === 'name')
1106
+ continue;
1107
+ if (d.winner === 'index' || d.winner === 'ambiguous')
1108
+ continue;
1109
+ // 只有「文件更新」才回写索引:反过来改会话文件要新增一行快照,属于
1110
+ // append 语义,等下一次真实的 status 写入一并完成,避免这里伪造状态变更。
1111
+ entry.topicStatus = d.fileStatus;
1112
+ entry.topicStatusUpdatedAt = d.fileUpdatedAt ?? Date.now();
1113
+ entry.lastActiveAt = Math.max(Number(entry.lastActiveAt ?? 0), Number(d.fileUpdatedAt ?? 0));
1114
+ applied++;
1115
+ }
1116
+ if (applied > 0)
1117
+ this.writeThreadIndex(selfAid, index);
1118
+ return { drift, applied };
1119
+ }
884
1120
  /**
885
1121
  * 查主会话(show <peer> 不带 threadId):读取与某对端的 active session。
886
1122
  */
@@ -927,7 +1163,7 @@ export class ThreadService {
927
1163
  const want = normalizeThreadPeer(peer);
928
1164
  const indexPath = agentThreadIndexPath(selfAid);
929
1165
  const index = readIndex(indexPath);
930
- const entry = index.threads.find(t => normalizeThreadPeer(t.peer) === want && t.threadId === threadId);
1166
+ const entry = index.threads.find(t => sameThreadPeer(t.peer, want, entryChannelType(t)) && t.threadId === threadId);
931
1167
  if (!entry)
932
1168
  return;
933
1169
  entry.lastActiveAt = Date.now();
@@ -946,7 +1182,7 @@ export class ThreadService {
946
1182
  const want = normalizeThreadPeer(peer);
947
1183
  const indexPath = agentThreadIndexPath(selfAid);
948
1184
  const index = readIndex(indexPath);
949
- const entryIdx = index.threads.findIndex(t => normalizeThreadPeer(t.peer) === want && t.threadId === threadId);
1185
+ const entryIdx = index.threads.findIndex(t => sameThreadPeer(t.peer, want, entryChannelType(t)) && t.threadId === threadId);
950
1186
  if (entryIdx < 0)
951
1187
  throw new ThreadServiceError(`话题不存在: ${threadId}`, 'TOPIC_NOT_FOUND');
952
1188
  const entry = index.threads[entryIdx];
@@ -1007,6 +1243,9 @@ export class ThreadService {
1007
1243
  metadata: {
1008
1244
  ...(latest.metadata ?? {}),
1009
1245
  ...(entry.nameUpdatedAt !== undefined ? { nameUpdatedAt: entry.nameUpdatedAt } : {}),
1246
+ ...(entry.topicStatusUpdatedAt !== undefined
1247
+ ? { topicStatusUpdatedAt: entry.topicStatusUpdatedAt }
1248
+ : {}),
1010
1249
  },
1011
1250
  // topic metadata — updated values
1012
1251
  threadId: entry.threadId,