Overview
You finish with a Git and DVC repository that rebuilds a clean Parquet table of 1.36 million commits, a marimo app that charts agent-attributed commits per repository, and two MLflow runs scored on held-out repositories. A fresh clone reproduces the same metrics files, so anyone can check the numbers in your write-up.
- A DVC pipeline whose
dvc repro --forceon a fresh clone writes metrics files identical to the committed ones. - A marimo app, opened with
marimo run app.py, where a repository dropdown redraws a monthly chart of agent-attributed commits beside a top-20 table. - An MLflow experiment with a logistic regression run and a gradient-boosted run, each scored on held-out repositories against a category baseline.
- A README that records the raw data hash and quotes how the dataset labels agent commits, plus a one-page write-up built from
reports/share_change.csv.
Tools
- DVC
DVC is free Apache 2.0 software. Remote storage and any separate hosting service require their own accounts and may incur charges.
- marimo
The local marimo notebook is free Apache 2.0 software. Hosted products, optional assistants and remote data services have separate terms; their paid entitlements are not established here.
- MLflow
The MLflow project is free Apache 2.0 software and can run on a local server. Managed hosting, storage and external model calls have separate charges.
Datasets
- Who Writes AI Code? 1.3M Open-Source AI Commits Kaggle
Commits from 118 AI repositories with the dataset's own measure of agent authorship feed the charts, the features and the classifier's labels.
Before you begin
Python 3.12
The pinned versions in requirements.txt were installed and run on Python 3.12. Check with python3 --version, or py -3.12 --version on Windows.
Git 2.x
Git is free. Check with git --version. DVC stores small pointer files in Git and keeps the data itself outside Git.
About 2 GB of free disk and 8 GB of RAM
The unzipped CSV files are about 305 MB, and DVC keeps a cache copy plus a copy in the local remote. Loading every row as text needs several gigabytes of memory.
A free Kaggle account, possibly optional
The public download worked without signing in when this guide was tested. If the Kaggle CLI asks for credentials, sign in to a free account and run kaggle auth login.
Working knowledge of pandas and scikit-learn
You should be able to read a groupby and know what a train and test split is. The guide explains average precision where it first appears.
Stage 01 · setup45 minutes
Set up the project and its tools
Create a Git repository with an isolated Python environment and confirm that DVC, marimo, MLflow and the Kaggle CLI run.
Every file in this build lives in one folder called ai-commits, and every command runs from its root. Create the folder, make it a Git repository and give it its own virtual environment.
mkdir ai-commits && cd ai-commits
git init
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pipmkdir ai-commits; cd ai-commits
git init
py -3.12 -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install --upgrade pipPin the versions so a fresh clone installs the same libraries. Model scores and Parquet output can shift between releases, and a shift would break the identical-metrics check at the end.
dvc==3.67.1
marimo==0.26.0
mlflow==3.18.0
scikit-learn==1.9.1
pandas==3.1.1
pyarrow==26.0.1
altair==6.3.0
pyyaml==6.0.4
kaggle==2.2.5
pip install -r requirements.txtTwo small files keep the repository clean. The .gitattributes file stores text with LF line endings on every platform, because DVC hashes file bytes and a Windows checkout with CRLF endings makes every stage look changed.
* text=auto eol=lf
.venv/
__pycache__/
mlflow.db
mlartifacts/
mlruns/
__marimo__/
dvc --version
marimo --version
mlflow --version
kaggle --version
python -c "import sklearn, pandas; print(sklearn.__version__, pandas.__version__)"3.67.1 0.26.0 mlflow, version 3.18.0 Kaggle CLI 2.2.5 1.9.1 3.1.1
All five version commands print the versions above, and git status lists the three new files as untracked.
Stage 02 · data45 minutes
Download the commits and version them with DVC
Put the raw Kaggle files under DVC, push them to a local remote and record their hash in the README.
The dataset is a public Kaggle download of about 83 MB zipped and 305 MB unzipped. The Kaggle CLI unzips it into data/raw and deletes the zip when you pass --unzip.
kaggle datasets download abirambharathisa/who-writes-ai-code-1-3m-open-source-ai-commits -p data/raw --unzipdata/
raw/
commits_2010_2021/
commits_2010_2021.csv
commits_2022_2023/
commits_2024/
commits_2025/
commits_2026/
releases.csv
repos.csv # one row per repositoryNow start DVC and point it at a local folder that plays the part of remote storage. The remote sits beside the project, so a clone in a sibling folder finds it through the same relative path.
dvc init
dvc remote add -d localstore ../dvc-store
dvc add data/raw
cat data/raw.dvcouts: - md5: <32 hex characters>.dir size: 304557345 nfiles: 7 hash: md5 path: raw
The .dir hash names the whole folder, so it changes if any raw file changes. Paste it into a new README, then commit and push the data to the remote.
# Agent-attributed commits in 118 open-source AI repositories
A DVC pipeline that cleans the Kaggle dataset "Who Writes AI Code? 1.3M Open-Source
AI Commits", a marimo app that charts each repository's agent-attributed share, and
MLflow-tracked classifiers scored on repositories held out from training.
## Data
- Source: https://www.kaggle.com/datasets/abirambharathisa/who-writes-ai-code-1-3m-open-source-ai-commits
- Author: Abiram Bharathi S.A., released under CC BY 4.0
(https://creativecommons.org/licenses/by/4.0/). Each source repository keeps its own license.
- Raw download tracked by DVC in `data/raw.dvc`
- Raw data hash (md5 from `data/raw.dvc`): PASTE-THE-MD5-HERE
git add .dvc .dvcignore data/.gitignore data/raw.dvc README.md requirements.txt .gitattributes .gitignore
git commit -m "Track raw commit data with DVC"
dvc pushcat .dvc/config shows a localstore remote, git status is clean, dvc push reports files pushed, and the folder ../dvc-store exists beside the project.
Stage 03 · data40 minutes
Read the columns and the label
Load a sample in pandas to learn which columns hold the label and its context, then quote the dataset's own labeling rule in the README.
Read a sample before writing any pipeline code. Loading every column as text with dtype=str avoids a mixed-type warning on ai_tool and shows each value exactly as the CSV stores it.
"""Print the columns and a few rows from one yearly commit file."""
import pandas as pd
sample = pd.read_csv(
"data/raw/commits_2026/commits_2026.csv",
nrows=5000,
dtype=str,
keep_default_na=False,
)
print(sample.dtypes)
print(sample.head(3).T)
print(sample["ai_assisted"].value_counts())
print(sample["author_type"].value_counts())
print(sample.loc[sample["ai_assisted"] == "True", ["ai_tool", "ai_model"]].value_counts().head(10))
python src/inspect_sample.pyrepo str category str commit_hash str author_datetime_utc str ... ai_assisted str ai_tool str ai_model str commit_type str message_title str dtype: object ... ai_assisted False <count> True <count>
Each yearly file has the same 16 columns. The table groups the ones this build uses, and its last row lists the fields that describe the author or the AI tool.
| Role | Columns | Use in this build |
|---|---|---|
| Repository | repo, category | Chart filter, split key and baseline group |
| Commit date | author_datetime_utc | Monthly chart plus the hour and weekday features |
| Label | ai_assisted | What the classifier predicts |
| Title and flags | message_title, commit_type, is_merge | Title length, scope and merge features |
| Author or tool fields | author_id, author_type, author_org, author_utc_offset, n_coauthors, ai_tool, ai_model, committer_datetime_utc | Dropped before features, since they encode the label |
The dataset page explains how a commit earns ai_assisted = True. Quote its lower-bound rule in the README and list the bot identities it tracks so readers know what the label measures.
## How the dataset attributes commits to agents
The dataset page on Kaggle describes its labels in these words:
> "AI-assisted is a lower bound. A commit is labeled only when an AI agent is the
> author or appears in a `Co-authored-by:` trailer."
The card notes that labels come from strict, known bot identities, such as
`copilot-swe-agent[bot]`, `devin-ai-integration[bot]`, Anthropic and OpenAI
`noreply` bot addresses, Cursor's `cursoragent` bot address, and the `(aider)`
author suffix.
This project predicts the `ai_assisted` column. A commit labeled `False` may still
have had help from a tool that left no trailer.
git add src/inspect_sample.py README.md
git commit -m "Inspect columns and document the label"The script prints 16 columns including repo and ai_assisted, and the README quotes the dataset's description of its agent labels.
Stage 04 · build1 hour
Write the cleaning stage
Add a DVC stage that writes one deduplicated Parquet table plus a metrics file of per-repository row counts.
The cleaning script joins the five yearly files and removes exact duplicate rows. It then removes repeated commit hashes, since a fork that imported its upstream history repeats the same commits in a second repository.
"""Stage 1: raw yearly CSV files to one clean Parquet table."""
import glob
import json
from pathlib import Path
import pandas as pd
RAW = "data/raw"
OUT = Path("data/clean/commits.parquet")
SUMMARY = Path("metrics/clean.json")
REPO_ROWS = Path("metrics/repo_rows.json")
def load_raw() -> pd.DataFrame:
files = sorted(glob.glob(f"{RAW}/**/commits_*.csv", recursive=True))
if not files:
raise SystemExit(f"No commits_*.csv files under {RAW}")
frames = [pd.read_csv(f, dtype=str, keep_default_na=False) for f in files]
return pd.concat(frames, ignore_index=True)
def main() -> None:
df = load_raw()
rows_in = len(df)
exact = int(df.duplicated().sum())
df = df.drop_duplicates()
# A fork that imported its upstream history repeats the same commit hash.
# Keep the copy in the larger repository so no commit sits in two splits.
size = df["repo"].map(df["repo"].value_counts())
df = df.assign(_size=size).sort_values(
["_size", "repo", "commit_hash"], ascending=[False, True, True]
)
shared = int(df.duplicated("commit_hash").sum())
df = df.drop_duplicates("commit_hash").drop(columns="_size")
df["author_datetime_utc"] = pd.to_datetime(df["author_datetime_utc"])
df["is_merge"] = df["is_merge"] == "True"
df["ai_assisted"] = df["ai_assisted"] == "True"
df["month"] = df["author_datetime_utc"].dt.to_period("M").dt.to_timestamp()
df = df.sort_values(["repo", "author_datetime_utc", "commit_hash"])
df = df.reset_index(drop=True)
OUT.parent.mkdir(parents=True, exist_ok=True)
SUMMARY.parent.mkdir(parents=True, exist_ok=True)
df.to_parquet(OUT, index=False)
summary = {
"rows_in": rows_in,
"exact_duplicates_removed": exact,
"shared_hash_duplicates_removed": shared,
"rows_out": len(df),
"repos": int(df["repo"].nunique()),
}
SUMMARY.write_text(json.dumps(summary, indent=2) + "\n", newline="\n")
counts = df["repo"].value_counts().sort_index()
REPO_ROWS.write_text(json.dumps(counts.to_dict(), indent=2) + "\n", newline="\n")
print(
f"clean: removed {exact} exact duplicate rows and "
f"{shared} shared-hash duplicates; wrote {len(df)} rows"
)
if __name__ == "__main__":
main()
Both JSON files are written with newline="\n" so Windows and Linux produce the same bytes. The stage declares them as metrics with cache: false, which keeps them in Git where a diff can compare them.
stages:
clean:
cmd: python src/clean.py
deps:
- src/clean.py
- data/raw
outs:
- data/clean/commits.parquet
metrics:
- metrics/clean.json:
cache: false
- metrics/repo_rows.json:
cache: false
dvc repro
dvc metrics show metrics/clean.jsonRunning stage 'clean': > python src/clean.py clean: removed <n> exact duplicate rows and <n> shared-hash duplicates; wrote <rows> rows Generating lock file 'dvc.lock' Path exact_duplicates_removed repos rows_in rows_out shared_hash_duplicates_removed metrics/clean.json <n> 118 <rows> <rows> <n>
git add src/clean.py dvc.yaml dvc.lock data/clean/.gitignore metrics
git commit -m "Add cleaning stage"
dvc pushdvc repro prints the line that starts clean: removed and writes data/clean/commits.parquet. A second dvc repro reports that stage clean did not change.
Stage 05 · build1 hour 15 minutes
Chart agent share in a marimo app
Build a marimo notebook with a repository dropdown that redraws a monthly commit chart beside a table of the 20 repositories with the highest agent share.
A marimo notebook is a Python file in which each cell is a function. Each function's arguments tell marimo which cells it depends on, so changing the dropdown reruns only the cells that read repo.value.
import marimo
__generated_with = "0.26.0"
app = marimo.App(width="full")
@app.cell
def _():
import altair as alt
import marimo as mo
import pandas as pd
return alt, mo, pd
@app.cell
def _(pd):
commits = pd.read_parquet(
"data/clean/commits.parquet", columns=["repo", "month", "ai_assisted"]
)
monthly = (
commits.groupby(["repo", "month", "ai_assisted"])
.size()
.rename("commits")
.reset_index()
)
monthly["attribution"] = monthly["ai_assisted"].map(
{True: "agent-attributed", False: "other"}
)
return commits, monthly
@app.cell
def _(commits, mo):
repo = mo.ui.dropdown(
options=sorted(commits["repo"].unique()),
value="mlflow/mlflow",
searchable=True,
label="Repository",
)
repo
return (repo,)
@app.cell
def _(alt, monthly, repo):
repo_chart = (
alt.Chart(monthly[monthly["repo"] == repo.value])
.mark_bar()
.encode(
x=alt.X("month:T", title="Month"),
y=alt.Y("commits:Q", title="Commits"),
color=alt.Color("attribution:N", title="Attribution"),
tooltip=["month:T", "attribution:N", "commits:Q"],
)
.properties(title=f"Monthly commits in {repo.value}", width=620, height=320)
)
return (repo_chart,)
@app.cell
def _(commits, mo):
by_repo = commits.groupby("repo")["ai_assisted"].agg(["mean", "size"])
top20 = (
by_repo[by_repo["size"] >= 500]
.sort_values("mean", ascending=False)
.head(20)
.rename(columns={"mean": "agent_share", "size": "commits"})
.round({"agent_share": 4})
.reset_index()
)
top20_view = mo.vstack([
mo.md("**Top 20 repositories by agent share, 500 or more commits**"),
mo.ui.table(top20, selection=None, page_size=20),
])
return (top20_view,)
@app.cell
def _(mo, repo_chart, top20_view):
mo.hstack([repo_chart, top20_view], justify="start", gap=2)
return
if __name__ == "__main__":
app.run()
The table keeps repositories with 500 or more commits, because a share computed from a few dozen commits swings with each one. Lower the cutoff if you want small projects in the list.
marimo check app.py
marimo edit app.pyThe editor opens in your browser with the code visible. When the cells run without errors, stop it with Ctrl+C and open the same file as an app, which hides the code and shows only the outputs.
marimo run app.py Running app.py
URL: http://localhost:<port>git add app.py
git commit -m "Add marimo app"marimo check app.py prints nothing, and in marimo run picking another repository from the dropdown redraws the bar chart with that name in its title while the top-20 table stays beside it.
Stage 06 · build1 hour
Build features and split by repository
Add a feature stage that leaves out every author and tool field, and a split stage that holds out whole repositories in a tracked file.
Features come only from the commit title, the commit type, the repository category and the commit time. The LEAKY list names the fields the script drops, matching the last row of the column table.
"""Stage 2: per-commit features that do not describe the author or the tool."""
from pathlib import Path
import pandas as pd
SRC = "data/clean/commits.parquet"
OUT = Path("data/features/features.parquet")
# Columns that record who wrote the commit or which AI tool did. The dataset
# derives ai_assisted from these, so a model that sees them reads the label.
LEAKY = [
"author_id", "author_type", "author_org", "author_utc_offset",
"n_coauthors", "ai_tool", "ai_model", "committer_datetime_utc",
]
CATEGORICAL = ["category", "commit_type"]
NUMERIC = [
"title_chars", "title_words", "hour_utc", "weekday",
"is_merge", "has_issue_ref", "has_backticks", "has_scope",
]
FEATURES = CATEGORICAL + NUMERIC
def main() -> None:
df = pd.read_parquet(SRC).drop(columns=LEAKY)
title = df["message_title"].fillna("")
out = pd.DataFrame({
"repo": df["repo"],
"label": df["ai_assisted"].astype(int),
"category": df["category"],
"commit_type": df["commit_type"].replace("", "none"),
"title_chars": title.str.len(),
"title_words": title.str.split().str.len().fillna(0).astype(int),
"hour_utc": df["author_datetime_utc"].dt.hour,
"weekday": df["author_datetime_utc"].dt.day_of_week,
"is_merge": df["is_merge"].astype(int),
"has_issue_ref": title.str.contains(r"#\d+", regex=True).astype(int),
"has_backticks": title.str.contains("`", regex=False).astype(int),
"has_scope": title.str.match(r"^\w+\(.+?\)!?:").astype(int),
})
OUT.parent.mkdir(parents=True, exist_ok=True)
out.to_parquet(OUT, index=False)
print(f"features: {len(out)} rows, {len(FEATURES)} features: {FEATURES}")
if __name__ == "__main__":
main()
A random split of commits would put rows from the same repository on both sides, and the models would learn each project's habits. The split script holds out whole repositories, sampling separately from repositories with and without agent commits.
"""Stage 3: hold out whole repositories for testing."""
import json
import random
from pathlib import Path
import pandas as pd
import yaml
OUT = Path("splits/test_repos.json")
def main() -> None:
params = yaml.safe_load(open("params.yaml"))["split"]
df = pd.read_parquet("data/clean/commits.parquet", columns=["repo", "ai_assisted"])
has_agent = df.groupby("repo")["ai_assisted"].any()
rng = random.Random(params["seed"])
test = []
# Sample within each group so the test set has repos with and without agent commits.
for flag in (True, False):
repos = sorted(has_agent[has_agent == flag].index)
rng.shuffle(repos)
test += repos[: round(len(repos) * params["test_fraction"])]
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps({"test_repos": sorted(test)}, indent=2) + "\n", newline="\n")
print(f"split: {len(test)} test repos, {len(has_agent) - len(test)} train repos")
if __name__ == "__main__":
main()
split:
test_fraction: 0.25
seed: 48
train:
seed: 48
logreg_C: 1.0
hgb_learning_rate: 0.1
hgb_max_iter: 200
features:
cmd: python src/features.py
deps:
- src/features.py
- data/clean/commits.parquet
outs:
- data/features/features.parquet
split:
cmd: python src/split.py
deps:
- src/split.py
- data/clean/commits.parquet
params:
- split
outs:
- splits/test_repos.json:
cache: false
dvc repro
git add src/features.py src/split.py params.yaml dvc.yaml dvc.lock data/features/.gitignore splits
git commit -m "Add features and repository split"Running stage 'features': > python src/features.py features: <rows> rows, 10 features: ['category', 'commit_type', 'title_chars', ...] Running stage 'split': > python src/split.py split: <n> test repos, <n> train repos
splits/test_repos.json lists about a quarter of the repositories, and python -c "import pandas as pd; print(pd.read_parquet('data/features/features.parquet').columns.tolist())" shows no author or AI tool column.
Stage 07 · test1 hour 30 minutes
Train two models and track them in MLflow
Train a logistic regression and a gradient-boosted model on training repositories and log their held-out scores to a local MLflow server.
Start the tracking server in a second terminal, from the project root with the virtual environment active. With no store options, MLflow 3 writes run data to mlflow.db and artifacts to mlartifacts/ in that folder, and .gitignore already excludes both.
mlflow server --host 127.0.0.1 --port 5000Average precision summarizes the precision-recall curve as a weighted mean of precision at each threshold. It suits this task because only a few percent of commits carry the label, and a model that gives every commit the same score earns an average precision equal to that small rate.
The baseline gives each held-out commit the agent share of its category in the training repositories. A model has to beat that number to show that titles and timing add anything beyond the project type.
"""Stage 4: train two models on train repos, score held-out repos, log to MLflow."""
import json
import os
import sys
from pathlib import Path
import mlflow
import numpy as np
import pandas as pd
import yaml
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (average_precision_score, precision_recall_curve,
precision_score, recall_score)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from features import CATEGORICAL, FEATURES, NUMERIC
METRICS = Path("metrics/train.json")
PER_REPO = Path("metrics/per_repo.json")
def r6(x: float) -> float:
return round(float(x), 6)
def load():
df = pd.read_parquet("data/features/features.parquet")
test_repos = set(json.load(open("splits/test_repos.json"))["test_repos"])
is_test = df["repo"].isin(test_repos)
return df[~is_test].reset_index(drop=True), df[is_test].reset_index(drop=True)
def baseline_scores(train: pd.DataFrame, test: pd.DataFrame) -> np.ndarray:
share = train.groupby("category")["label"].mean()
overall = train["label"].mean()
return test["category"].map(share).fillna(overall).to_numpy()
def build_models(p: dict) -> dict:
logreg = make_pipeline(
ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore"), CATEGORICAL),
("num", StandardScaler(), NUMERIC),
]),
LogisticRegression(C=p["logreg_C"], class_weight="balanced", max_iter=1000),
)
hgb = HistGradientBoostingClassifier(
learning_rate=p["hgb_learning_rate"],
max_iter=p["hgb_max_iter"],
class_weight="balanced",
random_state=p["seed"],
)
return {"logreg": logreg, "hgb": hgb}
def as_model_input(name: str, X: pd.DataFrame) -> pd.DataFrame:
if name == "hgb": # HistGradientBoosting reads pandas categoricals natively
X = X.astype({c: "category" for c in CATEGORICAL})
return X
def per_repo_ap(test: pd.DataFrame, scores: np.ndarray) -> dict:
out = {}
for repo, idx in test.groupby("repo").groups.items():
y = test.loc[idx, "label"]
# Average precision is undefined for a repo with no agent commits.
out[repo] = r6(average_precision_score(y, scores[idx])) if y.any() else None
return dict(sorted(out.items()))
def pr_points(y, scores, n=200) -> dict:
precision, recall, _ = precision_recall_curve(y, scores)
keep = np.unique(np.linspace(0, len(recall) - 1, n).astype(int))
return {"recall": recall[keep].round(4).tolist(),
"precision": precision[keep].round(4).tolist()}
def main() -> None:
# MLflow prints an emoji after each run; a cp1252 console on Windows cannot encode it.
sys.stdout.reconfigure(encoding="utf-8")
p = yaml.safe_load(open("params.yaml"))["train"]
train, test = load()
y_train, y_test = train["label"], test["label"]
base = baseline_scores(train, test)
results = {"baseline_average_precision": r6(average_precision_score(y_test, base)),
"test_rows": len(test), "test_positive_rate": r6(y_test.mean())}
per_repo = {"baseline": per_repo_ap(test, base)}
mlflow.set_tracking_uri(os.environ.get("MLFLOW_TRACKING_URI", "http://127.0.0.1:5000"))
mlflow.set_experiment("agent-commits")
for name, model in build_models(p).items():
model.fit(as_model_input(name, train[FEATURES]), y_train)
scores = model.predict_proba(as_model_input(name, test[FEATURES]))[:, 1]
preds = (scores >= 0.5).astype(int)
m = {
"precision": r6(precision_score(y_test, preds, zero_division=0)),
"recall": r6(recall_score(y_test, preds)),
"average_precision": r6(average_precision_score(y_test, scores)),
"baseline_average_precision": results["baseline_average_precision"],
}
results[name] = m
per_repo[name] = per_repo_ap(test, scores)
with mlflow.start_run(run_name=name):
mlflow.log_params({"model": name, **p, "n_features": len(FEATURES)})
mlflow.log_metrics(m)
mlflow.log_dict({"features": FEATURES}, "features.json")
mlflow.log_dict(pr_points(y_test, scores), "pr_curve.json")
mlflow.log_dict(per_repo[name], "per_repo_ap.json")
print(f"train: {name} average_precision={m['average_precision']}")
METRICS.write_text(json.dumps(results, indent=2) + "\n", newline="\n")
PER_REPO.write_text(json.dumps(per_repo, indent=2) + "\n", newline="\n")
if __name__ == "__main__":
main()
Both models use class_weight="balanced", so a 0.5 threshold still flags a useful share of the rare positive commits. Every score is rounded to six decimals, which keeps the metrics files byte for byte stable between runs.
train:
cmd: python src/train.py
deps:
- src/train.py
- src/features.py
- data/features/features.parquet
- splits/test_repos.json
params:
- train
metrics:
- metrics/train.json:
cache: false
- metrics/per_repo.json:
cache: false
dvc repro
dvc metrics show metrics/train.jsonRunning stage 'train': > python src/train.py train: logreg average_precision=<value> train: hgb average_precision=<value>
Open the MLflow UI at the server address and select the agent-commits experiment. Tick both runs and click Compare to see their parameters and metrics side by side.
For the deliverable, export the comparison to a CSV that the write-up can cite. The script reads every run in the experiment, best first.
"""Write the MLflow runs of the agent-commits experiment to a CSV for the write-up."""
import os
from pathlib import Path
import mlflow
mlflow.set_tracking_uri(os.environ.get("MLFLOW_TRACKING_URI", "http://127.0.0.1:5000"))
runs = mlflow.search_runs(
experiment_names=["agent-commits"],
order_by=["metrics.average_precision DESC"],
)
cols = ["run_id", "tags.mlflow.runName", "start_time", "params.model",
"metrics.precision", "metrics.recall", "metrics.average_precision",
"metrics.baseline_average_precision"]
Path("reports").mkdir(exist_ok=True)
runs[cols].to_csv("reports/mlflow_runs.csv", index=False, lineterminator="\n")
print(runs[cols].head(10).to_string(index=False))
python src/export_runs.py
git add src/train.py dvc.yaml dvc.lock metrics src/export_runs.py reports/mlflow_runs.csv
git commit -m "Train and track models"The MLflow UI lists at least two runs named logreg and hgb, each with precision, recall, average_precision and baseline_average_precision, and reports/mlflow_runs.csv has one row per run.
Stage 08 · build40 minutes
Show the best run in the app
Add marimo cells that load the best finished MLflow run and draw its precision-recall curve next to the repository chart.
The training script logged each run's curve as pr_curve.json, so the app needs no model file. The new cell asks MLflow for the finished run with the highest average precision and reads that artifact back as a dictionary.
Delete the last cell of app.py from the marimo stage, the one that calls mo.hstack([repo_chart, top20_view], ...). Paste these three cells in its place, above the if __name__ == "__main__": line.
@app.cell
def _():
import os
import mlflow
mlflow.set_tracking_uri(
os.environ.get("MLFLOW_TRACKING_URI", "http://127.0.0.1:5000")
)
best = mlflow.search_runs(
experiment_names=["agent-commits"],
filter_string="attributes.status = 'FINISHED'",
order_by=["metrics.average_precision DESC"],
max_results=1,
).iloc[0]
curve = mlflow.artifacts.load_dict(f"runs:/{best.run_id}/pr_curve.json")
return best, curve
@app.cell
def _(alt, best, curve, pd):
pr_chart = (
alt.Chart(pd.DataFrame(curve))
.mark_line()
.encode(
x=alt.X("recall:Q", title="Recall"),
y=alt.Y("precision:Q", title="Precision"),
)
.properties(
title=(
f"Best run: {best['tags.mlflow.runName']}, AP "
f"{best['metrics.average_precision']:.3f} on held-out repos"
),
width=420,
height=320,
)
)
return (pr_chart,)
@app.cell
def _(mo, pr_chart, repo_chart, top20_view):
mo.vstack([
mo.hstack([repo_chart, pr_chart], justify="start", gap=2),
top20_view,
])
return
The filter on attributes.status skips a run that crashed partway and has no curve artifact. The app reads from the MLflow server, so keep the second terminal open.
marimo check app.py
marimo run app.pygit add app.py
git commit -m "Show the best run's precision-recall curve"The app shows the monthly chart beside a precision-recall line whose title names the best run and its average precision. Changing the dropdown redraws only the repository chart.
Stage 09 · ship1 hour 15 minutes
Reproduce from a fresh clone and write it up
Add the share-change report, push everything, rebuild the pipeline in a fresh clone and confirm the metrics files match.
The write-up needs the repositories whose agent share changed most. This stage compares the 12 months up to the last commit in the data with the 12 months before, for repositories with at least 200 commits in each window.
"""Stage 5: which repositories' agent share changed most between two 12-month windows."""
from pathlib import Path
import pandas as pd
OUT = Path("reports/share_change.csv")
MIN_COMMITS = 200 # skip windows too small for a share to mean much
def main() -> None:
df = pd.read_parquet("data/clean/commits.parquet",
columns=["repo", "author_datetime_utc", "ai_assisted"])
end = df["author_datetime_utc"].max().normalize()
start_late = end - pd.DateOffset(months=12)
start_early = end - pd.DateOffset(months=24)
window = pd.Series(pd.NA, index=df.index, dtype="string")
t = df["author_datetime_utc"]
window[(t > start_early) & (t <= start_late)] = "earlier"
window[t > start_late] = "later"
df = df.assign(window=window).dropna(subset=["window"])
g = df.groupby(["repo", "window"])["ai_assisted"].agg(["mean", "size"]).unstack()
g.columns = [f"{stat}_{w}" for stat, w in g.columns]
g = g[(g["size_earlier"] >= MIN_COMMITS) & (g["size_later"] >= MIN_COMMITS)]
g["share_change"] = g["mean_later"] - g["mean_earlier"]
g = g.sort_values("share_change", ascending=False).round(4)
OUT.parent.mkdir(parents=True, exist_ok=True)
g.to_csv(OUT, lineterminator="\n")
print(f"report: {len(g)} repos compared, windows end {end.date()}")
print(g.head(10)[["mean_earlier", "mean_later", "share_change"]])
if __name__ == "__main__":
main()
report:
cmd: python src/share_change.py
deps:
- src/share_change.py
- data/clean/commits.parquet
outs:
- reports/share_change.csv:
cache: false
dvc repro
git add src/share_change.py dvc.yaml dvc.lock reports/share_change.csv
git commit -m "Add share change report"
dvc pushNow clone the repository into a sibling folder, build a new environment there and pull the data. Keep the MLflow server running, because the train stage logs two more runs when it reruns.
cd ..
git clone ai-commits ai-commits-check
cd ai-commits-check
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
dvc pull
dvc statuscd ..
git clone ai-commits ai-commits-check
cd ai-commits-check
py -3.12 -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
dvc pull
dvc statusData and pipelines are up to date.
An up-to-date pipeline would skip every stage, so force a full rebuild. Then compare the regenerated metrics against the committed originals with DVC and with Git.
dvc repro --force
dvc metrics diff
git diff --exit-code -- metrics splits reports/share_change.csv && echo "metrics match"clean: removed <n> exact duplicate rows and <n> shared-hash duplicates; wrote <rows> rows ... train: hgb average_precision=<value> report: <n> repos compared, windows end <date> metrics match
An empty dvc metrics diff means no metric changed. Copy the top rows of reports/share_change.csv and the scores into the write-up, then commit it in the original folder.
# Agent share in 118 AI repositories: write-up
## Repositories whose agent share changed most
Source: `reports/share_change.csv` (the 12 months to the last commit in the data,
against the 12 months before that, repositories with 200 or more commits in both).
| Repository | Earlier share | Later share | Change |
| --- | --- | --- | --- |
| (copy the top five rows) | | | |
Name the repositories, then describe what the marimo chart shows for two of them:
a steady rise, or a jump that starts in one month.
## How well commit metadata predicts agent attribution
Source: `metrics/train.json`, `metrics/per_repo.json`, `reports/mlflow_runs.csv`.
| Model | Pooled average precision | Precision | Recall |
| --- | --- | --- | --- |
| Category-share baseline | | n/a | n/a |
| Logistic regression | | | |
| Gradient boosting | | | |
Per held-out repository: list where the best model beats the baseline and where it
does not. Repositories with no agent commits have no average precision (null).
## Limits
The labels are a lower bound (see README). Commit titles are the only text feature.
cd ../ai-commits
git add reports/writeup.md
git commit -m "Add write-up"In ai-commits-check, dvc repro --force finishes every stage and dvc metrics diff prints nothing. The Git check then prints metrics match.
Troubleshooting
The train stage fails with Max retries exceeded for 127.0.0.1:5000.
The MLflow server is not running, or it listens on another address. Start mlflow server --host 127.0.0.1 --port 5000 in a second terminal with the virtual environment active, or set MLFLOW_TRACKING_URI to the address you used.
On macOS, port 5000 is already in use before MLflow starts.
The AirPlay Receiver often holds port 5000 on recent macOS versions. Start the server with --port 5001 and run export MLFLOW_TRACKING_URI=http://127.0.0.1:5001 in every terminal that runs dvc repro or marimo run.
A script that logs MLflow runs on Windows stops with UnicodeEncodeError: 'charmap' codec can't encode character.
MLflow prints an emoji after each run, and a cp1252 console cannot encode it. Keep the sys.stdout.reconfigure(encoding="utf-8") line in train.py, or set PYTHONUTF8=1 before running other scripts that start runs.
After cloning on Windows, dvc status reports every source file as modified.
Git converted the line endings to CRLF on checkout. Add the .gitattributes file from the setup stage, run git add --renormalize . and commit in the original folder, then clone again.
dvc repro fails with ModuleNotFoundError: No module named 'mlflow' or a similar import error.
DVC runs each cmd with the first python on your PATH. Activate .venv in that terminal before dvc repro, and confirm with python -c "import mlflow".
The clean stage is killed or raises MemoryError while reading the CSV files.
Reading every column as text needs several gigabytes. Close other programs, or pass usecols= to pd.read_csv with only the columns that later stages read.
The marimo app shows IndexError: single positional indexer is out-of-bounds in the MLflow cell.
The search found no finished run in the agent-commits experiment. Run dvc repro with the server up, then reload the app.
Done when
- dvc repro on a fresh clone finishes and produces metrics files identical to the originals.
- Running marimo run opens the notebook as an app, and changing the dropdown redraws the chart.
- The MLflow UI lists at least two runs with precision, recall and average precision on held-out repositories.
- The README quotes the dataset's own description of how it attributes commits to agents.
- Each run of the cleaning stage reports how many duplicate rows it removed.
Deliverables
- A repository containing dvc.yaml, the stage scripts and the marimo notebook.
- An exported MLflow comparison of the trained runs.
- A one-page write-up naming the repositories whose agent share changed most over the dataset's period.
How to measure it
Average precision for agent attribution on repositories held out from training, compared with a baseline that assigns every commit the agent share of its repository category in the training repositories. Report the pooled score and the score for each held-out repository.
Going further
- Score each held-out repository month by month and check whether precision falls in the months after a new tool first appears in
ai_tool. - Train on
ai_toolas a multi-class target, still without author fields, and report which tools leave the most recognizable commit titles. - Replace the local folder remote with an S3 or Google Cloud Storage bucket, and note the storage charges for the raw folder and its cache.
- Add a
plotssection todvc.yamlthat draws the logged precision-recall points, sodvc plots diffcompares curves between Git commits.
Bounty stretch goals
- Test whether commit-title keywords alone match the full feature set, and log the comparison as its own MLflow run.
- Export the marimo notebook as a WebAssembly HTML file that runs in a browser without a Python server.
- Add a DVC parameter for the date cutoff and compare model scores before and after a chosen month.
References
- Who Writes AI Code? 1.3M Open-Source AI Commits (Kaggle dataset page and Croissant metadata)
- Kaggle CLI documentation: authentication
- Kaggle CLI documentation: datasets commands
- DVC command reference: add
- DVC command reference: remote add
- DVC user guide: dvc.yaml files
- DVC command reference: repro
- DVC command reference: metrics diff
- marimo guide: run notebooks as apps
- marimo CLI reference
- marimo API: dropdown
- marimo API: table
- marimo API: hstack and vstack
- MLflow Tracking
- MLflow tracking server
- MLflow Python API: mlflow module
- MLflow Python API: mlflow.artifacts
- scikit-learn: average_precision_score
- scikit-learn: HistGradientBoostingClassifier
Reporting behind this quest
- Coding agents are growing up at the review desk 2026-11-24 · source
- Factory reports different completion rates across coding harnesses 2026-11-23 · source
- DVC connects a Git revision to the data an experiment used 2026-11-25 · source
- marimo keeps notebook outputs connected to their inputs 2026-11-25 · source
An AI guide writer drafted this walkthrough against the official documentation above, automated template and style checks validated every block, and an independent AI reviewer verified commands, flags and claims before publication.
