evolution.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. /**
  2. * Evolution reminder logic — memory write prompts.
  3. *
  4. * v3: skill crystallization in-turn reminder removed. Skill reflection moved
  5. * to the daily-digest session-end fallback re-prompt (see
  6. * `daily-digest.ts:runSessionLevelFallback`) and the 05:00 memory-cleanup
  7. * spawn (multi-session pattern detection). The state map signatures still
  8. * carry `lastSkillReminderAt` / `nextSkillReminderAt` / `skillReminderGap`
  9. * so external callers compile during the rename window — they're unused
  10. * by this function in v3.
  11. *
  12. * Migrated from legacy prompt transform.
  13. * State (counters, snapshots) lives on SystemReminderService instance fields.
  14. */
  15. import type { MemoryDirSnapshot } from './types.js';
  16. import { EVOLUTION_CONFIG } from './types.js';
  17. // ─── Bound helpers ───────────────────────────────────────────────────────────
  18. const MAX_MAP_SIZE = 200;
  19. /** Evict oldest entries when a Map exceeds the size bound. */
  20. export function boundMap<K, V>(map: Map<K, V>, max = MAX_MAP_SIZE): void {
  21. if (map.size <= max) return;
  22. const keysToDelete = [...map.keys()].slice(0, map.size - max);
  23. for (const key of keysToDelete) {
  24. map.delete(key);
  25. }
  26. }
  27. // ─── Evolution Reminder ──────────────────────────────────────────────────────
  28. export interface EvolutionState {
  29. memorySnapshots: Map<string, MemoryDirSnapshot>;
  30. /** @deprecated v3: skill in-turn reminder removed. Field kept so existing
  31. * SystemReminderService field declarations compile; not read by
  32. * `getEvolutionReminder` anymore. */
  33. lastSkillReminderAt: Map<string, number>;
  34. /** Next turn at which to fire memory reminder (exponential back-off). */
  35. nextMemoryReminderAt: Map<string, number>;
  36. /** Current back-off gap for memory reminder (doubles on each miss). */
  37. memoryReminderGap: Map<string, number>;
  38. /** @deprecated v3: skill in-turn reminder removed. */
  39. nextSkillReminderAt: Map<string, number>;
  40. /** @deprecated v3: skill in-turn reminder removed. */
  41. skillReminderGap: Map<string, number>;
  42. }
  43. /**
  44. * Check evolution conditions and return reminder text if needed.
  45. *
  46. * v3: only the memory write reminder remains. Schedule:
  47. * - First fires at turn INITIAL_INTERVAL (10)
  48. * - If ignored, gap doubles: 10 → 20 → 40 (capped at MAX)
  49. * - Preserves backoff pace when agent writes memory (only snapshot updated)
  50. *
  51. * Skill crystallization reminder removed — skill reflection now happens at
  52. * session end via the daily-digest fallback re-prompt and at 05:00 via the
  53. * memory-cleanup multi-session pattern scan.
  54. *
  55. * @param currentMemorySnapshot - Host-collected snapshot of agent-level memory files
  56. * @param sessionId - Current session ID
  57. * @param agentName - Agent name (for mavis memory commands)
  58. * @param turnCount - Current turn number (1-indexed, from service layer)
  59. * @param state - Mutable state maps (owned by SystemReminderService)
  60. * @returns Reminder text or undefined
  61. */
  62. export function getEvolutionReminder(
  63. currentMemorySnapshot: MemoryDirSnapshot | undefined,
  64. sessionId: string,
  65. _agentName: string,
  66. turnCount: number,
  67. state: EvolutionState,
  68. ): string | undefined {
  69. if (!currentMemorySnapshot) return undefined;
  70. // Take initial snapshot on first call (agent memory dir — session memory removed)
  71. if (!state.memorySnapshots.has(sessionId)) {
  72. state.memorySnapshots.set(sessionId, cloneMemorySnapshot(currentMemorySnapshot));
  73. boundMap(state.memorySnapshots);
  74. }
  75. const reminders: string[] = [];
  76. // ── Memory reminder with exponential back-off ──
  77. const nextAt =
  78. state.nextMemoryReminderAt.get(sessionId) ?? EVOLUTION_CONFIG.MEMORY_REMINDER_INITIAL_INTERVAL;
  79. const currentGap =
  80. state.memoryReminderGap.get(sessionId) ?? EVOLUTION_CONFIG.MEMORY_REMINDER_INITIAL_INTERVAL;
  81. // Compaction detection: if turnCount dropped below the last fire point
  82. // (context was compressed), reset the back-off schedule.
  83. const lastFiredAt = nextAt - currentGap;
  84. if (lastFiredAt > 0 && turnCount < lastFiredAt) {
  85. state.nextMemoryReminderAt.set(
  86. sessionId,
  87. turnCount + EVOLUTION_CONFIG.MEMORY_REMINDER_INITIAL_INTERVAL,
  88. );
  89. state.memoryReminderGap.set(sessionId, EVOLUTION_CONFIG.MEMORY_REMINDER_INITIAL_INTERVAL);
  90. }
  91. const effectiveNextAt =
  92. state.nextMemoryReminderAt.get(sessionId) ?? EVOLUTION_CONFIG.MEMORY_REMINDER_INITIAL_INTERVAL;
  93. if (turnCount >= effectiveNextAt) {
  94. const initial = state.memorySnapshots.get(sessionId)!; // eslint-disable-line @typescript-eslint/no-non-null-assertion
  95. const current = currentMemorySnapshot;
  96. const memoryChanged =
  97. current.maxMtime > initial.maxMtime || current.files.length > initial.files.length;
  98. const activeGap =
  99. state.memoryReminderGap.get(sessionId) ?? EVOLUTION_CONFIG.MEMORY_REMINDER_INITIAL_INTERVAL;
  100. if (!memoryChanged) {
  101. // Double the gap, capped at MAX
  102. const nextGap = Math.min(activeGap * 2, EVOLUTION_CONFIG.MEMORY_REMINDER_MAX_INTERVAL);
  103. state.memoryReminderGap.set(sessionId, nextGap);
  104. state.nextMemoryReminderAt.set(sessionId, turnCount + nextGap);
  105. boundMap(state.memoryReminderGap);
  106. boundMap(state.nextMemoryReminderAt);
  107. reminders.push(
  108. [
  109. `已工作 ${turnCount} 轮,检查一下有没有值得记住的东西。`,
  110. '',
  111. '问自己:这次 session 有没有学到**不看 memory 下次会重蹈覆辙**的教训?',
  112. '',
  113. '写入前用三问法判断归属(写到第一个匹配的层,不要默认 agent memory):',
  114. ' 1. 换用户会变? → **User memory** (例: MR 合入偏好、沟通风格、序号指代习惯)',
  115. ' 2. 换项目结论仍成立? → **Agent memory** (例: CI 调试技巧、非交互 shell 用 .zshenv)',
  116. ' 3. 只在当前项目成立? → **Project memory** AGENTS.md / topic file (例: MR target dev、飞书群 chat_id)',
  117. '',
  118. '没有新东西?不写也完全没问题,不是每次都有新知识。',
  119. '',
  120. '不要写:代码结构、git 历史、API schema、已有文档能查到的信息。',
  121. '如果你还没读过 `mavis-memory` skill,先 load 它再写——里面有完整的分层规则和排除项。',
  122. ].join('\n'),
  123. );
  124. } else {
  125. // Memory was written — update baseline snapshot and advance schedule
  126. // by current gap (no reset to initial — backoff pace is preserved).
  127. state.memorySnapshots.set(sessionId, cloneMemorySnapshot(current));
  128. state.nextMemoryReminderAt.set(sessionId, turnCount + activeGap);
  129. boundMap(state.memorySnapshots);
  130. boundMap(state.nextMemoryReminderAt);
  131. }
  132. }
  133. return reminders.length > 0 ? reminders.join('\n\n---\n\n') : undefined;
  134. }
  135. function cloneMemorySnapshot(snapshot: MemoryDirSnapshot): MemoryDirSnapshot {
  136. return { files: [...snapshot.files], maxMtime: snapshot.maxMtime };
  137. }