evolcore 0.0.43-test.6 → 0.0.43-test.8

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 (249) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/bin/ecmsg.js +188 -58
  3. package/dist/agent-template/jobs.js +62 -0
  4. package/dist/agent-template/runtime.js +214 -0
  5. package/dist/agent-template/service.js +465 -0
  6. package/dist/agent-template/tool-runner.js +45 -0
  7. package/dist/agent-template/types.js +5 -0
  8. package/dist/agents/baseagent-availability.js +1 -1
  9. package/dist/agents/claude-runner.js +1 -1
  10. package/dist/agents/codex/app-server-client.js +22 -0
  11. package/dist/agents/codex-runner.js +69 -2
  12. package/dist/aun/aid/agentmd.js +56 -1
  13. package/dist/aun/aid/client.js +3 -1
  14. package/dist/aun/menu/client.js +3 -2
  15. package/dist/aun/msg/p2p.js +6 -1
  16. package/dist/channels/aun.js +277 -49
  17. package/dist/cli/agent-command.js +5 -0
  18. package/dist/cli/agent-create.js +7 -3
  19. package/dist/cli/agent-template.js +124 -0
  20. package/dist/cli/aun-commands.js +2 -2
  21. package/dist/cli/ctl-command.js +2 -1
  22. package/dist/cli/daemon-commands.js +11 -66
  23. package/dist/cli/daemon-lifecycle-client.js +61 -0
  24. package/dist/cli/ecmsg-gateway.js +35 -2
  25. package/dist/cli/events-command.js +109 -0
  26. package/dist/cli/index.js +60 -14
  27. package/dist/cli/invoke-command.js +182 -0
  28. package/dist/cli/managed-command-guard.js +6 -1
  29. package/dist/cli/net-check.js +1 -1
  30. package/dist/cli/restart-monitor.js +160 -83
  31. package/dist/cli/services-command.js +137 -0
  32. package/dist/cli/team-workspace-command.js +134 -0
  33. package/dist/cli/thread-command.js +103 -13
  34. package/dist/cli/watch-msg.js +1 -1
  35. package/dist/config/boot-log.js +8 -8
  36. package/dist/config/config-field-policy.js +2 -2
  37. package/dist/config/config-manager.js +0 -7
  38. package/dist/config/invoke-ipc-service.js +118 -0
  39. package/dist/config/schema-migration.js +45 -15
  40. package/dist/config-store.js +2 -1
  41. package/dist/core/agent-ipc-registration.js +25 -4
  42. package/dist/core/agent-reload-coordinator.js +6 -4
  43. package/dist/core/agent-runtime.js +106 -10
  44. package/dist/core/auth/delegation-authorization.js +66 -0
  45. package/dist/core/auth/operation-authorizer.js +2 -0
  46. package/dist/core/auth/operation-catalog.js +29 -0
  47. package/dist/core/baseagent-loader.js +60 -130
  48. package/dist/core/channel-loader.js +10 -1
  49. package/dist/core/channel-runtime.js +20 -12
  50. package/dist/core/command/agent-control.js +12 -2
  51. package/dist/core/command/agent-storage-menu.js +1 -1
  52. package/dist/core/command/agent-template-menu.js +147 -0
  53. package/dist/core/command/chatmode-config.js +2 -36
  54. package/dist/core/command/command-handler.js +80 -17
  55. package/dist/core/command/data-root-resolver.js +32 -23
  56. package/dist/core/command/eventcenter-menu.js +468 -0
  57. package/dist/core/command/menu-catalog.js +15 -0
  58. package/dist/core/command/menu-handler.js +216 -90
  59. package/dist/core/command/menu-protocol.js +71 -13
  60. package/dist/core/command/menu-query-batch.js +194 -0
  61. package/dist/core/command/slash-gate.js +1 -1
  62. package/dist/core/command/slash-handler.js +34 -42
  63. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  64. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  65. package/dist/core/command/team-workspace-initializer.js +2 -0
  66. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  67. package/dist/core/command/team-workspace-job-store.js +88 -0
  68. package/dist/core/command/team-workspace-management-service.js +2 -0
  69. package/dist/core/command/team-workspace-management-store.js +96 -0
  70. package/dist/core/command/team-workspace-management.js +265 -0
  71. package/dist/core/command/team-workspace-members-menu.js +88 -0
  72. package/dist/core/command/team-workspace-store.js +612 -0
  73. package/dist/core/command/team-workspace-team.js +193 -0
  74. package/dist/core/daemon-control.js +22 -5
  75. package/dist/core/daemon-lifecycle.js +323 -191
  76. package/dist/core/handoff/runtime.js +45 -13
  77. package/dist/core/invoke/executors/index.js +13 -0
  78. package/dist/core/invoke/executors/media.js +283 -0
  79. package/dist/core/invoke/executors/text.js +198 -0
  80. package/dist/core/invoke/invoke-service.js +157 -0
  81. package/dist/core/invoke/style-router.js +48 -0
  82. package/dist/core/invoke/types.js +19 -0
  83. package/dist/core/ipc-registration.js +50 -7
  84. package/dist/core/legacy-rename.js +41 -0
  85. package/dist/core/memory/consolidation.js +7 -5
  86. package/dist/core/message/aun-ipc-sender.js +252 -17
  87. package/dist/core/message/im-renderer.js +116 -85
  88. package/dist/core/message/message-bridge.js +4 -0
  89. package/dist/core/message/message-queue.js +66 -15
  90. package/dist/core/message/message-utils.js +10 -2
  91. package/dist/core/message/peer-mode.js +7 -34
  92. package/dist/core/message/pending-hints.js +29 -5
  93. package/dist/core/message/response-engine.js +194 -61
  94. package/dist/core/message/send-options.js +7 -4
  95. package/dist/core/message/send-routing.js +50 -5
  96. package/dist/core/ownership/owner-resolver.js +7 -0
  97. package/dist/core/pack-auth.js +94 -0
  98. package/dist/core/pack-install.js +194 -0
  99. package/dist/core/permission/ec-command-parser.js +51 -17
  100. package/dist/core/permission/protected-paths.js +12 -2
  101. package/dist/core/permission/shell-environment.js +9 -0
  102. package/dist/core/rate-window.js +48 -0
  103. package/dist/core/relation/peer-identity.js +28 -0
  104. package/dist/core/session/session-file-health.js +243 -0
  105. package/dist/core/session/session-fs-store.js +67 -28
  106. package/dist/core/session/session-idle-monitor.js +59 -19
  107. package/dist/core/session/session-manager.js +13 -4
  108. package/dist/core/task/task-recovery-service.js +13 -2
  109. package/dist/core/thread/command-parser.js +9 -2
  110. package/dist/core/thread/thread-operation.js +21 -2
  111. package/dist/core/thread/thread-route.js +13 -2
  112. package/dist/core/thread/thread-service.js +52 -3
  113. package/dist/directory/owner-directory-admission.js +40 -53
  114. package/dist/directory/owner-directory-cache.js +89 -113
  115. package/dist/directory/owner-directory-query-operation.js +8 -10
  116. package/dist/eck/kit-renderer.js +7 -5
  117. package/dist/eck/message-renderer.js +2 -0
  118. package/dist/ecweb/basic-settings-service.js +1 -1
  119. package/dist/ecweb/message-context-service.js +0 -4
  120. package/dist/ecweb/runtime/lifecycle.js +6 -2
  121. package/dist/ecweb/runtime/supervisor.js +19 -4
  122. package/dist/event-center/admission-materializer.js +124 -0
  123. package/dist/event-center/bus-gate.js +154 -0
  124. package/dist/event-center/bus-host.js +307 -0
  125. package/dist/event-center/bus-resolver.js +120 -0
  126. package/dist/event-center/center-config.js +127 -0
  127. package/dist/event-center/daemon.js +44 -0
  128. package/dist/event-center/directory-source.js +55 -0
  129. package/dist/event-center/dispatcher.js +157 -0
  130. package/dist/event-center/event-log.js +110 -0
  131. package/dist/event-center/index-generator.js +73 -0
  132. package/dist/event-center/ipc-operation.js +423 -0
  133. package/dist/event-center/ledger.js +52 -0
  134. package/dist/event-center/pack-loader.js +207 -0
  135. package/dist/event-center/pack-manager.js +85 -0
  136. package/dist/event-center/registry.js +463 -0
  137. package/dist/event-center/runtime.js +837 -0
  138. package/dist/event-center/script-runner.js +356 -0
  139. package/dist/event-center/types.js +51 -0
  140. package/dist/event-center/validation.js +435 -0
  141. package/dist/index.js +424 -135
  142. package/dist/ipc.js +106 -12
  143. package/dist/paths.js +20 -0
  144. package/dist/product.js +14 -0
  145. package/dist/proxy/manager.js +5 -1
  146. package/dist/proxy/service-supervisor.js +13 -4
  147. package/dist/response-system/engines/v1/index.js +0 -1
  148. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  149. package/dist/response-system/modes/single-session/index.js +1 -1
  150. package/dist/services/dispatcher.js +100 -0
  151. package/dist/services/idempotency.js +90 -0
  152. package/dist/services/identity.js +52 -0
  153. package/dist/services/index-generator.js +70 -0
  154. package/dist/services/index.js +449 -0
  155. package/dist/services/ipc-operation.js +550 -0
  156. package/dist/services/ledger.js +52 -0
  157. package/dist/services/message-log.js +112 -0
  158. package/dist/services/pack-manager.js +215 -0
  159. package/dist/services/reply.js +55 -0
  160. package/dist/services/router.js +98 -0
  161. package/dist/services/script-runner.js +422 -0
  162. package/dist/services/service-payload.js +70 -0
  163. package/dist/services/types.js +18 -0
  164. package/dist/services/validation.js +297 -0
  165. package/dist/trigger/application-service.js +18 -0
  166. package/dist/trigger/event-source.js +1 -1
  167. package/dist/trigger/ipc-service.js +3 -1
  168. package/dist/trigger/scheduler.js +38 -0
  169. package/dist/trigger/script-sandbox.js +170 -24
  170. package/dist/utils/cross-platform.js +24 -10
  171. package/dist/utils/evolcore-version.js +69 -27
  172. package/dist/utils/instance-registry.js +19 -13
  173. package/dist/utils/npm-ops.js +2 -1
  174. package/dist/utils/package-version-info.js +6 -3
  175. package/dist/utils/process-introspect.js +45 -9
  176. package/dist/utils/startup-trace.js +74 -37
  177. package/dist/utils/windows-shell-trust.js +80 -6
  178. package/kits/docs/INDEX.md +2 -2
  179. package/kits/docs/aun/ABILITY_CALLING.md +9 -15
  180. package/kits/docs/context-assembly.md +1 -1
  181. package/kits/docs/evolcore/INDEX.md +3 -1
  182. package/kits/docs/evolcore/ability.md +4 -0
  183. package/kits/docs/evolcore/agent.md +22 -1
  184. package/kits/docs/evolcore/aid.md +1 -1
  185. package/kits/docs/evolcore/event-center.md +227 -0
  186. package/kits/docs/evolcore/file-navigation.md +10 -264
  187. package/kits/docs/evolcore/fs.md +5 -3
  188. package/kits/docs/evolcore/group.md +1 -1
  189. package/kits/docs/evolcore/memory-architecture.md +2 -0
  190. package/kits/docs/evolcore/menu-protocol.md +28 -1
  191. package/kits/docs/evolcore/msg.md +21 -9
  192. package/kits/docs/evolcore/provider.md +3 -1
  193. package/kits/docs/evolcore/response.md +5 -5
  194. package/kits/docs/evolcore/services.md +294 -0
  195. package/kits/docs/evolcore/task.md +2 -0
  196. package/kits/docs/evolcore/team-workspace.md +41 -0
  197. package/kits/docs/evolcore/thread-chain.md +15 -3
  198. package/kits/eck_manifest.json +26 -0
  199. package/kits/rules/02-navigation.md +10 -1
  200. package/kits/rules/06-channel.md +1 -0
  201. package/kits/schemas/_meta.json +17 -6
  202. package/kits/schemas/agent-config.schema.19.json +5 -7
  203. package/kits/schemas/agent-config.schema.20.json +936 -0
  204. package/kits/schemas/relation-config.schema.12.json +2 -3
  205. package/kits/schemas/role-config.schema.2.json +4 -4
  206. package/kits/skills/.switches.json +1 -5
  207. package/kits/skills/ability/SKILL.md +56 -0
  208. package/kits/skills/ability/references/calling.md +56 -0
  209. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  210. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  211. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  212. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  213. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  214. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  215. package/kits/skills/ec-group/SKILL.md +5 -8
  216. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  217. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  218. package/kits/skills/ec-trigger/SKILL.md +4 -4
  219. package/kits/skills/personal-assistant/SKILL.md +6 -6
  220. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  221. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  222. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  223. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  224. package/kits/skills/thread-ops/SKILL.md +10 -10
  225. package/kits/templates/message-fragments/item.md +1 -1
  226. package/kits/templates/system-fragments/channel.md +3 -3
  227. package/kits/templates/system-fragments/commands.md +5 -3
  228. package/kits/templates/system-fragments/reply.md +1 -5
  229. package/kits/templates/system-fragments/thread.md +13 -10
  230. package/package.json +5 -6
  231. package/scripts/agent-template/index.mjs +40 -0
  232. package/scripts/agent-template/inspect.mjs +240 -0
  233. package/scripts/agent-template/overlay.mjs +71 -0
  234. package/scripts/agent-template/pack.mjs +169 -0
  235. package/scripts/agent-template/shared/common.mjs +235 -0
  236. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  237. package/scripts/agent-template/shared/plan.mjs +129 -0
  238. package/scripts/agent-template/shared/team-schema.json +70 -0
  239. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  240. package/scripts/agent-template/shared/template-package.mjs +265 -0
  241. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  242. package/scripts/agent-template/shared/template.mjs +142 -0
  243. package/dist/cli/pa-workspace-command.js +0 -225
  244. package/dist/core/command/pa-workspace-store.js +0 -468
  245. package/dist/core/relation/pa-team.js +0 -132
  246. package/kits/docs/evolcore/pa-workspace.md +0 -51
  247. package/kits/skills/aid-ability/SKILL.md +0 -244
  248. package/kits/skills/ec-ability/SKILL.md +0 -67
  249. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -0,0 +1,134 @@
1
+ import path from 'node:path';
2
+ import { authorizeLocalCommand } from './task-context.js';
3
+ import { agentWorkspaceDir } from '../paths.js';
4
+ import { readTeamWorkspaceNavigation, upsertTeamWorkspaceNavigation, removeTeamWorkspaceNavigation, updateTeamWorkspaceNavigation, } from '../core/command/team-workspace-store.js';
5
+ import { readTeamMembers, updateTeamMembers } from '../core/command/team-workspace-team.js';
6
+ import { TeamWorkspaceBootstrapService, TeamWorkspaceInitializer } from '../core/command/team-workspace-bootstrap.js';
7
+ const USAGE = `用法: ec team workspace init [--workspace <绝对路径>]
8
+ ec team navigation show
9
+ ec team navigation update --upsert-json <entries-json> [--expected-revision <n>]
10
+ ec team navigation update --remove-ids-json <ids-json> [--expected-revision <n>]
11
+ ec team navigation update --replace-json <entries-json> [--expected-revision <n>]
12
+ ec team members show
13
+ ec team members update --members-json <aids-json>
14
+
15
+ 所有命令只输出 JSON;只允许当前 Agent Owner 的 AUN 私聊托管会话。`;
16
+ class TeamWorkspaceCommandError extends Error {
17
+ code;
18
+ constructor(code, message) {
19
+ super(message);
20
+ this.code = code;
21
+ this.name = 'TeamWorkspaceCommandError';
22
+ }
23
+ }
24
+ function parseJsonFlag(args, flag) {
25
+ const index = args.indexOf(flag);
26
+ if (index < 0 || !args[index + 1])
27
+ throw new TeamWorkspaceCommandError('INVALID_ARGUMENT', `${flag} is required`);
28
+ try {
29
+ return JSON.parse(args[index + 1]);
30
+ }
31
+ catch {
32
+ throw new TeamWorkspaceCommandError('INVALID_ARGUMENT', `${flag} must contain valid JSON`);
33
+ }
34
+ }
35
+ function assertFlags(args, allowed) {
36
+ const seen = new Set();
37
+ for (let index = 0; index < args.length; index += 2) {
38
+ const flag = args[index];
39
+ if (!allowed.includes(flag) || seen.has(flag) || !args[index + 1]) {
40
+ throw new TeamWorkspaceCommandError('INVALID_ARGUMENT', `Unexpected or duplicate argument: ${flag ?? ''}`);
41
+ }
42
+ seen.add(flag);
43
+ }
44
+ }
45
+ function expectedRevision(args, current) {
46
+ const index = args.indexOf('--expected-revision');
47
+ if (index < 0)
48
+ return current;
49
+ const raw = args[index + 1];
50
+ if (!raw || !/^\d+$/.test(raw))
51
+ throw new TeamWorkspaceCommandError('INVALID_ARGUMENT', '--expected-revision must be a non-negative integer');
52
+ const revision = Number(raw);
53
+ if (!Number.isSafeInteger(revision))
54
+ throw new TeamWorkspaceCommandError('INVALID_ARGUMENT', '--expected-revision must be a safe integer');
55
+ return revision;
56
+ }
57
+ function output(value) { process.stdout.write(`${JSON.stringify(value, null, 2)}\n`); }
58
+ function assertOwnerContext(context) {
59
+ if (context.channel !== 'aun' || context.chatType !== 'private' || context.peerRole !== 'owner' || !context.selfAid || !context.peerId) {
60
+ throw new TeamWorkspaceCommandError('NOT_ALLOWED', 'Team workspace commands require the current Agent Owner in an AUN private chat');
61
+ }
62
+ }
63
+ function initializeWorkspace(aid, ownerAid, suppliedPath) {
64
+ if (suppliedPath && !path.isAbsolute(suppliedPath))
65
+ throw new TeamWorkspaceCommandError('INVALID_ARGUMENT', '--workspace must be an absolute path');
66
+ const result = new TeamWorkspaceInitializer().initialize({ agentAid: aid, ownerAid }, suppliedPath ?? agentWorkspaceDir(aid), { allowExistingContent: !!suppliedPath });
67
+ return { workspaceId: result.state.workspaceId, navigationRevision: result.state.navigationRevision, rootPath: result.state.rootPath };
68
+ }
69
+ export async function cmdTeamWorkspace(rawArgs) {
70
+ if (rawArgs.length === 0 || rawArgs.includes('--help') || rawArgs.includes('-h')) {
71
+ console.log(USAGE);
72
+ return;
73
+ }
74
+ try {
75
+ const context = await authorizeLocalCommand(['team', ...rawArgs]);
76
+ assertOwnerContext(context);
77
+ if (rawArgs[0] === 'workspace' && rawArgs[1] === 'init') {
78
+ const pathIndex = rawArgs.indexOf('--workspace');
79
+ const workspace = pathIndex >= 0 ? rawArgs[pathIndex + 1] : undefined;
80
+ if (pathIndex >= 0 && (!workspace || rawArgs.length !== 4))
81
+ throw new TeamWorkspaceCommandError('INVALID_ARGUMENT', USAGE);
82
+ if (pathIndex < 0 && rawArgs.length !== 2)
83
+ throw new TeamWorkspaceCommandError('INVALID_ARGUMENT', USAGE);
84
+ if (!workspace)
85
+ new TeamWorkspaceBootstrapService().migrateLegacyDefault({ agentAid: context.selfAid, ownerAid: context.peerId });
86
+ output({ ok: true, ...initializeWorkspace(context.selfAid, context.peerId, workspace) });
87
+ return;
88
+ }
89
+ if (rawArgs[0] === 'navigation' && rawArgs[1] === 'show' && rawArgs.length === 2) {
90
+ new TeamWorkspaceBootstrapService().migrateLegacyDefault({ agentAid: context.selfAid, ownerAid: context.peerId });
91
+ output({ ok: true, ...readTeamWorkspaceNavigation(context.selfAid) });
92
+ return;
93
+ }
94
+ if (rawArgs[0] === 'navigation' && rawArgs[1] === 'update') {
95
+ new TeamWorkspaceBootstrapService().migrateLegacyDefault({ agentAid: context.selfAid, ownerAid: context.peerId });
96
+ assertFlags(rawArgs.slice(2), ['--upsert-json', '--remove-ids-json', '--replace-json', '--expected-revision']);
97
+ const modes = ['--upsert-json', '--remove-ids-json', '--replace-json'].filter(flag => rawArgs.includes(flag));
98
+ if (modes.length !== 1)
99
+ throw new TeamWorkspaceCommandError('INVALID_ARGUMENT', 'Specify exactly one navigation update mode');
100
+ const navigation = readTeamWorkspaceNavigation(context.selfAid);
101
+ const revision = expectedRevision(rawArgs, navigation.navigationRevision);
102
+ const mode = modes[0];
103
+ const value = parseJsonFlag(rawArgs, mode);
104
+ let result;
105
+ if (mode === '--upsert-json')
106
+ result = upsertTeamWorkspaceNavigation(context.selfAid, revision, value);
107
+ else if (mode === '--remove-ids-json')
108
+ result = removeTeamWorkspaceNavigation(context.selfAid, revision, value);
109
+ else
110
+ result = updateTeamWorkspaceNavigation(context.selfAid, revision, value);
111
+ output({ ok: true, action: mode.slice(2, -5), ...result });
112
+ return;
113
+ }
114
+ if (rawArgs[0] === 'members' && rawArgs[1] === 'show' && rawArgs.length === 2) {
115
+ output({ ok: true, aid: context.selfAid, members: readTeamMembers(context.selfAid) });
116
+ return;
117
+ }
118
+ if (rawArgs[0] === 'members' && rawArgs[1] === 'update') {
119
+ assertFlags(rawArgs.slice(2), ['--members-json']);
120
+ if (rawArgs.length !== 4)
121
+ throw new TeamWorkspaceCommandError('INVALID_ARGUMENT', USAGE);
122
+ const members = parseJsonFlag(rawArgs, '--members-json');
123
+ const result = updateTeamMembers(context.selfAid, members);
124
+ output({ ok: true, aid: context.selfAid, ...result });
125
+ return;
126
+ }
127
+ throw new TeamWorkspaceCommandError('INVALID_ARGUMENT', USAGE);
128
+ }
129
+ catch (error) {
130
+ const source = error;
131
+ process.stderr.write(`${JSON.stringify({ ok: false, code: source.code ?? 'TEAM_WORKSPACE_FAILED', error: error instanceof Error ? error.message : String(error) })}\n`);
132
+ process.exitCode = 1;
133
+ }
134
+ }
@@ -15,7 +15,7 @@ const HELP_TEXT = `
15
15
  list <peer> 列出与某对端的所有话题
16
16
  show <ref> 查看单个话题的元数据
17
17
  history <ref> 读取话题历史消息
18
- create <peer> --name 新建话题
18
+ create <peer> --name 新建话题(对端类型按关系证据自动识别,--group/--private 可覆盖)
19
19
  rename <ref> <名称> 修改话题名称(仅本端)
20
20
  label <ref> <标签> 设置话题标签
21
21
  status <ref> <状态> 更新话题业务状态
@@ -118,6 +118,68 @@ function printResult(data, jsonFormat, opts) {
118
118
  printItem(data, opts);
119
119
  }
120
120
  }
121
+ /**
122
+ * 空结果的成因诊断。分界线是「语法错误」(调用方已在前置校验里 exit 1)
123
+ * 与「语法合法但查不到」——后者一律 exit 0,但要说明是哪一种查不到。
124
+ */
125
+ function printEmptyThreadList(result, echoSelf) {
126
+ const peer = result.peer ?? '<peer>';
127
+ const self = echoSelf ? ` --self ${echoSelf}` : '';
128
+ if (result.indexState === 'corrupt') {
129
+ console.error('✗ 话题索引文件损坏,无法读取(数据文件仍在,重建索引不丢消息)');
130
+ console.error(' 先检查: ec thread rebuild-index --check');
131
+ console.error(' 修复: ec thread rebuild-index');
132
+ process.exitCode = 1;
133
+ return;
134
+ }
135
+ console.log(`0 条 · ${peer}`);
136
+ if (result.peerKnown === false) {
137
+ console.log(' 原因: 与该对端没有任何往来记录(索引和聊天日志中都没有)');
138
+ console.log(' 下一步: ec thread peers # 查看确实有话题记录的对端');
139
+ return;
140
+ }
141
+ if ((result.peerTopicCount ?? 0) > 0) {
142
+ const filters = [];
143
+ if (result.status)
144
+ filters.push(`--status ${result.status}`);
145
+ if (result.label)
146
+ filters.push(`--label "${result.label}"`);
147
+ if (result.unlabeled)
148
+ filters.push('--unlabeled');
149
+ console.log(` 原因: 该对端共 ${result.peerTopicCount} 个话题,均不匹配${filters.length ? ' ' + filters.join(' ') : '当前过滤条件'}`);
150
+ console.log(` 下一步: ec thread list ${peer}${self} # 去掉过滤条件`);
151
+ return;
152
+ }
153
+ if (result.hasMainChat) {
154
+ console.log(' 原因: 该对端只有主话题往来,没有独立话题;主话题不参与状态/标签过滤');
155
+ console.log(` 下一步: ec thread history ${peer}${self}`);
156
+ return;
157
+ }
158
+ if (result.indexState === 'missing') {
159
+ console.log(' 原因: 话题索引尚未建立');
160
+ console.log(' 下一步: ec thread rebuild-index');
161
+ return;
162
+ }
163
+ console.log(' 原因: 索引中没有该对端的话题,且没有主话题往来');
164
+ console.log(' 下一步: ec thread peers');
165
+ }
166
+ /**
167
+ * 对端标识的语法校验(存在性由 daemon 侧判断,这里只挡形态错误)。
168
+ * 合法:`alice.agentid.cn`、`aun#alice.agentid.cn`、非 AUN 渠道的 `ou_xxx`。
169
+ * 非法:空、含空白、`#` 之后为空。
170
+ */
171
+ function invalidPeerArg(raw) {
172
+ const trimmed = raw.trim();
173
+ if (!trimmed || /\s/.test(trimmed))
174
+ return true;
175
+ const tail = trimmed.includes('#') ? trimmed.slice(trimmed.lastIndexOf('#') + 1) : trimmed;
176
+ let decoded = tail;
177
+ try {
178
+ decoded = decodeURIComponent(tail);
179
+ }
180
+ catch { /* 解码失败不改变语法判断 */ }
181
+ return !decoded.trim();
182
+ }
121
183
  function printItem(item, opts) {
122
184
  if (typeof item !== 'object' || !item) {
123
185
  console.log(String(item));
@@ -195,6 +257,11 @@ function printItem(item, opts) {
195
257
  // ListThreadsResult
196
258
  if ('threads' in obj && Array.isArray(obj.threads)) {
197
259
  const result = obj;
260
+ // 空结果不裸打 0 条:区分「语法没错但查不到」的四种成因(见 B1 空探针)。
261
+ if (result.total === 0) {
262
+ printEmptyThreadList(result, opts?.echoSelf);
263
+ return;
264
+ }
198
265
  for (const t of result.threads)
199
266
  printItem(t);
200
267
  const shown = result.threads.length;
@@ -279,6 +346,13 @@ export async function runThreadCommand(args) {
279
346
  process.exitCode = 1;
280
347
  return;
281
348
  }
349
+ // 形态错属于「参数错误」,必须报错退出;查不到结果走空态诊断,两者不混。
350
+ if (invalidPeerArg(peer)) {
351
+ console.error(`✗ 对端标识无效: '${peer}'`);
352
+ console.error(' 应为裸 AID(如 alice.agentid.cn)或 <channel>#<peerId>');
353
+ process.exitCode = 1;
354
+ return;
355
+ }
282
356
  const statusVal = argValue(args, '--status');
283
357
  // B9: 枚举校验
284
358
  if (statusVal && !TOPIC_STATUSES.includes(statusVal)) {
@@ -374,6 +448,12 @@ export async function runThreadCommand(args) {
374
448
  process.exitCode = 1;
375
449
  return;
376
450
  }
451
+ if (invalidPeerArg(peer)) {
452
+ console.error(`✗ 对端标识无效: '${peer}'`);
453
+ console.error(' 应为裸 AID(如 alice.agentid.cn)或 <channel>#<peerId>');
454
+ process.exitCode = 1;
455
+ return;
456
+ }
377
457
  const name = argValue(args, '--name');
378
458
  if (!name) {
379
459
  console.error('✗ 必须指定 --name');
@@ -382,7 +462,11 @@ export async function runThreadCommand(args) {
382
462
  }
383
463
  const label = argValue(args, '--label');
384
464
  const topicStatus = argValue(args, '--status');
385
- const peerKind = hasFlag(args, '--group') ? 'group' : 'private';
465
+ // 对端类型:显式 --group / --private 优先;都不写时 daemon 侧按关系证据
466
+ // 推断(这里不能自行补值——daemon 会用 argv 重建请求,两者必须一致)。
467
+ const peerKind = hasFlag(args, '--group')
468
+ ? 'group'
469
+ : hasFlag(args, '--private') ? 'private' : undefined;
386
470
  const resp = await sendOp({ op: 'create', selfAid, peer, name, label, topicStatus, peerKind });
387
471
  if (!resp.ok) {
388
472
  console.error(`✗ ${resp.error}`);
@@ -497,15 +581,19 @@ export async function runThreadCommand(args) {
497
581
  }
498
582
  const r = resp.result;
499
583
  if (dryRun) {
500
- if (r.missing === 0 && r.stale === 0) {
501
- console.log(`✓ 索引健康:共 ${r.rebuilt} 条话题,session 文件完整`);
584
+ // 两个计数都可能缺省(接口只回传有问题的维度),缺省按 0 处理,
585
+ // 否则健康状态也会落进「建议 rebuild」分支。
586
+ const missing = r.missing ?? 0;
587
+ const stale = r.stale ?? 0;
588
+ if (missing === 0 && stale === 0) {
589
+ console.log(`✓ 索引健康:共 ${r.rebuilt ?? r.total} 条话题,session 文件完整`);
502
590
  }
503
591
  else {
504
- if (r.missing > 0) {
505
- console.warn(`⚠ [严重] ${r.missing} 条话题 session 文件缺失——rebuild 后这些话题的 rename/label/status 改动将回退`);
592
+ if (missing > 0) {
593
+ console.warn(`⚠ [严重] ${missing} 条话题 session 文件缺失——rebuild 后这些话题的 rename/label/status 改动将回退`);
506
594
  }
507
- if (r.stale > 0) {
508
- console.warn(`⚠ [轻微] ${r.stale} 条话题属性与 session 文件最后一行不一致(写盘时序),rebuild-index 可修复`);
595
+ if (stale > 0) {
596
+ console.warn(`⚠ [轻微] ${stale} 条话题属性与 session 文件最后一行不一致(写盘时序),rebuild-index 可修复`);
509
597
  }
510
598
  console.warn(` 建议执行 ec thread rebuild-index 修复`);
511
599
  if (jsonFormat)
@@ -528,15 +616,17 @@ export async function runThreadCommand(args) {
528
616
  return;
529
617
  }
530
618
  const r = resp.result;
531
- if (r.missing === 0 && r.stale === 0) {
619
+ const missing = r.missing ?? 0;
620
+ const stale = r.stale ?? 0;
621
+ if (missing === 0 && stale === 0) {
532
622
  console.log(`✓ 索引健康:共 ${r.total} 条话题,session 文件完整`);
533
623
  }
534
624
  else {
535
- if (r.missing > 0) {
536
- console.warn(`⚠ [严重] ${r.missing} 条话题 session 文件缺失——rebuild 后这些话题的 rename/label/status 改动将回退`);
625
+ if (missing > 0) {
626
+ console.warn(`⚠ [严重] ${missing} 条话题 session 文件缺失——rebuild 后这些话题的 rename/label/status 改动将回退`);
537
627
  }
538
- if (r.stale > 0) {
539
- console.warn(`⚠ [轻微] ${r.stale} 条话题属性与 session 文件最后一行不一致(写盘时序),rebuild-index 可修复`);
628
+ if (stale > 0) {
629
+ console.warn(`⚠ [轻微] ${stale} 条话题属性与 session 文件最后一行不一致(写盘时序),rebuild-index 可修复`);
540
630
  }
541
631
  console.warn(` 建议执行 ec thread rebuild-index 修复`);
542
632
  if (jsonFormat)
@@ -302,7 +302,7 @@ function renderMessagesPanel(state, width, height) {
302
302
  const isGroup = m.chatType === 'group';
303
303
  const chatTag = isGroup ? `${MAGENTA}[群聊]${RST}` : '';
304
304
  const encLabel = m.encrypt ? '密文' : '明文';
305
- const modeLabel = m.chatmode === 'paactive' ? 'PA' : m.chatmode === 'proactive' ? '自主' : '响应';
305
+ const modeLabel = m.chatmode === 'proactive' ? '自主' : '响应';
306
306
  const metaTags = (m.encrypt != null || m.chatmode) ? `${MAGENTA}[${encLabel}|${modeLabel}]${RST}` : '';
307
307
  // observer 插话:醒目标记,与对端真实消息区分
308
308
  const injectTag = m.source === 'owner-inject' ? `${YELLOW}[插话]${RST}` : '';
@@ -15,7 +15,7 @@ import { logger } from '../utils/logger.js';
15
15
  import { autoMigrateIfNeeded } from '../config-store.js';
16
16
  import { ConfigTarget, initConfigManager, notifyConfigWrite } from './config-manager.js';
17
17
  import { ensureRoleConfigV4OnStartup, ensureRoleConfigV5OnStartup } from './role-migration-startup.js';
18
- import { ensureAccessPolicyMigrationOnStartup, ensureAgentModelProviderMigrationOnStartup, ensureAgentOnlyModelMigrationOnStartup, ensureAuxiliaryModelMigrationOnStartup, ensurePeerFileRenameOnStartup, ensurePublishedSchemaConsolidationMigrationOnStartup, ensureProviderServiceTypeMigrationOnStartup, ensureProviderIdentityMigrationOnStartup, ensureRelationConfigVersionMigrationOnStartup, invalidateMigrationReadCache, withMigrationReadCache, } from './schema-migration.js';
18
+ import { ensureAccessPolicyMigrationOnStartup, ensureAgentModelProviderMigrationOnStartup, ensureAgentOnlyModelMigrationOnStartup, ensureAuxiliaryModelMigrationOnStartup, ensurePeerFileRenameOnStartup, ensureStartupConfigCompatibilityMigrationOnStartup, ensureProviderServiceTypeMigrationOnStartup, ensureProviderIdentityMigrationOnStartup, ensureRelationConfigVersionMigrationOnStartup, invalidateMigrationReadCache, withMigrationReadCache, } from './schema-migration.js';
19
19
  import { ensureContactBookV2OnStartup } from './peer-book-v2-startup.js';
20
20
  import { synchronizeAllManagementPeersSync } from './peer-book-store.js';
21
21
  import { readInstalledEvolcoreVersion, readFastaunVersion } from '../utils/evolcore-version.js';
@@ -38,9 +38,9 @@ export async function prepareStartupConfig(recoverRoleMutations, onStep) {
38
38
  step('auxiliaryModel');
39
39
  // 任一迁移真的落盘后立刻丢弃缓存:这三个迁移改的是同一批 relation 配置,
40
40
  // 后一个迁移若沿用写盘前的旧文本做整文件覆盖,会把前一个的改动回滚掉。
41
- const { publishedSchemaConsolidationMigration, auxiliaryModelMigration, agentOnlyModelMigration, relationVersionMigration } = await withMigrationReadCache(async () => {
42
- const publishedSchemaConsolidation = await ensurePublishedSchemaConsolidationMigrationOnStartup();
43
- if (publishedSchemaConsolidation)
41
+ const { startupConfigCompatibilityMigration, auxiliaryModelMigration, agentOnlyModelMigration, relationVersionMigration } = await withMigrationReadCache(async () => {
42
+ const startupConfigCompatibility = await ensureStartupConfigCompatibilityMigrationOnStartup();
43
+ if (startupConfigCompatibility)
44
44
  invalidateMigrationReadCache();
45
45
  const auxiliary = await ensureAuxiliaryModelMigrationOnStartup();
46
46
  if (auxiliary)
@@ -52,15 +52,15 @@ export async function prepareStartupConfig(recoverRoleMutations, onStep) {
52
52
  if (relationVersion)
53
53
  invalidateMigrationReadCache();
54
54
  return {
55
- publishedSchemaConsolidationMigration: publishedSchemaConsolidation,
55
+ startupConfigCompatibilityMigration: startupConfigCompatibility,
56
56
  auxiliaryModelMigration: auxiliary,
57
57
  agentOnlyModelMigration: agentOnly,
58
58
  relationVersionMigration: relationVersion,
59
59
  };
60
60
  });
61
- if (publishedSchemaConsolidationMigration) {
62
- const message = `✓ Published schema consolidation applied automatically: ${publishedSchemaConsolidationMigration.changedFiles} file(s) restamped`
63
- + (publishedSchemaConsolidationMigration.backup ? `; backup: ${publishedSchemaConsolidationMigration.backup}` : '');
61
+ if (startupConfigCompatibilityMigration) {
62
+ const message = `✓ Startup config compatibility migration applied automatically: ${startupConfigCompatibilityMigration.changedFiles} file(s)`
63
+ + (startupConfigCompatibilityMigration.backup ? `; backup: ${startupConfigCompatibilityMigration.backup}` : '');
64
64
  logger.info(message);
65
65
  console.error(message);
66
66
  }
@@ -328,9 +328,9 @@ export function parseConfigFieldValue(fieldPath, rawValue) {
328
328
  ? { ok: true, value: raw }
329
329
  : { ok: false, reason: 'Config field chatmode.group is fixed to proactive' };
330
330
  }
331
- return raw === 'interactive' || raw === 'proactive' || raw === 'paactive'
331
+ return raw === 'interactive' || raw === 'proactive'
332
332
  ? { ok: true, value: raw }
333
- : { ok: false, reason: `Config field ${fieldPath} must be interactive, proactive, or paactive` };
333
+ : { ok: false, reason: `Config field ${fieldPath} must be interactive or proactive` };
334
334
  case 'mention-mode':
335
335
  return raw === 'disabled' || raw === 'mention-only' || raw === 'auto'
336
336
  ? { ok: true, value: raw }
@@ -978,10 +978,6 @@ export function write(target, value, sel, opts = {}) {
978
978
  // 1. Schema 校验
979
979
  if (!opts.skipValidate) {
980
980
  validateOrThrow(schema, normalized, target);
981
- if (target === ConfigTarget.Relation && normalized.chatmode?.private === 'paactive'
982
- && (!sel?.peerKey?.startsWith('aun#') || normalized.targetKind !== 'private')) {
983
- throw new ConfigError('SCHEMA_INVALID', 'paactive only supports AUN private relations');
984
- }
985
981
  if (target === ConfigTarget.Defaults || target === ConfigTarget.Agent || target === ConfigTarget.Relation) {
986
982
  const previous = atomicReadJson(file) ?? {};
987
983
  const inherited = target === ConfigTarget.Defaults ? {}
@@ -1558,9 +1554,6 @@ export function normalizeDefaultsBehaviorCompat(defaults) {
1558
1554
  if (!normalized.chatmode && (chatMode === 'interactive' || chatMode === 'proactive')) {
1559
1555
  normalized.chatmode = { private: chatMode, group: 'proactive', nothuman: chatMode };
1560
1556
  }
1561
- else if (!normalized.chatmode && chatMode === 'paactive') {
1562
- normalized.chatmode = { private: 'paactive', group: 'proactive', nothuman: 'proactive' };
1563
- }
1564
1557
  if (normalized.mentionMode === undefined && (config.mentionMode === 'disabled' || config.mentionMode === 'mention-only' || config.mentionMode === 'auto')) {
1565
1558
  normalized.mentionMode = config.mentionMode;
1566
1559
  }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * `ec invoke` 的 argv 解析与 daemon 侧执行。
3
+ *
4
+ * 鉴权与 `provider.op` 同一条链:本地控制令牌或任务委托令牌。
5
+ * 与 provider.op 的差别在于 invoke **不做配置变更**,也不受 fullaccess 限制——
6
+ * 调用一个已登记的端点不改变任何状态。
7
+ */
8
+ import { executeInvoke } from '../core/invoke/invoke-service.js';
9
+ function argumentError(message) {
10
+ throw Object.assign(new Error(message), { code: 'INVALID_ARGUMENT' });
11
+ }
12
+ const SAFE_ID = /^[A-Za-z0-9_-]+$/u;
13
+ const PROHIBITED = new Set(['__proto__', 'constructor', 'prototype']);
14
+ /** 解析 `ec invoke` 的 argv(含首个 'invoke')。 */
15
+ export function parseInvokeArgv(argv) {
16
+ if (!Array.isArray(argv) || argv.some(value => typeof value !== 'string') || argv[0] !== 'invoke') {
17
+ argumentError('invoke.op requires invoke argv');
18
+ }
19
+ const options = new Map();
20
+ const flags = new Set();
21
+ const valueFlags = new Set(['--provider', '--service', '--model', '--out', '--timeout', '--timeout-ms', '--retries', '--input', '--input-file', '--format']);
22
+ const boolFlags = new Set(['--dry-run']);
23
+ for (let index = 1; index < argv.length; index++) {
24
+ const token = argv[index];
25
+ if (!token.startsWith('-'))
26
+ argumentError(`unexpected argument: ${token}`);
27
+ const separator = token.indexOf('=');
28
+ const name = separator < 0 ? token : token.slice(0, separator);
29
+ if (boolFlags.has(name)) {
30
+ if (separator >= 0)
31
+ argumentError(`${name} does not take a value`);
32
+ flags.add(name);
33
+ continue;
34
+ }
35
+ if (!valueFlags.has(name))
36
+ argumentError(`unknown or duplicate option: ${name}`);
37
+ if (options.has(name))
38
+ argumentError(`unknown or duplicate option: ${name}`);
39
+ const value = separator < 0 ? argv[++index] : token.slice(separator + 1);
40
+ if (typeof value !== 'string' || !value || value.startsWith('--'))
41
+ argumentError(`${name} requires a value`);
42
+ options.set(name, value);
43
+ }
44
+ if (options.has('--format') && options.get('--format') !== 'json' && options.get('--format') !== 'text') {
45
+ argumentError('--format must be json or text');
46
+ }
47
+ const providerId = options.get('--provider');
48
+ const serviceType = options.get('--service');
49
+ if (!providerId)
50
+ argumentError('--provider is required');
51
+ if (!serviceType)
52
+ argumentError('--service is required');
53
+ if (!SAFE_ID.test(providerId) || PROHIBITED.has(providerId))
54
+ argumentError('invalid provider id');
55
+ if (!SAFE_ID.test(serviceType) || PROHIBITED.has(serviceType))
56
+ argumentError('invalid service type');
57
+ // 输入可以走 argv(--input / --input-file),也可以由 IPC 单独携带(cmd.input)。
58
+ // 这里只做结构校验,「恰好一种」由 executeInvokeOperation 结合 cmd.input 判定。
59
+ const hasInput = options.has('--input');
60
+ const hasInputFile = options.has('--input-file');
61
+ if (hasInput && hasInputFile)
62
+ argumentError('--input and --input-file are mutually exclusive');
63
+ const retriesRaw = options.get('--retries');
64
+ if (retriesRaw !== undefined && !/^\d+$/u.test(retriesRaw))
65
+ argumentError('--retries must be a non-negative integer');
66
+ // daemon 侧统一收毫秒:`--timeout-ms` 是 CLI 换算后的形态;`--timeout` 也按毫秒接受。
67
+ const timeoutRaw = options.get('--timeout-ms') ?? options.get('--timeout');
68
+ if (timeoutRaw !== undefined && !/^\d+$/u.test(timeoutRaw))
69
+ argumentError('timeout must be a positive integer (ms)');
70
+ return {
71
+ providerId,
72
+ serviceType,
73
+ model: options.get('--model'),
74
+ out: options.get('--out'),
75
+ timeoutMs: timeoutRaw === undefined ? undefined : Number(timeoutRaw),
76
+ retries: retriesRaw === undefined ? undefined : Number(retriesRaw),
77
+ dryRun: flags.has('--dry-run'),
78
+ input: hasInput ? options.get('--input') : undefined,
79
+ inputFile: hasInputFile ? options.get('--input-file') : undefined,
80
+ };
81
+ }
82
+ function parseInput(text) {
83
+ if (text === undefined)
84
+ return undefined;
85
+ try {
86
+ return JSON.parse(text.replace(/^/u, ''));
87
+ }
88
+ catch {
89
+ argumentError('invoke input must be valid JSON');
90
+ }
91
+ }
92
+ /** Standalone IPC callers have already presented the local control token. */
93
+ export async function executeInvokeOperation(command) {
94
+ try {
95
+ const parsed = parseInvokeArgv(command.argv);
96
+ // CLI 已在本地读好 --input / --input-file,通过 cmd.input 传文本;
97
+ // 直接在 argv 里带 --input 的调用方也支持。
98
+ const inputText = command.input !== undefined ? String(command.input) : parsed.input;
99
+ if (inputText === undefined)
100
+ argumentError('exactly one of --input or --input-file is required');
101
+ const input = parseInput(inputText);
102
+ const request = {
103
+ providerId: parsed.providerId,
104
+ serviceType: parsed.serviceType,
105
+ model: parsed.model,
106
+ input,
107
+ outPath: parsed.out,
108
+ timeoutMs: parsed.timeoutMs,
109
+ retries: parsed.retries,
110
+ dryRun: parsed.dryRun,
111
+ };
112
+ return await executeInvoke(request);
113
+ }
114
+ catch (error) {
115
+ const failure = error;
116
+ return { ok: false, code: failure.code ?? 'INVALID_ARGUMENT', error: failure.message ?? 'Invoke failed' };
117
+ }
118
+ }
@@ -5,7 +5,7 @@ import path from 'path';
5
5
  import { resolvePaths } from '../paths.js';
6
6
  import { acquireConfigMutationLock, ConfigError } from './config-manager.js';
7
7
  import { firstConfiguredOwner } from './owner-config.js';
8
- import { loadSchema } from './schema-registry.js';
8
+ import { currentVersion, loadSchema } from './schema-registry.js';
9
9
  import { planProviderIdentityMigration } from './provider-identity-migration.js';
10
10
  import { providerIdentity } from './provider-identity.js';
11
11
  import { snapshot } from './snapshot.js';
@@ -1601,21 +1601,44 @@ export async function ensureRelationConfigVersionMigrationOnStartup() {
1601
1601
  throw new ConfigError('RELATION_CONFIG_VERSION_MIGRATION_FAILED', `Automatic relation-config version migration failed: ${detail}`, { cause: error });
1602
1602
  }
1603
1603
  }
1604
- // ── Published schema consolidation: retired v20/v13 → v19/v12 ───────────────
1604
+ // ── Startup config compatibility: retired schemas and chat modes ────────────
1605
1605
  /**
1606
1606
  * The unpublished v20/v13 schemas only split the group-chatmode consolidation
1607
1607
  * from v19/v12. Once those files were removed, persisted configs created in
1608
1608
  * the short release window must be restamped before the contact-book startup
1609
- * gate decides they are an unknown future format.
1609
+ * gate decides they are an unknown future format. This pass also maps retired
1610
+ * `paactive` values in known schemas before startup validators inspect them.
1610
1611
  */
1611
1612
  const PUBLISHED_SCHEMA_CONSOLIDATIONS = [
1612
1613
  { logicalName: 'agent-config', from: 20, to: 19 },
1613
1614
  { logicalName: 'relation-config', from: 13, to: 12 },
1614
1615
  ];
1615
1616
  function restampPublishedSchemaConsolidation(value, file, consolidation) {
1616
- if (value.$schema_version !== consolidation.from)
1617
- return null;
1618
- const next = { ...value, $schema_version: consolidation.to };
1617
+ let next = value;
1618
+ let chatModeChanged = false;
1619
+ const schemaVersion = value.$schema_version;
1620
+ const currentSchemaVersion = currentVersion(consolidation.logicalName);
1621
+ const knownSchema = Number.isInteger(schemaVersion) && Number(schemaVersion) >= 1
1622
+ && (Number(schemaVersion) <= currentSchemaVersion || schemaVersion === consolidation.from);
1623
+ if (knownSchema && isRecord(value.chatmode)) {
1624
+ const chatmode = { ...value.chatmode };
1625
+ for (const scene of ['private', 'group', 'nothuman']) {
1626
+ if (chatmode[scene] !== 'paactive')
1627
+ continue;
1628
+ chatmode[scene] = 'proactive';
1629
+ chatModeChanged = true;
1630
+ }
1631
+ if (chatModeChanged)
1632
+ next = { ...value, chatmode };
1633
+ }
1634
+ if (schemaVersion !== consolidation.from)
1635
+ return chatModeChanged ? next : null;
1636
+ // A consolidation only applies while the source version is unpublished.
1637
+ // Once that version is current, its fields (for example agent-config.team)
1638
+ // must be retained instead of being validated against the older schema.
1639
+ if (currentSchemaVersion >= consolidation.from)
1640
+ return chatModeChanged ? next : null;
1641
+ next = { ...next, $schema_version: consolidation.to };
1619
1642
  const schema = loadSchema(consolidation.logicalName, consolidation.to);
1620
1643
  if (!schema.validate(next)) {
1621
1644
  const detail = (schema.validate.errors ?? [])
@@ -1626,12 +1649,13 @@ function restampPublishedSchemaConsolidation(value, file, consolidation) {
1626
1649
  }
1627
1650
  return next;
1628
1651
  }
1629
- function planPublishedSchemaConsolidationMigration(home) {
1652
+ function planStartupConfigCompatibilityMigration(home) {
1630
1653
  const changes = [];
1631
1654
  const summary = {
1632
1655
  agentsScanned: 0,
1633
1656
  relationsScanned: 0,
1634
- filesRestamped: 0,
1657
+ filesChanged: 0,
1658
+ filesWithChatModesNormalized: 0,
1635
1659
  };
1636
1660
  const agentsRoot = path.join(home, 'agents');
1637
1661
  if (!fs.existsSync(agentsRoot))
@@ -1656,7 +1680,10 @@ function planPublishedSchemaConsolidationMigration(home) {
1656
1680
  const next = restampPublishedSchemaConsolidation(parsed.value, agentFile, agentConsolidation);
1657
1681
  if (next) {
1658
1682
  changes.push({ file: agentFile, kind: 'agent-only-model', before: parsed.text, after: jsonText(next) });
1659
- summary.filesRestamped += 1;
1683
+ summary.filesChanged += 1;
1684
+ if (JSON.stringify(parsed.value.chatmode) !== JSON.stringify(next.chatmode)) {
1685
+ summary.filesWithChatModesNormalized += 1;
1686
+ }
1660
1687
  }
1661
1688
  }
1662
1689
  }
@@ -1675,19 +1702,22 @@ function planPublishedSchemaConsolidationMigration(home) {
1675
1702
  if (!next)
1676
1703
  continue;
1677
1704
  changes.push({ file: relationFile, kind: 'agent-only-model', before: parsed.text, after: jsonText(next) });
1678
- summary.filesRestamped += 1;
1705
+ summary.filesChanged += 1;
1706
+ if (JSON.stringify(parsed.value.chatmode) !== JSON.stringify(next.chatmode)) {
1707
+ summary.filesWithChatModesNormalized += 1;
1708
+ }
1679
1709
  }
1680
1710
  }
1681
1711
  return { home, changes, summary };
1682
1712
  }
1683
- export function runPublishedSchemaConsolidationMigration(options = {}) {
1713
+ export function runStartupConfigCompatibilityMigration(options = {}) {
1684
1714
  const id = 'published-schema-consolidation-v1';
1685
1715
  const home = path.resolve(options.home || resolvePaths().root);
1686
1716
  const release = acquireLock(home, id);
1687
1717
  try {
1688
1718
  assertDaemonStopped(home);
1689
1719
  recoverJournal(home, id);
1690
- const plan = planPublishedSchemaConsolidationMigration(home);
1720
+ const plan = planStartupConfigCompatibilityMigration(home);
1691
1721
  const backup = options.apply ? applyMigration(plan, id) : null;
1692
1722
  return {
1693
1723
  ok: true,
@@ -1702,10 +1732,10 @@ export function runPublishedSchemaConsolidationMigration(options = {}) {
1702
1732
  release();
1703
1733
  }
1704
1734
  }
1705
- export async function ensurePublishedSchemaConsolidationMigrationOnStartup() {
1735
+ export async function ensureStartupConfigCompatibilityMigrationOnStartup() {
1706
1736
  const home = resolvePaths().root;
1707
1737
  try {
1708
- const result = runPublishedSchemaConsolidationMigration({ home, apply: true });
1738
+ const result = runStartupConfigCompatibilityMigration({ home, apply: true });
1709
1739
  if (result.changedFiles === 0)
1710
1740
  return null;
1711
1741
  return {
@@ -1717,7 +1747,7 @@ export async function ensurePublishedSchemaConsolidationMigrationOnStartup() {
1717
1747
  }
1718
1748
  catch (error) {
1719
1749
  const detail = error instanceof Error ? error.message : String(error);
1720
- throw new ConfigError('PUBLISHED_SCHEMA_CONSOLIDATION_MIGRATION_FAILED', `Automatic published schema consolidation failed: ${detail}`, { cause: error });
1750
+ throw new ConfigError('STARTUP_CONFIG_COMPATIBILITY_MIGRATION_FAILED', `Automatic startup config compatibility migration failed: ${detail}`, { cause: error });
1721
1751
  }
1722
1752
  }
1723
1753
  // ── Agent 消息准入重写:v16 → v17 → v18 ──────────────────────────────────────