Track Autonomous Agent Commits in Memgraph (Cypher)

Developer reviewing git commit history on a monitor to track autonomous coding agent changes in a graph database

Your coding agents are pushing commits, and a flat git log tells you very little about which ones matter. Who (or what) wrote them, which files keep getting touched, and where is risky code being changed without a human looking? This guide shows how to load GitHub commit history into Memgraph, tag agent-authored commits, and query the result so you can audit what autonomous agents are doing to your code.

Why a graph fits commit history better than a log

A commit log is a list. The questions you actually care about when agents write code are relationships: which author touched which files, which files change together, which agent-tagged commits landed on which branches, and who reviewed them. Those are joins in SQL and one-line traversals in a graph.

Here is the model we'll use throughout:

(:Author {login, email})-[:AUTHORED]->(:Commit {sha, message, ts, agent})
(:Commit)-[:IN_REPO]->(:Repo {full_name})
(:Commit)-[:CO_AUTHORED_BY]->(:Author)
(:Commit)-[:TOUCHES {additions, deletions}]->(:File {path})

Nothing exotic. The value is that "show me every file that agent-tagged commits touched in the last 14 days, grouped by directory" becomes a short Cypher query instead of a script.

Memgraph is a reasonable fit here. The main repo describes it as an open-source, in-memory, Cypher-compatible graph database built in C++, aimed at GraphRAG, AI memory, agentic AI and real-time analytics. For a commit graph measured in thousands to low millions of nodes, in-memory is more than enough.

One licensing note before you build on it: Memgraph Community is under the Business Source License 1.1. Per Memgraph's own explanation, you can use it in production for internal business purposes, but embedding it in a distributed product, offering it as database-as-a-service, or building a competing product needs a commercial license. Internal agent auditing is squarely the first category. If you plan to ship this inside a product you sell, read the license first.

Step 1: Start Memgraph and decide how you'll identify agent commits

Run Memgraph locally with Docker. Add the schema-info flag now so you can use SHOW SCHEMA INFO later (it is also what lets an LLM inspect your schema through the MCP server):

docker run -d --name memgraph -p 7687:7687 -p 7444:7444 \
  memgraph/memgraph-mage \
  --schema-info-enabled=True

The harder design question is the signal for "this commit was written by an agent." There is no single reliable one. Your options:

Signal Reliability Notes
Co-Authored-By: Claude ... trailer Medium Claude Code adds a Co-Authored-By trailer naming the model by default
Dedicated bot account / author email High Best if you control the agent's git identity
Branch naming convention (agent/*) Medium Only works if your agents follow it
Commit message prefix Low Easy to drift

The trailer is convenient, but do not treat it as an audit-grade signal on its own. Claude Code's attribution is controlled by a setting in settings.json, and it can be disabled or customized. Third-party write-ups, such as this one on how Claude Code's Co-Authored-By attribution works and this one on removing it, disagree on the exact trailer text (the model name varies), and I could not retrieve official Anthropic documentation for the setting, so check the current Claude Code settings docs before relying on specifics. In code, match the pattern Co-Authored-By: Claude rather than a hardcoded full string.

My recommendation: give every agent its own git identity (a dedicated author name and email), use the trailer as a secondary signal, and flag the disagreement between the two. A commit that looks agent-written but has a human identity and no trailer is exactly the kind of thing an audit should surface.

Step 2: Pull commits from the GitHub REST API

The endpoint is GET /repos/{owner}/{repo}/commits. Per GitHub's community documentation, it is paginated (default 30 per page, max 100) and supports sha (branch) and since/until (date range) parameters.

Rate limits shape how you design the pull. According to the GitHub REST API rate limit docs, unauthenticated requests get 60 per hour and authenticated users get 5,000 per hour. Secondary limits cap you at 100 concurrent requests shared between REST and GraphQL; exceeding a limit returns 403 or 429, and you should honor the retry-after and x-ratelimit-reset headers.

In practice: use a token, request per_page=100, paginate sequentially, and use since so repeat runs only fetch new commits.

Note that the list endpoint returns commit metadata but not per-file changes. For file-level data you need a second call per commit (GET /repos/{owner}/{repo}/commits/{ref}), which multiplies your request count. Start with commit-level data, and fetch file details only for commits you flag as agent-authored.

import csv, os, re, time, requests

TOKEN = os.environ["GITHUB_TOKEN"]
HEADERS = {"Authorization": f"Bearer {TOKEN}",
           "Accept": "application/vnd.github+json"}
AGENT_TRAILER = re.compile(r"co-authored-by:\s*claude", re.I)

def fetch_commits(owner, repo, since_iso):
    url = f"api.github.com
    params = {"per_page": 100, "since": since_iso}
    while url:
        r = requests.get(url, headers=HEADERS, params=params)
        if r.status_code in (403, 429):
            wait = int(r.headers.get("retry-after", 60))
            time.sleep(wait)
            continue
        r.raise_for_status()
        yield from r.json()
        url = r.links.get("next", {}).get("url")
        params = None  # next URL already carries the query string

def to_row(owner, repo, c):
    msg = c["commit"]["message"]
    author = (c.get("author") or {}).get("login") or c["commit"]["author"]["name"]
    return {
        "sha": c["sha"],
        "repo": f"{owner}/{repo}",
        "author": author,
        "email": c["commit"]["author"]["email"],
        "ts": c["commit"]["author"]["date"],
        "message": msg.splitlines()[0][:200],
        "agent": "true" if AGENT_TRAILER.search(msg) else "false",
    }

def export(owner, repo, since_iso, path):
    with open(path, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=[
            "sha","repo","author","email","ts","message","agent"])
        w.writeheader()
        for c in fetch_commits(owner, repo, since_iso):
            w.writerow(to_row(owner, repo, c))

export("memgraph", "ai-toolkit", "2026-10-01T00:00:00Z", "commits.csv")

Two things worth noticing. The author field on the API response can be null when GitHub can't map the commit email to an account, so the code falls back to the git author name. And the agent column is a string, because the next step reads CSV, which has no types.

I'm pointing the example at Memgraph's ai-toolkit repo, which the org lists as open-source tooling for persistent agent memory, GraphRAG and MCP integrations. Swap in your own repos; they will be far more interesting to you.

Step 3: Load the CSV into Memgraph with MERGE

Memgraph's LOAD CSV reads a file row by row and binds each row to a variable. Per the import docs, it supports http/https/ftp URLs and S3, and handles gzip or bzip2 compressed files. Three constraints matter for this job:

  1. LOAD CSV parses everything as strings, so timestamps and numbers need conversion (LOAD CSV clause).
  2. It is not a standalone clause and can be used at most once per query.
  3. For MERGE-based loads, create indexes first, or the load degrades badly as the graph grows (import docs).

Create the indexes:

CREATE INDEX ON :Commit(sha);
CREATE INDEX ON :Author(email);
CREATE INDEX ON :Repo(full_name);

Then load. Using MERGE makes the ingest idempotent: Memgraph's MERGE creates the pattern only if it doesn't exist and supports ON CREATE / ON MATCH, so you can re-run the pipeline on overlapping date windows without creating duplicates.

LOAD CSV FROM "/var/lib/memgraph/import/commits.csv" WITH HEADER AS row
MERGE (r:Repo {full_name: row.repo})
MERGE (a:Author {email: row.email})
  ON CREATE SET a.login = row.author
MERGE (c:Commit {sha: row.sha})
  ON CREATE SET c.message = row.message,
                c.ts = localDateTime(replace(replace(row.ts, "T", " "), "Z", "")),
                c.agent = (row.agent = "true")
MERGE (a)-[:AUTHORED]->(c)
MERGE (c)-[:IN_REPO]->(r);

The timestamp handling is the fiddly part: GitHub returns ISO 8601 with a T and a trailing Z, and the replace calls reshape it for localDateTime. Test this against a handful of rows before trusting a full load, because date parsing is where CSV imports usually break. Likewise c.agent is converted from the string "true" to a real boolean.

Memgraph also supports batched loading with USING PERIODIC COMMIT and CALL {...} IN TRANSACTIONS OF n ROWS (the docs examples use 1000 rows). You won't need it for a few thousand commits, but it matters if you backfill years of history across many repos.

Step 4: Cypher queries that answer real audit questions

Now the payoff. These all run against the model above.

How much of recent activity is agent-authored, per repo?

MATCH (c:Commit)-[:IN_REPO]->(r:Repo)
WHERE c.ts > localDateTime() - duration({day: 30})
RETURN r.full_name AS repo,
       count(c) AS total,
       sum(CASE WHEN c.agent THEN 1 ELSE 0 END) AS agent_commits
ORDER BY agent_commits DESC;

Which authors have agent-flagged commits, and how many?

MATCH (a:Author)-[:AUTHORED]->(c:Commit {agent: true})
RETURN a.login, a.email, count(c) AS n
ORDER BY n DESC;

This is the identity-mismatch check from Step 1. If a human email shows up here with a high count, either that person pairs heavily with an agent or someone is committing agent output under their own name. Both are worth knowing.

Commits with an agent trailer but no dedicated agent identity (assuming your agent accounts use a known email domain; adjust the pattern):

MATCH (a:Author)-[:AUTHORED]->(c:Commit {agent: true})
WHERE NOT a.email ENDS WITH "@agents.yourcompany.com"
RETURN c.sha, a.email, c.message, c.ts
ORDER BY c.ts DESC
LIMIT 50;

Daily agent commit volume, to spot bursts:

MATCH (c:Commit {agent: true})
RETURN c.ts.year AS y, c.ts.month AS m, c.ts.day AS d, count(c) AS n
ORDER BY y, m, d;

A sudden spike after you changed a prompt or loosened a permission is the kind of signal this catches early.

File-level hotspots (once you've added File nodes and TOUCHES edges for flagged commits):

MATCH (c:Commit {agent: true})-[t:TOUCHES]->(f:File)
RETURN f.path, count(c) AS agent_touches,
       sum(t.additions) AS added, sum(t.deletions) AS removed
ORDER BY agent_touches DESC
LIMIT 20;

Anything in auth/, billing/, migrations, or CI config that appears here repeatedly deserves a human review rule.

Run SHOW SCHEMA INFO; to confirm the labels and properties match what you intended. This is where the --schema-info-enabled=True flag from Step 1 pays off.

Step 5: Let an agent query the graph through MCP

Once the data is in, you probably don't want to hand-write Cypher every time. Memgraph's official MCP server lets an LLM do it. Per the Docker Hub listing, mcp-memgraph is read-only by default, exposes tools such as run_query, get_schema and get_page_rank, and uses streamable-http transport by default. The playbooks.com MCP listing describes the same server. The tool list, defaults, image name, and environment variable names differ between sources and versions, so follow the mcp-memgraph README for the exact docker run command, and set the Memgraph connection URL via the environment variable documented there.

Keep the read-only default. The point of this setup is auditing agents, so the thing doing the auditing should not be able to rewrite the evidence. Give it read access, let it answer "which agent commits touched billing code this week?", and keep write credentials out of that path entirely.

A related option: Memgraph's AI Toolkit includes a Context Graph package that, per the supported agents docs, gives coding agents (Claude Code, Codex, GitHub Copilot CLI, Cursor, and others) memory across sessions by installing hooks that record sessions. That is a different thing from what we built here. Context Graph records what the agent did and remembered inside sessions; the commit graph records what landed in the repository. Used together, you can connect "the agent's session" to "the commit it produced," but they solve separate problems, and I'd get the commit graph working first.

Step 6: Keep it current and know the limits

Refresh strategy. Run the export on a schedule (cron, a GitHub Action, or an n8n workflow) with since set to a few days back. Because ingestion uses MERGE, overlap is harmless. Persist the last successful timestamp so a failed run doesn't leave a gap.

An old tutorial, a caution. Memgraph published a tutorial on analyzing a GitHub commit stream that ingests commits from the NetworkX repo, runs PageRank on users and commits, and mentions the incremental pagerank_online module in MAGE. It's a good read for ideas on centrality over commit graphs, but it is several years old and its stream setup may be outdated. Don't connect to its stream endpoint without verifying it still exists; use the REST approach above instead.

Limits worth being honest about:

  • Attribution is soft. Trailers and naming conventions can be disabled, forgotten, or spoofed. This graph shows what agents declare about themselves, plus patterns. It is monitoring, not proof.
  • Commits are not behavior. A commit tells you what changed, not why the agent did it or what else it tried. For that you need session logs.
  • Rate limits cap backfills. Per-commit file lookups burn through your hourly request quota quickly. Fetch file details selectively.
  • Don't quote live counts. Commit totals and "last commit" dates in any repo change daily. Query them live rather than trusting a number in a blog post, including this one.

Where this sits in a wider stack: the commit graph is the audit and observability layer. Agents and workflow tools do the work, GitHub holds the artifacts, Memgraph models the relationships, and a scheduled job plus an MCP-connected reviewer closes the loop. It does not replace code review or branch protection; it tells you where to point them.

A pattern worth using for small teams

Once an agent can commit code or edit workflow definitions, someone needs to know what changed and whether a human saw it. Modeling that history as a graph helps for the reason described above: the relationships between agent identities, files, repos and reviewers are the interesting part, and a graph makes those queries cheap to write.

The practical pattern is the one in this post: a dedicated git identity per agent, a scheduled ingest into a graph, a handful of saved queries for the review rules that matter (sensitive paths, identity mismatches, activity bursts), and read-only access for whatever does the reviewing. It's unglamorous plumbing, but it is what makes it safer to let agents touch real systems.


Work with BizFlowAI

If you'd rather have this built for you, that's what we do: production AI automation for solo founders and small teams — agents, integrations, and document pipelines that actually ship.

Request a free discovery call — 30 minutes, we map the highest-ROI automation in your workflow. No pitch deck, just engineering.

More guides like this on the BizFlowAI blog.

Frequently asked questions

How do I identify which git commits were written by an AI coding agent?

There is no single reliable signal, so combine several. The strongest is a dedicated bot account or author email for each agent. Secondary signals include a Co-Authored-By trailer naming the model, which Claude Code adds by default but which can be disabled, plus branch naming conventions like agent/*. Flag commits where the signals disagree, since those are the ones an audit should surface.

Why use a graph database like Memgraph instead of git log for commit analysis?

A flat git log is a list, but the questions you ask about agent-written code are relationships: which author touched which files, which files change together, and which commits landed on which branches. In a graph these become short Cypher traversals instead of multi-table SQL joins or custom scripts. Memgraph is an in-memory, Cypher-compatible graph database, which is plenty for commit graphs with thousands to low millions of nodes.

How do I fetch commit history from the GitHub REST API without hitting rate limits?

Use an authenticated token, which raises the limit from 60 to 5,000 requests per hour. Request per_page=100, paginate sequentially, and use the since parameter so repeat runs only fetch new commits. If you receive a 403 or 429, honor the retry-after and x-ratelimit-reset headers. The list endpoint omits per-file changes, so only make the extra per-commit call for commits you care about.

How do I import a CSV of commits into Memgraph without creating duplicates?

Use LOAD CSV with MERGE instead of CREATE, so nodes are only created if they do not already exist and you can safely re-run overlapping date windows. Create indexes on the merge keys first (for example Commit.sha and Author.email), because MERGE-based loads degrade badly on large graphs without them. Remember LOAD CSV parses every value as a string, so convert timestamps and booleans in the query. It can be used at most once per query.

Can I use Memgraph Community for internal agent auditing in production?

Yes. Memgraph Community is licensed under the Business Source License 1.1, which allows production use for internal business purposes such as auditing your own agents' commits. You need a commercial license if you embed it in a distributed product, offer it as database-as-a-service, or build a competing product. If you plan to ship it inside something you sell, read the license before building.