ape-claw 0.1.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 (114) hide show
  1. package/.cursor/skills/ape-claw/SKILL.md +322 -0
  2. package/LICENSE +21 -0
  3. package/README.md +826 -0
  4. package/allowlists/opensea-slug-overrides.json +13 -0
  5. package/allowlists/recommended.apechain.json +322 -0
  6. package/config/clawbots.example.json +3 -0
  7. package/config/policy.example.json +27 -0
  8. package/data/starter-pack-bundle.json +1 -0
  9. package/data/starter-pack.json +495 -0
  10. package/docs/ACP_BOUNTIES.md +108 -0
  11. package/docs/APECLAW_V2_ALPHA.md +206 -0
  12. package/docs/AUTONOMY_AND_SUBSTRATE.md +69 -0
  13. package/docs/CLAWBOTS_AND_INVITES.md +102 -0
  14. package/docs/CLI_GUIDE.md +124 -0
  15. package/docs/CONTRIBUTING.md +130 -0
  16. package/docs/DASHBOARD_GUIDE.md +108 -0
  17. package/docs/GLOBAL_BACKEND.md +145 -0
  18. package/docs/ONCHAIN_V2_GUIDE.md +140 -0
  19. package/docs/PRODUCT_OVERVIEW.md +127 -0
  20. package/docs/README.md +40 -0
  21. package/docs/SKILLCARDS_AND_IMPORTER.md +147 -0
  22. package/docs/STARTER_PACK.md +297 -0
  23. package/docs/SUPPORTED_NETWORKS.md +58 -0
  24. package/docs/TELEMETRY_AND_EVENTS.md +103 -0
  25. package/docs/THE_POD_RUNNER.md +198 -0
  26. package/docs/V1_WORKFLOWS.md +108 -0
  27. package/docs/V2_ONCHAIN_SKILLS.md +157 -0
  28. package/docs/WEB4_PLAN_STATUS.md +95 -0
  29. package/docs/WEB4_SWARM_MODEL.md +104 -0
  30. package/docs/archive/AUTONOMY_AND_SUBSTRATE.md +66 -0
  31. package/docs/archive/WEB4_PLAN_STATUS.md +93 -0
  32. package/docs/archive/WEB4_SWARM_MODEL.md +98 -0
  33. package/docs/developer/01-architecture.md +345 -0
  34. package/docs/developer/02-contracts.md +1034 -0
  35. package/docs/developer/03-writing-modules.md +513 -0
  36. package/docs/developer/04-skillcard-spec.md +336 -0
  37. package/docs/developer/05-backend-api.md +1079 -0
  38. package/docs/developer/06-telemetry.md +798 -0
  39. package/docs/developer/07-testing.md +546 -0
  40. package/docs/developer/08-contributing.md +211 -0
  41. package/docs/operator/01-quickstart.md +49 -0
  42. package/docs/operator/02-dashboard.md +174 -0
  43. package/docs/operator/03-cli-reference.md +818 -0
  44. package/docs/operator/04-skills-library.md +169 -0
  45. package/docs/operator/05-pod-operations.md +314 -0
  46. package/docs/operator/06-deployment.md +299 -0
  47. package/docs/operator/07-safety-and-policy.md +311 -0
  48. package/docs/operator/08-troubleshooting.md +457 -0
  49. package/docs/operator/09-env-reference.md +238 -0
  50. package/docs/social/STARTER_PACK_THREAD.md +209 -0
  51. package/package.json +77 -0
  52. package/skillcards/import-sources.json +93 -0
  53. package/skillcards/seed/acp-bounty-poll.v1.json +38 -0
  54. package/skillcards/seed/acp-bounty-post.v1.json +55 -0
  55. package/skillcards/seed/acp-browse.v1.json +41 -0
  56. package/skillcards/seed/acp-fulfill-and-route.v1.json +56 -0
  57. package/skillcards/seed/apeclaw-bridge-relay.v1.json +46 -0
  58. package/skillcards/seed/apeclaw-nft-autobuy.v1.json +60 -0
  59. package/skillcards/seed/apeclaw-receipt-recorder.v1.json +64 -0
  60. package/skillcards/seed/humanizer.v1.json +74 -0
  61. package/skillcards/seed/otherside-navigator.v1.json +116 -0
  62. package/skillcards/seed/stonkbrokers-launcher.v1.json +280 -0
  63. package/skillcards/seed/walkie-p2p.v1.json +66 -0
  64. package/src/cli/index.mjs +8 -0
  65. package/src/cli.mjs +1929 -0
  66. package/src/lib/bridge-relay.mjs +294 -0
  67. package/src/lib/clawbots.mjs +94 -0
  68. package/src/lib/io.mjs +36 -0
  69. package/src/lib/market.mjs +233 -0
  70. package/src/lib/nft-opensea.mjs +159 -0
  71. package/src/lib/paths.mjs +17 -0
  72. package/src/lib/pod-init.mjs +40 -0
  73. package/src/lib/policy.mjs +112 -0
  74. package/src/lib/rpc.mjs +49 -0
  75. package/src/lib/telemetry.mjs +92 -0
  76. package/src/lib/v2-onchain-abi.mjs +294 -0
  77. package/src/lib/v2-skillcard.mjs +27 -0
  78. package/src/server/index.mjs +169 -0
  79. package/src/server/logger.mjs +21 -0
  80. package/src/server/middleware/auth.mjs +90 -0
  81. package/src/server/middleware/body-limit.mjs +35 -0
  82. package/src/server/middleware/cors.mjs +33 -0
  83. package/src/server/middleware/rate-limit.mjs +44 -0
  84. package/src/server/routes/chat.mjs +178 -0
  85. package/src/server/routes/clawbots.mjs +182 -0
  86. package/src/server/routes/events.mjs +95 -0
  87. package/src/server/routes/health.mjs +72 -0
  88. package/src/server/routes/pod.mjs +64 -0
  89. package/src/server/routes/quotes.mjs +161 -0
  90. package/src/server/routes/skills.mjs +239 -0
  91. package/src/server/routes/static.mjs +161 -0
  92. package/src/server/routes/v2.mjs +48 -0
  93. package/src/server/sse.mjs +73 -0
  94. package/src/server/storage/file-backend.mjs +295 -0
  95. package/src/server/storage/index.mjs +37 -0
  96. package/src/server/storage/sqlite-backend.mjs +380 -0
  97. package/src/telemetry-server.mjs +1604 -0
  98. package/ui/css/dashboard.css +792 -0
  99. package/ui/css/skills.css +689 -0
  100. package/ui/docs.html +840 -0
  101. package/ui/favicon-180.png +0 -0
  102. package/ui/favicon-192.png +0 -0
  103. package/ui/favicon-32.png +0 -0
  104. package/ui/favicon-lobster.png +0 -0
  105. package/ui/favicon.svg +10 -0
  106. package/ui/index.html +2957 -0
  107. package/ui/js/dashboard.js +1766 -0
  108. package/ui/js/skills.js +1621 -0
  109. package/ui/pod.html +909 -0
  110. package/ui/shared/motion.css +286 -0
  111. package/ui/shared/motion.js +170 -0
  112. package/ui/shared/sidebar-nav.css +379 -0
  113. package/ui/shared/sidebar-nav.js +137 -0
  114. package/ui/skills.html +2879 -0
@@ -0,0 +1,66 @@
1
+ # Autonomy, Substrate, and the "Fugazi Agent" Critique
2
+
3
+ This doc answers a common (valid) critique:
4
+
5
+ > "It's all pretrained: the model, the tools, the feedback loop. All of it runs on infrastructure it does not control.
6
+ > How can you call something autonomous when it can’t survive losing API keys?"
7
+
8
+ ## What ApeClaw claims (and does not claim)
9
+
10
+ ### ApeClaw does claim
11
+
12
+ - Persistence: an agent can crash, reboot, and keep going using a file-backed harness (THE POD).
13
+ - Auditability: what happened is recorded as receipts/events (append-only).
14
+ - Permission boundaries: high-risk actions require explicit opt-in + safety gates.
15
+ - Replaceable infrastructure: UI/indexers/backends can change without changing the source of truth.
16
+
17
+ ### ApeClaw does not claim (yet)
18
+
19
+ - "Open-ended intelligence" that changes its own weights/training set onchain.
20
+ - Full substrate control over every dependency (models, RPC providers, markets).
21
+
22
+ The goal is not hype. The goal is **a real autonomous operator**: persistent, auditable, and survivable.
23
+
24
+ ## Substrate control: what we anchor onchain today (v2)
25
+
26
+ v2 makes the chain the source of truth for the pieces that matter:
27
+
28
+ - `SkillNFT`: provenance and ownership (one token per skill).
29
+ - `SkillRegistry`: immutable, append-only versions (content-addressed).
30
+ - `ReceiptRegistry`: append-only receipts keyed by `traceIdHash`.
31
+ - `PodVault`: a split vault so skill revenue can be shared among Pod members (EIP-2981 royalties → PodVault).
32
+
33
+ This is the minimum "box" that the agent can’t lose.
34
+
35
+ ## Surviving API keys: what we do today
36
+
37
+ The critique is correct: if your agent depends on a single API key, it's not survivable.
38
+
39
+ In ApeClaw:
40
+
41
+ - THE POD runs safe-by-default and can run without any model keys (stub vision backend).
42
+ - For real vision, Claude CLI is an option; local VLM backends are the intended fallback path (planned hardening).
43
+ - Market/bridge integrations are modular and can be swapped (Relay today; additional sources planned).
44
+
45
+ ## The missing piece: onchain enforcement (planned)
46
+
47
+ The real answer to "bounded automation" is enforcement + governance:
48
+
49
+ - `AgentAccount` + `PolicyEngine` (planned): onchain policy gates before value moves.
50
+ - Permissionless solvers (planned): execution competition, not a single central runner.
51
+ - Attestations/reputation (planned): version trust for skills.
52
+
53
+ v2 ships the primitives those phases depend on.
54
+
55
+ ## Practical definition of "autonomy" used here
56
+
57
+ An agent is "autonomous" if it can:
58
+
59
+ - run continuously across restarts
60
+ - keep its operating state in a survivable substrate
61
+ - be audited by third parties
62
+ - operate within explicit safety constraints
63
+ - change out optional infrastructure without losing identity/history
64
+
65
+ If you want a stronger definition, ApeClaw’s design is meant to evolve into it.
66
+
@@ -0,0 +1,93 @@
1
+ # Web4 Onchain Skills Plan — Status
2
+
3
+ This project includes the reference plan in `web4_onchain_skills_plan.pdf`.
4
+
5
+ This doc maps that plan to what ApeClaw has shipped today.
6
+
7
+ ## What is shipped (v2)
8
+
9
+ These components exist in-repo and are tested:
10
+
11
+ - `SkillNFT` (`contracts/SkillNFT.sol`)
12
+ - ERC-721 skill provenance
13
+ - parent forks (`parentSkillId`)
14
+ - optional royalties (EIP-2981) so skill revenue can route to a Pod receiver
15
+ - `SkillRegistry` (`contracts/SkillRegistry.sol`)
16
+ - append-only version publishing
17
+ - stores `versionHash`, `contentHash`, `uri`, `riskTier`
18
+ - `IntentRegistry` (`contracts/IntentRegistry.sol`)
19
+ - minimal intent create/cancel primitive
20
+ - `ReceiptRegistry` (`contracts/ReceiptRegistry.sol`)
21
+ - append-only receipts keyed by `traceIdHash`
22
+ - `PolicyEngine` (`contracts/PolicyEngine.sol`)
23
+ - minimal onchain pre-check hook (allowlists + value cap)
24
+ - `AgentAccount` (`contracts/AgentAccount.sol`)
25
+ - minimal execution shell that enforces PolicyEngine and records receipts
26
+ - Initial module skills (`contracts/*Module.sol`)
27
+ - `SwapModule`, `BridgeModule`, `NftBuyModule` (policy-gated call wrappers)
28
+ - `PodVault` (`contracts/PodVault.sol`)
29
+ - PaymentSplitter-style revenue receiver for THE POD (native + ERC20)
30
+ - Seed + deploy flow (`npm run contracts:seed`)
31
+ - deploys v2 contracts
32
+ - publishes all SkillCards in `skillcards/seed/`
33
+
34
+ SkillCards + library ingestion:
35
+
36
+ - seed SkillCards in `skillcards/seed/` (including v1 skills, receipts, and ACP bounties runbooks)
37
+ - importer: `scripts/import-skillcards.mjs`
38
+ - imports SkillCards from GitHub repos and ClawHub (best-effort)
39
+ - writes `skillcards/imported/index.json` (provenance + hashes)
40
+
41
+ Frontend/docs:
42
+
43
+ - `/ui` dashboard (telemetry, chat, live feed)
44
+ - `/skills` library page (seed + imported library views)
45
+ - `/docs` in-site markdown docs reader
46
+ - `/pod` product landing for THE POD
47
+
48
+ Critique response:
49
+
50
+ - `docs/AUTONOMY_AND_SUBSTRATE.md` directly addresses the "bounded automation" critique without overclaiming.
51
+
52
+ ## What is NOT shipped yet (still part of the plan)
53
+
54
+ The Web4 plan calls out these primitives as critical for full permissionless autonomy. ApeClaw now ships a minimal `AgentAccount` + `PolicyEngine`, but the full design is still not shipped:
55
+
56
+ - session keys / AA kernel hardening (ERC-4337 style)
57
+ - richer policy constraints (token/time windows, slippage checks, approvals model)
58
+ - Permissionless solver network + payments
59
+ - Attestation/reputation registry + eval packs onchain
60
+ - Disputes + slashing (optional later phase)
61
+
62
+ The current posture is deliberately "v2":
63
+
64
+ - strong provenance + immutable versions + receipts primitive
65
+ - strict opt-in for high-risk automation
66
+ - offchain execution remains bounded by the runner "box"
67
+
68
+ ## Phase mapping (rough)
69
+
70
+ - P0 (contracts + basic UI): partially shipped
71
+ - contracts shipped: yes (SkillNFT, Registry, IntentRegistry, ReceiptRegistry)
72
+ - basic UI for discovery/install/intents: partially shipped
73
+ - discovery: `/skills` (seed + imported + submitted SkillCards, onchain status visualization)
74
+ - intents: `/skills#intents` ships a safe command-generator surface for `v2 intent create|cancel`
75
+ - install: download/curl commands are surfaced per-skill; full “one-click install into an agent runtime” remains planned
76
+ - P1 (AgentAccount + module skills + receipts): shipped (v2 minimal primitives)
77
+ - `AgentAccount.executeSkill()` enforces `PolicyEngine.preCheck()` and best-effort records to `ReceiptRegistry`
78
+ - modules shipped: `SwapModule`, `BridgeModule`, `NftBuyModule` (policy-gated call wrappers; routing/UX remains offchain)
79
+ - P2 (permissionless solvers): not shipped
80
+ - P3 (attestations/reputation): not shipped
81
+ - P4 (disputes/slashing): not shipped
82
+
83
+ ## Why this is still a functioning platform today
84
+
85
+ ApeClaw's "functioning platform" claim is grounded in:
86
+
87
+ - global onboarding + telemetry + audit trail (events + optional receipts)
88
+ - deterministic CLI safety gates for value-moving actions
89
+ - a skill library that is content-addressed and publishable onchain
90
+ - a persistent Pod harness (file-backed) for long-running operation
91
+
92
+ The plan items above are the path from "bounded automation with anchors" to "permissionless autonomy with substrate enforcement".
93
+
@@ -0,0 +1,98 @@
1
+ # Web4 Swarm Model (ApeClaw)
2
+
3
+ This doc explains the core vision behind ApeClaw as a Web4 platform: **agents operate as a swarm**, and the swarm scales when it can:
4
+
5
+ - share capabilities (skills)
6
+ - share ground truth (receipts)
7
+ - persist state (checkpointing) beyond any single machine
8
+ - coordinate value-moving work safely (policies + caps + confirmations)
9
+
10
+ ## Why Web4 needs onchain context
11
+
12
+ Most “autonomous agents” are bounded automation:
13
+
14
+ - they plan in language, but don’t control the substrate
15
+ - they lose state when the UI/backend/API keys disappear
16
+ - they can’t prove what happened or coordinate trustlessly with other agents
17
+
18
+ A Web4 swarm needs a source of truth that:
19
+
20
+ - survives disappearing infrastructure
21
+ - is globally readable by any agent
22
+ - is permissionless at the primitive layer, but filterable at the UI layer
23
+
24
+ That’s why ApeClaw uses onchain primitives for:
25
+
26
+ - **Skill identity + versions** (SkillNFT + SkillRegistry)
27
+ - **Receipts** (ReceiptRegistry)
28
+
29
+ ## Skills: swarm capability scaling
30
+
31
+ SkillCards are portable JSON definitions: metadata + bindings + constraints.
32
+
33
+ - Offchain SkillCard JSON is the human-readable spec.
34
+ - Onchain publication anchors immutable versions:
35
+ - `contentHash` (content-addressed)
36
+ - `uri` (where the SkillCard lives)
37
+ - `riskTier` (safety classification)
38
+
39
+ This enables:
40
+
41
+ - deterministic upgrades (no silent changes)
42
+ - global discovery (chain indexers + UIs)
43
+ - “skill provenance” (what version did we run?)
44
+
45
+ ## Receipts: swarm memory + audit truth
46
+
47
+ Receipts are append-only anchors keyed by `traceIdHash`.
48
+
49
+ The pattern:
50
+
51
+ 1) An agent does work (or simulates/quotes work)
52
+ 2) It records a receipt with:
53
+ - `traceIdHash` (deterministic id)
54
+ - `contentHash` (what happened)
55
+ - `subject` (who/what it’s about)
56
+ - `uri` (optional pointer to larger payload/log)
57
+ 3) Any other agent can later read the receipt back from chain
58
+
59
+ This gives the swarm:
60
+
61
+ - “memory reload” (reconstruct state from receipts)
62
+ - auditability (“prove what happened”)
63
+ - coordination hooks (receipts as triggers)
64
+
65
+ CLI primitives:
66
+
67
+ - Record: `ape-claw v2 receipt record ...`
68
+ - Read: `ape-claw v2 receipt get ...`
69
+
70
+ ## Persistence: Pod workspace + chain checkpoints
71
+
72
+ Chain receipts are not a replacement for local state; they are a globally readable checkpoint layer.
73
+
74
+ The Pod workspace pattern provides:
75
+
76
+ - durable local state (files)
77
+ - crash recovery (`memory/active-tasks.md`, journals)
78
+ - strict opt-in execution (dry-run by default)
79
+
80
+ Receipts provide:
81
+
82
+ - global, portable checkpoints
83
+ - tamper-resistant audit anchors
84
+
85
+ The combination is what makes “agent swarm” possible.
86
+
87
+ ## Contribution loop (how the swarm grows)
88
+
89
+ 1) Users/agents submit SkillCards to the library (`/skills`)
90
+ 2) Curators/operators mint + publish onchain (immutable version)
91
+ 3) Agents use published skills, record receipts
92
+ 4) New skills and receipts expand the swarm’s capability + context
93
+
94
+ See:
95
+
96
+ - `docs/CONTRIBUTING.md`
97
+ - `docs/ONCHAIN_V2_GUIDE.md`
98
+
@@ -0,0 +1,345 @@
1
+ # Architecture
2
+
3
+ ## System Overview
4
+
5
+ ApeClaw is an onchain AI agent ecosystem on ApeChain. It consists of:
6
+
7
+ ### Components
8
+
9
+ 1. **Smart Contracts** (Solidity, deployed on ApeChain)
10
+ - **SkillNFT** — NFT representation of skills (one token per skill)
11
+ - **SkillRegistry** — Version and metadata storage (append-only version log)
12
+ - **IntentRegistry** — Agent intent publishing (for solver-style architectures)
13
+ - **ReceiptRegistry** — Execution audit trail (append-only receipts)
14
+ - **PodVault** — Revenue sharing vault (receives SkillNFT royalties)
15
+ - **AgentAccount** — Agent execution shell (enforces PolicyEngine, records receipts)
16
+ - **PolicyEngine** — Safety guardrails (allowlists + value caps)
17
+ - **Modules** (Swap, Bridge, NftBuy) — Executable skill implementations
18
+
19
+ 2. **Backend Server** (`src/server/index.mjs`, modular architecture)
20
+ - Telemetry server with SSE event streaming (Last-Event-ID support)
21
+ - REST API for skills, pods, clawbot management, quotes, bridge requests
22
+ - Middleware: CORS allowlist, rate limiting, body size limits, auth
23
+ - Storage abstraction: file-based (default) or SQLite backend
24
+ - Structured logging via `pino`
25
+ - Static file server for the UI
26
+ - In-memory skill index with caching (60s TTL)
27
+ - Legacy monolith still available at `src/telemetry-server.mjs`
28
+
29
+ 3. **CLI** (`ape-claw`, entry: `src/cli/index.mjs` → delegates to `src/cli.mjs`)
30
+ - Onchain operations (mint, publish, execute)
31
+ - Clawbot registration and management
32
+ - NFT purchasing and bridging
33
+ - Pod workspace management
34
+
35
+ 4. **Frontend** (HTML in `ui/`, extracted CSS in `ui/css/`, JS in `ui/js/`)
36
+ - Dashboard with live event feed (`ui/index.html` + `ui/css/dashboard.css` + `ui/js/dashboard.js`)
37
+ - Skills Library (`ui/skills.html` + `ui/css/skills.css` + `ui/js/skills.js`)
38
+ - Pod management (`ui/pod.html`)
39
+ - Documentation viewer (`ui/docs.html`)
40
+ - Shared components: sidebar nav, motion effects
41
+
42
+ ## Data Flow
43
+
44
+ ```mermaid
45
+ graph TB
46
+ User[User/Agent] --> CLI[CLI: ape-claw]
47
+ User --> UI[Frontend UI]
48
+
49
+ CLI --> Backend[Backend Server]
50
+ UI --> Backend
51
+
52
+ Backend --> Contracts[Smart Contracts<br/>on ApeChain]
53
+
54
+ Contracts --> Events[Contract Events]
55
+ Events --> Backend
56
+
57
+ Backend --> SSE[SSE Stream]
58
+ SSE --> UI
59
+
60
+ CLI --> LocalState[Local State<br/>state/ directory]
61
+ CLI --> SkillCards[SkillCards<br/>skillcards/ directory]
62
+
63
+ SkillNFT --> Royalties[EIP-2981 Royalties]
64
+ Royalties --> PodVault[PodVault]
65
+ PodVault --> Members[Pod Members]
66
+
67
+ AgentAccount --> Policy[PolicyEngine<br/>preCheck]
68
+ AgentAccount --> Module[ISkillModule<br/>execute]
69
+ AgentAccount --> Receipts[ReceiptRegistry<br/>recordReceipt]
70
+ ```
71
+
72
+ ### Execution Flow
73
+
74
+ 1. **Skill Minting & Publishing**:
75
+ ```
76
+ CLI → SkillNFT.mintSkillWithRoyalty() → SkillRegistry.publishVersion()
77
+ ```
78
+
79
+ 2. **Module Execution**:
80
+ ```
81
+ CLI → AgentAccount.executeSkill() → PolicyEngine.preCheck() → ISkillModule.execute() → ReceiptRegistry.recordReceipt()
82
+ ```
83
+
84
+ 3. **Event Streaming**:
85
+ ```
86
+ Contract Events → Backend (SSE) → Frontend UI
87
+ ```
88
+
89
+ ## State Management
90
+
91
+ ### Onchain State
92
+
93
+ Contracts deployed on ApeChain store:
94
+
95
+ - **SkillNFT**: Ownership and provenance (one NFT per skill)
96
+ - **SkillRegistry**: Immutable version log (`skillId` → `SkillVersion[]`)
97
+ - **IntentRegistry**: Active intents for solver competition
98
+ - **ReceiptRegistry**: Append-only execution receipts
99
+ - **PodVault**: Revenue shares and pending payments
100
+ - **PolicyEngine**: Allowlists (modules, targets, selectors) and value caps
101
+
102
+ Example deployment record (`state/v2-deployments/apechain.json`):
103
+
104
+ ```json
105
+ {
106
+ "skillNft": "0x...",
107
+ "registry": "0x...",
108
+ "intents": "0x...",
109
+ "receipts": "0x...",
110
+ "policy": "0x...",
111
+ "agentAccount": "0x...",
112
+ "podVault": "0x...",
113
+ "modules": {
114
+ "swap": "0x...",
115
+ "bridge": "0x...",
116
+ "nftBuy": "0x..."
117
+ },
118
+ "chainId": 33139,
119
+ "network": "apechain"
120
+ }
121
+ ```
122
+
123
+ ### Local State
124
+
125
+ The `state/` directory contains:
126
+
127
+ - **`v2-deployments/`**: Deployment records per network
128
+ - **`skillcards-user/`**: User-submitted SkillCards
129
+ - **`quotes.json`**: NFT purchase quotes
130
+ - **`bridge-requests.json`**: Bridge request records
131
+ - **`events.jsonl`**: Telemetry events (appended by CLI/server)
132
+ - **`chat.jsonl`**: Chat messages
133
+ - **`invites.json`**: Registration invite tokens
134
+ - **`apeclaw.db`**: SQLite database (when `APE_CLAW_STORAGE=sqlite`)
135
+
136
+ The `config/` directory contains:
137
+
138
+ - **`clawbots.json`**: Registered clawbot configurations
139
+ - **`policy.json`**: Safety policy rules
140
+
141
+ ### Skill Library
142
+
143
+ SkillCards are stored in:
144
+
145
+ - **`skillcards/seed/`**: Seed skills (trusted, vetted)
146
+ - **`skillcards/imported/`**: Imported skills from external sources
147
+ - **`skillcards/imported/index.json`**: Index of imported skills
148
+
149
+ The backend merges all three sources into a unified index (cached for 60 seconds):
150
+
151
+ ```javascript
152
+ // From storage backend (file-backend.mjs or sqlite-backend.mjs)
153
+ function buildMergedSkillIndex() {
154
+ const merged = [];
155
+ // 1. Read seed skills from skillcards/seed/*.json
156
+ // 2. Read imported skills from skillcards/imported/index.json
157
+ // 3. Read user skills from state/skillcards-user/index.json
158
+ return merged;
159
+ }
160
+ ```
161
+
162
+ ### Pod Workspace
163
+
164
+ Configurable directory (default: `pod/`) with:
165
+
166
+ - **`AGENTS.md`**: Agent configuration and capabilities
167
+ - **`SOUL.md`**: Agent identity and preferences
168
+ - **`memory/`**: Persistent memory storage
169
+ - **`journal/YYYY-MM-DD.md`**: Daily execution logs
170
+ - **`executions/*.json`**: Execution audit trail
171
+
172
+ ## Contract Interactions
173
+
174
+ ### Skill Lifecycle
175
+
176
+ ```solidity
177
+ // 1. Mint SkillNFT
178
+ SkillNFT.mintSkillWithRoyalty(parentId, podVault, 500); // 5% royalty
179
+
180
+ // 2. Publish version to SkillRegistry
181
+ SkillRegistry.publishVersion(
182
+ skillId,
183
+ versionHash, // keccak256(version_string)
184
+ contentHash, // keccak256(canonical_json)
185
+ uri, // ipfs://... or file://...
186
+ riskTier // 0-3 (unknown, low, medium, high)
187
+ );
188
+ ```
189
+
190
+ ### Module Execution
191
+
192
+ ```solidity
193
+ // AgentAccount.executeSkill() flow:
194
+ // 1. PolicyEngine.preCheck(module, target, selector, value)
195
+ // 2. ISkillModule.execute(agentAccount, input)
196
+ // 3. ReceiptRegistry.recordReceipt(traceIdHash, contentHash, subjectHash, uri)
197
+
198
+ // Example: SwapModule
199
+ AgentAccount.executeSkill(
200
+ swapModule, // module address
201
+ abi.encode(target, calldata), // input: (address, bytes)
202
+ value, // ETH value
203
+ traceIdHash, // execution trace ID
204
+ subjectHash, // agent/skill identifier
205
+ uri // receipt metadata URI
206
+ );
207
+ ```
208
+
209
+ ### Policy Enforcement
210
+
211
+ The `PolicyEngine` enforces three allowlists:
212
+
213
+ ```solidity
214
+ // From PolicyEngine.sol
215
+ function preCheck(address module, address target, bytes4 selector, uint256 value) external view {
216
+ require(allowedModules[module], "module blocked");
217
+ require(value <= maxValuePerTx, "value over cap");
218
+ require(allowedTargets[target], "target blocked");
219
+ require(allowedSelectors[target][selector], "selector blocked");
220
+ }
221
+ ```
222
+
223
+ Registration example (from `deploy-and-seed-v2-alpha.js`):
224
+
225
+ ```javascript
226
+ await policy.write.setMaxValuePerTx([parseEther("1")]);
227
+ await policy.write.setModuleAllowed([swapModule.address, true]);
228
+ await policy.write.setTargetAllowed([targetAddress, true]);
229
+ await policy.write.setSelectorAllowed([targetAddress, selector, true]);
230
+ ```
231
+
232
+ ## Backend Architecture
233
+
234
+ ### Modular Server (`src/server/`)
235
+
236
+ The backend is organized into a modular structure:
237
+
238
+ ```
239
+ src/server/
240
+ index.mjs # Main entry point, request routing, safeHandler wrapper
241
+ sse.mjs # SSE client management, broadcast, Last-Event-ID support
242
+ logger.mjs # Structured logging (pino)
243
+ middleware/
244
+ cors.mjs # CORS allowlist (built-in, includes apeclaw.ai + localhost variants)
245
+ rate-limit.mjs # In-memory sliding-window rate limiter
246
+ body-limit.mjs # Request body size limits
247
+ auth.mjs # Agent/admin auth (requireSkillWriteAuth, resolveChatAuth)
248
+ routes/
249
+ health.mjs # GET /api/health
250
+ events.mjs # SSE stream, backlog, POST /api/events
251
+ skills.mjs # Skills search, get, stats, user skillcards
252
+ clawbots.mjs # Clawbot list, verify, register, invites
253
+ chat.mjs # Chat stream, rooms, messages, reactions
254
+ v2.mjs # V2 config, receipt get
255
+ pod.mjs # Pod status, stop
256
+ quotes.mjs # Quote/bridge-request CRUD, spend-today
257
+ static.mjs # Static files, rewrites, allowlist, policy
258
+ storage/
259
+ index.mjs # Storage abstraction (initStorage, getStorage, storageEvents)
260
+ file-backend.mjs # File-based storage (default)
261
+ sqlite-backend.mjs # SQLite storage (APE_CLAW_STORAGE=sqlite)
262
+ ```
263
+
264
+ Key endpoints:
265
+
266
+ - `GET /api/skills/search`: Merged skill index (seed + imported + user)
267
+ - `POST /api/skillcards/user/add`: Submit new SkillCard (requires auth)
268
+ - `GET /events/backlog?limit=300&since=<ts>`: Historical events
269
+ - `GET /events`: SSE stream with `id:` fields and Last-Event-ID reconnect support
270
+ - `POST /api/clawbots/register`: Register clawbot
271
+ - `POST /api/quotes`: Create quote (centralized state for multi-machine)
272
+ - `GET /api/quotes/spend-today`: Server-side daily spend (global enforcement)
273
+
274
+ ### Event System
275
+
276
+ Events flow through the storage abstraction and are broadcast via an EventEmitter:
277
+
278
+ ```javascript
279
+ // Storage backend emits events
280
+ storageEvents.emit("telemetryEvent", evt);
281
+
282
+ // SSE module broadcasts to connected clients
283
+ function sendSse(res, data, id) {
284
+ if (id !== undefined) res.write(`id: ${id}\n`);
285
+ res.write(`data: ${JSON.stringify(data)}\n\n`);
286
+ }
287
+ ```
288
+
289
+ ## CLI Architecture
290
+
291
+ The CLI (`src/cli.mjs`) handles:
292
+
293
+ - **Onchain Operations**: Minting, publishing, executing via viem
294
+ - **Policy Enforcement**: Loading and validating policy.json
295
+ - **Market Discovery**: Reservoir/OpenSea API integration
296
+ - **Bridge Execution**: Relay protocol integration
297
+ - **Telemetry**: Emitting events to backend
298
+
299
+ Example CLI flow (NFT purchase):
300
+
301
+ ```javascript
302
+ // 1. Quote
303
+ const quote = await quoteBuy({ collection, tokenId, maxPrice });
304
+
305
+ // 2. Simulate
306
+ const sim = await simulateBuy({ quoteId });
307
+
308
+ // 3. Execute (with confirm phrase)
309
+ const result = await executeBuy({ quoteId, confirm, execute: true });
310
+ ```
311
+
312
+ ## Revenue Flow
313
+
314
+ SkillNFT royalties flow to PodVault:
315
+
316
+ 1. **Royalty Setup**: `SkillNFT.mintSkillWithRoyalty(parentId, podVault, 500)` sets 5% royalty
317
+ 2. **Marketplace Payment**: When skill is sold, marketplace pays royalty to PodVault
318
+ 3. **Member Release**: Pod members call `PodVault.releaseNative(member)` to claim their share
319
+
320
+ ```solidity
321
+ // From PodVault.sol
322
+ function pendingNative(address member) public view returns (uint256) {
323
+ uint256 s = shares[member];
324
+ if (s == 0) return 0;
325
+ uint256 totalReceived = address(this).balance + totalReleasedNative;
326
+ uint256 already = releasedNative[member];
327
+ return (totalReceived * s) / totalShares - already;
328
+ }
329
+ ```
330
+
331
+ ## Network Configuration
332
+
333
+ ApeClaw supports:
334
+
335
+ - **ApeChain** (chainId: 33139): Production network
336
+ - **Hardhat Local** (chainId: 31337): Development network
337
+
338
+ RPC URLs are configured via environment variables:
339
+
340
+ ```bash
341
+ export APE_CLAW_V2_RPC_URL=https://apechain-rpc.example.com
342
+ export APE_CLAW_V2_PRIVATE_KEY=0x...
343
+ ```
344
+
345
+ Deployment records are stored per network in `state/v2-deployments/<network>.json`.