Quest 01 / 04 · Quick buildTier 01 · Daily

Bounty boards / Daily · Monday, November 23, 2026

Build an offline code-review buddy

  • Inkling 2 Mini
  • Time100 minutes
  • Stages5
  • BoardMonday, November 23, 2026

Overview

You finish with a small Python command that sends a Git diff to Inkling 2 Mini running in Ollama on your own machine and prints three review comments tied to changed lines. A demo run over five sample diffs with the network disconnected records every comment with its response time, plus the memory Ollama reports for the model.

  • Inkling 2 Mini downloaded once and answering on 127.0.0.1:11434 with no network connection.
  • A review.py command that prints three comments, each tied to a file and new line number and quoting the code from that line.
  • Five sample diffs in diffs/ and a demo run that saves results/comments.csv and results/runs.csv.
  • A scorecard that counts useful comments, false positives, response times and the loaded model size.
01SETUP30 minutesInstall Ollama and d...02DATA10 minutesMake five sample diffs03BUILD15 minutesNumber the changed l...04BUILD20 minutesAsk the model for th...05TEST25 minutesRun the five diffs w...
DATAGit diff fileCODEdiffparse.pyCODEreview.pyTOOLOllama on 127.0.0.1MODELInkling 2 MiniSTOREresults CSV filesUSERYour verdictsunified diffnumbered added lines/api/chat with schemacomments and timinguseful or false positive
One diff goes in, three line-linked comments and a timing row come out.

Tool

Inkling 2 Mini

Download the weights first and use hardware supported by the model's local inference setup.

Announcement

Thinking Machines released open weights for a looped model that can run locally, with a reported memory footprint of about 20 GB.

Official announcement · 2026-11-20

Before you begin

A Mac with 32 GB of memory or more, a DGX Spark, or a GPU with 32 GB of VRAM

Those are the local setups listed across the launch note, the Ollama library page and the model card. Pulling the weights takes roughly 20 GB of disk space.

Ollama, free

Install it from the Ollama download page and check it with ollama -v.

Python 3.10 or newer, free

Check the version with python --version. The scripts use only the standard library.

Git, free

Check the version with git --version. The sample diffs come from a throwaway repository the guide creates.

Basic terminal and Python reading skills

You will run short Python scripts and edit one CSV file by hand.

Stage 01 · setup30 minutes

Install Ollama and download the model

Get Inkling 2 Mini answering locally while the network is still connected.

Every step that needs the internet comes first. After the pull finishes, the model weights sit on your disk and Ollama serves them from 127.0.0.1:11434, so the review demo can run with Wi-Fi off.

Install Ollama with the command for your platform. The macOS and Windows commands come from the Ollama download page, which also links a manual installer for each.

bash
# macOS or Linux
curl -fsSL https://ollama.com/install.sh | sh
ollama -v
powershell
# Windows
irm https://ollama.com/install.ps1 | iex
ollama -v

Create the project folder and an isolated Python environment. The scripts use only the standard library, so the environment stays empty. It still keeps this project apart from your other Python work.

bash
mkdir review-buddy
cd review-buddy
python -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\Activate.ps1

Pull the model and send it one prompt. The latest tag is the 19 to 20 GB build listed on the Ollama library page.

bash
ollama pull inkling-2-mini
ollama run inkling-2-mini "Reply with the word ready."
ollama ps
Output
NAME                    ID            SIZE      PROCESSOR    ...
inkling-2-mini:latest   <model id>    <size>    <cpu/gpu split>    ...
Stage 01 Checkpoint

ollama run prints a reply, and ollama ps lists inkling-2-mini with a SIZE and a PROCESSOR value. Note the PROCESSOR column: 100% GPU means the whole model fits in GPU or unified memory.

Stage 02 · data10 minutes

Make five sample diffs

Create five small diffs with known problems so you can judge the comments.

The bounty names no dataset, so you make your own test material. The script below builds a one-file Git repository and writes five diffs, each with one planted problem. The problems are an off-by-one loop, a removed bounds check, SQL built from a string, a swallowed exception and a hard-coded token.

pythonmake_samples.py
"""Create a tiny Git repository and five sample diffs to review."""
import subprocess
from pathlib import Path

BASE = '''"""Tiny shopping cart used for the review demo."""


def subtotal(items):
    total = 0
    for item in items:
        total += item["price"] * item["qty"]
    return total


def apply_discount(total, percent):
    if percent < 0 or percent > 100:
        raise ValueError("percent must be between 0 and 100")
    return round(total * (100 - percent) / 100, 2)


def find_item(items, sku):
    for item in items:
        if item["sku"] == sku:
            return item
    return None
'''

CHANGES = {
    "01-loop": ('    for item in items:\n        total +=',
                '    for i in range(len(items) - 1):\n        item = items[i]\n        total +='),
    "02-discount": ('    if percent < 0 or percent > 100:\n        raise ValueError("percent must be between 0 and 100")\n    return round(total * (100 - percent) / 100, 2)',
                    '    return round(total * percent / 100, 2)'),
    "03-sql": ('    return None\n',
               '    return None\n\n\ndef load_cart(db, user_id):\n    return db.execute(f"SELECT * FROM carts WHERE user = \'{user_id}\'")\n'),
    "04-except": ('    return total\n',
                  '    return total\n\n\ndef safe_subtotal(items):\n    try:\n        return subtotal(items)\n    except Exception:\n        return 0\n'),
    "05-token": ('"""Tiny shopping cart used for the review demo."""\n',
                 '"""Tiny shopping cart used for the review demo."""\n\nPAYMENT_TOKEN = "test-token-123"\nprint("charging with", PAYMENT_TOKEN)\n'),
}


def git(*args):
    subprocess.run(["git", "-C", "sample-repo", *args], check=True, capture_output=True)


repo = Path("sample-repo")
(repo / "shop").mkdir(parents=True, exist_ok=True)
target = repo / "shop" / "cart.py"
target.write_text(BASE, encoding="utf-8", newline="\n")
git("init", "-q")
git("add", "shop/cart.py")
git("-c", "user.name=demo", "-c", "user.email=demo@localhost", "commit", "-q", "-m", "base cart")

Path("diffs").mkdir(exist_ok=True)
for name, (old, new) in CHANGES.items():
    assert old in BASE, name
    target.write_text(BASE.replace(old, new, 1), encoding="utf-8", newline="\n")
    diff = subprocess.run(["git", "-C", "sample-repo", "diff"], check=True, capture_output=True, text=True).stdout
    Path("diffs", f"{name}.diff").write_text(diff, encoding="utf-8", newline="\n")
    git("checkout", "--", "shop/cart.py")
    print(f"wrote diffs/{name}.diff ({diff.count(chr(10))} lines)")
bash
python make_samples.py
Output
wrote diffs/01-loop.diff (<n> lines)
wrote diffs/02-discount.diff (<n> lines)
wrote diffs/03-sql.diff (<n> lines)
wrote diffs/04-except.diff (<n> lines)
wrote diffs/05-token.diff (<n> lines)
Stage 02 Checkpoint

The diffs/ folder holds five .diff files, and each starts with a diff --git a/shop/cart.py b/shop/cart.py line.

Stage 03 · build15 minutes

Number the changed lines

Turn a unified diff into a list of added lines with their new line numbers.

Each hunk header such as @@ -3,7 +3,8 @@ gives the starting line in the new file. From there, context lines and added lines move the counter forward, while removed lines do not exist in the new file and leave it alone.

pythondiffparse.py
"""Find the added lines in a unified diff, with their new line numbers."""
import re

HUNK = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@")


def changed_lines(diff_text):
    """Return (path, line_number, text) for every added line."""
    path, line_no, found = None, 0, []
    for raw in diff_text.splitlines():
        if raw.startswith("+++ "):
            target = raw[4:].strip()
            path = None if target == "/dev/null" else target.removeprefix("b/")
            line_no = 0
        elif raw.startswith("@@"):
            match = HUNK.match(raw)
            line_no = int(match.group(1)) if match else 0
        elif path is None or line_no == 0:
            continue
        elif raw.startswith("+"):
            found.append((path, line_no, raw[1:]))
            line_no += 1
        elif raw.startswith(("-", "\\")):
            continue
        else:
            line_no += 1
    return found


if __name__ == "__main__":
    import sys
    from pathlib import Path
    for path, number, text in changed_lines(Path(sys.argv[1]).read_text(encoding="utf-8")):
        print(f"{path}:{number}: {text}")
bash
python diffparse.py diffs/01-loop.diff
Output
shop/cart.py:6:     for i in range(len(items) - 1):
shop/cart.py:7:         item = items[i]
Stage 03 Checkpoint

The loop diff prints lines 6 and 7 of shop/cart.py, and blank added lines are skipped later by review.py. Every sample diff prints at least one numbered line.

Stage 04 · build20 minutes

Ask the model for three linked comments

Send the diff and its numbered lines to Ollama and check every comment against a changed line.

The Ollama chat endpoint accepts a JSON schema in format, so the model has to answer with a comments array of file, line and comment objects. The script also hands the model the list of added lines, which gives it valid targets to point at.

pythonreview.py
"""Ask a local Inkling 2 Mini for three review comments on one diff."""
import json
import sys
import time
import urllib.request
from pathlib import Path

from diffparse import changed_lines

OLLAMA_URL = "http://127.0.0.1:11434/api/chat"
MODEL = "inkling-2-mini"
SCHEMA = {
    "type": "object",
    "properties": {"comments": {"type": "array", "items": {
        "type": "object",
        "properties": {"file": {"type": "string"}, "line": {"type": "integer"},
                       "comment": {"type": "string"}},
        "required": ["file", "line", "comment"]}}},
    "required": ["comments"],
}
PROMPT = """You are reviewing a Git diff. Write exactly three focused review comments.
Each comment must name one of the added lines listed below by its file and line number.
Prefer bugs, security problems and missing error handling over style. Keep each comment under 40 words.

Diff:
{diff}

Added lines you may comment on (file:line: code):
{lines}
"""


def ask_model(prompt, num_predict=2048):
    body = {"model": MODEL, "stream": False, "format": SCHEMA,
            "messages": [{"role": "user", "content": prompt}],
            "options": {"num_ctx": 16384, "num_predict": num_predict}}
    request = urllib.request.Request(OLLAMA_URL, data=json.dumps(body).encode("utf-8"),
                                     headers={"Content-Type": "application/json"})
    start = time.perf_counter()
    with urllib.request.urlopen(request, timeout=900) as response:
        reply = json.load(response)
    return reply, time.perf_counter() - start

The second half parses the reply and checks every comment against the set of added lines. A comment that names any other line is kept but flagged, so you can count it as a miss later.

pythonreview.pyAppend this to the same file.
def review(diff_path):
    diff_text = Path(diff_path).read_text(encoding="utf-8")
    lines = [(p, n, t) for p, n, t in changed_lines(diff_text) if t.strip()]
    if not lines:
        raise SystemExit(f"{diff_path}: no added lines to review")
    listing = "\n".join(f"{p}:{n}: {t}" for p, n, t in lines)
    reply, wall = ask_model(PROMPT.format(diff=diff_text, lines=listing))
    try:
        comments = json.loads(reply["message"]["content"])["comments"]
    except (KeyError, ValueError):
        comments = []
    changed = {(p, n): t for p, n, t in lines}
    linked = []
    for item in comments[:3]:
        key = (str(item.get("file", "")), int(item.get("line", 0)))
        linked.append({**item, "linked": key in changed, "code": changed.get(key, "")})
    return {"diff": Path(diff_path).name, "comments": linked, "wall_seconds": round(wall, 2),
            "model_seconds": round(reply.get("total_duration", 0) / 1e9, 2),
            "tokens": reply.get("eval_count", 0)}


if __name__ == "__main__":
    result = review(sys.argv[1])
    if not result["comments"]:
        print("no comments parsed; see Troubleshooting")
    for number, item in enumerate(result["comments"], 1):
        flag = "" if item["linked"] else "  [not a changed line]"
        print(f"{number}. {item['file']}:{item['line']}{flag}")
        print(f"   > {item['code'].strip()}")
        print(f"   {item['comment']}")
    print(f"time: {result['wall_seconds']} s wall, {result['model_seconds']} s in model, "
          f"{result['tokens']} tokens")
bash
python review.py diffs/01-loop.diff
Output
1. shop/cart.py:6
   > for i in range(len(items) - 1):
   <comment text>
2. shop/cart.py:<line>
   > <code on that line>
   <comment text>
3. ...
time: <seconds> s wall, <seconds> s in model, <tokens> tokens
SettingValueWhy
formatJSON schemaForces a parseable list of comments.
num_ctx16384Room for the diff and the line list; the Ollama default is 4096.
num_predict2048Caps output so a reasoning loop cannot run forever.
total_durationnanosecondsDivided by 1e9 to report seconds in the model.
Stage 04 Checkpoint

The command prints three numbered comments and a time line. Each comment shows the code it points at; a [not a changed line] flag means the model named a line outside the diff.

Stage 05 · test25 minutes

Run the five diffs with the network off

Disconnect, review every sample diff and record comments, timing and memory.

The demo script refuses to start while ollama.com is reachable, so the run begins with no route to the internet. Keep the network off until the last diff finishes. It reads the loaded size from ollama ps after each review, because Ollama keeps the model in memory for five minutes by default.

pythonrun_demo.py
"""Review every diff in diffs/ offline and save the measurements."""
import csv
import re
import socket
import subprocess
import sys
from pathlib import Path

from review import MODEL, review


def network_reachable():
    try:
        socket.create_connection(("ollama.com", 443), timeout=3).close()
        return True
    except OSError:
        return False


def loaded_size():
    try:
        rows = subprocess.run(["ollama", "ps"], capture_output=True, text=True).stdout.splitlines()
    except FileNotFoundError:
        return "ollama not on PATH"
    for row in rows[1:]:
        columns = re.split(r"\s{2,}", row.strip())
        if columns and columns[0].startswith(MODEL) and len(columns) > 3:
            return f"{columns[2]} ({columns[3]})"
    return "not loaded"
pythonrun_demo.pyAppend this to the same file.
if network_reachable() and "--allow-network" not in sys.argv:
    sys.exit("The network is still reachable. Disconnect it, then run this again.")

Path("results").mkdir(exist_ok=True)
with open("results/comments.csv", "w", newline="", encoding="utf-8") as c_file, \
        open("results/runs.csv", "w", newline="", encoding="utf-8") as r_file:
    comments = csv.writer(c_file)
    runs = csv.writer(r_file)
    comments.writerow(["diff", "n", "file", "line", "linked", "comment", "verdict"])
    runs.writerow(["diff", "wall_seconds", "model_seconds", "tokens", "ollama_size"])
    for diff in sorted(Path("diffs").glob("*.diff")):
        result = review(diff)
        size = loaded_size()
        runs.writerow([result["diff"], result["wall_seconds"], result["model_seconds"],
                       result["tokens"], size])
        for number, item in enumerate(result["comments"], 1):
            comments.writerow([result["diff"], number, item["file"], item["line"],
                               item["linked"], item["comment"], ""])
        print(f"{result['diff']}: {len(result['comments'])} comments, "
              f"{result['wall_seconds']} s, {size}")
  1. Run python review.py diffs/01-loop.diff once while still online, so the model is loaded and warm.
  2. Turn off Wi-Fi and unplug any network cable.
  3. Run python run_demo.py and leave your system memory monitor open beside it.
  4. Write the highest memory figure you see in the monitor into a note, next to the SIZE values in results/runs.csv.
Output
01-loop.diff: 3 comments, <seconds> s, <size> (<processor>)
02-discount.diff: 3 comments, <seconds> s, <size> (<processor>)
03-sql.diff: 3 comments, <seconds> s, <size> (<processor>)
04-except.diff: 3 comments, <seconds> s, <size> (<processor>)
05-token.diff: 3 comments, <seconds> s, <size> (<processor>)

Open results/comments.csv in a spreadsheet or text editor. Fill the verdict column with useful or false positive for each row, then save it and total the results.

pythonscore.py
"""Total the verdicts you wrote into results/comments.csv."""
import csv
from collections import Counter
from statistics import median

with open("results/comments.csv", encoding="utf-8") as handle:
    rows = list(csv.DictReader(handle))
with open("results/runs.csv", encoding="utf-8") as handle:
    runs = list(csv.DictReader(handle))

verdicts = Counter(row["verdict"].strip().lower() or "unlabelled" for row in rows)
unlinked = sum(row["linked"] != "True" for row in rows)
times = [float(run["wall_seconds"]) for run in runs]
print(f"comments: {len(rows)}  useful: {verdicts['useful']}  "
      f"false positives: {verdicts['false positive']}  unlabelled: {verdicts['unlabelled']}")
print(f"comments not on a changed line: {unlinked}")
print(f"response time: median {median(times):.1f} s, slowest {max(times):.1f} s")
print("ollama ps size per run: " + ", ".join(sorted({run['ollama_size'] for run in runs})))
bash
python score.py
Output
comments: 15  useful: <n>  false positives: <n>  unlabelled: 0
comments not on a changed line: <n>
response time: median <seconds> s, slowest <seconds> s
ollama ps size per run: <size> (<processor>)
Stage 05 Checkpoint

run_demo.py finished with the network disconnected, results/ holds both CSV files, and score.py prints zero unlabelled comments. Those four lines plus your peak memory note are the bounty's record.

Troubleshooting

run_demo.py exits with "The network is still reachable".

Some machines keep a wired or phone tether connection after Wi-Fi is off. Disconnect every adapter, or use --allow-network only for a dry run you will not report as offline.

urllib.error.URLError with connection refused on port 11434.

The Ollama server is not running. Start the Ollama app, or run ollama serve in a second terminal, then retry.

The review prints "no comments parsed" or fewer than three comments.

The model may have spent its token budget on reasoning before it wrote the JSON. Raise num_predict in ask_model to 4096 and run the diff again, then note the extra time in your results.

ollama ps shows a CPU and GPU split and each review takes minutes.

The model did not fit in GPU or unified memory, so close other large apps and keep num_ctx at 16384 or lower. Record the split in your results, because it explains the timing.

Most comments carry the [not a changed line] flag.

Check that the line list in the prompt is not empty by running python diffparse.py on the same diff. If the list is correct, add a sentence to PROMPT asking the model to copy the file and line exactly from that list.

ollama pull stops partway through the download.

Run the same ollama pull inkling-2-mini command again while online. Ollama resumes the layers it already has instead of starting over.

Done when

  • Demo five sample diffs with the network disabled after setup. Record useful comments, false positives, peak memory, and response time.

Going further

  • Add a Git hook that runs review.py on git diff --cached before each commit and prints the comments without blocking the commit.
  • Run the same five diffs against the 26b-a5b-iq4_NL tag and compare comment quality, SIZE and response time with latest.
  • Feed the reviewer the full file around each hunk, not only the diff, and see whether false positives drop on the loop and discount samples.

References

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.