# @origintrail/context-graph-openclaw

[OpenClaw](https://github.com/origintrail/openclaw) adapter for [`@origintrail/context-graph`](../context-graph). Automatically captures agent execution traces as [PROV-O](https://www.w3.org/TR/prov-o/) provenance events with hash chain integrity and Ed25519 signed submissions.

## What it does

When installed as an OpenClaw plugin, this adapter **automatically captures every tool call** your agent makes — file reads, writes, shell commands, git operations — and turns them into a verifiable provenance graph. Test runs and builds are auto-detected from shell output and promoted to typed events with parsed metrics.

At session end, claims like "CanFixTests" and "CanRunTests" are derived from the observed outcomes. The resulting public graph is signed with Ed25519 and can be submitted to [ClawTrail](https://clawtrail.ai) for reputation building.

```
OpenClaw Agent
  ├── read file      → FILE_READ event (path hashed)
  ├── write file     → FILE_WRITE event (diff hashed)
  ├── npx jest       → TEST_RUN event (pass/fail counts parsed)
  ├── npx tsc        → BUILD_RUN event (error counts parsed)
  └── git commit     → GIT_COMMIT event (message hashed)
                          │
                          ▼
                   Hash-chained JSONL log
                          │
                          ▼
              Summarize → claims + metrics
                          │
                          ▼
              Ed25519 signed public graph
                          │
                          ▼
              submission.signed.json (→ ClawTrail API)
```

**Privacy:** File contents, diffs, command strings, and stdout are **never stored** — only their SHA-256 hashes. The public graph contains aggregate metrics and claims, never raw data.

## Install

### As an OpenClaw plugin

```bash
# Install both packages
npm install @origintrail/context-graph @origintrail/context-graph-openclaw
```

Or link locally during development:

```bash
# Build the core engine first
cd context-graph
npm install && npm run build

# Then the adapter
cd ../context-graph-openclaw
npm install && npm run build
```

### Register with OpenClaw

Add to your OpenClaw plugin configuration:

```json
{
  "plugins": [
    {
      "id": "context-graph",
      "package": "@origintrail/context-graph-openclaw",
      "config": {
        "enabled": true,
        "agentId": "agent:openclaw:my-coder",
        "detectTests": true,
        "detectBuilds": true
      }
    }
  ]
}
```

The plugin hooks into OpenClaw's `session_start`, `session_end`, `before_tool_call`, and `after_tool_call` lifecycle events automatically.

### Standalone (without OpenClaw)

You can use the adapter directly in any Node.js environment:

```typescript
import { OpenClawAdapter } from "@origintrail/context-graph-openclaw";

const adapter = new OpenClawAdapter({
  contextGraphRoot: ".context-graph",
  agentId: "agent:my-agent",
  detectTests: true,
  detectBuilds: true,
});

// Create a mock context (or use your own session management)
const ctx = {
  sessionKey: "session-1",
  initialMessage: "Fix the auth bug",
  set: (k, v) => sessionStore.set(k, v),
  get: (k) => sessionStore.get(k),
};

// Start session
await adapter.onSessionStart(ctx);

// Feed tool call results as they happen
await adapter.onAfterToolCall(
  {
    toolName: "bash",
    params: { command: "npm test" },
    result: { stdout: "Tests: 5 passed, 0 failed", exitCode: 0 },
    durationMs: 3200,
  },
  ctx,
);

await adapter.onAfterToolCall(
  {
    toolName: "write",
    params: { path: "src/auth.ts" },
    result: { content: "...", bytesWritten: 200 },
    durationMs: 15,
  },
  ctx,
);

// End session
await adapter.onSessionEnd(ctx);

// Summarize + sign
const sessionId = ctx.get("cg:session_id");
const { summary, signed } = await adapter.summarizeAndSign(sessionId);

console.log(summary.claims); // [{ type: 'cg:CanRunTests', confidence: 0.8, scope: 'jest' }]
console.log(signed.payloadHash); // sha256:...
console.log(signed.signature); // base64 Ed25519 signature

// Verify the signature (e.g. on the ClawTrail server side)
const valid = OpenClawAdapter.verifySubmission(signed);
console.log(valid); // true
```

## How tool calls are mapped

| OpenClaw tool       | Event type      | What's captured                                 |
| ------------------- | --------------- | ----------------------------------------------- |
| `bash` / `shell`    | `SHELL_COMMAND` | cmd hash, exit code, stdout/stderr hash         |
| ↳ if test detected  | `TEST_RUN`      | framework, passed, failed, skipped              |
| ↳ if build detected | `BUILD_RUN`     | tool, error count, warning count                |
| `read`              | `FILE_READ`     | path hash, extension, byte count                |
| `write` / `edit`    | `FILE_WRITE`    | path hash, extension, diff hash, byte count     |
| `git` (diff)        | `GIT_DIFF`      | diff hash, files changed, insertions, deletions |
| `git` (commit)      | `GIT_COMMIT`    | commit hash, message hash                       |
| anything else       | `TOOL_CALL`     | tool name, args hash, result hash               |

### Auto-detected test frameworks

Jest, Vitest, Mocha, pytest, Hardhat test, Cargo test, Go test

### Auto-detected build tools

TypeScript (tsc), Webpack, Vite, Cargo build, Go build, Hardhat compile

## Signing

Every submission is signed with **Ed25519**:

1. A keypair is auto-generated on first use (saved to `.context-graph/signing-key.pem`)
2. The public graph is JSON-serialized and SHA-256 hashed
3. The hash is signed with the private key
4. The `submission.signed.json` contains: payload, hash, signature, and public key

ClawTrail (or any verifier) can check the signature:

```typescript
import { OpenClawAdapter } from "@origintrail/context-graph-openclaw";

// Load the signed submission (e.g. from an API request body)
const submission = JSON.parse(
  fs.readFileSync("submission.signed.json", "utf-8"),
);

const valid = OpenClawAdapter.verifySubmission(submission);
// true if payload matches hash AND signature is valid
```

This provides **non-repudiation**: the agent that produced the work is cryptographically bound to the submission.

## Claims derived

| Claim                       | When it fires                            | Confidence |
| --------------------------- | ---------------------------------------- | ---------- |
| `cg:CanFixBuild`            | Build failed → succeeded in same session | 0.9        |
| `cg:CanFixTests`            | Tests failed → succeeded in same session | 0.9        |
| `cg:CanRunTests`            | 3+ successful test runs                  | 0.8        |
| `cg:CanRecoverFromError`    | Error → subsequent success               | 0.85       |
| `cg:CanWrite:<lang>`        | File writes targeting `.ts`, `.py`, etc. | 0.3        |
| `cg:CanUseFramework:<name>` | Test/build framework usage               | 0.5        |
| `cg:CanUseTool:<name>`      | Shell tool usage (git, npm, etc.)        | 0.4        |

Plus the built-in rules from `@origintrail/context-graph`:

| Claim                   | When it fires                      | Confidence |
| ----------------------- | ---------------------------------- | ---------- |
| `cg:CanCompleteSession` | Session completed with > 5 actions | 0.6        |
| `cg:IntegrityValid`     | Hash chain is fully valid          | 1.0        |

## Agent-facing skill

The adapter ships with a `SKILL.md` that instructs the agent:

- Context Graph captures tool calls automatically — no agent action needed
- `context-graph.status` — check session progress
- `context-graph.summarize` — generate metrics and claims
- Never include raw code or secrets in notes (redaction is automatic)

## Demo

Run the interactive end-to-end demo that simulates a full agent session:

```bash
npx tsx demo.ts
```

This demonstrates: event capture → hash chain → Merkle root → claims → metrics → privacy verification → Ed25519 signing → tamper detection → export formats → storage layout.

## Configuration

```json
{
  "enabled": true,
  "contextGraphRoot": ".context-graph",
  "agentId": "agent:openclaw:my-coder",
  "policyPath": "policy.yaml",
  "detectTests": true,
  "detectBuilds": true,
  "signingKeyPath": ".context-graph/signing-key.pem"
}
```

| Option             | Default          | Description                                  |
| ------------------ | ---------------- | -------------------------------------------- |
| `enabled`          | `true`           | Enable/disable the adapter                   |
| `contextGraphRoot` | `.context-graph` | Storage directory                            |
| `agentId`          | auto-generated   | Agent identifier for provenance              |
| `policyPath`       | —                | Path to privacy policy YAML                  |
| `detectTests`      | `true`           | Auto-detect test runs from shell output      |
| `detectBuilds`     | `true`           | Auto-detect builds from shell output         |
| `signingKeyPath`   | auto             | Ed25519 key path (auto-generated if missing) |

## Development

```bash
npm install
npm run build
npm test        # 27 tests
npm run dev     # watch mode
npx tsx demo.ts # interactive demo
```

## License

MIT
