Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

55.4 KB
Raw Blame
import type { DeepSearchExecutor } from '../deep-search/protocol.js';
import { emptyDeepResult, type DeepSearchResult } from '../sqlite/tool-use-search.js';
import { formatDeepSearch } from '../../shared/deep-search-format.js';
import { AppError } from '../server/ErrorHandler.js';

import { SessionSearch } from '../sqlite/SessionSearch.js';
import { SessionStore } from '../sqlite/SessionStore.js';
import type { ContextReadWorkerClient } from '../context/ContextReadWorkerClient.js';
import { ChromaSync, type ChromaFallbackRowIds, type ChromaQueryProgress } from '../sync/ChromaSync.js';
import { CHROMA_SEARCH_BUDGET_MS } from '../sync/chroma-search-budget.js';
import { FormattingService, singleLineTitle } from './FormattingService.js';
import { TimelineService } from './TimelineService.js';
import type { TimelineItem } from './TimelineService.js';
import type { ObservationSearchResult, SessionSummarySearchResult, UserPromptSearchResult } from '../sqlite/types.js';
import { logger } from '../../utils/logger.js';
import { getProjectContext } from '../../utils/project-name.js';
import { normalizePlatformSource } from '../../shared/platform-source.js';
import { resolveDateBound } from '../../shared/date-bounds.js';
import { formatDate, formatTime, formatDateTime, formatSystemLocaleDateTime, extractFirstFile, groupByDate, estimateTokens } from '../../shared/timeline-formatting.js';
import { ModeManager } from '../domain/ModeManager.js';

import {
  SearchOrchestrator,
  SEARCH_CONSTANTS
} from './search/index.js';
import type { SearchResults, StrategySearchResult, DateRange } from './search/index.js';
import { assertSearchHasQueryOrFilter } from './search/SearchOrchestrator.js';
import { acceptsSemanticDistance, isCategoryRequested } from './search/types.js';
import { ResultFormatter } from './search/ResultFormatter.js';
import { ChromaUnavailableError } from './search/errors.js';
import { buildProjectWhereFilter, projectReadKeysFor } from './search/project-where-filter.js';
import { scopeRowIdsFor } from './search/scope-row-ids.js';

/**
 * Ceiling for `depth_before` / `depth_after` on the timeline route. Every unit
 * is a row fetched and rendered, so an unbounded depth turns one request into a
 * scan of the whole project history. The progressive search path caps this at 3
 * (`progressive-search.ts`); the direct route keeps a wider but finite window.
 */
const TIMELINE_MAX_DEPTH = 50;

/**
 * Telemetry envelope for search_performed (see docs/public/telemetry.mdx).
 * Populated by SearchManager.search() via a mutable sink param so response
 * shapes (json and text formats) stay untouched. Privacy: counts, booleans,
 * and closed enums only — never query text, results, or error messages.
 */
export interface SearchTelemetryEnvelope {
  result_count?: number;
  search_strategy?: 'chroma' | 'fts' | 'hybrid' | 'filter_only';
  chroma_available?: boolean;
  fallback_reason?: 'none' | 'chroma_connection' | 'chroma_error' | 'chroma_not_initialized' | 'chroma_zero_results';
}

type ObservationSearchState = { status: 'not_requested' | 'success_empty' | 'success_nonempty' | 'error' };

export class SearchManager {
  private orchestrator: SearchOrchestrator;

  constructor(
    private sessionSearch: SessionSearch,
    private sessionStore: SessionStore,
    private chromaSync: ChromaSync | null,
    private formatter: FormattingService,
    private timelineService: TimelineService,
    /**
     * Implicit window, in milliseconds, that date-less semantic searches
     * apply (CLAUDE_MEM_SEARCH_RECENCY_DAYS), except a typed relevance
     * search (see `search`). Defaults to the shipped 90 days; 0 disables the
     * window so every semantic match stays eligible. An explicit `dateRange`
     * on a request always wins over it.
     */
    private searchRecencyWindowMs: number = SEARCH_CONSTANTS.RECENCY_WINDOW_MS,
    private contextReader: ContextReadWorkerClient | null = null,
    private deepReader: DeepSearchExecutor | null = null,
    private maxDistance: number = Infinity
  ) {
    this.orchestrator = new SearchOrchestrator(
      sessionSearch,
      sessionStore,
      chromaSync,
      searchRecencyWindowMs,
      maxDistance
    );
  }

  getOrchestrator(): SearchOrchestrator {
    return this.orchestrator;
  }

  getFormatter(): FormattingService {
    return this.formatter;
  }

  getSessionStore(): SessionStore {
    return this.sessionStore;
  }

  private async queryChroma(
    query: string,
    limit: number,
    whereFilter: Record<string, any> | undefined,
    progress: ChromaQueryProgress | undefined,
    fallbackRowIds: ChromaFallbackRowIds,
    deadlineMs?: number
  ): Promise<{ ids: number[]; distances: number[]; metadatas: any[] }> {
    if (!this.chromaSync) {
      return { ids: [], distances: [], metadatas: [] };
    }
    return await this.chromaSync.queryChroma(query, limit, whereFilter, progress, fallbackRowIds, deadlineMs);
  }

  /**
   * Build a Chroma where-filter scoped to a single doc_type, applying the
   * dual-project ($or: project + merged_into_project) scoping used by every
   * single-type hybrid search path.
   */
  private buildDocTypeWhereFilter(docType: string, readKeys: string[], platformSource?: string): Record<string, any> {
    const filters: Array<Record<string, any>> = [{ doc_type: docType }];
    if (readKeys.length > 0) {
      filters.push(buildProjectWhereFilter(readKeys));
    }
    if (platformSource) {
      filters.push({ platform_source: normalizePlatformSource(platformSource) });
    }
    return filters.length === 1 ? filters[0] : { $and: filters };
  }

  /**
   * Shared "Chroma semantic match -> SQLite hydrate -> date-window filter"
   * pipeline for the single-doc-type hybrid searches. Explicit ranges replace the
   * default 90-day window. Returns the hydrated rows
   * (empty when Chroma yields nothing recent); callers own their own FTS
   * fallback and formatting so per-caller behavior is preserved exactly.
   */
  private async hybridSemanticHydrate<T extends { id: number; created_at_epoch: number }>(
    query: string,
    docType: string,
    project: string | undefined,
    platformSource: string | undefined,
    hydrate: (ids: number[], readKeys: string[]) => T[],
    projects?: string[],
    dateRange?: DateRange,
    requiredResults?: number,
    work?: { budgetReached: boolean }
  ): Promise<T[]> {
    const readKeys = projectReadKeysFor(this.sessionStore, project, projects);
    const whereFilter = this.buildDocTypeWhereFilter(docType, readKeys, platformSource);
    const fallbackRowIds = scopeRowIdsFor(this.sessionStore, {
      observations: docType === 'observation',
      sessions: docType === 'session_summary',
      prompts: docType === 'user_prompt',
    }, { project, projects: readKeys, platformSource });
    const startEpoch = dateRange
      ? dateRange.start != null ? resolveDateBound(dateRange.start, 'start') : undefined
      : this.searchRecencyWindowMs > 0 ? Date.now() - this.searchRecencyWindowMs : undefined;
    const endEpoch = dateRange?.end != null ? resolveDateBound(dateRange.end, 'end') : undefined;
    let candidateLimit: number = SEARCH_CONSTANTS.CHROMA_BATCH_SIZE;
    // Five ranked windows (100..1600), at most ten Chroma transport calls.
    // queryChroma caps raw fragment overfetch at 2000 documents per window;
    // filtered retries add at most 3100, bounding requested raw docs at 13100.
    const maxCandidates = 1600;
    const visited = new Set<number>();
    const hydrated = new Map<number, T>();
    // Five widening windows share one deadline, so a slow early window cannot
    // leave the last one running past the caller's search budget (#6323).
    const deadline = Date.now() + CHROMA_SEARCH_BUDGET_MS;

    while (true) {
      const progress: ChromaQueryProgress = {};
      const chromaResults = await this.queryChroma(query, candidateLimit, whereFilter, requiredResults ? progress : undefined, fallbackRowIds, deadline);
      const candidateIds = chromaResults.ids.filter((_id, index) => chromaResults.metadatas[index] != null
        && acceptsSemanticDistance(chromaResults.distances?.[index], this.maxDistance));
      // Repeated ranked prefixes reuse successful and rejected native lookups.
      // Build results in the current Chroma order, including cached matches.
      const newIds = candidateIds.filter(id => !visited.has(id));
      for (let offset = 0; offset < newIds.length; offset += 500) {
        const batch = newIds.slice(offset, offset + 500);
        for (const id of batch) visited.add(id);
        // The canonical date may have changed since the vector was indexed.
        for (const row of hydrate(batch, readKeys)) {
          if (row.created_at_epoch != null
            && (startEpoch === undefined || row.created_at_epoch >= startEpoch)
            && (endEpoch === undefined || row.created_at_epoch <= endEpoch)) hydrated.set(row.id, row);
        }
      }
      const rows = candidateIds.flatMap(id => {
        const row = hydrated.get(id);
        return row ? [row] : [];
      });
      if (requiredResults && rows.length >= requiredResults) return rows.slice(0, requiredResults);
      if (!requiredResults || progress.exhausted
        || (progress.exhausted === undefined && chromaResults.ids.length < candidateLimit)) return rows;
      if (candidateLimit >= maxCandidates) {
        if (work) work.budgetReached = true;
        return rows;
      }
      // Chroma has no offset. Widen only within the work budget; the caller
      // tries its filtered keyword fallback if this prefix is insufficient.
      candidateLimit = Math.min(candidateLimit * 2, maxCandidates);
    }
  }

  private async searchChromaForTimeline(query: string, project?: string, platformSource?: string, projects?: string[]): Promise<ObservationSearchResult[]> {
    const rows = await this.hybridSemanticHydrate(query, 'observation', project, platformSource, (ids, readKeys) =>
      this.sessionStore.getObservationsByIds(ids, { orderBy: 'relevance', project, projects: readKeys, platformSource }),
      projects,
    );
    return rows.slice(0, 1);
  }

  /**
   * Render a list of timeline items as grouped day -> file -> observation
   * markdown tables (with session/prompt rows interleaved). Returns the body
   * lines only; callers prepend their own title/window header. An item is the
   * anchor when its id matches a numeric anchorId (observation) or an "S{id}"
   * string anchorId (session).
   */
  private renderTimeline(
    filteredItems: TimelineItem[],
    anchorId: number | string | null,
    cwd: string
  ): string[] {
    const lines: string[] = [];

    const dayMap = new Map<string, TimelineItem[]>();
    for (const item of filteredItems) {
      const day = formatDate(item.epoch);
      if (!dayMap.has(day)) {
        dayMap.set(day, []);
      }
      dayMap.get(day)!.push(item);
    }

    const sortedDays = Array.from(dayMap.entries()).sort((a, b) => {
      const aDate = new Date(a[0]).getTime();
      const bDate = new Date(b[0]).getTime();
      return aDate - bDate;
    });

    for (const [day, dayItems] of sortedDays) {
      lines.push(`### ${day}`);
      lines.push('');

      let currentFile: string | null = null;
      let lastTime = '';
      let tableOpen = false;

      for (const item of dayItems) {
        const isAnchor = (
          (typeof anchorId === 'number' && item.type === 'observation' && item.data.id === anchorId) ||
          (typeof anchorId === 'string' && anchorId.startsWith('S') && item.type === 'session' && `S${item.data.id}` === anchorId)
        );

        if (item.type === 'session') {
          if (tableOpen) {
            lines.push('');
            tableOpen = false;
            currentFile = null;
            lastTime = '';
          }

          const sess = item.data as SessionSummarySearchResult;
          const title = sess.request || 'Session summary';
          const marker = isAnchor ? ' <- **ANCHOR**' : '';

          lines.push(`**🎯 #S${sess.id}** ${title} (${formatDateTime(item.epoch)})${marker}`);
          lines.push('');
        } else if (item.type === 'prompt') {
          if (tableOpen) {
            lines.push('');
            tableOpen = false;
            currentFile = null;
            lastTime = '';
          }

          const prompt = item.data as UserPromptSearchResult;
          const truncated = prompt.prompt_text.length > 100 ? prompt.prompt_text.substring(0, 100) + '...' : prompt.prompt_text;

          lines.push(`**💬 User Prompt #${prompt.prompt_number}** (${formatDateTime(item.epoch)})`);
          lines.push(`> ${truncated}`);
          lines.push('');
        } else if (item.type === 'observation') {
          const obs = item.data as ObservationSearchResult;
          const file = extractFirstFile(obs.files_modified, cwd, obs.files_read);

          if (file !== currentFile) {
            if (tableOpen) {
              lines.push('');
            }

            lines.push(`**${file}**`);
            lines.push(`| ID | Time | T | Title | Tokens |`);
            lines.push(`|----|------|---|-------|--------|`);

            currentFile = file;
            tableOpen = true;
            lastTime = '';
          }

          const icon = ModeManager.getInstance().getTypeIcon(obs.type);

          const time = formatTime(item.epoch);
          const title = singleLineTitle(obs.title || 'Untitled');
          const tokens = estimateTokens(obs.narrative);

          const showTime = time !== lastTime;
          const timeDisplay = showTime ? time : '"';
          lastTime = time;

          const anchorMarker = isAnchor ? ' <- **ANCHOR**' : '';
          lines.push(`| #${obs.id} | ${timeDisplay} | ${icon} | ${title}${anchorMarker} | ~${tokens} |`);
        }
      }

      if (tableOpen) {
        lines.push('');
      }
    }

    return lines;
  }

  private normalizeParams(args: any): any {
    const normalized: any = { ...args };

    if (normalized.filePath && !normalized.files) {
      // A single file path may itself contain commas.
      normalized.files = typeof normalized.filePath === 'string' ? [normalized.filePath] : normalized.filePath;
      delete normalized.filePath;
    }

    if (normalized.concept && !normalized.concepts) {
      normalized.concepts = normalized.concept;
      delete normalized.concept;
    }

    if (normalized.concepts && typeof normalized.concepts === 'string') {
      normalized.concepts = normalized.concepts.split(',').map((s: string) => s.trim()).filter(Boolean);
    }

    if (normalized.files && typeof normalized.files === 'string') {
      normalized.files = normalized.files.split(',').map((s: string) => s.trim()).filter(Boolean);
    }

    if (normalized.obs_type && typeof normalized.obs_type === 'string') {
      normalized.obs_type = normalized.obs_type.split(',').map((s: string) => s.trim()).filter(Boolean);
    }

    if (normalized.type && typeof normalized.type === 'string' && normalized.type.includes(',')) {
      normalized.type = normalized.type.split(',').map((s: string) => s.trim()).filter(Boolean);
    }

    const dateStart = normalized.dateStart ?? normalized.date_start ?? normalized.date_from;
    const dateEnd = normalized.dateEnd ?? normalized.date_end ?? normalized.date_to;
    if ((dateStart != null && dateStart !== '') || (dateEnd != null && dateEnd !== '')) {
      normalized.dateRange = {
        start: dateStart,
        end: dateEnd
      };
    }
    delete normalized.dateStart;
    delete normalized.dateEnd;
    delete normalized.date_start;
    delete normalized.date_end;
    delete normalized.date_from;
    delete normalized.date_to;

    // Source-scoping (#2389): normalize the platform_source filter so that a
    // codex/cursor/etc. agent only sees its own memory. Accept both the
    // camelCase API param and the snake_case column name for robustness.
    const rawPlatformSource = normalized.platformSource ?? normalized.platform_source;
    if (typeof rawPlatformSource === 'string' && rawPlatformSource.trim()) {
      normalized.platformSource = normalizePlatformSource(rawPlatformSource);
    } else {
      delete normalized.platformSource;
    }
    delete normalized.platform_source;

    return normalized;
  }

  /**
   * Reconcile the overloaded `type` param with `obs_type`.
   *
   * `type` is used two ways: as a document-category selector
   * ('observations' | 'sessions' | 'prompts'), and — per the MCP schema, which
   * documents it as "filter by observation type" — as an observation-type
   * filter. The real observation-type filter is `obs_type`, which reaches
   * SQLite as a `type IN (...)` condition with no allowlist, so custom types
   * work through it. But a custom `type` value matched no category, turned off
   * every collection, and returned nothing.
   *
   * Resolution: if every `type` value is a known category, use it as the
   * category selector (unchanged behavior). Otherwise treat it as an alias for
   * `obs_type` (merged with any explicit obs_type), and scope the search to
   * observations — the only category obs_type applies to.
   */
  private resolveTypeFilters(type: any, obs_type: any): { category: any; effectiveObsType: any } {
    const CATEGORY_TYPES = ['all', 'observations', 'sessions', 'prompts'];

    if (type == null) {
      return { category: type, effectiveObsType: obs_type };
    }

    const typeValues = Array.isArray(type) ? type : [type];
    const isCategorySelector = typeValues.length > 0 && typeValues.every(t => CATEGORY_TYPES.includes(t));

    if (isCategorySelector) {
      return { category: typeValues.includes('all') ? 'all' : type, effectiveObsType: obs_type };
    }

    const existingObsType = Array.isArray(obs_type)
      ? obs_type
      : (obs_type != null ? [obs_type] : []);
    const mergedObsType = Array.from(new Set([...existingObsType, ...typeValues]));

    return { category: 'observations', effectiveObsType: mergedObsType };
  }

  /**
   * Exact selection for a date-ordered search on the Chroma path (#4135). Chroma picks its
   * top-N candidates by relevance, so re-sorting only those by date misses the newest (or
   * oldest) matches outside them. Each requested category is unioned with its FTS5 keyword
   * matches, which SQL selects by date, then deduped by id, sorted by date and cut to `limit`.
   */
  private async mergeKeywordMatchesByDate(
    query: string,
    dateOrder: 'date_desc' | 'date_asc',
    chromaResults: SearchResults,
    observationOptions: any,
    options: any,
    scope: { searchObservations: boolean; searchSessions: boolean; searchPrompts: boolean }
  ): Promise<SearchResults> {
    const limit = options.limit || SEARCH_CONSTANTS.DEFAULT_LIMIT;
    const byDate = (a: { id: number; created_at_epoch: number }, b: { id: number; created_at_epoch: number }) =>
      dateOrder === 'date_desc'
        ? b.created_at_epoch - a.created_at_epoch || b.id - a.id
        : a.created_at_epoch - b.created_at_epoch || a.id - b.id;
    const mergeByDate = <T extends { id: number; created_at_epoch: number }>(chromaRows: T[], keywordRows: T[]): T[] => {
      const rowsById = new Map<number, T>();
      for (const row of [...chromaRows, ...keywordRows]) {
        if (!rowsById.has(row.id)) rowsById.set(row.id, row);
      }
      return Array.from(rowsById.values()).sort(byDate).slice(0, limit);
    };

    return {
      observations: scope.searchObservations
        ? mergeByDate(chromaResults.observations, this.contextReader
            ? await this.contextReader.searchObservations(query, { ...observationOptions, orderBy: dateOrder, limit })
            : this.sessionSearch.searchObservations(query, { ...observationOptions, orderBy: dateOrder, limit }))
        : chromaResults.observations,
      sessions: scope.searchSessions
        ? mergeByDate(chromaResults.sessions, this.contextReader
            ? await this.contextReader.searchSessions(query, { ...options, orderBy: dateOrder, limit })
            : this.sessionSearch.searchSessions(query, { ...options, orderBy: dateOrder, limit }))
        : chromaResults.sessions,
      prompts: scope.searchPrompts
        ? mergeByDate(chromaResults.prompts, this.contextReader
            ? await this.contextReader.searchUserPrompts(query, { ...options, orderBy: dateOrder, limit })
            : this.sessionSearch.searchUserPrompts(query, { ...options, orderBy: dateOrder, limit }))
        : chromaResults.prompts,
    };
  }

  /**
   * `recencyWindow`: per-prompt injection sets it, so a relevance search keeps
   * the default recency window (CLAUDE_MEM_SEARCH_RECENCY_DAYS) on both legs.
   * A typed search leaves it off and ranks Chroma and keyword matches of any
   * age, as the server's hybrid search does (#6539).
   */
  async search(
    args: any,
    telemetryOut?: SearchTelemetryEnvelope,
    { recencyWindow = false }: { recencyWindow?: boolean } = {}
  ): Promise<any> {
    if (args.deep !== undefined && ![true, false, 'true', 'false'].includes(args.deep)) {
      throw new AppError('deep must be true or false', 400, 'INVALID_SEARCH_REQUEST');
    }
    const state: ObservationSearchState = { status: 'not_requested' };
    const result = await this.searchMemory(args, telemetryOut, state, recencyWindow);
    if (args.deep !== true && args.deep !== 'true') return result;
    const normalized = this.normalizeParams(args);
    const { query, type, obs_type, concepts, files, format, ...options } = normalized;
    const { effectiveObsType } = this.resolveTypeFilters(type, obs_type);
    // Existing search has no session/tool predicate. Do not silently discard a
    // filter that the raw tier cannot apply with the same observation semantics.
    const unmapped = effectiveObsType || concepts?.length || files?.length
      || ['contentSessionId', 'sessionDbId', 'memorySessionId', 'session', 'toolName', 'agentId']
        .some(key => normalized[key] !== undefined);
    let raw: DeepSearchResult;
    if (typeof query !== 'string' || !query.trim()
      || Number(options.offset || 0) !== 0 || unmapped || state.status === 'not_requested') {
      raw = emptyDeepResult('not_applicable');
    } else if (state.status === 'error') raw = emptyDeepResult('observation_error');
    else if (state.status === 'success_nonempty') raw = emptyDeepResult('observations_found');
    else {
      try {
        const status = this.sessionSearch.getToolUseIndexStatus();
        const projects = projectReadKeysFor(this.sessionStore, options.project, options.projects);
        const rawOptions = { ...options, projects };
        raw = status !== 'ready' ? emptyDeepResult(status)
          : this.deepReader ? await this.deepReader.search(query, rawOptions)
            : emptyDeepResult('unsupported');
      } catch (error) {
        logger.error('SEARCH', 'Raw tool search failed', {}, error instanceof Error ? error : undefined);
        raw = emptyDeepResult('error');
      }
    }
    if (format === 'json' || format === 'export') return { ...result, ...raw };
    return { ...result, ...raw, content: [...result.content, { type: 'text', text: formatDeepSearch(raw) }] };
  }

  private async searchMemory(
    args: any,
    telemetryOut: SearchTelemetryEnvelope | undefined,
    state: ObservationSearchState,
    recencyWindow: boolean
  ): Promise<any> {
    const normalized = this.normalizeParams(args);
    const { query, type, obs_type, concepts, files, format, ...options } = normalized;
    // Gate P2-5: every key the requested projects are stored under, so a
    // checkout's search reaches what it wrote before a re-key. The SQLite paths
    // receive the same list (scopedProjects prefers `projects` over `project`).
    const projectReadKeys = projectReadKeysFor(this.sessionStore, options.project, options.projects);
    if (projectReadKeys.length > 0) {
      options.projects = projectReadKeys;
    } else {
      delete options.projects;
    }
    let observations: ObservationSearchResult[] = [];
    let sessions: SessionSummarySearchResult[] = [];
    let prompts: UserPromptSearchResult[] = [];
    let chromaFailed = false;
    let chromaSupplementStrategy: StrategySearchResult['strategy'] = 'chroma';
    let fusedWithKeywords = false;
    let chromaFailureReason: { message: string; isConnectionError: boolean } | null = null;

    // `type` historically doubles as a document-category selector
    // ('observations' | 'sessions' | 'prompts'). But it is documented in the
    // MCP schema as "filter by observation type", so callers routinely pass a
    // custom observation type (e.g. 'bugfix') here. Left as-is, such a value
    // matches none of the three categories, zeroes every collection boolean,
    // and returns nothing. Reconcile the two meanings: when `type` is not one
    // of the known categories, treat it as an alias for `obs_type` and scope
    // the search to observations, so the documented behavior actually holds.
    const { category, effectiveObsType } = this.resolveTypeFilters(type, obs_type);
    assertSearchHasQueryOrFilter({
      query,
      project: options.project ?? options.projects?.[0],
      platformSource: options.platformSource,
      dateRange: options.dateRange,
      obsType: effectiveObsType,
      concepts,
      files,
    });

    const searchObservations = isCategoryRequested(category, 'observations');
    const searchSessions = isCategoryRequested(category, 'sessions');
    const searchPrompts = isCategoryRequested(category, 'prompts');

    if (!query) {
      logger.debug('SEARCH', 'Filter-only query (no query text), using direct SQLite filtering', { enablesDateFilters: true });
      const obsOptions = { ...options, type: effectiveObsType, concepts, files };
      if (searchObservations) {
        observations = this.sessionSearch.searchObservations(undefined, obsOptions);
      }
      if (searchSessions) {
        sessions = this.sessionSearch.searchSessions(undefined, options);
      }
      if (searchPrompts) {
        prompts = this.sessionSearch.searchUserPrompts(undefined, options);
      }
    }
    // PATH 2: CHROMA SEMANTIC SEARCH (query text + Chroma available)
    else if (this.chromaSync) {
      let chromaResult: StrategySearchResult | undefined;
      logger.debug('SEARCH', 'Using ChromaDB semantic search', { typeFilter: category || 'all' });

      // HTTP pagination values can be strings. Keep enough filtered rows to
      // reach the page, and apply the offset only after supplementation/union.
      const offset = Number(options.offset || 0);
      const dateOrdered = options.orderBy === 'date_desc' || options.orderBy === 'date_asc';
      const limit = options.limit ? Number(options.limit) : (dateOrdered ? SEARCH_CONSTANTS.DEFAULT_LIMIT : undefined);
      const candidateOptions = { ...options, offset: 0, limit: limit === undefined ? undefined : offset + limit };
      // A typed relevance search ranks Chroma's matches of any age, as its
      // keyword leg does; injection keeps the window (`recencyWindow`).
      const relevanceOrder = (options.orderBy ?? 'relevance') === 'relevance';

      try {
        chromaResult = await this.orchestrator.searchChroma({
          ...candidateOptions,
          // The strategy resolves stored project keys itself; do not expand
          // the already-resolved candidateOptions.projects a second time.
          projects: normalized.projects,
          query,
          searchType: category ?? 'all',
          obsType: effectiveObsType,
          concepts,
          files,
          orderBy: options.orderBy ?? 'relevance',
          // Omitted-limit JSON searches historically expose the ranked window.
          limit: candidateOptions.limit ?? SEARCH_CONSTANTS.CHROMA_BATCH_SIZE,
          keepCandidateWindow: relevanceOrder,
          ...(relevanceOrder && !recencyWindow && { ignoreDefaultRecencyWindow: true }),
        });
      } catch (chromaError) {
        const errorObject = chromaError instanceof Error ? chromaError : new Error(String(chromaError));
        chromaFailureReason = {
          message: errorObject.message,
          isConnectionError: chromaError instanceof ChromaUnavailableError,
        };
        logger.warn('SEARCH', 'ChromaDB semantic search failed, falling back to FTS5 keyword search', {}, errorObject);
        chromaFailed = true;
      }

      // Only a failed semantic search should trigger the Chroma fallback.
      // A SQLite refill failure must escape, just as in SearchOrchestrator;
      // retrying it as a Chroma failure can silently discard semantic matches.
      if (chromaResult) {
        // Same policies as the orchestrator pipeline. Relevance order fuses Chroma's rows
        // with the keyword rows, as the server's hybrid search does. Date order refills
        // every requested category Chroma left empty, then unions keyword matches by date below.
        fusedWithKeywords = relevanceOrder;
        const candidates = {
          ...candidateOptions,
          limit: candidateOptions.limit ?? offset + SEARCH_CONSTANTS.DEFAULT_LIMIT,
          query,
          searchType: category ?? 'all',
          obsType: effectiveObsType,
          concepts,
          files,
          orderBy: options.orderBy ?? 'relevance',
        };
        const supplemented = fusedWithKeywords
          ? await this.orchestrator.fuseWithKeywordMatches(candidates, chromaResult, {
            keywordRecencyWindow: recencyWindow,
            // Omitted-limit JSON searches keep exposing Chroma's ranked window.
            keepSemanticWindow: candidateOptions.limit === undefined,
          })
          : await this.orchestrator.supplementEmptyCategories(candidates, chromaResult);
        ({ observations, sessions, prompts } = supplemented.results);
        chromaSupplementStrategy = supplemented.strategy;
      }

      if (!chromaFailed && (options.orderBy === 'date_desc' || options.orderBy === 'date_asc')) {
        ({ observations, sessions, prompts } = await this.mergeKeywordMatchesByDate(
          query,
          options.orderBy,
          { observations, sessions, prompts },
          { ...candidateOptions, type: effectiveObsType, concepts, files },
          candidateOptions,
          { searchObservations, searchSessions, searchPrompts }
        ));
      }

      if (!chromaFailed) {
        const end = limit === undefined ? undefined : offset + limit;
        observations = observations.slice(offset, end);
        sessions = sessions.slice(offset, end);
        prompts = prompts.slice(offset, end);
      }
    }
    // Read the same keyword categories when Chroma is absent or its query failed.
    if (query && (!this.chromaSync || chromaFailed)) {
      if (!this.chromaSync) {
        logger.debug('SEARCH', 'ChromaDB not initialized — falling back to FTS5 keyword search', {});
      }
      try {
        if (searchObservations) {
          observations = this.contextReader
            ? await this.contextReader.searchObservations(query, { ...options, type: effectiveObsType, concepts, files })
            : this.sessionSearch.searchObservations(query, { ...options, type: effectiveObsType, concepts, files });
        }
        if (searchSessions) {
          sessions = this.contextReader
            ? await this.contextReader.searchSessions(query, options)
            : this.sessionSearch.searchSessions(query, options);
        }
        if (searchPrompts) {
          prompts = this.contextReader
            ? await this.contextReader.searchUserPrompts(query, options)
            : this.sessionSearch.searchUserPrompts(query, options);
        }
      } catch (ftsError) {
        const errorObject = ftsError instanceof Error ? ftsError : new Error(String(ftsError));
        // The exporter can replace an existing archive only after all requested reads succeed.
        if (format === 'export') throw errorObject;
        const message = this.chromaSync ? 'FTS5 fallback search failed after a Chroma error' : 'FTS5 fallback search failed';
        logger.error('WORKER', message, {}, errorObject);
        chromaFailed = true;
      }
    }

    state.status = !searchObservations ? 'not_requested' : chromaFailed ? 'error'
      : observations.length ? 'success_nonempty' : 'success_empty';
    const totalResults = observations.length + sessions.length + prompts.length;

    // Telemetry envelope (search_performed): derive the strategy from the
    // three paths above. Enum/count values only — never the Chroma error
    // message, query text, or result content.
    if (telemetryOut) {
      let searchStrategy: SearchTelemetryEnvelope['search_strategy'];
      let fallbackReason: SearchTelemetryEnvelope['fallback_reason'];
      if (!query) {
        // PATH 1: filter-only SQLite (no query text; Chroma never consulted)
        searchStrategy = 'filter_only';
        fallbackReason = 'none';
      } else if (this.chromaSync) {
        // PATH 2: Chroma semantic search. FTS5 answers alone on a Chroma error
        // or when Chroma left every requested category empty. In relevance order
        // 'hybrid' means both legs ranked rows; in date order it means SQLite
        // refilled only the categories Chroma left empty.
        if (chromaFailed) {
          searchStrategy = 'fts';
          fallbackReason = chromaFailureReason?.isConnectionError ? 'chroma_connection' : 'chroma_error';
        } else if (chromaSupplementStrategy === 'sqlite') {
          searchStrategy = 'fts';
          fallbackReason = 'chroma_zero_results';
        } else if (chromaSupplementStrategy === 'hybrid') {
          searchStrategy = 'hybrid';
          fallbackReason = fusedWithKeywords ? 'none' : 'chroma_zero_results';
        } else {
          searchStrategy = 'chroma';
          fallbackReason = 'none';
        }
      } else {
        // PATH 3: FTS5 keyword search (Chroma not initialized)
        searchStrategy = 'fts';
        fallbackReason = 'chroma_not_initialized';
      }
      telemetryOut.result_count = totalResults;
      telemetryOut.search_strategy = searchStrategy;
      telemetryOut.chroma_available = this.chromaSync !== null && !chromaFailed;
      telemetryOut.fallback_reason = fallbackReason;
    }

    if (format === 'json' || format === 'export') {
      return {
        observations,
        sessions,
        prompts,
        totalResults,
        query: query || ''
      };
    }

    if (totalResults === 0) {
      if (chromaFailureReason !== null) {
        return {
          content: [{
            type: 'text' as const,
            text: ResultFormatter.formatChromaFailureMessage(chromaFailureReason)
          }]
        };
      }
      return {
        content: [{
          type: 'text' as const,
          text: `No results found matching "${query}"`
        }]
      };
    }

    interface CombinedResult {
      type: 'observation' | 'session' | 'prompt';
      data: any;
      epoch: number;
      created_at: string;
    }

    const allResults: CombinedResult[] = [
      ...observations.map(obs => ({
        type: 'observation' as const,
        data: obs,
        epoch: obs.created_at_epoch,
        created_at: obs.created_at
      })),
      ...sessions.map(sess => ({
        type: 'session' as const,
        data: sess,
        epoch: sess.created_at_epoch,
        created_at: sess.created_at
      })),
      ...prompts.map(prompt => ({
        type: 'prompt' as const,
        data: prompt,
        epoch: prompt.created_at_epoch,
        created_at: prompt.created_at
      }))
    ];

    if (options.orderBy === 'date_desc') {
      allResults.sort((a, b) => b.epoch - a.epoch);
    } else if (options.orderBy === 'date_asc') {
      allResults.sort((a, b) => a.epoch - b.epoch);
    }

    const limitedResults = allResults.slice(0, options.limit || 20);

    const cwd = process.cwd();
    const resultsByDate = groupByDate(
      limitedResults,
      item => item.created_at,
      // Date orders render their day groups in that order; relevance-ordered results keep the
      // order in which each day's first (most relevant) result appears.
      { order: options.orderBy === 'date_desc' ? 'desc' : options.orderBy === 'date_asc' ? 'asc' : 'first-seen' }
    );

    const lines: string[] = [];
    lines.push(`Found ${totalResults} result(s) matching "${query}" (${observations.length} obs, ${sessions.length} sessions, ${prompts.length} prompts)`);
    lines.push('');

    for (const [day, dayResults] of resultsByDate) {
      lines.push(`### ${day}`);
      lines.push('');

      const resultsByFile = new Map<string, CombinedResult[]>();
      for (const result of dayResults) {
        let file = 'General';
        if (result.type === 'observation') {
          file = extractFirstFile(result.data.files_modified, cwd, result.data.files_read);
        }
        if (!resultsByFile.has(file)) {
          resultsByFile.set(file, []);
        }
        resultsByFile.get(file)!.push(result);
      }

      for (const [file, fileResults] of resultsByFile) {
        lines.push(`**${file}**`);
        lines.push(this.formatter.formatSearchTableHeader());

        let lastTime = '';
        for (const result of fileResults) {
          if (result.type === 'observation') {
            const formatted = this.formatter.formatObservationSearchRow(result.data as ObservationSearchResult, lastTime);
            lines.push(formatted.row);
            lastTime = formatted.time;
          } else if (result.type === 'session') {
            const formatted = this.formatter.formatSessionSearchRow(result.data as SessionSummarySearchResult, lastTime);
            lines.push(formatted.row);
            lastTime = formatted.time;
          } else {
            const formatted = this.formatter.formatUserPromptSearchRow(result.data as UserPromptSearchResult, lastTime);
            lines.push(formatted.row);
            lastTime = formatted.time;
          }
        }

        lines.push('');
      }
    }

    return {
      content: [{
        type: 'text' as const,
        text: lines.join('\n')
      }]
    };
  }

  private parseNumericAnchor(anchor: unknown): number | null {
    if (typeof anchor === 'number') return anchor;
    // Search output names observations "#123" (sessions "#S5", accepted below).
    if (typeof anchor === 'string' && /^#?\d+$/.test(anchor.trim())) {
      return Number(anchor.trim().replace(/^#/, ''));
    }
    return null;
  }

  async timeline(args: any): Promise<any> {
    const normalized = this.normalizeParams(args);
    const { anchor, query, depth_before, depth_after, project, projects, platformSource } = normalized;
    const readKeys = projectReadKeysFor(this.sessionStore, project, projects);
    const scope = { project, projects: readKeys, platformSource };
    // A record anchor supplies the default project for its surrounding context.
    // Explicit scopes win; timestamp-only anchors have no project to infer.
    const readKeysForAnchor = (anchorProject: string): string[] => readKeys.length > 0
      ? readKeys
      : projectReadKeysFor(this.sessionStore, anchorProject, undefined);
    // HTTP query strings and MCP numbers must describe whole, bounded SQL LIMITs.
    const parseDepth = (value: unknown): number => value == null ? 10
      : typeof value === 'number' || (typeof value === 'string' && value.trim() !== '')
        ? Number(value) : NaN;
    const depthBefore = parseDepth(depth_before);
    const depthAfter = parseDepth(depth_after);
    const anchorAsNumber = this.parseNumericAnchor(anchor);
    const cwd = process.cwd();

    if (![depthBefore, depthAfter].every(depth => Number.isSafeInteger(depth) && depth >= 0)) {
      return { content: [{ type: 'text' as const, text: 'Invalid timeline depth: depth_before and depth_after must be non-negative safe integers' }], isError: true };
    }
    // A safe integer is still unbounded: depth is the one dimension on this
    // route with no ceiling, and each unit is a row fetched and rendered. Left
    // open, `depth_before=100000` walks the whole project history in one
    // request. The progressive search path already caps this at 3; keep the
    // direct route generous but finite.
    if (depthBefore > TIMELINE_MAX_DEPTH || depthAfter > TIMELINE_MAX_DEPTH) {
      return { content: [{ type: 'text' as const, text: `Invalid timeline depth: depth_before and depth_after must be at most ${TIMELINE_MAX_DEPTH}` }], isError: true };
    }
    if (anchorAsNumber !== null && (!Number.isSafeInteger(anchorAsNumber) || anchorAsNumber <= 0)) {
      return { content: [{ type: 'text' as const, text: 'Invalid observation anchor: must be a positive safe integer' }], isError: true };
    }

    if (!anchor && !query) {
      return {
        content: [{
          type: 'text' as const,
          text: 'Error: Must provide either "anchor" or "query" parameter'
        }],
        isError: true
      };
    }

    if (anchor && query) {
      return {
        content: [{
          type: 'text' as const,
          text: 'Error: Cannot provide both "anchor" and "query" parameters. Use one or the other.'
        }],
        isError: true
      };
    }

    let anchorId: string | number;
    let anchorEpoch: number;
    let timelineData: any;

    if (query) {
      let results: ObservationSearchResult[] = [];

      if (this.chromaSync) {
        logger.debug('SEARCH', 'Using hybrid semantic search for timeline query', {});
        try {
          results = await this.searchChromaForTimeline(query, project, platformSource, projects);
        } catch (chromaError) {
          const errorObject = chromaError instanceof Error ? chromaError : new Error(String(chromaError));
          logger.error('WORKER', 'Chroma search failed for timeline, continuing without semantic results', {}, errorObject);
        }
      }

      if (results.length === 0) {
        try {
          const ftsResults = this.sessionSearch.searchObservations(query, { ...scope, limit: 1 });
          if (ftsResults.length > 0) {
            results = ftsResults;
          }
        } catch (ftsError) {
          logger.warn('SEARCH', 'FTS fallback failed for timeline', {}, ftsError instanceof Error ? ftsError : undefined);
        }
      }

      if (results.length === 0) {
        return {
          content: [{
            type: 'text' as const,
            text: `No observations found matching "${query}". Try a different search query.`
          }]
        };
      }

      const topResult = results[0];
      anchorId = topResult.id;
      anchorEpoch = topResult.created_at_epoch;
      logger.debug('SEARCH', 'Query mode: Using observation as timeline anchor', { observationId: topResult.id });
      timelineData = this.sessionStore.getTimelineAroundObservation(topResult.id, topResult.created_at_epoch, depthBefore, depthAfter, project, platformSource, readKeysForAnchor(topResult.project));
    }
    // MODE 2: Anchor-based timeline
    else if (anchorAsNumber !== null) {
      const obs = this.sessionStore.getObservationsByIds([anchorAsNumber], { ...scope, limit: 1 })[0] ?? null;
      if (!obs) {
        return {
          content: [{
            type: 'text' as const,
            text: `Observation #${anchorAsNumber} not found`
          }],
          isError: true
        };
      }
      anchorId = anchorAsNumber;
      anchorEpoch = obs.created_at_epoch;
      timelineData = this.sessionStore.getTimelineAroundObservation(anchorAsNumber, anchorEpoch, depthBefore, depthAfter, project, platformSource, readKeysForAnchor(obs.project));
    } else if (typeof anchor === 'string') {
      if (anchor.startsWith('S') || anchor.startsWith('#S')) {
        const sessionMatch = /^#?S(\d+)$/.exec(anchor);
        const sessionNum = sessionMatch ? Number(sessionMatch[1]) : NaN;
        if (!Number.isSafeInteger(sessionNum) || sessionNum <= 0) {
          return { content: [{ type: 'text' as const, text: 'Invalid session anchor: must be S followed by a positive safe integer' }], isError: true };
        }
        const sessions = this.sessionStore.getSessionSummariesByIds([sessionNum], scope);
        if (sessions.length === 0) {
          return {
            content: [{
              type: 'text' as const,
              text: `Session #${sessionNum} not found`
            }],
            isError: true
          };
        }
        anchorEpoch = sessions[0].created_at_epoch;
        anchorId = `S${sessionNum}`;
        timelineData = this.sessionStore.getTimelineAroundTimestamp(anchorEpoch, depthBefore, depthAfter, project, platformSource, readKeysForAnchor(sessions[0].project));
      } else {
        const date = new Date(anchor);
        if (isNaN(date.getTime())) {
          return {
            content: [{
              type: 'text' as const,
              text: `Invalid timestamp: ${anchor}`
            }],
            isError: true
          };
        }
        anchorEpoch = date.getTime();
        anchorId = anchor;
        timelineData = this.sessionStore.getTimelineAroundTimestamp(anchorEpoch, depthBefore, depthAfter, project, platformSource, readKeys);
      }
    } else {
      return {
        content: [{
          type: 'text' as const,
          text: 'Invalid anchor: must be observation ID (number), session ID (e.g., "S123"), or ISO timestamp'
        }],
        isError: true
      };
    }

    const items: TimelineItem[] = [
      ...(timelineData.observations || []).map((obs: any) => ({ type: 'observation' as const, data: obs, epoch: obs.created_at_epoch })),
      ...(timelineData.sessions || []).map((sess: any) => ({ type: 'session' as const, data: sess, epoch: sess.created_at_epoch })),
      ...(timelineData.prompts || []).map((prompt: any) => ({ type: 'prompt' as const, data: prompt, epoch: prompt.created_at_epoch }))
    ];
    items.sort((a, b) => a.epoch - b.epoch);
    const filteredItems = this.timelineService.filterByDepth(items, anchorId, anchorEpoch, depthBefore, depthAfter);

    if (!filteredItems || filteredItems.length === 0) {
      return {
        content: [{
          type: 'text' as const,
          text: query
            ? `Found observation matching "${query}", but no timeline context available (${depthBefore} records before, ${depthAfter} records after).`
            : `No context found around anchor (${depthBefore} records before, ${depthAfter} records after)`
        }]
      };
    }

    const lines: string[] = [];

    if (query) {
      const anchorObs = filteredItems.find(item => item.type === 'observation' && item.data.id === anchorId);
      const anchorTitle = anchorObs && anchorObs.type === 'observation' ? ((anchorObs.data as ObservationSearchResult).title || 'Untitled') : 'Unknown';
      lines.push(`# Timeline for query: "${query}"`);
      lines.push(`**Anchor:** Observation #${anchorId} - ${anchorTitle}`);
    } else {
      lines.push(`# Timeline around anchor: ${anchorId}`);
    }

    lines.push(`**Window:** ${depthBefore} records before -> ${depthAfter} records after | **Items:** ${filteredItems?.length ?? 0}`);
    lines.push('');

    lines.push(...this.renderTimeline(filteredItems, anchorId, cwd));

    return {
      content: [{
        type: 'text' as const,
        text: lines.join('\n')
      }]
    };
  }

  async searchObservations(args: any): Promise<any> {
    const normalized = this.normalizeParams(args);
    const { query, ...options } = normalized;
    const limit = options.limit || 20;
    let results: ObservationSearchResult[] = [];

    if (query && this.chromaSync) {
      // Use the same filtered candidate window and final page boundary as the
      // unified search. This endpoint's `type` denotes an observation type.
      const retrieved = await this.searchMemory({
        ...options,
        query,
        type: 'observations',
        obs_type: options.type,
        format: 'json',
        limit,
      }, undefined, { status: 'not_requested' }, false);
      results = retrieved.observations;
    } else {
      try {
        results = this.sessionSearch.searchObservations(query, { ...options, limit });
      } catch (ftsError) {
        logger.warn('SEARCH', 'FTS fallback failed for observations', {}, ftsError instanceof Error ? ftsError : undefined);
      }
    }

    if (results.length === 0) {
      return {
        content: [{
          type: 'text' as const,
          text: `No observations found matching "${query}"`
        }]
      };
    }

    // Relevance-ordered results (FTS/Chroma): only add day headers, never
    // reorder into chronological groups, or the most relevant match could
    // print below a less relevant but more recent one.
    const resultsByDate = groupByDate(results, obs => obs.created_at, { order: 'first-seen' });

    const lines: string[] = [];
    lines.push(`Found ${results.length} observation(s) matching "${query}"`);
    lines.push('');

    for (const [day, dayResults] of resultsByDate) {
      lines.push(`### ${day}`);
      lines.push('');
      lines.push(this.formatter.formatTableHeader());
      for (const obs of dayResults) {
        lines.push(this.formatter.formatObservationIndex(obs, 0));
      }
      lines.push('');
    }

    return {
      content: [{
        type: 'text' as const,
        text: lines.join('\n')
      }]
    };
  }

  async getRecentContext(args: any): Promise<any> {
    const normalized = this.normalizeParams(args);
    const project = normalized.project || getProjectContext(process.cwd()).primary;
    const parsedLimit = parseInt(String(normalized.limit ?? '3'), 10);
    const limit = parsedLimit > 0 ? parsedLimit : 3;
    const { platformSource } = normalized;

    const sessions = this.sessionStore.getRecentSessionsWithStatus(project, limit, platformSource);

    if (sessions.length === 0) {
      return {
        content: [{
          type: 'text' as const,
          text: `# Recent Session Context\n\nNo previous sessions found for project "${project}".`
        }]
      };
    }

    const lines: string[] = [];
    lines.push('# Recent Session Context');
    lines.push('');
    lines.push(`Showing last ${sessions.length} session(s) for **${project}**:`);
    lines.push('');

    for (const session of sessions) {
      if (!session.memory_session_id) continue;

      lines.push('---');
      lines.push('');

      if (session.has_summary) {
        const summary = this.sessionStore.getSummaryForSession(session.memory_session_id, platformSource);
        if (summary) {
          const promptLabel = summary.prompt_number ? ` (Prompt #${summary.prompt_number})` : '';
          lines.push(`**Summary${promptLabel}**`);
          lines.push('');

          if (summary.request) lines.push(`**Request:** ${summary.request}`);
          if (summary.completed) lines.push(`**Completed:** ${summary.completed}`);
          if (summary.learned) lines.push(`**Learned:** ${summary.learned}`);
          if (summary.next_steps) lines.push(`**Next Steps:** ${summary.next_steps}`);

          if (summary.files_read) {
            try {
              const filesRead = JSON.parse(summary.files_read);
              if (Array.isArray(filesRead) && filesRead.length > 0) {
                lines.push(`**Files Read:** ${filesRead.join(', ')}`);
              }
            } catch (error) {
              const errorObject = error instanceof Error ? error : new Error(String(error));
              logger.debug('WORKER', 'files_read is plain string, using as-is', {}, errorObject);
              if (summary.files_read.trim()) {
                lines.push(`**Files Read:** ${summary.files_read}`);
              }
            }
          }

          if (summary.files_edited) {
            try {
              const filesEdited = JSON.parse(summary.files_edited);
              if (Array.isArray(filesEdited) && filesEdited.length > 0) {
                lines.push(`**Files Edited:** ${filesEdited.join(', ')}`);
              }
            } catch (error) {
              const errorObject = error instanceof Error ? error : new Error(String(error));
              logger.debug('WORKER', 'files_edited is plain string, using as-is', {}, errorObject);
              if (summary.files_edited.trim()) {
                lines.push(`**Files Edited:** ${summary.files_edited}`);
              }
            }
          }

          const date = formatSystemLocaleDateTime(summary.created_at);
          lines.push(`**Date:** ${date}`);
        }
      } else if (session.status === 'active') {
        lines.push('**In Progress**');
        lines.push('');

        if (session.user_prompt) {
          lines.push(`**Request:** ${session.user_prompt}`);
        }

        const observations = this.sessionStore.getObservationsForSession(session.memory_session_id, platformSource);
        if (observations.length > 0) {
          lines.push('');
          lines.push(`**Observations (${observations.length}):**`);
          for (const obs of observations) {
            lines.push(`- ${obs.title}`);
          }
        } else {
          lines.push('');
          lines.push('*No observations yet*');
        }

        lines.push('');
        lines.push('**Status:** Active - summary pending');

        const date = formatSystemLocaleDateTime(session.started_at);
        lines.push(`**Date:** ${date}`);
      } else {
        lines.push(`**${session.status.charAt(0).toUpperCase() + session.status.slice(1)}**`);
        lines.push('');

        if (session.user_prompt) {
          lines.push(`**Request:** ${session.user_prompt}`);
        }

        lines.push('');
        lines.push(`**Status:** ${session.status} - no summary available`);

        const date = formatSystemLocaleDateTime(session.started_at);
        lines.push(`**Date:** ${date}`);
      }

      lines.push('');
    }

    return {
      content: [{
        type: 'text' as const,
        text: lines.join('\n')
      }]
    };
  }

  async getTimelineByQuery(args: any): Promise<any> {
    const normalized = this.normalizeParams(args);
    const { query, mode, limit = 5, project, projects, platformSource } = normalized;

    if (mode !== 'interactive') {
      return this.timeline(args);
    }

    let results: ObservationSearchResult[] = [];

    if (this.chromaSync) {
      logger.debug('SEARCH', 'Using hybrid semantic search for timeline query', {});
      try {
        results = await this.hybridSemanticHydrate(query, 'observation', project, platformSource, (ids, readKeys) =>
          this.sessionStore.getObservationsByIds(ids, { orderBy: 'relevance', project, projects: readKeys, platformSource }),
          projects,
        );
        results = results.slice(0, limit);
      } catch (chromaError) {
        const errorObject = chromaError instanceof Error ? chromaError : new Error(String(chromaError));
        logger.error('WORKER', 'Chroma search failed for timeline by query, falling back to FTS', {}, errorObject);
      }
    }

    if (results.length === 0) {
      try {
        const readKeys = projectReadKeysFor(this.sessionStore, project, projects);
        const ftsResults = this.sessionSearch.searchObservations(query, { project, projects: readKeys, platformSource, limit });
        if (ftsResults.length > 0) {
          results = ftsResults;
        }
      } catch (ftsError) {
        logger.warn('SEARCH', 'FTS fallback failed for timeline by query', {}, ftsError instanceof Error ? ftsError : undefined);
      }
    }

    if (results.length === 0) {
      return {
        content: [{
          type: 'text' as const,
          text: `No observations found matching "${query}". Try a different search query.`
        }]
      };
    }

    const lines: string[] = [];
    lines.push(`# Timeline Anchor Search Results`);
    lines.push('');
    lines.push(`Found ${results.length} observation(s) matching "${query}"`);
    lines.push('');
    lines.push(`To get timeline context around any of these observations, use the \`get_context_timeline\` tool with the observation ID as the anchor.`);
    lines.push('');
    lines.push(`**Top ${results.length} matches:**`);
    lines.push('');

    for (let i = 0; i < results.length; i++) {
      const obs = results[i];
      const title = obs.title || `Observation #${obs.id}`;
      const date = formatSystemLocaleDateTime(obs.created_at_epoch);
      const type = obs.type ? `[${obs.type}]` : '';

      lines.push(`${i + 1}. **${type} ${title}**`);
      lines.push(`   - ID: ${obs.id}`);
      lines.push(`   - Date: ${date}`);
      if (obs.subtitle) {
        lines.push(`   - ${obs.subtitle}`);
      }
      lines.push('');
    }

    return {
      content: [{
        type: 'text' as const,
        text: lines.join('\n')
      }]
    };
  }
}