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.
- package/CHANGELOG.md +126 -0
- package/COMPATIBILITY.md +13 -0
- package/KNOWN_LIMITATIONS.md +19 -0
- package/LICENSE +44 -0
- package/LICENSING.md +10 -0
- package/README.md +378 -210
- package/SECURITY.md +52 -0
- package/dist/index.d.ts +1477 -0
- package/dist/index.js +3464 -0
- package/dist/index.js.map +1 -0
- package/native/Cargo.lock +4863 -0
- package/native/Cargo.toml +73 -0
- package/native/crates/canonical/Cargo.toml +24 -0
- package/native/crates/canonical/src/lib.rs +673 -0
- package/native/crates/compression/Cargo.toml +20 -0
- package/native/crates/compression/benches/compression_bench.rs +42 -0
- package/native/crates/compression/src/lib.rs +393 -0
- package/native/crates/evm-eth/Cargo.toml +13 -0
- package/native/crates/evm-eth/src/lib.rs +105 -0
- package/native/crates/fee/Cargo.toml +15 -0
- package/native/crates/fee/src/lib.rs +281 -0
- package/native/crates/index/Cargo.toml +16 -0
- package/native/crates/index/src/lib.rs +277 -0
- package/native/crates/policy/Cargo.toml +17 -0
- package/native/crates/policy/src/lib.rs +614 -0
- package/native/crates/security/Cargo.toml +22 -0
- package/native/crates/security/src/lib.rs +478 -0
- package/native/crates/tokens/Cargo.toml +13 -0
- package/native/crates/tokens/src/lib.rs +534 -0
- package/native/crates/verification/Cargo.toml +23 -0
- package/native/crates/verification/src/lib.rs +333 -0
- package/native/crates/wallet/Cargo.toml +20 -0
- package/native/crates/wallet/src/lib.rs +261 -0
- package/native/crates/x402/Cargo.toml +30 -0
- package/native/crates/x402/src/lib.rs +423 -0
- package/native/ffi/Cargo.toml +34 -0
- package/native/ffi/build.rs +4 -0
- package/native/ffi/index.node +0 -0
- package/native/ffi/src/lib.rs +352 -0
- package/native/ffi/tests/integration.rs +354 -0
- package/native/pyo3/Cargo.toml +26 -0
- package/native/pyo3/pyproject.toml +16 -0
- package/native/pyo3/src/lib.rs +407 -0
- package/native/pyo3/tests/test_smoke.py +180 -0
- package/native/wasm/Cargo.toml +44 -0
- package/native/wasm/pkg/.gitignore +6 -0
- package/native/wasm/pkg/clawpowers_wasm.d.ts +208 -0
- package/native/wasm/pkg/clawpowers_wasm.js +872 -0
- package/native/wasm/pkg/clawpowers_wasm_bg.wasm +0 -0
- package/native/wasm/pkg/clawpowers_wasm_bg.wasm.d.ts +40 -0
- package/native/wasm/pkg/package.json +17 -0
- package/native/wasm/pkg-node/.gitignore +6 -0
- package/native/wasm/pkg-node/clawpowers_wasm.d.ts +143 -0
- package/native/wasm/pkg-node/clawpowers_wasm.js +798 -0
- package/native/wasm/pkg-node/clawpowers_wasm_bg.wasm +0 -0
- package/native/wasm/pkg-node/clawpowers_wasm_bg.wasm.d.ts +40 -0
- package/native/wasm/pkg-node/package.json +13 -0
- package/native/wasm/src/lib.rs +433 -0
- package/package.json +71 -44
- package/src/skills/catalog.ts +435 -0
- package/src/skills/executor.ts +56 -0
- package/src/skills/index.ts +3 -0
- package/src/skills/itp/SKILL.md +112 -0
- package/src/skills/loader.ts +193 -0
- package/.claude-plugin/manifest.json +0 -19
- package/.codex/INSTALL.md +0 -36
- package/.cursor-plugin/manifest.json +0 -21
- package/.opencode/INSTALL.md +0 -52
- package/ARCHITECTURE.md +0 -69
- package/bin/clawpowers.js +0 -625
- package/bin/clawpowers.sh +0 -91
- package/docs/demo/clawpowers-demo.cast +0 -197
- package/docs/demo/clawpowers-demo.gif +0 -0
- package/docs/launch-images/25-skills-breakdown.jpg +0 -0
- package/docs/launch-images/clawpowers-vs-superpowers.jpg +0 -0
- package/docs/launch-images/economic-code-optimization.jpg +0 -0
- package/docs/launch-images/native-vs-bridge-2.jpg +0 -0
- package/docs/launch-images/native-vs-bridge.jpg +0 -0
- package/docs/launch-images/post1-hero-lobster.jpg +0 -0
- package/docs/launch-images/post2-dashboard.jpg +0 -0
- package/docs/launch-images/post3-superpowers.jpg +0 -0
- package/docs/launch-images/post4-before-after.jpg +0 -0
- package/docs/launch-images/post5-install-now.jpg +0 -0
- package/docs/launch-images/ultimate-stack.jpg +0 -0
- package/docs/launch-posts.md +0 -76
- package/docs/quickstart-first-transaction.md +0 -204
- package/gemini-extension.json +0 -32
- package/hooks/session-start +0 -205
- package/hooks/session-start.cmd +0 -43
- package/hooks/session-start.js +0 -163
- package/runtime/demo/README.md +0 -78
- package/runtime/demo/x402-mock-server.js +0 -230
- package/runtime/feedback/analyze.js +0 -621
- package/runtime/feedback/analyze.sh +0 -546
- package/runtime/init.js +0 -210
- package/runtime/init.sh +0 -178
- package/runtime/metrics/collector.js +0 -361
- package/runtime/metrics/collector.sh +0 -308
- package/runtime/payments/ledger.js +0 -305
- package/runtime/payments/ledger.sh +0 -262
- package/runtime/payments/pipeline.js +0 -455
- package/runtime/persistence/store.js +0 -433
- package/runtime/persistence/store.sh +0 -303
- package/skill.json +0 -106
- package/skills/agent-bounties/SKILL.md +0 -553
- package/skills/agent-payments/SKILL.md +0 -479
- package/skills/brainstorming/SKILL.md +0 -233
- package/skills/content-pipeline/SKILL.md +0 -282
- package/skills/cross-project-knowledge/SKILL.md +0 -345
- package/skills/dispatching-parallel-agents/SKILL.md +0 -305
- package/skills/economic-code-optimization/SKILL.md +0 -265
- package/skills/executing-plans/SKILL.md +0 -255
- package/skills/finishing-a-development-branch/SKILL.md +0 -260
- package/skills/formal-verification-lite/SKILL.md +0 -441
- package/skills/learn-how-to-learn/SKILL.md +0 -235
- package/skills/market-intelligence/SKILL.md +0 -323
- package/skills/meta-skill-evolution/SKILL.md +0 -325
- package/skills/prospecting/SKILL.md +0 -454
- package/skills/receiving-code-review/SKILL.md +0 -225
- package/skills/requesting-code-review/SKILL.md +0 -206
- package/skills/security-audit/SKILL.md +0 -353
- package/skills/self-healing-code/SKILL.md +0 -369
- package/skills/subagent-driven-development/SKILL.md +0 -244
- package/skills/systematic-debugging/SKILL.md +0 -355
- package/skills/test-driven-development/SKILL.md +0 -416
- package/skills/using-clawpowers/SKILL.md +0 -160
- package/skills/using-git-worktrees/SKILL.md +0 -261
- package/skills/validator/SKILL.md +0 -281
- package/skills/verification-before-completion/SKILL.md +0 -254
- package/skills/writing-plans/SKILL.md +0 -276
- package/skills/writing-skills/SKILL.md +0 -260
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/skills/catalog.ts","../src/config.ts","../src/constants.ts","../src/native/index.ts","../src/payments/discovery.ts","../src/payments/spending.ts","../src/payments/executor.ts","../src/payments/native-bridge.ts","../src/memory/working.ts","../src/memory/episodic.ts","../src/memory/procedural.ts","../src/memory/checkpoint.ts","../src/memory/context-injector.ts","../src/memory/native-store.ts","../src/rsi/metrics.ts","../src/rsi/hypothesis.ts","../src/rsi/mutation.ts","../src/rsi/ab-test.ts","../src/rsi/audit.ts","../src/rsi/auto-research.ts","../src/skills/loader.ts","../src/skills/executor.ts","../src/wallet/manager.ts","../src/wallet/crypto.ts","../src/itp/index.ts","../src/itp/swarm-bridge.ts","../src/swarm/concurrency.ts","../src/swarm/token_pool.ts","../src/swarm/model_router.ts"],"sourcesContent":["/**\n * ClawPowers Agent — Skills Catalog\n *\n * Static catalog of all skills available to ClawPowers.\n * Sources:\n * - openclaw-bundled: 51 skills bundled with OpenClaw\n * - managed: skills installed in ~/.openclaw/skills/\n *\n * Generated by reading SKILL.md frontmatter from each skill directory.\n * This is a STATIC array so it works everywhere (no runtime file I/O).\n */\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface SkillEntry {\n name: string;\n description: string;\n source: 'openclaw-bundled' | 'clawpowers' | 'managed';\n category: string;\n}\n\n// ─── OpenClaw Bundled Skills (51) ─────────────────────────────────────────────\n\nexport const SKILLS_CATALOG: SkillEntry[] = [\n // ── productivity ──────────────────────────────────────────────────────────\n {\n name: '1password',\n description: 'Set up and use 1Password CLI (op). Use when installing the CLI, enabling desktop app integration, signing in (single or multi-account), or reading/injecting/running secrets via op.',\n source: 'openclaw-bundled',\n category: 'productivity',\n },\n {\n name: 'apple-notes',\n description: 'Manage Apple Notes via the `memo` CLI on macOS (create, view, edit, delete, search, move, and export notes). Use when a user asks OpenClaw to add a note, list notes, search notes, or manage note folders.',\n source: 'openclaw-bundled',\n category: 'productivity',\n },\n {\n name: 'apple-reminders',\n description: 'Manage Apple Reminders via remindctl CLI (list, add, edit, complete, delete). Supports lists, date filters, and JSON/plain output.',\n source: 'openclaw-bundled',\n category: 'productivity',\n },\n {\n name: 'bear-notes',\n description: 'Create, search, and manage Bear notes via grizzly CLI.',\n source: 'openclaw-bundled',\n category: 'productivity',\n },\n {\n name: 'notion',\n description: 'Notion API for creating and managing pages, databases, and blocks.',\n source: 'openclaw-bundled',\n category: 'productivity',\n },\n {\n name: 'obsidian',\n description: 'Work with Obsidian vaults (plain Markdown notes) and automate via obsidian-cli.',\n source: 'openclaw-bundled',\n category: 'productivity',\n },\n {\n name: 'things-mac',\n description: 'Manage Things 3 via the `things` CLI on macOS (add/update projects+todos via URL scheme; read/search/list from the local Things database). Use when a user asks OpenClaw to add a task to Things, list items, or search tasks.',\n source: 'openclaw-bundled',\n category: 'productivity',\n },\n {\n name: 'trello',\n description: 'Manage Trello boards, lists, and cards via the Trello REST API.',\n source: 'openclaw-bundled',\n category: 'productivity',\n },\n {\n name: 'summarize',\n description: 'Summarize or extract text/transcripts from URLs, podcasts, and local files (great fallback for \"transcribe this YouTube/video\").',\n source: 'openclaw-bundled',\n category: 'productivity',\n },\n {\n name: 'tmux',\n description: 'Remote-control tmux sessions for interactive CLIs by sending keystrokes and scraping pane output.',\n source: 'openclaw-bundled',\n category: 'productivity',\n },\n // ── development ───────────────────────────────────────────────────────────\n {\n name: 'coding-agent',\n description: 'Delegate coding tasks to Codex, Claude Code, or Pi agents via background process. Use when: (1) building/creating new features or apps, (2) reviewing PRs (spawn in temp dir), (3) refactoring large codebases.',\n source: 'openclaw-bundled',\n category: 'development',\n },\n {\n name: 'github',\n description: 'GitHub operations via `gh` CLI: issues, PRs, CI runs, code review, API queries. Use when: (1) checking PR status or CI, (2) creating/commenting on issues, (3) listing/filtering PRs or issues, (4) viewing diffs.',\n source: 'openclaw-bundled',\n category: 'development',\n },\n {\n name: 'gh-issues',\n description: 'Fetch GitHub issues, spawn sub-agents to implement fixes and open PRs, then monitor and address PR review comments.',\n source: 'openclaw-bundled',\n category: 'development',\n },\n {\n name: 'skill-creator',\n description: 'Create, edit, improve, or audit AgentSkills. Use when creating a new skill from scratch or when asked to improve, review, audit, tidy up, or clean up an existing skill or SKILL.md file.',\n source: 'openclaw-bundled',\n category: 'development',\n },\n {\n name: 'clawhub',\n description: 'Use the ClawHub CLI to search, install, update, and publish agent skills from clawhub.com. Use when you need to fetch new skills on the fly, sync installed skills to latest or a specific version, or publish your own skills.',\n source: 'openclaw-bundled',\n category: 'development',\n },\n {\n name: 'oracle',\n description: 'Best practices for using the oracle CLI (prompt + file bundling, engines, sessions, and file attachment patterns).',\n source: 'openclaw-bundled',\n category: 'development',\n },\n {\n name: 'mcporter',\n description: 'Use the mcporter CLI to list, configure, auth, and call MCP servers/tools directly (HTTP or stdio), including ad-hoc servers, config edits, and CLI/type generation.',\n source: 'openclaw-bundled',\n category: 'development',\n },\n {\n name: 'nano-pdf',\n description: 'Edit PDFs with natural-language instructions using the nano-pdf CLI.',\n source: 'openclaw-bundled',\n category: 'development',\n },\n {\n name: 'node-connect',\n description: 'Diagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps. Use when QR/setup code/manual connect fails, local Wi-Fi works but VPS/tailnet does not, or errors mention pairing.',\n source: 'openclaw-bundled',\n category: 'development',\n },\n // ── communication ─────────────────────────────────────────────────────────\n {\n name: 'discord',\n description: 'Discord ops via the message tool (channel=discord).',\n source: 'openclaw-bundled',\n category: 'communication',\n },\n {\n name: 'slack',\n description: 'Use when you need to control Slack from OpenClaw via the slack tool, including reacting to messages or pinning/unpinning items in Slack channels or DMs.',\n source: 'openclaw-bundled',\n category: 'communication',\n },\n {\n name: 'bluebubbles',\n description: 'Use when you need to send or manage iMessages via BlueBubbles (recommended iMessage integration). Calls go through the generic message tool with channel=bluebubbles.',\n source: 'openclaw-bundled',\n category: 'communication',\n },\n {\n name: 'imsg',\n description: 'iMessage/SMS CLI for listing chats, history, and sending messages via Messages.app.',\n source: 'openclaw-bundled',\n category: 'communication',\n },\n {\n name: 'wacli',\n description: 'Send WhatsApp messages to other people or search/sync WhatsApp history via the wacli CLI (not for normal user chats).',\n source: 'openclaw-bundled',\n category: 'communication',\n },\n {\n name: 'himalaya',\n description: 'CLI to manage emails via IMAP/SMTP. Use `himalaya` to list, read, write, reply, forward, search, and organize emails from the terminal. Supports multiple accounts and message composition with MML.',\n source: 'openclaw-bundled',\n category: 'communication',\n },\n {\n name: 'gog',\n description: 'Google Workspace CLI for Gmail, Calendar, Drive, Contacts, Sheets, and Docs.',\n source: 'openclaw-bundled',\n category: 'communication',\n },\n // ── media ─────────────────────────────────────────────────────────────────\n {\n name: 'camsnap',\n description: 'Capture frames or clips from RTSP/ONVIF cameras.',\n source: 'openclaw-bundled',\n category: 'media',\n },\n {\n name: 'gifgrep',\n description: 'Search GIF providers with CLI/TUI, download results, and extract stills/sheets.',\n source: 'openclaw-bundled',\n category: 'media',\n },\n {\n name: 'video-frames',\n description: 'Extract frames or short clips from videos using ffmpeg.',\n source: 'openclaw-bundled',\n category: 'media',\n },\n {\n name: 'openai-whisper',\n description: 'Local speech-to-text with the Whisper CLI (no API key).',\n source: 'openclaw-bundled',\n category: 'media',\n },\n {\n name: 'openai-whisper-api',\n description: 'Transcribe audio via OpenAI Audio Transcriptions API (Whisper).',\n source: 'openclaw-bundled',\n category: 'media',\n },\n {\n name: 'sag',\n description: 'ElevenLabs text-to-speech with mac-style say UX.',\n source: 'openclaw-bundled',\n category: 'media',\n },\n {\n name: 'sherpa-onnx-tts',\n description: 'Local text-to-speech via sherpa-onnx (offline, no cloud).',\n source: 'openclaw-bundled',\n category: 'media',\n },\n {\n name: 'songsee',\n description: 'Generate spectrograms and feature-panel visualizations from audio with the songsee CLI.',\n source: 'openclaw-bundled',\n category: 'media',\n },\n {\n name: 'voice-call',\n description: 'Start voice calls via the OpenClaw voice-call plugin.',\n source: 'openclaw-bundled',\n category: 'media',\n },\n {\n name: 'peekaboo',\n description: 'Capture and automate macOS UI with the Peekaboo CLI.',\n source: 'openclaw-bundled',\n category: 'media',\n },\n // ── music ─────────────────────────────────────────────────────────────────\n {\n name: 'spotify-player',\n description: 'Terminal Spotify playback/search via spogo (preferred) or spotify_player.',\n source: 'openclaw-bundled',\n category: 'music',\n },\n {\n name: 'sonoscli',\n description: 'Control Sonos speakers (discover/status/play/volume/group).',\n source: 'openclaw-bundled',\n category: 'music',\n },\n {\n name: 'blucli',\n description: 'BluOS CLI (blu) for discovery, playback, grouping, and volume.',\n source: 'openclaw-bundled',\n category: 'music',\n },\n // ── smart-home ────────────────────────────────────────────────────────────\n {\n name: 'openhue',\n description: 'Control Philips Hue lights and scenes via the OpenHue CLI.',\n source: 'openclaw-bundled',\n category: 'smart-home',\n },\n {\n name: 'eightctl',\n description: 'Control Eight Sleep pods (status, temperature, alarms, schedules).',\n source: 'openclaw-bundled',\n category: 'smart-home',\n },\n // ── ai ────────────────────────────────────────────────────────────────────\n {\n name: 'gemini',\n description: 'Gemini CLI for one-shot Q&A, summaries, and generation.',\n source: 'openclaw-bundled',\n category: 'ai',\n },\n {\n name: 'canvas',\n description: 'Display HTML content on connected OpenClaw nodes (Mac app, iOS, Android). Great for displaying games, visualizations, and dashboards.',\n source: 'openclaw-bundled',\n category: 'ai',\n },\n // ── utilities ─────────────────────────────────────────────────────────────\n {\n name: 'blogwatcher',\n description: 'Monitor blogs and RSS/Atom feeds for updates using the blogwatcher CLI.',\n source: 'openclaw-bundled',\n category: 'utilities',\n },\n {\n name: 'goplaces',\n description: 'Query Google Places API (New) via the goplaces CLI for text search, place details, resolve, and reviews. Use for human-friendly place lookup or JSON output for scripts.',\n source: 'openclaw-bundled',\n category: 'utilities',\n },\n {\n name: 'healthcheck',\n description: 'Host security hardening and risk-tolerance configuration for OpenClaw deployments. Use when a user asks for security audits, firewall/SSH/update hardening, risk posture, exposure review, or OpenClaw cron health.',\n source: 'openclaw-bundled',\n category: 'utilities',\n },\n {\n name: 'model-usage',\n description: 'Use CodexBar CLI local cost usage to summarize per-model usage for Codex or Claude, including the current (most recent) model or a full model breakdown. Trigger when asked for model-level usage/cost details.',\n source: 'openclaw-bundled',\n category: 'utilities',\n },\n {\n name: 'ordercli',\n description: 'Foodora-only CLI for checking past orders and active order status (Deliveroo WIP).',\n source: 'openclaw-bundled',\n category: 'utilities',\n },\n {\n name: 'session-logs',\n description: 'Search and analyze your own session logs (older/parent conversations) using jq.',\n source: 'openclaw-bundled',\n category: 'utilities',\n },\n {\n name: 'weather',\n description: 'Get current weather and forecasts via wttr.in or Open-Meteo. Use when: user asks about weather, temperature, or forecasts for any location. NOT for: historical weather data, severe weather alerts, or other weather APIs.',\n source: 'openclaw-bundled',\n category: 'utilities',\n },\n {\n name: 'xurl',\n description: 'A CLI tool for making authenticated requests to the X (Twitter) API. Use this skill when you need to post tweets, reply, quote, search, read posts, manage followers, send DMs, upload media, or interact with X/Twitter programmatically.',\n source: 'openclaw-bundled',\n category: 'utilities',\n },\n\n // ─── Managed Skills (~/.openclaw/skills/) ──────────────────────────────────\n {\n name: 'agent-nexus-2',\n description: 'Multi-agent coordination and task delegation for complex workflows requiring parallel agent execution.',\n source: 'managed',\n category: 'development',\n },\n {\n name: 'autoresearch',\n description: 'Autonomous code quality improvement loop using keep-or-revert cycles. Optimizes a composite quality score derived from tests, lint, and type coverage.',\n source: 'managed',\n category: 'development',\n },\n {\n name: 'business-strategy',\n description: 'PMF validation, beachhead identification, activity ROI analysis, kill/invest decisions, and strategic metrics for the AI Agent Economy.',\n source: 'managed',\n category: 'productivity',\n },\n {\n name: 'coding-discipline.skill',\n description: 'Enforces strict TypeScript coding standards, test-first development, and zero-stub policies for production-grade agent code.',\n source: 'managed',\n category: 'development',\n },\n {\n name: 'content-writer',\n description: 'Use this skill everytime you are writing an article, social media post, email, etc.',\n source: 'managed',\n category: 'communication',\n },\n {\n name: 'execution-validation.skill',\n description: 'Multi-round automated validation pipeline for TypeScript/Solidity projects before publish or deploy.',\n source: 'managed',\n category: 'development',\n },\n {\n name: 'humanize',\n description: 'Transforms AI-generated writing into content that reads authentically human — passing AI detectors and resonating with real readers.',\n source: 'managed',\n category: 'communication',\n },\n {\n name: 'polyclaw',\n description: 'Trade on Polymarket via split + CLOB execution. Browse markets, track positions with P&L, discover hedges via LLM. Polygon/Web3.',\n source: 'managed',\n category: 'finance',\n },\n {\n name: 'prospector',\n description: 'Find leads, prospects, and contacts matching an Ideal Customer Profile. Searches companies via Exa and enriches contacts via Apollo, outputting to CSV and optionally syncing to Attio CRM.',\n source: 'managed',\n category: 'productivity',\n },\n {\n name: 'rsi.skill',\n description: 'RSI self-improvement cycles implementing measure → hypothesize → mutate → test → apply/discard → repeat for agent capability enhancement.',\n source: 'managed',\n category: 'development',\n },\n {\n name: 'security',\n description: 'Infrastructure threat detection, vulnerability management, and security audit workflows for the OpenClaw workspace.',\n source: 'managed',\n category: 'utilities',\n },\n {\n name: 'strykr-prism',\n description: 'Real-time financial data API for AI agents. Stocks, crypto, forex, ETFs. 120+ endpoints. Alternative to Alpha Vantage, CoinGecko. Works with Claude, Cursor.',\n source: 'managed',\n category: 'finance',\n },\n {\n name: 'taskbridge',\n description: 'Bridge tasks between agent sessions, preserving context and handoff state for long-running multi-session workflows.',\n source: 'managed',\n category: 'productivity',\n },\n {\n name: 'validator-agent',\n description: 'Multi-round automated validation pipeline for TypeScript/Solidity projects. Runs 8 rounds of checks before any publish or deploy: compile gate, lint, test suite, security audit, type coverage, docs, changelog, and final review.',\n source: 'managed',\n category: 'development',\n },\n {\n name: 'webmcp-payments',\n description: 'Handle HTTP 402 Payment Required responses via agentpay-mcp, enabling autonomous micropayment execution within configured spending limits.',\n source: 'managed',\n category: 'finance',\n },\n];\n\n// ─── Count ────────────────────────────────────────────────────────────────────\n\nexport const SKILLS_COUNT = SKILLS_CATALOG.length;\n","/**\n * ClawPowers Agent — Config Manager\n * CRUD for ~/.clawpowers/config.json with Zod validation.\n * T4 can never be set to \"auto\" — enforced at validation layer.\n */\n\nimport { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { z } from 'zod';\nimport { CONFIG_PATH, DEFAULT_CONFIG, RSI_TIER_ALLOWED_MODES } from './constants.js';\nimport type { ConfigFile } from './types.js';\n\n// ─── Zod Schemas ──────────────────────────────────────────────────────────────\n\nconst RSITierSchema = z.object({\n t1: z.enum(['auto', 'ask', 'off']),\n t2: z.enum(['auto', 'ask', 'off']),\n t3: z.enum(['auto', 'ask', 'off']),\n t4: z.enum(['ask', 'off']), // NO \"auto\" — safety invariant\n});\n\nconst RSIConfigSchema = z.object({\n enabled: z.boolean(),\n tiers: RSITierSchema,\n});\n\nconst PaymentConfigSchema = z.object({\n mode: z.enum(['human-first', 'auto', 'disabled']),\n dailyLimitUsd: z.number().min(0),\n weeklyLimitUsd: z.number().min(0),\n allowedDomains: z.array(z.string()),\n});\n\nconst LoggingConfigSchema = z.object({\n level: z.enum(['debug', 'info', 'warn', 'error']),\n retentionDays: z.number().min(1).max(365),\n});\n\nconst ConfigFileSchema = z.object({\n version: z.string(),\n profile: z.enum(['dev', 'lead', 'secure', 'growth', 'full']),\n rsi: RSIConfigSchema,\n payments: PaymentConfigSchema,\n logging: LoggingConfigSchema,\n skillsDir: z.string(),\n dataDir: z.string(),\n});\n\n// ─── Config Manager ───────────────────────────────────────────────────────────\n\nexport function loadConfig(configPath: string = CONFIG_PATH): ConfigFile {\n if (!existsSync(configPath)) {\n return DEFAULT_CONFIG;\n }\n const raw = readFileSync(configPath, 'utf-8');\n const parsed: unknown = JSON.parse(raw);\n return ConfigFileSchema.parse(parsed);\n}\n\n/**\n * Safe config loader — returns defaults if file is missing or invalid.\n * Used by CLI where crashing on stale config is bad UX.\n */\nexport function loadConfigSafe(configPath: string = CONFIG_PATH): ConfigFile {\n try {\n return loadConfig(configPath);\n } catch {\n return DEFAULT_CONFIG;\n }\n}\n\nexport function saveConfig(config: ConfigFile, configPath: string = CONFIG_PATH): void {\n const validated = ConfigFileSchema.parse(config);\n const dir = dirname(configPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n writeFileSync(configPath, JSON.stringify(validated, null, 2) + '\\n', 'utf-8');\n}\n\nexport function initConfig(configPath: string = CONFIG_PATH): ConfigFile {\n const config = DEFAULT_CONFIG;\n saveConfig(config, configPath);\n return config;\n}\n\n// ─── Dot-notation get/set ─────────────────────────────────────────────────────\n\n/**\n * Get a value from config using dot notation (e.g., \"rsi.tiers.t1\")\n */\nexport function getConfigValue(config: ConfigFile, key: string): unknown {\n const parts = key.split('.');\n let current: unknown = config;\n for (const part of parts) {\n if (current === null || current === undefined || typeof current !== 'object') {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/**\n * Set a value in config using dot notation. Returns the updated config.\n * Validates the entire config after the set to ensure consistency.\n * Throws on invalid values (e.g., T4 = \"auto\").\n */\nexport function setConfigValue(config: ConfigFile, key: string, value: string): ConfigFile {\n // Pre-validate RSI tier settings before deep set\n validateTierSetting(key, value);\n\n const parts = key.split('.');\n // Deep clone config to make it mutable\n const mutable = JSON.parse(JSON.stringify(config)) as Record<string, unknown>;\n\n let current: Record<string, unknown> = mutable;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (current[part] === undefined || typeof current[part] !== 'object') {\n throw new Error(`Invalid config path: ${key}`);\n }\n current = current[part] as Record<string, unknown>;\n }\n\n const lastKey = parts[parts.length - 1]!;\n if (!(lastKey in current)) {\n throw new Error(`Invalid config key: ${key}`);\n }\n\n // Coerce value types\n const coerced = coerceValue(current[lastKey], value);\n current[lastKey] = coerced;\n\n // Validate entire config through Zod\n return ConfigFileSchema.parse(mutable);\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction validateTierSetting(key: string, value: string): void {\n const tierMatch = key.match(/^rsi\\.tiers\\.(t[1-4])$/);\n if (tierMatch) {\n const tier = tierMatch[1] as keyof typeof RSI_TIER_ALLOWED_MODES;\n const allowed: readonly string[] = RSI_TIER_ALLOWED_MODES[tier];\n if (!allowed.includes(value)) {\n if (tier === 't4' && value === 'auto') {\n throw new Error(\n 'T4 (Architecture Proposals) cannot be set to \"auto\". ' +\n 'This is a safety invariant — T4 changes always require human approval. ' +\n 'Allowed modes: ask, off'\n );\n }\n throw new Error(\n `Invalid mode \"${value}\" for tier ${tier}. Allowed: ${allowed.join(', ')}`\n );\n }\n }\n}\n\nfunction coerceValue(existing: unknown, value: string): unknown {\n if (typeof existing === 'boolean') {\n if (value === 'true') return true;\n if (value === 'false') return false;\n throw new Error(`Expected boolean value (true/false), got \"${value}\"`);\n }\n if (typeof existing === 'number') {\n const num = Number(value);\n if (Number.isNaN(num)) {\n throw new Error(`Expected number value, got \"${value}\"`);\n }\n return num;\n }\n return value;\n}\n\n// ─── Exports for schema access ────────────────────────────────────────────────\n\nexport { ConfigFileSchema };\n","/**\n * ClawPowers Skills — Constants\n * Default paths, version, config values, RSI tier boundaries.\n */\n\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport type { ConfigFile, AgentStatus } from './types.js';\n\n// ─── Version ──────────────────────────────────────────────────────────────────\n\nexport const VERSION = '2.2.0';\nexport const PACKAGE_NAME = 'clawpowers';\n\n// ─── Paths ────────────────────────────────────────────────────────────────────\n\nexport const CLAWPOWERS_HOME = join(homedir(), '.clawpowers');\nexport const CONFIG_PATH = join(CLAWPOWERS_HOME, 'config.json');\nexport const SKILLS_DIR = join(CLAWPOWERS_HOME, 'skills');\nexport const DATA_DIR = join(CLAWPOWERS_HOME, 'data');\nexport const LOGS_DIR = join(CLAWPOWERS_HOME, 'logs');\nexport const MEMORY_DIR = join(CLAWPOWERS_HOME, 'memory');\nexport const METRICS_DIR = join(CLAWPOWERS_HOME, 'metrics');\nexport const PROFILES_DIR = join(CLAWPOWERS_HOME, 'profiles');\nexport const WALLET_DIR = join(CLAWPOWERS_HOME, 'wallet');\nexport const CHECKPOINTS_DIR = join(CLAWPOWERS_HOME, 'state', 'checkpoints');\n\n// ─── Default Config ───────────────────────────────────────────────────────────\n\nexport const DEFAULT_CONFIG: ConfigFile = {\n version: VERSION,\n profile: 'dev',\n rsi: {\n enabled: true,\n tiers: {\n t1: 'auto',\n t2: 'auto',\n t3: 'ask',\n t4: 'ask',\n },\n },\n payments: {\n mode: 'human-first',\n dailyLimitUsd: 25,\n weeklyLimitUsd: 100,\n allowedDomains: [],\n },\n logging: {\n level: 'info',\n retentionDays: 30,\n },\n skillsDir: SKILLS_DIR,\n dataDir: DATA_DIR,\n} as const;\n\n// ─── RSI Tier Definitions ─────────────────────────────────────────────────────\n\nexport const RSI_TIER_DESCRIPTIONS = {\n t1: 'Parameter Tuning — model params, retry counts, timeouts, thresholds',\n t2: 'Strategy Evolution — skill selection order, fallback chains, execution strategies',\n t3: 'Skill Composition — create new skill chains from existing skills',\n t4: 'Architecture Proposals — structural changes, human approval required',\n} as const;\n\n/**\n * Modes allowed per tier. T4 NEVER allows \"auto\" — this is a safety invariant.\n */\nexport const RSI_TIER_ALLOWED_MODES = {\n t1: ['auto', 'ask', 'off'] as const,\n t2: ['auto', 'ask', 'off'] as const,\n t3: ['auto', 'ask', 'off'] as const,\n t4: ['ask', 'off'] as const,\n} as const;\n\n// ─── Safety Invariants (NEVER modifiable by RSI) ──────────────────────────────\n\nexport const SAFETY_INVARIANTS = [\n 'Spending limits and SpendingPolicy',\n 'Core identity and directives',\n 'RSI safety tier definitions',\n 'Sandbox boundaries',\n 'Authentication credentials',\n] as const;\n\n// ─── Agent State Machine ──────────────────────────────────────────────────────\n\n/**\n * Valid state transitions. Maps each status to the set of statuses it can\n * transition to. Retained for checkpoint compatibility.\n */\nexport const VALID_TRANSITIONS: Record<AgentStatus, readonly AgentStatus[]> = {\n idle: ['intake'],\n intake: ['planning', 'failed'],\n planning: ['executing', 'failed'],\n executing: ['reviewing', 'failed', 'paused'],\n reviewing: ['complete', 'failed', 'executing'],\n complete: ['idle'],\n failed: ['idle'],\n paused: ['executing', 'idle'],\n} as const;\n\n// ─── Performance Targets ──────────────────────────────────────────────────────\n\nexport const PERFORMANCE = {\n coldStartupMs: 2000,\n maxMemoryRssMb: 150,\n maxContextTokens: 2000,\n checkpointWriteMs: 100,\n episodicSearchMs: 50,\n profileSwitchMs: 500,\n healthCheckIntervalMs: 30000,\n maxRetries: 3,\n} as const;\n","/**\n * 3-Tier Native Module Loader\n *\n * Loading precedence:\n * 1. Native .node addon (fastest — napi-rs compiled Rust)\n * 2. WASM module (portable — wasm-pack compiled Rust)\n * 3. Pure TypeScript fallback (universal — no Rust toolchain needed)\n *\n * The active tier is exposed via `getActiveTier()`.\n */\nimport { createRequire } from 'node:module';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst require = createRequire(import.meta.url);\n\n// ─── Types matching FFI exports from lib.rs ───────────────────────────────────\n\nexport interface NativeWallet {\n address(): string;\n signMessage(msg: Buffer): string;\n}\nexport interface NativeWalletConstructor {\n generate(): NativeWallet;\n fromPrivateKey(hex: string): NativeWallet;\n}\n\nexport interface NativeFeeSchedule {\n calculate(amount: number, decimals: number, feeType: string): string;\n}\nexport interface NativeFeeScheduleConstructor {\n withDefaults(): NativeFeeSchedule;\n new(txBps: number, swapBps: number, recipientHex: string): NativeFeeSchedule;\n}\n\nexport interface NativeX402Client {\n createPaymentHeader(paymentJson: string, signature: string): string;\n}\nexport interface NativeX402ClientConstructor {\n new(): NativeX402Client;\n}\n\nexport interface NativeCanonicalStore {\n insert(recordJson: string): string;\n get(id: string): string | null;\n verifyIntegrity(id: string): boolean;\n}\nexport interface NativeCanonicalStoreConstructor {\n open(path: string): NativeCanonicalStore;\n inMemory(): NativeCanonicalStore;\n}\n\nexport interface NativeTurboCompressor {\n compress(vector: Float32Array): string;\n decompress(compressedJson: string): Float32Array;\n}\nexport interface NativeTurboCompressorConstructor {\n new(dimensions: number, bits: number): NativeTurboCompressor;\n}\n\nexport interface NativeWriteFirewall {\n evaluate(requestJson: string): string;\n}\nexport interface NativeWriteFirewallConstructor {\n new(configJson: string): NativeWriteFirewall;\n}\n\nexport interface NativeModule {\n JsAgentWallet: NativeWalletConstructor;\n JsFeeSchedule: NativeFeeScheduleConstructor;\n JsX402Client: NativeX402ClientConstructor;\n JsCanonicalStore: NativeCanonicalStoreConstructor;\n JsTurboCompressor: NativeTurboCompressorConstructor;\n JsWriteFirewall: NativeWriteFirewallConstructor;\n /** Present when `clawpowers-ffi` was built with keccak helper (ClawPowers-Skills ≥2.1.0). */\n keccak256Bytes?: (data: Buffer) => string;\n /** secp256k1 + Keccak address (ClawPowers-Skills ≥2.2.0). */\n deriveEthereumAddress?: (privateKey: Buffer) => string;\n derivePublicKey?: (privateKey: Buffer) => Buffer;\n signEcdsa?: (privateKey: Buffer, messageHash: Buffer) => Buffer;\n verifyEcdsa?: (publicKey: Buffer, messageHash: Buffer, signature: Buffer) => boolean;\n}\n\n// ─── WASM Module Types ───────────────────────────────────────────────────────\n\nexport interface WasmModule {\n // Tokens\n tokenAmountFromHuman(human: number, decimals: number): string;\n tokenAmountToHuman(json: string): number;\n tokenAmountAdd(aJson: string, bJson: string): string;\n tokenAmountSub(aJson: string, bJson: string): string;\n tokenAmountMulBps(json: string, bps: bigint): string;\n getDefaultTokenRegistry(): string;\n\n // Fee\n calculateFee(\n amountJson: string,\n feeType: string,\n txFeeBps?: bigint,\n swapFeeBps?: bigint,\n ): string;\n\n // Compression\n compressVector(vectorJson: string, dimensions: number): string;\n decompressVector(compressedJson: string, dimensions: number): string;\n approximateDistance(aJson: string, bJson: string, dimensions: number): number;\n\n // Canonical\n WasmCanonicalStore: {\n new(): WasmCanonicalStoreInstance;\n };\n\n // Security\n evaluateWriteFirewall(json: string): string;\n\n // Hashing\n computeSha256(content: string): string;\n /** Keccak-256 over raw bytes (`0x` + 64 hex). Present in wasm builds from ClawPowers-Skills ≥2.1.0. */\n computeKeccak256?(bytes: Uint8Array): string;\n\n /** secp256k1 Ethereum address (ClawPowers-Skills ≥2.2.0). */\n deriveEthereumAddress?(privateKey: Uint8Array): string;\n derivePublicKey?(privateKey: Uint8Array): Uint8Array;\n signEcdsa?(privateKey: Uint8Array, messageHash: Uint8Array): Uint8Array;\n verifyEcdsa?(publicKey: Uint8Array, messageHash: Uint8Array, signature: Uint8Array): boolean;\n\n // Info\n getVersion(): string;\n getAvailableModules(): string;\n}\n\nexport interface WasmCanonicalStoreInstance {\n insert(json: string): string;\n get(id: string): string | null;\n getByHash(hash: string): string | null;\n queryNamespace(namespace: string, limit: number): string;\n softDelete(id: string): boolean;\n verifyIntegrity(id: string): boolean;\n exportJson(): string;\n importJson(json: string): number;\n}\n\n// ─── Active Tier ─────────────────────────────────────────────────────────────\n\nexport type LoadTier = 'native' | 'wasm' | 'typescript';\n\nlet _native: NativeModule | null = null;\nlet _wasm: WasmModule | null = null;\nlet _activeTier: LoadTier = 'typescript';\nlet _attempted = false;\n\n// ─── Tier 1: Native .node addon ──────────────────────────────────────────────\n\nfunction tryLoadNative(): NativeModule | null {\n const candidates = [\n join(__dirname, '../../native/ffi/index.node'),\n join(__dirname, '../../native/ffi/clawpowers_ffi.node'),\n join(__dirname, '../../../native/ffi/index.node'),\n join(__dirname, '../../../native/ffi/clawpowers_ffi.node'),\n join(__dirname, '../native/ffi/index.node'),\n join(__dirname, '../native/ffi/clawpowers_ffi.node'),\n ];\n\n for (const p of candidates) {\n try {\n const mod = require(p) as NativeModule;\n console.log(`[clawpowers] Tier 1: Native acceleration enabled (${p})`);\n return mod;\n } catch {\n // Continue\n }\n }\n return null;\n}\n\n// ─── Tier 2: WASM module ─────────────────────────────────────────────────────\n\nfunction tryLoadWasm(): WasmModule | null {\n // Try Node.js WASM package first (dist/index.js → ../native/...; src/native/*.ts → ../../native/...)\n const wasmCandidates = [\n join(__dirname, '../native/wasm/pkg-node/clawpowers_wasm.js'),\n join(__dirname, '../native/wasm/pkg/clawpowers_wasm.js'),\n join(__dirname, '../../native/wasm/pkg-node/clawpowers_wasm.js'),\n join(__dirname, '../../native/wasm/pkg/clawpowers_wasm.js'),\n ];\n\n for (const p of wasmCandidates) {\n try {\n const mod = require(p) as WasmModule;\n console.log(`[clawpowers] Tier 2: WASM module loaded (${p})`);\n return mod;\n } catch {\n // Continue\n }\n }\n return null;\n}\n\n// ─── Combined Loader ─────────────────────────────────────────────────────────\n\nfunction loadAll(): void {\n if (_attempted) return;\n _attempted = true;\n\n // Tier 1: Try native (primary tier for getActiveTier())\n _native = tryLoadNative();\n if (_native) {\n _activeTier = 'native';\n // Still load WASM when present: native builds may omit newer exports (e.g. secp256k1)\n // while prebuilt WASM provides them. Helpers try native first, then WASM.\n _wasm = tryLoadWasm();\n return;\n }\n\n // Tier 2: WASM only\n _wasm = tryLoadWasm();\n if (_wasm) {\n _activeTier = 'wasm';\n return;\n }\n\n // Tier 3: TypeScript fallback\n _activeTier = 'typescript';\n console.log('[clawpowers] Tier 3: TypeScript fallback active (no native or WASM)');\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Get the native .node module, or null if unavailable.\n */\nexport function getNative(): NativeModule | null {\n loadAll();\n return _native;\n}\n\n/**\n * Get the WASM module, or null if unavailable.\n */\nexport function getWasm(): WasmModule | null {\n loadAll();\n return _wasm;\n}\n\n/**\n * Returns true if the native Rust addon was loaded successfully.\n */\nexport function isNativeAvailable(): boolean {\n loadAll();\n return _native !== null;\n}\n\n/**\n * Returns true if the WASM module was loaded successfully.\n */\nexport function isWasmAvailable(): boolean {\n loadAll();\n return _wasm !== null;\n}\n\n/**\n * Returns the active loading tier.\n */\nexport function getActiveTier(): LoadTier {\n loadAll();\n return _activeTier;\n}\n\n/**\n * Returns a summary of available modules per tier.\n */\nexport function getCapabilitySummary(): {\n tier: LoadTier;\n nativeModules: string[];\n wasmModules: string[];\n typescriptFallback: string[];\n} {\n loadAll();\n\n const nativeModules = _native\n ? ['wallet', 'fee', 'x402', 'canonical', 'compression', 'verification', 'security']\n : [];\n\n let wasmModules: string[] = [];\n if (_wasm) {\n try {\n wasmModules = JSON.parse(_wasm.getAvailableModules());\n } catch {\n wasmModules = ['tokens', 'fee', 'compression', 'canonical', 'verification', 'security', 'index'];\n }\n }\n\n // These always have TS implementations\n const typescriptFallback = [\n 'wallet', // ethers.js / viem\n 'x402', // fetch()-based HTTP client\n 'tokens', // Pure TS decimal math\n 'fee', // Pure TS fee calculation\n 'policy', // Pure TS policy engine\n ];\n\n return {\n tier: _activeTier,\n nativeModules,\n wasmModules,\n typescriptFallback,\n };\n}\n\n// ─── Unified Operation Helpers ───────────────────────────────────────────────\n// These route to the best available backend automatically.\n\n/**\n * Compute SHA-256 hash, using the fastest available backend.\n */\nexport function computeSha256(content: string): string {\n loadAll();\n\n // Try WASM\n if (_wasm) {\n return _wasm.computeSha256(content);\n }\n\n // TypeScript fallback using Node.js crypto\n const { createHash } = require('node:crypto');\n return createHash('sha256').update(content).digest('hex');\n}\n\n/**\n * 32-byte digest as `0x` + 64 hex chars for wallet address derivation (last 20 bytes used as address).\n *\n * Tier 1: native `keccak256Bytes` when the `.node` addon includes it (custom `cargo build` of ffi).\n * Tier 2: WASM `computeKeccak256` (pre-built `pkg-node` ships with the npm package).\n * Tier 3: SHA-256 via Node.js `crypto` (legacy; use native/WASM for keccak256 parity).\n */\nexport function digestForWalletAddress(keyMaterial: Buffer): string {\n loadAll();\n\n if (_native && typeof _native.keccak256Bytes === 'function') {\n try {\n return _native.keccak256Bytes(keyMaterial);\n } catch {\n // fall through\n }\n }\n\n if (_wasm && typeof _wasm.computeKeccak256 === 'function') {\n try {\n return _wasm.computeKeccak256(new Uint8Array(keyMaterial));\n } catch {\n // fall through\n }\n }\n\n const { createHash } = require('node:crypto') as typeof import('node:crypto');\n return '0x' + createHash('sha256').update(keyMaterial).digest('hex');\n}\n\n/**\n * Keccak-256 digest of raw bytes as a 32-byte `Buffer`.\n * Tier 1: native `keccak256Bytes`; Tier 2: WASM `computeKeccak256`; Tier 3: `null`.\n */\nexport function keccak256Digest(data: Buffer): Buffer | null {\n loadAll();\n\n if (_native && typeof _native.keccak256Bytes === 'function') {\n try {\n const hex = _native.keccak256Bytes(data);\n return Buffer.from(hex.replace(/^0x/i, ''), 'hex');\n } catch {\n // fall through\n }\n }\n\n if (_wasm && typeof _wasm.computeKeccak256 === 'function') {\n try {\n const hex = _wasm.computeKeccak256(new Uint8Array(data));\n return Buffer.from(hex.replace(/^0x/i, ''), 'hex');\n } catch {\n // fall through\n }\n }\n\n return null;\n}\n\n/**\n * Ethereum address from 32-byte secp256k1 private key (EIP-55). Tier 1 → Tier 2 → `null`.\n */\nexport function deriveEthereumAddress(privateKey: Buffer): string | null {\n loadAll();\n\n if (_native && typeof _native.deriveEthereumAddress === 'function') {\n try {\n return _native.deriveEthereumAddress(privateKey);\n } catch {\n // fall through\n }\n }\n\n if (_wasm && typeof _wasm.deriveEthereumAddress === 'function') {\n try {\n return _wasm.deriveEthereumAddress(new Uint8Array(privateKey));\n } catch {\n // fall through\n }\n }\n\n return null;\n}\n\n/**\n * Uncompressed public key (64 bytes, no `0x04` prefix). Tier 1 → Tier 2 → `null`.\n */\nexport function derivePublicKey(privateKey: Buffer): Buffer | null {\n loadAll();\n\n if (_native && typeof _native.derivePublicKey === 'function') {\n try {\n return Buffer.from(_native.derivePublicKey(privateKey));\n } catch {\n // fall through\n }\n }\n\n if (_wasm && typeof _wasm.derivePublicKey === 'function') {\n try {\n return Buffer.from(_wasm.derivePublicKey(new Uint8Array(privateKey)));\n } catch {\n // fall through\n }\n }\n\n return null;\n}\n\n/**\n * ECDSA sign a 32-byte message hash (65 bytes: r‖s‖recovery_id). Tier 1 → Tier 2 → `null`.\n */\nexport function signEcdsa(privateKey: Buffer, messageHash: Buffer): Buffer | null {\n loadAll();\n\n if (_native && typeof _native.signEcdsa === 'function') {\n try {\n return Buffer.from(_native.signEcdsa(privateKey, messageHash));\n } catch {\n // fall through\n }\n }\n\n if (_wasm && typeof _wasm.signEcdsa === 'function') {\n try {\n return Buffer.from(_wasm.signEcdsa(new Uint8Array(privateKey), new Uint8Array(messageHash)));\n } catch {\n // fall through\n }\n }\n\n return null;\n}\n\n/**\n * Verify ECDSA over a 32-byte prehash. Tier 1 → Tier 2; otherwise `false`.\n */\nexport function verifyEcdsa(\n publicKey: Buffer,\n messageHash: Buffer,\n signature: Buffer,\n): boolean {\n loadAll();\n\n try {\n if (_native && typeof _native.verifyEcdsa === 'function') {\n return _native.verifyEcdsa(publicKey, messageHash, signature);\n }\n if (_wasm && typeof _wasm.verifyEcdsa === 'function') {\n return _wasm.verifyEcdsa(\n new Uint8Array(publicKey),\n new Uint8Array(messageHash),\n new Uint8Array(signature),\n );\n }\n } catch {\n return false;\n }\n return false;\n}\n\n/**\n * Create a token amount from a human-readable number.\n * Routes to WASM if available, otherwise pure TypeScript.\n */\nexport function tokenAmountFromHuman(\n human: number,\n decimals: number,\n): { raw: string; decimals: number } {\n loadAll();\n\n if (_wasm) {\n return JSON.parse(_wasm.tokenAmountFromHuman(human, decimals));\n }\n\n // TypeScript fallback\n const multiplier = Math.pow(10, decimals);\n const raw = Math.floor(human * multiplier);\n return { raw: raw.toString(), decimals };\n}\n\n/**\n * Calculate a fee, routing to the best available backend.\n */\nexport function calculateFee(\n amountHuman: number,\n decimals: number,\n feeType: 'transaction' | 'swap' | string,\n txFeeBps?: number,\n swapFeeBps?: number,\n): { gross_amount: number; fee_amount: number; net_amount: number } {\n loadAll();\n\n if (_wasm) {\n const amountJson = _wasm.tokenAmountFromHuman(amountHuman, decimals);\n const result = _wasm.calculateFee(\n amountJson,\n feeType,\n txFeeBps !== undefined ? BigInt(txFeeBps) : undefined,\n swapFeeBps !== undefined ? BigInt(swapFeeBps) : undefined,\n );\n return JSON.parse(result);\n }\n\n // TypeScript fallback\n const bps =\n feeType === 'transaction'\n ? (txFeeBps ?? 77)\n : feeType === 'swap'\n ? (swapFeeBps ?? 30)\n : parseInt(feeType.replace('custom:', ''), 10) || 0;\n\n const feeAmount = (amountHuman * bps) / 10_000;\n return {\n gross_amount: amountHuman,\n fee_amount: feeAmount,\n net_amount: amountHuman - feeAmount,\n };\n}\n\n/**\n * Evaluate a write request against the security firewall.\n * Routes to WASM if available, otherwise TypeScript.\n */\nexport function evaluateWriteFirewall(request: {\n namespace: string;\n content: string;\n trust_level: string;\n source: string;\n allowed_namespaces?: string[];\n blocked_patterns?: string[];\n max_content_length?: number;\n}): { decision: 'allow' | 'deny' | 'sanitize'; reason?: string; sanitized?: string } {\n loadAll();\n\n if (_wasm) {\n return JSON.parse(_wasm.evaluateWriteFirewall(JSON.stringify(request)));\n }\n\n // TypeScript fallback — basic security checks\n if (\n request.allowed_namespaces &&\n request.allowed_namespaces.length > 0 &&\n !request.allowed_namespaces.includes(request.namespace)\n ) {\n return {\n decision: 'deny',\n reason: `namespace '${request.namespace}' is not in the allow-list`,\n };\n }\n\n const maxLen = request.max_content_length ?? 1024 * 1024;\n if (request.content.length > maxLen) {\n return {\n decision: 'deny',\n reason: `content length ${request.content.length} exceeds maximum ${maxLen}`,\n };\n }\n\n if (request.blocked_patterns) {\n for (const pattern of request.blocked_patterns) {\n if (request.content.includes(pattern)) {\n if (request.trust_level === 'system' || request.trust_level === 'agent') {\n return {\n decision: 'deny',\n reason: `content contains blocked pattern '${pattern}'`,\n };\n }\n return {\n decision: 'sanitize',\n sanitized: request.content.replaceAll(pattern, ''),\n };\n }\n }\n }\n\n return { decision: 'allow' };\n}\n","/**\n * ClawPowers Agent — Payment Discovery\n * Detects HTTP 402 Payment Required responses and parses x402 headers.\n */\n\nimport type { PaymentRequired } from '../types.js';\n\nconst REQUIRED_HEADERS = [\n 'x-payment-amount',\n 'x-payment-currency',\n 'x-payment-recipient',\n 'x-payment-network',\n] as const;\n\ninterface HttpResponse {\n readonly status: number;\n readonly headers: Readonly<Record<string, string>>;\n}\n\n/**\n * Detect a 402 Payment Required response and extract payment details from x402 headers.\n * Returns null if the response is not a 402 or if required headers are missing.\n */\nexport function detect402(response: HttpResponse): PaymentRequired | null {\n if (response.status !== 402) {\n return null;\n }\n\n // Normalize header keys to lowercase for case-insensitive matching\n const normalizedHeaders: Record<string, string> = {};\n for (const [key, value] of Object.entries(response.headers)) {\n normalizedHeaders[key.toLowerCase()] = value;\n }\n\n // Check all required headers are present\n for (const header of REQUIRED_HEADERS) {\n if (!normalizedHeaders[header] || normalizedHeaders[header].trim() === '') {\n return null;\n }\n }\n\n const amountStr = normalizedHeaders['x-payment-amount']!;\n const amount = Number(amountStr);\n\n if (Number.isNaN(amount) || amount <= 0) {\n return null;\n }\n\n // Collect all x-payment headers for passthrough\n const x402Headers: Record<string, string> = {};\n for (const [key, value] of Object.entries(normalizedHeaders)) {\n if (key.startsWith('x-payment-')) {\n x402Headers[key] = value;\n }\n }\n\n return {\n amount,\n currency: normalizedHeaders['x-payment-currency']!,\n recipient: normalizedHeaders['x-payment-recipient']!,\n network: normalizedHeaders['x-payment-network']!,\n x402Headers,\n };\n}\n\n/**\n * Type guard to check if an error represents a 402 Payment Required response.\n */\nexport function isPaymentRequired(error: unknown): boolean {\n if (error === null || error === undefined) return false;\n\n if (typeof error === 'object') {\n const obj = error as Record<string, unknown>;\n\n // Check for status property\n if ('status' in obj && obj['status'] === 402) return true;\n\n // Check for statusCode property\n if ('statusCode' in obj && obj['statusCode'] === 402) return true;\n\n // Check for response.status\n if ('response' in obj && typeof obj['response'] === 'object' && obj['response'] !== null) {\n const response = obj['response'] as Record<string, unknown>;\n if ('status' in response && response['status'] === 402) return true;\n }\n\n // Check for message containing 402\n if ('message' in obj && typeof obj['message'] === 'string' && obj['message'].includes('402')) {\n return true;\n }\n }\n\n return false;\n}\n","/**\n * ClawPowers Agent — Spending Policy\n * Enforces daily limits, per-transaction limits, and domain allowlists.\n * Fail-closed: any policy error results in rejection.\n */\n\nimport type { SpendingDecision } from '../types.js';\n\ninterface SpendingRecord {\n amount: number;\n timestamp: number;\n domain: string;\n}\n\n/**\n * Get the start of the current UTC day as a timestamp.\n */\nfunction getUtcDayStart(): number {\n const now = new Date();\n const utcStart = new Date(Date.UTC(\n now.getUTCFullYear(),\n now.getUTCMonth(),\n now.getUTCDate(),\n 0, 0, 0, 0\n ));\n return utcStart.getTime();\n}\n\nexport class SpendingPolicy {\n readonly dailyLimit: number;\n readonly transactionLimit: number;\n readonly allowedDomains: readonly string[];\n\n private spendingLog: SpendingRecord[] = [];\n\n constructor(options: {\n dailyLimit: number;\n transactionLimit: number;\n allowedDomains: readonly string[];\n }) {\n this.dailyLimit = options.dailyLimit;\n this.transactionLimit = options.transactionLimit;\n this.allowedDomains = options.allowedDomains;\n }\n\n /**\n * Get total spending for the current UTC day.\n */\n getDailySpent(): number {\n const dayStart = getUtcDayStart();\n return this.spendingLog\n .filter(r => r.timestamp >= dayStart)\n .reduce((sum, r) => sum + r.amount, 0);\n }\n\n /**\n * Check whether a transaction is allowed under the current policy.\n * Fail-closed: any validation error results in rejection.\n */\n checkTransaction(amount: number, domain: string): SpendingDecision {\n try {\n // Validate amount\n if (amount <= 0 || !Number.isFinite(amount)) {\n return {\n allowed: false,\n reason: `Invalid amount: ${amount}`,\n remainingDaily: this.dailyLimit - this.getDailySpent(),\n };\n }\n\n // Check per-transaction limit\n if (amount > this.transactionLimit) {\n return {\n allowed: false,\n reason: `Amount $${amount} exceeds per-transaction limit of $${this.transactionLimit}`,\n remainingDaily: this.dailyLimit - this.getDailySpent(),\n };\n }\n\n // Check domain allowlist (if allowlist is non-empty)\n if (this.allowedDomains.length > 0) {\n const normalizedDomain = domain.toLowerCase();\n const isAllowed = this.allowedDomains.some(\n d => d.toLowerCase() === normalizedDomain\n );\n if (!isAllowed) {\n return {\n allowed: false,\n reason: `Domain \"${domain}\" is not in the allowed domains list`,\n remainingDaily: this.dailyLimit - this.getDailySpent(),\n };\n }\n }\n\n // Check daily limit\n const dailySpent = this.getDailySpent();\n if (dailySpent + amount > this.dailyLimit) {\n return {\n allowed: false,\n reason: `Transaction of $${amount} would exceed daily limit of $${this.dailyLimit} (already spent: $${dailySpent})`,\n remainingDaily: this.dailyLimit - dailySpent,\n };\n }\n\n return {\n allowed: true,\n reason: 'Transaction approved',\n remainingDaily: this.dailyLimit - dailySpent - amount,\n };\n } catch {\n // Fail-closed: any unexpected error = reject\n return {\n allowed: false,\n reason: 'Policy check failed due to internal error — rejecting for safety',\n remainingDaily: 0,\n };\n }\n }\n\n /**\n * Record a completed spending transaction.\n */\n recordSpend(amount: number, domain: string): void {\n this.spendingLog.push({\n amount,\n timestamp: Date.now(),\n domain,\n });\n }\n\n /**\n * Reset all spending records (used for testing).\n */\n reset(): void {\n this.spendingLog = [];\n }\n\n /**\n * Get the full spending log (for audit purposes).\n */\n getSpendingLog(): readonly SpendingRecord[] {\n return [...this.spendingLog];\n }\n}\n","/**\n * ClawPowers Agent — Payment Executor\n * Executes payments via agentpay-mcp with spending policy enforcement.\n * Never auto-retries failed payments (financial safety).\n */\n\nimport type {\n PaymentRequest,\n PaymentResult,\n PaymentAuditEntry,\n} from '../types.js';\nimport { SpendingPolicy } from './spending.js';\n\n/**\n * Interface for an MCP payment client.\n * In production, this wraps agentpay-mcp; in tests, it can be substituted.\n */\nexport interface MCPPaymentClient {\n executePayment(params: {\n amount: number;\n currency: string;\n recipient: string;\n x402Headers: Readonly<Record<string, string>>;\n }): Promise<{ txHash: string; status: 'success' | 'failed' }>;\n}\n\n/**\n * Payment executor that enforces spending policy and logs all attempts.\n */\nexport class PaymentExecutor {\n private readonly policy: SpendingPolicy;\n private readonly client: MCPPaymentClient;\n private readonly auditLog: PaymentAuditEntry[] = [];\n\n constructor(policy: SpendingPolicy, client: MCPPaymentClient) {\n this.policy = policy;\n this.client = client;\n }\n\n /**\n * Execute a payment request.\n * 1. Check spending policy\n * 2. If allowed, execute via MCP client\n * 3. Log the result (success or failure)\n * 4. Never auto-retry on failure\n */\n async executePayment(request: PaymentRequest): Promise<PaymentResult> {\n // Step 1: Check spending policy\n const decision = this.policy.checkTransaction(request.amount, request.domain);\n\n if (!decision.allowed) {\n const result: PaymentResult = {\n success: false,\n error: `Spending policy rejected: ${decision.reason}`,\n };\n\n this.logAudit(request, result);\n return result;\n }\n\n // Step 2: Execute payment via MCP client\n try {\n const mcpResult = await this.client.executePayment({\n amount: request.amount,\n currency: request.currency,\n recipient: request.recipient,\n x402Headers: request.x402Headers,\n });\n\n if (mcpResult.status === 'success') {\n // Record successful spend\n this.policy.recordSpend(request.amount, request.domain);\n\n const result: PaymentResult = {\n success: true,\n txHash: mcpResult.txHash,\n };\n\n this.logAudit(request, result);\n return result;\n }\n\n // MCP returned failure status\n const result: PaymentResult = {\n success: false,\n error: 'Payment execution failed at MCP layer',\n };\n\n this.logAudit(request, result);\n return result;\n } catch (err: unknown) {\n // Execution error — DO NOT retry (financial safety)\n const errorMessage = err instanceof Error ? err.message : String(err);\n const result: PaymentResult = {\n success: false,\n error: `Payment execution error: ${errorMessage}`,\n };\n\n this.logAudit(request, result);\n return result;\n }\n }\n\n /**\n * Get the full payment audit log.\n */\n getAuditLog(): readonly PaymentAuditEntry[] {\n return [...this.auditLog];\n }\n\n /**\n * Log a payment attempt to the audit trail.\n */\n private logAudit(request: PaymentRequest, result: PaymentResult): void {\n this.auditLog.push({\n timestamp: new Date().toISOString(),\n request,\n result,\n spendingSnapshot: {\n dailySpent: this.policy.getDailySpent(),\n dailyLimit: this.policy.dailyLimit,\n },\n });\n }\n}\n","/**\n * Native acceleration bridge for payments.\n *\n * Tier 1: Native Rust .node addon (fastest — napi-rs compiled)\n * Tier 2: WASM module (portable — wasm-pack compiled)\n * Tier 3: Pure TypeScript fallback (universal)\n *\n * Note: x402 remains native/TypeScript only, but wallet address derivation is\n * available in both Tier 1 native and Tier 2 WASM via the shared secp256k1 +\n * Keccak implementation in src/native/index.ts.\n */\nimport { randomBytes } from 'node:crypto';\nimport {\n calculateFee as wasmCalculateFee,\n deriveEthereumAddress,\n getNative,\n getWasm,\n} from '../native/index.js';\n\nexport interface FeeCalculation {\n gross: number;\n fee: number;\n net: number;\n feeRecipient: string;\n}\n\n/**\n * Calculate transaction fee using the best available backend.\n *\n * Tier 1: Native Rust fee crate (JsFeeSchedule.withDefaults, 77 bps)\n * Tier 2: WASM fee crate (calculateFee via index.ts helper)\n * Tier 3: Pure TypeScript 77 bps calculation\n */\nexport function calculateTransactionFee(\n amount: number,\n decimals: number = 6,\n): FeeCalculation {\n // Tier 1: Native\n const native = getNative();\n if (native) {\n try {\n const schedule = native.JsFeeSchedule.withDefaults();\n const raw = JSON.parse(schedule.calculate(amount, decimals, 'transaction')) as Record<string, unknown>;\n return {\n gross: raw.gross as number,\n fee: raw.fee as number,\n net: raw.net as number,\n feeRecipient: (raw.feeRecipient ?? raw.fee_recipient ?? '0x0000000000000000000000000000000000000000') as string,\n };\n } catch {\n // Fall through to Tier 2\n }\n }\n\n // Tier 2: WASM (via the unified helper in native/index.ts)\n const wasm = getWasm();\n if (wasm) {\n try {\n const result = wasmCalculateFee(amount, decimals, 'transaction');\n return {\n gross: result.gross_amount,\n fee: result.fee_amount,\n net: result.net_amount,\n feeRecipient: '0x0000000000000000000000000000000000000000',\n };\n } catch {\n // Fall through to Tier 3\n }\n }\n\n // Tier 3: TypeScript fallback — 77 bps\n const fee = amount * 0.0077;\n return {\n gross: amount,\n fee,\n net: amount - fee,\n feeRecipient: '0x0000000000000000000000000000000000000000',\n };\n}\n\n/**\n * Build an X-Payment header.\n *\n * Tier 1: Native Rust x402 crate (JsX402Client)\n * Tier 2: Not available in WASM (wallet/x402 excluded from wasm crate)\n * Tier 3: Base64-encoded JSON representation\n */\nexport function createPaymentHeader(paymentJson: string, signature: string): string {\n // Tier 1: Native\n const native = getNative();\n if (native) {\n try {\n const client = new native.JsX402Client();\n return client.createPaymentHeader(paymentJson, signature);\n } catch {\n // Fall through to Tier 3 (WASM does not expose x402)\n }\n }\n\n // Tier 3: TypeScript fallback (x402 excluded from WASM build)\n return Buffer.from(JSON.stringify({ payment: JSON.parse(paymentJson), signature })).toString('base64');\n}\n\n/**\n * Generate a new EVM agent wallet address.\n *\n * Tier 1: Native Rust wallet crate (JsAgentWallet.generate)\n * Tier 2: WASM secp256k1 + Keccak derivation via the shared loader\n * Tier 3: throws, because returning a fake zero address would be misleading\n */\nexport function generateWalletAddress(): string {\n // Tier 1: Native\n const native = getNative();\n if (native) {\n try {\n return native.JsAgentWallet.generate().address();\n } catch {\n // Fall through to shared loader path\n }\n }\n\n const address = deriveEthereumAddress(randomBytes(32));\n if (address) {\n return address;\n }\n\n throw new Error(\n 'Unable to derive a real Ethereum address. Native or WASM wallet support is required for generateWalletAddress().'\n );\n}\n","/**\n * ClawPowers Agent — Working Memory Manager\n * In-process working memory with token budget enforcement.\n */\n\nimport type { Goal, Plan, WorkingMemory } from '../types.js';\nimport { PERFORMANCE } from '../constants.js';\n\n/**\n * Estimate token count from text using simple approximation.\n */\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\nexport class WorkingMemoryManager {\n private memory: WorkingMemory | null = null;\n\n create(taskId: string, goal: Goal): WorkingMemory {\n const emptyPlan: Plan = {\n taskId,\n steps: [],\n status: 'draft',\n createdAt: new Date().toISOString(),\n approvedAt: null,\n parallelizable: false,\n };\n\n this.memory = {\n taskId,\n goal,\n plan: emptyPlan,\n currentStepId: null,\n intermediateOutputs: {},\n contextWindow: [],\n };\n\n return this.memory;\n }\n\n updateCurrentStep(stepId: string): void {\n if (!this.memory) {\n throw new Error('Working memory not initialized. Call create() first.');\n }\n this.memory = {\n ...this.memory,\n currentStepId: stepId,\n };\n }\n\n addIntermediateOutput(stepId: string, output: string): void {\n if (!this.memory) {\n throw new Error('Working memory not initialized. Call create() first.');\n }\n this.memory = {\n ...this.memory,\n intermediateOutputs: {\n ...this.memory.intermediateOutputs,\n [stepId]: output,\n },\n };\n }\n\n /**\n * Inject context entries into working memory, enforcing token budget.\n * Entries are added until the budget is exhausted, then truncated.\n */\n injectContext(entries: readonly string[]): void {\n if (!this.memory) {\n throw new Error('Working memory not initialized. Call create() first.');\n }\n\n const maxTokens = PERFORMANCE.maxContextTokens;\n const injected: string[] = [];\n let totalTokens = 0;\n\n for (const entry of entries) {\n const entryTokens = estimateTokens(entry);\n if (totalTokens + entryTokens > maxTokens) {\n // Try to fit a truncated version\n const remainingTokens = maxTokens - totalTokens;\n if (remainingTokens > 10) {\n const truncatedLength = remainingTokens * 4;\n injected.push(entry.slice(0, truncatedLength) + '...');\n }\n break;\n }\n totalTokens += entryTokens;\n injected.push(entry);\n }\n\n this.memory = {\n ...this.memory,\n contextWindow: injected,\n };\n }\n\n getSnapshot(): WorkingMemory {\n if (!this.memory) {\n throw new Error('Working memory not initialized. Call create() first.');\n }\n return this.memory;\n }\n\n clear(): void {\n this.memory = null;\n }\n}\n","/**\n * ClawPowers Agent — Episodic Memory\n * JSONL append-only storage for task episodes.\n */\n\nimport { readFile, appendFile, writeFile, mkdir } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { EpisodicEntry } from '../types.js';\n\nexport class EpisodicMemory {\n private readonly filePath: string;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n }\n\n private async ensureDir(): Promise<void> {\n const dir = dirname(this.filePath);\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n }\n\n async append(entry: EpisodicEntry): Promise<void> {\n await this.ensureDir();\n const line = JSON.stringify(entry) + '\\n';\n await appendFile(this.filePath, line, 'utf-8');\n }\n\n async readAll(): Promise<EpisodicEntry[]> {\n if (!existsSync(this.filePath)) {\n return [];\n }\n const content = await readFile(this.filePath, 'utf-8');\n return this.parseLines(content);\n }\n\n async search(query: string, limit: number = 10): Promise<EpisodicEntry[]> {\n const entries = await this.readAll();\n const queryLower = query.toLowerCase();\n const queryWords = queryLower.split(/\\s+/).filter(Boolean);\n\n const scored: Array<{ entry: EpisodicEntry; score: number }> = [];\n\n for (const entry of entries) {\n const searchText = [\n entry.description,\n ...entry.lessonsLearned,\n ...entry.tags,\n ].join(' ').toLowerCase();\n\n let score = 0;\n for (const word of queryWords) {\n if (searchText.includes(word)) {\n score += 1;\n }\n }\n\n // Exact phrase match bonus\n if (searchText.includes(queryLower)) {\n score += queryWords.length;\n }\n\n if (score > 0) {\n scored.push({ entry, score });\n }\n }\n\n scored.sort((a, b) => b.score - a.score);\n return scored.slice(0, limit).map(s => s.entry);\n }\n\n async readRecent(count: number): Promise<EpisodicEntry[]> {\n const entries = await this.readAll();\n return entries.slice(-count);\n }\n\n async recoverFromCorruption(): Promise<{ recovered: number; lost: number }> {\n if (!existsSync(this.filePath)) {\n return { recovered: 0, lost: 0 };\n }\n\n const content = await readFile(this.filePath, 'utf-8');\n const lines = content.split('\\n').filter(line => line.trim().length > 0);\n\n const validLines: string[] = [];\n let lost = 0;\n\n for (const line of lines) {\n try {\n JSON.parse(line);\n validLines.push(line);\n } catch {\n lost++;\n }\n }\n\n if (lost > 0) {\n await writeFile(this.filePath, validLines.map(l => l + '\\n').join(''), 'utf-8');\n }\n\n return { recovered: validLines.length, lost };\n }\n\n private parseLines(content: string): EpisodicEntry[] {\n const lines = content.split('\\n').filter(line => line.trim().length > 0);\n const entries: EpisodicEntry[] = [];\n\n for (const line of lines) {\n try {\n entries.push(JSON.parse(line) as EpisodicEntry);\n } catch {\n // Skip malformed lines\n }\n }\n\n return entries;\n }\n}\n","/**\n * ClawPowers Agent — Procedural Memory\n * JSON-based skill effectiveness tracking with atomic writes.\n */\n\nimport { readFile, writeFile, rename, mkdir, copyFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { ProceduralEntry, MutationRecord } from '../types.js';\n\nexport class ProceduralMemory {\n private readonly filePath: string;\n private cache: ProceduralEntry[] | null = null;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n }\n\n private async ensureDir(): Promise<void> {\n const dir = dirname(this.filePath);\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n }\n\n async load(): Promise<ProceduralEntry[]> {\n if (!existsSync(this.filePath)) {\n this.cache = [];\n return [];\n }\n const content = await readFile(this.filePath, 'utf-8');\n const entries = JSON.parse(content) as ProceduralEntry[];\n this.cache = entries;\n return entries;\n }\n\n async update(\n skillName: string,\n result: { succeeded: boolean; durationMs: number; taskId: string }\n ): Promise<void> {\n const entries = await this.load();\n const existing = entries.find(e => e.skillName === skillName);\n\n if (existing) {\n const newCount = existing.invocationCount + 1;\n const successCount = Math.round(existing.successRate * existing.invocationCount) + (result.succeeded ? 1 : 0);\n const newSuccessRate = successCount / newCount;\n const newAvgContribution =\n (existing.avgContribution * existing.invocationCount + result.durationMs) / newCount;\n\n const updated: ProceduralEntry = {\n ...existing,\n invocationCount: newCount,\n successRate: newSuccessRate,\n avgContribution: newAvgContribution,\n lastUsed: new Date().toISOString(),\n };\n\n const index = entries.indexOf(existing);\n entries[index] = updated;\n } else {\n const newEntry: ProceduralEntry = {\n skillName,\n invocationCount: 1,\n successRate: result.succeeded ? 1 : 0,\n avgContribution: result.durationMs,\n preferredContexts: [],\n lastUsed: new Date().toISOString(),\n mutations: [],\n };\n entries.push(newEntry);\n }\n\n await this.atomicWrite(entries);\n this.cache = entries;\n }\n\n getSkillScore(skillName: string): ProceduralEntry | null {\n if (!this.cache) {\n return null;\n }\n return this.cache.find(e => e.skillName === skillName) ?? null;\n }\n\n getTopSkills(context: string, limit: number): ProceduralEntry[] {\n if (!this.cache) {\n return [];\n }\n\n const contextLower = context.toLowerCase();\n const contextWords = contextLower.split(/\\s+/).filter(Boolean);\n\n const scored: Array<{ entry: ProceduralEntry; score: number }> = [];\n\n for (const entry of this.cache) {\n let score = entry.successRate * entry.invocationCount;\n\n // Boost if context matches preferred contexts\n for (const preferred of entry.preferredContexts) {\n const prefLower = preferred.toLowerCase();\n for (const word of contextWords) {\n if (prefLower.includes(word)) {\n score += 2;\n }\n }\n }\n\n // Boost if skill name matches context\n if (contextLower.includes(entry.skillName.toLowerCase())) {\n score += 5;\n }\n\n scored.push({ entry, score });\n }\n\n scored.sort((a, b) => b.score - a.score);\n return scored.slice(0, limit).map(s => s.entry);\n }\n\n async recordMutation(skillName: string, mutation: MutationRecord): Promise<void> {\n const entries = await this.load();\n const existing = entries.find(e => e.skillName === skillName);\n\n if (!existing) {\n throw new Error(`Skill \"${skillName}\" not found in procedural memory`);\n }\n\n const updated: ProceduralEntry = {\n ...existing,\n mutations: [...existing.mutations, mutation],\n };\n\n const index = entries.indexOf(existing);\n entries[index] = updated;\n\n await this.atomicWrite(entries);\n this.cache = entries;\n }\n\n async rollbackMutation(skillName: string, mutationId: string): Promise<void> {\n const entries = await this.load();\n const existing = entries.find(e => e.skillName === skillName);\n\n if (!existing) {\n throw new Error(`Skill \"${skillName}\" not found in procedural memory`);\n }\n\n const mutation = existing.mutations.find(m => m.mutationId === mutationId);\n if (!mutation) {\n throw new Error(`Mutation \"${mutationId}\" not found for skill \"${skillName}\"`);\n }\n\n const updatedMutations = existing.mutations.map(m => {\n if (m.mutationId === mutationId) {\n return {\n ...m,\n status: 'reverted' as const,\n revertedAt: new Date().toISOString(),\n };\n }\n return m;\n });\n\n const updated: ProceduralEntry = {\n ...existing,\n mutations: updatedMutations,\n };\n\n const index = entries.indexOf(existing);\n entries[index] = updated;\n\n await this.atomicWrite(entries);\n this.cache = entries;\n }\n\n private async atomicWrite(entries: ProceduralEntry[]): Promise<void> {\n await this.ensureDir();\n\n // Backup existing file\n if (existsSync(this.filePath)) {\n await copyFile(this.filePath, this.filePath + '.bak');\n }\n\n // Write to temp file then rename\n const tmpPath = this.filePath + '.tmp';\n await writeFile(tmpPath, JSON.stringify(entries, null, 2) + '\\n', 'utf-8');\n await rename(tmpPath, this.filePath);\n }\n}\n","/**\n * ClawPowers Agent — Checkpoint Manager\n * Crash recovery via atomic checkpoint files.\n */\n\nimport { readFile, writeFile, rename, unlink, readdir, mkdir } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { CheckpointState, CheckpointInfo } from '../types.js';\n\nconst DEFAULT_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 24 hours\n\nexport class CheckpointManager {\n private readonly dir: string;\n\n constructor(dir: string) {\n this.dir = dir;\n }\n\n private async ensureDir(): Promise<void> {\n if (!existsSync(this.dir)) {\n await mkdir(this.dir, { recursive: true });\n }\n }\n\n private filePath(taskId: string): string {\n return join(this.dir, `${taskId}.json`);\n }\n\n async save(taskId: string, state: CheckpointState): Promise<void> {\n await this.ensureDir();\n const path = this.filePath(taskId);\n const tmpPath = path + '.tmp';\n await writeFile(tmpPath, JSON.stringify(state, null, 2) + '\\n', 'utf-8');\n await rename(tmpPath, path);\n }\n\n async load(taskId: string): Promise<CheckpointState | null> {\n const path = this.filePath(taskId);\n if (!existsSync(path)) {\n return null;\n }\n const content = await readFile(path, 'utf-8');\n return JSON.parse(content) as CheckpointState;\n }\n\n async remove(taskId: string): Promise<void> {\n const path = this.filePath(taskId);\n if (existsSync(path)) {\n await unlink(path);\n }\n }\n\n async listIncomplete(): Promise<CheckpointInfo[]> {\n await this.ensureDir();\n const files = await readdir(this.dir);\n const results: CheckpointInfo[] = [];\n\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n\n const path = join(this.dir, file);\n try {\n const content = await readFile(path, 'utf-8');\n const state = JSON.parse(content) as CheckpointState;\n\n if (state.agentStatus !== 'complete' && state.agentStatus !== 'failed') {\n results.push({\n taskId: state.taskId,\n description: state.goal.description,\n savedAt: state.savedAt,\n isStale: this.isStale(state),\n });\n }\n } catch {\n // Skip corrupt checkpoint files\n }\n }\n\n return results;\n }\n\n isStale(checkpoint: CheckpointState, maxAgeMs: number = DEFAULT_MAX_AGE_MS): boolean {\n const savedTime = new Date(checkpoint.savedAt).getTime();\n const now = Date.now();\n return now - savedTime > maxAgeMs;\n }\n}\n","/**\n * ClawPowers Agent — Context Injector\n * Selects and compresses relevant memories for working memory injection.\n */\n\nimport type { Goal, EpisodicEntry, ProceduralEntry } from '../types.js';\nimport type { EpisodicMemory } from './episodic.js';\nimport type { ProceduralMemory } from './procedural.js';\n\nconst DEFAULT_MAX_TOKENS = 2000;\n\nfunction estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\nfunction compressEpisodicEntry(entry: EpisodicEntry): string {\n const date = entry.timestamp.slice(0, 10);\n const skills = entry.skillsUsed.length > 0 ? ` (${entry.skillsUsed.join(', ')})` : '';\n const lesson = entry.lessonsLearned.length > 0 ? ` Lesson: ${entry.lessonsLearned[0]}` : '';\n return `[${date}] '${entry.description.slice(0, 80)}' → ${entry.outcome}${skills}${lesson}`;\n}\n\nfunction compressProceduralEntry(entry: ProceduralEntry): string {\n const rate = Math.round(entry.successRate * 100);\n return `[skill] ${entry.skillName}: ${rate}% success over ${entry.invocationCount} invocations`;\n}\n\nfunction scoreEpisodicEntry(entry: EpisodicEntry, goalWords: readonly string[]): number {\n const text = [entry.description, ...entry.lessonsLearned, ...entry.tags].join(' ').toLowerCase();\n let score = 0;\n\n for (const word of goalWords) {\n if (text.includes(word)) {\n score += 1;\n }\n }\n\n // Recency bonus: more recent entries score higher\n const ageMs = Date.now() - new Date(entry.timestamp).getTime();\n const ageDays = ageMs / (24 * 60 * 60 * 1000);\n score += Math.max(0, 10 - ageDays) / 10; // Up to 1 point for recency\n\n return score;\n}\n\nexport class ContextInjector {\n private readonly episodic: EpisodicMemory;\n private readonly procedural: ProceduralMemory;\n\n constructor(episodic: EpisodicMemory, procedural: ProceduralMemory) {\n this.episodic = episodic;\n this.procedural = procedural;\n }\n\n async inject(goal: Goal, maxTokens: number = DEFAULT_MAX_TOKENS): Promise<string[]> {\n const goalWords = goal.description.toLowerCase().split(/\\s+/).filter(w => w.length > 2);\n\n // Score and sort episodic entries\n const allEpisodic = await this.episodic.readAll();\n const scoredEpisodic = allEpisodic\n .map(entry => ({ entry, score: scoreEpisodicEntry(entry, goalWords) }))\n .filter(s => s.score > 0)\n .sort((a, b) => b.score - a.score);\n\n // Get procedural entries\n const allProcedural = await this.procedural.load();\n const relevantProcedural = allProcedural\n .filter(entry => {\n const nameLower = entry.skillName.toLowerCase();\n return goalWords.some(w => nameLower.includes(w) || w.includes(nameLower));\n })\n .sort((a, b) => b.successRate * b.invocationCount - a.successRate * a.invocationCount);\n\n // Interleave: 2 episodic, 1 procedural, repeat\n const results: string[] = [];\n let totalTokens = 0;\n let eIdx = 0;\n let pIdx = 0;\n\n while (totalTokens < maxTokens && (eIdx < scoredEpisodic.length || pIdx < relevantProcedural.length)) {\n // Add up to 2 episodic entries\n for (let i = 0; i < 2 && eIdx < scoredEpisodic.length; i++, eIdx++) {\n const compressed = compressEpisodicEntry(scoredEpisodic[eIdx]!.entry);\n const tokens = estimateTokens(compressed);\n if (totalTokens + tokens > maxTokens) {\n return results;\n }\n results.push(compressed);\n totalTokens += tokens;\n }\n\n // Add 1 procedural entry\n if (pIdx < relevantProcedural.length) {\n const compressed = compressProceduralEntry(relevantProcedural[pIdx]!);\n const tokens = estimateTokens(compressed);\n if (totalTokens + tokens > maxTokens) {\n return results;\n }\n results.push(compressed);\n totalTokens += tokens;\n pIdx++;\n }\n }\n\n return results;\n }\n}\n","/**\n * Native acceleration bridge for memory storage.\n *\n * Tier 1: Native Rust .node addon (canonical store, TurboQuant compressor, write firewall)\n * Tier 2: WASM module (WasmCanonicalStore, compressVector, evaluateWriteFirewall)\n * Tier 3: Pure TypeScript fallback (null returns / fail-open defaults)\n *\n * Note: Wallet and x402 are excluded from the WASM build; memory functions\n * (canonical store, compression, security, verification) are all available in WASM.\n */\nimport { getNative, getWasm, computeSha256, evaluateWriteFirewall as wasmEvaluateWriteFirewall } from '../native/index.js';\nimport type { NativeCanonicalStore, WasmCanonicalStoreInstance } from '../native/index.js';\n\n// ─── Canonical Store ─────────────────────────────────────────────────────────\n\n/** Get a native persistent canonical store, or null if unavailable. */\nexport function getNativeCanonicalStore(dbPath: string): NativeCanonicalStore | null {\n const native = getNative();\n if (!native) return null;\n try {\n return native.JsCanonicalStore.open(dbPath);\n } catch {\n return null;\n }\n}\n\n/** Get an in-memory native canonical store for testing, or null if unavailable. */\nexport function getNativeCanonicalStoreInMemory(): NativeCanonicalStore | null {\n const native = getNative();\n if (!native) return null;\n try {\n return native.JsCanonicalStore.inMemory();\n } catch {\n return null;\n }\n}\n\n/**\n * Get an in-memory WASM canonical store, or null if WASM is unavailable.\n * This is the Tier 2 alternative to getNativeCanonicalStoreInMemory().\n */\nexport function getWasmCanonicalStore(): WasmCanonicalStoreInstance | null {\n const wasm = getWasm();\n if (!wasm) return null;\n try {\n return new wasm.WasmCanonicalStore();\n } catch {\n return null;\n }\n}\n\n/**\n * Get the best available in-memory canonical store.\n * Returns a unified interface regardless of which tier is active.\n *\n * Tier 1: Native canonical store (SQLite-backed in-memory)\n * Tier 2: WASM canonical store (in-memory HashMap)\n * Tier 3: null (caller must handle)\n */\nexport function getBestCanonicalStore(): NativeCanonicalStore | WasmCanonicalStoreInstance | null {\n return getNativeCanonicalStoreInMemory() ?? getWasmCanonicalStore();\n}\n\n// ─── Compression ─────────────────────────────────────────────────────────────\n\nexport interface CompressionResult {\n compressed: string;\n originalSize: number;\n compressedSize: number;\n}\n\n/**\n * Compress a float32 vector using the best available backend.\n *\n * Tier 1: Native TurboQuant compressor (JsTurboCompressor)\n * Tier 2: WASM vector compression (compressVector)\n * Tier 3: null (no compression available)\n */\nexport function compressVector(\n vector: Float32Array,\n bits: number = 8,\n): CompressionResult | null {\n // Tier 1: Native\n const native = getNative();\n if (native) {\n try {\n const compressor = new native.JsTurboCompressor(vector.length, bits);\n const compressed = compressor.compress(vector);\n return {\n compressed,\n originalSize: vector.length * 4,\n compressedSize: compressed.length,\n };\n } catch {\n // Fall through to Tier 2\n }\n }\n\n // Tier 2: WASM\n const wasm = getWasm();\n if (wasm) {\n try {\n const vectorJson = JSON.stringify(Array.from(vector));\n const compressed = wasm.compressVector(vectorJson, vector.length);\n return {\n compressed,\n originalSize: vector.length * 4,\n compressedSize: compressed.length,\n };\n } catch {\n // Fall through to Tier 3\n }\n }\n\n // Tier 3: null — caller handles missing compression\n return null;\n}\n\n/**\n * Decompress a previously compressed vector using the best available backend.\n *\n * Tier 1: Native TurboQuant decompressor\n * Tier 2: WASM vector decompressor\n * Tier 3: null (no decompression available)\n */\nexport function decompressVector(\n compressedJson: string,\n dimensions: number,\n bits: number = 8,\n): Float32Array | null {\n // Tier 1: Native\n const native = getNative();\n if (native) {\n try {\n const compressor = new native.JsTurboCompressor(dimensions, bits);\n return compressor.decompress(compressedJson);\n } catch {\n // Fall through to Tier 2\n }\n }\n\n // Tier 2: WASM\n const wasm = getWasm();\n if (wasm) {\n try {\n const arrayJson = wasm.decompressVector(compressedJson, dimensions);\n const arr = JSON.parse(arrayJson) as number[];\n return new Float32Array(arr);\n } catch {\n // Fall through to Tier 3\n }\n }\n\n // Tier 3: null\n return null;\n}\n\n/**\n * Compute approximate distance between two compressed vectors.\n *\n * Tier 1: Not exposed on native JsTurboCompressor directly\n * Tier 2: WASM approximateDistance\n * Tier 3: null\n */\nexport function approximateDistance(\n aJson: string,\n bJson: string,\n dimensions: number,\n): number | null {\n // Tier 2: WASM\n const wasm = getWasm();\n if (wasm) {\n try {\n return wasm.approximateDistance(aJson, bJson, dimensions);\n } catch {\n // Fall through\n }\n }\n return null;\n}\n\n// ─── Security / Write Firewall ────────────────────────────────────────────────\n\n/**\n * Evaluate a write request through the security firewall.\n * Fail-open: returns allowed:true if no backend is available.\n *\n * Tier 1: Native JsWriteFirewall\n * Tier 2: WASM evaluateWriteFirewall (via index.ts unified helper)\n * Tier 3: Basic TypeScript checks (via index.ts unified helper)\n */\nexport function evaluateWriteSecurity(\n namespace: string,\n content: string,\n allowedNamespaces: string[],\n source: string = 'agent',\n trustLevel: string = 'agent',\n): { allowed: boolean; reason?: string } {\n // Tier 1: Native\n const native = getNative();\n if (native) {\n try {\n const firewall = new native.JsWriteFirewall(\n JSON.stringify({ allowed_namespaces: allowedNamespaces }),\n );\n const result = JSON.parse(\n firewall.evaluate(JSON.stringify({ namespace, content, trust_level: trustLevel })),\n ) as { allowed: boolean; reason?: string };\n return result;\n } catch {\n // Fall through to Tier 2\n }\n }\n\n // Tier 2 + Tier 3: WASM or TypeScript fallback via unified helper in index.ts\n // wasmEvaluateWriteFirewall automatically routes to WASM if available, else TS\n try {\n const result = wasmEvaluateWriteFirewall({\n namespace,\n content,\n trust_level: trustLevel,\n source,\n allowed_namespaces: allowedNamespaces.length > 0 ? allowedNamespaces : undefined,\n });\n\n // Normalise: WASM returns {decision, reason, sanitized}, callers expect {allowed, reason}\n return {\n allowed: result.decision === 'allow' || result.decision === 'sanitize',\n reason: result.reason,\n };\n } catch {\n // Absolute fallback: fail-open\n return { allowed: true };\n }\n}\n\n/**\n * Compute SHA-256 hash of content using the best available backend.\n * Re-exported from native/index.ts for convenience — already 3-tier aware.\n */\nexport { computeSha256 };\n","/**\n * ClawPowers Agent — RSI Metrics Collector\n * Per-task and per-skill metric collection in JSONL format.\n */\n\nimport { readFile, appendFile, mkdir } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { TaskMetrics, SkillMetrics, SkillAggregateStats, TrendDirection } from '../types.js';\n\nexport class MetricsCollector {\n private readonly taskMetricsPath: string;\n private readonly skillMetricsPath: string;\n\n constructor(taskMetricsPath: string, skillMetricsPath: string) {\n this.taskMetricsPath = taskMetricsPath;\n this.skillMetricsPath = skillMetricsPath;\n }\n\n private async ensureDir(filePath: string): Promise<void> {\n const dir = dirname(filePath);\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n }\n\n async recordTaskMetrics(task: TaskMetrics): Promise<void> {\n await this.ensureDir(this.taskMetricsPath);\n const line = JSON.stringify(task) + '\\n';\n await appendFile(this.taskMetricsPath, line, 'utf-8');\n }\n\n async recordSkillMetrics(skill: SkillMetrics): Promise<void> {\n await this.ensureDir(this.skillMetricsPath);\n const line = JSON.stringify(skill) + '\\n';\n await appendFile(this.skillMetricsPath, line, 'utf-8');\n }\n\n async getTaskHistory(limit?: number): Promise<TaskMetrics[]> {\n const entries = await this.readJsonl<TaskMetrics>(this.taskMetricsPath);\n if (limit !== undefined) {\n return entries.slice(-limit);\n }\n return entries;\n }\n\n async getSkillHistory(skillName: string, limit?: number): Promise<SkillMetrics[]> {\n const all = await this.readJsonl<SkillMetrics>(this.skillMetricsPath);\n const filtered = all.filter(s => s.skillName === skillName);\n if (limit !== undefined) {\n return filtered.slice(-limit);\n }\n return filtered;\n }\n\n async getAggregatedSkillStats(skillName: string): Promise<SkillAggregateStats> {\n const history = await this.getSkillHistory(skillName);\n\n if (history.length === 0) {\n return {\n skillName,\n totalInvocations: 0,\n successRate: 0,\n avgDurationMs: 0,\n trendDirection: 'stable',\n };\n }\n\n const invokedEntries = history.filter(h => h.invoked);\n const totalInvocations = invokedEntries.length;\n const successCount = invokedEntries.filter(h => h.succeeded).length;\n const successRate = totalInvocations > 0 ? successCount / totalInvocations : 0;\n const avgDurationMs =\n totalInvocations > 0\n ? invokedEntries.reduce((sum, h) => sum + h.durationMs, 0) / totalInvocations\n : 0;\n\n const trendDirection = this.calculateTrend(invokedEntries);\n\n return {\n skillName,\n totalInvocations,\n successRate,\n avgDurationMs,\n trendDirection,\n };\n }\n\n private calculateTrend(entries: readonly SkillMetrics[]): TrendDirection {\n if (entries.length < 4) {\n return 'stable';\n }\n\n const mid = Math.floor(entries.length / 2);\n const firstHalf = entries.slice(0, mid);\n const secondHalf = entries.slice(mid);\n\n const firstRate = firstHalf.filter(e => e.succeeded).length / firstHalf.length;\n const secondRate = secondHalf.filter(e => e.succeeded).length / secondHalf.length;\n\n const diff = secondRate - firstRate;\n if (diff > 0.1) return 'improving';\n if (diff < -0.1) return 'declining';\n return 'stable';\n }\n\n private async readJsonl<T>(filePath: string): Promise<T[]> {\n if (!existsSync(filePath)) {\n return [];\n }\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n').filter(line => line.trim().length > 0);\n const results: T[] = [];\n for (const line of lines) {\n try {\n results.push(JSON.parse(line) as T);\n } catch {\n // Skip malformed lines\n }\n }\n return results;\n }\n}\n","/**\n * ClawPowers Agent — RSI Hypothesis Engine\n * Analyzes skill stats and task history to generate improvement hypotheses.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { SkillAggregateStats, TaskMetrics, RSIHypothesis, RSITierLabel } from '../types.js';\n\nconst MIN_DATA_POINTS = 10;\nconst LOW_SUCCESS_THRESHOLD = 0.6;\nconst SLOW_SKILL_PERCENTILE = 0.75;\n\nexport class HypothesisEngine {\n analyze(\n skillStats: readonly SkillAggregateStats[],\n taskHistory: readonly TaskMetrics[]\n ): RSIHypothesis[] {\n if (taskHistory.length < MIN_DATA_POINTS) {\n return [];\n }\n\n const hypotheses: RSIHypothesis[] = [];\n\n hypotheses.push(...this.detectLowSuccessRate(skillStats));\n hypotheses.push(...this.detectSlowSkills(skillStats));\n hypotheses.push(...this.detectFrequentlyPairedSkills(taskHistory));\n hypotheses.push(...this.detectUnusedInSuccessful(skillStats, taskHistory));\n\n return hypotheses;\n }\n\n private detectLowSuccessRate(stats: readonly SkillAggregateStats[]): RSIHypothesis[] {\n const hypotheses: RSIHypothesis[] = [];\n\n for (const skill of stats) {\n if (skill.totalInvocations >= 5 && skill.successRate < LOW_SUCCESS_THRESHOLD) {\n const expectedImprovement = Math.round((LOW_SUCCESS_THRESHOLD - skill.successRate) * 100);\n hypotheses.push({\n hypothesisId: randomUUID(),\n skillName: skill.skillName,\n description: `Adjusting retry count for ${skill.skillName} may improve success by ${expectedImprovement}%`,\n expectedImprovement,\n tier: 'T1' as RSITierLabel,\n confidence: Math.min(0.9, skill.totalInvocations / 20),\n evidence: [\n `Current success rate: ${Math.round(skill.successRate * 100)}%`,\n `Total invocations: ${skill.totalInvocations}`,\n `Trend: ${skill.trendDirection}`,\n ],\n });\n }\n }\n\n return hypotheses;\n }\n\n private detectSlowSkills(stats: readonly SkillAggregateStats[]): RSIHypothesis[] {\n const hypotheses: RSIHypothesis[] = [];\n const withInvocations = stats.filter(s => s.totalInvocations >= 5);\n\n if (withInvocations.length < 2) return hypotheses;\n\n const durations = withInvocations.map(s => s.avgDurationMs).sort((a, b) => a - b);\n const percentileIdx = Math.max(0, Math.floor(durations.length * SLOW_SKILL_PERCENTILE) - 1);\n const threshold = durations[percentileIdx] ?? Infinity;\n\n for (const skill of withInvocations) {\n if (skill.avgDurationMs > threshold) {\n const expectedImprovement = Math.round(\n ((skill.avgDurationMs - threshold) / skill.avgDurationMs) * 100\n );\n hypotheses.push({\n hypothesisId: randomUUID(),\n skillName: skill.skillName,\n description: `Increasing timeout for ${skill.skillName} may reduce failures by ${expectedImprovement}%`,\n expectedImprovement,\n tier: 'T1' as RSITierLabel,\n confidence: Math.min(0.8, skill.totalInvocations / 25),\n evidence: [\n `Avg duration: ${Math.round(skill.avgDurationMs)}ms`,\n `75th percentile threshold: ${Math.round(threshold)}ms`,\n ],\n });\n }\n }\n\n return hypotheses;\n }\n\n private detectFrequentlyPairedSkills(taskHistory: readonly TaskMetrics[]): RSIHypothesis[] {\n const hypotheses: RSIHypothesis[] = [];\n const pairCounts = new Map<string, number>();\n\n for (const task of taskHistory) {\n const skills = task.skillsUsed;\n for (let i = 0; i < skills.length; i++) {\n for (let j = i + 1; j < skills.length; j++) {\n const pair = [skills[i]!, skills[j]!].sort().join('+');\n pairCounts.set(pair, (pairCounts.get(pair) ?? 0) + 1);\n }\n }\n }\n\n for (const [pair, count] of pairCounts) {\n if (count >= 5) {\n const [skillA, skillB] = pair.split('+') as [string, string];\n hypotheses.push({\n hypothesisId: randomUUID(),\n skillName: `${skillA}+${skillB}`,\n description: `Creating a chain of ${skillA}+${skillB} may improve efficiency`,\n expectedImprovement: Math.round((count / taskHistory.length) * 30),\n tier: 'T3' as RSITierLabel,\n confidence: Math.min(0.7, count / 15),\n evidence: [\n `Co-occurrence: ${count}/${taskHistory.length} tasks`,\n ],\n });\n }\n }\n\n return hypotheses;\n }\n\n private detectUnusedInSuccessful(\n stats: readonly SkillAggregateStats[],\n taskHistory: readonly TaskMetrics[]\n ): RSIHypothesis[] {\n const hypotheses: RSIHypothesis[] = [];\n const successfulTasks = taskHistory.filter(t => t.outcome === 'success');\n\n if (successfulTasks.length < 5) return hypotheses;\n\n const successfulSkills = new Set<string>();\n for (const task of successfulTasks) {\n for (const skill of task.skillsUsed) {\n successfulSkills.add(skill);\n }\n }\n\n for (const skill of stats) {\n if (\n skill.totalInvocations >= 5 &&\n !successfulSkills.has(skill.skillName) &&\n skill.successRate < 0.5\n ) {\n hypotheses.push({\n hypothesisId: randomUUID(),\n skillName: skill.skillName,\n description: `Deprioritizing ${skill.skillName} for current task types`,\n expectedImprovement: 10,\n tier: 'T2' as RSITierLabel,\n confidence: 0.5,\n evidence: [\n `Not used in any of ${successfulTasks.length} successful tasks`,\n `Success rate: ${Math.round(skill.successRate * 100)}%`,\n ],\n });\n }\n }\n\n return hypotheses;\n }\n}\n","/**\n * ClawPowers Agent — RSI Mutation Engine\n * Creates and manages mutations from hypotheses with tier enforcement.\n */\n\nimport { readFile, appendFile, mkdir } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport { SAFETY_INVARIANTS } from '../constants.js';\nimport type { RSIHypothesis, RSIMutationExtended, RSIMutationExtendedStatus } from '../types.js';\n\nexport class MutationEngine {\n private readonly historyPath: string;\n\n constructor(historyPath: string) {\n this.historyPath = historyPath;\n }\n\n private async ensureDir(): Promise<void> {\n const dir = dirname(this.historyPath);\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n }\n\n createMutation(hypothesis: RSIHypothesis): RSIMutationExtended {\n // Safety check: never mutate safety invariants\n this.validateSafety(hypothesis);\n\n const initialStatus: RSIMutationExtendedStatus =\n hypothesis.tier === 'T4' ? 'proposed' : 'proposed';\n\n return {\n mutationId: randomUUID(),\n hypothesisId: hypothesis.hypothesisId,\n skillName: hypothesis.skillName,\n tier: hypothesis.tier,\n description: hypothesis.description,\n originalValue: '',\n mutatedValue: hypothesis.description,\n status: initialStatus,\n appliedAt: null,\n revertedAt: null,\n };\n }\n\n async applyMutation(mutation: RSIMutationExtended): Promise<void> {\n // Safety check\n if (this.isSafetyInvariant(mutation.skillName)) {\n throw new Error(\n `Cannot mutate safety invariant: ${mutation.skillName}. ` +\n `Safety invariants are: ${SAFETY_INVARIANTS.join(', ')}`\n );\n }\n\n // T4 never auto-applies\n if (mutation.tier === 'T4') {\n throw new Error(\n 'T4 mutations (Architecture) cannot be auto-applied. They must be proposed and reviewed by a human.'\n );\n }\n\n const applied: RSIMutationExtended = {\n ...mutation,\n status: 'applied',\n appliedAt: new Date().toISOString(),\n };\n\n await this.appendHistory(applied);\n }\n\n async revertMutation(mutation: RSIMutationExtended): Promise<void> {\n const reverted: RSIMutationExtended = {\n ...mutation,\n status: 'reverted',\n revertedAt: new Date().toISOString(),\n };\n\n await this.appendHistory(reverted);\n }\n\n async getMutationHistory(): Promise<RSIMutationExtended[]> {\n if (!existsSync(this.historyPath)) {\n return [];\n }\n const content = await readFile(this.historyPath, 'utf-8');\n const lines = content.split('\\n').filter(l => l.trim().length > 0);\n const results: RSIMutationExtended[] = [];\n for (const line of lines) {\n try {\n results.push(JSON.parse(line) as RSIMutationExtended);\n } catch {\n // Skip malformed\n }\n }\n return results;\n }\n\n private async appendHistory(mutation: RSIMutationExtended): Promise<void> {\n await this.ensureDir();\n const line = JSON.stringify(mutation) + '\\n';\n await appendFile(this.historyPath, line, 'utf-8');\n }\n\n private validateSafety(hypothesis: RSIHypothesis): void {\n if (this.isSafetyInvariant(hypothesis.skillName)) {\n throw new Error(\n `Cannot create mutation targeting safety invariant: ${hypothesis.skillName}`\n );\n }\n }\n\n private isSafetyInvariant(name: string): boolean {\n const nameLower = name.toLowerCase();\n return SAFETY_INVARIANTS.some(invariant =>\n nameLower.includes(invariant.toLowerCase()) ||\n invariant.toLowerCase().includes(nameLower)\n );\n }\n}\n","/**\n * ClawPowers Agent — A/B Test Manager\n * Orchestrates A/B tests for RSI mutations.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type {\n RSIMutationExtended,\n SkillAggregateStats,\n ABTest,\n ABTestResult,\n ABTestDecision,\n TaskMetrics,\n} from '../types.js';\n\nconst DEFAULT_MIN_SAMPLE_SIZE = 5;\nconst PROMOTION_THRESHOLD = 0.10;\nconst ROLLBACK_THRESHOLD = -0.10;\n\nexport class ABTestManager {\n private readonly tests: Map<string, ABTest> = new Map();\n private readonly results: Map<string, TaskMetrics[]> = new Map();\n\n startTest(\n mutation: RSIMutationExtended,\n baselineMetrics: SkillAggregateStats\n ): ABTest {\n const testId = randomUUID();\n\n const test: ABTest = {\n testId,\n mutationId: mutation.mutationId,\n skillName: mutation.skillName,\n baselineStats: baselineMetrics,\n variantStats: {\n skillName: mutation.skillName,\n totalInvocations: 0,\n successRate: 0,\n avgDurationMs: 0,\n trendDirection: 'stable',\n },\n sampleSize: 0,\n minSampleSize: DEFAULT_MIN_SAMPLE_SIZE,\n startedAt: new Date().toISOString(),\n status: 'running',\n };\n\n this.tests.set(testId, test);\n this.results.set(testId, []);\n return test;\n }\n\n recordResult(testId: string, taskMetrics: TaskMetrics): void {\n const test = this.tests.get(testId);\n if (!test) {\n throw new Error(`A/B test \"${testId}\" not found`);\n }\n if (test.status !== 'running') {\n throw new Error(`A/B test \"${testId}\" is not running (status: ${test.status})`);\n }\n\n const taskResults = this.results.get(testId) ?? [];\n taskResults.push(taskMetrics);\n this.results.set(testId, taskResults);\n\n // Update variant stats\n const successCount = taskResults.filter(t => t.outcome === 'success').length;\n const totalDuration = taskResults.reduce((sum, t) => sum + t.durationMs, 0);\n\n const updatedTest: ABTest = {\n ...test,\n sampleSize: taskResults.length,\n variantStats: {\n skillName: test.skillName,\n totalInvocations: taskResults.length,\n successRate: taskResults.length > 0 ? successCount / taskResults.length : 0,\n avgDurationMs: taskResults.length > 0 ? totalDuration / taskResults.length : 0,\n trendDirection: 'stable',\n },\n };\n\n this.tests.set(testId, updatedTest);\n }\n\n evaluateTest(testId: string): ABTestResult {\n const test = this.tests.get(testId);\n if (!test) {\n throw new Error(`A/B test \"${testId}\" not found`);\n }\n\n if (test.sampleSize < test.minSampleSize) {\n return {\n testId,\n decision: 'continue',\n improvement: 0,\n confidence: test.sampleSize / test.minSampleSize,\n };\n }\n\n const baselineRate = test.baselineStats.successRate;\n const variantRate = test.variantStats.successRate;\n\n const improvement = baselineRate > 0\n ? (variantRate - baselineRate) / baselineRate\n : variantRate > 0 ? 1 : 0;\n\n const confidence = Math.min(1, test.sampleSize / (test.minSampleSize * 2));\n\n let decision: ABTestDecision;\n if (improvement > PROMOTION_THRESHOLD) {\n decision = 'promote';\n } else if (improvement < ROLLBACK_THRESHOLD) {\n decision = 'rollback';\n } else {\n decision = 'continue';\n }\n\n // Update test status if decided\n if (decision === 'promote' || decision === 'rollback') {\n const updated: ABTest = {\n ...test,\n status: 'completed',\n };\n this.tests.set(testId, updated);\n }\n\n return {\n testId,\n decision,\n improvement,\n confidence,\n };\n }\n\n getActiveTests(): ABTest[] {\n const active: ABTest[] = [];\n for (const test of this.tests.values()) {\n if (test.status === 'running') {\n active.push(test);\n }\n }\n return active;\n }\n}\n","/**\n * ClawPowers Agent — RSI Audit Log\n * Append-only JSONL audit trail for all RSI actions.\n */\n\nimport { readFile, appendFile, mkdir } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { RSIAuditEntry } from '../types.js';\n\nexport class RSIAuditLog {\n private readonly filePath: string;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n }\n\n private async ensureDir(): Promise<void> {\n const dir = dirname(this.filePath);\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n }\n\n async log(entry: RSIAuditEntry): Promise<void> {\n await this.ensureDir();\n const line = JSON.stringify(entry) + '\\n';\n await appendFile(this.filePath, line, 'utf-8');\n }\n\n async getHistory(limit?: number): Promise<RSIAuditEntry[]> {\n if (!existsSync(this.filePath)) {\n return [];\n }\n const content = await readFile(this.filePath, 'utf-8');\n const lines = content.split('\\n').filter(l => l.trim().length > 0);\n const entries: RSIAuditEntry[] = [];\n for (const line of lines) {\n try {\n entries.push(JSON.parse(line) as RSIAuditEntry);\n } catch {\n // Skip malformed\n }\n }\n if (limit !== undefined) {\n return entries.slice(-limit);\n }\n return entries;\n }\n\n async getByMutation(mutationId: string): Promise<RSIAuditEntry[]> {\n const all = await this.getHistory();\n return all.filter(e => e.mutationId === mutationId);\n }\n}\n","/**\n * ClawPowers Agent — RSI AutoResearch Module\n *\n * Runs BEFORE the mutation engine when T3 is triggered.\n * Searches for solutions to task failures, tests candidates in sandbox,\n * and promotes successful solutions to new skills.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { execSync } from 'node:child_process';\nimport { mkdirSync, existsSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\n\n// ─── Public Interfaces ────────────────────────────────────────────────────────\n\nexport interface FailureTrace {\n taskDescription: string;\n error: string;\n executionSteps: string[];\n skillsUsed: string[];\n attemptCount: number;\n}\n\nexport interface CandidateSolution {\n source: 'web-search' | 'npm-registry' | 'skill-catalog';\n description: string;\n approach: string;\n confidence: number; // 0-1\n}\n\nexport interface TestResult {\n passed: boolean;\n output: string;\n durationMs: number;\n attempt: number;\n}\n\nexport interface SkillDefinition {\n skillId: string;\n name: string;\n description: string;\n approach: string;\n source: CandidateSolution['source'];\n promotedAt: string;\n testResults: TestResult[];\n}\n\nexport interface TaskContext {\n taskId: string;\n description: string;\n constraints: string[];\n successCriteria: string[];\n}\n\n// ─── Internal Helpers ─────────────────────────────────────────────────────────\n\n/** Minimum confidence required to attempt testing a candidate. */\nconst MIN_CONFIDENCE = 0.3;\n\n/** Number of sandbox runs a candidate must pass to be promoted. */\nconst REQUIRED_PASSING_RUNS = 3;\n\n/**\n * Extract the core error token(s) from a failure trace for use in a search query.\n * Strips ANSI codes, file paths, and noise; keeps meaningful error tokens.\n */\nexport function buildSearchQuery(failure: FailureTrace): string {\n // Strip ANSI escape sequences\n const clean = failure.error.replace(/\\x1b\\[[0-9;]*m/g, '');\n\n // Extract the most informative part: first line of the error\n const firstLine = clean.split('\\n')[0]?.trim() ?? clean.trim();\n\n // Strip absolute file paths (e.g. /Users/foo/bar.ts:10:5)\n const noPath = firstLine.replace(/\\/[^\\s:]+:\\d+:\\d+/g, '').trim();\n\n // Compose query: task description summary + cleaned error\n const taskSummary = failure.taskDescription.slice(0, 60).trim();\n const errorSummary = noPath.slice(0, 100).trim();\n\n if (!errorSummary) {\n return `${taskSummary} fix solution`;\n }\n return `${taskSummary} ${errorSummary}`.trim();\n}\n\n/**\n * Compute confidence score for a candidate solution based on heuristics.\n * Considers source reliability and relevance signals in description/approach.\n */\nexport function scoreConfidence(\n candidate: Omit<CandidateSolution, 'confidence'>,\n failure: FailureTrace\n): number {\n let base = 0.0;\n\n // Source reliability baseline\n switch (candidate.source) {\n case 'skill-catalog':\n base = 0.7; // Known-good, locally tested\n break;\n case 'npm-registry':\n base = 0.5; // Package exists, usage unknown\n break;\n case 'web-search':\n base = 0.4; // External, unverified\n break;\n }\n\n // Boost if approach mentions keywords from the failure description\n const failureWords = new Set(\n failure.taskDescription.toLowerCase().split(/\\W+/).filter(w => w.length > 3)\n );\n const approachWords = candidate.approach.toLowerCase().split(/\\W+/);\n const matches = approachWords.filter(w => failureWords.has(w)).length;\n const overlap = Math.min(matches / Math.max(failureWords.size, 1), 0.25);\n base += overlap;\n\n // Penalise if description is very short (likely low-quality)\n if (candidate.description.length < 20) {\n base -= 0.1;\n }\n\n // Clamp to [0, 1]\n return Math.max(0, Math.min(1, base));\n}\n\n// ─── AutoResearcher ───────────────────────────────────────────────────────────\n\nexport class AutoResearcher {\n private readonly skillsDir: string;\n\n constructor(skillsDir?: string) {\n this.skillsDir = skillsDir ?? join(tmpdir(), 'clawpowers-promoted-skills');\n }\n\n /**\n * Search for candidate solutions to a failure.\n *\n * Sources queried (in order of reliability):\n * 1. skill-catalog — skills already available that match the error domain\n * 2. npm-registry — packages that match the error keywords\n * 3. web-search — constructs a query from the failure trace\n *\n * Returns candidates sorted by confidence (highest first).\n */\n async research(failure: FailureTrace): Promise<CandidateSolution[]> {\n const candidates: CandidateSolution[] = [];\n\n // 1. Skill-catalog scan\n const skillCatalogCandidates = this.searchSkillCatalog(failure);\n candidates.push(...skillCatalogCandidates);\n\n // 2. npm-registry search\n const npmCandidates = await this.searchNpmRegistry(failure);\n candidates.push(...npmCandidates);\n\n // 3. Web-search candidates\n const webCandidates = this.buildWebSearchCandidates(failure);\n candidates.push(...webCandidates);\n\n // Sort by confidence descending\n return candidates\n .filter(c => c.confidence >= MIN_CONFIDENCE)\n .sort((a, b) => b.confidence - a.confidence);\n }\n\n /**\n * Test a candidate solution in an isolated sandbox.\n * Runs the candidate's approach as a shell command in a temp directory.\n * Returns a TestResult with pass/fail, output, and duration.\n */\n async testCandidate(\n candidate: CandidateSolution,\n task: TaskContext\n ): Promise<TestResult> {\n const startMs = Date.now();\n const sandboxDir = join(tmpdir(), `clawpowers-sandbox-${randomUUID()}`);\n\n try {\n mkdirSync(sandboxDir, { recursive: true });\n\n // Build a test script that validates the candidate's approach\n const testScript = this.buildTestScript(candidate, task, sandboxDir);\n const scriptPath = join(sandboxDir, 'test.sh');\n writeFileSync(scriptPath, testScript, { mode: 0o755 });\n\n const output = execSync(`bash \"${scriptPath}\"`, {\n cwd: sandboxDir,\n timeout: 30000,\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n\n return {\n passed: true,\n output: output.toString().slice(0, 2000),\n durationMs: Date.now() - startMs,\n attempt: 1,\n };\n } catch (err) {\n const output =\n err instanceof Error\n ? err.message\n : String(err);\n\n return {\n passed: false,\n output: output.slice(0, 2000),\n durationMs: Date.now() - startMs,\n attempt: 1,\n };\n } finally {\n // Best-effort cleanup\n try {\n execSync(`rm -rf \"${sandboxDir}\"`, { timeout: 5000, stdio: 'ignore' });\n } catch {\n // Ignore cleanup errors\n }\n }\n }\n\n /**\n * Run a candidate through REQUIRED_PASSING_RUNS sandbox tests.\n * Returns all TestResult objects. If fewer than REQUIRED_PASSING_RUNS pass,\n * the candidate is NOT promoted (caller must check).\n */\n async runSandboxTests(\n candidate: CandidateSolution,\n task: TaskContext\n ): Promise<TestResult[]> {\n const results: TestResult[] = [];\n for (let i = 1; i <= REQUIRED_PASSING_RUNS; i++) {\n const result = await this.testCandidate(candidate, task);\n results.push({ ...result, attempt: i });\n // Short-circuit: if a run fails, remaining runs won't help\n if (!result.passed) {\n break;\n }\n }\n return results;\n }\n\n /**\n * Promote a candidate solution to a new skill definition.\n * Writes a minimal SKILL.md to the skills directory and returns\n * the SkillDefinition.\n */\n async promoteToSkill(\n candidate: CandidateSolution,\n testResults: TestResult[]\n ): Promise<SkillDefinition> {\n const passingRuns = testResults.filter(r => r.passed).length;\n if (passingRuns < REQUIRED_PASSING_RUNS) {\n throw new Error(\n `Cannot promote candidate: only ${passingRuns}/${REQUIRED_PASSING_RUNS} test runs passed.`\n );\n }\n\n const skillId = `auto-${randomUUID().slice(0, 8)}`;\n const skillName = this.deriveSkillName(candidate);\n\n const definition: SkillDefinition = {\n skillId,\n name: skillName,\n description: candidate.description,\n approach: candidate.approach,\n source: candidate.source,\n promotedAt: new Date().toISOString(),\n testResults,\n };\n\n // Write SKILL.md to the skills directory\n const skillDir = join(this.skillsDir, skillName);\n if (!existsSync(skillDir)) {\n mkdirSync(skillDir, { recursive: true });\n }\n\n const skillMd = this.renderSkillMd(definition);\n writeFileSync(join(skillDir, 'SKILL.md'), skillMd, 'utf-8');\n\n return definition;\n }\n\n // ─── Private Methods ───────────────────────────────────────────────────────\n\n private searchSkillCatalog(failure: FailureTrace): CandidateSolution[] {\n // Import is dynamic to avoid circular deps — we use the static catalog if available\n try {\n const { SKILLS_CATALOG } = require('../skills/catalog.js') as {\n SKILLS_CATALOG: Array<{ name: string; description: string; category: string }>;\n };\n\n const errorTokens = failure.error.toLowerCase().split(/\\W+/).filter(t => t.length > 3);\n const taskTokens = failure.taskDescription.toLowerCase().split(/\\W+/).filter(t => t.length > 3);\n const relevantTokens = new Set([...errorTokens, ...taskTokens]);\n\n return SKILLS_CATALOG\n .filter(skill => {\n const haystack = `${skill.name} ${skill.description}`.toLowerCase();\n return [...relevantTokens].some(token => haystack.includes(token));\n })\n .slice(0, 3)\n .map(skill => {\n const base: Omit<CandidateSolution, 'confidence'> = {\n source: 'skill-catalog',\n description: skill.description,\n approach: `Use the '${skill.name}' skill (category: ${skill.category}) to address this failure.`,\n };\n return {\n ...base,\n confidence: scoreConfidence(base, failure),\n };\n });\n } catch {\n // skills-catalog not yet built or not importable in this context\n return [];\n }\n }\n\n private async searchNpmRegistry(failure: FailureTrace): Promise<CandidateSolution[]> {\n const query = buildSearchQuery(failure);\n // Construct search keywords from the error tokens\n const keywords = query.split(/\\s+/).filter(w => w.length > 3).slice(0, 5).join('+');\n\n try {\n const raw = execSync(\n `npm search ${keywords} --json --no-description 2>/dev/null`,\n {\n timeout: 15000,\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }\n );\n\n const results = JSON.parse(raw) as Array<{\n name: string;\n description?: string;\n keywords?: string[];\n }>;\n\n return results.slice(0, 3).map(pkg => {\n const base: Omit<CandidateSolution, 'confidence'> = {\n source: 'npm-registry',\n description: pkg.description ?? pkg.name,\n approach: `Install and use npm package '${pkg.name}' to resolve this failure.`,\n };\n return {\n ...base,\n confidence: scoreConfidence(base, failure),\n };\n });\n } catch {\n // npm search failed or timed out — return empty\n return [];\n }\n }\n\n private buildWebSearchCandidates(failure: FailureTrace): CandidateSolution[] {\n const query = buildSearchQuery(failure);\n\n // Without a live web-search API we return a structured candidate that\n // encodes the query for a future search agent to resolve.\n const base: Omit<CandidateSolution, 'confidence'> = {\n source: 'web-search',\n description: `Web search for: \"${query}\"`,\n approach: `Search the web for \"${query}\" and apply the top-ranked solution approach.`,\n };\n return [\n {\n ...base,\n confidence: scoreConfidence(base, failure),\n },\n ];\n }\n\n /**\n * Build a sandboxed test script for a candidate solution.\n * Validates the candidate's approach by checking its core prerequisites\n * (e.g. that a package is installed, or a command is available).\n */\n private buildTestScript(\n candidate: CandidateSolution,\n task: TaskContext,\n _sandboxDir: string\n ): string {\n const lines: string[] = [\n '#!/usr/bin/env bash',\n 'set -euo pipefail',\n '',\n '# AutoResearch sandbox test',\n `# Task: ${task.description.replace(/'/g, \"'\\\\''\").slice(0, 200)}`,\n `# Candidate source: ${candidate.source}`,\n `# Candidate: ${candidate.description.replace(/'/g, \"'\\\\''\").slice(0, 200)}`,\n '',\n ];\n\n if (candidate.source === 'npm-registry') {\n // Extract the package name from the approach\n const match = /npm package '([^']+)'/.exec(candidate.approach);\n if (match) {\n const pkgName = match[1];\n lines.push(`# Check if the npm package exists in the registry`);\n lines.push(`npm view \"${pkgName}\" name > /dev/null 2>&1`);\n lines.push(`echo \"Package '${pkgName}' exists in npm registry\"`);\n } else {\n lines.push('echo \"npm-registry candidate: no package name extractable\"');\n lines.push('exit 0');\n }\n } else if (candidate.source === 'skill-catalog') {\n // Validate that the skill name is mentioned\n const match = /skill '([^']+)'/.exec(candidate.approach);\n if (match) {\n lines.push(`# Validate skill '${match[1]}' reference`);\n lines.push(`echo \"Skill catalog candidate: ${match[1]}\"`);\n lines.push('exit 0');\n } else {\n lines.push('echo \"skill-catalog candidate validated\"');\n lines.push('exit 0');\n }\n } else {\n // web-search: validate the query is non-empty\n const q = buildSearchQuery({ error: candidate.description, taskDescription: task.description, executionSteps: [], skillsUsed: [], attemptCount: 1 });\n if (q.trim().length > 0) {\n lines.push(`echo \"web-search candidate: query is '${q.replace(/'/g, '').slice(0, 100)}'\"`);\n lines.push('exit 0');\n } else {\n lines.push('echo \"web-search candidate: empty query\" >&2');\n lines.push('exit 1');\n }\n }\n\n lines.push('');\n lines.push('# Success criteria check');\n for (const criterion of task.successCriteria.slice(0, 2)) {\n lines.push(`echo \"Criterion: ${criterion.replace(/'/g, '').slice(0, 100)}\"`);\n }\n\n lines.push('echo \"Test passed\"');\n return lines.join('\\n') + '\\n';\n }\n\n private deriveSkillName(candidate: CandidateSolution): string {\n // Build a slug from the description\n const slug = candidate.description\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40);\n return `auto-${slug}`;\n }\n\n private renderSkillMd(def: SkillDefinition): string {\n return [\n '---',\n `name: ${def.name}`,\n `description: \"${def.description.replace(/\"/g, \"'\")}\"`,\n `source: ${def.source}`,\n `skillId: ${def.skillId}`,\n `promotedAt: \"${def.promotedAt}\"`,\n '---',\n '',\n `# ${def.name}`,\n '',\n `**Auto-promoted by AutoResearcher on ${def.promotedAt}**`,\n '',\n `## Description`,\n '',\n def.description,\n '',\n `## Approach`,\n '',\n def.approach,\n '',\n `## Test Results`,\n '',\n `Passed ${def.testResults.filter(r => r.passed).length}/${def.testResults.length} sandbox runs.`,\n '',\n ].join('\\n');\n }\n}\n\n// ─── Module-level helper for RSI wiring ──────────────────────────────────────\n\n/**\n * Run the full AutoResearch cycle for a failed task.\n * Returns the promoted SkillDefinition if a solution was found and promoted,\n * or null if no solution was found (caller should fall through to mutation).\n */\nexport async function runAutoResearch(\n failure: FailureTrace,\n task: TaskContext,\n skillsDir?: string\n): Promise<SkillDefinition | null> {\n const researcher = new AutoResearcher(skillsDir);\n\n const candidates = await researcher.research(failure);\n if (candidates.length === 0) {\n return null;\n }\n\n // Try each candidate in order of confidence\n for (const candidate of candidates) {\n const results = await researcher.runSandboxTests(candidate, task);\n const passingRuns = results.filter(r => r.passed).length;\n\n if (passingRuns >= REQUIRED_PASSING_RUNS) {\n const skill = await researcher.promoteToSkill(candidate, results);\n return skill;\n }\n }\n\n // No candidate passed — fall through to mutation engine\n return null;\n}\n","/**\n * ClawPowers Agent — Skill Loader\n * Discovers skills from skill directories, validates SKILL.md frontmatter.\n */\n\nimport { readdirSync, readFileSync, existsSync, statSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { SkillManifest, SkillRequirements, Profile } from '../types.js';\n\n// ─── YAML Frontmatter Parser ──────────────────────────────────────────────────\n\ninterface ParsedFrontmatter {\n name?: string;\n description?: string;\n metadata?: {\n openclaw?: {\n requires?: {\n bins?: string[];\n env?: string[];\n config?: string[];\n };\n };\n };\n}\n\n/**\n * Parse YAML frontmatter from a SKILL.md file content.\n * Expects format: ---\\n<yaml>\\n---\\n<content>\n */\nexport function parseFrontmatter(content: string): ParsedFrontmatter {\n const match = content.match(/^---\\n([\\s\\S]*?)\\n---/);\n if (!match?.[1]) {\n return {};\n }\n\n const yamlText = match[1];\n const result: ParsedFrontmatter = {};\n\n // Simple YAML parser for our known structure\n const lines = yamlText.split('\\n');\n let currentKey = '';\n let inRequires = false;\n let requiresKey = '';\n const requires: { bins?: string[]; env?: string[]; config?: string[] } = {};\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed === '' || trimmed.startsWith('#')) continue;\n\n // Top-level keys\n const topLevel = line.match(/^(\\w+):\\s*(.*)$/);\n if (topLevel?.[1]) {\n currentKey = topLevel[1];\n const val = topLevel[2]?.trim().replace(/^[\"']|[\"']$/g, '') ?? '';\n if (currentKey === 'name' && val) result.name = val;\n if (currentKey === 'description' && val) result.description = val;\n inRequires = false;\n continue;\n }\n\n // metadata.openclaw.requires detection\n if (trimmed === 'openclaw:') continue;\n if (trimmed === 'requires:') {\n inRequires = true;\n continue;\n }\n\n if (inRequires) {\n const reqKey = trimmed.match(/^(\\w+):\\s*(.*)$/);\n if (reqKey?.[1]) {\n requiresKey = reqKey[1];\n // Inline array: bins: [\"node\", \"git\"]\n const inlineArr = reqKey[2]?.match(/\\[(.*)\\]/);\n if (inlineArr?.[1]) {\n const items = inlineArr[1].split(',').map(s => s.trim().replace(/^[\"']|[\"']$/g, ''));\n if (requiresKey === 'bins') requires.bins = items;\n if (requiresKey === 'env') requires.env = items;\n if (requiresKey === 'config') requires.config = items;\n }\n continue;\n }\n // List item under requires key\n const listItem = trimmed.match(/^-\\s*[\"']?(.+?)[\"']?$/);\n if (listItem?.[1] && requiresKey) {\n if (requiresKey === 'bins') {\n requires.bins = requires.bins ?? [];\n requires.bins.push(listItem[1]);\n }\n if (requiresKey === 'env') {\n requires.env = requires.env ?? [];\n requires.env.push(listItem[1]);\n }\n if (requiresKey === 'config') {\n requires.config = requires.config ?? [];\n requires.config.push(listItem[1]);\n }\n }\n }\n }\n\n if (Object.keys(requires).length > 0) {\n result.metadata = { openclaw: { requires } };\n }\n\n return result;\n}\n\n// ─── Skill Discovery ──────────────────────────────────────────────────────────\n\n/**\n * Load a single skill manifest from a directory containing SKILL.md\n */\nexport function loadSkillManifest(skillDir: string): SkillManifest | null {\n const skillMdPath = join(skillDir, 'SKILL.md');\n if (!existsSync(skillMdPath)) {\n return null;\n }\n\n const content = readFileSync(skillMdPath, 'utf-8');\n const frontmatter = parseFrontmatter(content);\n\n if (!frontmatter.name || !frontmatter.description) {\n return null;\n }\n\n let requirements: SkillRequirements | null = null;\n const req = frontmatter.metadata?.openclaw?.requires;\n if (req) {\n requirements = {\n bins: req.bins ?? [],\n env: req.env ?? [],\n config: req.config ?? [],\n };\n }\n\n return {\n name: frontmatter.name,\n description: frontmatter.description,\n path: skillDir,\n requirements,\n };\n}\n\n/**\n * Discover all skills in a directory. Each subdirectory with a valid SKILL.md\n * becomes a skill manifest.\n */\nexport function discoverSkills(skillsDir: string): SkillManifest[] {\n if (!existsSync(skillsDir)) {\n return [];\n }\n\n const entries = readdirSync(skillsDir);\n const manifests: SkillManifest[] = [];\n\n for (const entry of entries) {\n const fullPath = join(skillsDir, entry);\n if (!statSync(fullPath).isDirectory()) continue;\n\n const manifest = loadSkillManifest(fullPath);\n if (manifest) {\n manifests.push(manifest);\n }\n }\n\n return manifests.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * Filter skills based on active profile.\n * Returns only skills that are listed in the profile's skill list.\n */\nexport function getActiveSkills(\n allSkills: SkillManifest[],\n profile: Profile\n): SkillManifest[] {\n const profileSkillSet = new Set(profile.skills);\n return allSkills.filter(skill => profileSkillSet.has(skill.name));\n}\n\n/**\n * List skills with their active/inactive status for a given profile.\n */\nexport function listSkillsWithStatus(\n allSkills: SkillManifest[],\n profile: Profile\n): Array<{ skill: SkillManifest; active: boolean }> {\n const profileSkillSet = new Set(profile.skills);\n return allSkills.map(skill => ({\n skill,\n active: profileSkillSet.has(skill.name),\n }));\n}\n","/**\n * ClawPowers Skills — Skill Executor\n * Execute skills and track outcomes in procedural memory.\n */\n\nimport type { ProceduralMemory } from '../memory/procedural.js';\n\nexport interface SkillExecutionContext {\n readonly taskId: string;\n readonly input: string;\n readonly metadata?: Record<string, unknown>;\n}\n\nexport interface SkillExecutionResult {\n readonly success: boolean;\n readonly output: string;\n readonly durationMs: number;\n readonly error?: string;\n}\n\nexport class SkillExecutor {\n constructor(\n private readonly skillsDir: string,\n private readonly memory: ProceduralMemory\n ) {}\n\n async execute(skillName: string, context: SkillExecutionContext): Promise<SkillExecutionResult> {\n const start = Date.now();\n try {\n const result: SkillExecutionResult = {\n success: true,\n output: `Skill ${skillName} loaded from ${this.skillsDir}`,\n durationMs: Date.now() - start,\n };\n await this.memory.update(skillName, {\n succeeded: true,\n durationMs: result.durationMs,\n taskId: context.taskId,\n });\n return result;\n } catch (err: unknown) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n await this.memory.update(skillName, {\n succeeded: false,\n durationMs: Date.now() - start,\n taskId: context.taskId,\n });\n return {\n success: false,\n output: '',\n durationMs: Date.now() - start,\n error: errorMessage,\n };\n }\n }\n}\n","/**\n * ClawPowers Skills — Wallet Manager\n * High-level wallet management: generate, import, sign, list.\n */\n\nimport { readdir, readFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { WalletConfig, WalletInfo } from './types.js';\nimport { generateWallet, importWallet, signMessage } from './crypto.js';\n\nexport class WalletManager {\n constructor(private readonly config: WalletConfig) {}\n\n async generate(): Promise<WalletInfo> {\n return generateWallet(this.config);\n }\n\n async import(privateKey: string): Promise<WalletInfo> {\n return importWallet(privateKey, this.config);\n }\n\n async sign(message: string, walletInfo: WalletInfo, passphrase: string): Promise<string> {\n const result = await signMessage(message, walletInfo.keyFile, passphrase);\n return result.signature;\n }\n\n async listWallets(): Promise<WalletInfo[]> {\n if (!existsSync(this.config.dataDir)) {\n return [];\n }\n\n const files = await readdir(this.config.dataDir);\n const wallets: WalletInfo[] = [];\n\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n\n try {\n const filePath = join(this.config.dataDir, file);\n const content = await readFile(filePath, 'utf-8');\n const data = JSON.parse(content) as {\n address: string;\n chain: string;\n createdAt: string;\n };\n\n wallets.push({\n address: data.address,\n chain: data.chain,\n createdAt: data.createdAt,\n keyFile: filePath,\n });\n } catch {\n // Skip malformed key files\n }\n }\n\n return wallets;\n }\n}\n","/**\n * ClawPowers Skills — Wallet Crypto\n * Ethereum-oriented wallet generation, import, and signing.\n * Address derivation: secp256k1 public key → Keccak-256 → last 20 bytes (MetaMask-compatible)\n * when Tier 1 (native) or Tier 2 (WASM) is available; legacy hash-of-key digest only on Tier 3.\n */\n\nimport { randomBytes, createCipheriv, createDecipheriv, scryptSync } from 'node:crypto';\nimport { debuglog } from 'node:util';\nimport { writeFile, readFile, mkdir } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport {\n digestForWalletAddress,\n deriveEthereumAddress as deriveEthAddressNative,\n keccak256Digest,\n signEcdsa as signEcdsaNative,\n getActiveTier,\n} from '../native/index.js';\nimport type { WalletConfig, WalletInfo, SignedMessage } from './types.js';\n\nconst dlog = debuglog('clawpowers:wallet');\n\n// ─── Helpers ──────────────────────────────────────────────────────────────────\n\nconst SCRYPT_N = 16384;\nconst SCRYPT_R = 8;\nconst SCRYPT_P = 1;\nconst KEY_LENGTH = 32;\nconst IV_LENGTH = 12;\nconst AUTH_TAG_LENGTH = 16;\n\n/** Tier 3: last 20 bytes of the 32-byte digest as `0x`-prefixed address (legacy). */\nfunction addressFromKeyMaterial(keyMaterial: Buffer): string {\n const digestHex = digestForWalletAddress(keyMaterial);\n const hash = Buffer.from(digestHex.replace(/^0x/, ''), 'hex');\n return '0x' + hash.subarray(hash.length - 20).toString('hex');\n}\n\nfunction deriveKey(passphrase: string, salt: Buffer): Buffer {\n return scryptSync(passphrase, salt, KEY_LENGTH, {\n N: SCRYPT_N,\n r: SCRYPT_R,\n p: SCRYPT_P,\n });\n}\n\ninterface EncryptedKeyFile {\n readonly version: 1;\n readonly address: string;\n readonly chain: string;\n readonly createdAt: string;\n readonly crypto: {\n readonly cipher: 'aes-256-gcm';\n readonly ciphertext: string;\n readonly iv: string;\n readonly authTag: string;\n readonly salt: string;\n readonly scryptParams: {\n readonly N: number;\n readonly r: number;\n readonly p: number;\n };\n };\n}\n\nfunction encryptPrivateKey(privateKey: Buffer, passphrase: string): {\n ciphertext: string;\n iv: string;\n authTag: string;\n salt: string;\n} {\n const salt = randomBytes(32);\n const key = deriveKey(passphrase, salt);\n const iv = randomBytes(IV_LENGTH);\n\n const cipher = createCipheriv('aes-256-gcm', key, iv, { authTagLength: AUTH_TAG_LENGTH });\n const encrypted = Buffer.concat([cipher.update(privateKey), cipher.final()]);\n const authTag = cipher.getAuthTag();\n\n return {\n ciphertext: encrypted.toString('hex'),\n iv: iv.toString('hex'),\n authTag: authTag.toString('hex'),\n salt: salt.toString('hex'),\n };\n}\n\nfunction decryptPrivateKey(\n ciphertext: string,\n iv: string,\n authTag: string,\n salt: string,\n passphrase: string\n): Buffer {\n const key = deriveKey(passphrase, Buffer.from(salt, 'hex'));\n const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(iv, 'hex'), {\n authTagLength: AUTH_TAG_LENGTH,\n });\n decipher.setAuthTag(Buffer.from(authTag, 'hex'));\n\n const decrypted = Buffer.concat([\n decipher.update(Buffer.from(ciphertext, 'hex')),\n decipher.final(),\n ]);\n\n return decrypted;\n}\n\nfunction generateAddress(privateKeyHex: string): string {\n const cleaned = privateKeyHex.replace(/^0x/i, '');\n const privBuf = Buffer.from(cleaned, 'hex');\n const eth = deriveEthAddressNative(privBuf);\n if (eth) {\n dlog('address derivation: secp256k1+keccak (tier %s)', getActiveTier());\n return eth;\n }\n dlog('address derivation: tier3 legacy digest (tier %s)', getActiveTier());\n return addressFromKeyMaterial(privBuf);\n}\n\nasync function ensureDir(dir: string): Promise<void> {\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\n}\n\nasync function signMessageFromKeyFile(\n message: string,\n keyFile: string,\n passphrase: string\n): Promise<SignedMessage> {\n const content = await readFile(keyFile, 'utf-8');\n const keyFileData = JSON.parse(content) as EncryptedKeyFile;\n\n const privateKey = decryptPrivateKey(\n keyFileData.crypto.ciphertext,\n keyFileData.crypto.iv,\n keyFileData.crypto.authTag,\n keyFileData.crypto.salt,\n passphrase\n );\n\n const msgBuf = Buffer.from(message, 'utf8');\n const hash = keccak256Digest(msgBuf);\n const sigEcdsa = hash ? signEcdsaNative(privateKey, hash) : null;\n if (sigEcdsa) {\n dlog('signMessage (keyfile): secp256k1 ECDSA (tier %s)', getActiveTier());\n return {\n message,\n signature: '0x' + sigEcdsa.toString('hex'),\n address: keyFileData.address,\n };\n }\n\n const { createHmac } = await import('node:crypto');\n dlog('signMessage (keyfile): HMAC-SHA256 legacy (no secp256k1/keccak tier)');\n const signature = createHmac('sha256', privateKey).update(message).digest('hex');\n\n return {\n message,\n signature: '0x' + signature,\n address: keyFileData.address,\n };\n}\n\nasync function signMessageFromPrivateKey(privateKeyHex: string, message: string): Promise<string> {\n const cleaned = privateKeyHex.replace(/^0x/i, '');\n if (cleaned.length !== 64 || !/^[0-9a-fA-F]+$/.test(cleaned)) {\n throw new Error('Invalid private key: must be 32 bytes (64 hex characters)');\n }\n const priv = Buffer.from(cleaned, 'hex');\n const hash = keccak256Digest(Buffer.from(message, 'utf8'));\n if (!hash) {\n throw new Error(\n 'Ethereum signing requires Keccak-256 (Tier 1 native or Tier 2 WASM). Pure TypeScript tier has no Keccak.',\n );\n }\n const sig = signEcdsaNative(priv, hash);\n if (!sig) {\n throw new Error('Ethereum signing requires secp256k1 (Tier 1 native or Tier 2 WASM).');\n }\n return '0x' + sig.toString('hex');\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Generate a new Ethereum-compatible wallet.\n * Private key is encrypted with a random passphrase and stored to disk.\n */\nexport async function generateWallet(config: WalletConfig): Promise<WalletInfo> {\n const privateKey = randomBytes(32);\n const privateKeyHex = privateKey.toString('hex');\n const address = generateAddress(privateKeyHex);\n const createdAt = new Date().toISOString();\n\n // Generate a random passphrase for initial encryption\n const passphrase = randomBytes(16).toString('hex');\n\n const encrypted = encryptPrivateKey(privateKey, passphrase);\n\n const keyFileData: EncryptedKeyFile = {\n version: 1,\n address,\n chain: config.chain,\n createdAt,\n crypto: {\n cipher: 'aes-256-gcm',\n ciphertext: encrypted.ciphertext,\n iv: encrypted.iv,\n authTag: encrypted.authTag,\n salt: encrypted.salt,\n scryptParams: { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P },\n },\n };\n\n await ensureDir(config.dataDir);\n const keyFileName = `${address.slice(2, 10)}-${Date.now()}.json`;\n const keyFilePath = join(config.dataDir, keyFileName);\n await writeFile(keyFilePath, JSON.stringify(keyFileData, null, 2) + '\\n', 'utf-8');\n\n return {\n address,\n chain: config.chain,\n createdAt,\n keyFile: keyFilePath,\n };\n}\n\n/**\n * Import an existing wallet from a private key hex string.\n */\nexport async function importWallet(privateKeyHex: string, config: WalletConfig): Promise<WalletInfo> {\n // Validate private key format\n const cleaned = privateKeyHex.replace(/^0x/i, '');\n if (cleaned.length !== 64 || !/^[0-9a-fA-F]+$/.test(cleaned)) {\n throw new Error('Invalid private key: must be 32 bytes (64 hex characters)');\n }\n\n const privateKey = Buffer.from(cleaned, 'hex');\n const address = generateAddress(cleaned);\n const createdAt = new Date().toISOString();\n\n // Generate a random passphrase for encryption\n const passphrase = randomBytes(16).toString('hex');\n\n const encrypted = encryptPrivateKey(privateKey, passphrase);\n\n const keyFileData: EncryptedKeyFile = {\n version: 1,\n address,\n chain: config.chain,\n createdAt,\n crypto: {\n cipher: 'aes-256-gcm',\n ciphertext: encrypted.ciphertext,\n iv: encrypted.iv,\n authTag: encrypted.authTag,\n salt: encrypted.salt,\n scryptParams: { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P },\n },\n };\n\n await ensureDir(config.dataDir);\n const keyFileName = `${address.slice(2, 10)}-${Date.now()}.json`;\n const keyFilePath = join(config.dataDir, keyFileName);\n await writeFile(keyFilePath, JSON.stringify(keyFileData, null, 2) + '\\n', 'utf-8');\n\n return {\n address,\n chain: config.chain,\n createdAt,\n keyFile: keyFilePath,\n };\n}\n\n/**\n * Sign a message using an encrypted key file and passphrase (returns structured result).\n * Uses secp256k1 ECDSA over Keccak-256(UTF-8 message) when native/WASM tiers provide it;\n * otherwise falls back to HMAC-SHA256 for backward compatibility.\n */\nexport async function signMessage(\n message: string,\n keyFile: string,\n passphrase: string,\n): Promise<SignedMessage>;\n\n/**\n * Sign a message with a raw hex private key. Returns 65-byte ECDSA signature (r‖s‖v) as hex.\n * Requires Tier 1 or Tier 2 (Keccak + secp256k1).\n */\nexport async function signMessage(privateKeyHex: string, message: string): Promise<string>;\n\nexport async function signMessage(\n a: string,\n b: string,\n c?: string,\n): Promise<SignedMessage | string> {\n if (c !== undefined) {\n return signMessageFromKeyFile(a, b, c);\n }\n return signMessageFromPrivateKey(a, b);\n}\n","/**\n * ITP TypeScript Client — Identical Twins Protocol\n *\n * Wraps the Python ITP server HTTP API (http://localhost:8100).\n * Provides encode(), decode(), healthCheck() utilities.\n * Falls back gracefully if server not running (returns original message).\n */\n\nconst ITP_BASE_URL = 'http://localhost:8100';\nconst TIMEOUT_MS = 3000;\n\nexport interface EncodeResult {\n encoded: string;\n wasCompressed: boolean;\n savingsPct: number;\n}\n\nexport interface DecodeResult {\n decoded: string;\n wasItp: boolean;\n}\n\ninterface EncodeApiResponse {\n encoded?: string;\n was_compressed?: boolean;\n savings_pct?: number;\n}\n\ninterface DecodeApiResponse {\n decoded?: string;\n was_itp?: boolean;\n}\n\n/**\n * Encode a natural language message using the ITP codebook.\n * If the server is unreachable, returns the original message unchanged.\n */\nexport async function encode(\n message: string,\n sourceAgent?: string,\n): Promise<EncodeResult> {\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);\n\n const response = await fetch(`${ITP_BASE_URL}/tools/encode`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n message,\n source_agent: sourceAgent ?? 'unknown',\n target_agent: 'unknown',\n }),\n signal: controller.signal,\n });\n\n clearTimeout(timeout);\n\n if (!response.ok) {\n return { encoded: message, wasCompressed: false, savingsPct: 0 };\n }\n\n const data = (await response.json()) as EncodeApiResponse;\n return {\n encoded: data.encoded ?? message,\n wasCompressed: Boolean(data.was_compressed),\n savingsPct: typeof data.savings_pct === 'number' ? data.savings_pct : 0,\n };\n } catch {\n // Server unreachable — graceful fallback\n return { encoded: message, wasCompressed: false, savingsPct: 0 };\n }\n}\n\n/**\n * Decode an ITP-encoded message back to natural language.\n * If the server is unreachable, returns the original message unchanged.\n */\nexport async function decode(message: string): Promise<DecodeResult> {\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);\n\n const response = await fetch(`${ITP_BASE_URL}/tools/decode`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ message }),\n signal: controller.signal,\n });\n\n clearTimeout(timeout);\n\n if (!response.ok) {\n return { decoded: message, wasItp: false };\n }\n\n const data = (await response.json()) as DecodeApiResponse;\n return {\n decoded: data.decoded ?? message,\n wasItp: Boolean(data.was_itp),\n };\n } catch {\n // Server unreachable — graceful fallback\n return { decoded: message, wasItp: false };\n }\n}\n\n/**\n * Check if the ITP server is running and healthy.\n */\nexport async function healthCheck(): Promise<boolean> {\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);\n\n const response = await fetch(`${ITP_BASE_URL}/health`, {\n signal: controller.signal,\n });\n\n clearTimeout(timeout);\n return response.ok;\n } catch {\n return false;\n }\n}\n","/**\n * ITP ↔ Swarm Integration Bridge\n *\n * Compresses SwarmTask descriptions before fan-out and\n * decodes SwarmResult content after collection.\n * Graceful fallback — if ITP is unavailable, tasks/results pass through unchanged.\n */\n\nimport type { SwarmTask, SwarmResult } from '../swarm/types.js';\nimport { encode, decode } from './index.js';\n\n/**\n * Encode the task description and message before fan-out to sub-agents.\n * Returns a new SwarmTask with compressed fields (original task is not mutated).\n */\nexport async function encodeTaskDescription(task: SwarmTask): Promise<SwarmTask> {\n try {\n const [descResult, msgResult] = await Promise.all([\n encode(task.description, 'swarm-orchestrator'),\n encode(task.message, 'swarm-orchestrator'),\n ]);\n\n return {\n ...task,\n description: descResult.encoded,\n message: msgResult.encoded,\n };\n } catch {\n // Graceful fallback — return task unchanged\n return task;\n }\n}\n\n/**\n * Decode the result content returned from a sub-agent.\n * Returns a new SwarmResult with decoded fields (original result is not mutated).\n */\nexport async function decodeSwarmResult(result: SwarmResult): Promise<SwarmResult> {\n try {\n if (result.result === null) {\n return result;\n }\n\n const decoded = await decode(result.result);\n\n return {\n ...result,\n result: decoded.decoded,\n };\n } catch {\n // Graceful fallback — return result unchanged\n return result;\n }\n}\n","/**\n * ConcurrencyManager — Bounded parallelism with adaptive throttling.\n *\n * Promise-based semaphore that limits concurrent swarm task execution.\n * Mirrors the Python a0-parallel-swarm-plugin ConcurrencyManager.\n */\n\nexport class ConcurrencyManager {\n private readonly maxConcurrency: number;\n private readonly backpressureThreshold: number;\n private activeCount = 0;\n private throttleDelayMs = 0;\n private lastErrorTime = 0;\n\n // Semaphore queue — each entry is a resolver that grants a slot\n private readonly queue: Array<() => void> = [];\n\n constructor(maxConcurrency = 5, backpressureThreshold = 0.8) {\n this.maxConcurrency = maxConcurrency;\n this.backpressureThreshold = backpressureThreshold;\n }\n\n /**\n * Acquire a concurrency slot. Resolves when a slot is available.\n * Applies throttle delay if rate limits have been hit recently.\n */\n async acquire(): Promise<void> {\n if (this.activeCount < this.maxConcurrency) {\n this.activeCount++;\n } else {\n // Block until a slot is freed\n await new Promise<void>((resolve) => {\n this.queue.push(resolve);\n });\n this.activeCount++;\n }\n\n // Apply throttle delay after acquiring (backpressure)\n if (this.throttleDelayMs > 0) {\n await new Promise<void>((resolve) => setTimeout(resolve, this.throttleDelayMs));\n }\n }\n\n /**\n * Release a concurrency slot. Unblocks next queued waiter if any.\n */\n release(): void {\n this.activeCount = Math.max(0, this.activeCount - 1);\n const next = this.queue.shift();\n if (next) next();\n }\n\n /**\n * Number of currently active tasks.\n */\n get active(): number {\n return this.activeCount;\n }\n\n /**\n * Number of tasks waiting for a slot.\n */\n get pending(): number {\n return this.queue.length;\n }\n\n /**\n * Whether system has capacity for another task.\n */\n hasCapacity(): boolean {\n return this.activeCount < this.maxConcurrency;\n }\n\n /**\n * Increase throttle delay on rate-limit / transient errors.\n * Multiple errors in quick succession cause exponential backoff.\n */\n adaptiveThrottle(_errorType = 'rate_limit'): void {\n const now = Date.now();\n if (now - this.lastErrorTime < 5000) {\n // Multiple errors in <5s — exponential backoff, capped at 30s\n this.throttleDelayMs = Math.min(this.throttleDelayMs * 2 + 500, 30000);\n } else {\n this.throttleDelayMs = 500;\n }\n this.lastErrorTime = now;\n }\n\n /**\n * Gradually reduce throttle delay after a successful operation.\n */\n resetThrottle(): void {\n this.throttleDelayMs = Math.max(0, this.throttleDelayMs - 100);\n }\n\n /**\n * Check if system is above backpressure threshold.\n */\n isUnderPressure(): boolean {\n return this.activeCount / this.maxConcurrency >= this.backpressureThreshold;\n }\n}\n","/**\n * TokenPool — Centralized token budget manager for swarm parallel execution.\n *\n * Enforces a total token budget across all parallel agents via pre-allocation.\n * Single-threaded JS means no locking needed — operations are synchronous.\n *\n * Mirrors the Python a0-parallel-swarm-plugin TokenPool.\n */\n\nimport type { TokenAllocation, TokenUsageReport } from './types.js';\n\nexport class TokenPool {\n readonly totalBudget: number;\n readonly perTaskDefault: number;\n private readonly allocations: Map<string, TokenAllocation> = new Map();\n\n constructor(totalBudget = 100_000, perTaskDefault = 20_000) {\n this.totalBudget = totalBudget;\n this.perTaskDefault = perTaskDefault;\n }\n\n /**\n * Reserve tokens for a task.\n * Returns false if the pool doesn't have enough remaining budget.\n */\n allocate(taskId: string, budget?: number): boolean {\n const requested = budget ?? this.perTaskDefault;\n const currentAllocated = this.totalAllocated();\n if (currentAllocated + requested > this.totalBudget) {\n return false;\n }\n this.allocations.set(taskId, {\n task_id: taskId,\n budget: requested,\n consumed: 0,\n allocated_at: Date.now(),\n });\n return true;\n }\n\n /**\n * Record actual token usage for a task (cumulative).\n */\n consume(taskId: string, tokens: number): void {\n const alloc = this.allocations.get(taskId);\n if (alloc) {\n alloc.consumed += tokens;\n }\n }\n\n /**\n * Free the allocation when a task completes.\n * Returns tokens consumed by that task.\n */\n release(taskId: string): number {\n const alloc = this.allocations.get(taskId);\n this.allocations.delete(taskId);\n return alloc?.consumed ?? 0;\n }\n\n /**\n * Total remaining budget (total - allocated).\n */\n remaining(): number {\n return this.totalBudget - this.totalAllocated();\n }\n\n /**\n * Total tokens consumed across all active tasks.\n */\n consumed(): number {\n let total = 0;\n for (const alloc of this.allocations.values()) {\n total += alloc.consumed;\n }\n return total;\n }\n\n /**\n * Total tokens currently allocated (reserved but not necessarily consumed).\n */\n totalAllocated(): number {\n let total = 0;\n for (const alloc of this.allocations.values()) {\n total += alloc.budget;\n }\n return total;\n }\n\n /**\n * Check if a specific task has exceeded its allocation.\n */\n isTaskOverBudget(taskId: string): boolean {\n const alloc = this.allocations.get(taskId);\n if (!alloc) return false;\n return alloc.consumed >= alloc.budget;\n }\n\n /**\n * Remaining budget for a specific task.\n */\n taskBudgetRemaining(taskId: string): number {\n const alloc = this.allocations.get(taskId);\n if (!alloc) return 0;\n return Math.max(0, alloc.budget - alloc.consumed);\n }\n\n /**\n * Per-task token consumption summary for observability.\n */\n usageReport(): TokenUsageReport {\n const tasks: TokenUsageReport['tasks'] = {};\n let totalConsumed = 0;\n let totalAllocated = 0;\n\n for (const [taskId, alloc] of this.allocations.entries()) {\n tasks[taskId] = {\n budget: alloc.budget,\n consumed: alloc.consumed,\n remaining: Math.max(0, alloc.budget - alloc.consumed),\n over_budget: alloc.consumed >= alloc.budget,\n };\n totalConsumed += alloc.consumed;\n totalAllocated += alloc.budget;\n }\n\n return {\n total_budget: this.totalBudget,\n total_allocated: totalAllocated,\n total_consumed: totalConsumed,\n total_remaining: this.totalBudget - totalAllocated,\n tasks,\n };\n }\n\n /**\n * Clear all allocations (reset between runs).\n */\n reset(): void {\n this.allocations.clear();\n }\n}\n","/**\n * ModelRouter — Complexity classification and model routing for swarm tasks.\n *\n * Provides heuristic-based task complexity classification (no LLM required)\n * and maps complexity tiers to model IDs.\n *\n * Mirrors the Python a0-parallel-swarm-plugin model_router helpers.\n */\n\nimport type { ModelComplexity, SwarmConfig } from './types.js';\n\n// ─── Default Model Map ────────────────────────────────────────────────────────\n\nconst DEFAULT_MODELS: Record<ModelComplexity, string> = {\n simple: 'claude-3-haiku-20240307',\n moderate: 'claude-3-5-sonnet-20241022',\n complex: 'claude-opus-4-5',\n};\n\n// ─── Heuristic Classification ─────────────────────────────────────────────────\n\nconst COMPLEX_KEYWORDS = [\n 'architect', 'design', 'refactor', 'debug complex', 'optimize',\n 'cross-domain', 'integrate multiple', 'security audit', 'performance',\n 'distributed', 'concurrent requests', 'migration', 'system design',\n 'multi-step', 'synthesize', 'reasoning', 'trade-off',\n];\n\nconst SIMPLE_KEYWORDS = [\n 'format', 'list', 'count', 'lookup', 'translate', 'summarize briefly',\n 'extract', 'convert', 'rename', 'simple', 'trivial', 'basic',\n 'fetch', 'get', 'retrieve', 'find the',\n];\n\n/**\n * Classify task complexity using keyword heuristics and description length.\n * Fast — no LLM call required.\n *\n * @param description - Task description to classify\n * @returns ModelComplexity: 'simple' | 'moderate' | 'complex'\n */\nexport function classifyHeuristic(description: string): ModelComplexity {\n const lower = description.toLowerCase();\n\n // Complex keywords take priority\n for (const kw of COMPLEX_KEYWORDS) {\n if (lower.includes(kw)) return 'complex';\n }\n\n // Simple keywords\n for (const kw of SIMPLE_KEYWORDS) {\n if (lower.includes(kw)) return 'simple';\n }\n\n // Length heuristic (chars, not tokens)\n const len = description.length;\n if (len < 100) return 'simple';\n if (len > 500) return 'complex';\n\n return 'moderate';\n}\n\n/**\n * Select the model ID for a given complexity tier.\n * Falls back to default model map if no override is configured.\n *\n * @param complexity - Task complexity tier\n * @param config - Optional SwarmConfig with model overrides\n * @returns Model ID string\n */\nexport function selectModel(complexity: ModelComplexity, config?: SwarmConfig): string {\n const overrides = config?.models ?? {};\n return overrides[complexity] ?? DEFAULT_MODELS[complexity];\n}\n\n/**\n * Auto-classify a list of tasks, assigning complexity if not explicitly set.\n * Tasks with an existing complexity value are left unchanged.\n *\n * @param tasks - Array of tasks with optional complexity fields\n * @returns Map from task ID to resolved complexity\n */\nexport function classifyTasks(\n tasks: Array<{ id: string; description: string; complexity?: ModelComplexity }>,\n): Map<string, ModelComplexity> {\n const result = new Map<string, ModelComplexity>();\n for (const task of tasks) {\n result.set(task.id, task.complexity ?? classifyHeuristic(task.description));\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAuBa,gBA2ZA;AAlbb;AAAA;AAAA;AAuBO,IAAM,iBAA+B;AAAA;AAAA,MAE1C;AAAA,QACE,MAAM;AAAA,QACN,aAAa;AAAA,QACb,QAAQ;AAAA,QACR,UAAU;AAAA,MACZ;AAAA,MACA;AAAA,QACE,MAAM;AAAA,QACN,aAAa;AAAA,QACb,QAAQ;AAAA,QACR,UAAU;AAAA,MACZ;AAAA,MACA;AAAA,QACE,MAAM;AAAA,QACN,aAAa;AAAA,QACb,QAAQ;AAAA,QACR,UAAU;AAAA,MACZ;AAAA,MACA;AAAA,QAC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BAAmB;AAAA,EACvB;AAAA,EAAa;AAAA,EAAU;AAAA,EAAY;AAAA,EAAiB;AAAA,EACpD;AAAA,EAAgB;AAAA,EAAsB;AAAA,EAAkB;AAAA,EACxD;AAAA,EAAe;AAAA,EAAuB;AAAA,EAAa;AAAA,EACnD;AAAA,EAAc;AAAA,EAAc;AAAA,EAAa;AAC3C;AAEA,IAAM,kBAAkB;AAAA,EACtB;AAAA,EAAU;AAAA,EAAQ;AAAA,EAAS;AAAA,EAAU;AAAA,EAAa;AAAA,EAClD;AAAA,EAAW;AAAA,EAAW;AAAA,EAAU;AAAA,EAAU;AAAA,EAAW;AAAA,EACrD;AAAA,EAAS;AAAA,EAAO;AAAA,EAAY;AAC9B;AASO,SAAS,kBAAkB,aAAsC;AACtE,QAAM,QAAQ,YAAY,YAAY;AAGtC,aAAW,MAAM,kBAAkB;AACjC,QAAI,MAAM,SAAS,EAAE,EAAG,QAAO;AAAA,EACjC;AAGA,aAAW,MAAM,iBAAiB;AAChC,QAAI,MAAM,SAAS,EAAE,EAAG,QAAO;AAAA,EACjC;AAGA,QAAM,MAAM,YAAY;AACxB,MAAI,MAAM,IAAK,QAAO;AACtB,MAAI,MAAM,IAAK,QAAO;AAEtB,SAAO;AACT;AAUO,SAAS,YAAY,YAA6B,QAA8B;AACrF,QAAM,YAAY,QAAQ,UAAU,CAAC;AACrC,SAAO,UAAU,UAAU,KAAK,eAAe,UAAU;AAC3D;AASO,SAAS,cACd,OAC8B;AAC9B,QAAM,SAAS,oBAAI,IAA6B;AAChD,aAAW,QAAQ,OAAO;AACxB,WAAO,IAAI,KAAK,IAAI,KAAK,cAAc,kBAAkB,KAAK,WAAW,CAAC;AAAA,EAC5E;AACA,SAAO;AACT;","names":["dirname","join","require","result","existsSync","dirname","readFile","writeFile","mkdir","existsSync","dirname","readFile","writeFile","rename","mkdir","existsSync","join","estimateTokens","readFile","appendFile","mkdir","existsSync","dirname","readFile","appendFile","mkdir","existsSync","dirname","randomUUID","dirname","existsSync","mkdir","randomUUID","readFile","appendFile","randomUUID","readFile","appendFile","mkdir","existsSync","dirname","randomUUID","mkdirSync","existsSync","writeFileSync","join","SKILLS_CATALOG","readFileSync","existsSync","join","readdir","readFile","existsSync","join","randomBytes","writeFile","readFile","mkdir","existsSync","join","randomBytes","existsSync","mkdir","readFile","join","writeFile","existsSync","readdir","join","readFile"]}
|