import * as fs from "node:fs"; import * as path from "node:path"; import type { MemoryConfig, MemoryOverflowStrategy, ReviewTransport, SessionSearchVariant, ThinkingLevel } from "./types.js"; import { DEFAULT_MEMORY_CHAR_LIMIT, DEFAULT_USER_CHAR_LIMIT, DEFAULT_PROJECT_CHAR_LIMIT, DEFAULT_PROJECTS_MEMORY_DIR, DEFAULT_NUDGE_INTERVAL, DEFAULT_FLUSH_MIN_TURNS, DEFAULT_NUDGE_TOOL_CALLS, DEFAULT_REVIEW_RECENT_MESSAGES, DEFAULT_FLUSH_RECENT_MESSAGES, DEFAULT_CONSOLIDATION_CHUNKING, DEFAULT_CONSOLIDATION_CHUNK_CHARS, DEFAULT_CONSOLIDATION_TIMEOUT_MS, DEFAULT_FLUSH_COMPACT_TIMEOUT_MS, CONSOLIDATION_CHUNK_CHARS_MIN, DEFAULT_OVERFLOW_GRACE_MS, DEFAULT_FAILURE_INJECTION_MAX_AGE_DAYS, DEFAULT_FAILURE_INJECTION_MAX_ENTRIES, DEFAULT_SESSION_RETENTION_DAYS, } from "./constants.js"; import { AGENT_ROOT, normalizeConfiguredMemoryDir, normalizeProjectsMemoryDir } from "./paths.js"; const MEMORY_OVERFLOW_STRATEGIES: readonly MemoryOverflowStrategy[] = ["auto-consolidate", "reject", "fifo-evict"]; const SESSION_SEARCH_VARIANTS: readonly SessionSearchVariant[] = ["legacy", "anchors"]; const REVIEW_TRANSPORTS: readonly ReviewTransport[] = ["direct", "subprocess"]; const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const; /** Path separators that cannot appear in a first-level directory name. */ const PATH_SEPARATOR_RE = /[\\/]/; /** * Keep only `sessionIndexExclude` entries that can name a first-level * directory under the sessions root: trimmed, non-empty, and free of path * separators or `..` segments. Rejected entries are dropped with a warning. * * Entries are matched against first-level directory names under the sessions * root (exact names or `*` globs), so a blank, separator-bearing, or `..` entry * can never match one: it would sit in the config file looking like a working * exclusion while excluding nothing. Malformed entries are dropped and warned * about instead of trusted — a config key must not fail quietly. */ function sanitizeSessionIndexExclude(value: string[]): string[] { const accepted: string[] = []; const rejected: string[] = []; for (const entry of value) { const name = entry.trim(); // Separators are rejected outright, so a `..` segment can only be the // whole (already trimmed) entry — the split keeps the check literal. if (name.length === 0 || PATH_SEPARATOR_RE.test(name) || name.split(PATH_SEPARATOR_RE).includes("..")) { rejected.push(entry); } else { accepted.push(name); } } if (rejected.length > 0) { console.warn( `⚠️ Ignoring ${rejected.length} invalid sessionIndexExclude entr${rejected.length === 1 ? "y" : "ies"}: ` + `${rejected.map((entry) => JSON.stringify(entry)).join(", ")}.` + " Entries must be first-level directory names — no path separators, no \"..\" segments, no empty values.", ); } return accepted; } function isReviewTransport(value: unknown): value is ReviewTransport { return typeof value === "string" && REVIEW_TRANSPORTS.includes(value as ReviewTransport); } function isMemoryOverflowStrategy(value: unknown): value is MemoryOverflowStrategy { return typeof value === "string" && MEMORY_OVERFLOW_STRATEGIES.includes(value as MemoryOverflowStrategy); } function isSessionSearchVariant(value: unknown): value is SessionSearchVariant { return typeof value === "string" && SESSION_SEARCH_VARIANTS.includes(value as SessionSearchVariant); } function isThinkingLevel(value: unknown): value is ThinkingLevel { return typeof value === "string" && (THINKING_LEVELS as readonly string[]).includes(value); } const DEFAULT_CONFIG: MemoryConfig = { lazyInitialization: false, autoRecover: true, memoryMode: "policy-only", memoryPolicyStyle: "full", memoryCharLimit: DEFAULT_MEMORY_CHAR_LIMIT, userCharLimit: DEFAULT_USER_CHAR_LIMIT, projectCharLimit: DEFAULT_PROJECT_CHAR_LIMIT, nudgeInterval: DEFAULT_NUDGE_INTERVAL, reviewRecentMessages: DEFAULT_REVIEW_RECENT_MESSAGES, reviewEnabled: true, reviewTransport: "direct", flushOnCompact: false, flushOnShutdown: false, flushMinTurns: DEFAULT_FLUSH_MIN_TURNS, flushRecentMessages: DEFAULT_FLUSH_RECENT_MESSAGES, flushCompactTimeoutMs: DEFAULT_FLUSH_COMPACT_TIMEOUT_MS, memoryOverflowStrategy: "auto-consolidate", overflowGraceMs: DEFAULT_OVERFLOW_GRACE_MS, autoConsolidate: true, correctionDetection: false, failureInjectionEnabled: true, failureInjectionMaxAgeDays: DEFAULT_FAILURE_INJECTION_MAX_AGE_DAYS, failureInjectionMaxEntries: DEFAULT_FAILURE_INJECTION_MAX_ENTRIES, consolidationChunking: DEFAULT_CONSOLIDATION_CHUNKING, consolidationChunkChars: DEFAULT_CONSOLIDATION_CHUNK_CHARS, consolidationTimeoutMs: DEFAULT_CONSOLIDATION_TIMEOUT_MS, usageHitTrackingEnabled: true, consolidationUsageSignals: true, autoConsolidationWarnOnFailure: true, nudgeToolCalls: DEFAULT_NUDGE_TOOL_CALLS, standingInstructionsEnabled: true, projectsMemoryDir: DEFAULT_PROJECTS_MEMORY_DIR, sessionSearch: { variant: "legacy" }, quickCheckOnOpen: true, sessionRetentionDays: DEFAULT_SESSION_RETENTION_DAYS, sessionIndexExclude: [], }; export const DEFAULT_CONFIG_PATH = path.join( AGENT_ROOT, "hermes-memory-config.json", ); export const DEFAULT_SETTINGS_PATH = path.join(AGENT_ROOT, "settings.json"); export const HERMES_MEMORY_SETTINGS_KEY = "hermesMemory"; function readConfigObject(configPath: string | undefined): Record | undefined { if (!configPath) return undefined; try { const parsed: unknown = JSON.parse(fs.readFileSync(configPath, "utf-8")); return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed as Record : undefined; } catch { return undefined; } } function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } export const AUTOMATION_MIGRATION_MARKER = path.join(AGENT_ROOT, ".hermes-automation-defaults-migrated"); /** * One-time: review and overflow cleanup became default-on, but installs paused * by the old defaults/recovery steps carry explicit `false`/`reject` that would * pin them off forever. Drop those keys so the new defaults apply. The marker * makes later deliberate opt-outs stick. * ponytail: cannot tell a deliberate old opt-out from a leftover pause; that is the accepted tradeoff. */ export function migrateAutomationDefaults( files = [DEFAULT_SETTINGS_PATH, DEFAULT_CONFIG_PATH], marker = AUTOMATION_MIGRATION_MARKER, ): void { try { if (fs.existsSync(marker)) return; for (const file of files) { const root = readConfigObject(file); if (!root) continue; const isSettings = path.basename(file) === "settings.json"; const target = isSettings ? root[HERMES_MEMORY_SETTINGS_KEY] : root; if (!isRecord(target)) continue; let changed = false; for (const [key, pinnedOff] of [["reviewEnabled", false], ["autoConsolidate", false], ["memoryOverflowStrategy", "reject"]] as const) { if (target[key] === pinnedOff) { delete target[key]; changed = true; } } if (!changed) continue; const tmp = `${file}.${process.pid}.tmp`; fs.writeFileSync(tmp, `${JSON.stringify(root, null, 2)}\n`); fs.renameSync(tmp, file); } fs.writeFileSync(marker, new Date().toISOString()); } catch { // Best effort: a read-only settings file must never block startup; retried next launch. } } /** Read extension settings from settings.json, falling back to the legacy file. */ export function loadConfig( configPath = DEFAULT_CONFIG_PATH, settingsPath?: string, ): MemoryConfig { try { const legacyConfig = readConfigObject(configPath); const resolvedSettingsPath = settingsPath ?? (configPath === DEFAULT_CONFIG_PATH ? DEFAULT_SETTINGS_PATH : undefined); const settings = readConfigObject(resolvedSettingsPath); const extensionSettings = settings?.[HERMES_MEMORY_SETTINGS_KEY]; if (legacyConfig || isRecord(extensionSettings)) { const parsed: Record = { ...(legacyConfig ?? {}), ...(isRecord(extensionSettings) ? extensionSettings : {}), }; // New settings.json values take precedence over the legacy file. const config: MemoryConfig = { ...DEFAULT_CONFIG }; const isNonNegativeNumber = (value: unknown): value is number => ( typeof value === "number" && Number.isFinite(value) && value >= 0 ); const isStringArray = (value: unknown): value is string[] => ( Array.isArray(value) && value.every((item) => typeof item === "string") ); let hasLegacyAutoConsolidate = false; let hasMemoryOverflowStrategy = false; if (typeof parsed.lazyInitialization === "boolean") config.lazyInitialization = parsed.lazyInitialization; if (typeof parsed.autoRecover === "boolean") config.autoRecover = parsed.autoRecover; if (parsed.memoryMode === "policy-only" || parsed.memoryMode === "legacy-inject") config.memoryMode = parsed.memoryMode; if ( parsed.memoryPolicyStyle === "full" || parsed.memoryPolicyStyle === "compact" || parsed.memoryPolicyStyle === "custom" || parsed.memoryPolicyStyle === "none" ) config.memoryPolicyStyle = parsed.memoryPolicyStyle; if (typeof parsed.memoryPolicyCustomText === "string") config.memoryPolicyCustomText = parsed.memoryPolicyCustomText; if (isNonNegativeNumber(parsed.memoryCharLimit) && parsed.memoryCharLimit >= 1) config.memoryCharLimit = Math.floor(parsed.memoryCharLimit); if (isNonNegativeNumber(parsed.userCharLimit) && parsed.userCharLimit >= 1) config.userCharLimit = Math.floor(parsed.userCharLimit); if (typeof parsed.nudgeInterval === "number") config.nudgeInterval = parsed.nudgeInterval; if (isNonNegativeNumber(parsed.reviewRecentMessages)) config.reviewRecentMessages = parsed.reviewRecentMessages; if (typeof parsed.reviewEnabled === "boolean") config.reviewEnabled = parsed.reviewEnabled; if (isReviewTransport(parsed.reviewTransport)) config.reviewTransport = parsed.reviewTransport; if (typeof parsed.reviewTimeoutMs === "number" && Number.isFinite(parsed.reviewTimeoutMs) && parsed.reviewTimeoutMs > 0) { config.reviewTimeoutMs = parsed.reviewTimeoutMs; } if (typeof parsed.flushOnCompact === "boolean") config.flushOnCompact = parsed.flushOnCompact; if (typeof parsed.flushOnShutdown === "boolean") config.flushOnShutdown = parsed.flushOnShutdown; if (typeof parsed.flushMinTurns === "number") config.flushMinTurns = parsed.flushMinTurns; if (isNonNegativeNumber(parsed.flushRecentMessages)) config.flushRecentMessages = parsed.flushRecentMessages; if (typeof parsed.flushCompactTimeoutMs === "number" && Number.isFinite(parsed.flushCompactTimeoutMs)) { config.flushCompactTimeoutMs = parsed.flushCompactTimeoutMs; // Zero and below is the documented disable, not a too-low timeout. if (parsed.flushCompactTimeoutMs > 0 && parsed.flushCompactTimeoutMs < DEFAULT_FLUSH_COMPACT_TIMEOUT_MS) { console.warn( `⚠️ flushCompactTimeoutMs is set to ${parsed.flushCompactTimeoutMs}ms, below the ${DEFAULT_FLUSH_COMPACT_TIMEOUT_MS}ms default.` + " Compact flush is one LLM turn over the conversation; local models are routinely cut off below this.", ); } } if (typeof parsed.autoConsolidate === "boolean") { config.autoConsolidate = parsed.autoConsolidate; hasLegacyAutoConsolidate = true; } if (isMemoryOverflowStrategy(parsed.memoryOverflowStrategy)) { config.memoryOverflowStrategy = parsed.memoryOverflowStrategy; hasMemoryOverflowStrategy = true; } if (isNonNegativeNumber(parsed.overflowGraceMs)) config.overflowGraceMs = parsed.overflowGraceMs; if (typeof parsed.correctionDetection === "boolean") config.correctionDetection = parsed.correctionDetection; if (isStringArray(parsed.correctionStrongPatterns)) config.correctionStrongPatterns = parsed.correctionStrongPatterns; if (isStringArray(parsed.correctionWeakPatterns)) config.correctionWeakPatterns = parsed.correctionWeakPatterns; if (isStringArray(parsed.correctionNegativePatterns)) config.correctionNegativePatterns = parsed.correctionNegativePatterns; if (isStringArray(parsed.correctionDirectiveWords)) config.correctionDirectiveWords = parsed.correctionDirectiveWords; if (typeof parsed.consolidationTimeoutMs === "number") { config.consolidationTimeoutMs = parsed.consolidationTimeoutMs; if (parsed.consolidationTimeoutMs < DEFAULT_CONSOLIDATION_TIMEOUT_MS) { console.warn( `⚠️ consolidationTimeoutMs is set to ${parsed.consolidationTimeoutMs}ms, below the ${DEFAULT_CONSOLIDATION_TIMEOUT_MS}ms default.` + " Consolidation spawns a child agent turn and is routinely killed mid-run at lower values.", ); } } if (typeof parsed.consolidationChunking === "boolean") { config.consolidationChunking = parsed.consolidationChunking; } if (typeof parsed.usageHitTrackingEnabled === "boolean") { config.usageHitTrackingEnabled = parsed.usageHitTrackingEnabled; } if (typeof parsed.consolidationUsageSignals === "boolean") { config.consolidationUsageSignals = parsed.consolidationUsageSignals; } if (typeof parsed.consolidationChunkChars === "number" && Number.isFinite(parsed.consolidationChunkChars) && parsed.consolidationChunkChars >= CONSOLIDATION_CHUNK_CHARS_MIN) { config.consolidationChunkChars = parsed.consolidationChunkChars; } if (typeof parsed.autoConsolidationWarnOnFailure === "boolean") { config.autoConsolidationWarnOnFailure = parsed.autoConsolidationWarnOnFailure; } if (typeof parsed.failureInjectionEnabled === "boolean") config.failureInjectionEnabled = parsed.failureInjectionEnabled; if (typeof parsed.failureInjectionMaxAgeDays === "number") config.failureInjectionMaxAgeDays = parsed.failureInjectionMaxAgeDays; if (typeof parsed.failureInjectionMaxEntries === "number") config.failureInjectionMaxEntries = parsed.failureInjectionMaxEntries; if (typeof parsed.nudgeToolCalls === "number") config.nudgeToolCalls = parsed.nudgeToolCalls; // Accept any finite number >= 0 so a user can both opt in (positive value) // and explicitly disable retention with 0. Invalid/negative values are // ignored, keeping the current (default) semantics. if (typeof parsed.sessionRetentionDays === "number" && Number.isFinite(parsed.sessionRetentionDays) && parsed.sessionRetentionDays >= 0) { config.sessionRetentionDays = parsed.sessionRetentionDays; } if (typeof parsed.standingInstructionsEnabled === "boolean") config.standingInstructionsEnabled = parsed.standingInstructionsEnabled; if (isStringArray(parsed.sessionIndexExclude)) { config.sessionIndexExclude = sanitizeSessionIndexExclude(parsed.sessionIndexExclude); } if (isNonNegativeNumber(parsed.projectCharLimit) && parsed.projectCharLimit >= 1) config.projectCharLimit = Math.floor(parsed.projectCharLimit); if (typeof parsed.memoryDir === "string") { const normalizedMemoryDir = normalizeConfiguredMemoryDir(parsed.memoryDir); if (normalizedMemoryDir) config.memoryDir = normalizedMemoryDir; } if (typeof parsed.projectsMemoryDir === "string") { const normalizedProjectsMemoryDir = normalizeProjectsMemoryDir(parsed.projectsMemoryDir); if (normalizedProjectsMemoryDir) config.projectsMemoryDir = normalizedProjectsMemoryDir; } if ( isRecord(parsed.sessionSearch) && isSessionSearchVariant(parsed.sessionSearch.variant) ) { config.sessionSearch = { variant: parsed.sessionSearch.variant }; } if (typeof parsed.quickCheckOnOpen === "boolean") config.quickCheckOnOpen = parsed.quickCheckOnOpen; if (isThinkingLevel(parsed.llmThinkingOverride)) config.llmThinkingOverride = parsed.llmThinkingOverride; if (isStringArray(parsed.childExtensionPaths)) { const childExtensionPaths = [...new Set( (parsed.childExtensionPaths as string[]).map((item) => item.trim()).filter(Boolean), )]; if (childExtensionPaths.length > 0) config.childExtensionPaths = childExtensionPaths; } if (hasMemoryOverflowStrategy) { config.autoConsolidate = config.memoryOverflowStrategy === "auto-consolidate"; } else if (hasLegacyAutoConsolidate) { config.memoryOverflowStrategy = config.autoConsolidate ? "auto-consolidate" : "reject"; } return config; } } catch { // Fall back to defaults on unexpected parse or access issues. } return { ...DEFAULT_CONFIG }; }