Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/entities/reviewAction/reviewAction.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export interface ExecutionContext {
mrNumber: number
localPath: string
diffMetadata?: DiffMetadata
baseUrl: string | null
}

export interface ExecutionResult {
Expand Down
5 changes: 4 additions & 1 deletion src/frameworks/claude/claudeInvoker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,10 +305,13 @@ export async function invokeClaudeReview(
let stderr = '';
let cancelled = false;

const childEnv = { ...process.env };
// Remove CLAUDECODE to allow spawning Claude from within a Claude session
childEnv.CLAUDECODE = undefined;
const child = spawn(resolveClaudePath(), args, {
cwd: job.localPath,
env: {
...process.env,
...childEnv,
// Ensure non-interactive mode
TERM: 'dumb',
CI: 'true',
Expand Down
11 changes: 10 additions & 1 deletion src/frameworks/config/configLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,23 @@ function loadProjectConfig(localPath: string): ProjectConfig | null {
}
}

export function normalizeGitUrl(url: string): string {
// Convert SSH URLs (git@host:org/repo.git) to HTTPS (https://host/org/repo)
const sshMatch = url.match(/^git@([^:]+):(.+)$/);
if (sshMatch) {
return `https://${sshMatch[1]}/${sshMatch[2].replace(/\.git$/, '')}`;
}
return url.replace(/\.git$/, '');
}

function getGitRemoteUrl(localPath: string): string | null {
try {
const result = execSync('git remote get-url origin', {
cwd: localPath,
encoding: 'utf-8',
timeout: 5000,
});
return result.trim().replace(/\.git$/, '');
return normalizeGitUrl(result.trim());
} catch {
return null;
}
Expand Down
26 changes: 24 additions & 2 deletions src/interface-adapters/controllers/webhook/gitlab.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,24 @@ import type { ReviewContextGateway } from '@/entities/reviewContext/reviewContex
import type { ThreadFetchGateway } from '@/entities/threadFetch/threadFetch.gateway.js';
import type { DiffMetadataFetchGateway } from '@/entities/diffMetadata/diffMetadata.gateway.js';

export function extractBaseUrl(remoteUrl: string): string | null {
try {
// Handle HTTPS URLs: https://gitlab.example.com/group/project.git
if (remoteUrl.startsWith('http')) {
const url = new URL(remoteUrl)
return `${url.protocol}//${url.host}`
}
// Handle SSH URLs: git@gitlab.example.com:group/project.git
const sshMatch = remoteUrl.match(/@([^:]+):/)
if (sshMatch) {
return `https://${sshMatch[1]}`
}
} catch {
// Invalid URL — return null
}
return null
}

export interface GitLabWebhookDependencies {
reviewContextGateway: ReviewContextGateway;
threadFetchGateway: ThreadFetchGateway;
Expand Down Expand Up @@ -299,11 +317,13 @@ export async function handleGitLabWebhook(
const reviewContext = contextGateway.read(j.localPath, mergeRequestId);
if (reviewContext && reviewContext.actions.length > 0) {
threadResolveCount = reviewContext.actions.filter(a => a.type === 'THREAD_RESOLVE').length;
const followupBaseUrl = extractBaseUrl(updateRepoConfig.remoteUrl);
const contextActionResult = await executeActionsFromContext(
reviewContext,
j.localPath,
logger,
defaultCommandExecutor
defaultCommandExecutor,
followupBaseUrl,
);
logger.info(
{ ...contextActionResult, threadResolveCount, mrNumber: j.mrNumber },
Expand Down Expand Up @@ -533,11 +553,13 @@ export async function handleGitLabWebhook(
// PRIMARY: Execute actions from context file (agent writes actions here)
const reviewContext = contextGateway.read(j.localPath, mergeRequestId);
if (reviewContext && reviewContext.actions.length > 0) {
const reviewBaseUrl = extractBaseUrl(repoConfig.remoteUrl);
const contextActionResult = await executeActionsFromContext(
reviewContext,
j.localPath,
logger,
defaultCommandExecutor
defaultCommandExecutor,
reviewBaseUrl,
);
logger.info(
{ ...contextActionResult, mrNumber: j.mrNumber },
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ReviewAction } from '../../../entities/reviewAction/reviewAction.js'
import type { ReviewActionGateway, ExecutionContext } from '../../../entities/reviewAction/reviewAction.gateway.js'
import { ExecutionGatewayBase, type CommandInfo } from '../../../shared/foundation/executionGateway.base.js'
import type { ReviewAction } from '@/entities/reviewAction/reviewAction.js'
import type { ReviewActionGateway, ExecutionContext } from '@/entities/reviewAction/reviewAction.gateway.js'
import { ExecutionGatewayBase, type CommandInfo } from '@/shared/foundation/executionGateway.base.js'
import { enrichCommentWithLinks } from '@/services/commentLinkEnricher.js'

export class GitLabReviewActionCliGateway
extends ExecutionGatewayBase<ReviewAction, ExecutionContext>
Expand All @@ -17,11 +18,15 @@ export class GitLabReviewActionCliGateway
args: ['api', '--method', 'PUT', `${baseUrl}/discussions/${action.threadId}`, '--field', 'resolved=true'],
}

case 'POST_COMMENT':
case 'POST_COMMENT': {
const enrichedBody = context.baseUrl && context.diffMetadata
? enrichCommentWithLinks(action.body, context.baseUrl, context.projectPath, context.diffMetadata.headSha)
: action.body
return {
command: 'glab',
args: ['api', '--method', 'POST', `${baseUrl}/notes`, '--field', `body=${action.body}`],
args: ['api', '--method', 'POST', `${baseUrl}/notes`, '--field', `body=${enrichedBody}`],
}
}

case 'THREAD_REPLY':
return {
Expand Down
50 changes: 50 additions & 0 deletions src/services/commentLinkEnricher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Replace file:line references in a comment body with clickable GitLab/GitHub blob links.
*
* Pattern matches references like:
* file.py:42
* `file.py:42`
* (file.py:42)
* users/api.py:247
*
* Produces markdown links:
* [`file.py:42`](baseUrl/project/-/blob/sha/file.py#L42)
*
* Does NOT match:
* - URLs (http://localhost:8000, https://example.com:443)
* - Bare filenames without line numbers (docker-compose.yml)
*/

// File path must start with a word char, contain at least one dot (extension), then :lineNumber.
// The path must NOT start with // (to exclude URLs).
const FILE_LINE_PATTERN =
/(?<prefix>[`(]?)(?<filePath>[\w][\w./-]*\.[\w]+):(?<line>\d+)(?<suffix>[`)]?)/g

export function enrichCommentWithLinks(
body: string,
baseUrl: string,
projectPath: string,
headSha: string,
platform: 'gitlab' | 'github' = 'gitlab',
): string {
return body.replace(FILE_LINE_PATTERN, (match, prefix, filePath, line, suffix, offset) => {
// Skip if preceded by :// (URL pattern like https://example.com:443)
const beforeMatch = body.slice(Math.max(0, offset - 10), offset)
if (/:\/{1,2}$/.test(beforeMatch) || /:\/{1,2}[\w.-]*$/.test(beforeMatch)) {
return match
}

// Skip if the filePath portion doesn't look like a real file (must contain a dot for extension)
// Already handled by regex, but double check for edge cases
if (!filePath.includes('.')) {
return match
}

const blobPrefix = platform === 'github' ? 'blob' : '-/blob'
const blobUrl = `${baseUrl}/${projectPath}/${blobPrefix}/${headSha}/${filePath}#L${line}`
// When wrapped in backticks, the link markdown already includes backticks — don't double them
const outerPrefix = prefix === '`' ? '' : prefix
const outerSuffix = suffix === '`' ? '' : suffix
return `${outerPrefix}[\`${filePath}:${line}\`](${blobUrl})${outerSuffix}`
})
}
4 changes: 3 additions & 1 deletion src/services/contextActionsExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,15 @@ export async function executeActionsFromContext(
context: ReviewContext,
localPath: string,
_logger: Logger,
executor: CommandExecutor
executor: CommandExecutor,
baseUrl: string | null = null,
): Promise<ExecutionResult> {
const gatewayContext = {
projectPath: context.projectPath,
mrNumber: context.mergeRequestNumber,
localPath,
diffMetadata: context.diffMetadata,
baseUrl,
}

const gateway =
Expand Down
5 changes: 3 additions & 2 deletions src/services/threadActionsExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { execSync } from 'node:child_process'
import type { ReviewAction } from '../entities/reviewAction/reviewAction.js'
import { GitLabReviewActionCliGateway } from '../interface-adapters/gateways/cli/reviewAction.gitlab.cli.gateway.js'
import { GitHubReviewActionCliGateway } from '../interface-adapters/gateways/cli/reviewAction.github.cli.gateway.js'
import type { ExecutionResult, CommandExecutor } from '../entities/reviewAction/reviewAction.gateway.js'
import type { ExecutionResult, CommandExecutor, ExecutionContext as GatewayExecutionContext } from '../entities/reviewAction/reviewAction.gateway.js'

const COMMAND_TIMEOUT_MS = 30000

Expand Down Expand Up @@ -37,11 +37,12 @@ export async function executeThreadActions(
_logger: Logger,
executor: CommandExecutor
): Promise<ExecutionResult> {
const gatewayContext = {
const gatewayContext: GatewayExecutionContext = {
projectPath: context.projectPath,
mrNumber: context.mrNumber,
localPath: context.localPath,
diffMetadata: context.diffMetadata,
baseUrl: null,
}

const gateway =
Expand Down
24 changes: 24 additions & 0 deletions src/tests/units/frameworks/config/normalizeGitUrl.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, it, expect } from 'vitest'
import { normalizeGitUrl } from '@/frameworks/config/configLoader.js'

describe('normalizeGitUrl', () => {
it('should convert SSH URL to HTTPS', () => {
expect(normalizeGitUrl('git@gitlab.com:org/repo.git')).toBe('https://gitlab.com/org/repo')
})

it('should strip .git suffix from HTTPS URL', () => {
expect(normalizeGitUrl('https://gitlab.com/org/repo.git')).toBe('https://gitlab.com/org/repo')
})

it('should leave HTTPS URL without .git unchanged', () => {
expect(normalizeGitUrl('https://gitlab.com/org/repo')).toBe('https://gitlab.com/org/repo')
})

it('should handle SSH URL with nested groups', () => {
expect(normalizeGitUrl('git@host:group/subgroup/repo.git')).toBe('https://host/group/subgroup/repo')
})

it('should pass through plain HTTPS URL without .git', () => {
expect(normalizeGitUrl('https://github.com/owner/project')).toBe('https://github.com/owner/project')
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { describe, it, expect } from 'vitest'
import { extractBaseUrl } from '@/interface-adapters/controllers/webhook/gitlab.controller.js'

describe('extractBaseUrl', () => {
it('should extract protocol://host from HTTPS URL', () => {
expect(extractBaseUrl('https://gitlab.example.com/group/project.git')).toBe('https://gitlab.example.com')
})

it('should extract protocol://host from HTTP URL', () => {
expect(extractBaseUrl('http://gitlab.example.com/group/project.git')).toBe('http://gitlab.example.com')
})

it('should convert SSH URL to https://host', () => {
expect(extractBaseUrl('git@gitlab.example.com:group/project.git')).toBe('https://gitlab.example.com')
})

it('should preserve port in HTTPS URL', () => {
expect(extractBaseUrl('https://gitlab.example.com:8443/group/project.git')).toBe('https://gitlab.example.com:8443')
})

it('should extract host from SSH URL with nested groups', () => {
expect(extractBaseUrl('git@gitlab.example.com:group/subgroup/project.git')).toBe('https://gitlab.example.com')
})

it('should return null for empty string', () => {
expect(extractBaseUrl('')).toBeNull()
})

it('should return null for invalid URL', () => {
expect(extractBaseUrl('not-a-url')).toBeNull()
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ describe('GitHubReviewActionCliGateway', () => {
const gateway = new GitHubReviewActionCliGateway(executor)

const actions: ReviewAction[] = [{ type: 'THREAD_RESOLVE', threadId: 'PRRT_abc123' }]
const context = { projectPath: 'owner/repo', mrNumber: 42, localPath: '/tmp/repo' }
const context = { projectPath: 'owner/repo', mrNumber: 42, localPath: '/tmp/repo', baseUrl: null as string | null }

const result = await gateway.execute(actions, context)

Expand All @@ -24,7 +24,7 @@ describe('GitHubReviewActionCliGateway', () => {
const executor = vi.fn()
const gateway = new GitHubReviewActionCliGateway(executor)
const actions: ReviewAction[] = [{ type: 'POST_COMMENT', body: '## Review complete' }]
const context = { projectPath: 'owner/repo', mrNumber: 42, localPath: '/tmp' }
const context = { projectPath: 'owner/repo', mrNumber: 42, localPath: '/tmp', baseUrl: null as string | null }

const result = await gateway.execute(actions, context)

Expand All @@ -40,7 +40,7 @@ describe('GitHubReviewActionCliGateway', () => {
const executor = vi.fn()
const gateway = new GitHubReviewActionCliGateway(executor)
const actions: ReviewAction[] = [{ type: 'THREAD_REPLY', threadId: '123456', message: 'Done!' }]
const context = { projectPath: 'owner/repo', mrNumber: 42, localPath: '/tmp' }
const context = { projectPath: 'owner/repo', mrNumber: 42, localPath: '/tmp', baseUrl: null as string | null }

const result = await gateway.execute(actions, context)

Expand All @@ -56,7 +56,7 @@ describe('GitHubReviewActionCliGateway', () => {
const executor = vi.fn()
const gateway = new GitHubReviewActionCliGateway(executor)
const actions: ReviewAction[] = [{ type: 'ADD_LABEL', label: 'reviewed' }]
const context = { projectPath: 'owner/repo', mrNumber: 42, localPath: '/tmp' }
const context = { projectPath: 'owner/repo', mrNumber: 42, localPath: '/tmp', baseUrl: null as string | null }

const result = await gateway.execute(actions, context)

Expand All @@ -79,6 +79,7 @@ describe('GitHubReviewActionCliGateway', () => {
mrNumber: 42,
localPath: '/tmp',
diffMetadata: { baseSha: 'base111', headSha: 'head222', startSha: 'start333' },
baseUrl: null as string | null,
}

const result = await gateway.execute(actions, context)
Expand All @@ -103,7 +104,7 @@ describe('GitHubReviewActionCliGateway', () => {
const actions: ReviewAction[] = [
{ type: 'POST_INLINE_COMMENT', filePath: 'src/app.ts', line: 42, body: 'Test' }
]
const context = { projectPath: 'owner/repo', mrNumber: 42, localPath: '/tmp' }
const context = { projectPath: 'owner/repo', mrNumber: 42, localPath: '/tmp', baseUrl: null as string | null }

const result = await gateway.execute(actions, context)

Expand All @@ -115,7 +116,7 @@ describe('GitHubReviewActionCliGateway', () => {
const executor = vi.fn()
const gateway = new GitHubReviewActionCliGateway(executor)
const actions: ReviewAction[] = [{ type: 'FETCH_THREADS' }]
const context = { projectPath: 'owner/repo', mrNumber: 42, localPath: '/tmp' }
const context = { projectPath: 'owner/repo', mrNumber: 42, localPath: '/tmp', baseUrl: null as string | null }

const result = await gateway.execute(actions, context)

Expand Down
Loading