/ commands / clear / caches.ts
caches.ts
  1  /**
  2   * Session cache clearing utilities.
  3   * This module is imported at startup by main.tsx, so keep imports minimal.
  4   */
  5  import { feature } from 'bun:bundle'
  6  import {
  7    clearInvokedSkills,
  8    setLastEmittedDate,
  9  } from '../../bootstrap/state.js'
 10  import { clearCommandsCache } from '../../commands.js'
 11  import { getSessionStartDate } from '../../constants/common.js'
 12  import {
 13    getGitStatus,
 14    getSystemContext,
 15    getUserContext,
 16    setSystemPromptInjection,
 17  } from '../../context.js'
 18  import { clearFileSuggestionCaches } from '../../hooks/fileSuggestions.js'
 19  import { clearAllPendingCallbacks } from '../../hooks/useSwarmPermissionPoller.js'
 20  import { clearAllDumpState } from '../../services/api/dumpPrompts.js'
 21  import { resetPromptCacheBreakDetection } from '../../services/api/promptCacheBreakDetection.js'
 22  import { clearAllSessions } from '../../services/api/sessionIngress.js'
 23  import { runPostCompactCleanup } from '../../services/compact/postCompactCleanup.js'
 24  import { resetAllLSPDiagnosticState } from '../../services/lsp/LSPDiagnosticRegistry.js'
 25  import { clearTrackedMagicDocs } from '../../services/MagicDocs/magicDocs.js'
 26  import { clearDynamicSkills } from '../../skills/loadSkillsDir.js'
 27  import { resetSentSkillNames } from '../../utils/attachments.js'
 28  import { clearCommandPrefixCaches } from '../../utils/bash/commands.js'
 29  import { resetGetMemoryFilesCache } from '../../utils/claudemd.js'
 30  import { clearRepositoryCaches } from '../../utils/detectRepository.js'
 31  import { clearResolveGitDirCache } from '../../utils/git/gitFilesystem.js'
 32  import { clearStoredImagePaths } from '../../utils/imageStore.js'
 33  import { clearSessionEnvVars } from '../../utils/sessionEnvVars.js'
 34  
 35  /**
 36   * Clear all session-related caches.
 37   * Call this when resuming a session to ensure fresh file/skill discovery.
 38   * This is a subset of what clearConversation does - it only clears caches
 39   * without affecting messages, session ID, or triggering hooks.
 40   *
 41   * @param preservedAgentIds - Agent IDs whose per-agent state should survive
 42   *   the clear (e.g., background tasks preserved across /clear). When non-empty,
 43   *   agentId-keyed state (invoked skills) is selectively cleared and requestId-keyed
 44   *   state (pending permission callbacks, dump state, cache-break tracking) is left
 45   *   intact since it cannot be safely scoped to the main session.
 46   */
 47  export function clearSessionCaches(
 48    preservedAgentIds: ReadonlySet<string> = new Set(),
 49  ): void {
 50    const hasPreserved = preservedAgentIds.size > 0
 51    // Clear context caches
 52    getUserContext.cache.clear?.()
 53    getSystemContext.cache.clear?.()
 54    getGitStatus.cache.clear?.()
 55    getSessionStartDate.cache.clear?.()
 56    // Clear file suggestion caches (for @ mentions)
 57    clearFileSuggestionCaches()
 58  
 59    // Clear commands/skills cache
 60    clearCommandsCache()
 61  
 62    // Clear prompt cache break detection state
 63    if (!hasPreserved) resetPromptCacheBreakDetection()
 64  
 65    // Clear system prompt injection (cache breaker)
 66    setSystemPromptInjection(null)
 67  
 68    // Clear last emitted date so it's re-detected on next turn
 69    setLastEmittedDate(null)
 70  
 71    // Run post-compaction cleanup (clears system prompt sections, microcompact tracking,
 72    // classifier approvals, speculative checks, and — for main-thread compacts — memory
 73    // files cache with load_reason 'compact').
 74    runPostCompactCleanup()
 75    // Reset sent skill names so the skill listing is re-sent after /clear.
 76    // runPostCompactCleanup intentionally does NOT reset this (post-compact
 77    // re-injection costs ~4K tokens), but /clear wipes messages entirely so
 78    // the model needs the full listing again.
 79    resetSentSkillNames()
 80    // Override the memory cache reset with 'session_start': clearSessionCaches is called
 81    // from /clear and --resume/--continue, which are NOT compaction events. Without this,
 82    // the InstructionsLoaded hook would fire with load_reason 'compact' instead of
 83    // 'session_start' on the next getMemoryFiles() call.
 84    resetGetMemoryFilesCache('session_start')
 85  
 86    // Clear stored image paths cache
 87    clearStoredImagePaths()
 88  
 89    // Clear all session ingress caches (lastUuidMap, sequentialAppendBySession)
 90    clearAllSessions()
 91    // Clear swarm permission pending callbacks
 92    if (!hasPreserved) clearAllPendingCallbacks()
 93  
 94    // Clear tungsten session usage tracking
 95    if (process.env.USER_TYPE === 'ant') {
 96      void import('../../tools/TungstenTool/TungstenTool.js').then(
 97        ({ clearSessionsWithTungstenUsage, resetInitializationState }) => {
 98          clearSessionsWithTungstenUsage()
 99          resetInitializationState()
100        },
101      )
102    }
103    // Clear attribution caches (file content cache, pending bash states)
104    // Dynamic import to preserve dead code elimination for COMMIT_ATTRIBUTION feature flag
105    if (feature('COMMIT_ATTRIBUTION')) {
106      void import('../../utils/attributionHooks.js').then(
107        ({ clearAttributionCaches }) => clearAttributionCaches(),
108      )
109    }
110    // Clear repository detection caches
111    clearRepositoryCaches()
112    // Clear bash command prefix caches (Haiku-extracted prefixes)
113    clearCommandPrefixCaches()
114    // Clear dump prompts state
115    if (!hasPreserved) clearAllDumpState()
116    // Clear invoked skills cache (each entry holds full skill file content)
117    clearInvokedSkills(preservedAgentIds)
118    // Clear git dir resolution cache
119    clearResolveGitDirCache()
120    // Clear dynamic skills (loaded from skill directories)
121    clearDynamicSkills()
122    // Clear LSP diagnostic tracking state
123    resetAllLSPDiagnosticState()
124    // Clear tracked magic docs
125    clearTrackedMagicDocs()
126    // Clear session environment variables
127    clearSessionEnvVars()
128    // Clear WebFetch URL cache (up to 50MB of cached page content)
129    void import('../../tools/WebFetchTool/utils.js').then(
130      ({ clearWebFetchCache }) => clearWebFetchCache(),
131    )
132    // Clear ToolSearch description cache (full tool prompts, ~500KB for 50 MCP tools)
133    void import('../../tools/ToolSearchTool/ToolSearchTool.js').then(
134      ({ clearToolSearchDescriptionCache }) => clearToolSearchDescriptionCache(),
135    )
136    // Clear agent definitions cache (accumulates per-cwd via EnterWorktreeTool)
137    void import('../../tools/AgentTool/loadAgentsDir.js').then(
138      ({ clearAgentDefinitionsCache }) => clearAgentDefinitionsCache(),
139    )
140    // Clear SkillTool prompt cache (accumulates per project root)
141    void import('../../tools/SkillTool/prompt.js').then(({ clearPromptCache }) =>
142      clearPromptCache(),
143    )
144  }