Files
integraci-dagger-modules/ai-code-review/main.go
T

216 lines
6.9 KiB
Go

// Package main implements the IntegraCI ai-code-review Dagger module.
//
// This module is invoked from CI pipelines (Tekton/Argo Workflows) on every
// pull request. It runs three steps:
//
// 1. Snapshot the diff (`git diff origin/<base>..HEAD`) into a JSON envelope.
// 2. Send the envelope to the IntegraCI agent through `/api/v1/agent/sessions`
// using the `code_review` persona; the agent returns a structured Markdown
// review with risk highlights, suggested fixes, and citations to existing
// scan / scorecard data.
// 3. Optionally post the resulting Markdown back as a PR/MR comment via the
// IntegraCI code-review service (`/api/v1/webhooks/code-review`).
//
// Usage:
//
// dagger call review \
// --source . \
// --base origin/main \
// --service-id $SVC \
// --api-url http://localhost:8000 \
// --token $JWT \
// --post-comment=true \
// --pr-number 42 \
// --repo "org/repo"
package main
import (
"context"
"dagger/ai-code-review/internal/dagger"
"encoding/json"
"fmt"
"strings"
"time"
)
// AiCodeReview is the IntegraCI AI-driven code review module.
type AiCodeReview struct{}
// ReviewResult summarises one AI code review run.
type ReviewResult struct {
SessionID string `json:"session_id"`
AssistantMessage string `json:"assistant_message"`
ToolCalls int `json:"tool_calls"`
DiffLines int `json:"diff_lines"`
FilesChanged int `json:"files_changed"`
CommentPosted bool `json:"comment_posted"`
DurationSeconds int `json:"duration_seconds"`
Success bool `json:"success"`
ErrorMessage string `json:"error,omitempty"`
}
// Review runs an AI code review against a pull request diff.
func (m *AiCodeReview) Review(
ctx context.Context,
// Source directory of the workspace (must be a git repo)
source *dagger.Directory,
// Base branch / SHA to diff against
// +optional
base string,
// IntegraCI service id this review attaches to
// +optional
serviceID string,
// IntegraCI API URL
apiURL string,
// JWT token
token *dagger.Secret,
// When true, posts the Markdown review back to the PR/MR
// +optional
postComment bool,
// PR number (GitHub) or MR IID (GitLab) — required when postComment=true
// +optional
prNumber int,
// Repository slug, e.g. "org/repo"
// +optional
repo string,
) (*ReviewResult, error) {
if base == "" {
base = "origin/main"
}
start := time.Now()
result := &ReviewResult{}
// 1. compute diff stats inside a Git container so we don't depend on the
// host's git installation.
gitImage := dag.Container().
From("alpine/git:2.45.2").
WithDirectory("/repo", source).
WithWorkdir("/repo").
WithExec([]string{"sh", "-c", "git config --global --add safe.directory /repo"})
diff, err := gitImage.
WithExec([]string{"sh", "-c", fmt.Sprintf("git diff --stat %s..HEAD || true", base)}).
Stdout(ctx)
if err != nil {
result.ErrorMessage = "git diff failed: " + err.Error()
return result, err
}
result.FilesChanged = strings.Count(diff, "\n |")
patch, err := gitImage.
WithExec([]string{"sh", "-c", fmt.Sprintf("git diff %s..HEAD || true", base)}).
Stdout(ctx)
if err != nil {
result.ErrorMessage = "git diff -p failed: " + err.Error()
return result, err
}
result.DiffLines = strings.Count(patch, "\n")
// 2. ask the IntegraCI agent for a code review.
envelope := map[string]any{
"persona": "code_review",
"title": fmt.Sprintf("PR review @ %s", time.Now().Format("2006-01-02 15:04")),
}
envelopeBody, _ := json.Marshal(envelope)
// Token is injected as a secret env var ($API_TOKEN), never interpolated
// into argv, so it is redacted in the Dagger op graph / logs / cache.
curl := dag.Container().
From("curlimages/curl:8.10.1").
WithSecretVariable("API_TOKEN", token).
WithEnvVariable("CACHEBUST", time.Now().String())
createSessOut, err := curl.
WithNewFile("/tmp/session.json", string(envelopeBody)).
WithExec([]string{
"sh", "-c",
"curl -fsS -X POST " +
"-H 'Content-Type: application/json' " +
"-H \"Authorization: Bearer ${API_TOKEN}\" " +
"--data-binary @/tmp/session.json " +
"'" + fmt.Sprintf("%s/api/v1/agent/sessions", strings.TrimRight(apiURL, "/")) + "'",
}).Stdout(ctx)
if err != nil {
result.ErrorMessage = "create session failed: " + err.Error()
return result, err
}
sess := struct {
ID string `json:"id"`
}{}
_ = json.Unmarshal([]byte(createSessOut), &sess)
result.SessionID = sess.ID
if patch == "" {
patch = "(no diff against " + base + ")"
}
if len(patch) > 12000 {
patch = patch[:12000] + "\n...[truncated]"
}
prompt := fmt.Sprintf(
"Review this pull request diff. Focus on:\n"+
"1. Security issues (auth, secrets, injection).\n"+
"2. Reliability (error handling, timeouts).\n"+
"3. Maintainability (clarity, tests, naming).\n\n"+
"Service id: %s\n"+
"Files changed: %d\n"+
"Diff:\n```diff\n%s\n```",
serviceID, result.FilesChanged, patch,
)
msgBody, _ := json.Marshal(map[string]any{"content": prompt})
msgOut, err := curl.
WithNewFile("/tmp/message.json", string(msgBody)).
WithExec([]string{
"sh", "-c",
"curl -fsS -X POST " +
"-H 'Content-Type: application/json' " +
"-H \"Authorization: Bearer ${API_TOKEN}\" " +
"--data-binary @/tmp/message.json " +
"'" + fmt.Sprintf("%s/api/v1/agent/sessions/%s/messages",
strings.TrimRight(apiURL, "/"), sess.ID) + "'",
}).Stdout(ctx)
if err != nil {
result.ErrorMessage = "agent message failed: " + err.Error()
return result, err
}
reply := struct {
AssistantMessage struct {
Content string `json:"content"`
} `json:"assistant_message"`
ToolMessages []any `json:"tool_messages"`
}{}
_ = json.Unmarshal([]byte(msgOut), &reply)
result.AssistantMessage = reply.AssistantMessage.Content
result.ToolCalls = len(reply.ToolMessages)
// 3. post the review back as a PR/MR comment via the existing webhook.
if postComment && prNumber > 0 && repo != "" {
commentBody := strings.Builder{}
commentBody.WriteString("<!-- integraci-ai-review -->\n")
commentBody.WriteString("## IntegraCI AI Code Review\n\n")
commentBody.WriteString(reply.AssistantMessage.Content)
commentBody.WriteString("\n\n*Generated by IntegraCI Phase 7 agent.*")
body, _ := json.Marshal(map[string]any{
"repo": repo,
"pr_number": prNumber,
"comment": commentBody.String(),
"service_id": serviceID,
"source": "ai_code_review",
})
_, err := curl.
WithNewFile("/tmp/comment.json", string(body)).
WithExec([]string{
"sh", "-c",
"curl -fsS -X POST " +
"-H 'Content-Type: application/json' " +
"-H \"Authorization: Bearer ${API_TOKEN}\" " +
"--data-binary @/tmp/comment.json " +
"'" + fmt.Sprintf("%s/api/v1/webhooks/ai-code-review",
strings.TrimRight(apiURL, "/")) + "'",
}).Stdout(ctx)
result.CommentPosted = err == nil
}
result.DurationSeconds = int(time.Since(start).Seconds())
result.Success = result.AssistantMessage != ""
return result, nil
}