evolcore 0.0.41-test.0 → 0.0.41-test.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/dist/agents/baseagent-availability.js +1 -1
  3. package/dist/agents/baseagent.js +88 -49
  4. package/dist/agents/claude-runner.js +177 -92
  5. package/dist/agents/codex-runner.js +146 -71
  6. package/dist/agents/ecagent-runner.js +1 -1
  7. package/dist/agents/gemini-runner.js +1 -1
  8. package/dist/aun/aid/agentmd.js +98 -11
  9. package/dist/aun/aid/client.js +1 -1
  10. package/dist/aun/aid/control-aid.js +26 -2
  11. package/dist/aun/aid/identity.js +91 -0
  12. package/dist/aun/aid/index.js +1 -1
  13. package/dist/aun/aid/managed-operation.js +1 -1
  14. package/dist/aun/aid/ownership-operation.js +23 -22
  15. package/dist/aun/group/fs-download.js +39 -0
  16. package/dist/aun/group/identity.js +36 -21
  17. package/dist/aun/group/operations.js +5 -0
  18. package/dist/aun/menu/client.js +27 -0
  19. package/dist/aun/msg/managed-operation.js +68 -7
  20. package/dist/aun/msg/p2p.js +8 -8
  21. package/dist/aun/service-proxy.js +53 -12
  22. package/dist/channels/aun.js +633 -32
  23. package/dist/channels/daemon.js +15 -1
  24. package/dist/cli/agent-command.js +5 -2
  25. package/dist/cli/agent-create.js +991 -233
  26. package/dist/cli/agent.js +49 -10
  27. package/dist/cli/aid-bind-command.js +48 -19
  28. package/dist/cli/aun-commands.js +48 -36
  29. package/dist/cli/daemon-commands.js +679 -697
  30. package/dist/cli/fs-command.js +64 -2
  31. package/dist/cli/index.js +72 -5
  32. package/dist/cli/init-channel.js +1 -1
  33. package/dist/cli/init.js +75 -1
  34. package/dist/cli/managed-command-guard.js +17 -1
  35. package/dist/cli/model.js +40 -40
  36. package/dist/cli/provider-command.js +57 -0
  37. package/dist/cli/proxy-command.js +92 -0
  38. package/dist/cli/restart-monitor.js +4 -2
  39. package/dist/cli/role.js +85 -0
  40. package/dist/cli/stats.js +10 -3
  41. package/dist/cli/task-context.js +19 -0
  42. package/dist/config/access-policy.js +7 -2
  43. package/dist/config/boot-log.js +39 -1
  44. package/dist/config/config-field-policy.js +17 -39
  45. package/dist/config/config-manager.js +183 -44
  46. package/dist/config/config-operation-service.js +5 -19
  47. package/dist/config/contact-book-store.js +47 -21
  48. package/dist/config/contact-book.js +18 -12
  49. package/dist/config/contact-operation-service.js +3 -4
  50. package/dist/config/contact-request-service.js +11 -0
  51. package/dist/config/daemon-services.js +11 -0
  52. package/dist/config/gateway-config.js +88 -594
  53. package/dist/config/owner-config.js +2 -2
  54. package/dist/config/peer-role-resolver.js +15 -12
  55. package/dist/config/provider-ipc-service.js +132 -0
  56. package/dist/config/provider-menu-request.js +58 -0
  57. package/dist/config/providers-config.js +12 -7
  58. package/dist/config/providers-import.js +3 -21
  59. package/dist/config/providers-management.js +78 -5
  60. package/dist/config/resolved-config-op.js +11 -1
  61. package/dist/config/role-command-service.js +166 -0
  62. package/dist/config/role-request-service.js +193 -0
  63. package/dist/config/schema-migration.js +1000 -25
  64. package/dist/config-store.js +89 -4
  65. package/dist/contracts/ecweb-instance.js +41 -0
  66. package/dist/contracts/ecweb-service-protocol.js +4 -1
  67. package/dist/core/agent-application-service.js +60 -11
  68. package/dist/core/agent-create-status.js +203 -0
  69. package/dist/core/agent-creation-claim.js +177 -0
  70. package/dist/core/agent-ipc-registration.js +39 -18
  71. package/dist/core/agent-runtime.js +194 -24
  72. package/dist/core/auth/agent-delegation.js +6 -3
  73. package/dist/core/auth/auth-gateway.js +67 -2
  74. package/dist/core/auth/authorization-audit.js +58 -11
  75. package/dist/core/auth/delegation-authorization.js +5 -2
  76. package/dist/core/auth/operation-authorizer.js +43 -6
  77. package/dist/core/auth/operation-catalog.js +45 -7
  78. package/dist/core/channel-loader.js +2 -0
  79. package/dist/core/command/agent-control.js +260 -21
  80. package/dist/core/command/agent-storage-menu.js +5 -3
  81. package/dist/core/command/cli-intent-parser.js +8 -3
  82. package/dist/core/command/command-handler.js +112 -154
  83. package/dist/core/command/connect-menu.js +11 -3
  84. package/dist/core/command/data-root-resolver.js +5 -4
  85. package/dist/core/command/memory-slash.js +16 -8
  86. package/dist/core/command/menu-catalog.js +10 -6
  87. package/dist/core/command/menu-handler.js +106 -73
  88. package/dist/core/command/menu-protocol.js +15 -1
  89. package/dist/core/command/provider-menu.js +46 -0
  90. package/dist/core/command/role-menu.js +147 -30
  91. package/dist/core/command/slash-handler.js +125 -255
  92. package/dist/core/daemon-control.js +26 -27
  93. package/dist/core/event-catalog.js +10 -0
  94. package/dist/core/evolagent-registry.js +7 -5
  95. package/dist/core/evolagent.js +10 -8
  96. package/dist/core/file-integrity/store.js +11 -0
  97. package/dist/core/handoff/ipc-registration.js +3 -0
  98. package/dist/core/inference/text-inference.js +31 -40
  99. package/dist/core/initialization/service.js +491 -0
  100. package/dist/core/ipc-registration.js +40 -24
  101. package/dist/core/memory/consolidation-context.js +51 -5
  102. package/dist/core/memory/consolidation-ops-records.js +96 -1
  103. package/dist/core/memory/consolidation-trigger.js +208 -191
  104. package/dist/core/memory/consolidation.js +333 -35
  105. package/dist/core/memory/index-manager.js +27 -5
  106. package/dist/core/memory/memory-admin.js +45 -5
  107. package/dist/core/memory/memory-writer.js +163 -18
  108. package/dist/core/memory/relation-idle-monitor.js +119 -58
  109. package/dist/core/memory/relation-sweep.js +55 -45
  110. package/dist/core/message/aun-ipc-sender.js +81 -69
  111. package/dist/core/message/im-renderer.js +25 -4
  112. package/dist/core/message/message-admission.js +89 -4
  113. package/dist/core/message/message-bridge.js +66 -21
  114. package/dist/core/message/response-engine.js +108 -35
  115. package/dist/core/model/catalog-service.js +5 -3
  116. package/dist/core/model/config-scope.js +29 -71
  117. package/dist/core/model/field-scope.js +1 -1
  118. package/dist/core/model/model-catalog.js +30 -41
  119. package/dist/core/model/model-diagnostics.js +4 -3
  120. package/dist/core/model/model-fallback.js +10 -7
  121. package/dist/core/model/model-permission.js +3 -2
  122. package/dist/core/ownership/owner-resolver.js +772 -158
  123. package/dist/core/permission/approval-gateway.js +103 -403
  124. package/dist/core/permission/ec-command-parser.js +62 -6
  125. package/dist/core/permission/index.js +1 -0
  126. package/dist/core/permission/permission-result.js +78 -0
  127. package/dist/core/permission/sandbox-runtime.js +18 -1
  128. package/dist/core/permission/tool-policy.js +21 -46
  129. package/dist/core/relation/peer-identity.js +64 -1
  130. package/dist/core/role/runtime-policy.js +72 -13
  131. package/dist/core/session/session-capsule.js +1 -1
  132. package/dist/core/session/session-idle-monitor.js +1 -1
  133. package/dist/core/session/session-manager.js +20 -0
  134. package/dist/core/session/session-renew.js +3 -3
  135. package/dist/core/skill/index-generator.js +15 -5
  136. package/dist/core/system-session/memory.js +43 -8
  137. package/dist/core/thread/thread-service.js +19 -6
  138. package/dist/directory/owner-directory-admission.js +95 -0
  139. package/dist/directory/owner-directory-authorization.js +309 -0
  140. package/dist/directory/owner-directory-cache.js +635 -0
  141. package/dist/eck/kit-renderer.js +2 -2
  142. package/dist/ecweb/basic-settings-service.js +33 -40
  143. package/dist/ecweb/init-menu.js +32 -0
  144. package/dist/ecweb/message-context-service.js +110 -0
  145. package/dist/index.js +93 -19
  146. package/dist/ipc.js +247 -29
  147. package/dist/paths.js +7 -0
  148. package/dist/proxy/command.js +122 -0
  149. package/dist/proxy/ipc-service.js +68 -0
  150. package/dist/proxy/manager.js +484 -0
  151. package/dist/proxy/service-supervisor.js +603 -0
  152. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  153. package/dist/trigger/authorization.js +27 -17
  154. package/dist/trigger/feedback.js +2 -3
  155. package/dist/trigger/ipc-service.js +105 -78
  156. package/dist/trigger/local-files.js +2 -1
  157. package/dist/trigger/manager.js +5 -3
  158. package/dist/trigger/scheduler.js +88 -6
  159. package/dist/utils/atomic-write.js +28 -0
  160. package/dist/utils/cross-platform.js +14 -0
  161. package/dist/utils/ecweb-supervisor.js +258 -83
  162. package/dist/utils/error-utils.js +26 -2
  163. package/dist/utils/logger.js +92 -6
  164. package/dist/utils/package-version-info.js +4 -2
  165. package/dist/utils/welcome.js +1 -1
  166. package/kits/docs/INDEX.md +1 -0
  167. package/kits/docs/aun/SDK.md +4 -1
  168. package/kits/docs/channels/aun.md +9 -0
  169. package/kits/docs/evolcore/INDEX.md +1 -0
  170. package/kits/docs/evolcore/agent.md +8 -1
  171. package/kits/docs/evolcore/aid.md +67 -17
  172. package/kits/docs/evolcore/config.md +28 -7
  173. package/kits/docs/evolcore/contact.md +3 -0
  174. package/kits/docs/evolcore/fs.md +11 -0
  175. package/kits/docs/evolcore/group.md +1 -1
  176. package/kits/docs/evolcore/memory-architecture.md +2 -2
  177. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  178. package/kits/docs/evolcore/memory.md +1 -1
  179. package/kits/docs/evolcore/menu-protocol.md +4 -0
  180. package/kits/docs/evolcore/model.md +23 -20
  181. package/kits/docs/evolcore/msg.md +4 -7
  182. package/kits/docs/evolcore/provider.md +50 -0
  183. package/kits/docs/identity/AID_PROFILE_SPEC.md +52 -17
  184. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  185. package/kits/rules/01-overview.md +3 -0
  186. package/kits/rules/04-relation.md +1 -1
  187. package/kits/schemas/_meta.json +37 -4
  188. package/kits/schemas/agent-config.schema.13.json +8 -3
  189. package/kits/schemas/agent-config.schema.16.json +891 -0
  190. package/kits/schemas/daemon.schema.9.json +366 -0
  191. package/kits/schemas/defaults.schema.5.json +406 -127
  192. package/kits/schemas/relation-config.schema.11.json +277 -0
  193. package/kits/schemas/role-config.schema.1.json +7 -7
  194. package/kits/skills/.switches.json +4 -0
  195. package/kits/skills/ec-agent-create/SKILL.md +3 -0
  196. package/kits/skills/ec-identity/SKILL.md +2 -2
  197. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  198. package/kits/skills/ec-skill/scripts/skill.mjs +6 -0
  199. package/kits/skills/personal-assistant/SKILL.md +176 -0
  200. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  201. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  202. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  203. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  204. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  205. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  206. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  207. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  208. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  209. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  210. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  211. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  212. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  213. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  214. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  215. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  216. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  217. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  218. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  219. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  220. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  221. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  222. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  223. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  224. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  225. package/kits/skills/thread-ops/SKILL.md +5 -0
  226. package/kits/templates/memory-consolidation/forget.md +19 -6
  227. package/kits/templates/memory-consolidation/notes.md +1 -1
  228. package/kits/templates/memory-consolidation/profile.md +2 -2
  229. package/kits/templates/memory-consolidation/promote.md +20 -3
  230. package/kits/templates/roles/member.json +8 -1
  231. package/kits/templates/system-fragments/baseagent.md +2 -2
  232. package/kits/templates/system-fragments/memory.md +4 -4
  233. package/kits/templates/system-fragments/venue.md +1 -1
  234. package/package.json +7 -3
  235. package/dist/core/message/create-status.js +0 -96
@@ -36,12 +36,14 @@ import { parseTimeArg, TIME_ARG_FORMATS, splitConfigBatchGetArgv } from '../../c
36
36
  import { auditCommandAuthorization, auditFullAccessEvent, hashArgv } from '../auth/authorization-audit.js';
37
37
  import { ResponseModeRegistry } from '../../response-system/registry.js';
38
38
  import { registerBuiltinModes } from '../../response-system/modes/index.js';
39
+ import { executeResolvedRoleCommand, resolveRoleCommand } from '../../config/role-command-service.js';
40
+ import { applyApprovedRoleAssignment } from './role-menu.js';
39
41
  import { executeResolvedContactCommand, resolveContactCommand } from '../../config/contact-operation-service.js';
40
42
  import { hasTrustedFullAccessDelegation, trustedExecutionIdentityInput } from '../auth/agent-delegation.js';
41
43
  import { executeManagedAidOperation, ManagedAidOperationError, managedAidShowViewForRole, resolveManagedAidOperation, } from '../../aun/aid/managed-operation.js';
42
44
  import { MAX_AVATAR_SOURCE_BYTES } from '../../utils/avatar-upload.js';
43
45
  import { executeManagedGroupOperation, isManagedGroupRelationRead, isManagedGroupRelationWrite, ManagedGroupOperationError, resolveManagedGroupOperation, executeManagedMsgOperation, ManagedMsgOperationError, resolveManagedMsgOperation, executeManagedFsOperation, ManagedFsOperationError, resolveManagedFsOperation, } from '../../aun/msg/managed-operation.js';
44
- import { authorizeFreshOperation, buildAuthSubject } from '../auth/auth-gateway.js';
46
+ import { authorizeFreshOperation, buildAuthSubject, executeAuditedOperation } from '../auth/auth-gateway.js';
45
47
  import { isHClassPath, isLClassPath, isSameOrDescendant } from '../permission/protected-paths.js';
46
48
  import { validateModelSelectionForRole } from '../model/model-permission.js';
47
49
  import { getModelInfo } from '../model/model-catalog.js';
@@ -56,45 +58,6 @@ import { resolveCurrentSessionLoopTarget, sessionLoopError } from '../session/se
56
58
  export { isProcessLevelOwner } from './menu-handler.js';
57
59
  const CLI_EXEC_TIMEOUT_MS = 15_000;
58
60
  const CLI_EXEC_MAX_OUTPUT = 128 * 1024;
59
- /**
60
- * 写入用户级 ~/.claude/settings.json(与 Claude CLI 行为一致)
61
- * ⚠️ 已禁用:按需求不再修改用户的 ~/.claude/settings.json 文件。
62
- * 原会把 model/effortLevel 写入 settings.json(仅在找不到 owning agent 的 fallback 路径触发)。
63
- * 现直接返回成功且不落盘;如需恢复,取消下方注释即可。
64
- */
65
- function writeUserSettings(updates) {
66
- void updates;
67
- return { success: true };
68
- /* eslint-disable no-unreachable */
69
- // try {
70
- // const settingsPath = path.join(os.homedir(), '.claude', 'settings.json');
71
- // let settings: any = {};
72
- //
73
- // if (fs.existsSync(settingsPath)) {
74
- // settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
75
- // }
76
- //
77
- // if (updates.model !== undefined) settings.model = updates.model;
78
- // if (updates.effortLevel !== undefined) {
79
- // if (updates.effortLevel === null) {
80
- // delete settings.effortLevel;
81
- // } else {
82
- // settings.effortLevel = updates.effortLevel;
83
- // }
84
- // }
85
- //
86
- // const claudeDir = path.join(os.homedir(), '.claude');
87
- // if (!fs.existsSync(claudeDir)) {
88
- // fs.mkdirSync(claudeDir, { recursive: true });
89
- // }
90
- //
91
- // fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), 'utf-8');
92
- // return { success: true };
93
- // } catch (error: any) {
94
- // return { success: false, error: error.message };
95
- // }
96
- /* eslint-enable no-unreachable */
97
- }
98
61
  function isAdminRole(role) {
99
62
  return isManagementRole(role);
100
63
  }
@@ -178,7 +141,8 @@ export class CommandHandler {
178
141
  const target = fs.realpathSync(path.resolve(session.projectPath, file));
179
142
  const roots = [session.projectPath, this.getManagedSessionTempDir(session)].filter((v) => !!v)
180
143
  .map(root => fs.realpathSync(root));
181
- if (!roots.some(root => isSameOrDescendant(target, root)) || isHClassPath(target) || isLClassPath(target))
144
+ if (!roots.some(root => isSameOrDescendant(target, root))
145
+ || (!hasTrustedFullAccessDelegation(grant) && (isHClassPath(target) || isLClassPath(target))))
182
146
  throw new Error('Menu request file must be an unprotected file in the project or session TMPDIR');
183
147
  const stat = fs.statSync(target);
184
148
  if (!stat.isFile() || stat.nlink > 1 || stat.size > 128 * 1024)
@@ -820,60 +784,6 @@ export class CommandHandler {
820
784
  return owning.projectPath;
821
785
  return process.cwd();
822
786
  }
823
- /**
824
- * 持久化 baseagent.model:写到 agent config.json;找不到 owning agent 时
825
- * 退到用户级 ~/.claude/settings.json(Claude 专用)。
826
- */
827
- persistBaseagentModel(channel, baseagentName, newModel) {
828
- const owning = this.getOwningAgent(channel);
829
- if (owning) {
830
- try {
831
- owning.setBaseagentModel(newModel, baseagentName);
832
- }
833
- catch (e) {
834
- return `⚠️ 写入 agent config 失败: ${e?.message || e}`;
835
- }
836
- return undefined;
837
- }
838
- // 无 owning agent(罕见,新结构下应当不会发生)→ 仅 Claude 走用户级 fallback
839
- if (baseagentName !== 'claude') {
840
- return `⚠️ 找不到通道 "${channel}" 所属的 self-agent`;
841
- }
842
- const updates = {};
843
- if (newModel)
844
- updates.model = newModel;
845
- const writeResult = writeUserSettings(updates);
846
- // writeUserSettings 已禁用写入,总是返回 success: true
847
- if (!writeResult.success) {
848
- return `⚠️ 写入用户配置失败: ${writeResult.error}`;
849
- }
850
- return undefined;
851
- }
852
- /**
853
- * 持久化 baseagent.effort:写到 agent config.json;找不到时退到用户级 settings。
854
- */
855
- persistBaseagentEffort(channel, baseagentName, newEffort) {
856
- const owning = this.getOwningAgent(channel);
857
- if (owning) {
858
- try {
859
- owning.setBaseagentEffort(newEffort, baseagentName);
860
- }
861
- catch (e) {
862
- return `⚠️ 写入 agent config 失败: ${e?.message || e}`;
863
- }
864
- return undefined;
865
- }
866
- if (baseagentName !== 'claude') {
867
- return `⚠️ 找不到通道 "${channel}" 所属的 self-agent`;
868
- }
869
- const updates = { effortLevel: newEffort ?? null };
870
- const writeResult = writeUserSettings(updates);
871
- // writeUserSettings 已禁用写入,总是返回 success: true
872
- if (!writeResult.success) {
873
- return `⚠️ 写入用户配置失败: ${writeResult.error}`;
874
- }
875
- return undefined;
876
- }
877
787
  /** 项目列表快捷访问(无 channel 上下文时的 fallback,尽量不用) */
878
788
  get projects() {
879
789
  return {};
@@ -1130,7 +1040,7 @@ export class CommandHandler {
1130
1040
  return false;
1131
1041
  return !!userId && topic.metadata?.peerId === userId;
1132
1042
  }
1133
- buildTopicMenuItem(s) {
1043
+ buildTopicMenuItem(s, metadataOnly = false) {
1134
1044
  const displayName = displaySessionTitle(s.name, sessionTopicThreadId(s) || s.id.slice(0, 8));
1135
1045
  const item = {
1136
1046
  value: sessionTopicThreadId(s) ?? '',
@@ -1143,12 +1053,14 @@ export class CommandHandler {
1143
1053
  item.forkSource = forkSource;
1144
1054
  if (s.agentSessionId) {
1145
1055
  item.agentSessionId = s.agentSessionId;
1146
- const fileInfo = this.sessionManager.getSessionFileInfo(s.projectPath, s.agentSessionId, s.baseagent, s.selfAID);
1147
- if (fileInfo.turns)
1148
- item.turns = fileInfo.turns;
1149
- const firstMsg = this.sessionManager.readSessionFirstMessage(s.projectPath, s.agentSessionId, s.baseagent, s.selfAID);
1150
- if (firstMsg)
1151
- item.preview = firstMsg.length > 80 ? firstMsg.slice(0, 80) + '...' : firstMsg;
1056
+ if (!metadataOnly) {
1057
+ const fileInfo = this.sessionManager.getSessionFileInfo(s.projectPath, s.agentSessionId, s.baseagent, s.selfAID);
1058
+ if (fileInfo.turns)
1059
+ item.turns = fileInfo.turns;
1060
+ const firstMsg = this.sessionManager.readSessionFirstMessage(s.projectPath, s.agentSessionId, s.baseagent, s.selfAID);
1061
+ if (firstMsg)
1062
+ item.preview = firstMsg.length > 80 ? firstMsg.slice(0, 80) + '...' : firstMsg;
1063
+ }
1152
1064
  }
1153
1065
  if (s.updatedAt)
1154
1066
  item.lastActive = s.updatedAt;
@@ -1961,16 +1873,16 @@ export class CommandHandler {
1961
1873
  * Agent managed CLI config entrypoint. Identity and relation are resolved
1962
1874
  * from the daemon-owned session rather than caller-provided flags.
1963
1875
  */
1964
- async handleConfigOperation(argv, sessionId, delegationToken, delegationCommandHash) {
1876
+ async handleConfigOperation(argv, sessionId, delegationToken, delegationCommandHash, requestId) {
1965
1877
  if (!this.agentDelegationRegistry) {
1966
1878
  return { ok: false, code: 'DELEGATION_REQUIRED', error: 'Task delegation is not configured' };
1967
1879
  }
1968
1880
  const delegation = this.agentDelegationRegistry.validate(delegationToken, sessionId, delegationCommandHash);
1969
1881
  if (!delegation.ok)
1970
1882
  return { ok: false, code: delegation.code, error: delegation.reason };
1971
- return this.executeConfigOperation(argv, sessionId, delegation.grant);
1883
+ return this.executeConfigOperation(argv, sessionId, delegation.grant, requestId);
1972
1884
  }
1973
- async executeConfigOperation(argv, sessionId, grant) {
1885
+ async executeConfigOperation(argv, sessionId, grant, requestId) {
1974
1886
  const session = await this.sessionManager.getSessionById(sessionId);
1975
1887
  if (!session)
1976
1888
  return { ok: false, code: 'INVALID_SESSION', error: 'Invalid session' };
@@ -1994,6 +1906,8 @@ export class CommandHandler {
1994
1906
  }
1995
1907
  const subject = buildAuthSubject({
1996
1908
  selfAid: grant.selfAid,
1909
+ sessionId,
1910
+ requestId,
1997
1911
  actorId: grant.actorId,
1998
1912
  channel: grant.channel,
1999
1913
  channelType: grant.channelType,
@@ -2003,13 +1917,13 @@ export class CommandHandler {
2003
1917
  processOwners: ownerResolver.daemonOwners(),
2004
1918
  ...trustedExecutionIdentityInput(grant),
2005
1919
  });
2006
- const executeOne = async (fieldArgv) => {
1920
+ const executeOne = async (fieldArgv, itemIndex) => {
2007
1921
  const resolved = resolveConfigCommand(fieldArgv, {
2008
1922
  defaultRelation: { self: grant.selfAid, peerKey: grant.peerKey },
2009
1923
  });
2010
1924
  if (!resolved.ok)
2011
1925
  return { ok: false, code: resolved.code, error: resolved.reason };
2012
- const decision = await authorizeFreshOperation({
1926
+ return executeAuditedOperation({
2013
1927
  source: 'agent-tool',
2014
1928
  subject,
2015
1929
  intent: {
@@ -2030,28 +1944,28 @@ export class CommandHandler {
2030
1944
  taskId: grant.taskId,
2031
1945
  messageId: grant.messageId,
2032
1946
  },
2033
- });
2034
- if (!decision.allow)
2035
- return { ok: false, code: decision.code, error: decision.reason };
2036
- const roleContext = {
2037
- self: grant.selfAid,
2038
- actorRole: subject.role,
2039
- actorRoleSource: subject.roleSource,
2040
- actorAllowAccess: subject.allowAccess,
2041
- actorAid: grant.actorId,
2042
- isDaemonOwner: subject.isDaemonOwner,
2043
- fromControlChannel: subject.fromControlChannel,
2044
- chatType: grant.chatType,
2045
- };
2046
- return await executeResolvedConfigCommandAsync(resolved.command, {
2047
- role: subject.role,
2048
- roleContext,
2049
- });
1947
+ }, async (onExecutionStarted) => {
1948
+ const roleContext = {
1949
+ self: grant.selfAid,
1950
+ actorRole: subject.role,
1951
+ actorRoleSource: subject.roleSource,
1952
+ actorAllowAccess: subject.allowAccess,
1953
+ actorAid: grant.actorId,
1954
+ isDaemonOwner: subject.isDaemonOwner,
1955
+ fromControlChannel: subject.fromControlChannel,
1956
+ chatType: grant.chatType,
1957
+ };
1958
+ onExecutionStarted();
1959
+ return executeResolvedConfigCommandAsync(resolved.command, {
1960
+ role: subject.role,
1961
+ roleContext,
1962
+ });
1963
+ }, itemIndex);
2050
1964
  };
2051
1965
  const batch = splitConfigBatchGetArgv(argv);
2052
1966
  if (batch && batch.fields.length > 1) {
2053
- const results = await Promise.all(batch.fields.map(async (field) => {
2054
- const result = await executeOne(['config', 'get', field, ...batch.rest]);
1967
+ const results = await Promise.all(batch.fields.map(async (field, itemIndex) => {
1968
+ const result = await executeOne(['config', 'get', field, ...batch.rest], itemIndex);
2055
1969
  if (!result.ok)
2056
1970
  return { ok: false, field, code: result.code, error: result.error };
2057
1971
  if (result.subcommand !== 'get') {
@@ -2192,9 +2106,6 @@ export class CommandHandler {
2192
2106
  if (!delegation?.ok)
2193
2107
  return { ok: false, code: 'INVALID_DELEGATION', error: 'Valid task delegation is required' };
2194
2108
  const grant = delegation.grant;
2195
- if (grant.executionIdentity) {
2196
- return { ok: false, code: 'NOT_ALLOWED', error: 'Fullaccess execution does not grant protocol Owner binding authority' };
2197
- }
2198
2109
  const session = await this.sessionManager.getSessionById(sessionId);
2199
2110
  if (!session || session.selfAID !== grant.selfAid)
2200
2111
  return { ok: false, code: 'INVALID_SESSION', error: 'Delegation does not match the session identity' };
@@ -2202,11 +2113,13 @@ export class CommandHandler {
2202
2113
  const command = parseOwnershipCommand(argv);
2203
2114
  const targetAid = command.subjectAid ?? grant.selfAid;
2204
2115
  ownerResolver.assertLocalSubject(targetAid);
2205
- const isMutation = command.action !== 'status';
2206
- if (isMutation && !['request', 'bypass'].includes(grant.permissionMode ?? '')) {
2116
+ if (command.action === 'status') {
2117
+ return { ok: true, state: await executeOwnershipCommand(command, grant.selfAid) };
2118
+ }
2119
+ if (!['request', 'bypass'].includes(grant.permissionMode ?? '')) {
2207
2120
  return { ok: false, code: 'NOT_ALLOWED', error: 'Binding changes and decisions require a request or bypass task' };
2208
2121
  }
2209
- await refreshOwnershipForAuthorization(targetAid);
2122
+ await refreshOwnershipForAuthorization(targetAid, { includeDaemon: true });
2210
2123
  let conversationId;
2211
2124
  try {
2212
2125
  conversationId = parsePeerKey(grant.peerKey).channelId;
@@ -2217,21 +2130,24 @@ export class CommandHandler {
2217
2130
  const subject = buildAuthSubject({
2218
2131
  selfAid: targetAid, actorId: grant.actorId, channel: grant.channel, channelType: grant.channelType,
2219
2132
  channelId: conversationId, chatType: grant.chatType, conversationId,
2133
+ sessionId,
2220
2134
  processOwners: ownerResolver.daemonOwners(),
2221
2135
  });
2222
2136
  if (targetAid !== grant.selfAid && !subject.isDaemonOwner) {
2223
2137
  return { ok: false, code: 'SCOPE_MISMATCH', error: 'A different local subject requires the current daemon Owner' };
2224
2138
  }
2225
- if (!subject.isDaemonOwner && (isMutation ? subject.role !== 'owner' : !isManagementRole(subject.role))) {
2139
+ if (!subject.isDaemonOwner && subject.role !== 'owner') {
2226
2140
  return { ok: false, code: 'OWNER_REQUIRED', error: 'Ownership binding requires the subject Owner or daemon Owner; first daemon binding uses the local CLI' };
2227
2141
  }
2228
2142
  const decision = await authorizeFreshOperation({
2229
2143
  source: 'agent-tool', subject,
2230
2144
  intent: {
2231
- operation: isMutation ? 'ec.aid.bind' : 'ec.aid.bind.status', scope: 'agent', source: 'agent-tool',
2145
+ operation: command.action === 'transfer' ? 'ec.aid.transfer' : 'ec.aid.bind',
2146
+ scope: 'agent', source: 'agent-tool',
2232
2147
  args: {
2233
2148
  self: targetAid,
2234
2149
  ...(command.action === 'bind' ? { ownerAid: command.ownerAid } : {}),
2150
+ ...(command.action === 'transfer' ? { subAid: command.subAid, newOwnerAid: command.newOwnerAid } : {}),
2235
2151
  ...(command.action === 'accept' || command.action === 'reject'
2236
2152
  ? { decision: command.action, operationId: command.operationId } : {}),
2237
2153
  },
@@ -2246,7 +2162,40 @@ export class CommandHandler {
2246
2162
  return ownershipFailure(error);
2247
2163
  }
2248
2164
  }
2249
- async handleAidOperation(argv, sessionId, delegationToken, delegationCommandHash) {
2165
+ /**
2166
+ * Agent-managed role-request CLI entrypoint. Submitting a request never
2167
+ * changes permissions; only the Agent owner can approve it, and approval is
2168
+ * what actually applies the relation role.
2169
+ */
2170
+ async handleRoleOperation(argv, sessionId, delegationToken, delegationCommandHash) {
2171
+ if (!this.agentDelegationRegistry) {
2172
+ return { ok: false, code: 'DELEGATION_REQUIRED', error: 'Task delegation is not configured' };
2173
+ }
2174
+ const delegation = this.agentDelegationRegistry.validate(delegationToken, sessionId, delegationCommandHash);
2175
+ if (!delegation.ok)
2176
+ return { ok: false, code: delegation.code, error: delegation.reason };
2177
+ const session = await this.sessionManager.getSessionById(sessionId);
2178
+ if (!session)
2179
+ return { ok: false, code: 'INVALID_SESSION', error: 'Invalid session' };
2180
+ const grant = delegation.grant;
2181
+ const resolvedArgv = argv.includes('--self') ? argv : [...argv, '--self', grant.selfAid];
2182
+ const resolved = resolveRoleCommand(resolvedArgv);
2183
+ if (!resolved.ok)
2184
+ return { ok: false, code: resolved.code, error: resolved.reason };
2185
+ if (resolved.command.selfAid !== grant.selfAid) {
2186
+ return { ok: false, code: 'SCOPE_MISMATCH', error: 'Only the current Agent role requests can be targeted' };
2187
+ }
2188
+ try {
2189
+ const result = await executeResolvedRoleCommand(resolved.command, grant.actorId, applyApprovedRoleAssignment);
2190
+ if (!result.ok)
2191
+ return { ok: false, code: result.code, error: result.error, data: result.data };
2192
+ return { ok: true, result };
2193
+ }
2194
+ catch (error) {
2195
+ return { ok: false, code: 'ROLE_OPERATION_FAILED', error: error?.message ?? String(error) };
2196
+ }
2197
+ }
2198
+ async handleAidOperation(argv, sessionId, delegationToken, delegationCommandHash, requestId) {
2250
2199
  if (!this.agentDelegationRegistry) {
2251
2200
  return { ok: false, code: 'DELEGATION_REQUIRED', error: 'Task delegation is not configured' };
2252
2201
  }
@@ -2282,6 +2231,8 @@ export class CommandHandler {
2282
2231
  }
2283
2232
  const subject = buildAuthSubject({
2284
2233
  selfAid: delegation.grant.selfAid,
2234
+ sessionId,
2235
+ requestId,
2285
2236
  actorId: delegation.grant.actorId,
2286
2237
  channel: delegation.grant.channel,
2287
2238
  channelType: delegation.grant.channelType,
@@ -2292,7 +2243,7 @@ export class CommandHandler {
2292
2243
  ...trustedExecutionIdentityInput(delegation.grant),
2293
2244
  });
2294
2245
  const managementRole = isManagementRole(subject.role);
2295
- const decision = await authorizeFreshOperation({
2246
+ return executeAuditedOperation({
2296
2247
  source: 'agent-tool',
2297
2248
  subject,
2298
2249
  intent: {
@@ -2306,12 +2257,12 @@ export class CommandHandler {
2306
2257
  taskId: delegation.grant.taskId,
2307
2258
  messageId: delegation.grant.messageId,
2308
2259
  },
2309
- });
2310
- if (!decision.allow)
2311
- return { ok: false, code: decision.code, error: decision.reason };
2260
+ }, onExecutionStarted => this.executeAuthorizedAidOperation(parsed.command, session, subject, delegation.grant, onExecutionStarted));
2261
+ }
2262
+ async executeAuthorizedAidOperation(command, session, subject, grant, onExecutionStarted) {
2312
2263
  let avatarBuffer;
2313
- if (parsed.command.kind === 'avatar' && parsed.command.filePath) {
2314
- const filePath = String(parsed.command.filePath || '').trim();
2264
+ if (command.kind === 'avatar' && command.filePath) {
2265
+ const filePath = String(command.filePath || '').trim();
2315
2266
  if (typeof session.projectPath !== 'string' || !session.projectPath.trim()) {
2316
2267
  return { ok: false, code: 'INVALID_AVATAR_PATH', error: 'Avatar file requires a current session project path' };
2317
2268
  }
@@ -2322,7 +2273,7 @@ export class CommandHandler {
2322
2273
  if (!filePath || !allowedRoots.some(root => isSameOrDescendant(resolvedPath, root))) {
2323
2274
  return { ok: false, code: 'INVALID_AVATAR_PATH', error: 'Avatar file must be inside the current session project or managed TMPDIR' };
2324
2275
  }
2325
- if (isHClassPath(resolvedPath) || isLClassPath(resolvedPath)) {
2276
+ if (!hasTrustedFullAccessDelegation(grant) && (isHClassPath(resolvedPath) || isLClassPath(resolvedPath))) {
2326
2277
  return { ok: false, code: 'PROTECTED_AVATAR_PATH', error: 'Avatar file cannot be read from a protected EvolCore path' };
2327
2278
  }
2328
2279
  let fd;
@@ -2338,7 +2289,7 @@ export class CommandHandler {
2338
2289
  if (!realAllowedRoots.some(root => isSameOrDescendant(realPath, root))) {
2339
2290
  return { ok: false, code: 'INVALID_AVATAR_PATH', error: 'Avatar file resolves outside the current session project or managed TMPDIR' };
2340
2291
  }
2341
- if (isHClassPath(realPath) || isLClassPath(realPath)) {
2292
+ if (!hasTrustedFullAccessDelegation(grant) && (isHClassPath(realPath) || isLClassPath(realPath))) {
2342
2293
  return { ok: false, code: 'PROTECTED_AVATAR_PATH', error: 'Avatar file cannot be read from a protected EvolCore path' };
2343
2294
  }
2344
2295
  const stat = fs.lstatSync(resolvedPath);
@@ -2370,7 +2321,8 @@ export class CommandHandler {
2370
2321
  }
2371
2322
  }
2372
2323
  try {
2373
- const result = await executeManagedAidOperation(parsed.command, {
2324
+ onExecutionStarted();
2325
+ const result = await executeManagedAidOperation(command, {
2374
2326
  showView: managedAidShowViewForRole(subject.role),
2375
2327
  ...(avatarBuffer ? { avatarBuffer } : {}),
2376
2328
  });
@@ -2503,7 +2455,7 @@ export class CommandHandler {
2503
2455
  if (!filePath || !allowedPaths.some(root => isSameOrDescendant(resolvedPath, root))) {
2504
2456
  return { ok: false, code: 'INVALID_RULES_PATH', error: 'Rules file must be inside the current session project or managed TMPDIR' };
2505
2457
  }
2506
- if (isHClassPath(resolvedPath) || isLClassPath(resolvedPath)) {
2458
+ if (!hasTrustedFullAccessDelegation(grant) && (isHClassPath(resolvedPath) || isLClassPath(resolvedPath))) {
2507
2459
  return { ok: false, code: 'PROTECTED_RULES_PATH', error: 'Rules file cannot be read from a protected EvolCore path' };
2508
2460
  }
2509
2461
  let rulesFd;
@@ -2521,7 +2473,7 @@ export class CommandHandler {
2521
2473
  if (!realAllowedPaths.some(root => isSameOrDescendant(realPath, root))) {
2522
2474
  return { ok: false, code: 'INVALID_RULES_PATH', error: 'Rules file resolves outside the current session project or managed TMPDIR' };
2523
2475
  }
2524
- if (isHClassPath(realPath) || isLClassPath(realPath)) {
2476
+ if (!hasTrustedFullAccessDelegation(grant) && (isHClassPath(realPath) || isLClassPath(realPath))) {
2525
2477
  return { ok: false, code: 'PROTECTED_RULES_PATH', error: 'Rules file cannot be read from a protected EvolCore path' };
2526
2478
  }
2527
2479
  rulesFd = fs.openSync(realPath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
@@ -2879,7 +2831,7 @@ export class CommandHandler {
2879
2831
  if (!allowedRoots.some(root => isSameOrDescendant(resolvedPath, root))) {
2880
2832
  return { ok: false, code: 'INVALID_LOCAL_PATH', error: 'Upload source must be inside the current session project or managed TMPDIR' };
2881
2833
  }
2882
- if (isHClassPath(resolvedPath) || isLClassPath(resolvedPath)) {
2834
+ if (!hasTrustedFullAccessDelegation(grant) && (isHClassPath(resolvedPath) || isLClassPath(resolvedPath))) {
2883
2835
  return { ok: false, code: 'PROTECTED_LOCAL_PATH', error: 'Upload source cannot be a protected EvolCore path' };
2884
2836
  }
2885
2837
  try {
@@ -2898,7 +2850,7 @@ export class CommandHandler {
2898
2850
  }
2899
2851
  const realAllowedRoots = [realProjectPath, realManagedTempPath].filter((value) => !!value);
2900
2852
  if (!realAllowedRoots.some(root => isSameOrDescendant(realPath, root))
2901
- || isHClassPath(realPath) || isLClassPath(realPath)) {
2853
+ || (!hasTrustedFullAccessDelegation(grant) && (isHClassPath(realPath) || isLClassPath(realPath)))) {
2902
2854
  return { ok: false, code: 'PROTECTED_LOCAL_PATH', error: 'Upload source resolves outside the allowed project or managed TMPDIR path' };
2903
2855
  }
2904
2856
  if (realManagedTempPath && isSameOrDescendant(realPath, realManagedTempPath) && stat.nlink > 1) {
@@ -3267,6 +3219,13 @@ export class CommandHandler {
3267
3219
  : 'read';
3268
3220
  return intent(`ec.ctl.queue.${action}`);
3269
3221
  }
3222
+ // 模型参数只在 Agent 级:写操作按 agent scope 鉴权(仅当前 Agent 的 owner/admin)。
3223
+ const agentIntent = (operation, extra = {}) => ({
3224
+ operation,
3225
+ scope: 'agent',
3226
+ source: 'agent-tool',
3227
+ args: { self: selfAid, ...extra },
3228
+ });
3270
3229
  if (name === 'model') {
3271
3230
  if (args.length === 0 || args[0] === 'list')
3272
3231
  return intent('model.list');
@@ -3275,16 +3234,15 @@ export class CommandHandler {
3275
3234
  if (args[0] === 'info')
3276
3235
  return intent('model.info', { model: args[1] });
3277
3236
  if (args[0] === 'reset')
3278
- return intent('model.reset');
3279
- if (args[0] === 'check') {
3280
- return { operation: 'model.check', scope: 'agent', source: 'agent-tool', args: { self: selfAid } };
3281
- }
3282
- return intent('model.use', { model: args[0] });
3237
+ return agentIntent('model.reset');
3238
+ if (args[0] === 'check')
3239
+ return agentIntent('model.check');
3240
+ return agentIntent('model.use', { model: args[0] });
3283
3241
  }
3284
3242
  if (name === 'effort') {
3285
3243
  return args.length === 0
3286
3244
  ? intent('model.effort.current')
3287
- : intent('model.effort', { effort: args[0] });
3245
+ : agentIntent('model.effort', { effort: args[0] });
3288
3246
  }
3289
3247
  if (name === 'restart') {
3290
3248
  return { operation: 'system.restart', scope: 'process', source: 'agent-tool', args: { self: selfAid } };
@@ -101,7 +101,7 @@ async function handleOptions(self, args, context) {
101
101
  {
102
102
  option: 'access',
103
103
  label: '访问设置',
104
- description: '设置外部联系开关、指定 AID 名单、消息准入模式和准入控制消息限额',
104
+ description: '设置 Owner 名录与外部联系开关、指定 AID 名单、消息准入模式和准入控制消息限额',
105
105
  },
106
106
  ],
107
107
  });
@@ -266,6 +266,8 @@ async function handleAction(req, self, context) {
266
266
  }
267
267
  function isAccessUpdateResource(resource) {
268
268
  return resource === 'policyMode'
269
+ || resource === 'allowOwnerDirectoryContacts'
270
+ || resource === 'allowOwnerAgentDirectory'
269
271
  || resource === 'allowExternalContacts'
270
272
  || resource === 'allowedAids'
271
273
  || resource === 'requestLimit';
@@ -284,9 +286,9 @@ function updateAccessResource(req, context, resource) {
284
286
  return fail('INVALID_ARGUMENT', 'policyMode must be open, contacts, or owners');
285
287
  }
286
288
  }
287
- else if (resource === 'allowExternalContacts') {
289
+ else if (resource === 'allowOwnerDirectoryContacts' || resource === 'allowOwnerAgentDirectory' || resource === 'allowExternalContacts') {
288
290
  if (typeof decoded !== 'boolean') {
289
- return fail('INVALID_ARGUMENT', 'allowExternalContacts must be a JSON boolean');
291
+ return fail('INVALID_ARGUMENT', `${resource} must be a JSON boolean`);
290
292
  }
291
293
  }
292
294
  else if (resource === 'allowedAids') {
@@ -549,6 +551,12 @@ function accessPolicyWithUpdate(current, resource, decoded) {
549
551
  if (resource === 'policyMode') {
550
552
  return { ...current, policyMode: decoded };
551
553
  }
554
+ if (resource === 'allowOwnerDirectoryContacts') {
555
+ return { ...current, allowOwnerDirectoryContacts: decoded };
556
+ }
557
+ if (resource === 'allowOwnerAgentDirectory') {
558
+ return { ...current, allowOwnerAgentDirectory: decoded };
559
+ }
552
560
  if (resource === 'allowExternalContacts') {
553
561
  return { ...current, allowExternalContacts: decoded };
554
562
  }
@@ -2,10 +2,9 @@ import crypto from 'crypto';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { isValidAid } from '../../aun/aid/validation.js';
5
- import { isExplicitGroupId } from '../../aun/group/index.js';
6
5
  import { isStaticAgentOwner } from '../../config/peer-role-resolver.js';
7
6
  import { agentDir, agentRelationSharedDir } from '../../paths.js';
8
- import { formatPeerKey } from '../relation/peer-identity.js';
7
+ import { formatPeerKey, readAunPeerKind } from '../relation/peer-identity.js';
9
8
  export class DataRootError extends Error {
10
9
  code;
11
10
  data;
@@ -27,7 +26,8 @@ function isInside(root, candidate) {
27
26
  }
28
27
  function authenticatedPrincipal(subject) {
29
28
  const principalId = String(subject.principalId ?? '').trim();
30
- if (!isValidAid(principalId) || isExplicitGroupId(principalId)) {
29
+ if (!isValidAid(principalId) || !subject.selfAid
30
+ || readAunPeerKind(subject.selfAid, principalId, { routeKind: 'private' }).kind !== 'private') {
31
31
  throw new DataRootError('ROOT_FORBIDDEN', 'A verified private AUN principal is required');
32
32
  }
33
33
  return principalId;
@@ -71,7 +71,8 @@ export class DataRootResolver {
71
71
  throw new DataRootError('ROOT_FORBIDDEN', 'Only the Agent owner may select another relation');
72
72
  }
73
73
  const peerAid = explicitPeerAid || principalId;
74
- if (!isValidAid(peerAid) || isExplicitGroupId(peerAid)) {
74
+ const kind = readAunPeerKind(targetAid, peerAid, peerAid === principalId ? { routeKind: 'private' } : {});
75
+ if (!isValidAid(peerAid) || kind.kind !== 'private') {
75
76
  throw new DataRootError('INVALID_ARGUMENT', 'args.peerAid must identify an AUN private-chat peer');
76
77
  }
77
78
  const peerKey = formatPeerKey('aun', peerAid);
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import { CONSOLIDATION_MODES, MODE_SCOPE } from '../memory/consolidation-context.js';
11
11
  import { formatQueueDetails } from '../memory/consolidation-queue-format.js';
12
+ import { FORGET_REASON_MAX_CHARS, normalizeForgetReason } from '../memory/consolidation-ops-records.js';
12
13
  import { MEMORY_SCOPES, isMemoryScope, memoryOverview, listMemoryFiles, formatMemoryFiles, readMemoryIndex, showMemoryFile, formatPendingNotes, showPendingNote, reindexScope, dropNote, archiveMemoryFile, restoreMemoryFile, } from '../memory/memory-admin.js';
13
14
  const USAGE = [
14
15
  '用法:',
@@ -19,8 +20,8 @@ const USAGE = [
19
20
  ' /memory index <scope> 查看 MEMORY.md 索引',
20
21
  ' /memory list <scope> [archived] 正式 / 已归档记忆列表',
21
22
  ' /memory show <scope> <slug> [archived] 查看单条记忆',
22
- ' /memory archive <scope> <slug> 归档记忆(可用 restore 恢复)',
23
- ' /memory restore <scope> <slug> 恢复已归档记忆',
23
+ ' /memory archive <scope> <slug> [理由] 归档记忆(可用 restore 恢复),理由记入遗忘日志',
24
+ ' /memory restore <scope> <slug> [理由] 恢复已归档记忆',
24
25
  ' /memory reindex <scope> 重建索引',
25
26
  ' /memory consolidate [mode] [scope] 拉起整理(mode: notes|generalize|promote|profile|forget;forget 需指定 scope)',
26
27
  'scope: relation | agent | owner',
@@ -89,8 +90,8 @@ export function memoryHelpEntries(ctx) {
89
90
  if (view.includes('relation'))
90
91
  add('/memory note', '查看单条 note', '<slug>');
91
92
  if (write.length > 0) {
92
- add('/memory archive', '归档一条记忆', '<scope> <slug>');
93
- add('/memory restore', '恢复已归档记忆', '<scope> <slug>');
93
+ add('/memory archive', '归档一条记忆', '<scope> <slug> [理由]');
94
+ add('/memory restore', '恢复已归档记忆', '<scope> <slug> [理由]');
94
95
  if (write.includes('relation'))
95
96
  add('/memory note drop', '撤销一条 note', '<slug>');
96
97
  }
@@ -187,13 +188,20 @@ export async function handleMemorySlash(ctx) {
187
188
  if (isPayload(scope))
188
189
  return scope;
189
190
  if (!args[2])
190
- return error(`用法: /memory ${sub} <scope> <slug>`);
191
+ return error(`用法: /memory ${sub} <scope> <slug> [理由]`);
192
+ // 理由可空(记「未注明理由」),给了就按遗忘理由的上限校验
193
+ const reason = normalizeForgetReason(args.slice(3).join(' '));
194
+ if ([...reason].length > FORGET_REASON_MAX_CHARS) {
195
+ return error(`理由不能超过 ${FORGET_REASON_MAX_CHARS} 字(当前 ${[...reason].length} 字)`);
196
+ }
197
+ const log = { reason, actorAid: ctx.actorAid };
191
198
  if (sub === 'archive') {
192
- await archiveMemoryFile(target, scope, args[2]);
199
+ await archiveMemoryFile(target, scope, args[2], log);
193
200
  return result(`✅ 已归档 ${scope}/${args[2]},索引已重建\n恢复: /memory restore ${scope} ${args[2]}`);
194
201
  }
195
- await restoreMemoryFile(target, scope, args[2]);
196
- return result(`✅ 已恢复 ${scope}/${args[2]},索引已重建`);
202
+ const restored = await restoreMemoryFile(target, scope, args[2], log);
203
+ const from = restored.stamped ? `(取的是最新归档 ${restored.restoredFrom})` : '';
204
+ return result(`✅ 已恢复 ${scope}/${args[2]}${from},索引已重建`);
197
205
  }
198
206
  if (sub === 'reindex') {
199
207
  const scope = needScope(args[1], true);