Skip to content

Support multi-branch indexing for repositories #500

Closed

Description

@integry

Support Multi-Branch Indexing for Repositories

Context

The current indexing system identifies repositories solely by their 'full_name' (e.g., 'owner/repo'). This limitation prevents us from monitoring and indexing multiple branches of the same repository (e.g., 'main' and 'develop') simultaneously, as they would share the same database record and overwrite each other's summaries.

Objective

Update the database schema and indexing logic to support a composite key of 'full_name' + 'branch'. This will allow separate indexing status and summaries for different branches.

Implementation Steps

1. Database Schema Migration

Create a new migration file 'packages/core/src/db/migrations/20260109000000_add_branch_to_indexing.js' to:

  • Add a 'branch' column to 'repositories', 'file_summaries', and 'directory_summaries' tables (default to 'HEAD').
  • Update the Primary Key of 'repositories' to '('full_name', 'branch')'.
  • Update the Primary Key of 'file_summaries' to '('path', 'branch')'.
  • Update the Primary Key of 'directory_summaries' to '('path', 'branch')'.

2. Core Logic Updates ('@gitfix/core')

  • 'packages/core/src/services/relevance/summaryMiner.ts':
    • Update 'IndexRepo' to accept a 'branch' option.
    • Update 'updateRepositoryStatus' to query and insert using both 'full_name' and 'branch'.
    • Update 'identifyStaleFiles', 'deleteFileSummaries', 'getFileSummary', etc., to filter by the specific 'branch'.
  • 'packages/core/src/services/relevance/summaryMinerHelpers.ts':
    • Ensure 'processBatches' and 'aggregateDirectories' inject the 'branch' field when creating new summary records.
  • 'packages/core/src/queue/taskQueue.ts':
    • Update 'IndexingJobData' interface to include 'branch?: string'.

3. Worker Updates ('src/indexing_worker.ts')

  • Update 'scanAndQueueRepositories' to use 'loadMonitoredReposRaw()' instead of 'loadMonitoredRepos()'.
  • Iterate through the full config objects to access 'baseBranch'.
  • Pass 'baseBranch' (defaulting to 'HEAD') to 'processRepositoryForIndexing'.
  • Update 'processRepositoryForIndexing' and 'queueIndexingJob' to propagate the branch information.
  • Update 'cloneRepositoryForIndexing' to utilize the specific branch during the checkout/clone process.

Acceptance Criteria

  • 'repositories' table stores separate rows for the same repo with different branches.
  • 'file_summaries' are isolated by branch.
  • The indexing worker correctly picks up the configured 'baseBranch' from 'repos_to_monitor' config.

Activity

  1. integry commented on Jan 9, 2026

    @integry
    OwnerAuthor

    Here is the migration script to update the schema.
    Create 'packages/core/src/db/migrations/20260109000000_add_branch_to_indexing.js':

    /**
     * Add branch support to indexing tables
     */
    export async function up(knex) {
      // 1. Repositories
      await knex.schema.alterTable('repositories', (table) => {
        table.string('branch').defaultTo('HEAD').notNullable();
        // Drop old PK and add new composite PK
        table.dropPrimary();
        table.primary(['full_name', 'branch']);
      });
    
      // 2. File Summaries
      await knex.schema.alterTable('file_summaries', (table) => {
        table.string('branch').defaultTo('HEAD').notNullable();
        table.dropPrimary();
        table.primary(['path', 'branch']);
        // Add index for faster lookups by repo/branch
        table.index(['path', 'branch']);
      });
    
      // 3. Directory Summaries
      await knex.schema.alterTable('directory_summaries', (table) => {
        table.string('branch').defaultTo('HEAD').notNullable();
        table.dropPrimary();
        table.primary(['path', 'branch']);
      });
    }
    
    export async function down(knex) {
      // Revert Repositories
      await knex.schema.alterTable('repositories', (table) => {
        table.dropPrimary();
        table.dropColumn('branch');
        table.primary(['full_name']);
      });
    
      // Revert File Summaries
      await knex.schema.alterTable('file_summaries', (table) => {
        table.dropIndex(['path', 'branch']);
        table.dropPrimary();
        table.dropColumn('branch');
        table.primary(['path']);
      });
    
      // Revert Directory Summaries
      await knex.schema.alterTable('directory_summaries', (table) => {
        table.dropPrimary();
        table.dropColumn('branch');
        table.primary(['path']);
      });
    }
  2. integry commented on Jan 9, 2026

    @integry
    OwnerAuthor

    Updates for 'packages/core/src/services/relevance/summaryMiner.ts':

    // Update IndexingOptions
    export interface IndexingOptions {
      correlationId?: string;
      fullName?: string;
      branch?: string; // Add this
    }
    
    // Update indexRepo signature and usage
    export async function indexRepo(repoPath: string, options: IndexingOptions = {}): Promise<void> {
      // ...
      const branch = options.branch || 'HEAD';
      
      try {
        // ... 
        // Pass branch to updateRepositoryStatus
        await updateRepositoryStatus(fullName, 'indexing', branch);
    
        // ...
        // Pass branch to identifyStaleFiles
        const { filesToProcess, filesToDelete } = await identifyStaleFiles(
          fullName,
          gitFiles,
          correlatedLogger,
          branch
        );
    
        // ...
        if (filesToDelete.length > 0) {
          await deleteFileSummaries(filesToDelete, branch);
          // ...
        }
    
        // ...
        // Pass branch to processBatches
        const batchResult = await processBatches({
          repoPath,
          fullName,
          files: filesToProcess,
          agent,
          log: correlatedLogger,
          modelOverride,
          customPrompt: settings.custom_prompt,
          branch // Pass branch here
        });
    
        if (batchResult.filesProcessed > 0) {
          await aggregateDirectories(fullName, agent, correlatedLogger, branch);
        }
        
        // ...
        // Update final status
        await updateRepositoryStatus(fullName, batchResult.failedBatches > 0 ? 'failed' : 'completed', branch);
    
      } catch (error) {
         // ...
         await updateRepositoryStatus(options.fullName || path.basename(repoPath), 'failed', options.branch || 'HEAD');
         throw error;
      }
    }
    
    // Update updateRepositoryStatus
    export async function updateRepositoryStatus(
      fullName: string,
      status: 'idle' | 'indexing' | 'completed' | 'failed',
      branch: string = 'HEAD'
    ): Promise<void> {
      const updateData: Record<string, unknown> = {
        indexing_status: status,
        updated_at: db.fn.now()
      };
    
      if (status === 'completed') {
        updateData.last_indexed_at = db.fn.now();
      }
    
      await db('repositories')
        .insert({
          full_name: fullName,
          branch: branch,
          indexing_status: status,
          created_at: db.fn.now(),
          updated_at: db.fn.now(),
          ...(status === 'completed' ? { last_indexed_at: db.fn.now() } : {})
        })
        .onConflict(['full_name', 'branch']) // Use composite key
        .merge(updateData);
    }
    
    // Update identifyStaleFiles
    async function identifyStaleFiles(
      fullName: string,
      gitFiles: GitFileInfo[],
      log: Logger,
      branch: string
    ): Promise<{ filesToProcess: GitFileInfo[]; filesToDelete: string[]; }> {
      const existingSummaries = await db('file_summaries')
        .where('path', 'like', `${fullName}/%`)
        .andWhere({ branch }) // Filter by branch
        .select('path', 'commit_hash');
        
      // ... rest of logic remains similar
    }
    
    // Update deleteFileSummaries
    async function deleteFileSummaries(paths: string[], branch: string): Promise<void> {
      if (paths.length === 0) return;
    
      await db('file_summaries')
        .whereIn('path', paths)
        .andWhere({ branch })
        .delete();
    }
  3. integry commented on Jan 9, 2026

    @integry
    OwnerAuthor

    Updates for 'src/indexing_worker.ts':

    // Import the raw loader
    import { loadSummarizationSettings, loadMonitoredReposRaw } from '@gitfix/core';
    
    // Update local interfaces
    interface RepoStatus {
        full_name: string;
        branch: string;
        indexing_status: string;
        // ...
    }
    
    interface IndexingJobData {
        // ... existing
        branch?: string; 
    }
    
    // Update processIndexingJob
    async function processIndexingJob(job: Job<IndexingJobData>): Promise<IndexingResult> {
        const { repository, repoPath, correlationId, fullReindex, branch = 'HEAD' } = job.data;
        // ...
        
        // Pass branch to indexRepo
        await indexRepo(repoPath, {
            correlationId,
            fullName: repository,
            branch
        });
        // ...
    }
    
    // Update processRepositoryForIndexing
    async function processRepositoryForIndexing(
        repoConfig: { name: string; baseBranch?: string }, // Accept config object
        log: Logger
    ): Promise<void> {
        const repoName = repoConfig.name;
        const branch = repoConfig.baseBranch || 'HEAD';
    
        const repoStatus = await db('repositories')
            .where({ full_name: repoName, branch }) // Check specific branch
            .first() as RepoStatus | undefined;
    
        const decision = shouldIndexRepository(repoStatus);
    
        if (!decision.shouldIndex) {
            // ...
            return;
        }
    
        // Check if job already queued
        const existingJobs = await indexingQueue.getJobs(['waiting', 'active', 'delayed']);
        const alreadyQueued = existingJobs.some((j) => 
            j.data.repository === repoName && (j.data.branch || 'HEAD') === branch
        );
    
        if (alreadyQueued) {
            return;
        }
    
        // Clone and queue
        const repoPath = await cloneRepositoryForIndexing(repoName, branch); // Pass branch
        await queueIndexingJob(repoName, repoPath, decision.reason, log, branch); // Pass branch
    }
    
    // Update cloneRepositoryForIndexing
    async function cloneRepositoryForIndexing(repoName: string, branch: string): Promise<string> {
        const [owner, name] = repoName.split('/');
        const octokit = await getAuthenticatedOctokit();
        const { token } = await octokit.auth({ type: "installation" }) as { token: string };
        const repoUrl = getRepoUrl({ repoOwner: owner, repoName: name });
        
        // ensureRepoCloned already supports baseBranch
        return ensureRepoCloned({ 
            repoUrl, 
            owner, 
            repoName: name, 
            authToken: token,
            baseBranch: branch === 'HEAD' ? undefined : branch
        });
    }
    
    // Update queueIndexingJob
    async function queueIndexingJob(
        repoName: string,
        repoPath: string,
        reason: string,
        log: Logger,
        branch: string
    ): Promise<void> {
        // ...
        await indexingQueue.add(
            'indexRepository',
            {
                repository: repoName,
                repoPath,
                correlationId: jobCorrelationId,
                priority,
                branch // Add branch
            },
            // ...
        );
    }
    
    // Update scanAndQueueRepositories
    async function scanAndQueueRepositories(): Promise<void> {
        // ...
        const repos = await loadMonitoredReposRaw(); // Load full config
        // ...
        for (const repoConfig of repos) {
            if (!repoConfig.enabled) continue;
            try {
                await processRepositoryForIndexing(repoConfig, correlatedLogger);
            } catch (repoError) {
                // ...
            }
        }
        // ...
    }
  4. propr-dev commented on Jan 9, 2026

    @propr-dev
    Contributor

    🤖 AI processing has started for this issue using gemini agent with gemini-3-pro-preview model.

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

    Processing Details:

    • Agent: gemini
    • Model: gemini-3-pro-preview
    • Branch: 500/gemini-3-pro-preview-support-multi-branch-inde-20260109-1445-y2g
    • Base Branch: main
    • Worktree: issue-500-20260109-1445-gemini-3-pro-preview-y2g

    🔍 Track Task Execution

  5. propr-dev commented on Jan 9, 2026

    @propr-dev
    Contributor

    ⚠️ Post-processing encountered an error, but Claude analysis was completed.

    AI Processing Failed

    Execution Details:


    Powered by Claude Code v1.0.0

  6. propr-dev commented on Jan 12, 2026

    @propr-dev
    Contributor

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

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

    Processing Details:

    • Agent: claude
    • Model: claude-opus-4-5-20251101
    • Branch: 500/claude-opus-4-5-20251101-support-multi-branch-inde-20260112-0910-puq
    • Base Branch: main
    • Worktree: issue-500-20260112-0910-claude-opus-4-5-20251101-puq

    🔍 Track Task Execution

  7. added a commit that references this issue on Jan 12, 2026
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