Skip to content

Refactor: Add automatic token refresh to git push operations to prevent auth failures #99

Closed

Description

@integry

Task Description and Context

The 'worker.js' process occasionally fails during 'git push' operations with an "Authentication failed" error from GitHub. This occurs because the GitHub App installation token, which is valid for only one hour, is fetched at the start of a job. If a job, especially the AI-driven Claude execution phase, takes a significant amount of time to complete, the token can expire before the final push operation is executed. The current retry mechanism is not effective in this scenario as it repeatedly uses the same expired token.

The goal of this task is to make the git push operation more robust by incorporating an automatic token refresh mechanism when an authentication failure is detected.

Implementation Instructions

To resolve this, you'll need to modify the 'pushBranch' function in 'src/git/repoManager.js' to handle authentication errors gracefully.

  1. Import Authentication Utility:

    • In 'src/git/repoManager.js', add an import for 'getAuthenticatedOctokit' from '../auth/githubAuth.js'.
  2. Refactor 'pushBranch' Function:

    • The existing logic within 'pushBranch' should be extracted into a local async helper function, let's call it 'performPush'. This function will accept the token as an argument.
    • The main 'pushBranch' function will now contain the primary try/catch logic.
  3. Implement Retry Logic:

    • In the main 'pushBranch' function, make an initial call to 'performPush' with the 'authToken' passed in the options.
    • Wrap this call in a 'try...catch' block.
    • In the 'catch' block, check if the error message contains "Authentication failed" or "Invalid username or token".
    • If it's an authentication error:
      • Log that an authentication error was detected and a token refresh is being attempted.
      • Call 'getAuthenticatedOctokit()' to get a new instance.
      • Get a fresh token by calling '.auth({ type: "installation" })' on the new octokit instance.
      • Retry the push operation by calling 'performPush' again, this time with the newly acquired token.
      • If this retry also fails, the error should be thrown.
    • If the original error was not an authentication error, it should be re-thrown immediately.

Activity

  1. integry commented on Oct 7, 2025

    @integry
    OwnerAuthor

    Here is the suggested implementation:

    File: src/git/repoManager.js

    --- a/src/git/repoManager.js
    +++ b/src/git/repoManager.js
    @@ -4,6 +4,7 @@
     import logger from '../utils/logger.js';
     import { handleError } from './errorHandler.js';
    +import { getAuthenticatedOctokit } from '../auth/githubAuth.js';
     
     /**
      * Sets up authenticated remote URL for a Git repository
    @@ -442,76 +443,84 @@
     export async function pushBranch(worktreePath, branchName, options = {}) {
         const { repoUrl, authToken, remote = 'origin' } = options;
         const git = simpleGit({ baseDir: worktreePath });
    -    
    -    try {
    +
    +    const performPush = async (token) => {
             // Set up authentication if provided
    -        if (repoUrl && authToken) {
    -            await setupAuthenticatedRemote(git, repoUrl, authToken);
    +        if (repoUrl && token) {
    +            await setupAuthenticatedRemote(git, repoUrl, token);
             }
             
             // Verify the branch exists before pushing
             try {
                 const currentBranch = await git.revparse(['--abbrev-ref', 'HEAD']);
                 logger.debug({ 
                     worktreePath, 
                     currentBranch: currentBranch.trim(),
                     expectedBranch: branchName 
                 }, 'Current branch in worktree');
                 
                 if (currentBranch.trim() !== branchName) {
                     logger.warn({ 
                         worktreePath, 
                         currentBranch: currentBranch.trim(),
                         expectedBranch: branchName 
                     }, 'Branch mismatch detected, attempting to checkout correct branch');
                     
                     // Check if the branch exists locally
                     const branches = await git.branchLocal();
                     const branchExists = branches.all.includes(branchName);
                     
                     logger.debug({
                         worktreePath,
                         branchName,
                         branchExists,
                         localBranches: branches.all,
                         currentBranch: branches.current
                     }, 'Checking local branches before checkout');
                     
                     await git.checkout(branchName);
                     
                     // Verify checkout succeeded
                     const newBranch = await git.revparse(['--abbrev-ref', 'HEAD']);
                     logger.info({
                         worktreePath,
                         previousBranch: currentBranch.trim(),
                         newBranch: newBranch.trim(),
                         expectedBranch: branchName,
                         checkoutSuccess: newBranch.trim() === branchName
                     }, 'Branch checkout completed');
                 }
             } catch (branchCheckError) {
                 logger.warn({ 
                     error: branchCheckError.message 
                 }, 'Failed to verify current branch, proceeding with push anyway');
             }
             
             await git.push([remote, branchName, '--set-upstream']);
    +    };
    +    
    +    try {
    +        await performPush(authToken);
             
             logger.info({ 
                 worktreePath, 
                 branchName, 
                 remote 
             }, 'Branch pushed to remote successfully');
    -        
         } catch (error) {
    -        handleError(error, `Failed to push branch ${branchName} from worktree ${worktreePath}`);
    -        throw error;
    +        if (error.message && (error.message.includes('Authentication failed') || error.message.includes('Invalid username or token'))) {
    +            logger.info({ worktreePath, branchName }, 'Authentication error detected, attempting to refresh token');
    +            try {
    +                const freshOctokit = await getAuthenticatedOctokit();
    +                const freshAuth = await freshOctokit.auth({ type: "installation" });
    +                await performPush(freshAuth.token);
    +                logger.info({ worktreePath, branchName, remote }, 'Branch pushed to remote successfully after token refresh');
    +            } catch (retryError) {
    +                handleError(retryError, `Failed to push branch ${branchName} from worktree ${worktreePath} after token refresh`);
    +                throw retryError;
    +            }
    +        } else {
    +            handleError(error, `Failed to push branch ${branchName} from worktree ${worktreePath}`);
    +            throw error;
    +        }
         }
     }
     
    
  2. propr-dev commented on Oct 7, 2025

    @propr-dev
    Contributor

    🤖 AI processing has started for this issue using claude-sonnet-4-5-20250929 model.

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

    Processing Details:

    • Model: claude-sonnet-4-5-20250929
    • Branch: ai-fix/99-refactor-add-automatic-to-20251007-1159-claude-sonnet-4-5-20250929-j4o
    • Base Branch: main
    • Worktree: issue-99-20251007-1159-claude-sonnet-4-5-20250929-j4o
  3. added a commit that references this issue on Oct 7, 2025
  4. added a commit that references this issue on Oct 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions