evolcore 0.0.39 → 0.0.41-test.0

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 (153) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +31 -20
  3. package/bin/codex-managed-hook.mjs +11 -0
  4. package/bin/ec-safe-output.js +25 -3
  5. package/dist/agents/baseagent-availability.js +1 -0
  6. package/dist/agents/claude-runner.js +53 -152
  7. package/dist/agents/codex-runner.js +485 -241
  8. package/dist/agents/ecagent-runner.js +48 -18
  9. package/dist/agents/gemini-runner.js +27 -8
  10. package/dist/agents/runner-types.js +39 -9
  11. package/dist/aun/ability-device-routing.js +26 -0
  12. package/dist/aun/aid/client.js +1 -1
  13. package/dist/aun/aid/control-aid.js +23 -98
  14. package/dist/aun/aid/ownership-operation.js +1 -3
  15. package/dist/aun/group/identity.js +8 -0
  16. package/dist/aun/group/invite-service.js +6 -0
  17. package/dist/aun/msg/managed-operation.js +4 -4
  18. package/dist/aun/msg/p2p.js +28 -12
  19. package/dist/aun/storage/download.js +30 -0
  20. package/dist/aun/storage/index.js +14 -6
  21. package/dist/channels/aun.js +99 -52
  22. package/dist/channels/daemon.js +24 -4
  23. package/dist/channels/dingtalk.js +8 -2
  24. package/dist/channels/feishu.js +6 -1
  25. package/dist/channels/wecom.js +7 -3
  26. package/dist/cli/agent-command.js +2 -0
  27. package/dist/cli/agent-create.js +121 -23
  28. package/dist/cli/agent.js +10 -3
  29. package/dist/cli/aid-bind-command.js +4 -1
  30. package/dist/cli/aun-commands.js +82 -22
  31. package/dist/cli/daemon-commands.js +260 -26
  32. package/dist/cli/index.js +25 -13
  33. package/dist/cli/memory-command.js +33 -14
  34. package/dist/cli/restart-monitor.js +52 -13
  35. package/dist/cli/session-command.js +128 -13
  36. package/dist/cli/stats.js +60 -4
  37. package/dist/cli/task-context.js +1 -0
  38. package/dist/cli/trigger-command.js +2 -2
  39. package/dist/config/access-policy.js +2 -0
  40. package/dist/config/config-field-policy.js +1 -0
  41. package/dist/config/config-operation-service.js +17 -6
  42. package/dist/config/gateway-config.js +1 -1
  43. package/dist/config/peer-role-resolver.js +10 -8
  44. package/dist/contracts/ecweb-service-protocol.js +44 -0
  45. package/dist/core/agent-application-service.js +11 -1
  46. package/dist/core/agent-ipc-registration.js +4 -0
  47. package/dist/core/agent-runtime.js +6 -0
  48. package/dist/core/auth/agent-delegation.js +87 -9
  49. package/dist/core/auth/auth-gateway.js +3 -1
  50. package/dist/core/auth/authorization-audit.js +25 -4
  51. package/dist/core/auth/debug-context.js +5 -1
  52. package/dist/core/auth/operation-catalog.js +24 -0
  53. package/dist/core/command/agent-control.js +91 -12
  54. package/dist/core/command/command-handler.js +64 -47
  55. package/dist/core/command/connect-menu.js +23 -2
  56. package/dist/core/command/menu-catalog.js +49 -12
  57. package/dist/core/command/menu-handler.js +110 -105
  58. package/dist/core/command/menu-protocol.js +29 -3
  59. package/dist/core/command/role-menu.js +7 -6
  60. package/dist/core/command/slash-gate.js +22 -5
  61. package/dist/core/command/slash-handler.js +121 -102
  62. package/dist/core/event-catalog.js +17 -0
  63. package/dist/core/interaction-router.js +2 -1
  64. package/dist/core/ipc-registration.js +44 -8
  65. package/dist/core/memory/batch-meta.js +2 -0
  66. package/dist/core/memory/consolidation-context.js +42 -51
  67. package/dist/core/memory/consolidation-ops-records.js +39 -7
  68. package/dist/core/memory/consolidation-trigger.js +72 -65
  69. package/dist/core/memory/consolidation.js +226 -20
  70. package/dist/core/memory/memory-writer.js +160 -34
  71. package/dist/core/memory/relation-idle-monitor.js +287 -0
  72. package/dist/core/memory/relation-sweep.js +206 -0
  73. package/dist/core/message/aun-ipc-sender.js +31 -5
  74. package/dist/core/message/aun-request-registry.js +97 -3
  75. package/dist/core/message/im-renderer.js +4 -0
  76. package/dist/core/message/message-admission.js +8 -4
  77. package/dist/core/message/message-bridge.js +96 -53
  78. package/dist/core/message/message-log.js +72 -0
  79. package/dist/core/message/message-queue.js +11 -5
  80. package/dist/core/message/outbound.js +70 -0
  81. package/dist/core/message/peer-mode.js +7 -2
  82. package/dist/core/message/response-engine.js +633 -191
  83. package/dist/core/model/model-catalog.js +7 -6
  84. package/dist/core/ownership/owner-resolver.js +384 -178
  85. package/dist/core/permission/ec-command-parser.js +129 -8
  86. package/dist/core/permission/tool-policy.js +35 -14
  87. package/dist/core/role/runtime-policy.js +64 -0
  88. package/dist/core/session/session-capsule.js +197 -0
  89. package/dist/core/session/session-manager.js +172 -18
  90. package/dist/core/session/session-mapper.js +2 -0
  91. package/dist/core/system-session/memory.js +3 -18
  92. package/dist/ecweb/basic-settings-service.js +709 -0
  93. package/dist/ecweb/providers-service.js +172 -0
  94. package/dist/index.js +95 -7
  95. package/dist/ipc.js +100 -19
  96. package/dist/stats/budget.js +1 -1
  97. package/dist/stats/db.js +48 -0
  98. package/dist/stats/index.js +3 -3
  99. package/dist/stats/price-resolver.js +304 -5
  100. package/dist/stats/query.js +328 -3
  101. package/dist/stats/writer.js +79 -6
  102. package/dist/trigger/application-service.js +12 -0
  103. package/dist/trigger/authorization.js +2 -2
  104. package/dist/trigger/feedback.js +18 -7
  105. package/dist/trigger/history.js +36 -0
  106. package/dist/trigger/manager.js +20 -3
  107. package/dist/trigger/parser.js +6 -3
  108. package/dist/trigger/patch.js +1 -1
  109. package/dist/trigger/scheduler.js +3 -0
  110. package/dist/trigger/system-definitions.js +43 -7
  111. package/dist/trigger/validation.js +13 -5
  112. package/dist/utils/ecweb-supervisor.js +31 -10
  113. package/dist/utils/error-utils.js +22 -4
  114. package/dist/utils/evolcore-version.js +3 -2
  115. package/dist/utils/host-info.js +52 -0
  116. package/dist/utils/npm-ops.js +2 -1
  117. package/dist/utils/package-version-info.js +1 -1
  118. package/dist/utils/upgrade-jobs.js +45 -5
  119. package/ecagent/dist/harness/agent-harness.js +4 -1
  120. package/kits/docs/INDEX.md +1 -1
  121. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  122. package/kits/docs/evolcore/INDEX.md +3 -2
  123. package/kits/docs/evolcore/agent-create.md +3 -2
  124. package/kits/docs/evolcore/agent.md +1 -1
  125. package/kits/docs/evolcore/aid.md +29 -12
  126. package/kits/docs/evolcore/config.md +9 -7
  127. package/kits/docs/evolcore/event.md +1 -0
  128. package/kits/docs/evolcore/fs.md +5 -0
  129. package/kits/docs/evolcore/memory-architecture.md +3 -4
  130. package/kits/docs/evolcore/memory-consolidation.md +28 -7
  131. package/kits/docs/evolcore/memory-tags.md +1 -1
  132. package/kits/docs/evolcore/memory.md +1 -1
  133. package/kits/docs/evolcore/menu-client.md +1 -1
  134. package/kits/docs/evolcore/menu-protocol.md +38 -0
  135. package/kits/docs/evolcore/msg.md +18 -2
  136. package/kits/docs/evolcore/session.md +14 -0
  137. package/kits/eck_manifest.json +3 -3
  138. package/kits/rules/04-relation.md +3 -2
  139. package/kits/schemas/agent-config.schema.13.json +20 -1
  140. package/kits/skills/aid-ability/SKILL.md +35 -6
  141. package/kits/templates/memory-consolidation/generalize.md +32 -4
  142. package/kits/templates/memory-consolidation/notes.md +2 -2
  143. package/kits/templates/memory-consolidation/promote.md +10 -2
  144. package/kits/templates/session-capsule/recovery.md +5 -0
  145. package/kits/templates/session-capsule/renew.md +5 -0
  146. package/kits/templates/system-fragments/baseagent.md +5 -0
  147. package/kits/templates/system-fragments/bootstrap.md +6 -6
  148. package/kits/templates/system-fragments/channel.md +1 -1
  149. package/kits/templates/system-fragments/memory.md +12 -3
  150. package/kits/templates/system-fragments/session.md +1 -1
  151. package/kits/{rules/07-memory-and-thread.md → templates/system-fragments/thread.md} +17 -80
  152. package/package.json +3 -3
  153. package/dist/stats/billing.js +0 -215
@@ -14,6 +14,8 @@ import path from 'path';
14
14
  import fs from 'fs';
15
15
  import os from 'os';
16
16
  import { createHash } from 'node:crypto';
17
+ import { appendSessionCapsuleEvent, capsuleHistory, fallbackCapsuleContent, findSessionCapsule, generateCapsuleContent, generateCapsuleId, renderCapsuleInput, withoutBackendSessionId } from './session-capsule.js';
18
+ import { associateMessageCapsule } from '../message/message-log.js';
17
19
  function forkHistoryRecord(value) {
18
20
  return value && typeof value === 'object' && !Array.isArray(value)
19
21
  ? value
@@ -227,8 +229,8 @@ export function pageForkHistory(snapshot, before = snapshot.items.length, limit
227
229
  };
228
230
  }
229
231
  /** Metadata keys owned by ordinary topic/session routing writers. */
230
- const TOPIC_METADATA_PROTECTED_KEYS = new Set(['turnState', 'resumeAt', 'agentSessions', 'sessionLoop']);
231
- const TOPIC_BACKEND_SCOPED_KEYS = ['resumeAt', 'agentSessions'];
232
+ const TOPIC_METADATA_PROTECTED_KEYS = new Set(['turnState', 'resumeAt', 'agentSessions', 'sessionLoop', 'sessionFullAccess', 'capsuleId']);
233
+ const TOPIC_BACKEND_SCOPED_KEYS = ['resumeAt', 'agentSessions', 'capsuleId'];
232
234
  function topicMetadataOwnershipError(key) {
233
235
  const error = new Error(`topic metadata field is owned by a dedicated updater: ${key}`);
234
236
  error.code = 'TOPIC_METADATA_OWNERSHIP';
@@ -254,6 +256,13 @@ function newSessionStableMetadata(chatType, ...sources) {
254
256
  }
255
257
  return metadata;
256
258
  }
259
+ function matchesActiveTurn(session, lease) {
260
+ const active = session.metadata?.turnState?.active;
261
+ return session.id === lease.sessionId && !!active
262
+ && session.metadata?.turnState?.generation === lease.generation
263
+ && active.generation === lease.generation && active.taskId === lease.taskId
264
+ && active.turnId === lease.turnId && active.inputId === lease.inputId;
265
+ }
257
266
  /** 判定用户是否为指定渠道的 admin */
258
267
  /** 判定用户是否为指定渠道的 member */
259
268
  export class SessionManager {
@@ -265,6 +274,7 @@ export class SessionManager {
265
274
  /** findSessionFileById 的查找缓存:命中前一律 stat 校验,不作为真相源。 */
266
275
  sessionFileIndex = new Map();
267
276
  knownChatDirs = null;
277
+ capsuleTranscriptReader;
268
278
  constructor(sessionsDir, eventBus, identityResolver) {
269
279
  ensureDir(sessionsDir);
270
280
  this.sessionsDir = sessionsDir;
@@ -278,6 +288,90 @@ export class SessionManager {
278
288
  this.fileAdapters.set(adapter.baseagent, adapter);
279
289
  logger.debug(`[SessionManager] Registered file adapter: ${adapter.baseagent}`);
280
290
  }
291
+ setCapsuleTranscriptReader(reader) {
292
+ this.capsuleTranscriptReader = reader;
293
+ }
294
+ getPendingCapsule(session) {
295
+ const id = session.metadata?.capsuleId;
296
+ if (!id)
297
+ return undefined;
298
+ const capsule = findSessionCapsule(this.getChatDir(session), id);
299
+ if (!capsule || capsule.sessionId !== session.id)
300
+ throw new Error('Session capsule is unavailable');
301
+ return capsule.consumedAt === undefined ? capsule : undefined;
302
+ }
303
+ createCapsule(source, targetSessionId, cause, content) {
304
+ const capsule = {
305
+ capsuleId: generateCapsuleId(), sessionId: targetSessionId,
306
+ ...(source.id !== targetSessionId ? { sourceSessionId: source.id } : {}),
307
+ cause, sourceAgentSessionId: source.agentSessionId, content, createdAt: Date.now(),
308
+ };
309
+ appendSessionCapsuleEvent(this.getChatDir(source), { ...capsule, kind: 'created' });
310
+ return capsule;
311
+ }
312
+ stageBackendRecovery(session, content) {
313
+ if (!session.agentSessionId)
314
+ return this.getPendingCapsule(session);
315
+ const existing = this.getPendingCapsule(session);
316
+ if (existing?.sourceAgentSessionId === session.agentSessionId && !existing.agentSessionId)
317
+ return existing;
318
+ const capsule = this.createCapsule(session, session.id, 'backend-recovery', content ?? fallbackCapsuleContent(capsuleHistory(this.getChatDir(session), session), 'backend-recovery'));
319
+ session.metadata = { ...session.metadata, capsuleId: capsule.capsuleId };
320
+ return capsule;
321
+ }
322
+ /** Called before the first model input; pending context is never added to system instructions. */
323
+ prepareCapsuleInput(sessionId, prompt) {
324
+ const loaded = this.loadSessionForUpdate(sessionId);
325
+ if (!loaded)
326
+ return { prompt };
327
+ const capsule = this.getPendingCapsule(loaded.current);
328
+ if (!capsule)
329
+ return { prompt };
330
+ return { prompt: renderCapsuleInput(capsule, prompt), capsuleId: capsule.capsuleId };
331
+ }
332
+ /** Main-session runners may discover an unavailable transcript after generic admission. */
333
+ async prepareBackendRecovery(sessionId, expectedAgentSessionId, prompt, systemPrompt, lease) {
334
+ const cleared = await this.clearMainSessionBackendIfMatches(sessionId, expectedAgentSessionId, [], lease);
335
+ if (cleared !== 'cleared' && cleared !== 'already_clear') {
336
+ throw new Error(`Backend recovery rejected: ${cleared}`);
337
+ }
338
+ const prepared = this.prepareCapsuleInput(sessionId, prompt);
339
+ return { ...prepared, systemPrompt: withoutBackendSessionId(systemPrompt) };
340
+ }
341
+ recordCapsuleBinding(session, agentSessionId) {
342
+ const capsule = this.getPendingCapsule(session);
343
+ if (!capsule || capsule.agentSessionId === agentSessionId)
344
+ return;
345
+ if (capsule.agentSessionId)
346
+ throw new Error('Capsule is already bound to a different backend');
347
+ appendSessionCapsuleEvent(this.getChatDir(session), { ...capsule, content: undefined,
348
+ kind: 'bound', agentSessionId });
349
+ }
350
+ /** Requires both durable backend binding and current-turn input acceptance. */
351
+ consumeSessionCapsule(sessionId, capsuleId, input) {
352
+ const loaded = this.loadSessionForUpdate(sessionId);
353
+ if (!loaded || loaded.current.agentSessionId !== input.agentSessionId)
354
+ return undefined;
355
+ const session = loaded.current;
356
+ if (input.lease && !matchesActiveTurn(session, input.lease))
357
+ return undefined;
358
+ const capsule = this.getPendingCapsule(session);
359
+ if (!capsule || capsule.capsuleId !== capsuleId || capsule.agentSessionId !== input.agentSessionId)
360
+ return undefined;
361
+ const consumedAt = Date.now();
362
+ appendSessionCapsuleEvent(this.getChatDir(session), { ...capsule, content: undefined,
363
+ kind: 'consumed', consumedAt, messageId: input.messageId });
364
+ // Input was accepted even when an auxiliary message-log annotation fails.
365
+ // Keep the durable receipt so a retry cannot submit this context twice.
366
+ associateMessageCapsule(this.getChatDir(session), session.id, capsuleId, input.messageId, input.timestamp);
367
+ if (capsule.cause === 'backend-recovery') {
368
+ this.eventBus.publish({ type: 'session:backend-recovery', sessionId,
369
+ agentAid: session.selfAID, baseagent: session.baseagent,
370
+ sourceAgentSessionId: capsule.sourceAgentSessionId, agentSessionId: input.agentSessionId,
371
+ capsuleId, timestamp: consumedAt });
372
+ }
373
+ return { ...capsule, consumedAt, messageId: input.messageId };
374
+ }
281
375
  getFileAdapter(baseagent) {
282
376
  return this.fileAdapters.get(baseagent);
283
377
  }
@@ -659,13 +753,17 @@ export class SessionManager {
659
753
  * @returns 是否真的写入了 .jsonl(去重命中时返回 false)
660
754
  */
661
755
  persistSession(session, intent, opts) {
662
- if (!opts?.sessionLoopMutation) {
756
+ if (!opts?.sessionLoopMutation && !opts?.sessionFullAccessMutation) {
663
757
  const latest = this.readMetaLatest(this.metaPathForSession(session));
664
758
  const metadata = { ...(session.metadata ?? {}) };
665
759
  if (latest?.metadata?.sessionLoop !== undefined)
666
760
  metadata.sessionLoop = latest.metadata.sessionLoop;
667
761
  else
668
762
  delete metadata.sessionLoop;
763
+ if (latest?.metadata?.sessionFullAccess !== undefined)
764
+ metadata.sessionFullAccess = latest.metadata.sessionFullAccess;
765
+ else
766
+ delete metadata.sessionFullAccess;
669
767
  session.metadata = metadata;
670
768
  }
671
769
  // Topic session snapshots can be written by synchronous legacy paths
@@ -799,6 +897,7 @@ export class SessionManager {
799
897
  return agentSessionId;
800
898
  }
801
899
  logger.warn(`Session file not found for ${session.baseagent}: ${agentSessionId}, clearing session ID`);
900
+ this.stageBackendRecovery(session);
802
901
  session.agentSessionId = undefined;
803
902
  this.persistSession(session, 'sync');
804
903
  return undefined;
@@ -1045,6 +1144,10 @@ export class SessionManager {
1045
1144
  async rotateTopicBackend(input) {
1046
1145
  if (!input.expectedThreadId.trim())
1047
1146
  throw new Error('backend rotation requires a non-empty threadId');
1147
+ const before = this.latestSessionForBoundary(input.sessionId).session;
1148
+ const capsuleContent = before?.agentSessionId
1149
+ ? await generateCapsuleContent(this.getChatDir(before), before, 'topic-renew', this.capsuleTranscriptReader)
1150
+ : undefined;
1048
1151
  return this.mutateLatestTopicSession(input.sessionId, (current, found) => {
1049
1152
  if (sessionTopicThreadId(current) !== input.expectedThreadId) {
1050
1153
  const error = new Error('backend rotation threadId mismatch');
@@ -1052,21 +1155,18 @@ export class SessionManager {
1052
1155
  throw error;
1053
1156
  }
1054
1157
  const wasBound = !!normalizeBackendSessionId(current.agentSessionId);
1158
+ if (before?.agentSessionId !== current.agentSessionId)
1159
+ throw new Error('Backend changed while preparing renew context');
1055
1160
  const next = JSON.parse(JSON.stringify(current));
1056
1161
  const previousBaseagent = next.baseagent;
1057
- if (input.baseagent !== undefined) {
1058
- const requested = input.baseagent.trim();
1059
- if (!requested) {
1060
- const error = new Error('backend rotation baseagent must be non-empty');
1061
- error.code = 'BASEAGENT_REQUIRED';
1062
- throw error;
1063
- }
1064
- next.baseagent = requested;
1065
- }
1066
1162
  next.agentSessionId = undefined;
1067
1163
  const nextMetadata = { ...(next.metadata ?? {}) };
1068
1164
  delete nextMetadata.resumeAt;
1069
1165
  delete nextMetadata.agentSessions;
1166
+ if (capsuleContent !== undefined) {
1167
+ const capsule = this.createCapsule(current, current.id, 'topic-renew', capsuleContent);
1168
+ nextMetadata.capsuleId = capsule.capsuleId;
1169
+ }
1070
1170
  next.metadata = nextMetadata;
1071
1171
  this.persistConfirmedTopicBoundary(current, found, next);
1072
1172
  return {
@@ -1106,13 +1206,16 @@ export class SessionManager {
1106
1206
  || current.metadata?.turnState?.generation !== input.lease.generation)
1107
1207
  return 'stale';
1108
1208
  const currentId = normalizeBackendSessionId(current.agentSessionId);
1109
- if (currentId === agentSessionId)
1209
+ if (currentId === agentSessionId) {
1210
+ this.recordCapsuleBinding(current, agentSessionId);
1110
1211
  return 'already_active';
1212
+ }
1111
1213
  if (currentId && currentId !== agentSessionId)
1112
1214
  return 'conflict';
1113
1215
  const next = JSON.parse(JSON.stringify(current));
1114
1216
  next.agentSessionId = agentSessionId;
1115
1217
  this.persistConfirmedTopicBoundary(current, found, next);
1218
+ this.recordCapsuleBinding(next, agentSessionId);
1116
1219
  return 'activated';
1117
1220
  });
1118
1221
  }
@@ -1400,8 +1503,9 @@ export class SessionManager {
1400
1503
  if (updates.name !== undefined)
1401
1504
  current.name = updates.name;
1402
1505
  if (updates.metadata !== undefined) {
1403
- if (Object.hasOwn(updates.metadata, 'sessionLoop'))
1404
- throw topicMetadataOwnershipError('sessionLoop');
1506
+ if (Object.hasOwn(updates.metadata, 'sessionLoop') || Object.hasOwn(updates.metadata, 'sessionFullAccess')) {
1507
+ throw topicMetadataOwnershipError(Object.hasOwn(updates.metadata, 'sessionLoop') ? 'sessionLoop' : 'sessionFullAccess');
1508
+ }
1405
1509
  if (isTopicSession(current)) {
1406
1510
  for (const key of Object.keys(updates.metadata)) {
1407
1511
  if (TOPIC_METADATA_PROTECTED_KEYS.has(key))
@@ -1431,7 +1535,7 @@ export class SessionManager {
1431
1535
  return;
1432
1536
  const { current } = loaded;
1433
1537
  for (const key of Object.keys(patch)) {
1434
- if (key === 'sessionLoop')
1538
+ if (key === 'sessionLoop' || key === 'sessionFullAccess')
1435
1539
  throw topicMetadataOwnershipError(key);
1436
1540
  if (isTopicSession(current) && TOPIC_METADATA_PROTECTED_KEYS.has(key)) {
1437
1541
  throw topicMetadataOwnershipError(key);
@@ -1462,6 +1566,19 @@ export class SessionManager {
1462
1566
  return current;
1463
1567
  });
1464
1568
  }
1569
+ updateSessionFullAccess(sessionId, config) {
1570
+ if (typeof config.enabled !== 'boolean' || !config.authorizedBy.trim()) {
1571
+ throw Object.assign(new Error('invalid session fullaccess configuration'), { code: 'INVALID_ARGUMENT' });
1572
+ }
1573
+ return this.mutateLatestTopicSession(sessionId, current => {
1574
+ if (!isTopicSession(current)) {
1575
+ throw Object.assign(new Error('session fullaccess requires a topic session'), { code: 'INVALID_CONTEXT' });
1576
+ }
1577
+ current.metadata = { ...(current.metadata ?? {}), sessionFullAccess: { ...config } };
1578
+ this.persistSession(current, 'none', { sessionFullAccessMutation: true });
1579
+ return current;
1580
+ });
1581
+ }
1465
1582
  /** Persist only the turn coordinator-owned metadata field. */
1466
1583
  async updateTurnState(sessionId, turnState) {
1467
1584
  const loaded = this.loadSessionForUpdate(sessionId);
@@ -1479,6 +1596,7 @@ export class SessionManager {
1479
1596
  getOrCreateThreadSession(channel, channelId, threadId, defaultProjectPath, metadata, name, baseagent, selfAID, channelType, peerType, chatType, label, topicStatus) {
1480
1597
  const topicMetadata = { ...(metadata ?? {}) };
1481
1598
  delete topicMetadata.sessionLoop;
1599
+ delete topicMetadata.sessionFullAccess;
1482
1600
  // 使用精确路径(channelType + selfAID)
1483
1601
  const chatDir = (channelType && selfAID)
1484
1602
  ? (() => { const d = chatDirPath(this.sessionsDir, channelType, channelId, selfAID, channel); fs.mkdirSync(d, { recursive: true }); fs.mkdirSync(path.join(d, '_threads'), { recursive: true }); return d; })()
@@ -1698,6 +1816,8 @@ export class SessionManager {
1698
1816
  }
1699
1817
  active.agentSessionId = agentSessionId;
1700
1818
  this.persistSession(active, 'sync');
1819
+ if (agentSessionId)
1820
+ this.recordCapsuleBinding(active, agentSessionId);
1701
1821
  }
1702
1822
  async updateAgentSessionIdBySessionId(sessionId, agentSessionId, turnLease) {
1703
1823
  const loaded = this.loadSessionForUpdate(sessionId);
@@ -1714,8 +1834,12 @@ export class SessionManager {
1714
1834
  logger.warn(`[SessionManager] Ignoring topic agentSessionId update without an active turn lease: sessionId=${sessionId}`);
1715
1835
  return 'stale';
1716
1836
  }
1837
+ if (turnLease && !matchesActiveTurn(current, turnLease))
1838
+ return 'stale';
1717
1839
  current.agentSessionId = agentSessionId;
1718
1840
  const wrote = this.persistSession(current, 'sync');
1841
+ if (agentSessionId)
1842
+ this.recordCapsuleBinding(current, agentSessionId);
1719
1843
  if (wrote) {
1720
1844
  logger.info(`[SessionManager] Updating agent_session_id: sessionId=${sessionId}, agentSessionId=${agentSessionId}`);
1721
1845
  }
@@ -1726,18 +1850,37 @@ export class SessionManager {
1726
1850
  * points at the caller's expected ID. This is the recovery counterpart to
1727
1851
  * provider-side "session not found" errors and must never rotate a topic.
1728
1852
  */
1729
- async clearMainSessionBackendIfMatches(sessionId, expectedAgentSessionId, metadataKeys = []) {
1853
+ async clearMainSessionBackendIfMatches(sessionId, expectedAgentSessionId, metadataKeys = [], lease) {
1730
1854
  const loaded = this.loadSessionForUpdate(sessionId);
1731
1855
  if (!loaded)
1732
1856
  return 'missing';
1733
- const { current } = loaded;
1857
+ let { current } = loaded;
1734
1858
  if (isTopicSession(current))
1735
1859
  return 'topic';
1860
+ if (lease && !matchesActiveTurn(current, lease))
1861
+ return 'mismatch';
1736
1862
  const currentId = normalizeBackendSessionId(current.agentSessionId);
1737
1863
  if (!currentId)
1738
1864
  return 'already_clear';
1739
1865
  if (currentId !== normalizeBackendSessionId(expectedAgentSessionId))
1740
1866
  return 'mismatch';
1867
+ const content = await generateCapsuleContent(this.getChatDir(current), current, 'backend-recovery', this.capsuleTranscriptReader);
1868
+ // Summary generation is outside the short snapshot mutation. Re-check the
1869
+ // durable binding so a late recovery cannot clear a newer backend.
1870
+ const latest = this.loadSessionForUpdate(sessionId);
1871
+ if (!latest)
1872
+ return 'missing';
1873
+ current = latest.current;
1874
+ if (isTopicSession(current))
1875
+ return 'topic';
1876
+ if (lease && !matchesActiveTurn(current, lease))
1877
+ return 'mismatch';
1878
+ const latestId = normalizeBackendSessionId(current.agentSessionId);
1879
+ if (!latestId)
1880
+ return 'already_clear';
1881
+ if (latestId !== normalizeBackendSessionId(expectedAgentSessionId))
1882
+ return 'mismatch';
1883
+ this.stageBackendRecovery(current, content);
1741
1884
  current.agentSessionId = undefined;
1742
1885
  if (metadataKeys.length > 0 && current.metadata) {
1743
1886
  const metadata = { ...current.metadata };
@@ -2150,6 +2293,8 @@ export class SessionManager {
2150
2293
  createdAt: Date.now(),
2151
2294
  updatedAt: Date.now(),
2152
2295
  };
2296
+ if (eventMetadata?.sourceSessionId)
2297
+ session.sourceSessionId = eventMetadata.sourceSessionId;
2153
2298
  this.persistSession(session, 'set');
2154
2299
  this.eventBus.publish({
2155
2300
  type: 'session:created',
@@ -2184,6 +2329,7 @@ export class SessionManager {
2184
2329
  const sourceTopicId = sessionTopicThreadId(sourceSession);
2185
2330
  const session = {
2186
2331
  id: generateSessionId(),
2332
+ sourceSessionId: sourceSession.id,
2187
2333
  channel: sourceSession.channel,
2188
2334
  channelType,
2189
2335
  channelId: sourceSession.channelId,
@@ -2250,6 +2396,7 @@ export class SessionManager {
2250
2396
  };
2251
2397
  const session = {
2252
2398
  id: generateSessionId(),
2399
+ sourceSessionId: sourceSession.id,
2253
2400
  channel: sourceSession.channel,
2254
2401
  channelType,
2255
2402
  channelId: sourceSession.channelId,
@@ -2317,11 +2464,15 @@ export class SessionManager {
2317
2464
  const metadata = { ...(sourceSession.metadata || {}) };
2318
2465
  delete metadata.agentSessions;
2319
2466
  delete metadata.resumeAt;
2467
+ delete metadata.turnState;
2468
+ delete metadata.capsuleId;
2320
2469
  delete metadata.replyContext;
2321
2470
  delete metadata.sessionLoop;
2471
+ delete metadata.sessionFullAccess;
2322
2472
  metadata.__sessionRenewedAt = Date.now();
2323
2473
  const session = {
2324
2474
  id: generateSessionId(),
2475
+ sourceSessionId: sourceSession.id,
2325
2476
  channel: sourceSession.channel,
2326
2477
  channelType: sourceSession.channelType || sourceSession.channel,
2327
2478
  channelId: sourceSession.channelId,
@@ -2338,6 +2489,9 @@ export class SessionManager {
2338
2489
  updatedAt: Date.now(),
2339
2490
  };
2340
2491
  session.identity = sourceSession.identity;
2492
+ const content = await generateCapsuleContent(this.getChatDir(sourceSession), sourceSession, 'session-renew', this.capsuleTranscriptReader);
2493
+ const capsule = this.createCapsule(sourceSession, session.id, 'session-renew', content);
2494
+ session.metadata = { ...session.metadata, capsuleId: capsule.capsuleId };
2341
2495
  this.persistSession(session, 'set');
2342
2496
  this.eventBus.publish({
2343
2497
  type: 'session:created',
@@ -108,6 +108,7 @@ export function sessionToFile(session) {
108
108
  }
109
109
  return {
110
110
  id: session.id,
111
+ ...(session.sourceSessionId ? { sourceSessionId: session.sourceSessionId } : {}),
111
112
  channel: session.channel,
112
113
  channelType,
113
114
  channelId: session.channelId,
@@ -166,6 +167,7 @@ export function fileToSession(file) {
166
167
  const isTopic = kind.kind === 'topic';
167
168
  return {
168
169
  id: file.id,
170
+ ...(file.sourceSessionId ? { sourceSessionId: file.sourceSessionId } : {}),
169
171
  channel: file.channel,
170
172
  channelType: file.channelType,
171
173
  channelId: file.channelId,
@@ -11,12 +11,11 @@
11
11
  * generalize B, A/consolidated, A/MEMORY.md, R/consolidated, M
12
12
  * promote B, O/consolidated, O/MEMORY.md, R/consolidated, M
13
13
  * profile B, R/consolidated, R/MEMORY.md, M
14
- * forget B, X/consolidated, X/MEMORY.md(X=触发层级),X=relation 时加 M
14
+ * forget B, X/consolidated, X/MEMORY.md(X=触发层级,一次只审一层),X=relation 时加 M
15
15
  *
16
16
  * 详见 docs/memory/system-session-plugin-design.md §5-§8
17
17
  */
18
18
  import path from 'path';
19
- import fs from 'fs';
20
19
  import { resolveRoot } from '../../paths.js';
21
20
  import { parseCodexToolCommand } from '../permission/ec-command-parser.js';
22
21
  import { canonicalToolCall } from '../permission/tool-canonical.js';
@@ -70,22 +69,8 @@ export function memoryReadRoots(ctx) {
70
69
  add(...consolidated('relation'), messages);
71
70
  break;
72
71
  case 'forget':
73
- if (ctx.memoryScope === 'agent') {
74
- // agent 级 forget:给所有 relation 的 consolidated 目录 + agent 自身的 consolidated
75
- const relationsRoot = path.join(resolveRoot(), 'agents', ctx.selfAid, 'relations');
76
- if (fs.existsSync(relationsRoot)) {
77
- for (const peerKey of fs.readdirSync(relationsRoot)) {
78
- const consolidatedDir = path.join(relationsRoot, peerKey, 'memory', 'consolidated');
79
- const indexPath = path.join(relationsRoot, peerKey, 'memory', 'MEMORY.md');
80
- if (fs.existsSync(consolidatedDir)) {
81
- add(consolidatedDir, indexPath);
82
- }
83
- }
84
- }
85
- add(...consolidated('agent'));
86
- }
87
- else if (ctx.memoryScope) {
88
- // relation / owner 级 forget:只给当前层级
72
+ // 一次会话只审一层:关系层由关系整理链逐关系审,agent 层只审 personal/memory 自身
73
+ if (ctx.memoryScope) {
89
74
  add(...consolidated(ctx.memoryScope));
90
75
  if (ctx.memoryScope === 'relation')
91
76
  add(messages);