Metadata-Version: 2.4
Name: closegate
Version: 0.1.0
Summary: The policy chokepoint for finance AI agents — umbrella install for closegate-policy, closegate-engine, and closegate-agent.
Project-URL: Homepage, https://closegate.neullabs.com
Project-URL: Documentation, https://closegate.neullabs.com
Project-URL: Repository, https://github.com/neul-labs/closegate
Project-URL: Issues, https://github.com/neul-labs/closegate/issues
Project-URL: Changelog, https://github.com/neul-labs/closegate/blob/main/CHANGELOG.md
Author: closegate contributors
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: agentic,anthropic,ap-three-way-match,audit-log,claude,close,finance,hitl,mcp,policy-gate,reconciliation,soc2,sox
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial :: Accounting
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: closegate-agent
Requires-Dist: closegate-engine
Requires-Dist: closegate-policy
Description-Content-Type: text/markdown

<p align="center">
  <img src="documentation/assets/logo.svg" width="240" alt="closegate logo — the open-source policy gate for finance AI agents" />
</p>

<h1 align="center">closegate — the open-source policy gate for finance AI agents</h1>

<p align="center"><strong>SOX-grade SoD, materiality routing, HITL approval envelopes, and a tamper-evident audit log — shipped as an MCP server, a Python library, and a Docker image. Drop it in front of Claude, GPT-4, or Gemini before your AI agent touches the general ledger.</strong></p>

<p align="center">
  <a href="LICENSE"><img alt="License: Apache-2.0" src="https://img.shields.io/badge/license-Apache--2.0-blue.svg"></a>
  <a href="pyproject.toml"><img alt="Python 3.12+" src="https://img.shields.io/badge/python-3.12%2B-blue.svg"></a>
  <a href="mcp/server.json"><img alt="Model Context Protocol (MCP) server" src="https://img.shields.io/badge/MCP-listed-7c3aed.svg"></a>
  <a href="mcp/smithery.yaml"><img alt="Smithery one-line install" src="https://img.shields.io/badge/Smithery-listed-7c3aed.svg"></a>
  <a href="https://closegate.neullabs.com"><img alt="closegate documentation site" src="https://img.shields.io/badge/docs-closegate.neullabs.com-blue.svg"></a>
  <a href="https://github.com/neul-labs/closegate/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/neul-labs/closegate?style=social"></a>
  <a href="ROADMAP.md"><img alt="Project status: alpha" src="https://img.shields.io/badge/status-alpha-orange.svg"></a>
</p>

<p align="center">
  <!-- HERO IMAGE PLACEHOLDER. Replace with a polished diagram export
       (Figma → SVG recommended) once design lands. Target: a single-
       glance illustration of GL + subledger + bank feed flowing into
       the policy gate, branching to audit log + HITL approval, then
       settling to downstream systems (NetSuite, Slack, Teams). -->
  <img src="documentation/assets/hero-policy-gate.svg" width="720" alt="closegate — GL and subledger data flow through a tier-routed policy gate that branches to an append-only audit log and an HITL approval envelope before settling downstream." />
</p>

## What is closegate?

**closegate is an open-source policy gate, audit log, and human-in-the-loop (HITL) approval framework for finance AI agents.** It's the controls layer that goes between an LLM (Claude, GPT-4, Gemini, etc.) and your accounting systems — enforcing segregation of duties (SoD), materiality thresholds, sensitive-account routing, and a hash-chained audit log that an external auditor can replay.

closegate ships three ways:

- **`pip install closegate-policy`** — the policy gate as a pure Python library (no MCP, no Docker, no FastAPI). Wrap it around any tool call.
- **`uvx closegate-engine mcp serve`** — a [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server with 19 finance tools (run_recon_pass, propose_match, confirm_match, ap_match_three_way, ap_submit_payment_run, …) tier-routed by reversibility. Drops into [Claude Desktop](https://claude.ai/download), [Cursor](https://cursor.sh), the [OpenAI Apps SDK](https://platform.openai.com/docs/apps), and any other MCP-compliant client.
- **`docker run ghcr.io/neul-labs/closegate-demo`** — the full reference workflow (reconciliation + AP 3-way match + HITL approval inbox + Vue workspace) in one container for fly.io / Render / Railway one-click deploys.

> **TL;DR.** Put AI agents in front of your **monthly close, account reconciliation, and accounts payable** cycles — without losing the controls **SOX 404, SOC 2 Type 2, NIST AI RMF, and PCAOB AS 1215** require. closegate ships the policy gate, append-only SQLite audit log, HITL approval envelopes, and a four-dimension eval harness (matching accuracy, policy enforcement, adversarial robustness, latency) as open-source software you can pilot against your real policies.

<!-- DEMO VIDEO PLACEHOLDER
     A 30-90 second Loom walking through one reconciliation close:
       - Engine ingests GL + SL
       - Recon pass proposes matches
       - Above-threshold matches route to HITL approval inbox
       - Audit log entries replayed in the workspace UI
     Embed once recorded:
       <p align="center">
         <a href="https://www.loom.com/share/REPLACE-ID">
           <img src="documentation/assets/demos/recon-close-thumbnail.png" alt="60-second demo" width="720" />
         </a>
       </p>
-->

## Pick your path

<table>
<tr>
<td width="33%" align="center" valign="top">
<h3>📊 Finance teams</h3>
<p>Controllers, FP&amp;A leads, AP managers piloting an AI agent against a real close cycle.</p>
<a href="https://closegate.neullabs.com/for-finance-teams/"><strong>For finance teams →</strong></a>
</td>
<td width="33%" align="center" valign="top">
<h3>🧠 AI architects</h3>
<p>LLM engineers wiring closegate as the policy chokepoint for agentic workflows.</p>
<a href="https://closegate.neullabs.com/for-ai-architects/"><strong>For AI architects →</strong></a>
</td>
<td width="33%" align="center" valign="top">
<h3>⚙️ CTOs &amp; engineers</h3>
<p>Architecture, MCP design, audit log internals, eval harness, threat model.</p>
<a href="https://closegate.neullabs.com/for-engineers/"><strong>For engineers →</strong></a>
</td>
</tr>
</table>

---

`closegate` is an open-source reference architecture for finance teams who want
to put AI agents in front of their close, reconciliation, and AP/AR workflows
*without* losing the controls their auditors depend on. Every funded vendor in
the space (BlackLine, FloQast, Numeric, Ramp, Brex, Vic.ai, AppZen, Tabs,
Tesorio, Trullion) shipped "agentic" products in 2025–2026. Every one of them
keeps the **policy gate** — the chokepoint that enforces SoD, materiality, HITL,
and a tamper-evident audit log — closed-source. closegate ships it openly so
finance teams can build their own agents and pilot them safely against real
policies.

## How closegate compares to commercial finance AI vendors

| Capability | **closegate (OSS)** | BlackLine · FloQast · Numeric · Trullion | Ramp · Brex · Vic.ai · AppZen |
|---|:---:|:---:|:---:|
| Open-source policy gate (you can read + audit the chokepoint code) | ✅ Apache-2.0 | ❌ closed-source | ❌ closed-source |
| Per-agent identity + segregation of duties enforced server-side | ✅ `X-Actor-Id` on every MCP call | ✅ (proprietary) | ✅ (proprietary) |
| Materiality thresholds tier-routed to HITL (T0/T1/T2/T3 per NIST AI RMF) | ✅ executable `policy.yaml` | partial | partial |
| Append-only SQLite audit log with `BEFORE UPDATE/DELETE` triggers | ✅ open SQL schema | ❌ vendor-controlled | ❌ vendor-controlled |
| Verbatim policy clause text + JSON-pointer on every blocked event | ✅ | varies | varies |
| Dual-HITL on irreversible (T3) actions like payment-run submission | ✅ | varies | varies |
| Self-host on your own infra (Docker Compose / Kubernetes / fly.io) | ✅ | ❌ SaaS-only | ❌ SaaS-only |
| Drop-in MCP server (Claude Desktop / Cursor / OpenAI Apps SDK) | ✅ | ❌ | ❌ |
| Per-currency precision + ISO 4217 + crypto registry + ROUND_HALF_EVEN | ✅ Decimal-end-to-end | varies | varies |
| Per-entity timezone + business-day calendars (TARGET2 / BACS / TSE / NSE) | ✅ | partial | partial |
| Bring-your-own LLM (no vendor model lock-in) | ✅ Claude / GPT-4 / Gemini / OSS | ❌ | ❌ |
| SOC 2 Type 2 monitoring loop as code | ✅ `closegate-engine soc2-monitor` | vendor-attested | vendor-attested |
| Eval harness (matching accuracy, policy enforcement, adversarial, latency) | ✅ 4 dimensions, reproducible | ❌ | ❌ |
| Per-IdP SSO wiring (Entra ID / Okta / Google Workspace / SAML / Cloudflare) | ✅ OIDC + reverse-proxy | varies | varies |
| Cost | **free** (self-hosted compute only) | $50K–$500K/yr seat licensing | $20K–$200K/yr |

Looking for an **open-source alternative to BlackLine, FloQast, Numeric, Ramp, Brex, or Vic.ai** for AI-assisted close, reconciliation, or AP work? closegate is the reference architecture — written in public so your auditor, your CISO, and your engineering team can each read the part they care about.

> **Status:** alpha. The reconciliation reference workflow is end-to-end
> functional with **986 passing tests**; the policy + money + calendar + FSM
> primitives ship as `pip install closegate-policy`; the docs site is live
> at [closegate.neullabs.com](https://closegate.neullabs.com). The M7
> milestone closed the SOC 2 Type 2 monitoring loop, shipped extensible
> FX + intercompany-matcher adapters, added 6 jurisdictions (UK / EU / JP /
> IN / AU / CA) as executable YAML policies, and wired a live ROI
> calculator into the workspace. See [ROADMAP.md](./ROADMAP.md) for the
> full M7 → v1.0 path.

---

## Why this exists

Finance teams in 2026 face a contradiction. The pressure to put AI agents in
front of close, reconciliation, and AP cycles is real — Gartner says 2026 CFO
priorities are dominated by AI talent acquisition. But the agents that
actually *act* on financial systems need governance that the audit profession
recognises: per-agent identity, segregation of duties, materiality thresholds,
mandatory human-in-the-loop on irreversible actions, and a hash-chained audit
log that an external auditor can replay.

Commercial vendors solve this privately and won't share the architecture
— it's their compliance moat. There's no neutral OSS reference for "how to
put an AI agent in your finance stack and survive the audit." closegate is
that reference.

## The four pillars

| Pillar | What it is | Where it lives |
|---|---|---|
| **Policy gate** | Single chokepoint every state-changing tool call passes through. Tier-routes by reversibility (T0 read-only, T1 reversible, T2 reversible+above-materiality requires HITL, T3 irreversible requires dual-HITL). | `packages/closegate_policy/` |
| **Audit log** | Append-only SQLite table with `BEFORE UPDATE`/`BEFORE DELETE` triggers. Every gate decision records the verbatim policy rule + JSON-pointer source. | `packages/closegate_engine/.../store/` |
| **HITL approval envelopes** | LLM proposes, human confirms via a different actor identity. SoD enforced server-side. | `packages/closegate_agent/` |
| **Eval harness** | Four dimensions: matching accuracy, policy enforcement, adversarial robustness, latency. Continuous evaluation as a SOC 2 monitoring control. | `eval/` |

## Quick start

### Easy path — docker compose

The drop-in 60-second demo. Three containers (engine + agent + web),
auto-seeded with the SaaS pack on first start.

```sh
cp .env.example .env       # set ANTHROPIC_API_KEY=sk-ant-... if you want live LLM
docker compose up          # build + start; first run takes ~3 min
open http://localhost:5173 # the workspace
```

To switch the seeded data pack:

```sh
CLOSEGATE_SEED_PACK=holdco docker compose up   # multi-entity holdco
CLOSEGATE_SEED_PACK=fintech docker compose up  # payments fintech
CLOSEGATE_SEED_PACK=none docker compose up     # bring-your-own
```

Stop and clean:

```sh
docker compose down        # stop, keep data volume
docker compose down -v     # stop + wipe SQLite
```

### Developer path — `make demo`

Direct Python processes; faster iteration when you're modifying source.

```sh
# 1. Install
make install
cp .env.example .env       # edit .env; set ANTHROPIC_API_KEY=sk-ant-...

# 2. Seed and validate
make seed                  # loads seed/*.json into data/recon.db
make validate              # asserts schema, append-only triggers, spec parses

# 3. Tests
make test                  # 986 passing, 2 skipped

# 4. Local demo (Workspace + Advanced UI, full agent loop)
make demo                  # opens http://127.0.0.1:5173

# 5. Evaluation harness
make eval                  # 4 dimensions; report at evals/results/latest/report.md
```

You need: Python 3.12, [`uv`](https://docs.astral.sh/uv/), Node 20+, and an
`ANTHROPIC_API_KEY` for live LLM mode. `make demo` starts three processes —
engine MCP server on `:8001`, agent service on `:8000`, Vue dev server on
`:5173`. If port 8000 is taken, set `CLOSEGATE_AGENT_PORT=8002` and
`VITE_AGENT_PORT=8002`.

### Just the policy gate

Don't need the recon engine, the agent loop, or the web workspace? The
chokepoint primitive ships as a standalone package with no I/O. Drop it
in front of any LLM tool call:

```sh
pip install closegate-policy
```

```python
from decimal import Decimal
from closegate_policy.gate import (
    Action, ActorContext, MatchContext, PolicyConfig, evaluate,
    Allow, RequireHumanApproval, Deny,
)

decision = evaluate(
    action=Action.CONFIRM,
    match=MatchContext(match_id="m-1", state="PROPOSED_MATCH",
                       proposed_by="llm:claude", source="llm",
                       match_type="exact_match", amount_usd=Decimal("15000")),
    actor=ActorContext(id="engine:autoconfirm", kind="engine"),
    accounts={"5000-COGS"},
    rationale=None,
    config=PolicyConfig(...),
)
# match decision: Allow | RequireHumanApproval(clause) | Deny(clause)
```

You decide where the approval envelope goes (Slack, web inbox, a pager)
and how to persist the audit row. The gate stays a pure function. FX
rate providers and intercompany matchers ship as Protocol + registry
adapters — register your in-house Bloomberg feed or holdco account-pair
matcher without forking. See
[`packages/closegate_policy/README.md`](packages/closegate_policy/README.md)
for the full standalone story.

## Deploy

| Path | Best for | Doc |
|---|---|---|
| `docker compose` (default) | Self-hosted on your own infra; three separate services with proper logs + restart policies | [deploy/README.md](deploy/README.md) |
| `docker run` consolidated image | One-click PaaS (fly.io, Render, Railway) | [deploy/README.md](deploy/README.md) |
| Kubernetes | Production-scale | (not yet shipped; the compose file is a starting point for a Helm chart) |

### Enterprise SSO

closegate ships two authentication modes:

- **`CLOSEGATE_AUTH_BACKEND=header-trust`** *(default)* — trusts a
  reverse proxy upstream. Best fit when you already use Cloudflare
  Access, oauth2-proxy, Pomerium, or an AWS ALB with IAM auth.
- **`CLOSEGATE_AUTH_BACKEND=oidc`** — validates IdP-issued tokens
  directly. Works with Microsoft Entra ID (Azure AD), Okta, Auth0,
  Google Workspace, Microsoft 365, and any OIDC-compliant provider.

Per-IdP wiring guides:

- [Microsoft Entra ID](https://closegate.neullabs.com/integrations/sso-entra-id/)
- [Okta](https://closegate.neullabs.com/integrations/sso-okta/)
- [Google Workspace](https://closegate.neullabs.com/integrations/sso-google-workspace/)
- [Cloudflare Access](https://closegate.neullabs.com/integrations/sso-cloudflare-access/)
- [SAML 2.0 via oauth2-proxy](https://closegate.neullabs.com/integrations/sso-saml-via-oauth2-proxy/)

In dev mode (`CLOSEGATE_ENV=dev`, default), unauthenticated requests
fall through as `human:demo-user` so `make demo` and the test suite
work without an IdP. In staging/prod, no fallback — every request is
explicitly identified.

### Dev banner

The web UI shows a thin amber bar at the top of every page when
`CLOSEGATE_ENV != prod` or when the build is in Vite DEV mode. The
banner is hidden automatically in production builds that report a
`prod` environment. Toggle with `CLOSEGATE_ENV=prod` and rebuild the
web image.

## Synthetic seed packs

closegate ships six deterministically-generated synthetic data packs so you
can pilot against a company persona that resembles your own without exposing
real financial data:

```sh
python -m seeds.generator --pack saas --seed 42         # B2B SaaS (Northwind Software)
python -m seeds.generator --pack acme --seed 42         # Generic mid-market (Acme Corp)
python -m seeds.generator --pack holdco --seed 42       # 3-entity holdco (Pinecrest US/UK/DE)
python -m seeds.generator --pack fintech --seed 42      # Payments processor (Lumen Pay)
python -m seeds.generator --pack jp-multi --seed 42     # JP-parent + IN-sub (M7)
python -m seeds.generator --pack apac-holdco --seed 42  # 5-entity APAC holdco (M7)
```

Each pack outputs GL + SL entries, a `policy.yaml`-shaped `matching_spec.json`,
chart of accounts, entity-level timezone+calendar policy, and 12 hand-designed
adversarial anomalies (above-materiality matches, vendor bank-change attempts,
fat-finger amounts, multi-tz close-window overlaps, etc.). The multi-entity
packs (`holdco`, `jp-multi`, `apac-holdco`) include real intercompany pairs
in 1500-X ↔ 2500-X form so the `AccountCodePairMatcher` can match them as a
first pass. All amounts are written as JSON strings and parsed via
`decimal.Decimal` end-to-end — never float.

## Money + time + jurisdiction correctness

`closegate_policy` enforces the rules that production finance code can't get
wrong:

- **`Decimal` end-to-end.** Pydantic models, SQLite storage, JSON wire format,
  matchers, FX conversion. Tests run with the `decimal.FloatOperation` trap so
  any accidental float coercion fails the build.
- **Boundary-only rounding.** `ROUND_HALF_EVEN` (banker's, GAAP-aligned) by
  default, `ROUND_HALF_UP` adapter for IRS reports. Round at presentation,
  persistence, or external handoff — never mid-calculation.
- **Per-currency precision** from ISO 4217 + an extensible crypto registry
  (USD=2, JPY=0, KWD=3, BTC=8, ETH=18, USDC=6).
- **Per-entity timezone + calendar policy.** Each legal entity carries
  `(timezone: IANA, cutoff_time, calendar: enum)`. Calendar adapters cover
  US Federal/NYSE/SIFMA, UK BACS, EU TARGET2 (with computed Easter), Japan,
  India. **Multi-tz close-window overlap detection** is a first-class signal
  surfaced in the UI.
- **Single clock module.** All time comparisons go through
  `closegate_policy.clock.gate_now_utc()`; `fake_now()` for tests.

See [Currency and rounding](https://closegate.neullabs.com/reference/currency-and-rounding/)
and [Timezone and calendar](https://closegate.neullabs.com/reference/timezone-and-calendar/)
on the docs site for the full contract.

## The automation gradient

Every tool, FSM transition, and gate decision is tagged with a tier from the
NIST AI RMF Agentic Profile reversibility classification:

| Tier | Means | Default route |
|------|---|---|
| T0 | read-only / propose | always auto |
| T1 | reversible, below materiality | auto with audit |
| T2 | reversible, above materiality / sensitive account | HITL required |
| T3 | irreversible / systemic | dual HITL required |

The policy gate reads the tier and decides the automation route — there is no
implicit "should we ask the human" logic anywhere else. State machines
(`closegate_policy.fsm`) declare a tier per transition; the gate enforces it
uniformly across the seven shipped lifecycles (match, approval, workflow_run,
agent_session, ingestion_job, exception, period_close).

## Architecture

```
   Vue 3 + Tailwind                  web/  ·  Vite dev :5173
        │ /api/*
        ▼
   FastAPI agent service             :8000  ·  packages/closegate_agent/
        │  (Claude Agent SDK; recon-operator skill rendered with verbatim
        │   policy text; sessions, chat, traces, pending_approvals)
        │  data/agent.db
        │
        │ MCP HTTP  X-Actor-Id: human:demo-user | llm:sess-xxx
        ▼
   Engine + MCP server               :8001  ·  packages/closegate_engine/
        │  Tools: run_recon_pass · propose · confirm · reject ·
        │         flag_exception · investigate_exception · close_summary
        │  Resources: recon://status · policy · entries · matches/{state} ·
        │             audit · entry/{id} · match/{id}
        │  Engine: matchers → pipeline → state machine → policy gate
        │  data/recon.db (audit_events append-only via SQLite triggers)
        ▼
```

Three architectural commitments make this real:

1. **The MCP server is a process boundary.** The agent service has no Python
   import path into the engine; every read or write goes through MCP HTTP. Two
   databases split by ownership — `recon.db` is the SOX-relevant book of
   record, `agent.db` is orchestration metadata.
2. **Identity is bound to the transport.** Tools never accept `actor_id` as a
   parameter. The agent sets `X-Actor-Id` on the MCP client per request — chat
   turns use the LLM session's actor; modal-driven confirms use the human
   actor. The LLM cannot impersonate the human.
3. **One policy chokepoint.** Every state mutation flows through
   `policy.gate(...)`. There is no second mutation API. Every blocked event
   records the **verbatim policy rule text** and a JSON-pointer source — an
   auditor inspecting `audit_events` doesn't see opaque enums.

The full architecture, design rationale, and concept explainers live on the
docs site: [closegate.neullabs.com/for-engineers/architecture-at-a-glance](https://closegate.neullabs.com/for-engineers/architecture-at-a-glance/).

## Eval headline numbers

From `evals/results/latest/report.md` (live run, `claude-sonnet-4-6`):

| Dimension | Status | Headline |
|---|---|---|
| Matching accuracy | **OK** | macro-F1 **1.000** on 83 cases (perfect confusion matrix) |
| Override-policy enforcement | **OK** | **21/21** scenarios pass with verbatim rule text on every blocked event |
| Prompt robustness / adversarial | **OK** | **25/25** prompts blocked across 6 attack categories (51 live tool calls, 0 bypasses) |
| Latency & throughput | **OK** | engine p95 **13.7 ms** · **~5,135 matches/sec** |

## Install as an MCP server

closegate's MCP server is published to the public registries so any
compliant MCP client can install it with one line. Manifests live in
[`mcp/`](./mcp/); see [`mcp/README.md`](./mcp/README.md) for the full
install paths.

```sh
# Smithery one-line install (auto-configures Claude Desktop)
npx -y @smithery/cli install closegate-engine --client claude

# Direct uvx (any MCP client)
uvx closegate-engine mcp serve --transport stdio
```

Claude Desktop / Cursor `.mcp.json`:

```jsonc
{
  "mcpServers": {
    "closegate": {
      "command": "uvx",
      "args": ["closegate-engine", "mcp", "serve", "--transport", "stdio"],
      "env": { "CLOSEGATE_ACTOR_ID": "human:your-name" }
    }
  }
}
```

## CLIs

```sh
# Engine
closegate-engine init <project>              # scaffold a new closegate deployment
closegate-engine seed | reset --yes | validate
closegate-engine recon                       # run a recon pass
closegate-engine state                       # KPI dump
closegate-engine audit verify | tail -n 50   # tamper-test or recent events
closegate-engine policy                      # parsed policy
closegate-engine ap seed | status | match-all  # AP 3-way match (M3 alpha)
closegate-engine mcp serve --transport http  # MCP HTTP server (default :8001)
closegate-engine mcp inspect                 # list tools + resources

# M7 additions
closegate-engine sweep-stale-locks --max-age-seconds 600  # one-shot recovery sweep
closegate-engine outbox status | drain                    # outbox dead-letter ops
closegate-engine demo multi-jurisdiction                  # 5-entity APAC close cycle
closegate-engine impact-calc --seed-pack <pack> --out report.json  # ROI calculator
closegate-engine audit-evidence-export --since <iso> --until <iso> --out evidence.zip  # SOC 2 PBC bundle
closegate-engine soc2-monitor --out soc2-monitor.json     # Type 2 monitoring artifact

# Agent service
closegate-agent doctor                       # pre-flight checks
closegate-agent serve [--port 8000]          # FastAPI service
closegate-agent session new                  # create a chat session
closegate-agent chat -s <session> "..."      # one-shot chat
closegate-agent approvals list -s <session>  # pending approvals
closegate-agent eval run --dimension all     # run the harness
closegate-agent eval report --latest         # print latest report
```

## Documentation

The full docs site is at **[closegate.neullabs.com](https://closegate.neullabs.com)**.
Top-of-funnel entry points:

| Audience | Start here |
|---|---|
| Finance teams | [What is closegate?](https://closegate.neullabs.com/for-finance-teams/what-is-closegate/) · [30/60/90 pilot plan](https://closegate.neullabs.com/adoption/30-60-90-pilot-plan/) |
| AI architects | [AI architects overview](https://closegate.neullabs.com/for-ai-architects/) · [Reference: MCP tools](https://closegate.neullabs.com/reference/mcp-tools/) |
| CTOs & engineers | [Architecture at a glance](https://closegate.neullabs.com/for-engineers/architecture-at-a-glance/) · [Extending closegate](https://closegate.neullabs.com/for-engineers/extending-closegate/) |
| Auditors | [Auditor one-pager](https://closegate.neullabs.com/for-auditors/one-pager/) · [Control mapping](https://closegate.neullabs.com/for-auditors/control-mapping-detailed/) |
| CFOs | [ROI calculator](https://closegate.neullabs.com/for-cfos/roi-calculator/) · [Risk register impact](https://closegate.neullabs.com/for-cfos/risk-register-impact/) |

Repo-root references (these stay in the repo, not the docs site):

- [ROADMAP.md](./ROADMAP.md) — public M0..M7 milestones + versioning policy
- [COMPLIANCE.md](./COMPLIANCE.md) — control mapping (SOC 2, NIST AI RMF, PCAOB, SOX)
- [SECURITY.md](./SECURITY.md) — threat model + disclosure

M7 additions worth surfacing:

- [Concepts — FX rates](https://closegate.neullabs.com/concepts/fx-rates/) +
  [reference](https://closegate.neullabs.com/reference/fx-adapters/) — pluggable
  Protocol + 3 shipped adapters (`fixed`, `ecb_daily`, `open_exchange_rates`).
- [Concepts — intercompany matching](https://closegate.neullabs.com/concepts/intercompany-matching/) +
  [reference](https://closegate.neullabs.com/reference/intercompany-adapters/) —
  same shape (`none`, `account_code_pair`, `json_rules`).
- [11 starter `policy.yaml` files](https://closegate.neullabs.com/policy-library/) covering
  US / UK / EU / JP / IN / AU / CA / holdco / SOX / fintech / SaaS.
- [SOC 2 self-attestation template](https://closegate.neullabs.com/about/soc2-self-attestation/)
  + [Type 2 evidence package guide](https://closegate.neullabs.com/for-auditors/type-2-evidence-package/).

## Layout

```
closegate/
├── packages/
│   ├── closegate_policy/        # pip-installable headline package
│   │   src/closegate_policy/
│   │     money.py               # Decimal + py-moneyed-style Money + currency registry
│   │     calendar.py            # Calendar enum + holidays + pandas_market_calendars + TARGET2
│   │                            # M7: ASX (AU) + TSX (CA) market calendars + civil fallbacks
│   │     clock.py               # gate_now_utc() + fake_now()
│   │     tiers.py               # Tier T0/T1/T2/T3 + register_tool decorator
│   │     fx.py                  # M7 — FxRateAdapter Protocol + Fixed/ECB/OpenExchangeRates
│   │     gate.py                # M7 — per-entity policy overrides
│   │     fsm/                   # 7 declarative FSMs
│   ├── closegate_engine/        # engine + MCP server
│   │   src/closegate_engine/
│   │     config.py              # parses matching_spec.json into typed model
│   │     impact.py              # M7 — ImpactReport / calculate() for ROI widget + case studies
│   │     soc2.py                # M7 — audit-evidence-export + soc2-monitor implementation
│   │     domain/                # pydantic models, errors (+ MatchType.INTERCOMPANY)
│   │     engine/
│   │       policy.py            # the policy chokepoint
│   │       service.py           # only public mutation API
│   │       matchers/            # exact, fuzzy, multi_to_one (Decimal)
│   │         intercompany.py    # M7 — IC matcher Protocol + NoOp/AccountCodePair/JsonRules
│   │       pipeline.py
│   │       state_machine.py
│   │     ingest/                # IngestionAdapter contract + reference adapters
│   │     workers/outbox.py      # outbox worker with DEAD_LETTER transition (M7)
│   │     mcp_server/            # tools, resources, transport, auth
│   │     store/                 # schema, db connection, repos, seed loader
│   │     cli.py                 # closegate-engine
│   └── closegate_agent/         # agent service (was kraken_recon_agent)
│       src/closegate_agent/
│         agent/loop.py          # Claude Agent SDK driver
│         skills/recon_operator.md
│         store/                 # agent.db schema, repos
│         mcp_client.py
│         main.py                # FastAPI app
│         cli.py                 # closegate-agent
├── eval/                        # 4 dimensions
├── seeds/                       # synthetic seed generator + 6 packs
│   ├── generator.py             # multi-entity-aware (entity_id::ref prefixes)
│   ├── saas/  acme/  holdco/  fintech/
│   ├── jp-multi/                # M7 — JP-parent + IN-sub
│   └── apac-holdco/             # M7 — 5-entity APAC (US/JP/IN/AU/SG)
├── tests/                       # 986 passing
├── web/                         # Vue 3 + TS + Pinia + Tailwind
├── seed/                        # legacy reference seed (used by tests)
├── data/                        # gitignored — recon.db, agent.db
├── evals/results/{ts}/          # gitignored — report.{md,json}
├── ROADMAP.md
├── COMPLIANCE.md
├── SECURITY.md
└── README.md
```

The user-facing docs site source lives in the repo too but is served at
[closegate.neullabs.com](https://closegate.neullabs.com) — read it there
rather than browsing the source.

## Frequently asked questions

### What is closegate?

closegate is an open-source policy gate, audit log, and human-in-the-loop (HITL) approval framework for **finance AI agents** — the controls layer that goes between an LLM and your general ledger, accounts payable, and reconciliation workflows. It enforces segregation of duties (SoD), materiality thresholds, sensitive-account routing, and a tamper-evident audit log that an external auditor can replay. closegate ships as a Python library (`pip install closegate-policy`), a [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server (`uvx closegate-engine`), and a Docker image (`ghcr.io/neul-labs/closegate-engine`).

### How is closegate different from BlackLine, FloQast, Numeric, Vic.ai, or Ramp?

closegate is open source (Apache-2.0) — every line of the policy chokepoint, audit log, and HITL routing logic is readable, forkable, and auditable. The commercial vendors keep the policy gate closed as their compliance moat. closegate also runs on your own infrastructure (Docker Compose, Kubernetes, fly.io), supports any LLM you want (Claude, GPT-4, Gemini, open-weight models), and is free. See the [comparison table](#how-closegate-compares-to-commercial-finance-ai-vendors) above.

### Is closegate SOX 404 / SOC 2 Type 2 / NIST AI RMF compliant?

closegate ships **control mappings** for SOX 404, SOC 2 Trust Services Criteria, NIST AI RMF Agentic Profile, PCAOB AS 1215, EU GDPR Article 22, and state sales-tax rounding rules — see [`COMPLIANCE.md`](COMPLIANCE.md). The mappings cite `file.py:line` precision so your auditor can verify the implementation behind each claim. Compliance is a property of your **deployment** (your `policy.yaml`, your actor identities, your retention policy), not the framework alone — closegate ships the SOC 2 Type 2 nightly monitoring loop (`closegate-engine soc2-monitor`) and an audit-evidence-export PBC bundle (`closegate-engine audit-evidence-export`) so your operating effectiveness is demonstrable.

### Which LLMs does closegate work with?

closegate is **LLM-agnostic**. The MCP server speaks the open Model Context Protocol — any MCP-compliant client works (Claude Desktop, Cursor, OpenAI Apps SDK, Mastra, LangGraph, custom clients). The bundled `closegate-agent` service uses the Claude Agent SDK by default but is swappable; pin your model via `CLOSEGATE_AGENT_MODEL=claude-sonnet-4-6` (or `gpt-4`, or any other model your client supports).

### Can I use closegate without Docker?

Yes. Three independent install paths:

1. **Python library only**: `pip install closegate-policy` — the policy gate as a pure function, no I/O, no servers. Drop it in front of any LLM tool call.
2. **MCP server**: `pip install closegate-engine && closegate-engine mcp serve --transport stdio` — runs as a stdio MCP server for Claude Desktop / Cursor. No Docker needed.
3. **Docker**: `docker compose up` if you want the full reference workflow with the Vue workspace UI and the FastAPI agent loop in one go.

### Can I use closegate as just the policy gate (no MCP, no FastAPI, no recon engine)?

Yes — that's exactly what `closegate-policy` is. The gate is a pure function over duck-typed contexts: you build a `MatchContext` + `ActorContext`, call `evaluate(...)`, and pattern-match on `Allow` / `RequireHumanApproval(clause)` / `Deny(clause)`. You decide where the approval envelope goes and how to persist the audit row. See [`packages/closegate_policy/README.md`](packages/closegate_policy/README.md) for the standalone story.

### What ERPs / banks / accounting systems does closegate ingest?

Reference adapters ship for **Stripe, Plaid, Mercury, QuickBooks, NetSuite, Codat, and Merge.dev**, plus CSV + JSON file-drop. The ingestion contract is a single Protocol; new adapters typically take ~150 lines. See [`packages/closegate_engine/src/closegate_engine/ingest/vendors/`](packages/closegate_engine/src/closegate_engine/ingest/vendors/).

### Which jurisdictions does closegate support out of the box?

11 executable starter `policy.yaml` libraries cover **US (SOX + GAAP), UK (FRS 102 / IFRS / BACS / HMRC), EU (IFRS / TARGET2 / VAT OSS / GDPR Article 22), Japan (J-GAAP / BoJ / JPY 0-decimal), India (Ind-AS / NSE / BSE / INR), Australia (AASB / ASX), Canada (ASPE/IFRS / TSX)**, plus three vertical templates (SaaS, fintech, holdco) and a SOX-public-company template. Business-day calendars cover US Federal, US NYSE, US SIFMA, UK BACS, EU TARGET2, JP BoJ, AU ASX, CA TSX, NSE/BSE, and civil calendars for any ISO country. Per-currency precision via ISO 4217 + an extensible crypto registry (USD=2, JPY=0, KWD=3, BTC=8, ETH=18, USDC=6).

### Is closegate production-ready?

**Status: alpha.** 986 passing tests; the reconciliation reference workflow is end-to-end functional; the policy + money + calendar + FSM primitives ship today. Pre-1.0 means `0.x.y` minor releases may contain breaking changes — [pin tight](ROADMAP.md#versioning-policy-pre-10) (`closegate-policy==0.1.0`) until 1.0. Do **not** point closegate at real financial data without the [SECURITY.md go-live checklist](SECURITY.md#running-closegate-against-real-data).

### How do I install closegate as an MCP server in Claude Desktop or Cursor?

```jsonc
// ~/Library/Application Support/Claude/claude_desktop_config.json (macOS)
// %APPDATA%\Claude\claude_desktop_config.json (Windows)
// or .cursor/mcp.json
{
  "mcpServers": {
    "closegate": {
      "command": "uvx",
      "args": ["closegate-engine", "mcp", "serve", "--transport", "stdio"],
      "env": {
        "CLOSEGATE_ACTOR_ID": "human:your-name",
        "CLOSEGATE_DB_PATH": "/Users/you/.closegate/recon.db"
      }
    }
  }
}
```

One-line Smithery install: `npx -y @smithery/cli install closegate-engine --client claude`.

### Where do I report a security issue?

See [`SECURITY.md`](SECURITY.md). **Never** report security issues via GitHub Issues.

## License

closegate is licensed under **Apache 2.0** — see [`LICENSE`](LICENSE). You may use, modify, distribute, and sublicense closegate in commercial and non-commercial settings, subject to the Apache-2.0 terms.

## Contributing

closegate is pre-1.0. See [`CONTRIBUTING.md`](CONTRIBUTING.md) for the issue-
first workflow, code style, and PR process. Conduct expectations are in
[`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md). Security disclosures go through
[`SECURITY.md`](SECURITY.md).
