Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 35 additions & 4 deletions src/config/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,12 +264,24 @@ function applyEnvMappings(config: ExternalConfig, mappings: EnvMapping[]): void

const key = parts[parts.length - 1];
switch (type) {
case 'int':
obj[key] = parseInt(value, 10);
case 'int': {
const parsed = parseInt(value, 10);
if (isNaN(parsed)) {
log.warn(`Invalid integer for ${env}: '${value}'`);
continue;
}
obj[key] = parsed;
break;
case 'float':
obj[key] = parseFloat(value);
}
case 'float': {
const parsed = parseFloat(value);
if (isNaN(parsed)) {
log.warn(`Invalid float for ${env}: '${value}'`);
continue;
}
obj[key] = parsed;
break;
}
case 'boolean':
obj[key] = value === 'true';
break;
Expand Down Expand Up @@ -381,6 +393,25 @@ export function validateExternalConfig(config: ExternalConfig): string[] {
}
}

// Maintenance validation
if (config.maintenance?.clusterHour !== undefined) {
if (config.maintenance.clusterHour < 0 || config.maintenance.clusterHour > 23) {
errors.push('maintenance.clusterHour must be between 0 and 23 (inclusive)');
}
}

// Recency validation
if (config.recency?.halfLifeHours !== undefined) {
if (config.recency.halfLifeHours <= 0) {
errors.push('recency.halfLifeHours must be greater than 0');
}
}
if (config.recency?.decayFactor !== undefined) {
if (config.recency.decayFactor < 0) {
errors.push('recency.decayFactor must be >= 0');
}
}

// Length penalty validation
if (config.lengthPenalty?.referenceTokens !== undefined) {
if (config.lengthPenalty.referenceTokens <= 0) {
Expand Down
36 changes: 35 additions & 1 deletion src/config/memory-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,11 +225,45 @@ export const DEFAULT_CONFIG: MemoryConfig = {
},
};

/**
* Cached runtime config, populated by initRuntimeConfig().
* When set, getConfig() returns this instead of bare defaults,
* ensuring user config files and env vars are respected.
*/
let _runtimeConfig: MemoryConfig | null = null;

/**
* Initialize the runtime config cache. Call once at startup (e.g., MCP server start).
* This ensures getConfig() respects user config files and env vars.
*/
export function initRuntimeConfig(config: MemoryConfig): void {
_runtimeConfig = config;
}

/**
* Get configuration with overrides applied.
* Returns the cached runtime config (from initRuntimeConfig) if available,
* otherwise falls back to DEFAULT_CONFIG.
*/
export function getConfig(overrides: Partial<MemoryConfig> = {}): MemoryConfig {
return { ...DEFAULT_CONFIG, ...overrides };
const base = _runtimeConfig ?? DEFAULT_CONFIG;
if (Object.keys(overrides).length === 0) return base;
return {
...base,
...overrides,
// Deep-merge nested objects to prevent shallow spread from destroying them
hybridSearch: { ...base.hybridSearch, ...overrides.hybridSearch },
clusterExpansion: { ...base.clusterExpansion, ...overrides.clusterExpansion },
mmrReranking: { ...base.mmrReranking, ...overrides.mmrReranking },
recency: { ...base.recency, ...overrides.recency },
lengthPenalty: { ...base.lengthPenalty, ...overrides.lengthPenalty },
repomap: {
...base.repomap,
...overrides.repomap,
languages: overrides.repomap?.languages ?? base.repomap.languages,
},
semanticIndex: { ...base.semanticIndex, ...overrides.semanticIndex },
};
}

/**
Expand Down
6 changes: 5 additions & 1 deletion src/dashboard/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,11 @@ export function createApp() {
}

export async function startDashboard(port: number): Promise<void> {
// Ensure database is initialized before starting
// Ensure config and database are initialized before starting
const { initRuntimeConfig } = await import('../config/memory-config.js');
const { loadConfig, toRuntimeConfig } = await import('../config/loader.js');
initRuntimeConfig(toRuntimeConfig(loadConfig()));

const { getDb } = await import('../storage/db.js');
getDb();

Expand Down
4 changes: 3 additions & 1 deletion src/hooks/hook-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ export async function withRetry<T>(
hookName: string,
fn: () => Promise<T>,
options: RetryOptions = {},
metrics?: HookMetrics,
): Promise<T> {
const {
maxRetries = 3,
Expand All @@ -130,6 +131,7 @@ export async function withRetry<T>(
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
if (attempt > 0) {
if (metrics) metrics.retryCount = attempt;
const delay = calculateBackoff(attempt - 1, initialDelayMs, maxDelayMs, backoffFactor);

logHook({
Expand Down Expand Up @@ -229,7 +231,7 @@ export async function executeHook<T>(
let result: T;

if (options.retry) {
result = await withRetry(hookName, fn, options.retry);
result = await withRetry(hookName, fn, options.retry, metrics);
} else {
result = await fn();
}
Expand Down
8 changes: 6 additions & 2 deletions src/hooks/session-start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ import {
getSessionsForProject,
getChunksByTimeRange,
} from '../storage/chunk-store.js';
import { getConfig } from '../config/memory-config.js';
import { getConfig, initRuntimeConfig } from '../config/memory-config.js';
import { loadConfig, toRuntimeConfig } from '../config/loader.js';
import { approximateTokens } from '../utils/token-counter.js';
import { runStaleMaintenanceTasks } from '../maintenance/scheduler.js';
import { executeHook, logHook, isTransientError, type HookMetrics } from './hook-utils.js';
Expand Down Expand Up @@ -193,6 +194,9 @@ export async function handleSessionStart(
): Promise<SessionStartResult> {
const { enableRetry = true, maxRetries = 3, gracefulDegradation = true } = options;

// Ensure user config is loaded before getConfig() is used
initRuntimeConfig(toRuntimeConfig(loadConfig()));

// Run stale maintenance tasks in background (prune, recluster)
// Covers cases where scheduled cron times were missed (e.g. laptop asleep)
runStaleMaintenanceTasks();
Expand All @@ -217,7 +221,7 @@ export async function handleSessionStart(
retryOn: isTransientError,
}
: undefined,
fallback: gracefulDegradation ? undefined : undefined,
fallback: gracefulDegradation ? fallbackResult : undefined,
project: basename(projectPath) || projectPath,
},
);
Expand Down
11 changes: 6 additions & 5 deletions src/ingest/brief-debrief-detector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,13 +234,14 @@ export function detectDebriefPoints(
const turn = mainTurns[i];
if (extractSpawnedAgentIds(turn).includes(agentId)) {
// Link to the next turn's chunks (all of them)
const nextChunkIds = chunkIdsByTurn.get(i + 1);
const nextTurnIndex = i + 1 < mainTurns.length ? mainTurns[i + 1].index : -1;
const nextChunkIds = nextTurnIndex >= 0 ? chunkIdsByTurn.get(nextTurnIndex) : undefined;
if (nextChunkIds && nextChunkIds.length > 0) {
debriefPoints.push({
agentId,
agentFinalChunkIds: finalChunkIds,
parentChunkIds: [...nextChunkIds],
turnIndex: i + 1,
turnIndex: nextTurnIndex,
spawnDepth,
});
}
Expand Down Expand Up @@ -281,7 +282,7 @@ function findDebriefTurn(turns: Turn[], agentId: string, _finalChunk: Chunk): nu
// Only match if the result explicitly contains this agent's ID
// (removed isTaskResult fallback - it's too broad and matches unrelated agents)
if (exchange.result.includes(agentId)) {
return i;
return turn.index;
}
}
}
Expand All @@ -291,7 +292,7 @@ function findDebriefTurn(turns: Turn[], agentId: string, _finalChunk: Chunk): nu
if (msg.type === 'user' && msg.message?.content) {
const content = msg.message.content;
if (typeof content === 'string' && content.includes(agentId)) {
return i;
return turn.index;
}
}
}
Expand All @@ -303,7 +304,7 @@ function findDebriefTurn(turns: Turn[], agentId: string, _finalChunk: Chunk): nu
if (extractSpawnedAgentIds(turn).includes(agentId)) {
// Return the next turn if it exists
if (i + 1 < turns.length) {
return i + 1;
return turns[i + 1].index;
}
}
}
Expand Down
32 changes: 23 additions & 9 deletions src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import { createInterface } from 'readline';
import { tools, getTool } from './tools.js';
import { getDb, closeDb } from '../storage/db.js';
import { initRuntimeConfig } from '../config/memory-config.js';
import { loadConfig, toRuntimeConfig } from '../config/loader.js';
import { disposeRetrieval } from '../retrieval/context-assembler.js';
import { getChunkCount } from '../storage/chunk-store.js';
import { getEdgeCount } from '../storage/edge-store.js';
Expand Down Expand Up @@ -82,7 +84,7 @@ interface McpRequest {
*/
interface McpResponse {
jsonrpc: '2.0';
id: string | number;
id: string | number | null;
result?: unknown;
error?: {
code: number;
Expand Down Expand Up @@ -113,7 +115,7 @@ interface HealthStatus {
* Create a standardized error response.
*/
function createErrorResponse(
id: string | number,
id: string | number | null,
code: number,
message: string,
data?: unknown,
Expand Down Expand Up @@ -176,7 +178,8 @@ export class McpServer {
this.running = true;
this.startTime = Date.now();

// Initialize database
// Initialize config and database
initRuntimeConfig(toRuntimeConfig(loadConfig()));
getDb();

this.log({ level: 'info', event: 'server_started' });
Expand Down Expand Up @@ -229,7 +232,7 @@ export class McpServer {
} catch (error) {
this.errorCount++;
const errorResponse = createErrorResponse(
0,
null,
ErrorCodes.PARSE_ERROR,
'Parse error',
errorMessage(error),
Expand Down Expand Up @@ -326,11 +329,22 @@ export class McpServer {
case 'tools/list':
return this.handleToolsList(id);

case 'tools/call':
return await this.handleToolsCall(
id,
params as { name: string; arguments: Record<string, unknown> },
);
case 'tools/call': {
const toolParams = params as
| { name: string; arguments?: Record<string, unknown> }
| undefined;
if (!toolParams || typeof toolParams.name !== 'string') {
return createErrorResponse(
id,
ErrorCodes.INVALID_PARAMS,
'tools/call requires params.name',
);
}
return await this.handleToolsCall(id, {
name: toolParams.name,
arguments: toolParams.arguments ?? {},
});
}

case 'ping':
return this.handlePing(id);
Expand Down
2 changes: 1 addition & 1 deletion src/mcp/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ export const listSessionsTool: ToolDefinition = {
const daysBack = args.days_back as number | undefined;
const limit = (args.limit as number | undefined) ?? 30;

if (daysBack !== null && daysBack !== undefined) {
if (daysBack !== undefined && daysBack > 0 && from === undefined && to === undefined) {
to = new Date().toISOString();
from = new Date(Date.now() - daysBack * 24 * 60 * 60 * 1000).toISOString();
}
Expand Down
2 changes: 2 additions & 0 deletions src/models/embedder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ export class Embedder {
throw epError;
}
}

// Only set config after pipeline is successfully loaded
this.config = config;

const loadTimeMs = performance.now() - start;
Expand Down
6 changes: 4 additions & 2 deletions src/retrieval/chain-walker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,9 @@ async function walkAllPaths(
if (agentFilter && chunk.agentId !== agentFilter) {
const newSkips = consecutiveSkips + 1;
if (newSkips <= maxSkippedConsecutive) {
const before = candidates.length;
await dfs(nextId, depth + 1, newSkips);
anyChildEmitted = true;
if (candidates.length > before) anyChildEmitted = true;
}
pathVisited.delete(nextId);
continue;
Expand All @@ -193,8 +194,9 @@ async function walkAllPaths(
// adding to path. The chain doesn't break — we continue traversing — but
// this node won't appear in the output or affect the median score.
if (chunkTokens > tokenBudget) {
const before = candidates.length;
await dfs(nextId, depth + 1, 0);
anyChildEmitted = true;
if (candidates.length > before) anyChildEmitted = true;
pathVisited.delete(nextId);
continue;
}
Expand Down
2 changes: 2 additions & 0 deletions src/storage/chunk-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ export function isSessionIngested(sessionId: string): boolean {
export function deleteChunk(id: string): boolean {
const db = getDb();
const result = db.prepare('DELETE FROM chunks WHERE id = ?').run(id);
invalidateProjectsCache();
return result.changes > 0;
}

Expand All @@ -225,6 +226,7 @@ export function deleteChunks(ids: string[]): number {
const db = getDb();
const placeholders = sqlPlaceholders(ids.length);
const result = db.prepare(`DELETE FROM chunks WHERE id IN (${placeholders})`).run(...ids);
invalidateProjectsCache();
return result.changes;
}

Expand Down
Loading