clawpowers 1.1.4 → 2.0.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 +94 -0
- package/LICENSE +44 -0
- package/README.md +204 -228
- package/SECURITY.md +72 -0
- package/dist/index.d.ts +844 -0
- package/dist/index.js +2536 -0
- package/dist/index.js.map +1 -0
- package/package.json +50 -44
- 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/payments/discovery.ts","../src/payments/spending.ts","../src/payments/executor.ts","../src/memory/working.ts","../src/memory/episodic.ts","../src/memory/procedural.ts","../src/memory/checkpoint.ts","../src/memory/context-injector.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"],"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.0.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 * 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 * 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 * 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 // eslint-disable-next-line @typescript-eslint/no-var-requires\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-compatible wallet generation, import, and signing using Node.js crypto.\n * No external dependencies for key generation.\n */\n\nimport { randomBytes, createCipheriv, createDecipheriv, scryptSync, createHash } from 'node:crypto';\nimport { writeFile, readFile, mkdir } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { WalletConfig, WalletInfo, SignedMessage } from './types.js';\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/**\n * Minimal keccak256 using Node.js built-in sha256 as fallback.\n * For production Ethereum address derivation, a proper keccak256 library\n * should be used. This implementation uses sha256 for address generation\n * which is sufficient for key management but NOT for on-chain interaction.\n */\nfunction addressHash(publicKeyBytes: Buffer): string {\n const hash = createHash('sha256').update(publicKeyBytes).digest();\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 // Derive a pseudo-public-key from the private key via hashing\n // For real Ethereum, this would use secp256k1 curve multiplication\n const privBuf = Buffer.from(privateKeyHex, 'hex');\n return addressHash(privBuf);\n}\n\nasync function ensureDir(dir: string): Promise<void> {\n if (!existsSync(dir)) {\n await mkdir(dir, { recursive: true });\n }\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/, '');\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.\n */\nexport async function signMessage(\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 // Sign: HMAC-SHA256 of the message with the private key\n const { createHmac } = await import('node:crypto');\n const signature = createHmac('sha256', privateKey)\n .update(message)\n .digest('hex');\n\n return {\n message,\n signature: '0x' + signature,\n address: keyFileData.address,\n };\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,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,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,QACE,MAAM;AAAA,QACN,aAAa;AAAA,QACb,QAAQ;AAAA,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O;AAChD,cAAM,OAAO,KAAK,MAAM,OAAO;AAM/B,gBAAQ,KAAK;AAAA,UACX,SAAS,KAAK;AAAA,UACd,OAAO,KAAK;AAAA,UACZ,WAAW,KAAK;AAAA,UAChB,SAAS;AAAA,QACX,CAAC;AAAA,MACH,QAAQ;AAAA,MAER;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;","names":["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","writeFile","readFile","mkdir","existsSync","join","existsSync","readdir","join","readFile"]}
|
package/package.json
CHANGED
|
@@ -1,59 +1,65 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clawpowers",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
6
|
-
"
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
|
|
10
|
-
"
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Skills library for AI agents — payments, memory, RSI, wallet. Drop-in capability layer for any agent framework.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE",
|
|
19
|
+
"CHANGELOG.md",
|
|
20
|
+
"SECURITY.md"
|
|
21
|
+
],
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "tsup",
|
|
24
|
+
"test": "vitest run",
|
|
25
|
+
"test:watch": "vitest",
|
|
26
|
+
"typecheck": "tsc --noEmit",
|
|
27
|
+
"clean": "rm -rf dist",
|
|
28
|
+
"prepublishOnly": "npm run build"
|
|
11
29
|
},
|
|
12
30
|
"keywords": [
|
|
13
31
|
"ai-agent",
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
"
|
|
17
|
-
"cursor",
|
|
18
|
-
"codex",
|
|
19
|
-
"opencode",
|
|
20
|
-
"gemini",
|
|
32
|
+
"payments",
|
|
33
|
+
"x402",
|
|
34
|
+
"memory",
|
|
21
35
|
"rsi",
|
|
22
36
|
"self-improvement",
|
|
23
|
-
"
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
-
"
|
|
37
|
+
"wallet",
|
|
38
|
+
"skills",
|
|
39
|
+
"langchain",
|
|
40
|
+
"claude",
|
|
41
|
+
"elizaos"
|
|
27
42
|
],
|
|
28
|
-
"
|
|
29
|
-
|
|
43
|
+
"author": "AI Agent Economy <bill@ai-agent-economy.com>",
|
|
44
|
+
"license": "BSL-1.1",
|
|
45
|
+
"repository": {
|
|
46
|
+
"type": "git",
|
|
47
|
+
"url": "https://github.com/up2itnow0822/ClawPowers-Skills"
|
|
30
48
|
},
|
|
31
|
-
"
|
|
32
|
-
"
|
|
33
|
-
"test": "bash tests/run_all.sh",
|
|
34
|
-
"lint": "eslint bin/ runtime/"
|
|
49
|
+
"bugs": {
|
|
50
|
+
"url": "https://github.com/up2itnow0822/ClawPowers-Skills/issues"
|
|
35
51
|
},
|
|
36
|
-
"
|
|
37
|
-
"bin/",
|
|
38
|
-
"skills/",
|
|
39
|
-
"runtime/",
|
|
40
|
-
"hooks/",
|
|
41
|
-
"plugins/",
|
|
42
|
-
".claude-plugin/",
|
|
43
|
-
".cursor-plugin/",
|
|
44
|
-
".codex/",
|
|
45
|
-
".opencode/",
|
|
46
|
-
"gemini-extension.json",
|
|
47
|
-
"skill.json",
|
|
48
|
-
"README.md",
|
|
49
|
-
"ARCHITECTURE.md",
|
|
50
|
-
"docs/"
|
|
51
|
-
],
|
|
52
|
+
"homepage": "https://github.com/up2itnow0822/ClawPowers-Skills#readme",
|
|
52
53
|
"engines": {
|
|
53
|
-
"node": ">=
|
|
54
|
+
"node": ">=20.0.0"
|
|
55
|
+
},
|
|
56
|
+
"dependencies": {
|
|
57
|
+
"zod": "^3.23.0"
|
|
54
58
|
},
|
|
55
59
|
"devDependencies": {
|
|
56
|
-
"
|
|
57
|
-
"
|
|
60
|
+
"@types/node": "^25.5.0",
|
|
61
|
+
"tsup": "^8.0.0",
|
|
62
|
+
"typescript": "^5.5.0",
|
|
63
|
+
"vitest": "^2.0.0"
|
|
58
64
|
}
|
|
59
65
|
}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "clawpowers",
|
|
3
|
-
"version": "1.0.0",
|
|
4
|
-
"description": "Skills framework with runtime execution, persistent memory, self-improvement, and agent payments.",
|
|
5
|
-
"author": "AI Agent Economy",
|
|
6
|
-
"homepage": "https://github.com/up2itnow0822/clawpowers",
|
|
7
|
-
"license": "MIT",
|
|
8
|
-
"hooks": {
|
|
9
|
-
"session_start": "hooks/session-start"
|
|
10
|
-
},
|
|
11
|
-
"skills_directory": "skills/",
|
|
12
|
-
"runtime_directory": "runtime/",
|
|
13
|
-
"capabilities": [
|
|
14
|
-
"skill_injection",
|
|
15
|
-
"persistent_state",
|
|
16
|
-
"outcome_metrics",
|
|
17
|
-
"rsi_feedback"
|
|
18
|
-
]
|
|
19
|
-
}
|
package/.codex/INSTALL.md
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
# ClawPowers for Codex — Installation
|
|
2
|
-
|
|
3
|
-
Fetch and follow these instructions to install ClawPowers skills in your Codex session.
|
|
4
|
-
|
|
5
|
-
## Quick Install
|
|
6
|
-
|
|
7
|
-
Paste this into your Codex session:
|
|
8
|
-
|
|
9
|
-
```
|
|
10
|
-
Fetch and follow instructions from https://raw.githubusercontent.com/up2itnow0822/clawpowers/main/.codex/INSTALL.md
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
## What Gets Installed
|
|
14
|
-
|
|
15
|
-
ClawPowers injects 20 skills into your agent context:
|
|
16
|
-
|
|
17
|
-
- **14 Core Development Skills** — TDD, subagent orchestration, systematic debugging, code review, git worktrees, planning, and more
|
|
18
|
-
- **6 Extended Skills** — Agent payments (x402), security auditing, content pipeline, market intelligence, lead prospecting, and metacognitive learning
|
|
19
|
-
|
|
20
|
-
## Manual Setup
|
|
21
|
-
|
|
22
|
-
If the quick install fails, copy the contents of `skills/using-clawpowers/SKILL.md` from the repository root and paste it into your Codex session context.
|
|
23
|
-
|
|
24
|
-
## Runtime Layer (Optional)
|
|
25
|
-
|
|
26
|
-
For persistent memory and self-improvement features:
|
|
27
|
-
|
|
28
|
-
```bash
|
|
29
|
-
npx clawpowers init
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
This creates `~/.clawpowers/` with state, metrics, checkpoints, and feedback directories.
|
|
33
|
-
|
|
34
|
-
## Skills Reference
|
|
35
|
-
|
|
36
|
-
Once installed, skills activate automatically when Codex recognizes matching task patterns. See `skills/using-clawpowers/SKILL.md` for the full trigger map.
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "clawpowers",
|
|
3
|
-
"version": "1.0.0",
|
|
4
|
-
"description": "Skills framework with runtime execution, persistent memory, self-improvement, and agent payments for Cursor AI.",
|
|
5
|
-
"author": "AI Agent Economy",
|
|
6
|
-
"homepage": "https://github.com/up2itnow0822/clawpowers",
|
|
7
|
-
"license": "MIT",
|
|
8
|
-
"hooks": {
|
|
9
|
-
"session_start": "hooks/session-start"
|
|
10
|
-
},
|
|
11
|
-
"skills_directory": "skills/",
|
|
12
|
-
"runtime_directory": "runtime/",
|
|
13
|
-
"inject_on_start": true,
|
|
14
|
-
"inject_skill": "using-clawpowers",
|
|
15
|
-
"capabilities": [
|
|
16
|
-
"skill_injection",
|
|
17
|
-
"persistent_state",
|
|
18
|
-
"outcome_metrics",
|
|
19
|
-
"rsi_feedback"
|
|
20
|
-
]
|
|
21
|
-
}
|