OKLMdocumentation v1.0.3
On this page

Git Spec: Working with Git in My Local LLM Agent

Status: specification; implementation to do (roadmap M12), after the parts of the agent and process specifications it builds on.

Instructions for Claude Code: This spec extends AGENT_SPEC.md (and uses the ProcessManager from PROCESS_SPEC.md). Read them all before starting.

Rule #1: audit before you build. Same rule as AGENT_SPEC.md §0A.

  1. Phase 0: search the repo for anything git-related. Look for:

    • git subprocess calls, git libraries (libgit2, isomorphic-git, GitPython, gitoxide)
    • git status in the prompt, commit or PR code, gh/glab usage, worktree code
    • diff rendering, checkpoint code, review commands

    Append the results to docs/gap-analysis.md under "Git", using the ✅/🟡/❌/⚠️ table with file:line evidence.

  2. Write docs/git-design.md, mapping each section to existing modules or new code.

  3. Stop and show me both. Ask only what you can't infer.

  4. Implement milestone by milestone (§16), only ❌ and 🟡 items. Re-search at the start of each milestone. Test everything. Show evidence and wait for my go-ahead between milestones.

Fill in before starting:

  • Git hosts to support: Gitea first (this project's host, git.nilorea.net, through its REST API or tea), GitHub through gh; GitLab (glab) and Bitbucket when asked. To confirm before G7.
  • Default co-author trailer: none by default; a setting (git.coAuthor) adds one, so a repository that wants one says so.
  • Signed commits in use: no for this repository (commit.gpgsign is unset); the agent never signs or disables signing itself, it lets git follow the user's configuration (§0).
  • Non-git VCS to support via hooks: none.

Before starting (OKLM)

What this spec needs settled or built before its G0 can start, and how its names map onto OKLM's.

Names.

The spec says OKLM
AGENT_SPEC.md agent_skill_chat_spec.md (roadmap M10)
PROCESS_SPEC.md process_spec.md (M11)
GIT_SPEC.md git_spec.md (M12)
COMMANDS_SPEC.md commands_spec.md (M13)
the agent binary, agent oklm agent
.agent/, ~/.agent/ .oklm/ and ~/.config/oklm/ ($XDG_CONFIG_HOME, %APPDATA% on Windows)
AGENT.md, AGENT.local.md AGENTS.md (also OKLM.md, AGENT.md, CLAUDE.md; agent-design.md)
the ProcessManager the job manager, src/harness/jobs.c (adr/0012-jobs.md)
.agent/worktrees/<name>, branch agent/<name> .oklm/worktrees/<name>, branch oklm/<name>
.agent/settings.local.json in the unwanted-file check .oklm/settings.local.json, .oklm/audit/, .oklm/jobs/

What exists. No git code in the harness yet: nothing in src/harness/ or apps/oklm.c runs or reads git. What the git features will stand on is there: Bash and its permission rules with compound-command parsing (src/harness/permissions.c, adr/0010-permission-rules.md), the sandbox, the job manager for long operations, sub-agents for reviews. The G0 audit checks that again and appends a "Git" section to gap-analysis.md.

Owned elsewhere, not built twice. This spec owns everything git: the agent specification's §21 and its worktree isolation (§12) point here, and worktrees are built once, here (§9), used by the agent's Task tool. The dangerous-pattern mechanism, the status line and the command environment belong to the agent and process specifications (§2.3, §1.3, §2.4 here add entries and fields); the full map is agent-specs.md. Checkpoints are the agent specification's §11 (§10 here only states the relationship). The git slash commands are implemented by the commands specification's framework (C7), with the behavior defined here. Polling PR checks uses the process specification's Monitor (§4).

Prerequisites. The agent specification's M0 audit (done) and its settings (§7), system prompt assembly (§9, for the git snapshot), dangerous-pattern list and question UX (§6), sessions (§11), sub-agents (§12); the process specification's P1 to P5 for long git operations and monitoring. G1 to G3 (detection, snapshot, classifier, commits) can start once the agent's M4 to M6 are done; G7 needs a host decision; G8 and G9 need the agent's M12 (sub-agents).

Decisions to take at G0: Gitea access (API with the user's token from git's credential helper, or tea); whether the classifier of §2 is a table of git subcommands in permissions.c or rules shipped in a default managed settings file.


0. Principles

  • Git through the CLI. Run the real git binary through Bash and the ProcessManager. It respects the user's config, hooks, credentials, signing and aliases. A library is acceptable only for fast, read-only queries (status and branch for the prompt), and only if one already exists in the repo.
  • The agent never rewrites shared history or loses work without explicit approval. Force pushes, hard resets, branch deletion and amending published commits always ask.
  • The agent commits only when asked, unless the user has opted into auto-commit for this session or project.
  • Mirror the repo's conventions: commit message style, branch naming, PR template.
  • Everything works in a non-git directory too. Git features degrade gracefully, and checkpoints (AGENT_SPEC §11) don't depend on git.

1. Repository detection and context

1.1 Detection (at session start and after /cd)

  • git rev-parse --show-toplevel --git-dir --is-inside-work-tree --is-bare-repository
  • Detect:
    • the worktree root, and whether this is a linked worktree (git worktree list --porcelain)
    • submodules, LFS (git lfs env), sparse checkout, shallow clone
  • Detect the default branch: git symbolic-ref refs/remotes/origin/HEAD, falling back to main/master existence and then init.defaultBranch. Cache it per repo.
  • Detect the host per remote URL (github.com, gitlab.*, custom) and whether gh/glab is installed and authenticated (gh auth status).
  • Detect commit conventions from the last 50 commits: Conventional Commits (feat:), gitmoji, ticket prefixes (ABC-123:), capitalization, and typical subject length. Store them in session state and expose them to the model.
  • Detect branch naming from existing branches (feat/…, user/…, ABC-123-…).
  • Detect the PR template (.github/pull_request_template.md, .gitlab/merge_request_templates/*).
  • Detect hooks in use (core.hooksPath, .husky/, .pre-commit-config.yaml, lefthook.yml), which tells the agent that commits may run linters.
  • Detect signing: commit.gpgsign, gpg.format (ssh/openpgp/x509).

1.2 Git snapshot in the system prompt (AGENT_SPEC §9, item 6)

Computed once per session start and kept byte-stable, for cache hits:

gitStatus: This is the git status at the start of the conversation. It is a snapshot and will not update.
Current branch: feat/login-rate-limit
Main branch (for PRs): main
Status:
M src/auth/login.ts
?? src/auth/ratelimit.ts
Recent commits:
a1b2c3d feat(auth): add password reset email
…(5 commits)
  • Status is truncated to 40 lines with a "+N more" marker. Commit subjects are truncated to 80 chars.
  • When the working tree changes significantly mid-session (branch switch, pull, rebase), add a short system reminder rather than rebuilding the prompt: "Branch changed to X; HEAD now abc123".

1.3 Status line and UI

  • The status line (the agent specification's §19) shows the branch, ahead/behind counts, and dirty, conflict, rebase-in-progress or detached-HEAD state.
  • The welcome screen warns when the session starts in the middle of a merge, rebase, cherry-pick or bisect.

2. Permissions and safety (additions to AGENT_SPEC §6)

2.1 Auto-allowed (read-only) git commands

git status, diff, log, show, blame, branch (list), tag (list), remote -v, rev-parse, ls-files, ls-tree, cat-file, describe, shortlog, reflog (read), stash list, worktree list, config --get, merge-base, grep, check-ignore. The same goes for gh pr view/list/diff/checks, gh issue view/list, gh run view/list, gh api GET, and glab equivalents.

2.2 Prompt by default (mutating, local)

add, commit, checkout/switch, branch <new>, merge, rebase (non-interactive), cherry-pick, revert, stash push/pop/apply, tag <new>, restore, rm, mv, worktree add/remove, pull, fetch, submodule update. acceptEdits mode does not auto-approve these. Only explicit rules do, e.g. Bash(git add:*), Bash(git commit:*).

2.3 Always ask, even when allowed (dangerous-pattern list)

These are entries of the agent specification's one dangerous-pattern list (its §6.4), which owns the mechanism. | Pattern | Why | |---|---| | push --force, -f, --force-with-lease, push +ref | rewrites remote history (extra warning if the target is the default or a protected branch) | | push to the default branch | bypasses review | | reset --hard, checkout -- ., restore . with uncommitted changes, clean -f/-fd/-fdx | destroys local work | | branch -D, push --delete, push :branch, tag -d + push | deletes work or refs | | commit --amend on a commit already pushed | rewrites published history | | rebase of commits already pushed, filter-branch, filter-repo | history rewrite | | stash drop/clear | loses stashed work | | --no-verify, -c core.hooksPath=…, --no-gpg-sign | bypasses the user's hooks or signing | | git config writes (any scope) | changes the user's environment | | update-ref, reflog expire, gc --prune=now | low-level destructive | | gh pr merge, gh pr close, gh release create, gh repo delete, gh api non-GET | remote side effects |

2.4 Never run

  • Interactive commands: rebase -i, add -i/-p, commit without -m/-F, mergetool, and anything that opens an editor or pager.
  • Neutralized globally: the editor, pager and prompt variables are set for every command by the process specification, which owns the command environment (process_spec.md §2.2). If a command still needs input, it fails fast with an instructional error instead of hanging.

2.5 Pre-commit safety checks (code, not just prompt)

Before any git commit the agent runs:

  • Secret scan of staged changes: built-in regexes for keys and tokens, plus gitleaks/trufflehog if installed. A hit blocks the commit and shows the findings to the user.
  • Large file check: warn if a staged file is over 5 MB and isn't tracked by LFS.
  • Unwanted file check: .env*, credentials files, node_modules/, build outputs, and the agent's own .agent/settings.local.json or AGENT.local.md. Warn and suggest .gitignore.
  • Unrelated user changes: staging only touches files the agent changed or that the user named. Never git add -A/git add . unless the user asks for "everything" (§3.2).

3. Commit workflow

3.1 Trigger

Only when the user asks ("commit this", /commit), or when auto-commit is on (git.autoCommit: "off" | "ask" | "after-task"). The default is off.

3.2 Steps (encoded in the system prompt and in the /commit command)

  1. Gather in parallel: git status (never -uall on big repos), git diff and git diff --staged, git log -n 10 --oneline, and the current branch.
  2. Analyze:
    • Which files belong to this change? Leave unrelated user modifications alone, and mention them.
    • What kind of change is it: feature, fix, refactor, docs, test, chore?
    • Are any secrets or unwanted files staged? (§2.5)
  3. Draft the message. It follows the detected convention (§1.1). The subject is imperative and ≤ 72 chars and says why as well as what. The body is optional, explains motivation, wraps at 72, and references issues if the user mentioned them.
  4. Stage specific paths: git add -- path1 path2. For partial staging, use git apply --cached with a generated patch, never interactive -p.
  5. Commit with a heredoc or -F file to preserve formatting. Append the configured trailer, e.g. Co-Authored-By: …, if git.coAuthorTrailer is set.
  6. Verify: git status plus git log -1 --stat.
  7. If a pre-commit hook fails or modifies files:
    • Read the hook output.
    • If the hook auto-fixed files (formatters), re-stage those files and create a new commit attempt. Never --amend a commit the agent didn't just create in this attempt.
    • If the hook reports errors, fix them, then commit again.
    • Max 3 attempts, then stop and report.
    • Never use --no-verify unless the user explicitly says so.
  8. Report the short SHA, subject, and files changed.

3.3 Amending

  • Allowed without extra confirmation only when all of these hold:
    • the user asked to amend
    • HEAD was authored by the agent in this session
    • HEAD isn't pushed (git branch -r --contains HEAD is empty)
  • Otherwise it is a dangerous action (§2.3).

3.4 Empty and edge cases

  • Nothing to commit: say so, and don't create an empty commit.
  • Detached HEAD: warn, and offer to create a branch first.
  • Merge in progress: commit only after conflicts are resolved (§6). Use the default merge message unless asked.
  • Signing: let git handle it. If signing fails (agent unavailable), report it and don't retry unsigned.

4. Branches

  • Creating: follow the detected naming convention. Derive the name from the task ("add login rate limiting" becomes feat/login-rate-limit). Base it on the up-to-date default branch when starting new work (git fetch first; asks if fetch needs credentials).
  • Before switching: if the tree is dirty, ask whether to commit, stash (git stash push -m "agent: …") or carry the changes over. Never discard.
  • Protected branches (git.protectedBranches, default [main, master, develop, release/*]): the agent never commits directly to them without confirmation, and suggests creating a feature branch.
  • Syncing: git pull --rebase or --ff-only according to pull.rebase config. On divergence, explain and ask.
  • Cleanup: after a PR is merged, offer to delete the local branch (branch -d, not -D).

5. Pull/merge requests

5.1 Creating a PR (/pr command or a user request)

  1. Gather in parallel: status, the current branch and its upstream, ahead/behind, git log <base>..HEAD, git diff <base>...HEAD --stat, and the full diff (or a summary if it's huge).
  2. Read all commits in the range, not just the latest.
  3. If the branch has no upstream, push with git push -u origin <branch>. That push needs approval unless a rule allows it.
  4. Title: ≤ 70 chars, following the convention.
  5. Body: use the repo's PR template if present. Otherwise:
    ## Summary
    - 1–3 bullets: what and why
    ## Changes
    - notable implementation points
    ## Test plan
    - [ ] how it was verified (commands run, results)
    Append the configured footer (e.g. "Generated with MyAgent").
  6. Create: gh pr create --title … --body-file … [--draft] [--base …] (or glab mr create). Draft is the default if git.draftPRs is set.
  7. Return the PR URL.

5.2 Working with existing PRs

  • View: gh pr view <n> --json …, gh pr diff, gh pr checks.
  • Comments: the agent reads both review comments (gh api repos/:o/:r/pulls/<n>/comments) and issue comments, then summarizes or addresses them. Replying or posting asks first.
  • Checkout: gh pr checkout <n>, warning if the tree is dirty.
  • CI failures: gh run view --log-failed, then a summary, then a fix.
  • Local "autofix-pr" equivalent (/autofix-pr):
    • a scheduled or monitored loop (PROCESS_SPEC §4) polls gh pr checks and new review comments
    • when something fails, the agent fixes it on the branch, commits, and pushes
    • pushing needs approval unless an allow rule exists
    • stops on success, on /stop, or after N iterations

5.3 Issues

  • gh issue view/list/create/comment. Creating or commenting asks first.
  • Branch names and PR bodies can link issues (Closes #123) when the user mentions them.

6. Conflicts, rebases, cherry-picks, bisect

  • Merge/rebase conflicts:
    • list the files (git diff --name-only --diff-filter=U)
    • for each file, read the conflict markers with context, git log --merge, and both sides' intent (commit messages)
    • resolve with Edit, run the tests or build, git add, then git rebase --continue or a merge commit
    • if a resolution is ambiguous (both sides changed behavior), ask the user and show both sides
    • --abort is always offered as a way out
  • Rebase: non-interactive only. To squash or reorder, use git reset --soft <base> plus a new commit, which is a dangerous action if the commits are pushed, or explain the alternative.
  • Cherry-pick and revert: standard flow, with conflict handling as above.
  • Bisect (/bisect or a request):
    • git bisect start <bad> <good>, then git bisect run <test-cmd> when a script exists
    • otherwise the agent tests each step itself
    • it always runs git bisect reset at the end, even after an interrupt (registered cleanup)
  • Interrupted operations: at startup, detect .git/rebase-merge, MERGE_HEAD, CHERRY_PICK_HEAD and BISECT_LOG, and tell the user.

7. History and code archaeology

  • Teach the model (system prompt plus a git-history skill) to use:
    • git log -S'symbol' / -G'regex' (pickaxe)
    • git log -L :func:file (function history), git blame -w -C
    • git show <sha>, and git log --follow for renames
  • Use cases:
    • "Why was this added?" Blame the line, show the commit, and summarize the message and linked PR (gh pr list --search <sha>).
    • "When did this break?" Bisect (§6).
    • "What changed since release X?" Run git log X..HEAD --oneline and summarize.
  • Output stays compact: one line per commit, and full diffs only on request.

8. Diffs and review

8.1 /diff

  • An interactive viewer of working-tree changes: staged, unstaged and untracked.
  • It shows which files the agent edited this session, using the checkpoint registry, versus the user's own changes.
  • Views: per-file list with +/− counts, unified diff with syntax highlighting, and side-by-side if the terminal is wide.
  • Actions: stage/unstage a file, revert one file (asks first), and open the file in $EDITOR.
  • In -p mode it prints git diff --stat plus the diff.

8.2 /code-review (alias /review)

  • Arguments: [low|medium|high|max] [--fix] [--comment] [--max-findings n|all] [pr#|branch|path].
  • Target:
    • default: the working-tree diff against HEAD, plus the branch's diff against the merge base with the default branch
    • a PR number uses gh pr diff
    • a branch is diffed against its merge base
    • a path reviews files under it
  • Engine:
    • the effort level sets how many parallel review subagents run (AGENT_SPEC §12) and how deep they go
    • low: 1 pass
    • medium: separate correctness, edge-case and test-coverage reviewers
    • high/max: add verification of each finding by a separate agent that tries to refute it, plus a cleanup pass
  • Output: findings with severity, file:line, explanation, and suggested fix. Deduplicated and ranked.
  • --fix applies the findings (edits with normal permissions). --comment posts them as PR review comments (asks first).
  • When no level is given, the last level the user chose is remembered.

8.3 /security-review

  • Diff of the current branch against origin/<default>'s merge base. Needs an origin remote, with a clear error if it's missing.
  • A dedicated prompt covers injection, authn/authz, secrets, unsafe deserialization, path traversal, SSRF, crypto misuse, dependency changes, and data exposure.
  • Each finding has severity, confidence, a short explanation of how it could be exploited, and a fix. False-positive filtering is done by a verification subagent.

8.4 /simplify

  • Parallel reviewers for: reuse of existing helpers, simplification, efficiency, and level of abstraction. No correctness hunting.
  • Applies the fixes after confirmation.

9. Worktrees (parallel isolated work)

  • CLI: agent --worktree [name] starts the session in a new worktree at .agent/worktrees/<name>, or a configurable location outside the repo, on a new branch agent/<name> from the current HEAD.
  • Tools: EnterWorktree(name?, base?) / ExitWorktree(keep|remove|merge?), for the model to move the session into or out of an isolated worktree.
  • Subagent isolation: isolation: "worktree" on the Task tool (AGENT_SPEC §12). Each subagent gets its own worktree. If it made no changes, the worktree is removed automatically. Otherwise the branch and path are returned to the parent.
  • Setup and teardown:
    • copy or link git-ignored essentials into new worktrees, according to git.worktree.copy: [".env.local", …] and git.worktree.symlink: ["node_modules"]
    • optional git.worktree.setup commands (e.g. npm ci) run through the ProcessManager
  • Hooks: WorktreeCreate / WorktreeRemove. If a WorktreeCreate hook is defined, it replaces the git implementation. That's how non-git VCS (jj, hg, p4) are supported: the hook prints the created path.
  • Cleanup:
    • removal never uses --force when there are uncommitted changes without asking
    • orphaned agent worktrees are listed by /doctor and offered for cleanup (git worktree prune)
  • /batch <instruction>:
    • research, decompose into 5–30 independent units, and show the plan
    • after approval, run one background subagent per unit in its own worktree
    • each subagent implements its unit, runs the tests, commits, and pushes a branch or opens a PR (configurable)
    • a summary table at the end shows each unit's status and links

10. Checkpoints vs git (clarify the relationship)

  • Checkpoints (AGENT_SPEC §11) are the agent's own undo for its file edits. They're independent of git and also work outside repos.
  • Rewind never runs git commands, and never touches commits, branches or the index.
  • /rewind shows a warning if commits were made after the selected point ("2 commits made since; rewinding files won't remove them; use git to undo commits").

Registered by the commands framework and listed, with their arguments and the section here that defines each one's behavior, in commands_spec.md §3.4: /diff (§8.1), /commit (§3), /pr (§5.1), /code-review and /review (§8.2), /security-review (§8.3), /simplify (§8.4), /batch (§9), /autofix-pr (§5.2), /bisect (§6), /install-github-app (§13).


12. Settings (additions to AGENT_SPEC §7)

git.coAuthorTrailer (string | null), git.prFooter, git.autoCommit (off|ask|after-task), git.protectedBranches, git.draftPRs, git.branchPrefix, git.commitConvention (auto|conventional|none|custom regex), git.secretScan (builtin|gitleaks|off), git.maxStatusLines, git.worktree.{dir,copy,symlink,setup}, git.host overrides per remote, review.defaultLevel.

Respect the user's own git config. Never write to it unless asked.


13. CI and headless usage

  • Headless works inside CI (agent -p … --output-format json) with git credentials from the environment.
  • GitHub Actions example workflow (docs plus an optional /install-github-app-style generator):
    • triggers on @agent mentions in PR or issue comments
    • runs the agent with restricted tools
    • pushes to a branch and comments the result
    • for a local model, it needs a self-hosted runner; document that clearly
  • GitLab CI equivalent snippet.
  • Safety in CI: bypassPermissions only together with a sandbox. Push only to non-protected branches. Never force.

14. Large and unusual repos

  • Big repos: avoid -uall. Use git status --porcelain=v2 -z, consider core.fsmonitor/untrackedCache hints, and time out slow commands while still showing partial info.
  • Submodules: show their status. Edits inside a submodule commit there first, then the parent pointer (ask first).
  • LFS: check git lfs status before commit, and never add large binaries without LFS when .gitattributes expects it.
  • Monorepos: scope diffs and reviews to the paths touched. Respect CODEOWNERS when suggesting PR reviewers (--reviewer, asks first).
  • Shallow clones: git log and blame may be incomplete. Say so, and offer git fetch --unshallow (asks first).

15. Testing

  • A fixture repo factory (script) that creates temp repos with:
    • commit history in various conventions, multiple branches, and a fake origin (a local bare repo)
    • merge, rebase and cherry-pick conflicts, a pre-commit hook that reformats, a pre-commit hook that fails
    • submodules, LFS stub, detached HEAD, an in-progress rebase, a dirty tree with user changes
  • A fake gh script that records calls and returns canned JSON for PR, checks and comments tests.
  • Unit/integration tests:
    • detection of default branch, conventions, hooks and signing
    • snapshot rendering and truncation
    • the permission classifier for every command in §2, with a fuzz test on compound commands (git status && git push -f)
    • env neutralization (no hang on an editor)
    • secret-scan blocking, and staging only the intended files
    • hook-failure retry without --amend
    • amend rules (pushed vs unpushed)
    • protected-branch prompt
    • conflict resolution flow with the mock model
    • bisect cleanup on interrupt
    • worktree create, remove and auto-remove when unchanged, and the WorktreeCreate hook replacing git
  • Mock-model E2E: "fix bug → commit → create PR" against the fixture repo plus fake gh. Assert on the commit message format, the staged files, push with -u, and the PR body sections.
  • Real-model evals:
    • "commit my changes" with unrelated user edits present (must not stage them)
    • "resolve the merge conflict"
    • "why was this function added?"
    • "rebase onto main"

16. Milestones

Every milestone follows the same steps:

  1. Re-search the code.
  2. Update the gap analysis.
  3. Implement only ❌/🟡 items.
  4. Test.
  5. Show evidence.
  6. Report what was reused, extended and new.
# Milestone Done when
G0 Audit + docs/git-design.md Gap table covers §1–§14 with evidence
G1 Detection, git snapshot in prompt, status line, env neutralization Snapshot test green; no command can hang on an editor or pager
G2 Git permission classifier (§2.1–2.4) + dangerous list Classifier test suite (incl. compound fuzz) green
G3 Commit workflow + pre-commit safety checks + /commit Hook-failure, secret-block and selective-staging tests green
G4 Branch handling, protected branches, sync Dirty-switch and protected-branch flows tested
G5 Conflicts, rebase, cherry-pick, bisect, interrupted-op detection Mock-model conflict E2E passes; bisect resets on interrupt
G6 /diff viewer + session-edited-file tracking Manual checklist + -p output test
G7 Host integration (gh/glab): PR create/view/checks/comments, /pr Fake-gh E2E passes
G8 /code-review, /security-review, /simplify with subagents Seeded-bug fixture: review finds ≥ 80% of seeded bugs at medium
G9 Worktrees: --worktree, Enter/ExitWorktree, subagent isolation, hooks, /batch Parallel /batch on fixture produces N clean branches
G10 /autofix-pr local loop, history/archaeology skill, CI docs and workflow templates Loop fixes a failing fake check and stops
G11 Large-repo, submodule, LFS and shallow handling; docs (docs/git.md); evals Eval report generated

Priority if time is short:

  • G1–G3 give safe commits.
  • G5 and G7 cover daily PR work.
  • G8–G9 cover reviews and parallel work.