<!--
  canonical-url: https://www.avonture.be/blog/ollama-git-precommit
  published:     2026-08-10
  This is a static plain-Markdown mirror generated at build time.
  Visit the canonical URL above for the fully rendered page, with images and interactive components.
-->

# ai-review, ai-secrets, ai-commit: Three zsh Checks Before Every git Commit

> Three zsh functions that together form a local, offline pre-commit quality gate: ai-review catches SOLID violations and naming issues, ai-secrets separates real hardcoded credentials from false positives, and ai-commit drafts the Conventional Commits message once the diff is actually clean.

---
![ai-review, ai-secrets, ai-commit: Three zsh Checks Before Every git Commit](/img/v2/ai_review.webp)

**TL;DR**

This article adds three functions to the "Ollama daily use" series — `ai-review`, `ai-secrets`, and `ai-commit` — that together cover the moment right before a `git commit`. All three read the same `git diff --staged`, so they share a single extracted helper (`_git_staged_diff`) instead of repeating the same guard clauses three times. The workflow is intentional: review first, catch any secrets second, write the commit message last — once the diff is actually what you want it to be.

The moment right before a `git commit` is probably the most valuable one in the whole development cycle to pause and look at what you've actually written. Not because something is necessarily wrong — usually it isn't — but because that's when the diff is small and bounded. One more minute of review when you can still see every changed line clearly is worth more than an hour of archaeology later.

I already have [pre-commit hooks](/blog/git-precommit) running phpcbf, PHPStan and friends. Those catch *rules*. What they don't catch is judgment: a method that quietly grew three responsibilities, `0.21` on line 20 that should have a name (like `discount_rate`), `$d` that was a lazy parameter name three months ago and is unreadable today — or, more critically, a real database password that slipped into a config diff.

These three functions fill that gap, locally, without a cloud subscription.

## What `ai-review` Catches Before You Even Write a Commit Message

`ai-review` reads your staged diff and flags what a linter can't: a method quietly doing three things at once, a magic number that should have a name, a parameter that used to make sense. Here's a staged diff with a few deliberate issues planted in it:

**src/Invoice/InvoiceProcessor.php (staged diff)**

```php
diff --git a/src/Invoice/InvoiceProcessor.php b/src/Invoice/InvoiceProcessor.php
index 1234567..89abcde 100644
--- a/src/Invoice/InvoiceProcessor.php
+++ b/src/Invoice/InvoiceProcessor.php
@@ -10,6 +10,32 @@ class InvoiceProcessor
 {
+    public function process($d)
+    {
+        if (!isset($d['amount']) || !isset($d['email'])) {
+            return false;
+        }
+
+        if ($d['amount'] <= 0) {
+            return false;
+        }
+
+        $tax = $d['amount'] * 0.21;
+        $total = $d['amount'] + $tax;
+
+        $conn = new PDO('mysql:host=localhost;dbname=billing', 'root', 'root');
+        $stmt = $conn->prepare('INSERT INTO invoices (amount, tax, total) VALUES (?, ?, ?)');
+        $stmt->execute([$d['amount'], $tax, $total]);
+
+        $subject = 'Your invoice';
+        $body = 'Total due: ' . $total;
+        mail($d['email'], $subject, $body);
+
+        return true;
+    }
 }
```

```bash
$ git diff --staged --stat

 src/Invoice/InvoiceProcessor.php | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)

$ ai-review

## SOLID violations
- src/Invoice/InvoiceProcessor.php:11 — process() validates input, calculates tax, persists to the database, and sends an email: four responsibilities in one method, violating Single Responsibility. Split into validateInvoiceData(), calculateTax(), saveInvoice() and sendInvoiceEmail().

## Magic constants
- src/Invoice/InvoiceProcessor.php:20 — 0.21 is a hardcoded VAT rate with no named meaning. Extract it to a class constant such as VAT_RATE_STANDARD = 0.21, or load it from configuration.

## Naming
- src/Invoice/InvoiceProcessor.php:11 — the parameter $d gives no indication of its shape or purpose. Rename to $invoiceData, and consider a typed value object instead of a raw array.

## Overall quality
- src/Invoice/InvoiceProcessor.php:23 — database credentials ('root', 'root') are hardcoded directly in the method body. Move them to environment variables or a configuration service; this connection also should not be constructed inside a method that also handles business logic.
```

Four genuine issues surfaced, under four of the five fixed headings the prompt allows. "Long functions" stayed empty — the model decided 26 lines didn't cross that line, and the prompt explicitly told it not to invent a section just to fill it.

> **Read-only, on purpose:**
>
> `ai-review` never touches the diff, never blocks a commit, never writes anything. It prints a review to your terminal. What you do with it is your call.

## Why It's Built This Way

* All three read the same `git diff --staged` — they share one helper for the guard clauses (repo check, empty diff, size warning) instead of repeating them three times.
* `ai-secrets` runs a cheap regex first; the model is only called when something actually looks suspicious, so a clean diff costs zero model calls.
* `ai-commit` never commits by itself — the default answer is "no," you explicitly type `y` to accept or `e` to edit.
* The order isn't arbitrary: review while you can still fix the diff, check for secrets once it's the diff you meant to write, then write the message for what you've actually cleaned up.

## Installing the Three Functions

All three build on a shared `_ollama.zsh` foundation (introduced in [ai-test](/blog/ollama-test-generator)) that owns the guard clauses once, instead of each function repeating them:

**\~/.zsh/fns/\_ollama.zsh**

````bash
# Foundation file for every "ai-*" function in this series. Named with a
# leading underscore: the ~/.zsh/fns/*.zsh loader sources files in
# alphabetical order, and "_" sorts before any letter — so this file is
# always loaded first, no matter how many ai-* functions get added later.
#
# Provides:
#   - _ollama_check       reachability guard for Ollama
#   - _ollama_query       shared HTTP client (curl + jq)
#   - _ai_strip_fences    removes the Markdown fences models add anyway
#   - _ai_bat             resolves "bat" vs Debian's "batcat"
#   - _ai_confirm         yes/no prompt
#   - _git_staged_diff    validated staged-diff fetcher (shared by pre-commit functions)
#   - AI_COMMANDS         registry each ai-* function adds itself to
#   - AI_PARAMS           registry of interactive parameter types (file/language/number/text/none)
#   - _ai_prompt_*        FZF/read helpers for interactive argument collection
#   - ai                  entry-point dispatcher / interactive menu

typeset -gA AI_COMMANDS
typeset -gA AI_PARAMS

# ---------------------------------------------------------------------------
# Ollama helpers
# ---------------------------------------------------------------------------

# _ollama_check — verify that the Ollama daemon is reachable.
# Fails loudly so callers can bail early rather than watching curl hang.
_ollama_check() {
  local host="${OLLAMA_HOST:-http://localhost:11434}"
  if ! curl --silent --max-time 2 "${host}/api/tags" >/dev/null 2>&1; then
    echo "ollama: cannot reach ${host} — is the Ollama container running?" >&2
    return 1
  fi
}

# _ollama_query <prompt> — send a prompt to the local model and print the response.
# Assumes Ollama is reachable; call _ollama_check first if you need an early guard.
_ollama_query() {
  local prompt="$1"
  local model="${OLLAMA_MODEL:-qwen3-coder:30b}"
  local host="${OLLAMA_HOST:-http://localhost:11434}"

  _ollama_check || return 1

  # The prompt is piped into jq rather than passed with "--arg": Linux caps a
  # single argv entry at 128 KB (MAX_ARG_STRLEN), and a large staged diff or a
  # long source file sails straight through that ceiling — jq then dies with
  # "argument list too long". "-R -s" slurps stdin as one raw string, which jq
  # escapes exactly like --arg would.
  print -r -- "$prompt" \
    | jq -Rs --arg model "$model" '{model: $model, prompt: ., stream: false}' \
    | curl --silent "${host}/api/generate" --data-binary @- \
    | jq -r '.response // empty'
}

# ---------------------------------------------------------------------------
# Output helpers
# ---------------------------------------------------------------------------

# _ai_strip_fences <text> — return only the code, without the Markdown fences.
#
# Every prompt in this series ends with "no markdown fences" and models still
# wrap their answer in ```language … ``` often enough that the output can't be
# piped or pasted as-is. When at least one fence is present, only the fenced
# regions are kept (which also drops the "Here is your test suite:" preamble);
# when there is none, the text is returned untouched.
_ai_strip_fences() {
  local text="$1"

  if [[ "$text" != *'```'* ]]; then
    print -r -- "$text"
    return 0
  fi

  print -r -- "$text" | awk '
    /^[[:space:]]*```/ { inside = !inside; next }
    inside             { print }
  '
}

# _ai_bat — print the name of the "bat" binary installed on this machine, if any.
# Debian and Ubuntu ship the package as "batcat" because the "bat" name was
# already taken by bacula-console-qt, so both spellings have to be probed.
_ai_bat() {
  local candidate
  for candidate in bat batcat; do
    if command -v "$candidate" >/dev/null 2>&1; then
      print -- "$candidate"
      return 0
    fi
  done
  return 1
}

# _ai_relpath <path> — print <path> relative to the current folder when it sits
# below it. Purely cosmetic: it keeps prompts readable instead of asking
# "Save as /home/christophe/projects/…/tests/backup.bats?".
_ai_relpath() {
  local path="${1:A}"
  print -- "${path#${PWD}/}"
}

# _ai_confirm <question> — ask a yes/no question; return 0 only on an explicit yes.
_ai_confirm() {
  local answer
  print -n "${1} [y/N] "
  read -r answer
  [[ "$answer" == [yY]* ]]
}

# ---------------------------------------------------------------------------
# Git helpers
# ---------------------------------------------------------------------------

# _git_staged_diff <caller> — validate the git context and return the staged diff.
# Handles three early-exit cases (not a repo, nothing staged, oversized diff)
# so every pre-commit function gets them for free without repeating the guards.
#
# Past AI_DIFF_MAX_CHARS the full diff is *not* returned: a diff of several
# hundred kilobytes overflows the model's context window, and the answer that
# comes back is worse than the one you get from a summary. The fallback keeps
# the shape of the change — per-file stat, plus the file and hunk headers,
# which carry the enclosing function names git puts after each "@@" — and
# drops the line-by-line content.
_git_staged_diff() {
  local caller="${1:-ai}"
  local max="${AI_DIFF_MAX_CHARS:-12000}"

  if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    echo "${caller}: not inside a git repository" >&2
    return 1
  fi

  local diff
  diff=$(git diff --staged)

  if [[ -z "$diff" ]]; then
    echo "${caller}: nothing staged — run 'git add' first" >&2
    return 1
  fi

  # "print -r" everywhere below: without it, print expands escape sequences and
  # a literal \n or \t inside the diff would come back mangled.
  if (( ${#diff} <= max )); then
    print -r -- "$diff"
    return 0
  fi

  echo "${caller}: staged diff is large (${#diff} chars) — sending a structural summary instead of the full diff. Commit in smaller chunks for a more precise answer." >&2

  local summary
  summary="$(git diff --staged --stat)

--- FILE AND HUNK HEADERS ONLY (full diff omitted, ${#diff} chars) ---
$(print -r -- "$diff" | grep -E '^(diff --git|new file|deleted file|rename (from|to)|@@)')"

  # Even the summary can exceed the ceiling on a very wide change.
  if (( ${#summary} > max )); then
    summary="${summary[1,$max]}
[…summary truncated…]"
  fi

  print -r -- "$summary"
}

# ---------------------------------------------------------------------------
# Interactive argument helpers (used by the ai() dispatcher)
# ---------------------------------------------------------------------------

# _ai_prompt_file [label] — open an fzf file picker; print the chosen path.
_ai_prompt_file() {
  local label="${1:-Select a file:}"
  local bat_bin preview='cat {}'
  bat_bin=$(_ai_bat) && preview="${bat_bin} --color=always {} 2>/dev/null || cat {}"

  if command -v fd >/dev/null 2>&1; then
    fd --type f | fzf --prompt="${label} " --height=50% --reverse --preview="$preview"
  else
    find . -type f | fzf --prompt="${label} " --height=50% --reverse --preview="$preview"
  fi
}

# _ai_prompt_language — open an fzf language picker; print the chosen language.
_ai_prompt_language() {
  printf '%s\n' English French Dutch German Spanish Italian Portuguese Japanese Chinese Korean \
    | fzf --prompt='Target language: ' --height=40% --reverse
}

# _ai_prompt_number [label] — read a positive integer; print it (or nothing on Enter, which
# lets the caller fall back to its own default). Returns 1 only on invalid input.
_ai_prompt_number() {
  local label="${1:-Number (Enter for default):}"
  print -n "${label} "
  local n
  read n
  if [[ -z "$n" ]]; then
    return 0
  fi
  if [[ ! "$n" =~ ^[1-9][0-9]*$ ]]; then
    echo "Expected a positive integer." >&2
    return 1
  fi
  print -- "$n"
}

# _ai_prompt_text [label] — read a free-form string; print it. Returns 1 if empty.
_ai_prompt_text() {
  local label="${1:-Input:}"
  print -n "${label} "
  local t
  read t
  if [[ -z "$t" ]]; then
    echo "No input given." >&2
    return 1
  fi
  print -- "$t"
}

# ---------------------------------------------------------------------------
# Entry-point dispatcher
# ---------------------------------------------------------------------------

# ai              → interactive fzf menu of every registered ai-* command
# ai <cmd> [args] → dispatch straight to ai-<cmd> [args]
#
# When opened via the fzf menu, each command's declared AI_PARAMS type triggers
# a secondary picker before the command runs:
#   file     → fzf file picker (fd + preview if available)
#   language → fzf language list
#   number   → read prompt, empty input uses the command's own default
#   text     → read prompt, required
#   none     → run the command directly (it collects its own input)
# Space-separated values declare multiple parameters in order, e.g. "file language".
ai() {
  local cmd="$1"

  # Direct dispatch: ai <cmd> [args]
  if [[ -n "$cmd" && "$cmd" != "help" && "$cmd" != "list" ]]; then
    if (( ${+AI_COMMANDS[$cmd]} )); then
      shift
      "ai-${cmd}" "$@"
      return
    fi
    echo "ai: unknown command '${cmd}'" >&2
    echo >&2
  fi

  # Interactive menu
  if ! command -v fzf >/dev/null 2>&1; then
    echo "Available ai commands:"
    for key in ${(ok)AI_COMMANDS}; do
      printf "  ai %-10s %s\n" "$key" "$AI_COMMANDS[$key]"
    done
    return
  fi

  local picked
  picked=$(
    for key in ${(ok)AI_COMMANDS}; do
      printf '%s\t%s\n' "$key" "$AI_COMMANDS[$key]"
    done \
      | fzf --delimiter='\t' --with-nth=2 --prompt='ai > ' --height=40% --reverse \
      | cut -f1
  )
  [[ -z "$picked" ]] && return

  # Collect arguments interactively based on AI_PARAMS declaration
  local -a args=()
  local param_type
  for param_type in ${(s: :)${AI_PARAMS[$picked]:-none}}; do
    case "$param_type" in
      file)
        local f
        f=$(_ai_prompt_file "File for ai-${picked}:") || return 1
        args+=("$f")
        ;;
      language)
        local l
        l=$(_ai_prompt_language) || return 1
        args+=("$l")
        ;;
      number)
        local n
        n=$(_ai_prompt_number) || return 1
        [[ -n "$n" ]] && args+=("$n")
        ;;
      text)
        local t
        t=$(_ai_prompt_text) || return 1
        args+=("$t")
        ;;
      none) ;;
    esac
  done

  "ai-${picked}" "${args[@]}"
}
````

Add the three functions on top of it. Save each file in `~/.zsh/fns/` under the name shown above it (`mkdir -p ~/.zsh/fns` first if the folder doesn't exist yet), pasting its content:

**\~/.zsh/fns/ai-review\.zsh**

```bash
# ai-review — SOLID, magic-constants, naming and overall quality review of
# staged changes, printed straight to the terminal. Read-only: it never
# modifies the diff or blocks a commit — that decision stays with you.

AI_COMMANDS[review]="ai-review  — code review of staged changes (SOLID, magic constants, naming)"
AI_PARAMS[review]="none"

ai-review() {
  local diff
  diff=$(_git_staged_diff ai-review) || return 1

  local prompt="You are a strict senior code reviewer. Review the staged diff below and report ONLY genuine issues, organized under these exact headings (omit a heading entirely if there is nothing to report under it):

## SOLID violations
## Magic constants
## Long functions
## Naming
## Overall quality

For each issue: cite the file and approximate line, state the problem in one sentence, and suggest a concrete fix in one sentence. Do not invent issues to fill every heading — an empty section is a good outcome, not a failure. Do not comment on formatting or style already enforced by a linter.

--- STAGED DIFF ---
${diff}"

  _ollama_query "$prompt"
}
```

**\~/.zsh/fns/ai-secrets.zsh**

```bash
# ai-secrets — scan staged changes for hardcoded credentials.
# Phase 1: a cheap regex pass over the diff finds candidate lines
#           (no model call wasted if nothing matches).
# Phase 2: the LLM judges each candidate — real leak vs. safe pattern
#           (getenv(), placeholder, variable name only, already-redacted value).

AI_COMMANDS[secrets]="ai-secrets  — scan staged changes for hardcoded credentials"
AI_PARAMS[secrets]="none"

ai-secrets() {
  local diff
  diff=$(_git_staged_diff ai-secrets) || return 1

  local suspects
  suspects=$(print -- "$diff" | grep -nEi \
    '(api[_-]?key|secret|password|passwd|token|access[_-]?key|private[_-]?key|AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)')

  if [[ -z "$suspects" ]]; then
    echo "ai-secrets: no suspicious patterns in the staged diff." >&2
    return 0
  fi

  local prompt="You are a secrets-detection expert reviewing a git diff. Below are ONLY the lines that matched a suspicious pattern — context around them has been trimmed. For each line: quote it, then state whether it is a genuine hardcoded secret or a false positive. False positives include: a variable NAME containing 'password' with no real value, a placeholder like 'changeme', an already-redacted value, or a correct read from the environment via getenv()/os.environ/process.env. Output only genuine findings, one per line with a one-sentence reason, or the single line 'No secrets detected.' if every match is a false positive.

--- SUSPICIOUS LINES ---
${suspects}"

  _ollama_query "$prompt"
}
```

**\~/.zsh/fns/ai-commit.zsh**

```bash
# ai-commit — draft a Conventional Commits message from staged changes using
# a local LLM, then ask for explicit confirmation before committing anything.
# The default answer (Enter) is always "no" — this function never commits
# on your behalf without a deliberate y or e.

AI_COMMANDS[commit]="ai-commit  — draft a Conventional Commits message from staged changes"
AI_PARAMS[commit]="none"

ai-commit() {
  local diff
  diff=$(_git_staged_diff ai-commit) || return 1

  local prompt="You are a git commit message expert. Write a single Conventional Commits message (type(scope): subject, optionally a short body) for the staged diff below. Keep the subject line under 72 characters, imperative mood. Output ONLY the commit message — no explanations, no markdown fences, no surrounding quotes.

--- STAGED DIFF ---
${diff}"

  local message
  message=$(_ollama_query "$prompt") || return 1

  echo "--------------------------------------------------"
  echo "$message"
  echo "--------------------------------------------------"
  print -n "Use this message? [y]es / [e]dit / [N]o: "
  local answer
  read -k1 answer
  echo

  case "$answer" in
    y|Y) git commit -m "$message" ;;
    e|E) git commit -e -m "$message" ;;
    *)   echo "ai-commit: aborted, nothing committed." ;;
  esac
}
```

If an earlier article of this series already made your `~/.zshrc` load that folder, there's nothing else to set up. Otherwise, add these lines at the end of `~/.zshrc` — they source every `.zsh` file in the folder:

```zsh title="~/.zshrc"
for fn_file in ~/.zsh/fns/*.zsh; do
  source "$fn_file"
done
```

Then open a new terminal (or run `exec zsh`), and check that the shell knows the three functions:

```zsh
type ai-review ai-secrets ai-commit
```

Each one should answer `… is a shell function from …`; `not found` means the `~/.zshrc` loop is missing.

## `ai-secrets`: Catching Real Credentials

A plain regex scanner can't tell `'password' => 'Sup3rSecret!'` (a real leak) from `'password' => getenv('DB_PASSWORD')` (the right pattern) — both lines contain "password" next to an `=`. That's exactly the gap the model closes:

**config/database.php (staged diff)**

```php
diff --git a/config/database.php b/config/database.php
index 1234567..89abcde 100644
--- a/config/database.php
+++ b/config/database.php
@@ -5,6 +5,14 @@ return [

+    'mysql' => [
+        'host' => 'db.internal.example.com',
+        'username' => 'app_user',
+        'password' => 'Sup3rSecret!2027',
+    ],
+
+    'legacy' => [
+        'password' => getenv('LEGACY_DB_PASSWORD'),
+    ],

 ];
```

```bash
$ git diff --staged --stat

 config/database.php | 8 ++++++++
 1 file changed, 8 insertions(+)

$ ai-secrets

- config/database.php:8 — 'password' => 'Sup3rSecret!2027' is a genuine hardcoded credential in plain text. Move it to an environment variable and load it with getenv('DB_PASSWORD'), matching the pattern already used two lines below for 'legacy'.
- config/database.php:12 — 'password' => getenv('LEGACY_DB_PASSWORD') is the correct pattern (reads from an environment variable), not a leak. No action needed.
```

Two lines matched the regex, both containing "password." The model correctly separated them: one is a real leak with a concrete fix, the other is the exact `getenv()` pattern that fix should follow — correctly left alone.

> **A safety net, not a guarantee:**
>
> This catches what shows up in a text diff. It won't catch a secret split across multiple commits, baked into a binary, or encoded in a way the regex doesn't recognize. Treat it as a second pair of eyes before a commit, not a replacement for a real secrets-scanning tool in CI.

## `ai-commit`: Writing the Message for the Diff You've Just Cleaned Up

Once the diff is what you actually want to commit, hand it to `ai-commit` instead of typing "fix" for the fourth time this week — it already contains everything needed to describe what changed:

**api/reactions.php (staged diff)**

```php
diff --git a/api/reactions.php b/api/reactions.php
index 1234567..89abcde 100644
--- a/api/reactions.php
+++ b/api/reactions.php
@@ -12,6 +12,10 @@ header('Content-Type: application/json');

 $slug = $_POST['slug'] ?? '';

+if ($slug === '') {
+    http_response_code(400);
+    exit(json_encode(['error' => 'Missing slug parameter']));
+}
+
 $reaction = $_POST['reaction'] ?? '';
```

```bash
$ git diff --staged --stat

 api/reactions.php | 4 ++++
 1 file changed, 4 insertions(+)

$ ai-commit

--------------------------------------------------
fix(api): reject empty slug parameter in reactions endpoint

Return a 400 response with a clear error message when the
`slug` POST parameter is missing or empty, instead of silently
processing an invalid reaction.
--------------------------------------------------
Use this message? [y]es / [e]dit / [N]o: y
[main a1b2c3d] fix(api): reject empty slug parameter in reactions endpoint
 1 file changed, 4 insertions(+)
```

A properly scoped `fix(api):` message with a short explanatory body, generated in the two or three seconds it takes the model to read a four-line diff.

> **Nothing commits itself:**
>
> `ai-commit` only ever calls `git commit` after an explicit `y` or `e`. Pressing Enter, Escape, or anything else aborts cleanly.

## Under the Hood: `_git_staged_diff` (skip this if you just want to use it)

The guard clauses shared by all three functions — repo check, empty-diff check, size ceiling — live in one place:

```zsh title="~/.zsh/fns/_ollama.zsh (extract)"
_git_staged_diff() {
  local caller="${1:-ai}"
  local max="${AI_DIFF_MAX_CHARS:-12000}"

  if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    echo "${caller}: not inside a git repository" >&2
    return 1
  fi

  local diff
  diff=$(git diff --staged)

  if [[ -z "$diff" ]]; then
    echo "${caller}: nothing staged — run 'git add' first" >&2
    return 1
  fi

  if (( ${#diff} <= max )); then
    print -r -- "$diff"
    return 0
  fi

  echo "${caller}: staged diff is large (${#diff} chars) — sending a structural summary instead of the full diff." >&2

  local summary
  summary="$(git diff --staged --stat)

--- FILE AND HUNK HEADERS ONLY (full diff omitted, ${#diff} chars) ---
$(print -r -- "$diff" | grep -E '^(diff --git|new file|deleted file|rename (from|to)|@@)')"

  if (( ${#summary} > max )); then
    summary="${summary[1,$max]}
[…summary truncated…]"
  fi

  print -r -- "$summary"
}
```

Every function above calls `_git_staged_diff` and gets back the diff — or exits cleanly with a clear message. In the original versions of these functions, those guard clauses were copy-pasted into each one — a classic SRP violation hiding in plain sight. One responsibility, one place, now.

The size ceiling deserves a word, because I learned it the hard way: staging a few hundred files and running `ai-commit` on a 490 KB diff gives you a *worse* commit message, not a longer one — the model's context window overflows and what comes back is vague or empty. So past `AI_DIFF_MAX_CHARS` (12 000 by default, override it in your shell if your model has room), the helper stops sending the content and sends the *shape* instead: the per-file `--stat`, plus every file and hunk header. Those `@@` lines carry the enclosing function name git puts after them, so the model still knows which files changed, how much, and where — enough for a decent `feat(scope):` line, without drowning.

> **Why the prompt is piped into jq, not passed as an argument:**
>
> In `_ollama_query` you'll see `print -r -- "$prompt" | jq -Rs …` rather than the more obvious `jq -n --arg prompt "$prompt"`. That's deliberate: Linux caps a **single** command-line argument at 128 KB (`MAX_ARG_STRLEN`), regardless of the much larger total `ARG_MAX`. Pass a big diff or a long source file as `--arg` and `jq` dies before it starts, with `argument list too long`. A pipe has no such limit, and `jq -R -s` slurps stdin as one raw string — escaping quotes, backslashes and newlines exactly like `--arg` would.

## Running Them Together

These three aren't a pipeline — you don't have to run all three, and you don't have to run them in order. But the order makes sense when you do:

```zsh
# 1. Look at the diff for design issues
ai-review

# 2. Fix anything worth fixing, then re-stage
git add -p

# 3. Make sure you haven't accidentally left a real credential
ai-secrets

# 4. Write the commit message for the diff you've now cleaned up
ai-commit
```

Each function is also reachable directly (`ai-review`, `ai-secrets`, `ai-commit`) or via the `ai` dispatcher — type bare `ai`, pick a function from the fzf menu, and if the function needs a parameter the menu collects it interactively before running. All three register themselves with one line each — `AI_COMMANDS[review]=...`, `AI_COMMANDS[secrets]=...`, `AI_COMMANDS[commit]=...` — and declare `AI_PARAMS[...]=none`, since they read the staged diff themselves and need no argument.

That registry is what makes the family extensible. [`ai-blog-search`](/blog/anythingllm-chat-with-your-docs) joined it later with the same two lines — except it declares `AI_PARAMS[blog-search]="text"`, so the menu prompts for a question first, and it queries an AnythingLLM workspace rather than Ollama directly.

## Conclusion

None of these three functions does anything you couldn't do manually. `ai-review` is a slower version of reading your own diff. `ai-secrets` is a faster version of `grep -i password`. `ai-commit` is a draft of the message you were going to write anyway. The value isn't in the individual capabilities — it's in the fact that all three run locally, take under ten seconds each, and slot into the moment you're already in: staged, ready to commit, just before you actually do. That's the only moment when the cost of "fix it now" is still lower than the cost of "fix it later."
