Skip to content

Implement Core Repository Retrieval Engine for Semantic and Literal File Matching and Bounded Reading #2797

Closed

Description

@propr-dev

Context

The ProPR planner already retrieves repository files and matches prompts using relevance algorithms and indexed summaries (findRelevantFiles, scoreSemanticRelevance, file_summaries, directory_summaries), while git operations inspect commits and worktrees. However, there is no shared service that surfaces repository code search and file reading as clean, standalone primitives. Today, external clients (such as MCP agents) have no mechanism to read repository code or search files without pulling the entire repository locally. This task implements a unified repository retrieval service in @propr/core that reuses the planner's indexing and relevance engine for semantic search, provides literal git grep across the repository tree at any ref, and supports bounded file reading directly from git.

Requirements

  1. Create Repository Retrieval Service: Create packages/core/src/services/repositoryRetrievalService.ts exporting typed options and result interfaces for search and file reading.
  2. Implement searchRepositoryFiles:
    • Accept parameters: repository, query, mode ('semantic' | 'literal', default 'semantic'), branch / ref, path prefix, caseSensitive, offset, and limit.
    • Semantic Mode:
      • Inspect indexing status in the repositories table for the specified branch (indexing_status, last_indexed_at, last_indexed_hash).
      • Delegate to findRelevantFiles using useSummaryScoring: true and the default agent from AgentRegistry.
      • Degrade gracefully if the repository is not yet indexed or if indexing is in progress by falling back to keyword and path scoring, returning an explicit freshness caveat in freshness.caveat.
      • Return ranked file paths with relevance scores, matching reasons (semantic, path-match, git-history), and pagination metadata (offset, limit, nextOffset, totalMatches).
    • Literal Mode:
      • Resolve the repository's local clone path via ensureRepoCloned / resolveRepositoryClonePath.
      • Use createHooklessGit(repoPath) to execute git.raw(['grep', '-n', '-I', ...]) against the target ref.
      • Parse grep output into matching paths, match counts, and line matches.
      • Return matching file paths and match counts without loading full file bodies, with pagination metadata.
  3. Implement readRepositoryFileContent:
    • Accept parameters: repository, path, ref / branch, startLine, endLine, maxLines, maxBytes.
    • Prevent directory traversal by rejecting paths containing .., leading /, backslashes \, or null bytes \0.
    • Fetch the exact file content from the git object database at ref:path using createHooklessGit(repoPath).show().
    • Detect binary files (\0 byte) and throw a descriptive error with status 400.
    • Slice lines between startLine and endLine, bounded by maxLines (default 800) and maxBytes (default 120,000).
    • Return file content, line counts, total bytes, and truncation status.
  4. Public Core Exports: Export the service functions and types in packages/core/src/index.ts.
  5. Unit Test Suite: Implement unit tests in packages/core/test/repositoryRetrievalService.test.ts verifying semantic search, literal grep parsing, chunked reading, and error conditions.

Implementation Specification

  • File: packages/core/src/services/repositoryRetrievalService.ts (new file)
  • File: packages/core/src/index.ts (add export)
  • File: packages/core/test/repositoryRetrievalService.test.ts (new file)

Acceptance Criteria

  • searchRepositoryFiles in semantic mode returns files scored and ranked by relevance with freshness metadata.
  • If the repository is not indexed or indexing is incomplete, semantic search returns results via fallback heuristics with an explicit caveat explaining index staleness.
  • searchRepositoryFiles in literal mode executes git grep at the requested ref, correctly filters by path prefix, handles case sensitivity, and returns empty results (not an error) when no matches are found.
  • readRepositoryFileContent reads lines accurately within startLine/endLine, caps output at maxLines and maxBytes, sets truncated: true when truncated, and rejects traversal or binary files with clear errors.
  • Unit tests in packages/core/test/repositoryRetrievalService.test.ts pass cleanly.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    This implementation introduces a centralized repository retrieval service within @propr/core that directly exposes the existing planner relevance pipeline (findRelevantFiles) and git tree inspection (createHooklessGit). Rather than duplicating relevance logic or spawning ad-hoc processes, we consolidate search and read operations into reusable domain primitives. For semantic search, we query database indexing metadata and invoke findRelevantFiles with AI-generated summary scoring, degrading gracefully to keyword and git-history scoring when the repository index is pending or stale. For literal search, we execute git grep against the repository tree at a specific ref, which bypasses the index entirely and guarantees commit-level freshness without requiring a checked-out worktree. For file reading, we use git show to stream bounded line and byte slices directly from the object database, enforcing path sanitization and binary detection.

    File: packages/core/src/services/repositoryRetrievalService.ts (new file)

    Why this file: This new service module centralizes all repository code retrieval logic for both semantic and literal modes. It bridges findRelevantFiles, database index records, and git object inspection so that both backend planners and external MCP tools can search and read repository files through consistent, bounded interfaces.

    import path from 'node:path';
    import { db } from '../db/connection.js';
    import { createHooklessGit } from '../git/hooklessGit.js';
    import { ensureRepoCloned } from '../git/repoManager.js';
    import { resolveRepositoryClonePath } from '../git/repositoryPaths.js';
    import { getAgentRegistry } from '../agents/AgentRegistry.js';
    import { findRelevantFiles } from './relevanceService.js';
    import { getGitHubInstallationToken } from '../auth/githubAuth.js';
    import logger from '../utils/logger.js';
    
    // Base directory where cloned repositories are maintained locally by ProPR
    const CLONES_BASE_PATH = process.env.GIT_CLONES_BASE_PATH || '/tmp/git-processor/clones';
    
    export interface SearchRepositoryFilesOptions {
      repository: string;
      query: string;
      mode?: 'semantic' | 'literal';
      branch?: string;
      ref?: string;
      path?: string;
      caseSensitive?: boolean;
      offset?: number;
      limit?: number;
      authToken?: string;
      correlationId?: string;
    }
    
    export interface SearchRepositoryFilesResult {
      repository: string;
      ref: string;
      mode: 'semantic' | 'literal';
      freshness?: {
        state: string;
        indexedAt: string | null;
        revision: string | null;
        caveat?: string;
      };
      files: Array<{
        path: string;
        score?: number;
        reason?: string;
        matchCount?: number;
        lineMatches?: Array<{ line: number; text: string }>;
      }>;
      totalMatches: number;
      offset: number;
      limit: number;
      nextOffset: number | null;
    }
    
    export interface ReadRepositoryFileOptions {
      repository: string;
      path: string;
      ref?: string;
      branch?: string;
      startLine?: number;
      endLine?: number;
      maxLines?: number;
      maxBytes?: number;
      authToken?: string;
    }
    
    export interface ReadRepositoryFileResult {
      repository: string;
      ref: string;
      path: string;
      startLine: number;
      endLine: number;
      totalLines: number;
      totalBytes: number;
      content: string;
      truncated: boolean;
    }
    
    /**
     * Resolves the local clone path for a given repository. If not yet cloned,
     * calls ensureRepoCloned using the provided or resolved installation token.
     */
    async function resolveRepoDirectory(repository: string, authToken?: string, baseBranch?: string): Promise<string> {
      const [owner, repoName] = repository.split('/');
      if (!owner || !repoName) {
        // Validate repository handle format to prevent path traversal and ensure safe directory resolution
        throw new Error('Invalid repository format: Expected "owner/repo"');
      }
    
      const localRepoPath = resolveRepositoryClonePath(CLONES_BASE_PATH, owner, repoName);
      
      // Resolve effective auth token: prefer caller-provided token, falling back to GitHub App installation token.
      // This trade-off allows both user-scoped grants and server-level credentials to authenticate without hardcoding.
      let effectiveToken = authToken;
      if (!effectiveToken) {
        try {
          effectiveToken = await getGitHubInstallationToken();
        } catch {
          // Non-fatal if installation token resolution fails and repo is already on disk
        }
      }
    
      // Ensure repository is cloned and updated on disk using ensureRepoCloned.
      // If updating the clone fails due to transient network issues, fall back to the existing clone on disk to maintain offline availability.
      if (effectiveToken) {
        try {
          const repoUrl = `https://github.com/${owner}/${repoName}.git`;
          return await ensureRepoCloned({
            repoUrl,
            owner,
            repoName,
            authToken: effectiveToken,
            baseBranch,
          });
        } catch (cloneError) {
          logger.warn({ error: (cloneError as Error).message, repository }, 'Failed to fetch latest changes; using existing clone if present');
        }
      }
    
      return localRepoPath;
    }
    
    /**
     * Searches repository files using either semantic index relevance or literal git grep.
     */
    export async function searchRepositoryFiles(options: SearchRepositoryFilesOptions): Promise<SearchRepositoryFilesResult> {
      const {
        repository,
        query,
        mode = 'semantic',
        branch,
        ref,
        path: pathPrefix,
        caseSensitive = false,
        offset = 0,
        limit = 20,
        authToken,
        correlationId,
      } = options;
    
      const targetRef = ref || branch || 'HEAD';
      const targetBranch = branch || ref || 'HEAD';
      const repoPath = await resolveRepoDirectory(repository, authToken, targetBranch);
    
      if (mode === 'literal') {
        // Literal grep search runs directly on the git tree at the requested ref via createHooklessGit.
        // We chose this over checking out a worktree or pulling files into memory to minimize disk I/O and support concurrent reads at different commits.
        const git = createHooklessGit(repoPath);
        const grepArgs = ['grep', '-n', '-I'];
        if (!caseSensitive) grepArgs.push('-i');
        grepArgs.push('-F', '-e', query, targetRef);
        if (pathPrefix) {
          grepArgs.push('--', pathPrefix);
        }
    
        let grepOutput = '';
        try {
          grepOutput = await git.raw(grepArgs);
        } catch (error) {
          // Simple-git throws on non-zero exit codes. Git grep exits with code 1 when no matches are found,
          // which is a normal query result rather than a system failure. Catch and return an empty match set.
          const msg = error instanceof Error ? error.message : String(error);
          if (!msg.includes('exit code 1') && !msg.includes('Status 1')) {
            throw error;
          }
        }
    
        // Parse git grep output lines formatted as "<ref>:<path>:<line>:<text>"
        const fileMap = new Map<string, { matchCount: number; lineMatches: Array<{ line: number; text: string }> }>();
        if (grepOutput.trim()) {
          const lines = grepOutput.split('\n');
          for (const rawLine of lines) {
            if (!rawLine.trim()) continue;
            let remainder = rawLine;
            if (remainder.startsWith(`${targetRef}:`)) {
              remainder = remainder.slice(targetRef.length + 1);
            }
            const firstColon = remainder.indexOf(':');
            if (firstColon === -1) continue;
            const filePath = remainder.slice(0, firstColon);
            const secondColon = remainder.indexOf(':', firstColon + 1);
            if (secondColon === -1) continue;
            const lineNumber = parseInt(remainder.slice(firstColon + 1, secondColon), 10);
            const matchText = remainder.slice(secondColon + 1).slice(0, 500);
    
            if (!fileMap.has(filePath)) {
              fileMap.set(filePath, { matchCount: 0, lineMatches: [] });
            }
            const entry = fileMap.get(filePath)!;
            entry.matchCount++;
            // Retain up to 5 preview lines per file to prevent response payload bloat over the MCP transport while giving the agent enough context to confirm relevance before issuing a read.
            if (entry.lineMatches.length < 5) {
              entry.lineMatches.push({ line: lineNumber, text: matchText });
            }
          }
        }
    
        const allMatches = Array.from(fileMap.entries()).map(([filePath, data]) => ({
          path: filePath,
          matchCount: data.matchCount,
          lineMatches: data.lineMatches,
        }));
    
        const totalMatches = allMatches.length;
        const pagedFiles = allMatches.slice(offset, offset + limit);
        const nextOffset = offset + limit < totalMatches ? offset + limit : null;
    
        return {
          repository,
          ref: targetRef,
          mode: 'literal',
          files: pagedFiles,
          totalMatches,
          offset,
          limit,
          nextOffset,
        };
      }
    
      // --- Semantic Search Mode ---
      // Query database indexing metadata from the repositories table. This lets the caller know if the semantic results reflect a fresh index or if they should expect degraded heuristic results.
      let repoRecord = null;
      try {
        if (db) {
          repoRecord = await db('repositories').where({ full_name: repository, branch: targetBranch }).first();
          if (!repoRecord && targetBranch !== 'HEAD') {
            repoRecord = await db('repositories').where({ full_name: repository, branch: 'HEAD' }).first();
          }
        }
      } catch (dbError) {
        logger.warn({ error: (dbError as Error).message }, 'Failed to query repository indexing status from database');
      }
    
      const indexingStatus = repoRecord?.indexing_status || 'not_indexed';
      const indexedAt = repoRecord?.last_indexed_at ? new Date(repoRecord.last_indexed_at).toISOString() : null;
      const revision = repoRecord?.last_indexed_hash || null;
      let caveat: string | undefined;
    
      // Provide explicit caveats if the index is missing, stale, or in progress. This informs the agent that results may be incomplete without throwing an outright error, allowing graceful degradation.
      if (indexingStatus !== 'completed') {
        caveat = `Repository index status is "${indexingStatus}". Results are generated using heuristic keyword/path scoring and may be incomplete.`;
      }
    
      // Resolve the configured agent for summary-based semantic scoring. We fall back gracefully if the registry is uninitialized so search remains operational even in degraded worker states.
      let agent = undefined;
      try {
        const registry = getAgentRegistry();
        await registry.ensureInitialized();
        agent = registry.getDefaultAgent();
      } catch {
        // Graceful fallback: continue relevance analysis without agent summary scoring
      }
    
      // Reuse the planner's findRelevantFiles pipeline. We disable LLM keyword extraction (useLLMKeywords: false) to prioritize sub-second interactive search latency over exhaustive semantic expansion.
      const relevanceResult = await findRelevantFiles(repoPath, query, {
        repoName: repository,
        branch: targetBranch,
        useSummaryScoring: !!agent,
        agent,
        useLLMKeywords: false,
        correlationId,
      });
    
      let matchedFiles = relevanceResult.files;
      if (pathPrefix) {
        matchedFiles = matchedFiles.filter(f => f.path.startsWith(pathPrefix));
      }
    
      const totalMatches = matchedFiles.length;
      const pagedFiles = matchedFiles.slice(offset, offset + limit).map(f => ({
        path: f.path,
        score: Math.round(f.score),
        reason: f.reason,
      }));
      const nextOffset = offset + limit < totalMatches ? offset + limit : null;
    
      return {
        repository,
        ref: targetRef,
        mode: 'semantic',
        freshness: {
          state: indexingStatus,
          indexedAt,
          revision,
          caveat,
        },
        files: pagedFiles,
        totalMatches,
        offset,
        limit,
        nextOffset,
      };
    }
    
    /**
     * Reads bounded line chunks from a repository file directly from the git tree at the specified ref.
     */
    export async function readRepositoryFileContent(options: ReadRepositoryFileOptions): Promise<ReadRepositoryFileResult> {
      const {
        repository,
        path: filePath,
        ref,
        branch,
        startLine = 1,
        endLine,
        maxLines = 800,
        maxBytes = 120_000,
        authToken,
      } = options;
    
      // Enforce repository-relative path safety early to fail fast on directory traversal attempts before invoking git commands. Traversal attacks or absolute paths would break out of the repository boundary.
      if (
        !filePath ||
        typeof filePath !== 'string' ||
        filePath.startsWith('/') ||
        filePath.split('/').includes('..') ||
        filePath.includes('\\') ||
        filePath.includes('\0')
      ) {
        const err = new Error('Invalid repository path: Path must be a non-empty, repository-relative path without traversal.');
        (err as any).code = 'INVALID_PATH';
        (err as any).status = 400;
        throw err;
      }
    
      const targetRef = ref || branch || 'HEAD';
      const repoPath = await resolveRepoDirectory(repository, authToken, branch || ref);
      const git = createHooklessGit(repoPath);
    
      let rawContent: string;
      try {
        // Read file directly from git object storage using 'git show' without worktree checkout. This prevents dirtying the working tree or risking concurrent write conflicts across tasks.
        rawContent = await git.show([`${targetRef}:${filePath}`]);
      } catch (error) {
        const msg = error instanceof Error ? error.message : String(error);
        if (
          msg.includes('does not exist') ||
          msg.includes('fatal: path') ||
          msg.includes('exists on disk, but not in')
        ) {
          const notFound = new Error(`File not found: ${filePath} at ref ${targetRef}`);
          (notFound as any).code = 'FILE_NOT_FOUND';
          (notFound as any).status = 404;
          throw notFound;
        }
        throw error;
      }
    
      // Reject binary files over MCP text protocol. Returning raw binary bytes in JSON payloads could corrupt character encoding or waste token limits on unreadable bytes.
      if (rawContent.includes('\0')) {
        const binaryErr = new Error(`Binary file cannot be read: ${filePath}`);
        (binaryErr as any).code = 'BINARY_FILE';
        (binaryErr as any).status = 400;
        throw binaryErr;
      }
    
      const lines = rawContent.split(/\r?\n/);
      const totalLines = lines.length;
      const totalBytes = Buffer.byteLength(rawContent, 'utf8');
    
      // Calculate 1-indexed bounded line window. Slicing by line range enables agents to read files in manageable chunks (default 800 lines) so large source files never exceed MCP buffer limits.
      const effectiveStart = Math.max(1, Math.min(startLine, totalLines));
      const lineLimit = Math.min(maxLines, 1000);
      const requestedEnd = endLine !== undefined ? Math.min(endLine, totalLines) : Math.min(effectiveStart + lineLimit - 1, totalLines);
      const effectiveEnd = Math.max(effectiveStart, Math.min(requestedEnd, effectiveStart + lineLimit - 1));
    
      const selectedLines = lines.slice(effectiveStart - 1, effectiveEnd);
      let content = selectedLines.join('\n');
      let truncated = effectiveStart > 1 || effectiveEnd < totalLines;
    
      // Enforce byte ceiling on the returned string. Slicing at a byte threshold (default 120,000 bytes) ensures that files with extremely long single lines (e.g. minified bundles) do not blow message size limits.
      const byteLimit = Math.min(maxBytes, 500_000);
      if (Buffer.byteLength(content, 'utf8') > byteLimit) {
        content = Buffer.from(content, 'utf8').subarray(0, byteLimit).toString('utf8');
        truncated = true;
      }
    
      return {
        repository,
        ref: targetRef,
        path: filePath,
        startLine: effectiveStart,
        endLine: effectiveEnd,
        totalLines,
        totalBytes,
        content,
        truncated,
      };
    }

    File: packages/core/src/index.ts

    Why this file: packages/core/src/index.ts is the public API entry point for the @propr/core package. Re-exporting the repository retrieval service here makes searchRepositoryFiles and readRepositoryFileContent available for the API layer (@propr/api), MCP handlers, and background tasks.

    --- a/packages/core/src/index.ts
    +++ b/packages/core/src/index.ts
    @@ -504,2 +504,5 @@
     export * from './services/taskPlanning/epicExecutionQueue.js';
    +
    +// Re-export repository code search and retrieval engine for planner and MCP
    +export * from './services/repositoryRetrievalService.js';
     

    File: packages/core/test/repositoryRetrievalService.test.ts (new file)

    Why this file: Provides automated unit test coverage for the repository retrieval engine. It validates semantic search ranking, literal tree grep parsing, line-bounded chunk reading, binary file rejection, and path traversal protection.

    import assert from 'node:assert/strict';
    import { test } from 'node:test';
    import { searchRepositoryFiles, readRepositoryFileContent } from '../src/services/repositoryRetrievalService.js';
    
    test('repositoryRetrievalService: path traversal protection rejects unsafe paths', async () => {
      // Directory traversal attempts with '..' must be rejected immediately to prevent breaking out of repository bounds
      await assert.rejects(
        () => readRepositoryFileContent({
          repository: 'test/repo',
          path: '../etc/passwd',
        }),
        (error: any) => {
          assert.equal(error.status, 400);
          assert.equal(error.code, 'INVALID_PATH');
          return true;
        }
      );
    
      // Leading slashes must be rejected because paths must remain strictly repository-relative
      await assert.rejects(
        () => readRepositoryFileContent({
          repository: 'test/repo',
          path: '/absolute/path/file.ts',
        }),
        (error: any) => {
          assert.equal(error.status, 400);
          assert.equal(error.code, 'INVALID_PATH');
          return true;
        }
      );
    });
    
    test('repositoryRetrievalService: search parameter bounds validation', async () => {
      // Repository handles missing the 'owner/repo' structure must fail fast with a descriptive error
      await assert.rejects(
        () => searchRepositoryFiles({
          repository: 'invalid-format',
          query: 'test',
        }),
        (error: any) => {
          assert.match(error.message, /Invalid repository format/);
          return true;
        }
      );
    });
  2. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5-5 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: claude
    • Model: claude-opus-5-5
    • Branch: 2797/claude-opus-5-5-implement-core-repository-20261006-1219-gso
    • Base Branch: 2797-epic-repository-search-sgj
    • Worktree: issue-2797-20261006-1219-claude-opus-5-5-gso

    🔍 Track Task Execution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions