Building an Enterprise Code Review Agent with DeepSeek Harness: Chapter 14 Practical Project

This chapter guides developers through constructing a production-ready code review agent using the DeepSeek Harness framework, covering architecture design, multi-analyzer integration (LSP, security, style, complexity), GitHub/GitLab webhook handling, automated reporting, Docker/Kubernetes deployment, and testing strategies.

AI Digital Ideal
AI Digital Ideal
AI Digital Ideal
Building an Enterprise Code Review Agent with DeepSeek Harness: Chapter 14 Practical Project

Chapter Overview

Chapter 14 consolidates knowledge from Chapters 1–13 of the DeepSeek Harness (DSH) course to build a complete enterprise-grade code review agent. The system automates pull request analysis, detects bugs and security vulnerabilities, enforces coding standards, and reduces manual review effort by 50% or more.

Requirements Analysis

Business Context

Targeting a mid-sized tech company with 20–50 developers, 50+ Git repositories, and 30–50 PRs per day. Pain points include lengthy manual reviews (30–60 minutes per PR), inconsistent standards, missed security flaws, style drift, and recurring issues.

Functional Requirements (Priority-Ordered)

P0 : Git integration (GitHub/GitLab PR fetching), code analysis (static analysis, complexity), security scanning (OWASP Top 10), report generation

P1 : Style checking, PR commenting, notifications (DingTalk, Feishu, Slack)

P2 : Review history recording and querying

Non-Functional Requirements

Performance:
├── Single PR review time < 5 minutes
├── Concurrent PR handling > 10
└── Cache hit rate > 60%

Availability:
├── Service uptime > 99.5%
├── Automatic error retry
└── Graceful degradation

Security:
├── No persistent code storage
├── API key encryption
└── Audit logging

System Architecture

Overall Architecture

The system comprises three layers:

External Systems : GitHub, GitLab, DingTalk, Feishu

API Gateway : Authentication, rate limiting, logging, routing

Code Review Core : Code Fetch Service, Code Analysis Service, Report Service

Analysis Engine : LSP Analyzer, Security Scanner, Style Checker, Complexity Detector, AI-enhanced analysis via DSH Agent

Storage Layer : PostgreSQL (review records), Redis (cache), S3 (attachments), Elasticsearch (log search)

Directory Structure

code-review-agent/
├── src/
│   ├── main.ts
│   ├── config/          # Configuration management
│   ├── api/             # Routes, middleware, controllers
│   ├── services/        # CodeFetch, CodeAnalysis, Report, Notification, Git
│   ├── analyzers/       # Lsp, Security, Style, Complexity
│   ├── models/          # Review, Issue, Report (TypeORM entities)
│   ├── integrations/    # GitHub, GitLab, DingTalk, Feishu
│   ├── tools/           # Custom DSH tools
│   ├── skills/          # Custom DSH skills
│   └── utils/           # Logger, crypto
├── tests/               # Unit & integration tests
├── config/              # default.yaml, production.yaml, local.yaml
├── package.json
├── tsconfig.json
└── README.md

Core Implementation

Configuration Management ( src/config/index.ts )

Uses a ConfigManager class that loads environment-specific YAML files ( development, production, local) with fallback defaults. Exposes a getDSAgentConfig() method to supply DSH SDK settings (model, API key, temperature, timeout).

Data Models ( src/models/Review.ts )

Defines TypeORM entities and enums: ReviewStatus: PENDING, RUNNING, COMPLETED, FAILED Severity: CRITICAL, HIGH, MEDIUM, LOW, INFO IssueCategory: BUG, SECURITY, STYLE, PERFORMANCE, BEST_PRACTICE, COMPLEXITY Review entity: UUID, provider, repository, PR number, commit SHA, status, files (JSONB), result (JSONB), error, timestamps ReviewResult interface: summary counts, issues array, markdown report, suggestions array Issue interface: file, line, column, category, severity, title, description, code snippet, suggestion, ruleId, CWE ID

Code Fetch Service ( src/services/CodeFetchService.ts )

Wraps GitHub/GitLab operations as DSH Tool objects. Provides fetchPRChanges, fetchFile, fetchBranchDiff methods that delegate to provider-specific tools. The GitHub tool supports actions: pr_changes, file, diff, comment.

Code Analysis Service ( src/services/CodeAnalysisService.ts )

Orchestrates four specialized analyzers plus an AI-enhanced pass:

LSP Analyzer : Iterates files, calls LspAnalyzer.analyze(file) for semantic diagnostics.

Security Analyzer : Runs SecurityAnalyzer.analyze(files) (detailed below).

Style Analyzer : Checks formatting and conventions.

Complexity Analyzer : Measures cyclomatic/cognitive complexity.

AI Analysis : Builds a prompt with up to 10 files (first 500 chars each), invokes the DSH Agent.run(), parses JSON response into Issue objects.

Results are merged, deduplicated (key = file:line:title), and summarized by severity counts.

Security Analyzer ( src/analyzers/SecurityAnalyzer.ts )

Implements 10 regex-based rules mapped to CWE IDs:

SEC001 – SQL Injection – CRITICAL – CWE-89 – Pattern:

/(?:execute|query|exec)\s*\(['"`].*\$\{|['"`].*\+.*(?:request|params|body|input)/gi

SEC002 – Cross-Site Scripting (XSS) – HIGH – CWE-79 – Pattern:

/(?:innerHTML|dangerouslySetInnerHTML|v-html|\.html\(\)).*(?:request|params|body|input|user)/gi

SEC003 – Hardcoded Credentials – CRITICAL – CWE-798 – Pattern:

/(?:password|secret|api[_-]?key|token)\s*[:=]\s*['"][^'"]{8,}['"]/gi

SEC004 – Insecure Random – MEDIUM – CWE-338 – Pattern: /Math\.random\(\)|new Random\(\)|Random\(\)\.next/g SEC005 – Eval Usage – HIGH – CWE-95 – Pattern: /\beval\s*\(|new Function\s*\(|Function\s*\(/g SEC006 – Path Traversal – HIGH – CWE-22 – Pattern:

/(?:readFile|readFileSync|open|createReadStream)\s*\(.*(?:request|params|body)\./gi

SEC007 – Command Injection – CRITICAL – CWE-78 – Pattern:

/(?:exec|spawn|execSync|system)\s*\(.*(?:request|params|body|input)/gi

SEC008 – Weak Cryptography (MD5, SHA1, DES, RC4) – MEDIUM – CWE-327 – Pattern: /md5|sha1|des\b|rc4/i SEC009 – Sensitive Data Logging – HIGH – CWE-532 – Pattern:

/console\.(?:log|debug|info)\s*\(.*(?:password|secret|token|key|credential)/gi

SEC010 – JWT None Algorithm – CRITICAL – CWE-347 – Pattern: /algorithm\s*:\s*['"]?none['"]?/gi For each file, iterates rules, uses matchAll to find occurrences, computes line numbers, extracts ±50-char code snippets, and emits Issue objects with ruleId and cweId.

GitHub Integration

Webhook Handling ( src/integrations/github.ts )

GitHubIntegration

class verifies HMAC-SHA256 signatures via crypto.timingSafeEqual, parses pull_request payloads into structured objects (repo, PR number, commit SHA, base/head refs, author), and posts review comments via the GitHub REST API ( POST /repos/{owner}/{repo}/issues/{pr_number}/comments).

GitHub App Authentication ( src/integrations/github-app.ts )

GitHubAppAuth

generates short-lived (10 min) RS256 JWTs (header: alg: RS256, typ: JWT; payload: iat, exp, iss: appId), lists installations, and exchanges JWTs for installation access tokens via POST /app/installations/{id}/access_tokens.

Report Generation

Markdown Report ( src/services/ReportService.ts )

ReportService.generateMarkdown()

assembles sections: header (emoji-coded overall status), summary table (counts per severity), critical/high issues (with file:line, category, ruleId, code snippet, suggestion), medium issues, suggestions, and per-file detail lists. Includes a weighted scoring function (CRITICAL=50, HIGH=30, MEDIUM=10, LOW=3, INFO=0) yielding ratings: ✅ Excellent (0), ✅ Good (<30), ⚠️ Needs Improvement (<100), ❌ Major Overhaul (≥100).

PR Comment Template ( src/services/CommentService.ts )

Produces a concise Markdown comment for the PR: overview badge, stats table, severity breakdown, top 5 critical/high issues with file:line links, and a footer disclaimer.

Notification Service

DingTalk Notifier ( src/integrations/dingtalk.ts )

DingTalkNotifier.send(title, content)

computes a timestamped HMAC-SHA256 signature (string-to-sign = timestamp\nsecret), posts a markdown message to the webhook URL with timestamp and sign query parameters, and validates HTTP response.

Workflow Orchestration

Main Workflow ( workflows/code-review.yaml )

DSH YAML workflow with variables ( review_id, repo, pr_number, commit_sha) and seven steps:

receive_request : Webhook trigger, extracts variables.

fetch_changes : Calls code_fetch.get_pr_changes, outputs files and stats.

parallel_analysis : Four parallel branches — lsp_analysis, security_scan, style_check, ai_analysis — each consuming files and emitting issues.

generate_report : Merges all issues, produces report and summary.

update_status : Persists COMPLETED status, result summary, completion timestamp to reviews table.

post_comment : Posts generated markdown to the PR via github.post_comment.

send_notification : Sends DingTalk alert with PR number and issue count.

Error handling: on failure, logs error and updates review status to FAILED with error message.

Deployment

Dockerfile

Multi-stage build: node:20-alpine builder installs production deps, compiles TypeScript; production stage copies dist/ and node_modules/ as non-root user (UID 1001), adds health check ( wget /health), and runs node dist/main.js.

Docker Compose

Three services: app (build from Dockerfile, port 3000, env vars from .env, depends on healthy db and redis), db (PostgreSQL 15 Alpine with volume and pg_isready health check), redis (Redis 7 Alpine with redis-cli ping health check).

Kubernetes ( k8s/deployment.yaml )

Deployment (3 replicas, resource requests 256Mi/250m, limits 512Mi/500m, liveness/readiness probes on /health and /ready), ClusterIP Service (port 80 → 3000), Ingress (TLS, host api.example.com, path /). Secrets referenced for DATABASE_URL and LLM_API_KEY.

Testing

Unit Tests ( tests/unit/SecurityAnalyzer.test.ts )

Vitest suite for SecurityAnalyzer:

Detects SQL injection (template literal in db.execute) → expects SEC001, CRITICAL.

Detects hardcoded password string → expects SEC003.

Validates clean code (env var password, parameterized query) produces zero CRITICAL issues.

Integration Tests ( tests/integration/github-integration.test.ts )

Tests GitHubIntegration.verifySignature with a known-good HMAC, and parseWebhook field extraction (PR number, repo, commit SHA, author).

Key Takeaways

Modular Design : Each capability isolated for testability and maintainability.

Configuration Separation : Environment-specific YAML files.

Security First : Webhook signature verification, encrypted secrets.

Extensibility : Plugin interfaces for new analyzers.

Observability : Health checks, metrics, structured logging.

Discussion Questions

How to handle performance for large repositories?

How to reduce false positives and improve accuracy?

How to support multi-language code review?

Assignments

Required : Understand architecture, implement a simple security analyzer, configure GitHub webhook, run integration tests. Advanced : Full GitLab integration, add performance analyzer, deploy to Kubernetes, implement history queries.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DockerTypeScriptKubernetessecurity scanningGitHub integrationDeepSeek Harnesscode review agentLSP analysis
AI Digital Ideal
Written by

AI Digital Ideal

Express ideas with code, expand imagination with AI.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.