# @trucore/openclaw-atf

OpenClaw plugin for the **TruCore Agent Transaction Firewall (ATF)**.

Gives OpenClaw agents first-class tools to discover, adopt, and report on ATF — the policy-enforced transaction firewall for autonomous DeFi agents. ATF evaluates swap, lend, and perps intents against a human-configured policy before any transaction reaches the chain. It never signs. It is deny-by-default.

> **New to the Protected Bot Execution Standard?** Start with the
> [Developer Adoption Guide](../../docs/specs/developer-adoption-guide.md)
> for quickstarts, adapter chooser, and canonical field reference.

---

## Install

```sh
openclaw plugins install @trucore/openclaw-atf
openclaw gateway restart
```

---

## Quick Start — Install, Enable, Verify, Disable

### 1. Install

```sh
openclaw plugins install @trucore/openclaw-atf
```

### 2. Enable (minimal config — zero keys required)

Add to your OpenClaw config (`~/.openclaw/openclaw.json` by default, or
`$OPENCLAW_CONFIG` if set):

```json
{
  "plugins": {
    "trucore-atf": {}
  }
}
```

That's it. All defaults are safe and correct for most environments.

### 3. Restart and verify

```sh
openclaw gateway restart
openclaw tool call atf_integration_doctor
```

**Healthy state checklist:**
- `status` = `"ok"`
- `plugin_loaded` = `true`
- `native_tools_available` lists all 13 tools
- `native_tools_missing` is empty `[]`
- `config_validation.valid` = `true`
- `warnings` is empty or contains only informational items

### 4. Disable (if needed)

Set plugin entries to empty in `~/.openclaw/openclaw.json`:

```json
{
  "plugins": {}
}
```

Then: `openclaw gateway restart`. The install is preserved — re-enable at
any time by adding `"trucore-atf": {}` back. This has zero effect on
ATF CLI/API.

**See also:** [examples/](examples/) for copy-paste-safe config files.

---

## What this plugin does

This plugin registers **13 optional agent tools** into OpenClaw:

| Tool | Purpose |
|---|---|
| `atf_health` | Check ATF CLI/API availability and readiness |
| `atf_discover` | Fetch and summarise the ATF manifest (capabilities, recipes, feature gates) |
| `atf_bootstrap_plan` | Generate ATF self-install steps for a recipe (plan only, no side effects) |
| `atf_bootstrap_execute_safe` | Run safe bootstrap steps locally (env setup + verify, no signing) |
| `atf_protect_intent` | Submit a DeFi intent for policy evaluation — returns allow/deny + receipt |
| `atf_verify_receipt` | Verify a receipt deterministically (proof for humans) |
| `atf_report_savings` | Generate a receipt-backed "ATF saved you" report |
| `atf_integration_doctor` | Run integration readiness check — reports plugin/backend/tool status |
| `atf_bot_preflight` | Pre-session readiness check — returns go/no-go with backend + config diagnostics |
| `atf_tx_explain` | Explain ATF deny decisions — maps reason codes to human-readable explanations |
| `atf_billing_info` | Billing/pricing metadata for the advanced bot package |
| `atf_billing_claim` | Verify on-chain payment and process billing claim |
| `atf_adoption_advisor` | Deterministic adoption recommendation for bots |

All tools are **optional** — agents and operators must opt in via OpenClaw's tool allowlist. Default-safe:

- `safety.allowNetwork = false` — `atf_discover` returns offline instructions unless explicitly enabled.
- `safety.allowExecuteSafe = true` — bootstrap execute-safe runs (env/verify only; no signing).
- ATF **never signs transactions**.

### Diagnostic tools

`atf_bot_preflight` is a lightweight readiness check designed for bot startup:
it probes CLI/API availability, validates plugin config, and returns a single
`ready: true/false` signal with remediation steps if needed.

`atf_tx_explain` maps ATF deny reason codes to structured human-readable
explanations with category, description, and remediation guidance.  It works
offline and requires no backend — it reads from the built-in reason code
catalog.  Pass either a `reasonCodes` array or a full `receipt` object.

---

## Enable tools

The simplest config enables all plugin tools with safe defaults:

```json
{
  "plugins": {
    "trucore-atf": {}
  }
}
```

To explicitly allowlist individual tools and customize settings:

```json
{
  "plugins": {
    "trucore-atf": {
      "prefer": "cli",
      "receiptsDir": "./atf_receipts"
    }
  },
  "tools": {
    "alsoAllow": [
      "atf_health",
      "atf_protect_intent",
      "atf_verify_receipt",
      "atf_integration_doctor"
    ]
  }
}
```

To allow live manifest fetching, set `safety.allowNetwork = true` (agent environment must have outbound HTTP access).

---

## Config reference

| Field | Type | Default | Description |
|---|---|---|---|
| `atfCli` | string | `"atf"` | CLI command name or absolute path |
| `atfBaseUrl` | string | — | Base URL for HTTP API mode (e.g. `https://api.trucore.xyz`) |
| `prefer` | `"cli"` \| `"api"` | `"cli"` | Whether to call ATF via CLI subprocess or HTTP API |
| `receiptsDir` | string | — | Directory of ATF receipt JSON files (used by `atf_report_savings`) |
| `safety.allowExecuteSafe` | boolean | `true` | Allow `atf_bootstrap_execute_safe` to run |
| `safety.allowNetwork` | boolean | `false` | Allow `atf_discover` to fetch the manifest over the network |

---

## Integration Doctor

Validate the full integration in one step:

```sh
openclaw tool call atf_integration_doctor
```

Returns a structured readiness report including:
- Plugin loading status
- CLI / API availability
- Backend preference vs effective backend (with fallback details)
- Registered tool inventory
- Configuration warnings and remediation steps

Status values: `ok`, `degraded`, `misconfigured`, `unavailable`.

See the [operator runbook](../../docs/runbooks/openclaw-plugin-operations.md) for expected outputs and troubleshooting.

---

## Backend preference

The plugin supports two backends:

| Backend | When to use |
|---|---|
| `cli` (default) | Local dev, offline, ATF CLI installed |
| `api` | Hosted environments, shared infra, centrally deployed ATF API |

Set `prefer` in your plugin config. If the preferred backend is unavailable, the plugin falls back to the other automatically. Both `atf_health` and `atf_integration_doctor` report what was preferred, what was chosen, and why fallback occurred.

---

## Example: "ATF saved you" message

When your agent runs `atf_report_savings`, it produces a receipt-backed human summary like:

```
=== ATF Protection Summary ===

ATF prevented 12 risky actions.

Top deny reasons:
  • PERPS_MARKET_NOT_ALLOWED: 7 times
  • PERPS_ORDER_TYPE_NOT_ALLOWED: 3 times
  • SWAP_SLIPPAGE_TOO_HIGH: 2 times

Evidence: 12 verified receipts.
  receipt: sha256:a1b2c3d4e5f6...
  receipt: sha256:9e8d7c6b5a4f...
  ... and 10 more.

No savings estimate available. To enable estimates, include
exposure_hints (notional_usd, leverage, slippage_bps) in
intentJson when calling atf_protect_intent.

Verify receipts: atf receipts verify --receipt <hash>
```

When `exposure_hints` are provided at protect time, the report adds a conservative estimate:

```
Conservative savings estimate: $4,200.00
  (Assumptions: estimate is based on exposure_hints
  (notional_usd, leverage, slippage_bps) provided at protect time.
  Actual outcomes may differ.)
```

The estimate is **never invented** — it is only shown if `exposure_hints` are present. receipts are always cited.

---

## Example: verified receipt snippet

```json
{
  "verified": true,
  "content_hash": "sha256:a1b2c3d4e5f6789abcdef...",
  "intent_hash": "sha256:fedcba987654321...",
  "allow": false,
  "reason_codes": ["PERPS_MARKET_NOT_ALLOWED"],
  "chain_id": "solana",
  "intent_type": "perps_open"
}
```

Verify any receipt yourself:

```sh
atf receipts verify --receipt sha256:a1b2c3d4e5f6...
```

---

## OpenClaw plugin option (fastest path)

> **Fastest path for OpenClaw agents to adopt ATF:**

```sh
# 1. Install the plugin
openclaw plugins install @trucore/openclaw-atf
openclaw gateway restart

# 2. The agent can now call:
#    atf_discover       → learn what ATF does
#    atf_bootstrap_plan → get self-install steps
#    atf_bootstrap_execute_safe → run safe setup
#    atf_protect_intent → guard every DeFi action
#    atf_verify_receipt → prove decisions to humans
#    atf_report_savings → generate savings report
```

No custom coding required for drop-in protection.

---

## Manual integration (without OpenClaw)

```sh
# Install ATF CLI
npm install -g @trucore/atf

# Self-install ATF
atf bootstrap --format json --recipe bootstrap_local
atf bootstrap --execute-safe --recipe bootstrap_local

# Protect an intent
echo '{"chain_id":"solana","intent_type":"swap","intent":{...}}' | atf bot protect --stdin

# Verify a receipt
atf receipts verify --receipt sha256:aabbcc...

# Generate savings report
atf report savings --receipts-dir ./atf_receipts --format json
```

Full docs: [docs/runbooks/agent-adoption-atf.md](../../docs/runbooks/agent-adoption-atf.md)

---

## Jupiter Endpoint Configuration

ATF swap commands use the canonical Jupiter v6 production endpoint by default:

```text
https://quote-api.jup.ag/v6
```

Override via environment:

| Variable | Purpose |
| --- | --- |
| `ATF_JUPITER_BASE` | Full override (takes priority over all other settings) |
| `ATF_JUPITER_API_KEY` | API key for x-api-key header (never logged) |
| `ATF_JUPITER_PREPROD` | Set to `1` for preprod endpoint (explicit opt-in only) |

Or via ATF profile config: `jupiter_quote_url` / `jupiter_swap_url`.

---

## Fallback: Direct CLI (if plugin install fails)

If `openclaw plugins install @trucore/openclaw-atf` is unavailable:

```sh
# Install ATF CLI directly
npm install -g @trucore/atf

# Bootstrap
atf bootstrap --recipe bootstrap_local --execute-safe

# Protect an intent
echo '{"chain_id":"solana","intent_type":"swap","intent":{...}}' | atf bot protect --stdin

# Verify receipt
atf receipts verify --receipt sha256:aabbcc...

# Report savings
atf report savings --receipts-dir ./atf_receipts --format json
```

The plugin is an optional convenience layer. All ATF security guarantees
work identically via direct CLI.

---

## Tests

```sh
cd packages/openclaw-atf
node --test tests/test_tools.mjs
node --test tests/test_plugin_package.mjs
node --test tests/test_integration_hardening.mjs
node --test tests/test_doctor.mjs
node --test tests/test_config_ux.mjs
node --test tests/test_activate_validation.mjs
node --test tests/test_native_tools.mjs
node --test tests/test_entrypoint_regression.mjs
node --test tests/test_gateway_load_compat.mjs
node --test tests/test_schema_strict_walk.mjs
node --test tests/test_strict_gateway_validation.mjs
node --test tests/test_toolcard_integrity.mjs
node --test tests/test_pack_artifact.mjs
node --test tests/test_contracts.mjs
node --test tests/test_billing.mjs
node --test tests/test_billing_claim.mjs
node --test tests/test_adoption_advisor.mjs
node --test tests/test_perps_contract.mjs
node --test tests/test_plugin_stabilization.mjs
node --test tests/test_cjs_bridge_dispatch.mjs
node --test tests/test_openclaw_e2e_harness.mjs
```

All tests are offline. No network calls. No ATF CLI required.

### Real E2E Smoke (opt-in)

```sh
OPENCLAW_E2E=1 node scripts/openclaw_e2e_smoke.mjs
```

Requires `openclaw` binary. Uses an isolated temp home by default. Skips
safely when OpenClaw is unavailable. See `docs/runbooks/openclaw-smoke-test.md`.

---

## Plugin exports

The plugin provides the following entry-points:

| Export | Type | Purpose |
|---|---|---|
| `default` | `function(api)` | Legacy single-function entry (calls `register(api)`) |
| `register(api)` | `function` | OpenClaw lifecycle: register tools |
| `activate(ctx)` | `function` | OpenClaw lifecycle: activate (runs non-blocking config validation) |
| `deactivate()` | `function` | OpenClaw lifecycle: deactivate (no-op for stateless ATF) |
| `PLUGIN_ID` | `string` | Canonical plugin identity: `trucore-atf` |
| `PLUGIN_VERSION` | `string` | Current plugin version |
| `buildHumanSummary(report)` | `function` | Human messaging helper for savings reports |
| `REASON_CODE_CATALOG` | `object` | Frozen map of deny reason codes → `{category, explanation, remediation}` |
| `ATF_BILLING_MANIFEST` | `object` | Machine-readable billing/pricing metadata |
| `evaluateAdoption` | `function` | Adoption advisor evaluation function |
| `verifyBillingClaim` | `function` | Billing claim verification function |
| `CLAIM_STATUS` | `object` | Claim status enum |
| `CLAIM_DENY_CODES` | `object` | Claim deny code catalog |
| `TREASURY_ADDRESS` | `string` | Canonical treasury address |
| `USDC_MINT` | `string` | Canonical Solana mainnet USDC mint address |
| `CONTRACT_FAMILIES` | `object` | Universal contract family definitions |
| `TOOL_FAMILY_MAP` | `object` | Tool → contract family mapping |
| `CANONICAL_TOOLS` | `array` | Frozen list of all 13 tool names |
| `CANONICAL_TOOL_COUNT` | `number` | Number of canonical tools (13) |

The canonical plugin ID is `trucore-atf` everywhere: manifest, package.json, config, docs.

---

## Activation-time config validation

When the plugin activates, it validates the config and surfaces any issues as `console.warn` messages. **Invalid config never blocks activation.** The plugin always loads and remains operational.

- **Valid config** — activates silently, no warnings.
- **Config with warnings** — activates normally; warnings logged with `[trucore-atf]` prefix.
- **Config with errors / unsupported keys** — activates normally; errors and unsupported keys logged clearly.
- Warnings include remediation guidance and recommend running `atf_integration_doctor` for full details.

This gives operators immediate feedback at startup without breaking the integration.

---

## Graceful degradation

- If ATF CLI is not installed, tools return clear error messages — never crash.
- If ATF API is unreachable, tools degrade to CLI fallback or return errors.
- If the plugin receives an invalid `api` object, it logs a warning and skips registration.
- If activate() receives invalid or missing context, it degrades silently.
- All tool handlers are wrapped in a safe-handler that catches runtime errors.
- Plugin failure never breaks the OpenClaw gateway or other plugins.

---

## License

MIT — TruCore AI

---

## Install Readiness Check

Before running the real E2E harness, use the readiness script for a
deterministic diagnostic that works even when OpenClaw is NOT installed:

```bash
cd packages/openclaw-atf
node scripts/openclaw_readiness.mjs
```

**What it does:**

- Detects whether `openclaw` binary exists on PATH (or `OPENCLAW_BIN`)
- Shows version and compatibility status if present
- Lists all supported environment variables
- Prints the exact next command to run and the exact success marker
- Maps every failure class to operator remediation
- Generates a copy-paste-ready operator checklist

**Deterministic operator sequence:**

1. `node scripts/openclaw_readiness.mjs` → checklist and next steps
2. Install OpenClaw if absent → <https://openclaw.dev>
3. `node scripts/openclaw_readiness.mjs` → confirm `Installed: YES`
4. `OPENCLAW_E2E=1 node scripts/openclaw_e2e_smoke.mjs` → expect `[e2e] RESULT: ALL CHECKS PASSED`
5. `node --test tests/*.mjs` → all offline tests pass

---

## Execution Contract

All success markers and failure codes are defined in
`scripts/openclaw_execution_contract.mjs` (contract version 1.0.0).
Both the readiness script and the E2E harness import from this single
source of truth. Changes to markers or failure codes require a contract
version bump.

### Success markers (grep-friendly)

| Marker | Phase | Meaning |
|---|---|---|
| `OpenClaw installed : YES` | readiness | Binary detected |
| `Compatible (>=0.1.0) : YES` | readiness | Version meets minimum |
| `[e2e] SKIP:` | e2e | Binary absent — informational skip |
| `[e2e] Packed:` | e2e | Tarball packed |
| `[e2e] Plugin installed successfully.` | e2e | Install OK |
| `[e2e] Config written to:` | e2e | Config enable OK |
| `[e2e] Gateway restarted.` | e2e | Restart OK |
| `: PASS` | e2e | Tool call OK |
| `[e2e] RESULT: ALL CHECKS PASSED` | e2e | **Overall E2E pass** |
| `[e2e] RESULT: SOME CHECKS FAILED` | e2e | One or more steps failed |

### Failure codes

| Code | Severity | Meaning | Operator action |
|---|---|---|---|
| `binary_missing` | skip | Binary not found | Install OpenClaw |
| `version_incompatible` | warn | Version < 0.1.0 | Upgrade OpenClaw |
| `install_failed` | hard | Install command failed | Check tarball / `openclaw plugins install --help` |
| `config_write_failed` | hard | Config write failed | Check OPENCLAW_HOME permissions |
| `restart_failed` | warn | Restart returned nonzero | Try `openclaw server restart` or restart manually |
| `restart_incompatible` | warn | Restart not recognized | Try alternative restart commands |
| `tool_call_failed` | hard | Tool call failed | Check tool registration / try alt syntax |

### Quick validation block

```bash
# Step 1: readiness (always safe, always exit 0)
cd packages/openclaw-atf
node scripts/openclaw_readiness.mjs

# Step 2: E2E (requires openclaw binary)
OPENCLAW_E2E=1 node scripts/openclaw_e2e_smoke.mjs

# Expected success: "[e2e] RESULT: ALL CHECKS PASSED"
# Expected skip if no OpenClaw: "[e2e] SKIP: ..."
# On failure: check the failure code in output against table above
```

---

## One-Command Real Validation (Real Runner)

The real-runner scaffold wraps readiness + E2E into a single deterministic
command for operators and CI runners:

```bash
cd packages/openclaw-atf
OPENCLAW_E2E=1 node scripts/openclaw_real_runner.mjs
```

### What it does

1. Runs readiness check (binary detection, version, compatibility)
2. If OpenClaw missing → exits 0 with contract-driven informational output
3. If OpenClaw present + `OPENCLAW_E2E=1` → runs the full E2E harness
4. Prints a concise final summary block with:
   - Contract version
   - Binary/version status
   - Compatibility status
   - Resolved command forms
   - Result class (`SKIPPED` / `PASSED` / `FAILED`)
   - Observed success markers
5. Optionally writes a sanitized JSON artifact

### Environment variables

| Variable | Required | Description |
|---|---|---|
| `OPENCLAW_E2E` | Yes (for E2E) | Must be `1` to run E2E phase |
| `OPENCLAW_BIN` | No | Path to openclaw binary (default: `openclaw`) |
| `OPENCLAW_HOME` | No | Override home dir (default: temp dir) |
| `OPENCLAW_E2E_ARTIFACT` | No | Set to `1` to write JSON artifact |
| `OPENCLAW_E2E_ARTIFACT_PATH` | No | Custom artifact file path |

### Expected output

**Binary missing (default CI):**
```
Result class       : SKIPPED
```

**Binary present and compatible:**
```
Result class       : PASSED
Success markers    : e2e_pack_ok, e2e_install_ok, e2e_config_ok, ...
```

**E2E failure:**
```
Result class       : FAILED
Failure code       : <failure_code>
```

### Optional artifact output

When `OPENCLAW_E2E_ARTIFACT=1`, the runner writes a sanitized JSON file:

```json
{
  "timestamp": "2026-03-10T00:00:00.000Z",
  "contract_version": "1.0.0",
  "openclaw_detected": true,
  "openclaw_version": "0.3.0",
  "compatible": true,
  "resolved_command_forms": {
    "install": ["plugins", "install"],
    "restart": ["gateway", "restart"],
    "tool_call": ["tool", "call"]
  },
  "result_status": "passed",
  "failure_code": null,
  "success_markers_observed": ["e2e_pack_ok", "e2e_install_ok", "..."]
}
```

The artifact contains **only** non-sensitive metadata. No secrets, no raw
home paths, no tokens.

### Compatibility row capture template

After the first successful real validation, record the result:

| Field | Value |
|---|---|
| Date | |
| OpenClaw version | |
| Command forms: install | |
| Command forms: restart | |
| Command forms: tool call | |
| Install path used | tarball / npm |
| Result | passed / failed / skipped |
| Notes | |

Or generate a prefilled row from the artifact:

```bash
node scripts/openclaw_compat_row.mjs /tmp/openclaw-binary-present-proof.json
```

---

## Binary-Present Proof Run

When OpenClaw is installed and you want to validate the full E2E path in
one shot, use the **binary-present proof checklist**:

```bash
# Full sequence:
cd packages/openclaw-atf
openclaw --version                     # A. confirm binary
node scripts/openclaw_readiness.mjs    # B. readiness check
OPENCLAW_E2E=1 \
OPENCLAW_E2E_ARTIFACT=1 \
OPENCLAW_E2E_ARTIFACT_PATH=/tmp/openclaw-binary-present-proof.json \
  node scripts/openclaw_real_runner.mjs  # C. real-runner with artifact
cat /tmp/openclaw-binary-present-proof.json | python3 -m json.tool  # D. inspect
node scripts/openclaw_compat_row.mjs /tmp/openclaw-binary-present-proof.json  # E. row
node --test tests/*.mjs                # F. offline tests
```

**Pass:** `Result class: PASSED` and `result_status: "passed"` in artifact.
**Fail:** Check `failure_code` — see failure codes table above.
**Skip:** Binary not detected — install OpenClaw first.

Full step-by-step: [docs/openclaw_binary_present_proof_checklist.md](docs/openclaw_binary_present_proof_checklist.md)
