async function findExistingJunieComment()

in src/github/operations/comments/feedback.ts [109:177]


async function findExistingJunieComment(
    octokit: Octokit,
    context: JunieExecutionContext,
): Promise<number | undefined> {
    // entityNumber is required for all comment searches
    // It's checked in writeInitialFeedbackComment, but we verify here too for safety
    if (!context.entityNumber) {
        return undefined;
    }

    const {owner, name} = context.payload.repository;
    const ownerLogin = owner.login;

    try {
        let comments;

        // Different APIs based on context type
        if (isPullRequestReviewCommentEvent(context)) {
            // For review comments (code-level comments), search within the specific thread
            const parentCommentId = context.payload.comment.id;
            console.log(`Searching for Junie comment in review thread ${parentCommentId}`);

            const response = await octokit.rest.pulls.listReviewComments({
                owner: ownerLogin,
                repo: name,
                pull_number: context.entityNumber,
                per_page: 100, // Get up to 100 most recent comments
            });

            // Filter comments to only those in the same thread
            // A comment is in the same thread if it's a direct reply (in_reply_to_id matches)
            // or if it's the parent comment itself
            comments = response.data.filter(comment =>
                comment.id === parentCommentId ||
                comment.in_reply_to_id === parentCommentId
            );

            console.log(`Found ${comments.length} comments in the review thread`);
        } else {
            // For issue comments and PR comments (conversation-level)
            const response = await octokit.rest.issues.listComments({
                owner: ownerLogin,
                repo: name,
                issue_number: context.entityNumber,
                per_page: 100, // Get up to 100 most recent comments
            });
            comments = response.data;
        }

        // Find the most recent comment with Junie marker for this workflow
        // Search in reverse order to find the most recent comment first
        const existingComment = comments
            .reverse()
            .find(comment => comment.body && hasJunieMarker(comment.body, context.workflow));

        if (existingComment) {
            console.log(`Found existing Junie comment with ID: ${existingComment.id}`);
            return existingComment.id;
        }

        console.log('No existing Junie comment found');
        return undefined;
    } catch (error) {
        console.error('Error searching for existing Junie comment:', error);
        // If we can't search for existing comments, return undefined
        // This allows the code to fall back to creating a new comment
        return undefined;
    }
}