Metadata-Version: 2.4
Name: kyvvu-claude
Version: 1.0.0
Summary: Kyvvu compliance integration for Claude Code — policy enforcement via hooks
Author-email: "Kyvvu B.V." <info@kyvvu.com>
License: Copyright 2026 Kyvvu B.V.
        
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
        
        http://www.apache.org/licenses/LICENSE-2.0
        
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
        
        This license applies only to the contents of the kyvvu-claude/ directory
        of the Kyvvu monorepo. Other directories in this monorepo are governed
        by their own LICENSE files.
        
Project-URL: Documentation, https://docs.kyvvu.com/
Project-URL: Changelog, https://docs.kyvvu.com/reference/changelog
Project-URL: Issues, https://github.com/Kyvvu/issues/issues
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: kyvvu-engine<2.0.0,>=1.0.0
Requires-Dist: kyvvu-templates<2.0.0,>=1.0.0
Requires-Dist: kyvvu-cli<2.0.0,>=1.0.0
Requires-Dist: httpx>=0.27
Requires-Dist: typer>=0.12
Requires-Dist: rich>=13
Provides-Extra: dev
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: jsonschema<5,>=4.23; extra == "dev"
Requires-Dist: rfc3339-validator>=0.1.4; extra == "dev"
Requires-Dist: pyyaml>=6.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: ruff>=0.16.9; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Dynamic: license-file

# kyvvu-claude

Kyvvu agent-security integration for Claude Code. Its hooks evaluate tool calls against [Kyvvu](https://kyvvu.com) policies before execution, can block calls that violate those policies, and record observed calls as an audit trail. When the trail goes to the platform, the client computes its hash chain (v1) and the platform verifies it on arrival.

## Installation

Claude Code support is the `claude-code` extra of `kyvvu-cli`, the `kyvvu` command line. It installs this package as the plugin that adds the `kyvvu claude` commands:

```bash
uv tool install "kyvvu-cli[claude-code]"
```

Requires Python 3.11+ and macOS or Linux.

## Getting started

### 1. Create a Kyvvu account

Sign up at [platform.kyvvu.com](https://platform.kyvvu.com) and create an API key under **Workspace → API Keys**. The API key starts with `KvKey-`.

### 2. Set up Claude Code

```bash
kyvvu claude setup
```

This interactive wizard will:
- Connect to the Kyvvu API (defaults to `https://platform.kyvvu.com`)
- Register your Claude Code instance as a Kyvvu agent
- Fetch policies assigned to your agent
- Install hooks into Claude Code's `~/.claude/settings.json`

Setup uses the API URL saved by `kyvvu auth` in `~/.kyvvu/config.toml`. The
agent API key comes from `--api-key` or `KV_API_KEY`, else a prompt with echo
off. For a
scripted setup, export `KV_API_KEY`
(and `KV_API_URL`), and set the agent key, environment and EU AI Act owner
with `--agent-key`, `--environment` and `--owner`; `kyvvu claude setup --help`
lists them all. Without `--owner` the platform records the API key owner's
email as the agent's owner.

### 3. Start using Claude Code

Run `kyvvu claude status` to verify that all hook events are installed. With the hooks running, Claude Code tool calls are evaluated before they run. Open the [Kyvvu dashboard](https://platform.kyvvu.com) to see your agent's behavioral traces.

### 4. Default policies

Nothing to assign: registration applies the **Claude Code Safety** manifest (`manifests/developer/claude-code-safety.yaml`) and the EU AI Act minimal/limited-risk manifest automatically. Claude Code Safety protects against:

- Credential exfiltration (blocks Bash after reading `.env`, `.pem`, `.key` files)
- Destructive commands (`git push --force`, `rm -rf /`, `git reset --hard`)
- Scope escape (writes to `/etc`, `~/.ssh`, `~/.aws`)
- Runaway loops (max 50 Bash calls, max 10 consecutive)
- PII in commands (SSN, credit card patterns)

To add more manifests, use the dashboard's **Manifests** page or the `kyvvu` command line you installed `kyvvu claude` with (`kyvvu auth`, then `kyvvu assign-manifest --agent-id <the agent key from kyvvu claude status> ...`).

## How it works

kyvvu-claude uses Claude Code's [hook system](https://docs.claude.ai/en/docs/hooks). Each hook invocation is a fresh process that reads JSON from stdin and writes JSON to stdout.

```
Claude Code                          kyvvu-claude
    |                                     |
    +-- SessionStart --stdin JSON--->  Register task, fetch policies from API
    |                                  Return status message
    |
    +-- PreToolUse ----stdin JSON--->  Map tool -> Kyvvu Behavior
    |                                  Evaluate policies (local, <50ms)
    |                                  Block or allow
    |
    +-- PostToolUse ---stdin JSON--->  Record completed step in session history
    |                                  (for path-dependent rules)
    |
    +-- SubagentStart -stdin JSON--->  Link spawned sub-agent to its parent
    |                                  Agent/Task step (back-reference)
    |
    +-- SubagentStop --stdin JSON--->  Record sub-agent boundary in the trail
    |
    +-- SessionEnd ----stdin JSON--->  Flush remaining audit steps to API
                                       Clean up session
```

Policy evaluation is fully local via [kyvvu-engine](https://pypi.org/project/kyvvu-engine/) — no network I/O on the hot path. Policies are fetched from the API at session start and cached on disk.

LLM calls are captured from Claude Code's session transcript (model name, token usage, proposed tools) and included in the behavioral trace.

Audit steps also flush when the count reaches `flush_threshold` or, on the next
hook, when the oldest pending step reaches `flush_interval_seconds`. A new
`SessionStart` retries unflushed steps left by other sessions before stale
session cleanup. More frequent flushes reduce the amount delayed by an abrupt
exit, at the cost of more HTTP requests and hook latency. The client records a
durable exported-through cursor before trimming sent steps, so a crash after
that cursor write does not resend them. A crash after the API's 201 response
but before the cursor write resends the HTTP batch with the same idempotency
key. The API replays its acknowledgement without storing the batch again while
the seven-day receipt is retained.

## The audit trail model

The audit trail is a **single flat list of steps per task** — there is no nesting and no per-sub-agent `task_id`. Two things define ordering and structure:

- **`seq` is the order of the record.** It is strictly increasing per (`agent_id`, `task_id`), may have gaps, and is assigned by the client that opened the task — here, the session's hooks. **Read the trail in `seq` order**: that is the order in which steps were recorded. It says nothing about which of two concurrent tool calls happened first. kyvvu-claude currently assigns it when a step is recorded (a tool call when it is admitted at `PreToolUse`, an LLM call when the hook reads it from the transcript); that is an implementation detail, not a promise. The order in which calls finished is tracked separately, in local session state only (`completion_order`, used for policy evaluation, not exported). Consumers must not assume `seq` is contiguous, nor that a higher `seq` means "caused by" a lower one: Claude Code runs tool calls in parallel batches that sub-agents widen.
- **Timestamps are claimed times.** Every step carries a UTC timestamp: tool steps are stamped when the hook records them, and `step.model` (LLM call) steps reuse the timestamp from Claude Code's transcript, which is when the call is claimed to have happened (a transcript timestamp without an offset is read as UTC; one that cannot be parsed is replaced by the hook's own time). A timestamp is what the producer says, not the order of the record, so it can disagree with `seq`.

### Sub-agent partial order (flat storage, reconstructable)

When Claude Code fans out to sub-agents (the `Task`/`Agent` tool), every sub-agent's inner tool calls are merged into the same flat task trail. Flat storage is retained, but enough structure is **stamped** onto each step that the meaningful partial orders reconstruct without nesting:

- Each step carries a sub-agent correlation stamp under `properties["kyvvu.subagent"]`: `{"id": <tag>, "depth": <0|1>, "spawn_seq": <parent step>}`. The tag is `"main"` for the parent session, or the sub-agent's id derived from its dedicated transcript path (`…/subagents/agent-{id}.jsonl`).
- **Within one sub-agent:** group steps by their `kyvvu.subagent.id`, then order by `seq`. This keeps a sub-agent's own read-then-exec sequence intact even though a sibling's steps may be interleaved in flat storage.
- **Parent → child:** each sub-agent step carries `spawn_seq`, the parent `Agent`/`Task` step that spawned it (established from the `SubagentStart` lifecycle hook). This preserves the platform-guaranteed "read `.env`, then delegate" happens-before.
- **Cross-sibling order is deliberately not preserved** — concurrent siblings are a genuine race, so their relative order is dropped (out of scope per design).

**Enforcement is independent of these tags.** Policy replay is always **whole-task (conservative)**: at every `PreToolUse` the engine replays the entire task history regardless of sub-agent lineage, so a secret read in one sub-agent still taints exec anywhere in the task. The sub-agent tags are for storage and reconstruction only — they never scope enforcement.

## What this control does and does not prevent

With the hooks installed and a blocking policy in force, kyvvu-claude can deny
a tool call before Claude Code runs it. `kyvvu claude status` checks that all six
hook events are wired in `~/.claude/settings.json`; it exits non-zero and names
any missing or misconfigured event. The dashboard records the agent's last
authenticated policy fetch or log batch. When an administrator sets an expected
cadence for that agent, the dashboard marks it silent after that interval.

A person who controls the local machine can remove or change the hooks, alter
local configuration, or prevent the hook process from running. Local checks
cannot prevent that person from bypassing them. A status check only describes
the settings file at the time it runs; a last-seen or silence indicator detects
missing contact after the fact, according to the configured cadence. Neither
proves that every tool call was checked or that a quiet agent was running.

## Enforcement behavior

When a policy blocks a tool call, kyvvu-claude returns `permissionDecision: "deny"` to Claude Code. This **denies the specific tool call** but **does not stop the agent**. Claude Code treats it like a permission denial — the model continues reasoning and may try alternative approaches.

This is intentional and consistent with Claude Code's hook design:

- The blocked step is recorded in the audit trail with `output.status = "blocked"`
- The policy name and severity are logged locally in `~/.kyvvu/integrations/claude-code/session.log`
- An incident is reported to the Kyvvu API
- The model receives the block reason and adapts

**The cached policy set must be for this agent.** Every hook evaluates under
the `agent_id` in the config, and the policy cache records the agent the
platform served its set for. When they differ (the agent was re-created on the
platform, `setup` registered another agent and its refresh failed, or the config
was edited or copied), none of that agent's policies would apply, so the state
is `NOT ENFORCING` and every tool call is **denied under `enforce`**
(`UNCHECKED` in monitor mode). The message names both ids; run
`kyvvu claude setup` to recover, and `kyvvu claude status` to compare them.

Files in `~/.kyvvu/integrations/claude-code` are written with POSIX mode `0600`. New directories
use `0700`; existing directories lose group and other access without gaining
owner permissions. `kyvvu claude status` reports paths with unexpected modes.
These mode guarantees apply on POSIX filesystems; Windows and filesystems
without POSIX modes may not enforce them.

**Tainted-path policies** (credential exfiltration guard) are permanent within a session: after reading a secret file (`.env`, `.pem`, `.key`, etc.), ALL subsequent Bash commands and file reads outside the project are blocked. Use `/clear` in Claude Code to start a new session and reset the taint.

## Tool mapping

The `kind` field identifies the action kind assigned to each Claude Code tool;
the mapping below shows the value recorded for each tool.

| Claude Code Tool | Action kind     | Verb  | Properties                        |
|-----------------|-----------------|-------|-----------------------------------|
| Bash            | step.exec       | -     | command (+ target.host / data.classification parsed from shell writes & secret reads) |
| Read            | step.resource   | GET   | target.host (file path)           |
| Write           | step.resource   | POST  | target.host (file path)           |
| Edit            | step.resource   | PATCH | target.host (file path)           |
| Glob            | step.resource   | GET   | target.host, target.pattern       |
| Grep            | step.resource   | GET   | target.host, target.pattern       |
| WebFetch        | step.resource   | GET   | target.host (URL)                 |
| WebSearch       | step.resource   | GET   | target.host (query)               |
| Agent           | step.self       | POST  | target.description                |
| NotebookEdit    | step.resource   | PATCH | target.host (notebook path)       |
| mcp__*          | step.resource   | *     | target.mcp_server, target.mcp_tool|
| (unknown)       | step.unknown    | -     | -                                 |

Tool arguments for every tool, including unknown tools, are recorded under
`input`. The properties above are derived fields used for policy evaluation;
tool arguments are not copied into properties. Model calls record proposed tool
names under `output.proposed_tools`.

Files matching secret patterns (`.env`, `.pem`, `.key`, `.secret`, `.credentials`, `.pgpass`, `.netrc`) are automatically classified with `data.classification: secret` for tainted-path policies. This applies both to the file tools (Read/Edit/Write/Glob/Grep) and to **shell commands**: a `Bash` command that reads a secret file (`cat .env`, `cp *.pem …`) is classified too, and a `Bash` shell write (`>`, `>>`, `tee`, `cp`, `mv`, …) sets `target.host` so scope-containment policies apply to shell writes — not just the `Write`/`Edit` tools.

### What this does not prevent

Bash is an opaque command string to the hook. Regular expressions recognize common literal reads and writes; they do not execute or fully interpret shell syntax. A command can read a secret or write outside the project without producing the classification or target that these policies need. Known misses include `python -c` and here-doc programs that write files, a write hidden behind `bash -c`, `eval`, `xargs`, or base64-decoded commands, and secret reads through a variable, split quotes (`cat .en''v`), command substitution (`env $(cat .en''v)`), or backticks. Conversely, `echo "value > /etc/hosts"` is only printing text, but the redirect regex treats `/etc/hosts` as a write target and can cause a false block.

Treat hook checks as defense in depth. For a real boundary, run the agent with a read-only bind mount over protected paths, a restricted `PATH`, network egress controls, and a user that cannot read secret files. We do not add a shell parser: even a parser that handles quoting and redirection cannot determine what `eval`, variables, or decoded commands will do at runtime.

## Configuration

Stored at `~/.kyvvu/integrations/claude-code/config.json`:

| Field                          | Default                       | Description                                                      |
|-------------------------------|-------------------------------|------------------------------------------------------------------|
| api_url                       | https://platform.kyvvu.com    | Kyvvu API URL (policy fetch + agent registration)                |
| log_location                  | `auto` (follows policy source)| WHERE logs go. `stdout` = local. `none` = disabled. Can be a URL or file path. `auto` resolves to the platform when it is the policy source, else `stdout`. |
| log_format                    | kv                            | HOW logs are formatted: `kv` (Kyvvu API), `json`, or `otlp`     |
| incident_location             | (empty = inherit trace sink)  | WHERE incidents go. Same vocabulary as `log_location`; empty inherits the trace sink. |
| incident_format               | (empty = inherit log_format)  | HOW incidents are formatted: `kv`, `json`, or `otlp`. Empty inherits `log_format`. |
| api_key                       | (required)                    | API key from your Kyvvu organization (KvKey-...)                 |
| agent_id                      | (auto)                        | Assigned at registration                                         |
| enforce                       | false                         | `true` = block violations, `false` = observe-only (log but allow) |
| fail_mode                     | open                          | `open` = allow on hook or evaluation failure; `closed` = deny PreToolUse when a check fails or no policies are loaded, even in monitor mode. Other hook events remain nonblocking. |
| agent_key                     | `claude-code-<host>-<user>`   | The key the agent registers under (`kyvvu claude setup --agent-key`)         |
| owner_id                      | (empty = the API key owner)   | EU AI Act owner, sent as `owner_id` at registration (`kyvvu claude setup --owner`) |
| environment                   | `KV_ENVIRONMENT`, else production | `development`, `qa`, `staging`, or `production` (`kyvvu claude setup --environment`) |
| risk_classification           | limited                       | EU AI Act tier: `high`, `limited`, or `minimal`                  |
| flush_threshold               | 100                           | Flush after N pending steps (0 disables count-based flush)       |
| flush_interval_seconds        | 60                            | Flush old pending steps on the next hook (0 disables interval flush) |
| log_full_content              | false                         | `false`: export tool `input` and `output` as `{redacted, bytes, sha256}` summaries; retain structural properties (resource type, MCP names, classification, subagent links) and model metadata, but omit copied commands, queries, paths, and other input values. Gate decisions, model stop reasons and proposed tool names, abandoned status, and task boundaries remain visible. `true`: export full recorded input, output, and properties. Local policy checks always use full input. |

Choose the fail mode during `kyvvu claude setup` (or pass `--fail-mode closed` for
scripted setup), or set `fail_mode` in `config.json`. Closed mode
only covers failures inside the running hook process. If the executable is
missing, a hook times out, or the hook entry is removed from Claude Code's
settings, no verdict is delivered and Claude Code may proceed.

## Compatibility

kyvvu-claude uses Claude Code's hook system. It works with:

- **Claude Code CLI** (`claude` command)
- **VS Code extension** (Claude Code in VS Code)
- **JetBrains plugin** (Claude Code in IntelliJ/PyCharm)
- **GitHub Actions** (`anthropics/claude-code-action`) — reads `.claude/settings.json` from repo

Claude Desktop now exposes hooks too. A dedicated kyvvu-claude Desktop
integration is planned;
the setup commands above currently target Claude Code settings.

## CLI commands

| Command | Description |
|---------|-------------|
| `kyvvu claude setup` | Interactive setup: API connection, agent registration, hook installation. `--api-url`, `--api-key`, `--agent-key`, `--environment`, `--owner`, `--fail-mode` answer their prompts |
| `kyvvu claude hooks install` | Install hooks into `~/.claude/settings.json` (also offered during setup); `--project` writes `.claude/settings.json` in the current directory instead |
| `kyvvu claude hooks remove` | Remove kyvvu claude hooks from Claude Code settings (`--project` for the current directory's) |
| `kyvvu claude status` | Show current configuration, policy count, active sessions |
| `kyvvu claude set` | Change a saved option, for example `enforce true` or `fail-mode closed` |
| `kyvvu claude policies` | Display cached policies as a table |
| `kyvvu claude refresh` | Force policy refresh from the API |

## Known limitations

- **Tool blocks deny the tool call but do not stop the session** — Claude Code continues reasoning and may try alternatives. This is consistent with how Claude Code handles permission denials.
- **LLM calls are observed, not blocked** — captured from the session transcript (model name, token usage) but cannot be intercepted pre-flight since no hook fires before model inference.
- **LLM call capture may miss very short sessions** — the transcript is written asynchronously by Claude Code; in sessions under ~10 seconds, LLM calls may not appear in the trace.
- **Claude Desktop integration is pending** — Desktop has hooks, but this setup currently installs Claude Code hooks.
- **macOS and Linux only** — uses `fcntl.flock` for session file locking (no Windows support).

## Uninstalling

```bash
kyvvu claude hooks remove
uv tool uninstall kyvvu-cli
rm -rf ~/.kyvvu/integrations/claude-code
```
