clawpowers 1.1.4 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/COMPATIBILITY.md +13 -0
  3. package/KNOWN_LIMITATIONS.md +19 -0
  4. package/LICENSE +44 -0
  5. package/LICENSING.md +10 -0
  6. package/README.md +378 -210
  7. package/SECURITY.md +52 -0
  8. package/dist/index.d.ts +1477 -0
  9. package/dist/index.js +3464 -0
  10. package/dist/index.js.map +1 -0
  11. package/native/Cargo.lock +4863 -0
  12. package/native/Cargo.toml +73 -0
  13. package/native/crates/canonical/Cargo.toml +24 -0
  14. package/native/crates/canonical/src/lib.rs +673 -0
  15. package/native/crates/compression/Cargo.toml +20 -0
  16. package/native/crates/compression/benches/compression_bench.rs +42 -0
  17. package/native/crates/compression/src/lib.rs +393 -0
  18. package/native/crates/evm-eth/Cargo.toml +13 -0
  19. package/native/crates/evm-eth/src/lib.rs +105 -0
  20. package/native/crates/fee/Cargo.toml +15 -0
  21. package/native/crates/fee/src/lib.rs +281 -0
  22. package/native/crates/index/Cargo.toml +16 -0
  23. package/native/crates/index/src/lib.rs +277 -0
  24. package/native/crates/policy/Cargo.toml +17 -0
  25. package/native/crates/policy/src/lib.rs +614 -0
  26. package/native/crates/security/Cargo.toml +22 -0
  27. package/native/crates/security/src/lib.rs +478 -0
  28. package/native/crates/tokens/Cargo.toml +13 -0
  29. package/native/crates/tokens/src/lib.rs +534 -0
  30. package/native/crates/verification/Cargo.toml +23 -0
  31. package/native/crates/verification/src/lib.rs +333 -0
  32. package/native/crates/wallet/Cargo.toml +20 -0
  33. package/native/crates/wallet/src/lib.rs +261 -0
  34. package/native/crates/x402/Cargo.toml +30 -0
  35. package/native/crates/x402/src/lib.rs +423 -0
  36. package/native/ffi/Cargo.toml +34 -0
  37. package/native/ffi/build.rs +4 -0
  38. package/native/ffi/index.node +0 -0
  39. package/native/ffi/src/lib.rs +352 -0
  40. package/native/ffi/tests/integration.rs +354 -0
  41. package/native/pyo3/Cargo.toml +26 -0
  42. package/native/pyo3/pyproject.toml +16 -0
  43. package/native/pyo3/src/lib.rs +407 -0
  44. package/native/pyo3/tests/test_smoke.py +180 -0
  45. package/native/wasm/Cargo.toml +44 -0
  46. package/native/wasm/pkg/.gitignore +6 -0
  47. package/native/wasm/pkg/clawpowers_wasm.d.ts +208 -0
  48. package/native/wasm/pkg/clawpowers_wasm.js +872 -0
  49. package/native/wasm/pkg/clawpowers_wasm_bg.wasm +0 -0
  50. package/native/wasm/pkg/clawpowers_wasm_bg.wasm.d.ts +40 -0
  51. package/native/wasm/pkg/package.json +17 -0
  52. package/native/wasm/pkg-node/.gitignore +6 -0
  53. package/native/wasm/pkg-node/clawpowers_wasm.d.ts +143 -0
  54. package/native/wasm/pkg-node/clawpowers_wasm.js +798 -0
  55. package/native/wasm/pkg-node/clawpowers_wasm_bg.wasm +0 -0
  56. package/native/wasm/pkg-node/clawpowers_wasm_bg.wasm.d.ts +40 -0
  57. package/native/wasm/pkg-node/package.json +13 -0
  58. package/native/wasm/src/lib.rs +433 -0
  59. package/package.json +71 -44
  60. package/src/skills/catalog.ts +435 -0
  61. package/src/skills/executor.ts +56 -0
  62. package/src/skills/index.ts +3 -0
  63. package/src/skills/itp/SKILL.md +112 -0
  64. package/src/skills/loader.ts +193 -0
  65. package/.claude-plugin/manifest.json +0 -19
  66. package/.codex/INSTALL.md +0 -36
  67. package/.cursor-plugin/manifest.json +0 -21
  68. package/.opencode/INSTALL.md +0 -52
  69. package/ARCHITECTURE.md +0 -69
  70. package/bin/clawpowers.js +0 -625
  71. package/bin/clawpowers.sh +0 -91
  72. package/docs/demo/clawpowers-demo.cast +0 -197
  73. package/docs/demo/clawpowers-demo.gif +0 -0
  74. package/docs/launch-images/25-skills-breakdown.jpg +0 -0
  75. package/docs/launch-images/clawpowers-vs-superpowers.jpg +0 -0
  76. package/docs/launch-images/economic-code-optimization.jpg +0 -0
  77. package/docs/launch-images/native-vs-bridge-2.jpg +0 -0
  78. package/docs/launch-images/native-vs-bridge.jpg +0 -0
  79. package/docs/launch-images/post1-hero-lobster.jpg +0 -0
  80. package/docs/launch-images/post2-dashboard.jpg +0 -0
  81. package/docs/launch-images/post3-superpowers.jpg +0 -0
  82. package/docs/launch-images/post4-before-after.jpg +0 -0
  83. package/docs/launch-images/post5-install-now.jpg +0 -0
  84. package/docs/launch-images/ultimate-stack.jpg +0 -0
  85. package/docs/launch-posts.md +0 -76
  86. package/docs/quickstart-first-transaction.md +0 -204
  87. package/gemini-extension.json +0 -32
  88. package/hooks/session-start +0 -205
  89. package/hooks/session-start.cmd +0 -43
  90. package/hooks/session-start.js +0 -163
  91. package/runtime/demo/README.md +0 -78
  92. package/runtime/demo/x402-mock-server.js +0 -230
  93. package/runtime/feedback/analyze.js +0 -621
  94. package/runtime/feedback/analyze.sh +0 -546
  95. package/runtime/init.js +0 -210
  96. package/runtime/init.sh +0 -178
  97. package/runtime/metrics/collector.js +0 -361
  98. package/runtime/metrics/collector.sh +0 -308
  99. package/runtime/payments/ledger.js +0 -305
  100. package/runtime/payments/ledger.sh +0 -262
  101. package/runtime/payments/pipeline.js +0 -455
  102. package/runtime/persistence/store.js +0 -433
  103. package/runtime/persistence/store.sh +0 -303
  104. package/skill.json +0 -106
  105. package/skills/agent-bounties/SKILL.md +0 -553
  106. package/skills/agent-payments/SKILL.md +0 -479
  107. package/skills/brainstorming/SKILL.md +0 -233
  108. package/skills/content-pipeline/SKILL.md +0 -282
  109. package/skills/cross-project-knowledge/SKILL.md +0 -345
  110. package/skills/dispatching-parallel-agents/SKILL.md +0 -305
  111. package/skills/economic-code-optimization/SKILL.md +0 -265
  112. package/skills/executing-plans/SKILL.md +0 -255
  113. package/skills/finishing-a-development-branch/SKILL.md +0 -260
  114. package/skills/formal-verification-lite/SKILL.md +0 -441
  115. package/skills/learn-how-to-learn/SKILL.md +0 -235
  116. package/skills/market-intelligence/SKILL.md +0 -323
  117. package/skills/meta-skill-evolution/SKILL.md +0 -325
  118. package/skills/prospecting/SKILL.md +0 -454
  119. package/skills/receiving-code-review/SKILL.md +0 -225
  120. package/skills/requesting-code-review/SKILL.md +0 -206
  121. package/skills/security-audit/SKILL.md +0 -353
  122. package/skills/self-healing-code/SKILL.md +0 -369
  123. package/skills/subagent-driven-development/SKILL.md +0 -244
  124. package/skills/systematic-debugging/SKILL.md +0 -355
  125. package/skills/test-driven-development/SKILL.md +0 -416
  126. package/skills/using-clawpowers/SKILL.md +0 -160
  127. package/skills/using-git-worktrees/SKILL.md +0 -261
  128. package/skills/validator/SKILL.md +0 -281
  129. package/skills/verification-before-completion/SKILL.md +0 -254
  130. package/skills/writing-plans/SKILL.md +0 -276
  131. package/skills/writing-skills/SKILL.md +0 -260
package/README.md CHANGED
@@ -1,287 +1,455 @@
1
- # 🦞 ClawPowers
1
+ # ClawPowers
2
2
 
3
- > **v1.1.3** · 26 skills · 372 tests · MIT · **Patent Pending**
3
+ **Launch surface:** `clawpowers` is the capability library. It is not the stock OpenClaw wrapper runtime. For the wrapper runtime, install `clawpowers-agent`.
4
4
 
5
- **Your agent needs to pay for APIs. ClawPowers makes that work.**
5
+ **Recommended pairing:** `clawpowers` 2.2.x with `clawpowers-agent` 1.1.x.
6
6
 
7
- When your agent hits a premium API and gets back HTTP 402 Payment Required, it needs to pay and retry — automatically, within limits you set, with your approval before anything moves. That's the core problem ClawPowers solves. The other 25 skills are a bonus.
7
+ **More docs:** [SECURITY](./SECURITY.md) · [Compatibility](./COMPATIBILITY.md) · [Known Limitations](./KNOWN_LIMITATIONS.md) · [Licensing](./LICENSING.md) · [Releasing](./RELEASING.md) · [Demo](./DEMO.md)
8
8
 
9
- ## The Pay-to-Complete Flow
9
+ **Skills library for AI agents — payments, memory, RSI, wallet, parallel swarm, ITP.** Drop-in capability layer for any agent framework.
10
10
 
11
- ```
12
- Agent calls API
13
-
14
-
15
- HTTP 402 ←── "Payment required: $0.50 USDC"
16
-
17
-
18
- ClawPowers evaluates:
19
- • Is this within your spend cap? ($5/tx limit → ✅)
20
- • Is this on the allowlist? (api.example.com → ✅)
21
- • Human approval required? (under $1 threshold → auto)
22
-
23
-
24
- Payment sent → API retried → Result returned
25
-
26
-
27
- Outcome logged (for RSI analysis)
11
+ [![npm version](https://img.shields.io/npm/v/clawpowers)](https://www.npmjs.com/package/clawpowers)
12
+ [![License: BSL 1.1](https://img.shields.io/badge/License-BSL%201.1-blue.svg)](LICENSE)
13
+
14
+ ```bash
15
+ npm install clawpowers
28
16
  ```
29
17
 
30
- ## Quick Start
18
+ ## 60-Second Demo
31
19
 
32
20
  ```bash
33
- npx clawpowers init # Set up ~/.clawpowers/ runtime
34
- npx clawpowers demo x402 # See the full 402 → pay → 200 flow (no real money)
35
- npx clawpowers status # Check what's running
21
+ npm install clawpowers
22
+ node -e "
23
+ const { generateWallet, detect402, SpendingPolicy, signMessage } = await import('clawpowers');
24
+
25
+ // 1. Generate a real Ethereum wallet (MetaMask-compatible)
26
+ const wallet = await generateWallet({ chain: 'base', dataDir: './demo-wallet' });
27
+ console.log('Address:', wallet.address);
28
+
29
+ // 2. Detect an x402 payment-required response
30
+ const req = detect402({ status: 402, headers: {
31
+ 'x-payment-amount': '0.10',
32
+ 'x-payment-currency': 'USD',
33
+ 'x-payment-recipient': '0xabc',
34
+ 'x-payment-network': 'base'
35
+ }});
36
+ console.log('Payment required:', req);
37
+
38
+ // 3. Enforce a spending policy
39
+ const policy = new SpendingPolicy({ dailyLimitUsd: 25, allowedDomains: ['api.example.com'] });
40
+ console.log('Allowed:', policy.checkTransaction(0.10, 'api.example.com').allowed);
41
+ "
36
42
  ```
37
43
 
38
- ## Human-Approval Mode (the default)
44
+ That's a real Ethereum wallet, real x402 detection, and a real spending policy check — all in 60 seconds, zero config, zero Rust toolchain. The `native/` Rust acceleration is optional; the WASM tier ships pre-built in the npm package.
39
45
 
40
- ClawPowers defaults to supervised payments your agent proposes, you approve. No funds move until you say so.
46
+ > **⚠️ Patent Pending:** The x402 payment detection, autonomous spending policy enforcement, and recursive self-improvement (RSI) systems described in this library are subject to pending patent applications. Use is governed by the BSL 1.1 license.
41
47
 
42
- ```typescript
43
- import { createX402Client } from 'agentwallet-sdk';
44
- import { createWallet, setSpendPolicy } from 'agentwallet-sdk';
45
- import { createWalletClient, http } from 'viem';
46
- import { privateKeyToAccount } from 'viem/accounts';
47
- import { base } from 'viem/chains';
48
+ ---
48
49
 
49
- const account = privateKeyToAccount(process.env.AGENT_PRIVATE_KEY as `0x${string}`);
50
- const walletClient = createWalletClient({ account, chain: base, transport: http() });
50
+ ## What Is This?
51
51
 
52
- const wallet = createWallet({
53
- accountAddress: process.env.AGENT_WALLET_ADDRESS as `0x${string}`,
54
- chain: 'base',
55
- walletClient,
56
- });
52
+ ClawPowers extracts the core capabilities from [ClawPowers-Agent](https://github.com/up2itnow0822/ClawPowers-Agent) into a standalone library. **No agent control loop** — bring your own agent framework and get:
57
53
 
58
- // Spend policy — enforced on-chain, not in application code
59
- await setSpendPolicy(wallet, {
60
- token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC on Base
61
- perTxLimit: 1_000_000n, // $1 auto-approved per transaction
62
- periodLimit: 10_000_000n, // $10/day hard cap
63
- periodLength: 86400,
64
- });
54
+ That separation is intentional:
65
55
 
66
- const x402 = createX402Client(wallet, {
67
- supportedNetworks: ['base:8453'],
68
- globalDailyLimit: 10_000_000n, // matches spend policy
69
- globalPerRequestMax: 1_000_000n, // $1 per request
70
- requireApproval: true, // human-in-the-loop mode (default)
71
- });
56
+ - **`clawpowers`** owns the shared capability implementation.
57
+ - **`clawpowers-agent`** owns the stock OpenClaw wrapper runtime.
58
+ - Downstream wrappers should consume this package rather than duplicating capability logic.
72
59
 
73
- // Agent hits a paid API
74
- const response = await x402.fetch('https://api.example.com/premium-data');
75
- // If cost < $1: auto-approved and paid
76
- // If cost > $1: queued you get a notification to approve or reject
77
- const data = await response.json();
78
- ```
60
+ - **x402 Payments** Detect HTTP 402 responses, enforce spending policies, execute payments
61
+ - **Three-Tier Memory** Working, episodic, procedural memory with crash recovery
62
+ - **RSI Engine** Metrics collection, hypothesis generation, mutation, A/B testing
63
+ - **Wallet** Generate, import, and sign with **MetaMask-compatible** Ethereum addresses out of the box (secp256k1 + Keccak-256 via pre-built WASM, no Rust toolchain required)
64
+ - **Skills** Discover, load, and track skill execution outcomes
65
+ - **Parallel Swarm** — Concurrent task execution with intelligent model routing and token budgeting
66
+ - **ITP (Identical Twins Protocol)** — Context compression that eliminates redundant token usage across agent sessions
79
67
 
80
- ## Simulation Mode
68
+ ## Native Acceleration
81
69
 
82
- Test the full payment flow before enabling live payments.
70
+ ClawPowers ships the same optional **Rust + WASM + PyO3** stack as [ClawPowers-Agent](https://github.com/up2itnow0822/ClawPowers-Agent), exposed through a **3-tier loader** in TypeScript. **v2.2.0+:** when a native `.node` addon is present, the WASM bundle is still loaded if available so helpers such as secp256k1 stay available even if your local addon predates those exports; `getActiveTier()` remains `native` in that case.
83
71
 
84
- ```bash
85
- # Run a local mock x402 merchant — full 402 → pay → 200 cycle
86
- npx clawpowers demo x402
87
- ```
72
+ | Tier | Backend | When it loads |
73
+ |------|---------|----------------|
74
+ | **1 Native** | `napi-rs` `.node` addon (`native/ffi`, built locally with Rust) | Fastest; optional — not required for npm installs |
75
+ | **2 — WASM** | Pre-built `native/wasm/pkg-node` (and `pkg` for web) | **Default** for most Node.js installs — no `wasm-pack` or Rust needed |
76
+ | **3 — TypeScript** | Pure JS / Node built-ins | Universal fallback when native and WASM are unavailable |
88
77
 
89
- In code:
78
+ Check status in code:
90
79
 
91
80
  ```typescript
92
- const x402 = createX402Client(wallet, {
93
- supportedNetworks: ['base:8453'],
94
- globalDailyLimit: 10_000_000n,
95
- globalPerRequestMax: 1_000_000n,
96
- dryRun: true, // logs exactly what would happen, no funds move
97
- });
81
+ import { getActiveTier, isNativeAvailable, isWasmAvailable, getCapabilitySummary } from 'clawpowers';
98
82
 
99
- const response = await x402.fetch('https://api.example.com/premium-data');
100
- // Response includes: { simulated: true, wouldHavePaid: '0.50 USDC', withinLimits: true }
83
+ console.log(getActiveTier()); // 'native' | 'wasm' | 'typescript'
84
+ console.log(isNativeAvailable(), isWasmAvailable());
85
+ console.log(getCapabilitySummary());
101
86
  ```
102
87
 
103
- ## Explicit Spend Caps
88
+ ### Building native / WASM locally
104
89
 
105
- Caps are enforced by smart contract, not application code. Even a prompt injection or jailbreak can't bypass them.
90
+ **Requirements (optional):** Rust (`rustc` 1.70+), `wasm-pack` for regenerating WASM bindings.
106
91
 
107
- ```
108
- Agent wants to spend $0.50 → Auto-approved (under $1/tx cap)
109
- Agent wants to spend $5.00 Queued for your approval
110
- Agent spent $9.00 today → 🛑 Next tx blocked ($10/day cap hit)
92
+ ```bash
93
+ npm run build:native # workspace `cargo build --release` (ignored if Rust missing)
94
+ npm run build:wasm # wasm-packnative/wasm/pkg-node (optional)
111
95
  ```
112
96
 
113
- ```bash
114
- # Check what your agent has spent
115
- npx clawpowers store get agent-payments:daily-total
116
- # → "2.50 USDC spent today, $7.50 remaining"
97
+ `wasm-pack` may regenerate `pkg/.gitignore` / `pkg-node/.gitignore` that ignore all files in those folders — remove those ignore files if you need to commit refreshed WASM output.
98
+
99
+ Pre-built `.wasm` artifacts are included in the package so consumers are **not** required to run `wasm-pack`.
100
+
101
+ ### Module coverage (aligned with ClawPowers-Agent)
102
+
103
+ | Area | Tier 1 / 2 capability | TypeScript fallback |
104
+ |------|------------------------|---------------------|
105
+ | Payments | `JsFeeSchedule`, WASM fee math | Pure-TS fee formula |
106
+ | Payments | `JsX402Client` | Base64 JSON header |
107
+ | Payments | `JsAgentWallet` (native only) | TS wallet + WASM secp256k1 + Keccak for real Ethereum addresses |
108
+ | Memory | `JsCanonicalStore`, `JsTurboCompressor`, `JsWriteFirewall` | File/JSONL memory; simplified firewall |
109
+ | Wallet / secp256k1 | Native + WASM: `deriveEthereumAddress`, `derivePublicKey`, `signEcdsa`, `verifyEcdsa`, `computeKeccak256` / `keccak256Bytes` | Tier 3: legacy digest-based “address” + HMAC signing fallback only |
110
+
111
+ Exported helpers include `calculateTransactionFee`, `createPaymentHeader`, `generateWalletAddress`, `compressVector`, `getBestCanonicalStore`, `digestForWalletAddress`, and the full loader API in `src/native/index.ts`.
112
+
113
+ ## x402 Payment Flow
117
114
 
118
- # Review and approve queued payments
119
- npx clawpowers payments queue
120
- # [1] $5.00 USDC — api.example.com/premium-report — approve? (y/n)
115
+ ```
116
+ ┌─────────┐ ┌──────────────┐ ┌───────────────┐ ┌──────────┐
117
+ │ Agent │────▶│ API Server │────▶│ detect402() │────▶│ Spending
118
+ │ │ │ returns 402 │ │ parse x402 │ │ Policy │
119
+ └─────────┘ └──────────────┘ │ headers │ │ check │
120
+ └───────────────┘ └────┬─────┘
121
+
122
+ ┌─────────────────▼─────────────────┐
123
+ │ PaymentExecutor │
124
+ │ ┌───────────┐ ┌─────────────┐ │
125
+ │ │ MCP Client │ │ Audit Log │ │
126
+ │ │ (agentpay) │ │ (append-only│ │
127
+ │ └─────┬─────┘ └─────────────┘ │
128
+ └───────┬───────────────────────────┘
129
+
130
+ ┌───────▼───────┐
131
+ │ Base Network │
132
+ │ USDC Payment │
133
+ └───────────────┘
121
134
  ```
122
135
 
123
- ## Why Supervised, Not Autonomous
136
+ ## Framework Compatibility
124
137
 
125
- Fully autonomous agent payments sound great until an agent in a loop runs up $500 in API calls overnight. ClawPowers is built around three constraints:
138
+ | Framework | Integration | Example |
139
+ |-----------|------------|---------|
140
+ | **LangChain** | `DynamicStructuredTool` | [`demos/langchain.ts`](demos/langchain.ts) |
141
+ | **Claude Code** | `CLAUDE.md` config | [`demos/claude-code.md`](demos/claude-code.md) |
142
+ | **ElizaOS** | Plugin pattern | [`demos/elizaos.ts`](demos/elizaos.ts) |
143
+ | **AutoGPT** | Direct import | See examples below |
144
+ | **CrewAI** | Tool wrapper | See examples below |
145
+ | **Custom** | Direct TypeScript import | See examples below |
126
146
 
127
- 1. **Caps enforced on-chain** — the agent *cannot* exceed them, full stop
128
- 2. **Human approval by default** — auto-approve only below thresholds you set
129
- 3. **Full audit trail** — every payment logged at `~/.clawpowers/metrics/`
147
+ ## Quick Start
130
148
 
131
- When you've verified the agent behaves correctly, raise the auto-approve threshold. Start low.
149
+ ### Payments
132
150
 
133
- ## Installation
151
+ ```typescript
152
+ import { SpendingPolicy, PaymentExecutor, detect402 } from 'clawpowers';
134
153
 
135
- ### Universal (Windows, macOS, Linux)
154
+ // Configure spending limits
155
+ const policy = new SpendingPolicy({
156
+ dailyLimit: 25, // $25/day
157
+ transactionLimit: 10, // $10 per tx
158
+ allowedDomains: ['api.example.com'],
159
+ });
136
160
 
137
- ```bash
138
- npx clawpowers init
161
+ // Create executor with your MCP client
162
+ const executor = new PaymentExecutor(policy, mcpClient);
163
+
164
+ // Detect and handle 402 responses
165
+ const payment = detect402({ status: 402, headers: responseHeaders });
166
+ if (payment) {
167
+ const result = await executor.executePayment({
168
+ amount: payment.amount,
169
+ currency: payment.currency,
170
+ recipient: payment.recipient,
171
+ domain: 'api.example.com',
172
+ x402Headers: payment.x402Headers,
173
+ });
174
+ }
139
175
  ```
140
176
 
141
- ### OpenClaw
177
+ ### Memory
142
178
 
143
- ```bash
144
- openclaw skills install clawpowers
145
- # or from GitHub
146
- openclaw skills install github:up2itnow0822/clawpowers
147
- ```
179
+ ```typescript
180
+ import { EpisodicMemory, ProceduralMemory, ContextInjector } from 'clawpowers';
181
+
182
+ // Episodic: Task history (append-only JSONL)
183
+ const episodic = new EpisodicMemory('~/.clawpowers/memory/episodic.jsonl');
184
+ await episodic.append({
185
+ taskId: 'task-1',
186
+ timestamp: new Date().toISOString(),
187
+ description: 'Built authentication module',
188
+ outcome: 'success',
189
+ lessonsLearned: ['Always test edge cases'],
190
+ skillsUsed: ['tdd'],
191
+ durationMs: 5000,
192
+ tags: ['auth'],
193
+ });
148
194
 
149
- ### Claude Code
195
+ // Procedural: Skill effectiveness tracking
196
+ const procedural = new ProceduralMemory('~/.clawpowers/memory/procedural.json');
197
+ await procedural.update('tdd', { succeeded: true, durationMs: 5000, taskId: 'task-1' });
150
198
 
151
- ```bash
152
- /plugin install clawpowers@claude-plugins-official
199
+ // Context injection: Relevant memories for new tasks
200
+ const injector = new ContextInjector(episodic, procedural);
201
+ const context = await injector.inject(goal, 2000); // 2000 token budget
153
202
  ```
154
203
 
155
- ### Cursor
204
+ ### RSI (Recursive Self-Improvement)
156
205
 
157
- ```text
158
- /add-plugin clawpowers
206
+ ```typescript
207
+ import { MetricsCollector, HypothesisEngine, MutationEngine, ABTestManager } from 'clawpowers';
208
+
209
+ // Collect metrics
210
+ const metrics = new MetricsCollector('task-metrics.jsonl', 'skill-metrics.jsonl');
211
+ await metrics.recordTaskMetrics({ taskId: 'task-1', outcome: 'success', /* ... */ });
212
+
213
+ // Generate improvement hypotheses
214
+ const hypothesis = new HypothesisEngine();
215
+ const hypotheses = hypothesis.analyze(skillStats, taskHistory);
216
+
217
+ // Create and test mutations
218
+ const mutations = new MutationEngine('mutations.jsonl');
219
+ const mutation = mutations.createMutation(hypotheses[0]);
220
+
221
+ // A/B test mutations
222
+ const ab = new ABTestManager();
223
+ const test = ab.startTest(mutation, baselineStats);
224
+ ab.recordResult(test.testId, newTaskMetrics);
225
+ const result = ab.evaluateTest(test.testId);
226
+ // result.decision: 'promote' | 'rollback' | 'continue'
159
227
  ```
160
228
 
161
- ### Codex / OpenCode
229
+ ### Wallet
162
230
 
163
- ```text
164
- Fetch and follow instructions from https://raw.githubusercontent.com/up2itnow0822/clawpowers/main/.codex/INSTALL.md
165
- ```
231
+ **v2.2.0+ produces real MetaMask-compatible Ethereum addresses** via the standard derivation chain: secp256k1 private key → uncompressed public key → Keccak-256 → last 20 bytes, with EIP-55 checksum case. Verified against the Hardhat default test vector (`0xac09...ff80` → `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266`). Addresses are importable into MetaMask, Etherscan, and any EVM wallet.
166
232
 
167
- ### Manual
233
+ **Tier behavior:**
234
+ - **Tier 1** (native `.node` addon, built locally with `cargo`): full secp256k1 + ECDSA + Keccak-256 via the `k256` Rust crate
235
+ - **Tier 2** (pre-built WASM, ships in the npm package): same secp256k1 + ECDSA + Keccak-256 via `k256` compiled to WebAssembly
236
+ - **Tier 3** (pure TypeScript, used only if Tier 1 AND Tier 2 both fail to load): legacy SHA-256 digest and HMAC signing — **not production-safe for on-chain use**
168
237
 
169
- ```bash
170
- git clone https://github.com/up2itnow0822/clawpowers.git
171
- cd clawpowers
172
- node bin/clawpowers.js init
238
+ Since Tier 2 WASM artifacts ship pre-built in the npm package, **every install gets real Ethereum wallets out of the box** — no Rust toolchain required.
239
+
240
+ ```typescript
241
+ import { WalletManager, generateWallet, signMessage } from 'clawpowers';
242
+
243
+ // High-level API
244
+ const wallet = new WalletManager({
245
+ chain: 'base',
246
+ dataDir: '~/.clawpowers/wallet',
247
+ });
248
+
249
+ const info = await wallet.generate();
250
+ console.log(info.address); // 0x... — real Ethereum address, EIP-55 checksummed
251
+
252
+ // Low-level API for direct key handling
253
+ const sig = await signMessage(privateKeyHex, 'Hello, Ethereum');
254
+ // Returns 65-byte ECDSA signature (r || s || recovery) as 0x-prefixed hex
255
+ // Verifiable by any Ethereum node, ethers.js, viem, or MetaMask
173
256
  ```
174
257
 
175
- ## All 26 Skills
176
-
177
- ### Core Development (14)
178
-
179
- | Skill | What It Does |
180
- |-------|-------------|
181
- | `subagent-driven-development` | Orchestrate parallel subagents persistent execution DB, resumable checkpoints |
182
- | `test-driven-development` | RED-GREEN-REFACTOR with mutation analysis to verify tests actually catch bugs |
183
- | `writing-plans` | Spec implementation plan with historical estimation and dependency validation |
184
- | `executing-plans` | Execute plans with interruption recovery and milestone tracking |
185
- | `brainstorming` | Structured ideation with cross-session idea persistence |
186
- | `systematic-debugging` | Persistent hypothesis tree so you never re-investigate the same dead end |
187
- | `verification-before-completion` | Pre-merge quality gates that actually run the verification suite |
188
- | `finishing-a-development-branch` | Branch cleanup, changelog, merge prep |
189
- | `requesting-code-review` | Reviewer match scoring, review history |
190
- | `receiving-code-review` | Feedback pattern tracking, common issues database |
191
- | `using-git-worktrees` | Isolated branch development with conflict prediction |
192
- | `using-clawpowers` | Meta-skill: how to use ClawPowers |
193
- | `writing-skills` | Create new skills via TDD with quality scoring |
194
- | `dispatching-parallel-agents` | Fan-out with load balancing, failure isolation, result aggregation |
195
-
196
- ### Extended Capabilities (6)
197
-
198
- | Skill | What It Does |
199
- |-------|-------------|
200
- | `agent-payments` | x402 payment protocol — supervised, capped, human-in-the-loop by default |
201
- | `security-audit` | Automated vulnerability scanning (Trivy, gitleaks, npm audit) |
202
- | `content-pipeline` | Write → humanize → format → publish with platform-specific formatting |
203
- | `learn-how-to-learn` | Metacognitive protocols, anti-pattern detection, confidence calibration |
204
- | `market-intelligence` | Competitive research, trend detection, opportunity scoring |
205
- | `prospecting` | Lead generation, contact enrichment, CRM sync (Exa + Apollo) |
206
-
207
- ### RSI Intelligence Layer (4)
208
-
209
- Skills that require runtime execution and persistent state — not available in static frameworks.
210
-
211
- | Skill | What It Does |
212
- |-------|-------------|
213
- | `meta-skill-evolution` | Every 50 tasks: analyzes outcomes, identifies weakest skill, rewrites its methodology |
214
- | `self-healing-code` | On test failure: hypothesis tree → 2+ patches → applies best → auto-commits |
215
- | `cross-project-knowledge` | Pattern library across all repos — bug fixes and solutions transfer between projects |
216
- | `formal-verification-lite` | Property-based testing (fast-check/Hypothesis/QuickCheck) — 1000+ examples per property |
217
-
218
- ## Cross-Session Memory
219
-
220
- Skills persist state across sessions. Your agent's debugging hypotheses, payment outcomes, and learned patterns survive session restarts.
258
+ For production on-chain sending and transaction construction, you can still use [`viem`](https://viem.sh) or [`ethers`](https://docs.ethers.org) alongside ClawPowers — our wallet produces the same addresses they do.
259
+
260
+ ## Memory Module
261
+
262
+ | Layer | Storage | Purpose |
263
+ |-------|---------|---------|
264
+ | **Working** | In-process | Current task context with token budget |
265
+ | **Episodic** | JSONL file | Task history, searchable by keywords |
266
+ | **Procedural** | JSON file | Skill effectiveness tracking with atomic writes |
267
+ | **Checkpoint** | JSON files | Crash recovery, stale detection |
268
+ | **Context Injector** | Computed | Selects relevant memories for new tasks |
269
+
270
+ ## RSI Module
271
+
272
+ The RSI engine implements a continuous improvement loop:
221
273
 
222
274
  ```
223
- ~/.clawpowers/
224
- ├── state/ # Key-value store
225
- ├── metrics/ # Outcome tracking per skill (JSONL)
226
- ├── checkpoints/ # Resumable workflow state
227
- ├── feedback/ # RSI self-improvement data
228
- └── logs/ # Execution logs
275
+ measure → hypothesize → mutate → A/B test → promote/rollback → repeat
229
276
  ```
230
277
 
231
- ## CLI Reference
278
+ **Tier Safety:**
279
+ - **T1** (Parameter Tuning) — Can auto-apply
280
+ - **T2** (Strategy Evolution) — Can auto-apply with notification
281
+ - **T3** (Skill Composition) — Requires testing gate
282
+ - **T4** (Architecture Proposals) — **ALWAYS requires human approval**
232
283
 
233
- ```bash
234
- npx clawpowers init # Set up runtime
235
- npx clawpowers status # Health check
236
- npx clawpowers demo x402 # Payment demo (no real money)
237
- npx clawpowers metrics record --skill <name> --outcome success|failure
238
- npx clawpowers metrics summary # Per-skill stats
239
- npx clawpowers analyze # RSI performance analysis
240
- npx clawpowers store get <key> # Read persistent state
241
- npx clawpowers store set <key> <value> # Write persistent state
242
- npx clawpowers payments queue # Review pending approvals
284
+ Safety invariants (spending limits, identity, RSI definitions, sandbox boundaries, credentials) can **NEVER** be modified by RSI.
285
+
286
+ ## Parallel Swarm
287
+
288
+ Run multiple tasks concurrently with intelligent model routing, shared context, and token budget management.
289
+
290
+ ```typescript
291
+ import { ConcurrencyManager, TokenPool, classifyHeuristic, selectModel } from 'clawpowers';
292
+
293
+ const pool = new TokenPool({ totalBudget: 100000 });
294
+ const concurrency = new ConcurrencyManager({ maxConcurrency: 5 });
295
+
296
+ // Classify and route tasks to optimal models
297
+ const complexity = classifyHeuristic('Build a distributed trading system');
298
+ const model = selectModel(complexity); // → claude-opus-4-5
299
+
300
+ // Allocate token budgets per task
301
+ pool.allocate('task-1', 5000);
243
302
  ```
244
303
 
245
- ## Platform Support
304
+ ### Swarm vs Sequential Sessions
246
305
 
247
- | Platform | Windows | macOS | Linux | WSL2 |
248
- |----------|:-------:|:-----:|:-----:|:----:|
249
- | Claude Code | ✅ | ✅ | ✅ | ✅ |
250
- | Cursor | ✅ | ✅ | ✅ | ✅ |
251
- | Codex | ✅ | ✅ | ✅ | ✅ |
252
- | OpenCode | ✅ | ✅ | ✅ | ✅ |
253
- | Gemini CLI | ✅ | ✅ | ✅ | ✅ |
306
+ Running N tasks as a single parallel swarm instead of N separate LLM sessions avoids reloading shared context (system prompt, workspace files, tool schemas) for every task.
254
307
 
255
- ## Requirements
308
+ **Measured benefits:**
309
+ - **Wall time:** parallel fan-out is significantly faster than sequential execution, scaling with task count and concurrency limit
310
+ - **Token usage:** shared-context overhead is paid once per swarm run instead of once per task
256
311
 
257
- - **Node.js >= 16** (for cross-platform runtime)
258
- - **OR bash** (for Unix-native runtime)
259
- - **Zero runtime dependencies** — `package.json` has an empty `dependencies` object
312
+ **Current measurement snapshot:**
260
313
 
261
- ## Security Model
314
+ **Live ITP compression measurements:**
315
+ - **25-message corpus:** 11 of 25 messages compressed, `862` to `759` estimated tokens, **11.95% token reduction**, **7.8 ms/message** round-trip
316
+ - **5-task live swarm payload:** `183` to `133` task tokens, **27.32% payload reduction**, **5 of 5 tasks compressed**, **10.8 ms** average encode latency
262
317
 
263
- - State directory (`~/.clawpowers/`) uses `700` permissions — owner-only
264
- - No network access in runtime scripts — store, metrics, and analyze are fully offline
265
- - No `eval()`, `Function()`, or dynamic code execution anywhere in the runtime
266
- - Payment guardrails enforced by smart contract — application code cannot override them
318
+ **Modeled prompt-cache economics on those same live prompt sizes:**
267
319
 
268
- ## Credential
320
+ | Scenario | Effective input units | Reduction vs baseline | Source type |
321
+ |----------|-----------------------|-----------------------|-------------|
322
+ | Baseline | 1902.00 | 0.00% | Derived from live prompt sizes |
323
+ | ITP only | 1848.00 | 2.84% | Live ITP server compression applied to full prompts |
324
+ | Prompt cache only | 752.95 | 60.41% | Anthropic cache-pricing model |
325
+ | ITP + prompt cache | 698.95 | 63.25% | Hybrid result: live ITP compression + modeled cache pricing |
269
326
 
270
- Built by [AI Agent Economy](https://github.com/up2itnow0822):
271
- - Payment infrastructure in [NVIDIA's official NeMo Agent Toolkit](https://github.com/NVIDIA/NeMo-Agent-Toolkit-Examples/pull/17)
272
- - [agentwallet-sdk](https://www.npmjs.com/package/agentwallet-sdk) — 741+ downloads/week
273
- - [agentpay-mcp](https://github.com/up2itnow0822/agentpay-mcp) — MCP payment server
327
+ - **Shared prompt prefix in swarm test:** 1,372 characters, about 343 estimated input tokens
328
+ - **Three-set hybrid validation on a MacBook Pro (Apple M1, 16 GB RAM) with benchmark runner model `openai-codex/gpt-5.4`:** combined reduction ranged from **61.89%** to **63.25%**, with a **62.56%** mean and **0.56** standard deviation
274
329
 
275
- ## Patent Notice
330
+ **Reproduce:**
331
+ - `node benchmarks/itp-measurement.mjs` for the live ITP corpus benchmark
332
+ - `node benchmarks/swarm-vs-sequential.mjs` for the structure-only swarm cost model
333
+ - `node benchmarks/itp-cache-swarm-benchmark.mjs` for the hybrid benchmark (live ITP compression + modeled cache economics)
334
+ - `node benchmarks/itp-cache-multi-swarm-benchmark.mjs` for the same hybrid methodology across three swarm sets
335
+
336
+ ## ITP (Identical Twins Protocol) - Experimental
276
337
 
277
- **Patent Pending** The underlying financial infrastructure (agentwallet-sdk, agentpay-mcp) is covered by USPTO provisional patent application filed March 2026: "Non-Custodial Multi-Chain Financial Infrastructure System for Autonomous AI Agents."
338
+ > **Status: Experimental.** ITP compression and latency numbers below are measured against the running server. Any prompt-cache numbers are modeled Anthropic cache economics applied to those same live prompt sizes.
278
339
 
279
- We support the open x402 standard. Our provisional filing is defensive intended to prevent hostile monopolization of open payment rails, not to restrict builders.
340
+ Context compression for multi-agent communication. When agents share similar context (same model, same workspace), ITP deduplicates the common payload before transmission. The library ships with a graceful passthrough fallback, so code using ITP works even when the ITP server is offline. Messages are simply forwarded unchanged.
341
+
342
+ ```typescript
343
+ import { itpEncode, itpDecode, itpHealthCheck, encodeTaskDescription, decodeSwarmResult } from 'clawpowers';
280
344
 
281
- ## Disclaimer
345
+ // Graceful fallback, works without ITP server running
346
+ const encoded = await encodeTaskDescription('Analyze quarterly revenue data');
347
+ const decoded = await decodeSwarmResult(result);
348
+
349
+ // Health check
350
+ const serverUp = await itpHealthCheck(); // false = passthrough mode
351
+ ```
352
+
353
+ **Live ITP benchmark snapshot:**
354
+ - **Codebook:** `v1.0.0`, 99 entries
355
+ - **Corpus benchmark:** **11.95%** token reduction on 25 messages
356
+ - **Swarm payload benchmark:** **27.32%** task-token reduction on a 5-task swarm
357
+ - **Hybrid swarm benchmark:** **63.25%** effective input-cost reduction from live ITP compression plus modeled prompt caching
358
+
359
+ ITP is most effective in parallel swarm scenarios where multiple tasks share the same model context. Prompt caching handles repeated prompt structure, and ITP reduces the changing task payload inside that structure. Cross-model savings can also compound because providers inject similar preambles across nearby model tiers.
360
+
361
+ ## Fee Structure
362
+
363
+ | Operation | Fee |
364
+ |-----------|-----|
365
+ | Transaction | 0.77% |
366
+ | Token Swap | 0.30% |
367
+
368
+ Fees are applied at the payment execution layer and are included in the transaction amount.
369
+
370
+ ## Python Integration
371
+
372
+ ```python
373
+ import subprocess
374
+ import json
375
+
376
+ # Call ClawPowers via Node.js subprocess
377
+ # Note: use --input-type=module (or a .mjs file) because clawpowers is an ES module
378
+ result = subprocess.run(
379
+ ['node', '--input-type=module'],
380
+ input='''
381
+ import { detect402, SpendingPolicy } from "clawpowers";
382
+ const policy = new SpendingPolicy({ dailyLimit: 25, transactionLimit: 10, allowedDomains: [] });
383
+ const decision = policy.checkTransaction(5.00, "api.example.com");
384
+ console.log(JSON.stringify(decision));
385
+ ''',
386
+ capture_output=True, text=True
387
+ )
388
+ decision = json.loads(result.stdout)
389
+ ```
282
390
 
283
- ClawPowers and agentwallet-sdk are non-custodial developer tooling. You control your own keys and set your own spending limits. You are responsible for compliance with applicable laws in your jurisdiction. This software is provided as-is under the MIT license. Nothing here constitutes financial advice, custody services, or money transmission.
391
+ ## API Reference
392
+
393
+ ### Native acceleration
394
+ - `getActiveTier()`, `isNativeAvailable()`, `isWasmAvailable()`, `getCapabilitySummary()` — Loader introspection
395
+ - `computeSha256`, `digestForWalletAddress`, `tokenAmountFromHuman`, `calculateFee`, `evaluateWriteFirewall` — Routed helpers
396
+ - `getNative()`, `getWasm()` — Low-level module access
397
+
398
+ ### Payments
399
+ - `detect402(response)` — Parse x402 headers from 402 response
400
+ - `isPaymentRequired(error)` — Type guard for 402 errors
401
+ - `SpendingPolicy` — Enforce daily/transaction/domain limits
402
+ - `PaymentExecutor` — Execute payments via MCP client
403
+ - `calculateTransactionFee`, `createPaymentHeader`, `generateWalletAddress` — Native/WASM-accelerated payment helpers (with TS fallbacks)
404
+
405
+ ### Memory
406
+ - `WorkingMemoryManager` — In-process context management
407
+ - `EpisodicMemory` — JSONL task history
408
+ - `ProceduralMemory` — Skill effectiveness tracking
409
+ - `CheckpointManager` — Crash recovery
410
+ - `ContextInjector` — Memory-to-context selection
411
+ - `getBestCanonicalStore`, `getWasmCanonicalStore`, `compressVector`, `decompressVector`, `evaluateWriteSecurity` — Optional native/WASM memory bridges
412
+
413
+ ### RSI
414
+ - `MetricsCollector` — Task/skill metrics in JSONL
415
+ - `HypothesisEngine` — Generate improvement hypotheses
416
+ - `MutationEngine` — Create/apply/revert mutations
417
+ - `ABTestManager` — A/B test mutations
418
+ - `RSIAuditLog` — Append-only audit trail
419
+ - `AutoResearcher` — Research solutions to failures
420
+
421
+ ### Skills
422
+ - `discoverSkills(dir)` — Find skills in a directory
423
+ - `loadSkillManifest(dir)` — Load a single skill manifest
424
+ - `SkillExecutor` — Execute skills with outcome tracking
425
+
426
+ ### Wallet
427
+
428
+ - `WalletManager` — High-level wallet operations
429
+ - `generateWallet(config)` — Generate new wallet (**v2.2.0+**: standard Ethereum address via secp256k1 when Tier 1/2 is active)
430
+ - `importWallet(key, config)` — Import existing wallet (same derivation)
431
+ - `signMessage(message, keyFile, passphrase)` — Sign; uses **ECDSA (secp256k1) over Keccak-256(UTF-8 message)** when native/WASM provides crypto, else legacy HMAC
432
+ - `signMessage(privateKeyHex, message)` — Same ECDSA path; returns `0x` + 130 hex chars (65-byte signature)
433
+
434
+ ### Config
435
+ - `loadConfig()` / `saveConfig()` — Zod-validated config CRUD
436
+ - `initConfig()` — Create default config
437
+ - `getConfigValue()` / `setConfigValue()` — Dot-notation access
284
438
 
285
439
  ## License
286
440
 
287
- MIT
441
+ **Business Source License 1.1 (BSL 1.1)**
442
+
443
+ This software is licensed under the BSL 1.1. You may use it for non-production purposes freely. Production use requires a commercial license until the Change Date, after which the software converts to the Apache 2.0 license.
444
+
445
+ See [LICENSE](LICENSE) for full terms.
446
+
447
+ ## Patent Notice
448
+
449
+ ⚠️ **Patent Pending:** The autonomous payment detection, spending policy enforcement, recursive self-improvement engine, and multi-tier memory systems implemented in this library are subject to pending patent applications filed by AI Agent Economy. Unauthorized commercial use may constitute patent infringement.
450
+
451
+ ---
452
+
453
+ Built by [AI Agent Economy](https://github.com/up2itnow0822) 🦅
454
+
455
+ For commercial use, review [LICENSING.md](./LICENSING.md).