Zero Labs
Industry News / AI

Your CI Pipeline Wasn’t Built for AI Code. Here’s How to Fix It.

Source · Towards AI By Christopher Montes

From the publisher’s feed, collected in the ZeroLabs newsroom.

Source: Image by Greg Daines on UnsplashEvery AI-generated PR on our team passes CI on the first try.That should be reassuring. It isn’t.I recently saw it play out on an ambitious AI-powered sales platform I consulted on. The platform comprised several microservices totaling about 130,000 lines of Python and TypeScript. The team was using Claude Code and Cursor-based AI agents for most new development. CI pipeline: ruff for linting and formatting, pyright for type checking, and pytest with coverage. All on GitHub Actions.Between mid-2025 and February 2026, dozens of AI-generated PRs shipped with green builds, clean reviews, and approvals from experienced engineers. Then someone ran an audit.The signature incident was a PR from October 2025. An AI agent built a UniversalContextEnricher service — 450 lines of Python with custom keyword-matching for "semantic similarity":async def _calculate_semantic_similarity(...) -> float: current_topics = current_content.lower().split() overlap_count = sum(1 for topic in past_topics if any(word in current_topics for word in topic.lower().split())) return overlap_count / len(past_topics) if past_topics else 0.0Meanwhile, the codebase had SemanticMemory.hybrid_search(), a production-tested, embedding-based semantic search that was roughly 10x better at the same job.The AI didn’t know it existed. The CI pipeline didn’t check. The PR passed.This is the core problem: your CI pipeline was built to catch the mistakes humans make. Syntax errors. Missing tests. Style violations. Known CVEs. LLM-based coding agents don’t make those mistakes. They make different ones — DRY violations at scale, outdated dependencies, duplicate infrastructure, and missing integration points. Your pipeline was never designed to look for them.And right now, it isn’t.Why Green Builds Don’t Mean Good Code AnymoreTraditional CI gates check for human failure modes. Those gates work exactly as intended.Linters catch inconsistent style. Type checkers catch type mismatches. Coverage requirements catch untested code. Vulnerability scanners catch known CVEs. A human who commits code that passes all of this has at least attempted to think through their changes.LLM-generated code passes all of these too. It lints perfectly. It generates tests that hit coverage targets, even if those tests are shallow. It follows your style conventions. It doesn’t introduce syntax errors. This is not a failure of the models — it’s a failure of the pipeline to check for what the models actually get wrong.The aforementioned code duplication audit found duplicates scattered across all seven services:78 duplicate rate-limiting implementations49 duplicate retry logic implementations30 duplicate circuit breakers28 duplicate vector and embedding operations~15,000 lines of code across 187 files marked for removal4 of 29 supposedly complete tasks that failed to wire into centralized infrastructureAll green builds. All reviewed. All merged.These failures cluster into three categories that your pipeline misses:Bloat and repetition. No standard linter checks whether a 400-line utility duplicates existing code elsewhere in the repo. No tool flags when you’ve added a test file with dozens of copy-pasted setup methods that should be a shared fixture. LLMs don’t have full repository context when generating code — they optimize for local correctness in the current file, not system-wide coherence [1].Stale dependencies and patterns. Version pinning checks exist, but most teams don’t enforce “never use a dependency more than one major version behind latest” or “flag any import of this deprecated module.” If your team moved from moment.js to date-fns in 2022, your linter doesn't know. Neither does the LLM — it was trained on code from an era where the old library was standard.Duplicate infrastructure and missing integration. No automated check verifies “does this new payment handler wire into your error tracking system?” or “does this new service initialize the request ID context the way every other service does?” LLM agents build things that work in isolation. They don’t see your system’s logging, error tracking, feature flags, event bus, or monitoring. They can’t see what should be wired together.Every one of these categories sails through traditional gates untouched.The Gates You’re MissingHere are four gates designed specifically to catch LLM code failure modes. Each addresses a different category of damage. Each is implementable today with tools you already have.Gate 1: Duplication and Bloat DetectionWhat it catches: Utility functions, API clients, or helpers that duplicate existing code. Test files with repetitive patterns that should be fixtures. PRs that are dramatically larger than the ticket scope.The team built a duplication checker as their first CI job, before linting, before tests. It analyzed the codebase for duplicated rate limiting logic, retry patterns, and circuit breakers. It ran in 4 seconds. After deployment, it caught every subsequent attempt to introduce a duplicate rate limiter. Not a single one slipped through, and not a single legitimate PR was blocked.How to implement it: Start with a tool like jscpd (JavaScript), Simian, or SonarQube’s duplication detection configured with lower thresholds than defaults. Set sensible starting points: flag duplications above 20 lines or 5 blocks of identical logic. Don’t make it a hard block yet — make it a required comment: “This PR adds 120 lines of duplicate client code. This is intentional because [reason].”For test files specifically, add a heuristic that flags files where more than 70% of test functions share identical setup and only vary one parameter. That’s the signature of LLM-generated tests — high coverage, high repetition, low verification.For PR size, track the relationship between ticket complexity and PR size. Flag outliers with a required justification. “Small feature” PRs that touch 15 files and add 450 lines need explanation — and with agent-driven development, this pattern shows up constantly because the LLM doesn’t scope its changes to what’s needed.Enforcement: Run as a warning on most PRs. Make it blocking for high-risk categories (rate limiters, auth, billing logic).Example GitHub Actions workflow:- name: Check for infrastructure duplication run: | python tools/check_infrastructure_duplication.py \ --check-rate-limiters \ --check-retry-logic \ --check-circuit-breakers \ --fail-on-high-confidenceGate 2: Dependency and Pattern FreshnessWhat it catches: Pinned dependencies more than one major version behind latest. Deprecated APIs and patterns your team has moved past. Code that contradicts your architectural decisions.The audit found several instances of pinned dependencies from 2024 being used in new code written in 2025. Not security vulnerabilities — just stale. The codebase had moved to a different approach, but the LLM’s training data hadn’t caught up. This is a fundamental limitation of code generation models: their knowledge has a cutoff, and your codebase evolves faster than their training data [2].How to implement it: Create a simple script that checks any new dependency in package.json (or requirements.txt for Python) against the latest registry version. Flag major version gaps:import subprocessimport jsonimport sysdef check_dependency_freshness(requirements_file, max_major_gap=1): with open(requirements_file) as f: for line in f: package, version = parse_requirement(line) latest = get_latest_version(package) if version_gap(version, latest) > max_major_gap: print(f"WARNING: {package}=={version} is outdated. Latest: {latest}")def get_latest_version(package): result = subprocess.run( ["pip", "index", "versions", package], capture_output=True, text=True ) return parse_version_output(result.stdout)Add a machine-readable “deprecated patterns” file to your repo. List each deprecated import, pattern, or API:deprecated_patterns: - pattern: "from moment import" replacement: "from datetime import" reason: "Moved to stdlib datetime in 2023" deprecated_since: "2023-06-15" - pattern: "old_payment_client.charge()" replacement: "payment_service.charge()" reason: "Old client removed from production Jan 2025" deprecated_since: "2024-12-01"Then add a CI step that greps for these patterns and fails if any are found in new code:for pattern in $(yq -r '.deprecated_patterns[].pattern' deprecated.yaml); do if git diff origin/main HEAD | grep -q "$pattern"; then echo "FAIL: Deprecated pattern found: $pattern" exit 1 fidoneEnforcement: Block for major version gaps and known deprecated patterns. Warn for minor version drift.Gate 3: Integration CompletenessWhat it catches: Code that works in isolation but doesn’t wire into your system’s logging, error tracking, feature flags, event bus, or monitoring.This is where the team took a different approach. They built a pre-coding discovery tool that runs before the AI agent even starts writing, showing what infrastructure already exists for a given task. This reduced false positives from 96% to 15.3% because the agent could see what to wire into before making decisions. This is the difference between treating LLM agents as code generators and treating them as junior engineers who need onboarding [3].How to implement it: First, maintain a checklist of “must-integrate” systems. For most teams, this includes:Request logging and tracing (OpenTelemetry, structured logs, request IDs)Error tracking (Sentry, DataDog, custom handler)Authentication middlewareFeature flagsEvent bus or async job queueDatabase connection poolingCreate a CI gate that scans for these patterns. Use tools like Dependency Cruiser (JavaScript/TypeScript) or ArchUnit (Java) to enforce architectural rules. For custom checks, write a simple static analysis:import astimport sysdef check_integration_completeness(file_path): with open(file_path) as f: tree = ast.parse(f.read()) imports = set() for node in ast.walk(tree): if isinstance(node, ast.Import): imports.update(alias.name for alias in node.names) elif isinstance(node, ast.ImportFrom) and node.module: imports.add(node.module) if 'fastapi' in imports or 'flask' in imports: if 'sentry_sdk' not in imports and 'datadog' not in imports: print(f"WARN: {file_path} defines an endpoint but doesn't import error tracking") return False return TrueAdd a “missing file” check: if a PR adds a new endpoint but doesn’t update your route registry, API documentation, or integration tests, flag it. This catches a specific LLM blind spot — code that builds one component without the supporting structure.Enforcement: Warnings for new services or endpoints that don’t reference logging or error tracking. Blocking for critical integration points: auth, billing, PII handling.Gate 4: Test Quality Beyond CoverageWhat it catches: LLM-generated tests that inflate coverage numbers without testing real behavior. Tests that only verify happy paths. Low-quality assertions.High coverage doesn’t mean good tests. LLMs are exceptionally good at generating tests that hit every line of code while validating almost nothing. A test that just calls a function and asserts the result isn’t falsy has 100% coverage but zero actual verification. This is arguably the most insidious failure mode because it gives teams false confidence in code they’ve never actually tested [4].How to implement it: Use mutation testing. Tools like Stryker (JavaScript), mutmut (Python), or PIT (Java) generate mutations in your code (changing operators, removing lines, inverting conditions) and check whether your tests catch them. LLM-generated tests often have 90%+ coverage but low mutation scores (40–60%) because they don’t assert specific behavior [5].// High coverage, low mutation score — the LLM defaulttest('calculateTotal returns a number', () => { const result = calculateTotal([10, 20, 30]); expect(result).toBeDefined(); // Catches nothing});// Verifies actual behavior - catches mutationstest('calculateTotal sums all items correctly', () => { const result = calculateTotal([10, 20, 30]); expect(result).toBe(60);});Add assertion density checks. Count unique assertion types per test file. Flag files where every test uses only .toBeDefined() or .toHaveLength(). Variety in assertions suggests you're actually testing different behaviors.Track negative test ratio: what percentage of tests verify error cases, edge cases, boundary conditions? Flag test suites that are >80% happy path. LLMs tend to skip the unhappy paths because they require more contextual reasoning about how the system should fail.Example Stryker configuration:{ "mutate": ["src/**/*.js"], "testRunner": "jest", "mutationThreshold": 75, "dashboard": { "baseUrl": "https://dashboard.stryker.mutant-testing.com", "reportType": "all" }, "checkStrictlyRequired": true}Run mutation testing asynchronously (it’s slow) but report the results as a PR comment. If your mutation score is 40%, that’s useful feedback even if it’s not a merge blocker.Enforcement: Warn on mutation scores below 70%. Team-defined thresholds. Don’t block on first implementation — gather data, then decide what’s too low.Building the Pipeline Without Slowing It DownAdding gates sounds great until your CI pipeline goes from 5 minutes to 25. Then you have a different problem.Don’t add all four gates to every PR. Consider using a tier system like the one I discussed in The AI Coding Bottleneck Keeping Developer Teams at 1x:Tier 1 (automated only): Standard linting, formatting, existing tests. Fast. Runs on every PR. 2–3 minutes.Tier 2 (enhanced): Add duplication detection and dependency freshness. Runs on PRs that touch shared code or add dependencies. 5–7 minutes.Tier 3 (full): All gates including mutation testing and integration completeness. Runs on high-risk PRs (auth, billing, core infrastructure). 10–15 minutes.This is how we scaled it. The duplication check ran only on PRs that modified services, clients, or shared utilities. Average CI time stayed at 6 minutes. High-risk PRs got the full suite and ran in 12 minutes, which was acceptable because they happened less frequently.Run expensive checks asynchronously. Mutation testing can report results as a GitHub comment without blocking the merge. Duplication analysis can flag files for human review without preventing the merge. This separates “we need to talk about this” from “you can’t merge this.”Start with warnings, not blocks. Introduce new gates as informational. Track the hit rate for a month. Does your duplication gate fire on every AI-generated PR? On 20% of them? Never? That tells you whether it’s catching real problems or just creating noise.Gates that fire frequently on problems you care about become blockers. Gates with high false-positive rates stay as warnings or get tuned. The data should drive the decision, not philosophy.What To Do NextYour CI pipeline was built to catch bugs that humans write. LLM agents don’t write those bugs. They write different ones — bloated, stale, isolated from the system they should extend. They all pass your existing gates with flying colors.Start here:Audit against the four gates. Which ones do you have? Which are you missing entirely? Duplication detection exists in most codebases. The other three are rarely built.Start with Gate 1. Duplication detection is the easiest to add and catches the most common LLM failure mode. Run jscpd on your last 20 AI-generated PRs and see what surfaces. We found over 400 lines of duplicate HTTP client code in our first scan.Create a deprecated patterns file. Maintenance this week, not next month. Add one entry per week as your team evolves. Even a simple grep-based CI step checking for deprecated imports is a huge improvement over nothing.After we ran duplication detection and consolidated, the codebase went from 15,000 lines of duplicate code down to 1,500. A 90–98% reduction. The duplication check prevented it from creeping back. The ROI paid for itself in 3 weeks.Your fix isn’t more human review. Humans can’t catch what they can’t see. It’s teaching your pipeline what to look for in a world where the code is always syntactically perfect and sometimes fundamentally wrong.References[1] Faros AI, “The AI Productivity Paradox: Why More Code Doesn’t Equal Better Outcomes,” Faros AI Blog, 2025. Available: https://www.faros.ai/blog/ai-software-engineering[2] CodeRabbit, “Measuring What Matters in AI-Assisted Development,” CodeRabbit Blog, 2025. Available: https://www.coderabbit.ai/blog/measuring-what-matters-in-the-age-of-ai-assisted-development[3] Speedscale, “Testing AI Code in CI/CD Made Simple for Developers,” Speedscale Blog, 2025. Available: https://speedscale.com/blog/testing-ai-code-in-cicd-made-simple-for-developers/[4] Propel, “Setting Up Code Quality Gates,” Propel Blog, 2025. Available: https://www.propelcode.ai/blog/continuous-integration-code-quality-gates-setup-guide[5] Aikido, “Continuous Code Quality in CI/CD,” Aikido Blog, 2025. Available: https://www.aikido.dev/blog/continuous-code-quality-ci-cdYour CI Pipeline Wasn’t Built for AI Code. Here’s How to Fix It. was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.