Rendered live from the cfgit guide

cfgit guide

The long-form walkthrough: why cfgit exists, when to use it, setup, everyday flows, the UI, agents, impact, adapters and the safety model. For a command-by-command reference see USAGE.md; for every .cfg.toml option see CONFIGURATION.md.

Why cfgit exists

Many teams keep runtime behavior in live database records: model routing, agent prompts, provider settings, pricing tables, policy config, workflow definitions, feature controls, and other control-plane data. These records are often edited by people, scripts, admin APIs, and AI coding agents. The edits take effect immediately, but the workflow usually lacks the things engineers expect from code:

  • a useful history
  • a readable diff
  • a safe commit path
  • rollback to a known good point
  • a way to see when someone changed the database outside the tool

Existing "git for data" tools usually solve a different problem: they want to own the database or sit in front of storage. cfgit is for the case where you cannot move the data and cannot put a gateway in the runtime path.

Core idea

cfgit versions opaque JSON records identified by a stable id. It stores history beside the live datastore, not inside your application code and not in a hosted prompt registry.

The important state is drift:

  • cfg status detects live records that changed outside cfgit.
  • cfg diff <record> =HEAD =live shows what changed.
  • cfg adopt <record> folds that out-of-band change into history.
  • cfg commit refuses to overwrite un-adopted drift.

That drift reconciliation is the main reason cfgit exists.

Status

cfgit is pre-1.0 software. The current implementation includes:

  • CLI with JSON output
  • MongoDB adapter
  • Postgres adapter
  • local author permission checks
  • per-environment identity modes with hashed token or DB-principal verification
  • opt-in branch and PR workflow for draft changes before runtime merge
  • system restore by tag or timestamp
  • localhost web UI
  • MCP server
  • portable Codex or Claude Code skill
  • built-in impact analysis (records and code that reference a change) with opt-in LLM narration

The engine is intentionally DB-neutral. Mongo and Postgres are the first two adapters to prove the storage seam.

When to use cfgit

Good fit:

  • control-plane collections or tables
  • low to moderate record counts
  • records edited by a small team or agents
  • changes where "who changed what and why" matters
  • data where rollback to a known good state is a real operation

Examples:

  • agent configs
  • model routing records
  • provider templates
  • pricing or policy config
  • workflow definitions
  • feature or runtime behavior config

Bad fit:

  • user-generated content
  • events, logs, analytics, metrics
  • high-write transactional tables
  • append-only data
  • rows written by traffic rather than curated by people

cfgit stores full document versions. It is not a warehouse, event log, backup system, or schema migration tool.

Install

From PyPI:

pip install 'cfgit[mongo,postgres,mcp]'

Minimal install for Mongo only:

pip install 'cfgit[mongo]'

Minimal install for Postgres only:

pip install 'cfgit[postgres]'

With pipx:

pipx install 'cfgit[mongo,postgres,mcp]'

Impact analysis and LLM narration are built in (they need no extra packages). The old cfgit-impact plugin is deprecated; if you have it installed, see UPGRADING.md.

Quick start

Create .cfg.toml in the repo or working directory where you want to operate:

[project]
name = "runtime-control-plane"

[history]
history_collection = "config_history"
heads_collection = "config_heads"

[branches]
enabled = false
refs_collection = "cfgit_refs"
default_branch = "main"

[[collection]]
name = "agent_configs"
id_field = "config_id"
live_when = { is_active = true }
ignore_fields = ["_id", "is_active", "updated_at", "updated_by"]
secret_fields = []

[env.dev]
database = "mongo"
uri = "env:DEV_MONGODB_URI"
db = "my-dev-db"
needs_approval = false

[env.dev.identity]
mode = "open"

[env.dev.permissions]
mode = "open"
admins = []
writers = []
admin_actions = ["restore_system"]

You can define multiple [env.<name>] blocks, but one cfgit command opens one env at a time:

cfg --env dev status
cfg --env prod log agent_configs:agent_planner

Keep each physical history store under one stable env name. If the same database is later addressed as a different env, cfgit will report that history exists under the original env instead of returning an empty log.

Point it at a local or staging database first:

export DEV_MONGODB_URI='mongodb://localhost:27017/?replicaSet=rs0'
cfg init
cfg doctor
cfg import --all -m "initial import"
cfg status

cfg doctor is read-only. Run it before the first import for a new database or .cfg.toml; it reports secret-deny matches, large fields, and live-rule/key issues in one pass, with paste-ready secret_fields and ignore_fields suggestions. cfg doctor --status prints a "where am I" header: the resolved config file, env, target database, identity mode and whether it is verified, store reachability, and how many records are tracked or drifted — plus a warning if a needs_approval environment is still in open identity mode (writes would succeed unaudited).

Check drift:

cfg status
cfg diff agent_configs:agent_planner =HEAD =live

Edit a few fields in place (the fast path — no temp file). cfg set fetches the live document and commits the change through the same drift-guarded path as cfg commit, so it refuses on out-of-band drift rather than clobbering it:

cfg set modelgarden_models:openai/gpt-4o-mini enabled=true retry.max=3 -m "enable + retry"

Values are JSON-coerced (enabled=true → bool, n=5 → int, tags=["a","b"] → list); prefix with str: to force a string (version=str:1.0). Edit one element of a list without copying the whole list: orgs+=abc123 appends it if absent (creating the array if the field is missing) and orgs-=abc123 removes every occurrence. Use cfg edit <record> to hand-edit the whole document in $EDITOR.

Commit a full JSON document (add --dry-run to preview the field-level delta and exit without writing):

cfg commit agent_configs:agent_planner --from planner.json -m "tune planner routing"
cfg commit agent_configs:agent_planner --from planner.json --dry-run

Commit multiple records as one batch intent:

[
  {"record": "agent_configs:planner", "doc": {"config_id": "planner", "model": "fast"}},
  {"record": "modelgarden_models:openai/gpt-4o-mini", "doc": {"model_path": "openai/gpt-4o-mini"}}
]
cfg commit --bulk-from batch.json -m "switch planner routing"
cfg commit --bulk-from batch.json --dry-run   # preview every record's delta, write nothing

Bulk commit preflights the whole batch before writing. If any target has un-adopted drift, is missing, duplicates another target, or trips the secret policy, cfgit applies none of the batch. --dry-run previews the per-record delta (would_commit / noop / changed_outside_cfgit) for the whole batch without writing — run it before any collection-scale replace.

Snapshot and restore a whole collection

For "back it up, replace many rows, roll the whole thing back," cfg export writes a portable, re-importable snapshot of the current live documents (each stamped with its cfgit head seq/oid), and cfg import --from writes those documents back through the drift-guarded bulk-commit path — so the restore is recorded in history like any other change:

cfg export --out backup.json                       # snapshot every collection to a file
cfg export modelgarden_models:openai/gpt-4o-mini   # or one record, to stdout
# ... do a risky bulk change ...
cfg import --from backup.json --dry-run             # preview the restore
cfg import --from backup.json -m "restore from backup"

This is the file-based backup artifact (portable, out-of-tool, diffable). For an in-tool rollback with no file, use cfg tag + cfg restore --tag / cfg restore --as-of <date>, which version the whole system inside cfgit. Both record the restore in history; export/import also gives you a standalone file to keep or share.

Draft changes on a branch before mutating runtime:

cfg branch create router-test --from main
cfg --branch router-test commit agent_configs:agent_planner --from planner.json -m "try router change"
cfg diff main..router-test
cfg pr create --base main --head router-test -m "review router change"
cfg pr merge <pr-id>

Branching is opt-in with [branches] enabled = true. branch, branch commits, branch diff, and PR creation write only cfgit draft/review refs. The only branch command that mutates runtime is cfg pr merge, and it refuses stale main heads or un-adopted live drift. Multi-record PR merges require adapter batch atomicity: all runtime records, canonical history/head updates, and PR closure commit together or roll back together.

commit, import, and adopt scan the would-be-stored document for secret-like field names and values from [secrets] (name rules apply to string values only, so max_tokens = 4096 is not a secret). Fields listed in secret_fields are stripped before history. Use --allow-secret only for intentional fixtures or known false positives; cfgit records the override in history metadata.

A collection can declare validate = { schema = "flags.json" } (JSON Schema) or validate = { python = "module:fn" }; every write path refuses a document that fails it, and cfg doctor reports live documents that already do. See CONFIGURATION.md.

Plain JSON has no dates, so documents that travel as files use MongoDB Extended JSON: cfg export and cfg edit write datetimes as {"$date": "..."} (and decimals / ObjectIds as $numberDecimal / $oid), and every write path decodes those wrappers at any depth. A write that would replace a live datetime, decimal or ObjectId with a different type, typically an ISO string, is refused, because the hash treats both as equal and the diff would hide it. Use --allow-type-change only when that is the intent; it is recorded in history metadata.

Adopt an out-of-band database write:

cfg adopt agent_configs:agent_planner -m "adopt admin console edit"

Tag and restore:

cfg tag june7-good
cfg restore --tag june7-good --dry-run -m "preview rollback"
cfg restore --tag june7-good -m "restore known good state"

Open the local UI:

cfg ui

Run the MCP server:

cfg-mcp                              # installed with the [mcp] extra (same as `cfg mcp`)
uvx --from 'cfgit[mcp,mongo,postgres]' cfg-mcp      # or without installing

It is also listed on the MCP Registry as io.github.AusafMo/cfgit, so clients that install from the registry can add it by name.

Add it to an agent:

# Claude Code: MCP server + the cfgit skill, as a plugin
/plugin install cfgit --marketplace AusafMo/cfgit
# (older Claude Code: /plugin marketplace add AusafMo/cfgit, then /plugin install cfgit@cfgit)

# Claude Code, server only
claude mcp add --transport stdio cfgit -- uvx --from 'cfgit[mcp,mongo,postgres]' cfg-mcp

# Codex CLI
codex mcp add cfgit -- uvx --from 'cfgit[mcp,mongo,postgres]' cfg-mcp

Cursor, VS Code and other clients take the same stdio command: {"command": "uvx", "args": ["--from", "cfgit[mcp,mongo,postgres]", "cfg-mcp"]}. The server finds .cfg.toml from CFG_CONFIG or by walking up from its working directory; when the client starts it elsewhere (GUI apps often do), set CFG_CONFIG to an absolute path in the server's env. See AGENTS.md for what agents should know.

cfg-mcp requires the mcp extra. If you installed cfgit without it (a plain pip install cfgit / pipx install cfgit), cfg-mcp exits with ModuleNotFoundError — which is what an MCP client (or a one-click install deeplink) will surface as a failed connection. Install the extra:

pip install 'cfgit[mcp,mongo,postgres]'            # pip / venv
pipx inject cfgit 'mcp>=1.0,<2'     # if cfgit was installed via pipx

The extra currently pins mcp>=1.0,<2 — the cfgit MCP server targets the mcp 1.x FastMCP API and is not yet ported to mcp 2.0.

Record syntax

Records are addressed as:

collection:id

Examples:

agent_configs:agent_planner
modelgarden_models:openai/gpt-4o-mini

The collection and id field are configured in .cfg.toml.

Commands

Common commands:

cfg init
cfg doctor [record]
cfg doctor --status
cfg import --all -m "initial import"
cfg export [record] [--out file.json]
cfg import --from <export.json> [--dry-run] -m "message"
cfg status [record]
cfg diff <record> [from] [to]
cfg impact <record> [from] [to]
cfg commit <record> --from <file.json> -m "message"
cfg commit <record> --from <file.json> --dry-run
cfg commit --bulk-from <batch.json> -m "message"
cfg commit --bulk-from <batch.json> --dry-run
cfg set <record> field=value nested.field=value list+=item list-=item -m "message"
cfg edit <record> -m "message"
cfg add <record> --from <file.json> -m "message"
cfg rm <record> -m "message" [--dry-run] [--force]
cfg promote <record> --from dev --to prod [--ref @seq] -m "message" [--dry-run]
cfg promote --tag <tag> --from dev --to prod -m "message"
cfg branch list
cfg branch create <name> --from main
cfg branch delete <name>
cfg switch <name>
cfg --branch <name> commit <record> --from <file.json> -m "message"
cfg --branch <name> commit --bulk-from <batch.json> -m "message"
cfg diff main..<branch>
cfg --branch <branch> log
cfg pr create --base main --head <branch> -m "message"
cfg pr list
cfg pr show <id>
cfg pr close <id>
cfg pr merge <id>
cfg log <record> [-n N] [--since 30d]
cfg show <record> <ref>
cfg adopt <record> -m "message"
cfg adopt --all -m "message"
cfg tag <name>
cfg restore <record> <ref> -m "message"
cfg restore --as-of <date> --dry-run -m "message"
cfg restore --tag <name> --dry-run -m "message"
cfg fsck
cfg whoami
cfg check-update [--snooze [DAYS]]
cfg ui

cfgit checks PyPI for a newer release on cheap read commands (throttled to once a day) and, for an interactive terminal, prints a one-line nudge to stderr with what's new — it never upgrades for you (run pip install -U cfgit) and never prints on --json/piped output. cfg check-update forces a check; cfg check-update --snooze 30 silences it for 30 days; CFGIT_NO_UPDATE_CHECK=1 disables it entirely.

Every command supports --json for scripts and agents. By default output is human-readable when stdout is a terminal and JSON when piped or redirected; set CFG_OUTPUT=json|human|auto to control this, and --json always forces JSON.

Every refusal and terminal outcome also carries a next block — a plain-language reason plus the exact next command(s) to run. On the CLI it prints to stderr; over --json/MCP it is a structured next field so agents can act on next.commands directly.

Environment defaults: CFG_ENV (default env), CFG_CONFIG (config file path), and CFG_AUTHOR (author) let you set a session once instead of repeating flags. cfgit also discovers .cfg.toml by walking up from the current directory.

Refs:

  • =HEAD or HEAD: last cfgit-recorded version
  • =live or live: current live database record
  • @<seq>: history entry number
  • <oid-prefix>: content hash prefix
  • tag:<name>: tagged version

Local UI

cfg ui starts a localhost-only web UI over the same action layer as the CLI and MCP server. It opens on an Inbox: every record changed outside cfgit gets a card with its first changed fields, recorded against live, and Discard, Adopt and Review buttons. Review one by one walks the drifted records, and j and k move between them.

Selecting a record shows its system impact (computed locally), a line-aligned side-by-side diff that collapses unchanged context and keeps the field name pinned while you scroll, and its version history, where any older version can be restored. LLM narration is opt-in behind its own button, because it sends the record's diff to your configured provider.

Every write confirms first. Adopt, discard and restore show the local impact before you commit to them, merge lists the records it will write, and deleting a branch asks you to type its name.

The Branches view shows what each draft branch holds compared with main. Pull requests lists the open PRs and the draft branches ready to open one; the selected one shows its changed records, its diff and a single action, open or merge. With a draft branch as the working branch, a record's view offers an Edit on branch button for a draft commit.

Keyboard: / finds a record, r refreshes, j and k step through drift, and Esc and Enter cancel and confirm dialogs. It ships light and dark themes and works offline.

By default it binds to 127.0.0.1:8765 and tries the next free ports if needed:

cfg ui
cfg ui --port 9000 --no-open

If you omit --port, cfgit will try the next free local ports. If you pass --port explicitly, cfgit treats that port as intentional and fails if it is already in use.

Production-shaped UI demo

The repo includes a safe support-control-plane fixture for screenshots, demos, and UI testing. It creates synthetic records only in the database you pass; use a throwaway database name when you want the run contained.

python examples/seed_support_demo.py \
  --uri 'mongodb://localhost:27017/?replicaSet=rs0' \
  --db cfgit_ui_demo \
  --reset

cfg --config-file examples/cfgit-support-demo.toml --env dev init
cfg --config-file examples/cfgit-support-demo.toml --env dev import --all -m "initial production-shaped demo import"

python examples/seed_support_demo.py \
  --uri 'mongodb://localhost:27017/?replicaSet=rs0' \
  --db cfgit_ui_demo \
  --drift

cfg --config-file examples/cfgit-support-demo.toml --env dev status
cfg --config-file examples/cfgit-support-demo.toml --env dev ui

The base seed creates a realistic support-agent runtime surface: orchestrator and specialist agent configs, model routing, policy rules, tool registry records, routing policies, escalation policies, eval suites, rollout controls, and knowledge-source allowlists. The --drift pass simulates admin-console edits to refund automation, refund policy, routing confidence, eval gates, rollout traffic, and a new loyalty-credit tool. That gives the UI useful drift, impact, scoped impact, adopt, branch, PR, merge, and restore-history paths without using proprietary data.

MCP and agent usage

The MCP server exposes the same operations with a uniform envelope:

{
  "status": "ok",
  "code": 0,
  "message": "",
  "data": {},
  "state": null,
  "next": null
}

state echoes the outcome's terminal state (for example changed_outside_cfgit), and next carries a self-teaching remedy ({why, remedy, commands, actions, docs}) when the outcome needs one (a refusal, drift, a blocked batch, an identity/permission failure). Agents should branch on state and use next.actions (ready tool calls); an action marked writes: true needs a dry run and the user's go first. Both are null on a clean success. See AGENTS.md.

Tools include:

  • cfg_status
  • cfg_doctor
  • cfg_diff
  • cfg_impact
  • cfg_commit
  • cfg_bulk_commit
  • cfg_set
  • cfg_add
  • cfg_rm
  • cfg_promote
  • cfg_export
  • cfg_import
  • cfg_branch_list
  • cfg_branch_create
  • cfg_branch_delete
  • cfg_branch_diff
  • cfg_branch_log
  • cfg_pr_create
  • cfg_pr_list
  • cfg_pr_show
  • cfg_pr_close
  • cfg_pr_merge
  • cfg_recent_history
  • cfg_log
  • cfg_show
  • cfg_adopt
  • cfg_restore
  • cfg_tag
  • cfg_fsck
  • cfg_whoami
  • cfg_init
  • cfg_identity_hash
  • cfg_check_update

A portable skill lives at skills/cfgit/SKILL.md. cfg_impact accepts the same against list/string as the CLI --against flag, so MCP clients can request scoped narration without shelling out. cfg_pr_merge has the same runtime semantics as the CLI: it is the only branch or PR MCP tool that mutates runtime, and multi-record PRs are merged as one adapter-atomic batch when the backend supports that guarantee.

If cfg_log or cfg_show returns bad_config with a message saying history exists under another env, the same database has been addressed with two different .cfg.toml env names. Re-run with the env that wrote the history, or standardize the config so that database always uses one env name.

Impact summaries

cfg impact runs deterministic local analysis by default. It categorizes changed paths, finds static references to changed values across configured records, lists the file:line places your code reads the record (when the collection sets code_refs, see CONFIGURATION.md), and reports a risk level. cfg rm runs the same reference scan and refuses to delete a record something still points at.

Opt-in LLM narration (--llm) reads the real before/after of the change plus a map of the surrounding records, then explains in plain language what the change does, what it ripples into, and how to roll it back:

cfg impact agent_configs:agent_planner --llm --json

By default the narration reasons against the whole system. To scope it to a few records you care about, pass --against (repeat it, or comma-separate). The model then reasons about the changed record against only those selected records; no unselected sibling record text leaves your machine:

cfg impact agent_configs:brief_classifier \
  --against agent_configs:critic --against agent_configs:shot_breakdown --llm

In the web UI the same scoping is a click: Cmd- or Ctrl-click records in the left tree to add them, and the impact panel re-runs against that set.

Provider selection comes from [connections].ai_provider in .cfg.toml, unless you pass --provider. --llm is gated by [connections].share_with_ai; add the exact record id, collection:*, or * before any provider call. Narration supports claude, openai, and gemini. API keys are read from the environment only (ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY or GOOGLE_API_KEY), never from the config file.

Narration talks to providers over the Python standard library: cfgit imports no vendor SDK or HTTP client, and provider code loads only when you pass --llm. Both are tested.

Storage adapters

Mongo:

  • requires a replica set or sharded cluster for transactional writes
  • versions documents in configured collections
  • stores history in configured history and heads collections

Postgres:

  • uses ordinary ACID transactions
  • expects each live table to have:
  • an id column named by id_field
  • optional scalar columns used by live_when
  • a doc jsonb column containing the full record

See ADAPTERS.md.

Safety model

cfgit is non-custodial. It does not stop other writers from changing the database. It detects and reconciles those changes.

Important safety properties:

  • mutating operations use adapter-level compare-and-swap checks
  • commits refuse to clobber live drift
  • system restore supports dry runs
  • per-environment identity can stay open or require verified token/DB-principal identity
  • local permissions can restrict high-blast-radius actions
  • secret fields can be stripped from stored history
  • core imports no DB drivers and no LLM providers

Start on a local or staging database. Do not point a new config at production until you have run cfg status, cfg import, cfg diff, and restore dry runs against a safe environment.

Development

python -m venv .venv
. .venv/bin/activate
pip install -e '.[mongo,postgres,mcp,dev]'
ruff check src tests plugins/cfg_impact/cfg_impact
pytest tests/ -q
git diff --check

See ../CONTRIBUTING.md.