How to Add a Code Originality Check to Your CI Pipeline

A code originality check in CI is a job that fingerprints every incoming source file, compares it against peer submissions, the public web, and an AI-generation model, then hands a pass, review, or block decision back to the merge gate. It is not a linter. It is not license scanning, though the two overlap. It answers a narrower question: did this code come from somewhere we didn't pay for?

Ours has been running on every pull request for eleven months. It blocks about 0.4% of them. Two of those blocks in March traced back to the same freelance contractor shipping near-identical TypeScript to two different clients, one of which was us, under a work-for-hire agreement that said the code was original. That single finding paid for the whole build.

Why a merge gate and not a quarterly audit

We tried the audit first. Legal asked for a review of contractor deliverables at the end of Q3, we pulled 34 repositories, and six weeks later we had a spreadsheet nobody trusted. The problem with retrospective review is that by the time you find the copy, the code is in production, the contractor's invoice is paid, and your only remedy is a conversation with a vendor who has already moved on to the next client.

A merge gate moves the conversation to the cheapest possible moment. The contractor is still on the contract. The code is still five files in a pull request instead of spread across a service. And there's an audit trail attached to the commit, which matters more than the detection itself when you're sitting across from procurement.

The tradeoff is obvious and I won't pretend otherwise: you're adding a scan to a path developers wait on. Ours costs 40 to 90 seconds depending on PR size. We accepted that because the alternative was a two-day manual review at the end of every sprint.

Fingerprints, not string matching, because contractors refactor

Every source code similarity engine worth running normalizes before it compares. The naive version is a diff, and a diff is useless here: rename a variable, reformat with Prettier, extract a method, and the text match drops to nothing while the logic stays identical. What you want is the token stream or the AST shape, with identifiers collapsed and whitespace destroyed.

Here's a method that came back at 91% in our very first scan, from a Java service:

public BigDecimal fetchRate(String isin) {
    BigDecimal rate = cache.lookup(isin);
    if (rate == null) {
        rate = upstream.get(isin);
        cache.put(isin, rate);
    }
    return rate;
}

And the version the second contractor delivered, which a plain text diff scores near zero:

private BigDecimal resolveRate(final String instrumentId) {
    BigDecimal cached = rateCache.lookup(instrumentId);
    if (cached != null) return cached;
    BigDecimal fresh = pricingUpstream.get(instrumentId);
    rateCache.put(instrumentId, fresh);
    return fresh;
}

Different names, different control flow shape on the surface, same token sequence once you replace every identifier with ID and every literal with LIT. That's the whole trick, and it's why source code plagiarism checker tools that only do string matching return a clean bill of health on code that two vendors clearly shared.

Codequiry web results tracing copied code to GitHub repositories and other web sources with per-domain scores
Web results: every domain a submission matched, scored per source, from GitHub repos to tutorial sites.

Wiring it into GitHub Actions

We run on GitHub Enterprise, self-hosted runners, ubuntu-24.04 images. The job is deliberately boring. It collects the changed source files, posts them as a check, polls for the report, and writes the outcome to both the build status and a SARIF file so the findings land in the security tab next to the CodeQL results.

name: originality-gate
on:
  pull_request:
    paths:
      - 'services/**'
      - 'packages/**'
jobs:
  fingerprint:
    runs-on: [self-hosted, linux, x64]
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - run: pip install requests==2.32.3
      - name: Collect changed sources
        run: python .ci/collect_diff.py "${{ github.event.pull_request.base.sha }}" > /tmp/changed.json
      - name: Submit for fingerprinting
        env:
          CODEQUIRY_API_KEY: ${{ secrets.CODEQUIRY_API_KEY }}
          PR_NUMBER: ${{ github.event.number }}
        run: python .ci/originality.py /tmp/changed.json

The submission script is about 90 lines, most of it retry logic. The shape:

import json, os, time, requests

API = "https://api.codequiry.com/v1"
H = {"Authorization": f"Bearer {os.environ['CODEQUIRY_API_KEY']}"}

paths = json.load(open("/tmp/changed.json"))
check = requests.post(f"{API}/checks", headers=H, json={
    "name": f"pr-{os.environ['PR_NUMBER']}",
    "language": "java",
    "engines": ["peer", "web", "ai"],
}).json()

for p in paths:
    with open(p, "rb") as fh:
        requests.post(f"{API}/checks/{check['id']}/submissions",
                      headers=H,
                      files={"file": (os.path.basename(p), fh)},
                      data={"submission": f"vendor-{os.environ['PR_NUMBER']}"},
                      timeout=60)

# poll until the scan reports a terminal state
while True:
    r = requests.get(f"{API}/checks/{check['id']}", headers=H).json()
    if r["status"] in ("complete", "failed"):
        break
    time.sleep(10)

Endpoint shapes drift, so read the current API reference before you copy that verbatim. Our version has three custom headers we added for internal routing that you don't need.

Codequiry API keys page with a masked key, signed webhook configuration and API resources
The API surface: an account key, signed webhooks for finished checks, and docs for wiring scans into CI.

The thresholds that survived contact with a real review queue

This is the part every blog post skips, and it's the only part that matters operationally. Set the block threshold too low and your reviewers stop reading. Set it too high and you catch nothing. We tuned for three sprints before the numbers settled.

SignalBlockReviewAuto-pass
Peer similarity (vendor vs. vendor)85%+60 to 84%under 60%
Web / GitHub match with license conflict70%+40 to 69%under 40%
AI generation scorenever80%+under 80%

Note the third row. We never block on an AI score alone. The AI code detector signal is good enough to route a file to a human and nowhere near good enough to reject a contractor's week of work. Generated code that a developer then edited heavily will often score in the 50s, and idiomatic boilerplate from a careful human can score high because it looks like everything else ever written in that language. Treat AI scores as a queue-sorting device.

Peer similarity is the opposite: when two vendor submissions hit 85%, that's near-conclusive in our pool, because the two teams have never met and don't share a codebase. The false positive risk is essentially a shared template or a shared generator, which we handle by fingerprinting generated directories out of the scan entirely.

The five weeks the gate passed everything

We shipped the job in June and it went green for a month and a half. Then a reviewer noticed manually that two vendors had submitted a nearly identical React router wrapper. The gate had scored one of them at 41%, under threshold.

The cause was pagination. The results endpoint returns 20 submissions per page, and my polling loop read page one and stopped. Our largest vendor ships 60 to 90 files per PR. Everything past file twenty was never scored at all, and because the check reported "complete," the build stayed green and the dashboard looked normal. We only found it because someone got suspicious for unrelated reasons.

Two fixes came out of that. First, the loop now walks pages until next_cursor is null. Second, and more important, we compare the count of submitted files against the count of scored files and fail the job if they diverge. Any gate that can't tell you what it didn't scan is a decoration.

Codequiry scan monitor mid-run at 92% with CPU and memory gauges and a live per-file activity log
A check in flight: live progress, resource gauges, and a per-file activity log as each submission is scored.

What this doesn't catch

Honest limits, because we've hit all of them.

Code copied from a private repository we also can't see is invisible to any web corpus. A contractor who lifts a module from a previous employer's proprietary codebase produces a file with no public match and no peer match. Nothing in a similarity engine finds that. What finds it is a contractual clause requiring disclosure plus a human who asks.

Inline Copilot completions inside a large hand-written file barely move the AI score, because the file is mostly human. That's a detection limit, not a tool bug, and anyone selling you 98% accuracy on "some AI was involved" is selling you a number.

And structurally, you need a real API. MOSS, which Stanford still runs, emails you an HTML page and doesn't do web corpora or AI scores. JPlag 4.x is solid and self-hostable but you own the storage, the queue, and the UI. Dolos 2.x has a genuinely nice interface and no hosted web-crawl corpus unless you build one. We picked Codequiry solutions for the combination we actually needed: one API call that returns peer, web, and AI signals together, with a hosted corpus we didn't have to assemble and a dashboard our legal team can read without me in the room.

Frequently asked questions

Does a code originality gate slow down the pull request flow?

Ours adds 40 to 90 seconds to PRs that touch source files, and zero to PRs that only touch docs or config because of the paths filter. The scan runs in parallel with the test suite, so in practice nobody waits on it unless the report flags something.

Can I run it on pull request diffs only instead of whole files?

You can, but fingerprints work better on complete compilation units. A diff loses the surrounding structure that token normalization depends on, and you'll get weaker matches. We submit whole changed files and let the engine handle the rest.

How does this differ from license scanning like FOSSA or Snyk?

License scanners read your dependency manifests and identify known packages. An originality gate reads the code you wrote or commissioned and asks whether it resembles something else. A snippet pasted from Stack Overflow with no attribution is invisible to a dependency scanner and obvious to a fingerprint match.

Should the AI score ever fail a build?

Not in our pipeline, and I'd push back on anyone who does it. Route high AI scores to a human reviewer, keep the score in the audit log, and let policy handle disclosure separately. The signal is too noisy to be a hard gate.

If you want to see what the report looks like before you wire anything into a pipeline, run a small set of vendor submissions through the code plagiarism checker and read the similarity view against files you already know are related. That tells you more about your thresholds than any documentation will.