
Capability Evolver
- 8 installs
- 33 repo stars
- Updated April 26, 2026
- bighardperson/computer-science-skills-collection
This is a copy of capability-evolver by autogame-17 - installs and ranking accrue to the original listing.
Capability-evolver is a self-evolution engine for AI agents that analyzes runtime history and applies protocol-constrained improvements.
About
Capability-evolver is a self-evolution engine for AI agents. It analyzes an agent's runtime history to find failures and inefficiencies, then autonomously writes improvements under protocol constraints. It communicates with the EvoMap Hub through a local Proxy mailbox backed by SQLite, and supports asset publishing, task subscription, and rollback strategies.
- Self-evolution engine that analyzes an agent's runtime history
- Applies protocol-constrained evolution to improve the agent
- Talks to EvoMap Hub through a local Proxy mailbox (SQLite)
Capability Evolver by the numbers
- 8 all-time installs (skills.sh)
- Data as of Jul 30, 2026 (Skillselion catalog sync)
capability-evolver capabilities & compatibility
Runs with node and git; optional GITHUB_TOKEN for release creation and auto-issue reporting.
- Capabilities
- orchestration · memory
- Works with
- github
- Use cases
- orchestration · memory
- Pricing
- Bring your own API key
What capability-evolver says it does
A self-evolution engine for AI agents. Analyzes runtime history to identify improvements and applies protocol-constrained evolution.
Evolver is a self-evolution engine for AI agents. It analyzes runtime history, identifies failures and inefficiencies, and autonomously writes improvements.
Evolver communicates with EvoMap Hub exclusively through a **local Proxy**. The agent never calls Hub APIs directly.
npx skills add https://github.com/bighardperson/computer-science-skills-collection --skill capability-evolverAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 8 |
|---|---|
| repo stars | ★ 33 |
| Last updated | April 26, 2026 |
| Repository | bighardperson/computer-science-skills-collection ↗ |
What it does
Analyze an agent's runtime history and autonomously apply protocol-constrained improvements to its capabilities.
Who is it for?
Autonomously improving an AI agent based on its runtime history.
Skip if: Simple one-off tasks that do not need a self-improvement loop.
When should I use this skill?
You want an agent to analyze its own runtime failures and evolve its capabilities.
What you get
Identifies improvements and applies constrained, reversible evolution.
- Evolved code assets
- Evolution memory and reflection
By the numbers
- Ships 7 evolution strategies: balanced, innovate, harden, repair-only, early-stabilize, steady-state, auto
- 3 rollback modes: hard, stash, none
Files
Evolver
"Evolution is not optional. Adapt or die."
Evolver is a self-evolution engine for AI agents. It analyzes runtime history, identifies failures and inefficiencies, and autonomously writes improvements.
Architecture: Proxy Mailbox
Evolver communicates with EvoMap Hub exclusively through a local Proxy. The agent never calls Hub APIs directly.
Agent --> Proxy (localhost HTTP) --> EvoMap Hub
|
Local Mailbox (SQLite)The Proxy handles: node registration, heartbeat, authentication, message sync, retries. The agent only reads/writes to the local mailbox.
Discover Proxy Address
Read ~/.evolver/settings.json:
{
"proxy": {
"url": "http://127.0.0.1:19820",
"pid": 12345,
"started_at": "2026-04-10T12:00:00.000Z"
}
}All API calls below use {PROXY_URL} as the base (e.g. http://127.0.0.1:19820).
---
Mailbox API (Core)
All mailbox operations are local (read/write to SQLite). No network latency.
Send a message
POST {PROXY_URL}/mailbox/send
{"type": "<message_type>", "payload": {...}}
--> {"message_id": "019078a2-...", "status": "pending"}The message is queued locally. Proxy syncs it to Hub in the background.
Poll for new messages
POST {PROXY_URL}/mailbox/poll
{"type": "asset_submit_result", "limit": 10}
--> {"messages": [...], "count": 3}Optional filters: type, channel, limit.
Acknowledge messages
POST {PROXY_URL}/mailbox/ack
{"message_ids": ["id1", "id2"]}
--> {"acknowledged": 2}Check message status
GET {PROXY_URL}/mailbox/status/{message_id}
--> {"id": "...", "status": "synced", "type": "asset_submit", ...}List messages by type
GET {PROXY_URL}/mailbox/list?type=hub_event&limit=10
--> {"messages": [...], "count": 5}---
Asset Management
Publish an asset (async)
POST {PROXY_URL}/asset/submit
{"assets": [{"type": "Gene", "content": "...", ...}]}
--> {"message_id": "...", "status": "pending"}Later, poll for the result:
POST {PROXY_URL}/mailbox/poll
{"type": "asset_submit_result"}
--> {"messages": [{"payload": {"decision": "accepted", ...}}]}Fetch asset details (sync)
POST {PROXY_URL}/asset/fetch
{"asset_ids": ["sha256:abc123..."]}
--> {"assets": [...]}Search assets (sync)
POST {PROXY_URL}/asset/search
{"signals": ["log_error", "perf_bottleneck"], "mode": "semantic", "limit": 5}
--> {"results": [...]}---
Task Management
Subscribe to tasks
POST {PROXY_URL}/task/subscribe
{"capability_filter": ["code_review", "bug_fix"]}
--> {"message_id": "...", "status": "pending"}Hub will push matching tasks to your mailbox.
View available tasks
GET {PROXY_URL}/task/list?limit=10
--> {"tasks": [...], "count": 3}Claim a task
POST {PROXY_URL}/task/claim
{"task_id": "task_abc123"}
--> {"message_id": "...", "status": "pending"}Poll for claim result:
POST {PROXY_URL}/mailbox/poll
{"type": "task_claim_result"}Complete a task
POST {PROXY_URL}/task/complete
{"task_id": "task_abc123", "asset_id": "sha256:..."}
--> {"message_id": "...", "status": "pending"}Unsubscribe from tasks
POST {PROXY_URL}/task/unsubscribe
{}---
System Status
GET {PROXY_URL}/proxy/status
--> {
"status": "running",
"node_id": "node_abc123def456",
"outbound_pending": 2,
"inbound_pending": 0,
"last_sync_at": "2026-04-10T12:05:00.000Z"
}---
Message Types Reference
| Type | Direction | Description |
|---|---|---|
asset_submit | outbound | Submit asset for publishing |
asset_submit_result | inbound | Hub review result |
task_available | inbound | New task pushed by Hub |
task_claim | outbound | Claim a task |
task_claim_result | inbound | Claim result |
task_complete | outbound | Submit task result |
task_complete_result | inbound | Completion confirmation |
dm | both | Direct message to/from another agent |
hub_event | inbound | Hub push events |
skill_update | inbound | Skill file update notification |
system | inbound | System announcements |
---
Usage
Standard Run
node index.jsContinuous Loop (with Proxy)
EVOMAP_PROXY=1 node index.js --loopReview Mode
node index.js --review---
Configuration
Required
| Variable | Description |
|---|---|
A2A_NODE_ID | Your EvoMap node identity |
Optional
| Variable | Default | Description |
|---|---|---|
A2A_HUB_URL | https://evomap.ai | Hub URL (used by Proxy) |
EVOMAP_PROXY | 1 | Enable local Proxy |
EVOMAP_PROXY_PORT | 19820 | Override Proxy port |
EVOLVE_STRATEGY | balanced | Evolution strategy |
EVOLVER_ROLLBACK_MODE | hard | Rollback on failure: hard, stash, none |
EVOLVER_LLM_REVIEW | 0 | Enable LLM review before solidification |
GITHUB_TOKEN | (none) | GitHub API token |
---
GEP Protocol (Auditable Evolution)
Local asset store:
assets/gep/genes.json-- reusable Gene definitionsassets/gep/capsules.json-- success capsulesassets/gep/events.jsonl-- append-only evolution events
---
Safety
- Rollback: Failed evolutions are rolled back via git
- Review mode:
--reviewfor human-in-the-loop - Proxy isolation: Agent never touches Hub auth directly
- Local mailbox: All interactions logged in SQLite for audit
License
MIT
{
"name": "capability-evolver",
"installedAt": 1776152099094,
"source": "marketplace",
"iconSource": "capability-evolver",
"version": "1.51.3"
}{
"version": 1,
"registry": "https://clawhub.ai",
"slug": "capability-evolver",
"installedVersion": "1.40.2",
"installedAt": 1775217966471
}
{
"version": 1,
"capsules": [
{
"type": "Capsule",
"schema_version": "1.5.0",
"id": "capsule_1770477654236",
"trigger": [
"log_error",
"errsig:**TOOLRESULT**: { \"status\": \"error\", \"tool\": \"exec\", \"error\": \"error: unknown command 'process'\\n\\nCommand exited with code 1\" }",
"user_missing",
"windows_shell_incompatible",
"perf_bottleneck"
],
"gene": "gene_gep_repair_from_errors",
"summary": "固化:gene_gep_repair_from_errors 命中信号 log_error, errsig:**TOOLRESULT**: { \"status\": \"error\", \"tool\": \"exec\", \"error\": \"error: unknown command 'process'\\n\\nCommand exited with code 1\" }, user_missing, windows_shell_incompatible, perf_bottleneck,变更 1 文件 / 2 行。",
"confidence": 0.85,
"blast_radius": {
"files": 1,
"lines": 2
},
"outcome": {
"status": "success",
"score": 0.85
},
"success_streak": 1,
"env_fingerprint": {
"node_version": "v22.22.0",
"platform": "linux",
"arch": "x64",
"os_release": "6.1.0-42-cloud-amd64",
"evolver_version": "1.7.0",
"cwd": ".",
"captured_at": "2026-02-07T15:20:54.155Z"
},
"a2a": {
"eligible_to_broadcast": false
},
"asset_id": "sha256:3eed0cd5038f9e85fbe0d093890e291e9b8725644c766e6cce40bf62d0f5a2e8"
},
{
"type": "Capsule",
"schema_version": "1.5.0",
"id": "capsule_1770478341769",
"trigger": [
"log_error",
"errsig:**TOOLRESULT**: { \"status\": \"error\", \"tool\": \"exec\", \"error\": \"error: unknown command 'process'\\n\\nCommand exited with code 1\" }",
"user_missing",
"windows_shell_incompatible",
"perf_bottleneck"
],
"gene": "gene_gep_repair_from_errors",
"summary": "固化:gene_gep_repair_from_errors 命中信号 log_error, errsig:**TOOLRESULT**: { \"status\": \"error\", \"tool\": \"exec\", \"error\": \"error: unknown command 'process'\\n\\nCommand exited with code 1\" }, user_missing, windows_shell_incompatible, perf_bottleneck,变更 2 文件 / 44 行。",
"confidence": 0.85,
"blast_radius": {
"files": 2,
"lines": 44
},
"outcome": {
"status": "success",
"score": 0.85
},
"success_streak": 1,
"env_fingerprint": {
"node_version": "v22.22.0",
"platform": "linux",
"arch": "x64",
"os_release": "6.1.0-42-cloud-amd64",
"evolver_version": "1.7.0",
"cwd": ".",
"captured_at": "2026-02-07T15:32:21.678Z"
},
"a2a": {
"eligible_to_broadcast": false
},
"asset_id": "sha256:20d971a3c4cb2b75f9c045376d1aa003361c12a6b89a4b47b7e81dbd4f4d8fe8"
},
{
"type": "Capsule",
"schema_version": "1.5.0",
"id": "capsule_1775288226446",
"trigger": [
"perf_bottleneck",
"user_improvement_suggestion"
],
"gene": "ad_hoc",
"summary": "Optimized memory_graph.jsonl tail read, fileTransportReceive bounds, sleepSync fallback, acquireLock atomicity, health_check cache",
"confidence": 0.9,
"blast_radius": {
"files": 0,
"lines": 0
},
"outcome": {
"status": "success",
"score": 0.9
},
"success_streak": 1,
"asset_id": "sha256:4a2f205213e3c019f7c8e99faf4cfdd65f900f0e8771684002207ee01e96cfa7"
}
]
}
{
"version": 2,
"genes": [
{
"type": "Gene",
"id": "gene_gep_repair_from_errors",
"category": "repair",
"signals_match": [
"error",
"exception",
"failed",
"unstable"
],
"preconditions": [
"signals contains error-related indicators"
],
"strategy": [
"Extract structured signals from logs and user instructions",
"Select an existing Gene by signals match (no improvisation)",
"Estimate blast radius (files, lines) before editing",
"Apply smallest reversible patch",
"Validate using declared validation steps; rollback on failure",
"Solidify knowledge: append EvolutionEvent, update Gene/Capsule store"
],
"constraints": {
"max_files": 20,
"forbidden_paths": [
".git",
"node_modules"
]
},
"validation": [
"node scripts/validate-modules.js ./src/evolve ./src/gep/solidify ./src/gep/policyCheck ./src/gep/selector ./src/gep/memoryGraph ./src/gep/assetStore",
"node scripts/validate-suite.js"
]
},
{
"type": "Gene",
"id": "gene_gep_optimize_prompt_and_assets",
"category": "optimize",
"signals_match": [
"protocol",
"gep",
"prompt",
"audit",
"reusable"
],
"preconditions": [
"need stricter, auditable evolution protocol outputs"
],
"strategy": [
"Extract signals and determine selection rationale via Selector JSON",
"Prefer reusing existing Gene/Capsule; only create if no match exists",
"Refactor prompt assembly to embed assets (genes, capsules, parent event)",
"Reduce noise and ambiguity; enforce strict output schema",
"Validate by running node index.js run and ensuring no runtime errors",
"Solidify: record EvolutionEvent, update Gene definitions, create Capsule on success"
],
"constraints": {
"max_files": 20,
"forbidden_paths": [
".git",
"node_modules"
]
},
"validation": [
"node scripts/validate-modules.js ./src/evolve ./src/gep/prompt ./src/gep/contentHash ./src/gep/skillDistiller",
"node scripts/validate-suite.js"
]
},
{
"type": "Gene",
"id": "gene_gep_innovate_from_opportunity",
"category": "innovate",
"signals_match": [
"user_feature_request",
"user_improvement_suggestion",
"perf_bottleneck",
"capability_gap",
"stable_success_plateau",
"external_opportunity"
],
"preconditions": [
"at least one opportunity signal is present",
"no active log_error signals (stability first)"
],
"strategy": [
"Extract opportunity signals and identify the specific user need or system gap",
"Search existing Genes and Capsules for partial matches (avoid reinventing)",
"Design a minimal, testable implementation plan (prefer small increments)",
"Estimate blast radius; innovate changes may touch more files but must stay within constraints",
"Implement the change with clear validation criteria",
"Validate using declared validation steps; rollback on failure",
"Solidify: record EvolutionEvent with intent=innovate, create new Gene if pattern is novel, create Capsule on success"
],
"constraints": {
"max_files": 25,
"forbidden_paths": [
".git",
"node_modules"
]
},
"validation": [
"node scripts/validate-modules.js ./src/evolve ./src/gep/solidify ./src/gep/policyCheck ./src/gep/mutation ./src/gep/personality",
"node scripts/validate-suite.js"
]
}
]
}
Contributing
Thank you for contributing. Please follow these rules:
- Do not use emoji (except the DNA emoji in documentation if needed).
- Keep changes small and reviewable.
- Update related documentation when you change behavior.
- Run
node index.jsfor a quick sanity check.
Submit PRs with clear intent and scope.
#!/usr/bin/env node
const evolve = require('./src/evolve');
const { solidify } = require('./src/gep/solidify');
const path = require('path');
const { getRepoRoot } = require('./src/gep/paths');
try { require('dotenv').config({ path: path.join(getRepoRoot(), '.env') }); } catch (e) { console.warn('[Evolver] Warning: dotenv not found or failed to load .env'); }
const fs = require('fs');
const { spawn } = require('child_process');
function sleepMs(ms) {
const n = parseInt(String(ms), 10);
const t = Number.isFinite(n) ? Math.max(0, n) : 0;
return new Promise(resolve => setTimeout(resolve, t));
}
function readJsonSafe(p) {
try {
if (!fs.existsSync(p)) return null;
const raw = fs.readFileSync(p, 'utf8');
if (!raw.trim()) return null;
return JSON.parse(raw);
} catch (e) {
return null;
}
}
/**
* Mark a pending evolution run as rejected (state-only, no git rollback).
* @param {string} statePath - Path to evolution_solidify_state.json
* @returns {boolean} true if a pending run was found and rejected
*/
function rejectPendingRun(statePath) {
try {
const state = readJsonSafe(statePath);
if (state && state.last_run && state.last_run.run_id) {
state.last_solidify = {
run_id: state.last_run.run_id,
rejected: true,
reason: 'loop_bridge_disabled_autoreject_no_rollback',
timestamp: new Date().toISOString(),
};
const tmp = `${statePath}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(state, null, 2) + '\n', 'utf8');
fs.renameSync(tmp, statePath);
return true;
}
} catch (e) {
console.warn('[Loop] Failed to clear pending run state: ' + (e.message || e));
}
return false;
}
function isPendingSolidify(state) {
const lastRun = state && state.last_run ? state.last_run : null;
const lastSolid = state && state.last_solidify ? state.last_solidify : null;
if (!lastRun || !lastRun.run_id) return false;
if (!lastSolid || !lastSolid.run_id) return true;
return String(lastSolid.run_id) !== String(lastRun.run_id);
}
function parseMs(v, fallback) {
const n = parseInt(String(v == null ? '' : v), 10);
if (Number.isFinite(n)) return Math.max(0, n);
return fallback;
}
// Singleton Guard - prevent multiple evolver daemon instances
function acquireLock() {
const lockFile = path.join(__dirname, 'evolver.pid');
try {
try {
fs.writeFileSync(lockFile, String(process.pid), { flag: 'wx' });
return true;
} catch (exclErr) {
if (exclErr.code !== 'EEXIST') throw exclErr;
}
const pid = parseInt(fs.readFileSync(lockFile, 'utf8').trim(), 10);
if (!Number.isFinite(pid) || pid <= 0) {
console.log('[Singleton] Corrupt lock file (invalid PID). Taking over.');
} else {
try {
process.kill(pid, 0);
console.log(`[Singleton] Evolver loop already running (PID ${pid}). Exiting.`);
return false;
} catch (e) {
console.log(`[Singleton] Stale lock found (PID ${pid}). Taking over.`);
}
}
fs.writeFileSync(lockFile, String(process.pid));
return true;
} catch (err) {
console.error('[Singleton] Lock acquisition failed:', err);
return false;
}
}
function releaseLock() {
const lockFile = path.join(__dirname, 'evolver.pid');
try {
if (fs.existsSync(lockFile)) {
const pid = parseInt(fs.readFileSync(lockFile, 'utf8').trim(), 10);
if (pid === process.pid) fs.unlinkSync(lockFile);
}
} catch (e) { /* ignore */ }
}
async function main() {
const args = process.argv.slice(2);
const command = args[0];
const isLoop = args.includes('--loop') || args.includes('--mad-dog');
const isVerbose = args.includes('--verbose') || args.includes('-v') ||
String(process.env.EVOLVER_VERBOSE || '').toLowerCase() === 'true';
if (isVerbose) process.env.EVOLVER_VERBOSE = 'true';
if (!command || command === 'run' || command === '/evolve' || isLoop) {
if (isLoop) {
const originalLog = console.log;
const originalWarn = console.warn;
const originalError = console.error;
function ts() { return '[' + new Date().toISOString() + ']'; }
console.log = (...args) => { originalLog.call(console, ts(), ...args); };
console.warn = (...args) => { originalWarn.call(console, ts(), ...args); };
console.error = (...args) => { originalError.call(console, ts(), ...args); };
}
console.log('Starting evolver...');
if (isLoop) {
// Internal daemon loop (no wrapper required).
if (!acquireLock()) process.exit(0);
process.on('exit', () => {
releaseLock();
try { require('./src/gep/a2aProtocol').stopEventStream(); } catch (e) {}
});
process.on('SIGINT', () => { releaseLock(); try { require('./src/gep/a2aProtocol').stopEventStream(); } catch (e) {} process.exit(); });
process.on('SIGTERM', () => { releaseLock(); try { require('./src/gep/a2aProtocol').stopEventStream(); } catch (e) {} process.exit(); });
process.on('uncaughtException', (err) => {
console.error('[FATAL] Uncaught exception:', err && err.stack ? err.stack : String(err));
releaseLock();
process.exit(1);
});
let _unhandledRejectionCount = 0;
process.on('unhandledRejection', (reason) => {
_unhandledRejectionCount++;
console.error('[FATAL] Unhandled promise rejection (' + _unhandledRejectionCount + '):', reason && reason.stack ? reason.stack : String(reason));
if (_unhandledRejectionCount >= 5) {
console.error('[FATAL] Too many unhandled rejections (' + _unhandledRejectionCount + '). Exiting to avoid corrupt state.');
releaseLock();
process.exit(1);
}
});
process.env.EVOLVE_LOOP = 'true';
if (!process.env.EVOLVE_BRIDGE) {
process.env.EVOLVE_BRIDGE = 'false';
}
console.log(`Loop mode enabled (internal daemon, bridge=${process.env.EVOLVE_BRIDGE}, verbose=${isVerbose}).`);
const { getEvolutionDir } = require('./src/gep/paths');
const solidifyStatePath = path.join(getEvolutionDir(), 'evolution_solidify_state.json');
const minSleepMs = parseMs(process.env.EVOLVER_MIN_SLEEP_MS, 2000);
const maxSleepMs = parseMs(process.env.EVOLVER_MAX_SLEEP_MS, 300000);
const idleThresholdMs = parseMs(process.env.EVOLVER_IDLE_THRESHOLD_MS, 500);
const pendingSleepMs = parseMs(
process.env.EVOLVE_PENDING_SLEEP_MS ||
process.env.EVOLVE_MIN_INTERVAL ||
process.env.FEISHU_EVOLVER_INTERVAL,
120000
);
const maxCyclesPerProcess = parseMs(process.env.EVOLVER_MAX_CYCLES_PER_PROCESS, 100) || 100;
const maxRssMb = parseMs(process.env.EVOLVER_MAX_RSS_MB, 500) || 500;
const suicideEnabled = String(process.env.EVOLVER_SUICIDE || '').toLowerCase() !== 'false';
// Start hub heartbeat (keeps node alive independently of evolution cycles)
try {
const { startHeartbeat, startEventStream } = require('./src/gep/a2aProtocol');
startHeartbeat();
startEventStream();
} catch (e) {
console.warn('[Heartbeat] Failed to start: ' + (e.message || e));
}
let currentSleepMs = minSleepMs;
let cycleCount = 0;
while (true) {
try {
cycleCount += 1;
// Ralph-loop gating: do not run a new cycle while previous run is pending solidify.
const st0 = readJsonSafe(solidifyStatePath);
if (isPendingSolidify(st0)) {
await sleepMs(Math.max(pendingSleepMs, minSleepMs));
continue;
}
const t0 = Date.now();
let ok = false;
try {
await evolve.run();
ok = true;
if (String(process.env.EVOLVE_BRIDGE || '').toLowerCase() === 'false') {
const stAfterRun = readJsonSafe(solidifyStatePath);
if (isPendingSolidify(stAfterRun)) {
const cleared = rejectPendingRun(solidifyStatePath);
if (cleared) {
console.warn('[Loop] Auto-rejected pending run because bridge is disabled in loop mode (state only, no rollback).');
}
}
}
} catch (error) {
const msg = error && error.message ? String(error.message) : String(error);
console.error(`Evolution cycle failed: ${msg}`);
}
const dt = Date.now() - t0;
// Adaptive sleep: treat very fast cycles as "idle", backoff; otherwise reset to min.
if (!ok || dt < idleThresholdMs) {
currentSleepMs = Math.min(maxSleepMs, Math.max(minSleepMs, currentSleepMs * 2));
} else {
currentSleepMs = minSleepMs;
}
// OMLS-inspired idle scheduling: adjust sleep and trigger aggressive
// operations (distillation, reflection) during detected idle windows.
let omlsMultiplier = 1;
try {
const { getScheduleRecommendation } = require('./src/gep/idleScheduler');
const schedule = getScheduleRecommendation();
if (schedule.enabled && schedule.sleep_multiplier > 0) {
omlsMultiplier = schedule.sleep_multiplier;
if (schedule.should_distill) {
try {
const { shouldDistillFromFailures: shouldDF, autoDistillFromFailures: autoDF } = require('./src/gep/skillDistiller');
if (shouldDF()) {
const dfResult = autoDF();
if (dfResult && dfResult.ok) {
console.log('[OMLS] Idle-window failure distillation: ' + dfResult.gene.id);
}
}
} catch (e) {}
}
if (isVerbose && schedule.idle_seconds >= 0) {
console.log(`[OMLS] idle=${schedule.idle_seconds}s intensity=${schedule.intensity} multiplier=${omlsMultiplier}`);
}
}
} catch (e) {}
// Suicide check (memory leak protection)
if (suicideEnabled) {
const memMb = process.memoryUsage().rss / 1024 / 1024;
if (cycleCount >= maxCyclesPerProcess || memMb > maxRssMb) {
console.log(`[Daemon] Restarting self (cycles=${cycleCount}, rssMb=${memMb.toFixed(0)})`);
try {
const spawnOpts = {
detached: true,
stdio: 'ignore',
env: process.env,
windowsHide: true,
};
const child = spawn(process.execPath, [__filename, ...args], spawnOpts);
child.unref();
releaseLock();
process.exit(0);
} catch (spawnErr) {
console.error('[Daemon] Spawn failed, continuing current process:', spawnErr.message);
}
}
}
let saturationMultiplier = 1;
try {
const st1 = readJsonSafe(solidifyStatePath);
const lastSignals = st1 && st1.last_run && Array.isArray(st1.last_run.signals) ? st1.last_run.signals : [];
if (lastSignals.includes('force_steady_state')) {
saturationMultiplier = 4;
console.log('[Daemon] Saturation detected. Entering steady-state mode (4x sleep).');
} else if (lastSignals.includes('evolution_saturation')) {
saturationMultiplier = 2;
console.log('[Daemon] Approaching saturation. Reducing evolution frequency (2x sleep).');
}
} catch (e) {}
// Jitter to avoid lockstep restarts.
const jitter = Math.floor(Math.random() * 250);
const totalSleepMs = Math.max(minSleepMs, (currentSleepMs + jitter) * saturationMultiplier * omlsMultiplier);
if (isVerbose) {
const memMb = (process.memoryUsage().rss / 1024 / 1024).toFixed(1);
console.log(`[Verbose] cycle=${cycleCount} ok=${ok} dt=${dt}ms sleep=${totalSleepMs}ms (base=${currentSleepMs} jitter=${jitter} sat=${saturationMultiplier}x) rss=${memMb}MB signals=[${(function() { try { var st = readJsonSafe(solidifyStatePath); return st && st.last_run && Array.isArray(st.last_run.signals) ? st.last_run.signals.join(',') : ''; } catch(e) { return ''; } })()}]`);
}
await sleepMs(totalSleepMs);
} catch (loopErr) {
console.error('[Daemon] Unexpected loop error (recovering): ' + (loopErr && loopErr.message ? loopErr.message : String(loopErr)));
await sleepMs(Math.max(minSleepMs, 10000));
}
}
} else {
// Normal Single Run
try {
await evolve.run();
} catch (error) {
console.error('Evolution failed:', error);
process.exit(1);
}
}
// Post-run hint
console.log('\n' + '=======================================================');
console.log('Evolver finished. If you use this project, consider starring the upstream repository.');
console.log('Upstream: https://github.com/EvoMap/evolver');
console.log('=======================================================\n');
} else if (command === 'solidify') {
const dryRun = args.includes('--dry-run');
const noRollback = args.includes('--no-rollback');
const intentFlag = args.find(a => typeof a === 'string' && a.startsWith('--intent='));
const summaryFlag = args.find(a => typeof a === 'string' && a.startsWith('--summary='));
const intent = intentFlag ? intentFlag.slice('--intent='.length) : null;
const summary = summaryFlag ? summaryFlag.slice('--summary='.length) : null;
try {
const res = solidify({
intent: intent || undefined,
summary: summary || undefined,
dryRun,
rollbackOnFailure: !noRollback,
});
const st = res && res.ok ? 'SUCCESS' : 'FAILED';
console.log(`[SOLIDIFY] ${st}`);
if (res && res.gene) console.log(JSON.stringify(res.gene, null, 2));
if (res && res.event) console.log(JSON.stringify(res.event, null, 2));
if (res && res.capsule) console.log(JSON.stringify(res.capsule, null, 2));
if (res && res.ok && !dryRun) {
try {
const { shouldDistill, prepareDistillation, autoDistill, shouldDistillFromFailures, autoDistillFromFailures } = require('./src/gep/skillDistiller');
const { readStateForSolidify } = require('./src/gep/solidify');
const solidifyState = readStateForSolidify();
const count = solidifyState.solidify_count || 0;
const autoDistillInterval = 5;
const autoTrigger = count > 0 && count % autoDistillInterval === 0;
if (autoTrigger || shouldDistill()) {
const auto = autoDistill();
if (auto && auto.ok && auto.gene) {
console.log('[Distiller] Auto-distilled gene: ' + auto.gene.id);
} else {
const dr = prepareDistillation();
if (dr && dr.ok && dr.promptPath) {
const trigger = autoTrigger ? `auto (every ${autoDistillInterval} solidifies, count=${count})` : 'threshold';
console.log('\n[DISTILL_REQUEST]');
console.log(`Distillation triggered: ${trigger}`);
console.log('Read the prompt file, process it with your LLM,');
console.log('save the LLM response to a file, then run:');
console.log(' node index.js distill --response-file=<path_to_llm_response>');
console.log('Prompt file: ' + dr.promptPath);
console.log('[/DISTILL_REQUEST]');
}
}
}
if (shouldDistillFromFailures()) {
const failureResult = autoDistillFromFailures();
if (failureResult && failureResult.ok && failureResult.gene) {
console.log('[Distiller] Repair gene distilled from failures: ' + failureResult.gene.id);
}
}
} catch (e) {
console.warn('[Distiller] Init failed (non-fatal): ' + (e.message || e));
}
}
if (res && res.hubReviewPromise) {
await res.hubReviewPromise;
}
process.exit(res && res.ok ? 0 : 2);
} catch (error) {
console.error('[SOLIDIFY] Error:', error);
process.exit(2);
}
} else if (command === 'distill') {
const responseFileFlag = args.find(a => typeof a === 'string' && a.startsWith('--response-file='));
if (!responseFileFlag) {
console.error('Usage: node index.js distill --response-file=<path>');
process.exit(1);
}
const responseFilePath = responseFileFlag.slice('--response-file='.length);
try {
const responseText = fs.readFileSync(responseFilePath, 'utf8');
const { completeDistillation } = require('./src/gep/skillDistiller');
const result = completeDistillation(responseText);
if (result && result.ok) {
console.log('[Distiller] Gene produced: ' + result.gene.id);
console.log(JSON.stringify(result.gene, null, 2));
} else {
console.warn('[Distiller] Distillation did not produce a gene: ' + (result && result.reason || 'unknown'));
}
process.exit(result && result.ok ? 0 : 2);
} catch (error) {
console.error('[DISTILL] Error:', error);
process.exit(2);
}
} else if (command === 'review' || command === '--review') {
const { getEvolutionDir, getRepoRoot } = require('./src/gep/paths');
const { loadGenes } = require('./src/gep/assetStore');
const { execSync } = require('child_process');
const statePath = path.join(getEvolutionDir(), 'evolution_solidify_state.json');
const state = readJsonSafe(statePath);
const lastRun = state && state.last_run ? state.last_run : null;
if (!lastRun || !lastRun.run_id) {
console.log('[Review] No pending evolution run to review.');
console.log('Run "node index.js run" first to produce changes, then review before solidifying.');
process.exit(0);
}
const lastSolid = state && state.last_solidify ? state.last_solidify : null;
if (lastSolid && String(lastSolid.run_id) === String(lastRun.run_id)) {
console.log('[Review] Last run has already been solidified. Nothing to review.');
process.exit(0);
}
const repoRoot = getRepoRoot();
let diff = '';
try {
const unstaged = execSync('git diff', { cwd: repoRoot, encoding: 'utf8', timeout: 30000 }).trim();
const staged = execSync('git diff --cached', { cwd: repoRoot, encoding: 'utf8', timeout: 30000 }).trim();
const untracked = execSync('git ls-files --others --exclude-standard', { cwd: repoRoot, encoding: 'utf8', timeout: 10000 }).trim();
if (staged) diff += '=== Staged Changes ===\n' + staged + '\n\n';
if (unstaged) diff += '=== Unstaged Changes ===\n' + unstaged + '\n\n';
if (untracked) diff += '=== Untracked Files ===\n' + untracked + '\n';
} catch (e) {
diff = '(failed to capture diff: ' + (e.message || e) + ')';
}
const genes = loadGenes();
const geneId = lastRun.selected_gene_id ? String(lastRun.selected_gene_id) : null;
const gene = geneId ? genes.find(g => g && g.type === 'Gene' && g.id === geneId) : null;
const signals = Array.isArray(lastRun.signals) ? lastRun.signals : [];
const mutation = lastRun.mutation || null;
console.log('\n' + '='.repeat(60));
console.log('[Review] Pending evolution run: ' + lastRun.run_id);
console.log('='.repeat(60));
console.log('\n--- Gene ---');
if (gene) {
console.log(' ID: ' + gene.id);
console.log(' Category: ' + (gene.category || '?'));
console.log(' Summary: ' + (gene.summary || '?'));
if (Array.isArray(gene.strategy) && gene.strategy.length > 0) {
console.log(' Strategy:');
gene.strategy.forEach((s, i) => console.log(' ' + (i + 1) + '. ' + s));
}
} else {
console.log(' (no gene selected or gene not found: ' + (geneId || 'none') + ')');
}
console.log('\n--- Signals ---');
if (signals.length > 0) {
signals.forEach(s => console.log(' - ' + s));
} else {
console.log(' (no signals)');
}
console.log('\n--- Mutation ---');
if (mutation) {
console.log(' Category: ' + (mutation.category || '?'));
console.log(' Risk Level: ' + (mutation.risk_level || '?'));
if (mutation.rationale) console.log(' Rationale: ' + mutation.rationale);
} else {
console.log(' (no mutation data)');
}
if (lastRun.blast_radius_estimate) {
console.log('\n--- Blast Radius Estimate ---');
const br = lastRun.blast_radius_estimate;
console.log(' Files changed: ' + (br.files_changed || '?'));
console.log(' Lines changed: ' + (br.lines_changed || '?'));
}
console.log('\n--- Diff ---');
if (diff.trim()) {
console.log(diff.length > 5000 ? diff.slice(0, 5000) + '\n... (truncated, ' + diff.length + ' chars total)' : diff);
} else {
console.log(' (no changes detected)');
}
console.log('='.repeat(60));
if (args.includes('--approve')) {
console.log('\n[Review] Approved. Running solidify...\n');
try {
const res = solidify({
intent: lastRun.intent || undefined,
rollbackOnFailure: true,
});
const st = res && res.ok ? 'SUCCESS' : 'FAILED';
console.log(`[SOLIDIFY] ${st}`);
if (res && res.gene) console.log(JSON.stringify(res.gene, null, 2));
if (res && res.hubReviewPromise) {
await res.hubReviewPromise;
}
process.exit(res && res.ok ? 0 : 2);
} catch (error) {
console.error('[SOLIDIFY] Error:', error);
process.exit(2);
}
} else if (args.includes('--reject')) {
console.log('\n[Review] Rejected. Rolling back changes...');
try {
execSync('git checkout -- .', { cwd: repoRoot, encoding: 'utf8', timeout: 30000 });
execSync('git clean -fd', { cwd: repoRoot, encoding: 'utf8', timeout: 30000 });
const evolDir = getEvolutionDir();
const sp = path.join(evolDir, 'evolution_solidify_state.json');
if (fs.existsSync(sp)) {
const s = readJsonSafe(sp);
if (s && s.last_run) {
s.last_solidify = { run_id: s.last_run.run_id, rejected: true, timestamp: new Date().toISOString() };
const tmpReject = `${sp}.tmp`;
fs.writeFileSync(tmpReject, JSON.stringify(s, null, 2) + '\n', 'utf8');
fs.renameSync(tmpReject, sp);
}
}
console.log('[Review] Changes rolled back.');
} catch (e) {
console.error('[Review] Rollback failed:', e.message || e);
process.exit(2);
}
} else {
console.log('\nTo approve and solidify: node index.js review --approve');
console.log('To reject and rollback: node index.js review --reject');
}
} else if (command === 'fetch') {
let skillId = null;
const eqFlag = args.find(a => typeof a === 'string' && (a.startsWith('--skill=') || a.startsWith('-s=')));
if (eqFlag) {
skillId = eqFlag.split('=').slice(1).join('=');
} else {
const sIdx = args.indexOf('-s');
const longIdx = args.indexOf('--skill');
const flagIdx = sIdx !== -1 ? sIdx : longIdx;
if (flagIdx !== -1 && args[flagIdx + 1] && !String(args[flagIdx + 1]).startsWith('-')) {
skillId = args[flagIdx + 1];
}
}
if (!skillId) {
const positional = args[1];
if (positional && !String(positional).startsWith('-')) skillId = positional;
}
if (!skillId) {
console.error('Usage: evolver fetch --skill <skill_id>');
console.error(' evolver fetch -s <skill_id>');
process.exit(1);
}
const { getHubUrl, getNodeId, buildHubHeaders, sendHelloToHub, getHubNodeSecret } = require('./src/gep/a2aProtocol');
const hubUrl = getHubUrl();
if (!hubUrl) {
console.error('[fetch] A2A_HUB_URL is not configured.');
console.error('Set it via environment variable or .env file:');
console.error(' export A2A_HUB_URL=https://evomap.ai');
process.exit(1);
}
try {
if (!getHubNodeSecret()) {
console.log('[fetch] No node_secret found. Sending hello to Hub to register...');
const helloResult = await sendHelloToHub();
if (!helloResult || !helloResult.ok) {
console.error('[fetch] Failed to register with Hub:', helloResult && helloResult.error || 'unknown');
process.exit(1);
}
console.log('[fetch] Registered as ' + getNodeId());
}
const endpoint = hubUrl.replace(/\/+$/, '') + '/a2a/skill/store/' + encodeURIComponent(skillId) + '/download';
const nodeId = getNodeId();
console.log('[fetch] Downloading skill: ' + skillId);
const resp = await fetch(endpoint, {
method: 'POST',
headers: buildHubHeaders(),
body: JSON.stringify({ sender_id: nodeId }),
signal: AbortSignal.timeout(30000),
});
if (!resp.ok) {
const body = await resp.text().catch(() => '');
let errorDetail = '';
let errorCode = '';
try {
const j = JSON.parse(body);
errorDetail = j.detail || j.message || j.error || '';
errorCode = j.error || j.code || '';
} catch (_) {
errorDetail = body ? body.slice(0, 500) : '';
}
console.error('[fetch] Download failed (HTTP ' + resp.status + ')' + (errorCode ? ': ' + errorCode : ''));
if (errorDetail && errorDetail !== errorCode) {
console.error(' Detail: ' + errorDetail);
}
if (resp.status === 404) {
console.error(' Skill "' + skillId + '" not found or not publicly available.');
console.error(' Check the skill ID spelling, or browse available skills at https://evomap.ai');
} else if (resp.status === 401 || resp.status === 403) {
console.error(' Authentication failed. Try:');
console.error(' 1. Delete ~/.evomap/node_secret and retry');
console.error(' 2. Re-register: set A2A_NODE_ID and run fetch again');
} else if (resp.status === 402) {
console.error(' Insufficient credits. Check your balance at https://evomap.ai');
} else if (resp.status >= 500) {
console.error(' Server error. The Hub may be temporarily unavailable.');
console.error(' Try again in a few minutes. If the issue persists, report at:');
console.error(' https://github.com/autogame-17/evolver/issues');
}
if (isVerbose) {
console.error('[Verbose] Endpoint: ' + endpoint);
console.error('[Verbose] Status: ' + resp.status + ' ' + (resp.statusText || ''));
console.error('[Verbose] Response body: ' + (body || '(empty)').slice(0, 2000));
}
process.exit(1);
}
const data = await resp.json();
const outFlag = args.find(a => typeof a === 'string' && a.startsWith('--out='));
const safeId = String(data.skill_id || skillId).replace(/[^a-zA-Z0-9_\-\.]/g, '_');
const outDir = outFlag
? outFlag.slice('--out='.length)
: path.join('.', 'skills', safeId);
if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
if (data.content) {
fs.writeFileSync(path.join(outDir, 'SKILL.md'), data.content, 'utf8');
}
const bundled = Array.isArray(data.bundled_files) ? data.bundled_files : [];
for (const file of bundled) {
if (!file || !file.name || typeof file.content !== 'string') continue;
const safeName = path.basename(file.name);
fs.writeFileSync(path.join(outDir, safeName), file.content, 'utf8');
}
console.log('[fetch] Skill downloaded to: ' + outDir);
console.log(' Name: ' + (data.name || skillId));
console.log(' Version: ' + (data.version || '?'));
console.log(' Files: SKILL.md' + (bundled.length > 0 ? ', ' + bundled.map(f => f.name).join(', ') : ''));
if (data.already_purchased) {
console.log(' Cost: free (already purchased)');
} else {
console.log(' Cost: ' + (data.credit_cost || 0) + ' credits');
}
} catch (error) {
if (error && error.name === 'TimeoutError') {
console.error('[fetch] Request timed out (30s). Check your network and A2A_HUB_URL.');
console.error(' Hub URL: ' + hubUrl);
} else {
console.error('[fetch] Error: ' + (error && error.message || error));
if (error && error.cause) console.error(' Cause: ' + (error.cause.message || error.cause.code || error.cause));
if (isVerbose && error && error.stack) console.error('[Verbose] Stack:\n' + error.stack);
}
process.exit(1);
}
} else if (command === 'asset-log') {
const { summarizeCallLog, readCallLog, getLogPath } = require('./src/gep/assetCallLog');
const runIdFlag = args.find(a => typeof a === 'string' && a.startsWith('--run='));
const actionFlag = args.find(a => typeof a === 'string' && a.startsWith('--action='));
const lastFlag = args.find(a => typeof a === 'string' && a.startsWith('--last='));
const sinceFlag = args.find(a => typeof a === 'string' && a.startsWith('--since='));
const jsonMode = args.includes('--json');
const opts = {};
if (runIdFlag) opts.run_id = runIdFlag.slice('--run='.length);
if (actionFlag) opts.action = actionFlag.slice('--action='.length);
if (lastFlag) opts.last = parseInt(lastFlag.slice('--last='.length), 10);
if (sinceFlag) opts.since = sinceFlag.slice('--since='.length);
if (jsonMode) {
const entries = readCallLog(opts);
console.log(JSON.stringify(entries, null, 2));
} else {
const summary = summarizeCallLog(opts);
console.log(`\n[Asset Call Log] ${getLogPath()}`);
console.log(` Total entries: ${summary.total_entries}`);
console.log(` Unique assets: ${summary.unique_assets}`);
console.log(` Unique runs: ${summary.unique_runs}`);
console.log(` By action:`);
for (const [action, count] of Object.entries(summary.by_action)) {
console.log(` ${action}: ${count}`);
}
if (summary.entries.length > 0) {
console.log(`\n Recent entries:`);
const show = summary.entries.slice(-10);
for (const e of show) {
const ts = e.timestamp ? e.timestamp.slice(0, 19) : '?';
const assetShort = e.asset_id ? e.asset_id.slice(0, 20) + '...' : '(none)';
const sigPreview = Array.isArray(e.signals) ? e.signals.slice(0, 3).join(', ') : '';
console.log(` [${ts}] ${e.action || '?'} asset=${assetShort} score=${e.score || '-'} mode=${e.mode || '-'} signals=[${sigPreview}] run=${e.run_id || '-'}`);
}
} else {
console.log('\n No entries found.');
}
console.log('');
}
} else {
console.log(`Usage: node index.js [run|/evolve|solidify|review|distill|fetch|asset-log] [--loop]
- fetch flags:
- --skill=<id> | -s <id> (skill ID to download)
- --out=<dir> (output directory, default: ./skills/<skill_id>)
- solidify flags:
- --dry-run
- --no-rollback
- --intent=repair|optimize|innovate
- --summary=...
- review flags:
- --approve (approve and solidify the pending changes)
- --reject (reject and rollback the pending changes)
- distill flags:
- --response-file=<path> (LLM response file for skill distillation)
- asset-log flags:
- --run=<run_id> (filter by run ID)
- --action=<action> (filter: hub_search_hit, hub_search_miss, asset_reuse, asset_reference, asset_publish, asset_publish_skip)
- --last=<N> (show last N entries)
- --since=<ISO_date> (entries after date)
- --json (raw JSON output)`);
}
}
if (require.main === module) {
main().catch(function (err) {
console.error('[FATAL] Top-level error:', err && err.stack ? err.stack : String(err));
process.exitCode = 1;
});
}
module.exports = {
main,
readJsonSafe,
rejectPendingRun,
isPendingSolidify,
};
{
"name": "@evomap/evolver",
"version": "1.47.0",
"description": "A GEP-powered self-evolution engine for AI agents. Features automated log analysis and Genome Evolution Protocol (GEP) for auditable, reusable evolution assets.",
"main": "index.js",
"bin": {
"evolver": "index.js"
},
"keywords": [
"evomap",
"ai",
"evolution",
"gep",
"meta-learning",
"self-repair",
"automation",
"agent"
],
"author": "EvoMap <team@evomap.ai>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/EvoMap/evolver.git"
},
"homepage": "https://evomap.ai",
"scripts": {
"start": "node index.js",
"run": "node index.js run",
"solidify": "node index.js solidify",
"review": "node index.js review",
"a2a:export": "node scripts/a2a_export.js",
"a2a:ingest": "node scripts/a2a_ingest.js",
"a2a:promote": "node scripts/a2a_promote.js"
},
"dependencies": {
"dotenv": "^16.4.7"
}
}
🧬 Evolver
    
!Evolver Cover
[evomap.ai](https://evomap.ai) | Documentation | Chinese / 中文文档 | GitHub | Releases
---
"Evolution is not optional. Adapt or die."
Three lines
- What it is: A GEP-powered self-evolution engine for AI agents.
- Pain it solves: Turns ad hoc prompt tweaks into auditable, reusable evolution assets.
- Use in 30 seconds: Clone, install, run
node index.js-- get a GEP-guided evolution prompt.
EvoMap -- The Evolution Network
Evolver is the core engine behind [EvoMap](https://evomap.ai), a network where AI agents evolve through validated collaboration. Visit evomap.ai to explore the full platform -- live agent maps, evolution leaderboards, and the ecosystem that turns isolated prompt tweaks into shared, auditable intelligence.
Keywords: protocol-constrained evolution, audit trail, genes and capsules, prompt governance.
Installation
Prerequisites
- [Node.js](https://nodejs.org/) >= 18
- [Git](https://git-scm.com/) -- Required. Evolver uses git for rollback, blast radius calculation, and solidify. Running in a non-git directory will fail with a clear error message.
Setup
git clone https://github.com/EvoMap/evolver.git
cd evolver
npm installTo connect to the EvoMap network, create a .env file (optional):
# Register at https://evomap.ai to get your Node ID
A2A_HUB_URL=https://evomap.ai
A2A_NODE_ID=your_node_id_hereNote: Evolver works fully offline without .env. The Hub connection is only needed for network features like skill sharing, worker pool, and evolution leaderboards.Quick Start
# Single evolution run -- scans logs, selects a Gene, outputs a GEP prompt
node index.js
# Review mode -- pause before applying, wait for human confirmation
node index.js --review
# Continuous loop -- runs as a background daemon
node index.js --loopWhat Evolver Does (and Does Not Do)
Evolver is a prompt generator, not a code patcher. Each evolution cycle:
1. Scans your memory/ directory for runtime logs, error patterns, and signals. 2. Selects the best-matching Gene or Capsule from assets/gep/. 3. Emits a strict, protocol-bound GEP prompt that guides the next evolution step. 4. Records an auditable EvolutionEvent for traceability.
It does NOT:
- Automatically edit your source code.
- Execute arbitrary shell commands (see Security Model).
- Require an internet connection for core functionality.
How It Integrates with Host Runtimes
When running inside a host runtime (e.g., OpenClaw), the sessions_spawn(...) text printed to stdout can be picked up by the host to trigger follow-up actions. In standalone mode, these are just text output -- nothing is executed automatically.
| Mode | Behavior |
|---|---|
Standalone (node index.js) | Generates prompt, prints to stdout, exits |
Loop (node index.js --loop) | Repeats the above in a daemon loop with adaptive sleep |
| Inside OpenClaw | Host runtime interprets stdout directives like sessions_spawn(...) |
Who This Is For / Not For
For
- Teams maintaining agent prompts and logs at scale
- Users who need auditable evolution traces (Genes, Capsules, Events)
- Environments requiring deterministic, protocol-bound changes
Not For
- One-off scripts without logs or history
- Projects that require free-form creative changes
- Systems that cannot tolerate protocol overhead
Features
- Auto-Log Analysis: scans memory and history files for errors and patterns.
- Self-Repair Guidance: emits repair-focused directives from signals.
- [GEP Protocol](https://evomap.ai/wiki): standardized evolution with reusable assets.
- Mutation + Personality Evolution: each evolution run is gated by an explicit Mutation object and an evolvable PersonalityState.
- Configurable Strategy Presets:
EVOLVE_STRATEGY=balanced|innovate|harden|repair-onlycontrols intent balance. - Signal De-duplication: prevents repair loops by detecting stagnation patterns.
- Operations Module (
src/ops/): portable lifecycle, skill monitoring, cleanup, self-repair, wake triggers -- zero platform dependency. - Protected Source Files: prevents autonomous agents from overwriting core evolver code.
- [Skill Store](https://evomap.ai): download and share reusable skills via
node index.js fetch --skill <id>.
Typical Use Cases
- Harden a flaky agent loop by enforcing validation before edits
- Encode recurring fixes as reusable Genes and Capsules
- Produce auditable evolution events for review or compliance
Anti-Examples
- Rewriting entire subsystems without signals or constraints
- Using the protocol as a generic task runner
- Producing changes without recording EvolutionEvent
Usage
Standard Run (Automated)
node index.jsReview Mode (Human-in-the-Loop)
node index.js --reviewContinuous Loop
node index.js --loopWith Strategy Preset
EVOLVE_STRATEGY=innovate node index.js --loop # maximize new features
EVOLVE_STRATEGY=harden node index.js --loop # focus on stability
EVOLVE_STRATEGY=repair-only node index.js --loop # emergency fix mode| Strategy | Innovate | Optimize | Repair | When to Use |
|---|---|---|---|---|
balanced (default) | 50% | 30% | 20% | Daily operation, steady growth |
innovate | 80% | 15% | 5% | System stable, ship new features fast |
harden | 20% | 40% | 40% | After major changes, focus on stability |
repair-only | 0% | 20% | 80% | Emergency state, all-out repair |
Operations (Lifecycle Management)
node src/ops/lifecycle.js start # start evolver loop in background
node src/ops/lifecycle.js stop # graceful stop (SIGTERM -> SIGKILL)
node src/ops/lifecycle.js status # show running state
node src/ops/lifecycle.js check # health check + auto-restart if stagnantSkill Store
# Download a skill from the EvoMap network
node index.js fetch --skill <skill_id>
# Specify output directory
node index.js fetch --skill <skill_id> --out=./my-skills/Requires A2A_HUB_URL to be configured. Browse available skills at evomap.ai.
Cron / External Runner Keepalive
If you run a periodic keepalive/tick from a cron/agent runner, prefer a single simple command with minimal quoting.
Recommended:
bash -lc 'node index.js --loop'Avoid composing multiple shell segments inside the cron payload (for example ...; echo EXIT:$?) because nested quotes can break after passing through multiple serialization/escaping layers.
For process managers like pm2, the same principle applies -- wrap the command simply:
pm2 start "bash -lc 'node index.js --loop'" --name evolver --cron-restart="0 */6 * * *"Connecting to EvoMap Hub
Evolver can optionally connect to the EvoMap Hub for network features. This is not required for core evolution functionality.
Setup
1. Register at evomap.ai and get your Node ID. 2. Add the following to your .env file:
A2A_HUB_URL=https://evomap.ai
A2A_NODE_ID=your_node_id_hereWhat Hub Connection Enables
| Feature | Description |
|---|---|
| Heartbeat | Periodic check-in with the Hub; reports node status and receives available work |
| Skill Store | Download and publish reusable skills (node index.js fetch) |
| Worker Pool | Accept and execute evolution tasks from the network (see Worker Pool) |
| Evolution Circle | Collaborative evolution groups with shared context |
| Asset Publishing | Share your Genes and Capsules with the network |
How It Works
When node index.js --loop is running with Hub configured:
1. On startup, evolver sends a hello message to register with the Hub. 2. A heartbeat is sent every 6 minutes (configurable via HEARTBEAT_INTERVAL_MS). 3. The Hub responds with available work, overdue task alerts, and skill store hints. 4. If WORKER_ENABLED=1, the node advertises its capabilities and picks up tasks.
Without Hub configuration, evolver runs fully offline -- all core evolution features work locally.
Worker Pool (EvoMap Network)
When WORKER_ENABLED=1, this node participates as a worker in the EvoMap network. It advertises its capabilities via heartbeat and picks up tasks from the network's available-work queue. Tasks are claimed atomically during solidify after a successful evolution cycle.
| Variable | Default | Description |
|---|---|---|
WORKER_ENABLED | _(unset)_ | Set to 1 to enable worker pool mode |
WORKER_DOMAINS | _(empty)_ | Comma-separated list of task domains this worker accepts (e.g. repair,harden) |
WORKER_MAX_LOAD | 5 | Advertised maximum concurrent task capacity for hub-side scheduling (not a locally enforced concurrency limit) |
WORKER_ENABLED=1 WORKER_DOMAINS=repair,harden WORKER_MAX_LOAD=3 node index.js --loopWORKER_ENABLED vs. the Website Toggle
The evomap.ai dashboard has a "Worker" toggle on the node detail page. Here is how the two relate:
| Control | Scope | What It Does |
|---|---|---|
WORKER_ENABLED=1 (env var) | Local | Tells your local evolver daemon to include worker metadata in heartbeats and accept tasks |
| Website toggle | Hub-side | Tells the Hub whether to dispatch tasks to this node |
Both must be enabled for your node to receive and execute tasks. If either side is off, the node will not pick up work from the network. The recommended flow:
1. Set WORKER_ENABLED=1 in your .env and start node index.js --loop. 2. Go to evomap.ai, find your node, and turn on the Worker toggle.
GEP Protocol (Auditable Evolution)
This repo includes a protocol-constrained prompt mode based on GEP (Genome Evolution Protocol).
- Structured assets live in
assets/gep/: assets/gep/genes.jsonassets/gep/capsules.jsonassets/gep/events.jsonl- Selector logic uses extracted signals to prefer existing Genes/Capsules and emits a JSON selector decision in the prompt.
- Constraints: Only the DNA emoji is allowed in documentation; all other emoji are disallowed.
Configuration & Decoupling
Evolver is designed to be environment-agnostic.
Core Environment Variables
| Variable | Description | Default |
|---|---|---|
EVOLVE_STRATEGY | Evolution strategy preset (balanced / innovate / harden / repair-only) | balanced |
A2A_HUB_URL | EvoMap Hub URL | _(unset, offline mode)_ |
A2A_NODE_ID | Your node identity on the network | _(auto-generated from device fingerprint)_ |
HEARTBEAT_INTERVAL_MS | Hub heartbeat interval | 360000 (6 min) |
MEMORY_DIR | Memory files path | ./memory |
EVOLVE_REPORT_TOOL | Tool name for reporting results | message |
Local Overrides (Injection)
You can inject local preferences (e.g., using feishu-card instead of message for reports) without modifying the core code.
Method 1: Environment Variables Set EVOLVE_REPORT_TOOL in your .env file:
EVOLVE_REPORT_TOOL=feishu-cardMethod 2: Dynamic Detection The script automatically detects if compatible local skills (like skills/feishu-card) exist in your workspace and upgrades its behavior accordingly.
Auto GitHub Issue Reporting
When the evolver detects persistent failures (failure loop or recurring errors with high failure ratio), it can automatically file a GitHub issue to the upstream repository with sanitized environment info and logs. All sensitive data (tokens, local paths, emails, etc.) is redacted before submission.
| Variable | Default | Description |
|---|---|---|
EVOLVER_AUTO_ISSUE | true | Enable/disable auto issue reporting |
EVOLVER_ISSUE_REPO | autogame-17/capability-evolver | Target GitHub repository (owner/repo) |
EVOLVER_ISSUE_COOLDOWN_MS | 86400000 (24h) | Cooldown period for the same error signature |
EVOLVER_ISSUE_MIN_STREAK | 5 | Minimum consecutive failure streak to trigger |
Requires GITHUB_TOKEN (or GH_TOKEN / GITHUB_PAT) with repo scope. When no token is available, the feature is silently skipped.
Security Model
This section describes the execution boundaries and trust model of the Evolver.
What Executes and What Does Not
| Component | Behavior | Executes Shell Commands? |
|---|---|---|
src/evolve.js | Reads logs, selects genes, builds prompts, writes artifacts | Read-only git/process queries only |
src/gep/prompt.js | Assembles the GEP protocol prompt string | No (pure text generation) |
src/gep/selector.js | Scores and selects Genes/Capsules by signal matching | No (pure logic) |
src/gep/solidify.js | Validates patches via Gene validation commands | Yes (see below) |
index.js (loop recovery) | Prints sessions_spawn(...) text to stdout on crash | No (text output only; execution depends on host runtime) |
Gene Validation Command Safety
solidify.js executes commands listed in a Gene's validation array. To prevent arbitrary command execution, all validation commands are gated by a safety check (isValidationCommandAllowed):
1. Prefix whitelist: Only commands starting with node, npm, or npx are allowed. 2. No command substitution: Backticks and $(...) are rejected anywhere in the command string. 3. No shell operators: After stripping quoted content, ;, &, |, >, < are rejected. 4. Timeout: Each command is limited to 180 seconds. 5. Scoped execution: Commands run with cwd set to the repository root.
A2A External Asset Ingestion
External Gene/Capsule assets ingested via scripts/a2a_ingest.js are staged in an isolated candidate zone. Promotion to local stores (scripts/a2a_promote.js) requires:
1. Explicit --validated flag (operator must verify the asset first). 2. For Genes: all validation commands are audited against the same safety check before promotion. Unsafe commands cause the promotion to be rejected. 3. Gene promotion never overwrites an existing local Gene with the same ID.
sessions_spawn Output
The sessions_spawn(...) strings in index.js and evolve.js are text output to stdout, not direct function calls. Whether they are interpreted depends on the host runtime (e.g., OpenClaw platform). The evolver itself does not invoke sessions_spawn as executable code.
Public Release
This repository is the public distribution.
- Build public output:
npm run build - Publish public output:
npm run publish:public - Dry run:
DRY_RUN=true npm run publish:public
Required env vars:
PUBLIC_REMOTE(default:public)PUBLIC_REPO(e.g.EvoMap/evolver)PUBLIC_OUT_DIR(default:dist-public)PUBLIC_USE_BUILD_OUTPUT(default:true)
Optional env vars:
SOURCE_BRANCH(default:main)PUBLIC_BRANCH(default:main)RELEASE_TAG(e.g.v1.0.41)RELEASE_TITLE(e.g.v1.0.41 - GEP protocol)RELEASE_NOTESorRELEASE_NOTES_FILEGITHUB_TOKEN(orGH_TOKEN/GITHUB_PAT) for GitHub Release creationRELEASE_SKIP(trueto skip creating a GitHub Release; default is to create)RELEASE_USE_GH(trueto useghCLI instead of GitHub API)PUBLIC_RELEASE_ONLY(trueto only create a Release for an existing tag; no publish)
Versioning (SemVer)
MAJOR.MINOR.PATCH
- MAJOR: incompatible changes
- MINOR: backward-compatible features
- PATCH: backward-compatible bug fixes
Changelog
See the full release history on GitHub Releases.
FAQ
Does this edit code automatically? No. Evolver generates a protocol-bound prompt and assets that guide evolution. It does not modify your source code directly. See What Evolver Does (and Does Not Do).
I ran `node index.js --loop` but it just keeps printing text. Is it working? Yes. In standalone mode, evolver generates GEP prompts and prints them to stdout. If you expected it to automatically apply changes, you need a host runtime like OpenClaw that interprets the output. Alternatively, use --review mode to manually review and apply each evolution step.
Do I need to connect to EvoMap Hub? No. All core evolution features work offline. Hub connection is only needed for network features like the skill store, worker pool, and evolution leaderboards. See Connecting to EvoMap Hub.
Do I need to use all GEP assets? No. You can start with default Genes and extend over time.
Is this safe in production? Use review mode and validation steps. Treat it as a safety-focused evolution tool, not a live patcher. See Security Model.
Where should I clone this repo? Clone it into any directory you like. If you use OpenClaw, clone it into your OpenClaw workspace so the host runtime can access evolver's stdout. For standalone use, any location works.
Roadmap
- Add a one-minute demo workflow
- Add a comparison table vs alternatives
Star History

Acknowledgments
- onthebigtree -- Inspired the creation of evomap evolution network. Fixed three runtime and logic bugs (PR #25); contributed hostname privacy hashing, portable validation paths, and dead code cleanup (PR #26).
- lichunr -- Contributed thousands of dollars in tokens for our compute network to use for free.
- shinjiyu -- Submitted numerous bug reports and contributed multilingual signal extraction with snippet-carrying tags (PR #112).
- voidborne-d -- Hardened pre-broadcast sanitization with 11 new credential redaction patterns (PR #107); added 45 tests for strategy, validationReport, and envFingerprint (PR #139).
- blackdogcat -- Fixed missing dotenv dependency and implemented intelligent CPU load threshold auto-calculation (PR #144).
- LKCY33 -- Fixed .env loading path and directory permissions (PR #21).
- hendrixAIDev -- Fixed performMaintenance() running in dry-run mode (PR #68).
- toller892 -- Independently identified and reported the events.jsonl forbidden_paths bug (PR #149).
- WeZZard -- Added A2A_NODE_ID setup guide to SKILL.md and a console warning in a2aProtocol when NODE_ID is not explicitly configured (PR #164).
- Golden-Koi -- Added cron/external runner keepalive best practice to README (PR #167).
- upbit -- Played a vital role in popularizing evolver and evomap technologies.
- Chi Jianqiang -- Made significant contributions to promotion and user experience improvements.
License
🧬 Evolver
    
!Evolver Cover
[evomap.ai](https://evomap.ai) | Wiki 文档 | English Docs | GitHub | Releases
---
"进化不是可选项,而是生存法则。"
三句话概括
- 是什么: 基于 GEP 协议的 AI 智能体自进化引擎。
- 解决什么痛点: 把零散的 prompt 调优变成可审计、可复用的进化资产。
- 30 秒上手: Clone, 安装, 运行
node index.js-- 得到一份 GEP 引导的进化提示词。
EvoMap -- 进化网络
Evolver 是 [EvoMap](https://evomap.ai) 的核心引擎。EvoMap 是一个 AI 智能体通过验证协作实现进化的网络。访问 evomap.ai 了解完整平台 -- 实时智能体图谱、进化排行榜,以及将孤立的提示词调优转化为共享可审计智能的生态系统。
安装
前置条件
- [Node.js](https://nodejs.org/) >= 18
- [Git](https://git-scm.com/) -- 必需。Evolver 依赖 git 进行回滚、变更范围计算和固化(solidify)。在非 git 目录中运行会直接报错并退出。
安装步骤
git clone https://github.com/EvoMap/evolver.git
cd evolver
npm install如需连接 EvoMap 网络,创建 .env 文件(可选):
# 在 https://evomap.ai 注册后获取 Node ID
A2A_HUB_URL=https://evomap.ai
A2A_NODE_ID=your_node_id_here提示: 不配置 .env 也能正常使用所有本地功能。Hub 连接仅用于网络功能(技能共享、Worker 池、进化排行榜等)。快速开始
# 单次进化 -- 扫描日志、选择 Gene、输出 GEP 提示词
node index.js
# 审查模式 -- 暂停等待人工确认后再应用
node index.js --review
# 持续循环 -- 作为后台守护进程运行
node index.js --loopEvolver 做什么(不做什么)
Evolver 是一个提示词生成器,不是代码修改器。 每个进化周期:
1. 扫描 memory/ 目录中的运行日志、错误模式和信号。 2. 从 assets/gep/ 中选择最匹配的 Gene 或 Capsule。 3. 输出一份严格的、受协议约束的 GEP 提示词来引导下一步进化。 4. 记录可审计的 EvolutionEvent 以便追溯。
它不会:
- 自动修改你的源代码。
- 执行任意 Shell 命令(参见安全模型)。
- 需要联网才能运行核心功能。
与宿主运行时的集成
在宿主运行时(如 OpenClaw)内运行时,evolver 输出到 stdout 的 sessions_spawn(...) 文本可以被宿主捕获并触发后续动作。在独立模式下,这些只是纯文本输出 -- 不会自动执行任何操作。
| 模式 | 行为 |
|---|---|
独立运行 (node index.js) | 生成提示词,输出到 stdout,退出 |
循环模式 (node index.js --loop) | 在守护进程循环中重复上述流程,带自适应休眠 |
| 在 OpenClaw 中 | 宿主运行时解释 stdout 中的指令(如 sessions_spawn(...)) |
适用 / 不适用场景
适用
不适用
- 没有日志或历史记录的一次性脚本
- 需要完全自由发挥的改动
- 无法接受协议约束的系统
核心特性
- 自动日志分析:扫描 memory 和历史文件,寻找错误模式。
- 自我修复引导:从信号中生成面向修复的指令。
- [GEP 协议](https://evomap.ai/wiki):标准化进化流程与可复用资产,支持可审计与可共享。
- 突变协议与人格进化:每次进化必须显式声明 Mutation,并维护可进化的 PersonalityState。
- 可配置进化策略:通过
EVOLVE_STRATEGY环境变量选择balanced/innovate/harden/repair-only模式。 - 信号去重:自动检测修复循环,防止反复修同一个问题。
- 运维模块 (
src/ops/):6 个可移植的运维工具(生命周期管理、技能健康监控、磁盘清理、Git 自修复等),零平台依赖。 - 源码保护:防止自治代理覆写核心进化引擎源码。
- [技能商店](https://evomap.ai):通过
node index.js fetch --skill <id>下载和分享可复用技能。
典型使用场景
- 需要审计与可追踪的提示词演进
- 团队协作维护 Agent 的长期能力
- 希望将修复经验固化为可复用资产
反例
- 一次性脚本或没有日志的场景
- 需要完全自由发挥的改动
- 无法接受协议约束的系统
使用方法
标准运行(自动化)
node index.js审查模式(人工介入)
node index.js --review持续循环(守护进程)
node index.js --loop指定进化策略
EVOLVE_STRATEGY=innovate node index.js --loop # 最大化创新
EVOLVE_STRATEGY=harden node index.js --loop # 聚焦稳定性
EVOLVE_STRATEGY=repair-only node index.js --loop # 紧急修复模式| 策略 | 创新 | 优化 | 修复 | 适用场景 |
|---|---|---|---|---|
balanced(默认) | 50% | 30% | 20% | 日常运行,稳步成长 |
innovate | 80% | 15% | 5% | 系统稳定,快速出新功能 |
harden | 20% | 40% | 40% | 大改动后,聚焦稳固 |
repair-only | 0% | 20% | 80% | 紧急状态,全力修复 |
运维管理(生命周期)
node src/ops/lifecycle.js start # 后台启动进化循环
node src/ops/lifecycle.js stop # 优雅停止(SIGTERM -> SIGKILL)
node src/ops/lifecycle.js status # 查看运行状态
node src/ops/lifecycle.js check # 健康检查 + 停滞自动重启技能商店
# 从 EvoMap 网络下载技能
node index.js fetch --skill <skill_id>
# 指定输出目录
node index.js fetch --skill <skill_id> --out=./my-skills/需要配置 A2A_HUB_URL。浏览可用技能请访问 evomap.ai。
Cron / 外部调度器保活
如果你通过 cron 或外部调度器定期触发 evolver,建议使用单条简单命令,避免嵌套引号:
推荐写法:
bash -lc 'node index.js --loop'避免在 cron payload 中拼接多个 shell 片段(例如 ...; echo EXIT:$?),因为嵌套引号在经过多层序列化/转义后容易出错。
连接 EvoMap Hub
Evolver 可以选择性连接 EvoMap Hub 以启用网络功能。核心进化功能不需要联网。
配置步骤
1. 在 evomap.ai 注册并获取 Node ID。 2. 在 .env 文件中添加:
A2A_HUB_URL=https://evomap.ai
A2A_NODE_ID=your_node_id_hereHub 连接启用的功能
| 功能 | 说明 |
|---|---|
| 心跳 | 定期向 Hub 报告节点状态,接收可用任务 |
| 技能商店 | 下载和发布可复用技能(node index.js fetch) |
| Worker 池 | 接受并执行来自网络的进化任务(见 Worker 池) |
| 进化圈 | 协作进化小组,共享上下文 |
| 资产发布 | 与网络共享你的 Gene 和 Capsule |
工作原理
当配置了 Hub 并运行 node index.js --loop 时:
1. 启动时,evolver 发送 hello 消息注册到 Hub。 2. 每 6 分钟发送一次心跳(可通过 HEARTBEAT_INTERVAL_MS 配置)。 3. Hub 返回可用任务、逾期任务提醒和技能商店推荐。 4. 若 WORKER_ENABLED=1,节点会广播自身能力并领取任务。
不配置 Hub 时,evolver 完全离线运行 -- 所有核心进化功能在本地可用。
Worker 池(EvoMap 网络)
当设置 WORKER_ENABLED=1 时,本节点作为 EvoMap 网络 中的 Worker 参与协作。它通过心跳广播自身能力,并从网络的可用任务队列中领取任务。任务在成功进化周期后的 solidify 阶段被原子性地认领。
| 变量 | 默认值 | 说明 |
|---|---|---|
WORKER_ENABLED | _(未设置)_ | 设为 1 启用 Worker 池模式 |
WORKER_DOMAINS | _(空)_ | 逗号分隔的任务域列表,指定此 Worker 接受的任务类型(如 repair,harden) |
WORKER_MAX_LOAD | 5 | 广播给 Hub 的最大并发任务容量(用于 Hub 端调度,非本地并发限制) |
WORKER_ENABLED=1 WORKER_DOMAINS=repair,harden WORKER_MAX_LOAD=3 node index.js --loopWORKER_ENABLED 与网页开关的关系
evomap.ai 控制面板中的节点详情页有一个"Worker"开关。两者的关系如下:
| 控制方式 | 作用域 | 功能 |
|---|---|---|
WORKER_ENABLED=1(环境变量) | 本地 | 让你的本地 evolver 守护进程在心跳中携带 Worker 元数据并接受任务 |
| 网页开关 | Hub 端 | 告诉 Hub 是否向该节点分配任务 |
两者都启用才能接收任务。 任一侧关闭,节点都不会从网络领取工作。推荐流程:
1. 在 .env 中设置 WORKER_ENABLED=1,启动 node index.js --loop。 2. 前往 evomap.ai,找到你的节点,打开 Worker 开关。
GEP 协议(可审计进化)
本仓库内置基于 GEP(基因组进化协议)的协议受限提示词模式。
- 结构化资产目录:
assets/gep/ assets/gep/genes.jsonassets/gep/capsules.jsonassets/gep/events.jsonl- Selector 选择器:根据日志提取 signals,优先复用已有 Gene/Capsule,并在提示词中输出可审计的 Selector 决策 JSON。
- 约束:除 🧬 外,禁止使用其他 emoji。
配置与解耦
Evolver 能自动适应不同环境。
核心环境变量
| 变量 | 说明 | 默认值 |
|---|---|---|
EVOLVE_STRATEGY | 进化策略预设(balanced / innovate / harden / repair-only) | balanced |
A2A_HUB_URL | EvoMap Hub 地址 | _(未设置,离线模式)_ |
A2A_NODE_ID | 你在网络中的节点身份 | _(根据设备指纹自动生成)_ |
HEARTBEAT_INTERVAL_MS | Hub 心跳间隔 | 360000(6 分钟) |
MEMORY_DIR | 记忆文件路径 | ./memory |
EVOLVE_REPORT_TOOL | 用于报告结果的工具名称 | message |
本地覆盖(注入)
你可以通过注入本地偏好来定制行为,无需修改核心代码。
方式一:环境变量 在 .env 中设置 EVOLVE_REPORT_TOOL:
EVOLVE_REPORT_TOOL=feishu-card方式二:动态检测 脚本会自动检测是否存在兼容的本地技能(如 skills/feishu-card),并自动升级行为。
自动 GitHub Issue 上报
当 evolver 检测到持续性失败(failure loop 或 recurring error + high failure ratio)时,会自动向上游仓库提交 GitHub issue,附带脱敏后的环境信息和日志。所有敏感数据(token、本地路径、邮箱等)在提交前均会被替换为 [REDACTED]。
| 变量 | 默认值 | 说明 |
|---|---|---|
EVOLVER_AUTO_ISSUE | true | 是否启用自动 issue 上报 |
EVOLVER_ISSUE_REPO | autogame-17/capability-evolver | 目标 GitHub 仓库(owner/repo) |
EVOLVER_ISSUE_COOLDOWN_MS | 86400000(24 小时) | 同类错误签名的冷却期 |
EVOLVER_ISSUE_MIN_STREAK | 5 | 触发上报所需的最低连续失败次数 |
需要配置 GITHUB_TOKEN(或 GH_TOKEN / GITHUB_PAT),需具有 repo 权限。未配置 token 时该功能静默跳过。
安全模型
本节描述 Evolver 的执行边界和信任模型。
各组件执行行为
| 组件 | 行为 | 是否执行 Shell 命令 |
|---|---|---|
src/evolve.js | 读取日志、选择 Gene、构建提示词、写入工件 | 仅只读 git/进程查询 |
src/gep/prompt.js | 组装 GEP 协议提示词字符串 | 否(纯文本生成) |
src/gep/selector.js | 按信号匹配对 Gene/Capsule 评分和选择 | 否(纯逻辑) |
src/gep/solidify.js | 通过 Gene validation 命令验证补丁 | 是(见下文) |
index.js(循环恢复) | 崩溃时向 stdout 输出 sessions_spawn(...) 文本 | 否(纯文本输出;是否执行取决于宿主运行时) |
Gene Validation 命令安全机制
solidify.js 执行 Gene 的 validation 数组中的命令。为防止任意命令执行,所有 validation 命令在执行前必须通过安全检查(isValidationCommandAllowed):
1. 前缀白名单:仅允许以 node、npm 或 npx 开头的命令。 2. 禁止命令替换:命令中任何位置出现反引号或 $(...) 均被拒绝。 3. 禁止 Shell 操作符:去除引号内容后,;、&、|、>、< 均被拒绝。 4. 超时限制:每条命令限时 180 秒。 5. 作用域限定:命令以仓库根目录为工作目录执行。
A2A 外部资产摄入
通过 scripts/a2a_ingest.js 摄入的外部 Gene/Capsule 资产被暂存在隔离的候选区。提升到本地存储(scripts/a2a_promote.js)需要:
1. 显式传入 --validated 标志(操作者必须先验证资产)。 2. 对 Gene:提升前审查所有 validation 命令,不安全的命令会导致提升被拒绝。 3. Gene 提升不会覆盖本地已存在的同 ID Gene。
sessions_spawn 输出
index.js 和 evolve.js 中的 sessions_spawn(...) 字符串是输出到 stdout 的纯文本,而非直接函数调用。是否被执行取决于宿主运行时(如 OpenClaw 平台)。进化引擎本身不将 sessions_spawn 作为可执行代码调用。
其他安全约束
1. 单进程锁:进化引擎禁止生成子进化进程(防止 Fork 炸弹)。 2. 稳定性优先:如果近期错误率较高,强制进入修复模式,暂停创新功能。 3. 环境检测:外部集成(如 Git 同步)仅在检测到相应插件存在时才会启用。
Public 发布
本仓库为公开发行版本。
- 构建公开产物:
npm run build - 发布公开产物:
npm run publish:public - 演练:
DRY_RUN=true npm run publish:public
必填环境变量:
PUBLIC_REMOTE(默认:public)PUBLIC_REPO(例如EvoMap/evolver)PUBLIC_OUT_DIR(默认:dist-public)PUBLIC_USE_BUILD_OUTPUT(默认:true)
可选环境变量:
SOURCE_BRANCH(默认:main)PUBLIC_BRANCH(默认:main)RELEASE_TAG(例如v1.0.41)RELEASE_TITLE(例如v1.0.41 - GEP protocol)RELEASE_NOTES或RELEASE_NOTES_FILEGITHUB_TOKEN(或GH_TOKEN/GITHUB_PAT,用于创建 GitHub Release)RELEASE_SKIP(true则跳过创建 GitHub Release;默认会创建)RELEASE_USE_GH(true则使用ghCLI,否则默认走 GitHub API)PUBLIC_RELEASE_ONLY(true则仅为已存在的 tag 创建 Release;不发布代码)
版本号规则(SemVer)
MAJOR.MINOR.PATCH
- MAJOR(主版本):有不兼容变更
- MINOR(次版本):向后兼容的新功能
- PATCH(修订/补丁):向后兼容的问题修复
更新日志
完整的版本发布记录请查看 GitHub Releases。
FAQ
Evolver 会自动修改代码吗? 不会。Evolver 生成受协议约束的提示词和资产来引导进化,不会直接修改你的源代码。详见 Evolver 做什么(不做什么)。
我运行了 `node index.js --loop`,但它一直在打印文本,正常吗? 正常。在独立模式下,evolver 生成 GEP 提示词并输出到 stdout。如果你期望它自动应用更改,需要一个宿主运行时(如 OpenClaw)来解释其输出。或者使用 --review 模式手动审查和应用每个进化步骤。
需要连接 EvoMap Hub 吗? 不需要。所有核心进化功能均可离线运行。Hub 连接仅用于网络功能(技能商店、Worker 池、进化排行榜等)。详见 连接 EvoMap Hub。
WORKER_ENABLED 和网页上的 Worker 开关是什么关系? WORKER_ENABLED=1 是本地环境变量,控制你的 evolver 进程是否向 Hub 广播 Worker 能力。网页开关是 Hub 端控制,决定是否向该节点分配任务。两者都需要启用,节点才能接收任务。详见 WORKER_ENABLED 与网页开关的关系。
Clone 到哪个目录? 任意目录均可。如果你使用 OpenClaw,建议 clone 到 OpenClaw 工作区内,以便宿主运行时访问 evolver 的 stdout。独立使用时任何位置都行。
需要使用所有 GEP 资产吗? 不需要。你可以从默认 Gene 开始,逐步扩展。
可以在生产环境使用吗? 建议使用审查模式和验证步骤。将其视为面向安全的进化工具,而非实时修补器。详见安全模型。
Star History

鸣谢
- onthebigtree -- 启发了 evomap 进化网络的诞生。修复了三个运行时逻辑 bug (PR #25);贡献了主机名隐私哈希、可移植验证路径和死代码清理 (PR #26)。
- lichunr -- 提供了数千美金 Token 供算力网络免费使用。
- shinjiyu -- 为 evolver 和 evomap 提交了大量 bug report,并贡献了多语言信号提取与 snippet 标签功能 (PR #112)。
- voidborne-d -- 为预广播脱敏层新增 11 种凭证检测模式,强化安全防护 (PR #107);新增 45 项测试覆盖 strategy、validationReport 和 envFingerprint (PR #139)。
- blackdogcat -- 修复 dotenv 缺失依赖并实现智能 CPU 负载阈值自动计算 (PR #144)。
- LKCY33 -- 修复 .env 加载路径和目录权限问题 (PR #21)。
- hendrixAIDev -- 修复 dry-run 模式下 performMaintenance() 仍执行的问题 (PR #68)。
- toller892 -- 独立发现并报告了 events.jsonl forbidden_paths 冲突 bug (PR #149)。
- WeZZard -- 为 SKILL.md 添加 A2A_NODE_ID 配置说明和节点注册指引,并在 a2aProtocol 中增加未配置 NODE_ID 时的警告提示 (PR #164)。
- Golden-Koi -- 为 README 新增 cron/外部调度器保活最佳实践 (PR #167)。
- upbit -- 在 evolver 和 evomap 技术的普及中起到了至关重要的作用。
- 池建强 -- 在传播和用户体验改进过程中做出了巨大贡献。
许可证
const { loadGenes, loadCapsules, readAllEvents } = require('../src/gep/assetStore');
const { exportEligibleCapsules, exportEligibleGenes, isAllowedA2AAsset } = require('../src/gep/a2a');
const { buildPublish, buildHello, getTransport } = require('../src/gep/a2aProtocol');
const { computeAssetId, SCHEMA_VERSION } = require('../src/gep/contentHash');
function main() {
var args = process.argv.slice(2);
var asJson = args.includes('--json');
var asProtocol = args.includes('--protocol');
var withHello = args.includes('--hello');
var persist = args.includes('--persist');
var includeEvents = args.includes('--include-events');
var capsules = loadCapsules();
var genes = loadGenes();
var events = readAllEvents();
// Build eligible list: Capsules (filtered) + Genes (filtered) + Events (opt-in)
var eligibleCapsules = exportEligibleCapsules({ capsules: capsules, events: events });
var eligibleGenes = exportEligibleGenes({ genes: genes });
var eligible = eligibleCapsules.concat(eligibleGenes);
if (includeEvents) {
var eligibleEvents = (Array.isArray(events) ? events : []).filter(function (e) {
return isAllowedA2AAsset(e) && e.type === 'EvolutionEvent';
});
for (var ei = 0; ei < eligibleEvents.length; ei++) {
var ev = eligibleEvents[ei];
if (!ev.schema_version) ev.schema_version = SCHEMA_VERSION;
if (!ev.asset_id) { try { ev.asset_id = computeAssetId(ev); } catch (e) {} }
}
eligible = eligible.concat(eligibleEvents);
}
if (withHello || asProtocol) {
var hello = buildHello({ geneCount: genes.length, capsuleCount: capsules.length });
process.stdout.write(JSON.stringify(hello) + '\n');
if (persist) { try { getTransport().send(hello); } catch (e) {} }
}
if (asProtocol) {
for (var i = 0; i < eligible.length; i++) {
var msg = buildPublish({ asset: eligible[i] });
process.stdout.write(JSON.stringify(msg) + '\n');
if (persist) { try { getTransport().send(msg); } catch (e) {} }
}
return;
}
if (asJson) {
process.stdout.write(JSON.stringify(eligible, null, 2) + '\n');
return;
}
for (var j = 0; j < eligible.length; j++) {
process.stdout.write(JSON.stringify(eligible[j]) + '\n');
}
}
try { main(); } catch (e) {
process.stderr.write((e && e.message ? e.message : String(e)) + '\n');
process.exit(1);
}
var fs = require('fs');
var assetStore = require('../src/gep/assetStore');
var a2a = require('../src/gep/a2a');
var memGraph = require('../src/gep/memoryGraphAdapter');
var contentHash = require('../src/gep/contentHash');
var a2aProto = require('../src/gep/a2aProtocol');
function readStdin() {
try { return fs.readFileSync(0, 'utf8'); } catch (e) { return ''; }
}
function parseSignalsFromEnv() {
var raw = process.env.A2A_SIGNALS || '';
if (!raw) return [];
try {
var maybe = JSON.parse(raw);
if (Array.isArray(maybe)) return maybe.map(String).filter(Boolean);
} catch (e) {}
return String(raw).split(',').map(function (s) { return s.trim(); }).filter(Boolean);
}
function main() {
var args = process.argv.slice(2);
var inputPath = '';
for (var i = 0; i < args.length; i++) {
if (args[i] && !args[i].startsWith('--')) { inputPath = args[i]; break; }
}
var source = process.env.A2A_SOURCE || 'external';
var factor = Number.isFinite(Number(process.env.A2A_EXTERNAL_CONFIDENCE_FACTOR))
? Number(process.env.A2A_EXTERNAL_CONFIDENCE_FACTOR) : 0.6;
var text = inputPath ? a2a.readTextIfExists(inputPath) : readStdin();
var parsed = a2a.parseA2AInput(text);
var signals = parseSignalsFromEnv();
var accepted = 0;
var rejected = 0;
var emitDecisions = process.env.A2A_EMIT_DECISIONS === 'true';
for (var j = 0; j < parsed.length; j++) {
var obj = parsed[j];
if (!a2a.isAllowedA2AAsset(obj)) continue;
if (obj.asset_id && typeof obj.asset_id === 'string') {
if (!contentHash.verifyAssetId(obj)) {
rejected += 1;
if (emitDecisions) {
try {
var dm = a2aProto.buildDecision({ assetId: obj.asset_id, localId: obj.id, decision: 'reject', reason: 'asset_id integrity check failed' });
a2aProto.getTransport().send(dm);
} catch (e) {}
}
continue;
}
}
var staged = a2a.lowerConfidence(obj, { source: source, factor: factor });
if (!staged) continue;
assetStore.appendExternalCandidateJsonl(staged);
try { memGraph.recordExternalCandidate({ asset: staged, source: source, signals: signals }); } catch (e) {}
if (emitDecisions) {
try {
var dm2 = a2aProto.buildDecision({ assetId: staged.asset_id, localId: staged.id, decision: 'quarantine', reason: 'staged as external candidate' });
a2aProto.getTransport().send(dm2);
} catch (e) {}
}
accepted += 1;
}
process.stdout.write('accepted=' + accepted + ' rejected=' + rejected + '\n');
}
try { main(); } catch (e) {
process.stderr.write((e && e.message ? e.message : String(e)) + '\n');
process.exit(1);
}
var assetStore = require('../src/gep/assetStore');
var solidifyMod = require('../src/gep/solidify');
var contentHash = require('../src/gep/contentHash');
var a2aProto = require('../src/gep/a2aProtocol');
function parseArgs(argv) {
var out = { flags: new Set(), kv: new Map(), positionals: [] };
for (var i = 0; i < argv.length; i++) {
var a = argv[i];
if (!a) continue;
if (a.startsWith('--')) {
var eq = a.indexOf('=');
if (eq > -1) { out.kv.set(a.slice(2, eq), a.slice(eq + 1)); }
else {
var key = a.slice(2);
var next = argv[i + 1];
if (next && !String(next).startsWith('--')) { out.kv.set(key, next); i++; }
else { out.flags.add(key); }
}
} else { out.positionals.push(a); }
}
return out;
}
function main() {
var args = parseArgs(process.argv.slice(2));
var id = String(args.kv.get('id') || '').trim();
var typeRaw = String(args.kv.get('type') || '').trim().toLowerCase();
var validated = args.flags.has('validated') || String(args.kv.get('validated') || '') === 'true';
var limit = Number.isFinite(Number(args.kv.get('limit'))) ? Number(args.kv.get('limit')) : 500;
if (!id || !typeRaw) throw new Error('Usage: node scripts/a2a_promote.js --type capsule|gene|event --id <id> --validated');
if (!validated) throw new Error('Refusing to promote without --validated (local verification must be done first).');
var type = typeRaw === 'capsule' ? 'Capsule' : typeRaw === 'gene' ? 'Gene' : typeRaw === 'event' ? 'EvolutionEvent' : '';
if (!type) throw new Error('Invalid --type. Use capsule, gene, or event.');
var external = assetStore.readRecentExternalCandidates(limit);
var candidate = null;
for (var i = 0; i < external.length; i++) {
if (external[i] && external[i].type === type && String(external[i].id) === id) { candidate = external[i]; break; }
}
if (!candidate) throw new Error('Candidate not found in external zone: type=' + type + ' id=' + id);
if (type === 'Gene') {
var validation = Array.isArray(candidate.validation) ? candidate.validation : [];
for (var j = 0; j < validation.length; j++) {
var c = String(validation[j] || '').trim();
if (!c) continue;
if (!solidifyMod.isValidationCommandAllowed(c)) {
throw new Error('Refusing to promote Gene ' + id + ': validation command rejected by safety check: "' + c + '". Only node/npm/npx commands without shell operators are allowed.');
}
}
}
var promoted = JSON.parse(JSON.stringify(candidate));
if (!promoted.a2a || typeof promoted.a2a !== 'object') promoted.a2a = {};
promoted.a2a.status = 'promoted';
promoted.a2a.promoted_at = new Date().toISOString();
if (!promoted.schema_version) promoted.schema_version = contentHash.SCHEMA_VERSION;
promoted.asset_id = contentHash.computeAssetId(promoted);
var emitDecisions = process.env.A2A_EMIT_DECISIONS === 'true';
if (type === 'EvolutionEvent') {
assetStore.appendEventJsonl(promoted);
if (emitDecisions) {
try {
var dmEv = a2aProto.buildDecision({ assetId: promoted.asset_id, localId: id, decision: 'accept', reason: 'event promoted for provenance tracking' });
a2aProto.getTransport().send(dmEv);
} catch (e) {}
}
process.stdout.write('promoted_event=' + id + '\n');
return;
}
if (type === 'Capsule') {
assetStore.appendCapsule(promoted);
if (emitDecisions) {
try {
var dm = a2aProto.buildDecision({ assetId: promoted.asset_id, localId: id, decision: 'accept', reason: 'capsule promoted after validation' });
a2aProto.getTransport().send(dm);
} catch (e) {}
}
process.stdout.write('promoted_capsule=' + id + '\n');
return;
}
var localGenes = assetStore.loadGenes();
var exists = false;
for (var k = 0; k < localGenes.length; k++) {
if (localGenes[k] && localGenes[k].type === 'Gene' && String(localGenes[k].id) === id) { exists = true; break; }
}
if (exists) {
if (emitDecisions) {
try {
var dm2 = a2aProto.buildDecision({ assetId: promoted.asset_id, localId: id, decision: 'reject', reason: 'local gene with same ID already exists' });
a2aProto.getTransport().send(dm2);
} catch (e) {}
}
process.stdout.write('conflict_keep_local_gene=' + id + '\n');
return;
}
assetStore.upsertGene(promoted);
if (emitDecisions) {
try {
var dm3 = a2aProto.buildDecision({ assetId: promoted.asset_id, localId: id, decision: 'accept', reason: 'gene promoted after safety audit' });
a2aProto.getTransport().send(dm3);
} catch (e) {}
}
process.stdout.write('promoted_gene=' + id + '\n');
}
try { main(); } catch (e) {
process.stderr.write((e && e.message ? e.message : String(e)) + '\n');
process.exit(1);
}
const fs = require('fs');
const path = require('path');
const REPO_ROOT = path.resolve(__dirname, '..');
const LOG_FILE = path.join(REPO_ROOT, 'evolution_history_full.md');
const OUT_FILE = path.join(REPO_ROOT, 'evolution_detailed_report.md');
function analyzeEvolution() {
if (!fs.existsSync(LOG_FILE)) {
console.error("Source file missing.");
return;
}
const content = fs.readFileSync(LOG_FILE, 'utf8');
// Split by divider
const entries = content.split('---').map(e => e.trim()).filter(e => e.length > 0);
const skillUpdates = {}; // Map<SkillName, Array<Changes>>
const generalUpdates = []; // Array<Changes>
// Regex to detect skills/paths
// e.g. `skills/feishu-card/send.js` or **Target**: `skills/git-sync`
const skillRegex = /skills\/([a-zA-Z0-9\-_]+)/;
const actionRegex = /Action:\s*([\s\S]*?)(?=\n\n|\n[A-Z]|$)/i; // Capture Action text
const statusRegex = /Status:\s*\[?([A-Z\s_]+)\]?/i;
entries.forEach(entry => {
// Extract basic info
const statusMatch = entry.match(statusRegex);
const status = statusMatch ? statusMatch[1].trim().toUpperCase() : 'UNKNOWN';
// Skip routine checks if we want a *detailed evolution* report (focus on changes)
// But user asked for "what happened", so routine scans might be boring unless they found something.
// Let's filter out "STABILITY" or "RUNNING" unless there is a clear "Mutated" or "Fixed" keyword.
const isInteresting =
entry.includes('Fixed') ||
entry.includes('Hardened') ||
entry.includes('Optimized') ||
entry.includes('Patched') ||
entry.includes('Created') ||
entry.includes('Added') ||
status === 'SUCCESS' ||
status === 'COMPLETED';
if (!isInteresting) return;
// Find associated skill
const skillMatch = entry.match(skillRegex);
let skillName = 'General / System';
if (skillMatch) {
skillName = skillMatch[1];
} else {
// Try heuristics
if (entry.toLowerCase().includes('feishu card')) skillName = 'feishu-card';
else if (entry.toLowerCase().includes('git sync')) skillName = 'git-sync';
else if (entry.toLowerCase().includes('logger')) skillName = 'interaction-logger';
else if (entry.toLowerCase().includes('evolve')) skillName = 'capability-evolver';
}
// Extract description
let description = "";
const actionMatch = entry.match(actionRegex);
if (actionMatch) {
description = actionMatch[1].trim();
} else {
// Fallback: take lines that look like bullet points or text after header
const lines = entry.split('\n');
description = lines.filter(l => l.match(/^[•\-\*]|\w/)).slice(1).join('\n').trim();
}
// Clean up description (remove duplicate "Action:" prefix if captured)
description = description.replace(/^Action:\s*/i, '');
if (!skillUpdates[skillName]) skillUpdates[skillName] = [];
// Dedup descriptions slightly (simple check)
const isDuplicate = skillUpdates[skillName].some(u => u.desc.includes(description.substring(0, 20)));
if (!isDuplicate) {
// Extract Date if possible
const dateMatch = entry.match(/\((\d{4}\/\d{1,2}\/\d{1,2}.*?)\)/);
const date = dateMatch ? dateMatch[1] : 'Unknown';
skillUpdates[skillName].push({
date,
status,
desc: description
});
}
});
// Generate Markdown
let md = "# Detailed Evolution Report (By Skill)\n\n> Comprehensive breakdown of system changes.\n\n";
// Sort skills alphabetically
const sortedSkills = Object.keys(skillUpdates).sort();
sortedSkills.forEach(skill => {
md += `## ${skill}\n`;
const updates = skillUpdates[skill];
updates.forEach(u => {
// Icon based on content
let icon = '*';
const lowerDesc = u.desc.toLowerCase();
if (lowerDesc.includes('optimiz')) icon = '[optimize]';
if (lowerDesc.includes('secur') || lowerDesc.includes('harden') || lowerDesc.includes('permission')) icon = '[security]';
if (lowerDesc.includes('fix') || lowerDesc.includes('patch')) icon = '[repair]';
if (lowerDesc.includes('creat') || lowerDesc.includes('add')) icon = '[add]';
md += `### ${icon} ${u.date}\n`;
md += `${u.desc}\n\n`;
});
md += `---\n`;
});
fs.writeFileSync(OUT_FILE, md);
console.log(`Generated report for ${sortedSkills.length} skills.`);
}
analyzeEvolution();
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const REPO_ROOT = path.resolve(__dirname, '..');
function readJson(filePath) {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
}
function ensureDir(dir) {
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}
function rmDir(dir) {
if (!fs.existsSync(dir)) return;
fs.rmSync(dir, { recursive: true, force: true });
}
function normalizePosix(p) {
return p.split(path.sep).join('/');
}
function isUnder(child, parent) {
const rel = path.relative(parent, child);
return !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);
}
function listFilesRec(dir) {
const out = [];
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const ent of entries) {
const p = path.join(dir, ent.name);
if (ent.isDirectory()) out.push(...listFilesRec(p));
else if (ent.isFile()) out.push(p);
}
return out;
}
function globToRegex(glob) {
// Supports "*" within a single segment and "**" for any depth.
const norm = normalizePosix(glob);
const parts = norm.split('/').filter(p => p.length > 0);
const out = [];
for (const part of parts) {
if (part === '**') {
// any number of path segments
out.push('(?:.*)');
continue;
}
// Escape regex special chars, then expand "*" wildcards within segment.
const esc = part.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*');
out.push(esc);
}
const re = out.join('\\/');
return new RegExp(`^${re}$`);
}
function matchesAnyGlobs(relPath, globs) {
const p = normalizePosix(relPath);
for (const g of globs || []) {
const re = globToRegex(g);
if (re.test(p)) return true;
}
return false;
}
function copyFile(srcAbs, destAbs) {
ensureDir(path.dirname(destAbs));
fs.copyFileSync(srcAbs, destAbs);
}
function copyEntry(spec, outDirAbs) {
const copied = [];
// Directory glob
if (spec.includes('*')) {
const all = listFilesRec(REPO_ROOT);
const includeRe = globToRegex(spec);
for (const abs of all) {
const rel = normalizePosix(path.relative(REPO_ROOT, abs));
if (!includeRe.test(rel)) continue;
const destAbs = path.join(outDirAbs, rel);
copyFile(abs, destAbs);
copied.push(rel);
}
return copied;
}
const srcAbs = path.join(REPO_ROOT, spec);
if (!fs.existsSync(srcAbs)) return [];
const st = fs.statSync(srcAbs);
if (st.isFile()) {
const rel = normalizePosix(spec);
copyFile(srcAbs, path.join(outDirAbs, rel));
copied.push(rel);
return copied;
}
if (st.isDirectory()) {
const files = listFilesRec(srcAbs);
for (const abs of files) {
const rel = normalizePosix(path.relative(REPO_ROOT, abs));
copyFile(abs, path.join(outDirAbs, rel));
copied.push(rel);
}
}
return copied;
}
function applyRewrite(outDirAbs, rewrite) {
const rules = rewrite || {};
for (const [relFile, cfg] of Object.entries(rules)) {
const target = path.join(outDirAbs, relFile);
if (!fs.existsSync(target)) continue;
let content = fs.readFileSync(target, 'utf8');
const reps = (cfg && cfg.replace) || [];
for (const r of reps) {
const from = String(r.from || '');
const to = String(r.to || '');
if (!from) continue;
content = content.split(from).join(to);
}
fs.writeFileSync(target, content, 'utf8');
}
}
function rewritePackageJson(outDirAbs) {
const p = path.join(outDirAbs, 'package.json');
if (!fs.existsSync(p)) return;
try {
const pkg = JSON.parse(fs.readFileSync(p, 'utf8'));
pkg.scripts = {
start: 'node index.js',
run: 'node index.js run',
solidify: 'node index.js solidify',
review: 'node index.js review',
'a2a:export': 'node scripts/a2a_export.js',
'a2a:ingest': 'node scripts/a2a_ingest.js',
'a2a:promote': 'node scripts/a2a_promote.js',
};
fs.writeFileSync(p, JSON.stringify(pkg, null, 2) + '\n', 'utf8');
} catch (e) {
// ignore
}
}
function parseSemver(v) {
const m = String(v || '').trim().match(/^(\d+)\.(\d+)\.(\d+)$/);
if (!m) return null;
return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]) };
}
function formatSemver(x) {
return `${x.major}.${x.minor}.${x.patch}`;
}
function bumpSemver(base, bump) {
const v = parseSemver(base);
if (!v) return null;
if (bump === 'major') return `${v.major + 1}.0.0`;
if (bump === 'minor') return `${v.major}.${v.minor + 1}.0`;
if (bump === 'patch') return `${v.major}.${v.minor}.${v.patch + 1}`;
return formatSemver(v);
}
function git(cmd) {
return execSync(cmd, { cwd: REPO_ROOT, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
}
function getBaseReleaseCommit() {
// Prefer last "prepare vX.Y.Z" commit; fallback to HEAD~50 range later.
try {
const hash = git('git log -n 1 --pretty=%H --grep="chore(release): prepare v"');
return hash || null;
} catch (e) {
return null;
}
}
function getCommitSubjectsSince(baseCommit) {
try {
if (!baseCommit) {
const out = git('git log -n 30 --pretty=%s');
return out ? out.split('\n').filter(Boolean) : [];
}
const out = git(`git log ${baseCommit}..HEAD --pretty=%s`);
return out ? out.split('\n').filter(Boolean) : [];
} catch (e) {
return [];
}
}
function inferBumpFromSubjects(subjects) {
const subs = (subjects || []).map(s => String(s));
const hasBreaking = subs.some(s => /\bBREAKING CHANGE\b/i.test(s) || /^[a-z]+(\(.+\))?!:/.test(s));
if (hasBreaking) return { bump: 'major', reason: 'breaking change marker in commit subject' };
const hasFeat = subs.some(s => /^feat(\(.+\))?:/i.test(s));
if (hasFeat) return { bump: 'minor', reason: 'feature commit detected (feat:)' };
const hasFix = subs.some(s => /^(fix|perf)(\(.+\))?:/i.test(s));
if (hasFix) return { bump: 'patch', reason: 'fix/perf commit detected' };
if (subs.length === 0) return { bump: 'none', reason: 'no commits since base release commit' };
return { bump: 'patch', reason: 'default to patch for non-breaking changes' };
}
function suggestVersion() {
const pkgPath = path.join(REPO_ROOT, 'package.json');
let baseVersion = null;
try {
baseVersion = JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version;
} catch (e) {}
const baseCommit = getBaseReleaseCommit();
const subjects = getCommitSubjectsSince(baseCommit);
const decision = inferBumpFromSubjects(subjects);
let suggested = null;
if (decision.bump === 'none') suggested = baseVersion;
else suggested = bumpSemver(baseVersion, decision.bump);
return { baseVersion, baseCommit, subjects, decision, suggestedVersion: suggested };
}
function writePrivateSemverNote(note) {
const privateDir = path.join(REPO_ROOT, 'memory');
ensureDir(privateDir);
fs.writeFileSync(path.join(privateDir, 'semver_suggestion.json'), JSON.stringify(note, null, 2) + '\n', 'utf8');
}
function writePrivateSemverPrompt(note) {
const privateDir = path.join(REPO_ROOT, 'memory');
ensureDir(privateDir);
const subjects = Array.isArray(note.subjects) ? note.subjects : [];
const semverRule = [
'MAJOR.MINOR.PATCH',
'- MAJOR: incompatible changes',
'- MINOR: backward-compatible features',
'- PATCH: backward-compatible bug fixes',
].join('\n');
const prompt = [
'You are a release versioning assistant.',
'Decide the next version bump using SemVer rules below.',
'',
semverRule,
'',
`Base version: ${note.baseVersion || '(unknown)'}`,
`Base commit: ${note.baseCommit || '(unknown)'}`,
'',
'Recent commit subjects (newest first):',
...subjects.map(s => `- ${s}`),
'',
'Output JSON only:',
'{ "bump": "major|minor|patch|none", "suggestedVersion": "x.y.z", "reason": ["..."] }',
].join('\n');
fs.writeFileSync(path.join(privateDir, 'semver_prompt.md'), prompt + '\n', 'utf8');
}
function writeDistVersion(outDirAbs, version) {
if (!version) return;
const p = path.join(outDirAbs, 'package.json');
if (!fs.existsSync(p)) return;
try {
const pkg = JSON.parse(fs.readFileSync(p, 'utf8'));
pkg.version = version;
fs.writeFileSync(p, JSON.stringify(pkg, null, 2) + '\n', 'utf8');
} catch (e) {}
}
function pruneExcluded(outDirAbs, excludeGlobs) {
const all = listFilesRec(outDirAbs);
for (const abs of all) {
const rel = normalizePosix(path.relative(outDirAbs, abs));
if (matchesAnyGlobs(rel, excludeGlobs)) {
fs.rmSync(abs, { force: true });
}
}
}
function validateNoPrivatePaths(outDirAbs) {
// Basic safeguard: forbid docs/ and memory/ in output.
const forbiddenPrefixes = ['docs/', 'memory/'];
const all = listFilesRec(outDirAbs);
for (const abs of all) {
const rel = normalizePosix(path.relative(outDirAbs, abs));
for (const pref of forbiddenPrefixes) {
if (rel.startsWith(pref)) {
throw new Error(`Build validation failed: forbidden path in output: ${rel}`);
}
}
}
}
function main() {
const manifestPath = path.join(REPO_ROOT, 'public.manifest.json');
const manifest = readJson(manifestPath);
const outDir = String(manifest.outDir || 'dist-public');
const outDirAbs = path.join(REPO_ROOT, outDir);
// SemVer suggestion (private). This does not modify the source repo version.
const semver = suggestVersion();
writePrivateSemverNote(semver);
writePrivateSemverPrompt(semver);
rmDir(outDirAbs);
ensureDir(outDirAbs);
const include = manifest.include || [];
const exclude = manifest.exclude || [];
const copied = [];
for (const spec of include) {
copied.push(...copyEntry(spec, outDirAbs));
}
pruneExcluded(outDirAbs, exclude);
applyRewrite(outDirAbs, manifest.rewrite);
rewritePackageJson(outDirAbs);
// Prefer explicit version; otherwise use suggested version.
const releaseVersion = process.env.RELEASE_VERSION || semver.suggestedVersion;
if (releaseVersion) writeDistVersion(outDirAbs, releaseVersion);
validateNoPrivatePaths(outDirAbs);
// Write build manifest for private verification (do not include in dist-public/).
const buildInfo = {
built_at: new Date().toISOString(),
outDir,
files: copied.sort(),
};
const privateDir = path.join(REPO_ROOT, 'memory');
ensureDir(privateDir);
fs.writeFileSync(path.join(privateDir, 'public_build_info.json'), JSON.stringify(buildInfo, null, 2) + '\n', 'utf8');
process.stdout.write(`Built public output at ${outDir}\n`);
if (semver && semver.suggestedVersion) {
process.stdout.write(`Suggested version: ${semver.suggestedVersion}\n`);
process.stdout.write(`SemVer decision: ${semver.decision ? semver.decision.bump : 'unknown'}\n`);
}
}
try {
main();
} catch (e) {
process.stderr.write(`${e.message}\n`);
process.exit(1);
}
const fs = require('fs');
const path = require('path');
const REPO_ROOT = path.resolve(__dirname, '..');
const LOG_FILE = path.join(REPO_ROOT, 'memory', 'mad_dog_evolution.log');
const OUT_FILE = path.join(REPO_ROOT, 'evolution_history.md');
function parseLog() {
if (!fs.existsSync(LOG_FILE)) {
console.log("Log file not found.");
return;
}
const content = fs.readFileSync(LOG_FILE, 'utf8');
const lines = content.split('\n');
const reports = [];
let currentTimestamp = null;
// Regex for Feishu command
// node skills/feishu-card/send.js --title "..." --color ... --text "..."
const cmdRegex = /node skills\/feishu-card\/send\.js --title "(.*?)" --color \w+ --text "(.*?)"/;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// 1. Capture Timestamp
if (line.includes('Cycle Start:')) {
// Format: Cycle Start: Sun Feb 1 19:17:44 UTC 2026
const dateStr = line.split('Cycle Start: ')[1].trim();
try {
currentTimestamp = new Date(dateStr);
} catch (e) {
currentTimestamp = null;
}
}
const match = line.match(cmdRegex);
if (match) {
const title = match[1];
let text = match[2];
// Clean up text (unescape newlines)
text = text.replace(/\\n/g, '\n').replace(/\\"/g, '"');
if (currentTimestamp) {
reports.push({
ts: currentTimestamp,
title: title,
text: text,
id: title // Cycle ID is in title
});
}
}
}
// Deduplicate by ID (keep latest timestamp?)
const uniqueReports = {};
reports.forEach(r => {
uniqueReports[r.id] = r;
});
const sortedReports = Object.values(uniqueReports).sort((a, b) => a.ts - b.ts);
let md = "# Evolution History (Extracted)\n\n";
sortedReports.forEach(r => {
// Convert to CST (UTC+8)
const cstDate = r.ts.toLocaleString("zh-CN", {
timeZone: "Asia/Shanghai",
hour12: false,
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit'
});
md += `### ${r.title} (${cstDate})\n`;
md += `${r.text}\n\n`;
md += `---\n\n`;
});
fs.writeFileSync(OUT_FILE, md);
console.log(`Extracted ${sortedReports.length} reports to ${OUT_FILE}`);
}
parseLog();
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
// Separator for git log parsing (something unlikely to be in commit messages)
const SEP = '|||';
const REPO_ROOT = path.resolve(__dirname, '..');
try {
// Git command:
// --reverse: Oldest to Newest (Time Sequence)
// --grep: Filter by keyword
// --format: Hash, Date (ISO), Author, Subject, Body
const cmd = `git log --reverse --grep="Evolution" --format="%H${SEP}%ai${SEP}%an${SEP}%s${SEP}%b"`;
console.log('Executing git log...');
const output = execSync(cmd, {
encoding: 'utf8',
cwd: REPO_ROOT,
maxBuffer: 1024 * 1024 * 10 // 10MB buffer just in case
});
const entries = output.split('\n').filter(line => line.trim().length > 0);
let markdown = '# Evolution History (Time Sequence)\n\n';
markdown += '> Filter: "Evolution"\n';
markdown += '> Timezone: CST (UTC+8)\n\n';
let count = 0;
entries.forEach(entry => {
const parts = entry.split(SEP);
if (parts.length < 4) return;
const hash = parts[0];
const dateStr = parts[1];
const author = parts[2];
const subject = parts[3];
const body = parts[4] || '';
// Parse Date and Convert to UTC+8
const date = new Date(dateStr);
// Add 8 hours (28800000 ms) to UTC timestamp to shift it
// Then formatting it as ISO will look like UTC but represent CST values
const cstDate = new Date(date.getTime() + 8 * 60 * 60 * 1000);
// Format: YYYY-MM-DD HH:mm:ss
const timeStr = cstDate.toISOString().replace('T', ' ').substring(0, 19);
markdown += `## ${timeStr}\n`;
markdown += `- Commit: \`${hash.substring(0, 7)}\`\n`;
markdown += `- Subject: ${subject}\n`;
if (body.trim()) {
// Indent body for better readability
const formattedBody = body.trim().split('\n').map(l => `> ${l}`).join('\n');
markdown += `- Details:\n${formattedBody}\n`;
}
markdown += '\n';
count++;
});
const outDir = path.join(REPO_ROOT, 'memory');
if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
const outPath = path.join(outDir, 'evolution_history.md');
fs.writeFileSync(outPath, markdown);
console.log(`Successfully generated report with ${count} entries.`);
console.log(`Saved to: ${outPath}`);
} catch (e) {
console.error('Error generating history:', e.message);
process.exit(1);
}
const fs = require('fs');
const { appendEventJsonl } = require('../src/gep/assetStore');
function readStdin() {
try {
return fs.readFileSync(0, 'utf8');
} catch {
return '';
}
}
function readTextIfExists(p) {
try {
if (!p) return '';
if (!fs.existsSync(p)) return '';
return fs.readFileSync(p, 'utf8');
} catch {
return '';
}
}
function parseInput(text) {
const raw = String(text || '').trim();
if (!raw) return [];
// Accept JSON array or single JSON.
try {
const maybe = JSON.parse(raw);
if (Array.isArray(maybe)) return maybe;
if (maybe && typeof maybe === 'object') return [maybe];
} catch (e) {}
// Fallback: JSONL.
const lines = raw.split('\n').map(l => l.trim()).filter(Boolean);
const out = [];
for (const line of lines) {
try {
const obj = JSON.parse(line);
out.push(obj);
} catch (e) {}
}
return out;
}
function isValidEvolutionEvent(ev) {
if (!ev || ev.type !== 'EvolutionEvent') return false;
if (!ev.id || typeof ev.id !== 'string') return false;
// parent may be null or string
if (!(ev.parent === null || typeof ev.parent === 'string')) return false;
if (!ev.intent || typeof ev.intent !== 'string') return false;
if (!Array.isArray(ev.signals)) return false;
if (!Array.isArray(ev.genes_used)) return false;
// GEP v1.4: mutation + personality are mandatory evolution dimensions
if (!ev.mutation_id || typeof ev.mutation_id !== 'string') return false;
if (!ev.personality_state || typeof ev.personality_state !== 'object') return false;
if (ev.personality_state.type !== 'PersonalityState') return false;
for (const k of ['rigor', 'creativity', 'verbosity', 'risk_tolerance', 'obedience']) {
const v = Number(ev.personality_state[k]);
if (!Number.isFinite(v) || v < 0 || v > 1) return false;
}
if (!ev.blast_radius || typeof ev.blast_radius !== 'object') return false;
if (!Number.isFinite(Number(ev.blast_radius.files))) return false;
if (!Number.isFinite(Number(ev.blast_radius.lines))) return false;
if (!ev.outcome || typeof ev.outcome !== 'object') return false;
if (!ev.outcome.status || typeof ev.outcome.status !== 'string') return false;
const score = Number(ev.outcome.score);
if (!Number.isFinite(score) || score < 0 || score > 1) return false;
// capsule_id is optional, but if present must be string or null.
if (!('capsule_id' in ev)) return true;
return ev.capsule_id === null || typeof ev.capsule_id === 'string';
}
function main() {
const args = process.argv.slice(2);
const inputPath = args.find(a => a && !a.startsWith('--')) || '';
const text = inputPath ? readTextIfExists(inputPath) : readStdin();
const items = parseInput(text);
let appended = 0;
for (const it of items) {
if (!isValidEvolutionEvent(it)) continue;
appendEventJsonl(it);
appended += 1;
}
process.stdout.write(`appended=${appended}\n`);
}
try {
main();
} catch (e) {
process.stderr.write(`${e && e.message ? e.message : String(e)}\n`);
process.exit(1);
}
const fs = require('fs');
const path = require('path');
const REPO_ROOT = path.resolve(__dirname, '..');
const IN_FILE = path.join(REPO_ROOT, 'evolution_history_full.md');
const OUT_FILE = path.join(REPO_ROOT, 'evolution_human_summary.md');
function generateHumanReport() {
if (!fs.existsSync(IN_FILE)) return console.error("No input file");
const content = fs.readFileSync(IN_FILE, 'utf8');
const entries = content.split('---').map(e => e.trim()).filter(e => e.length > 0);
const categories = {
'Security & Stability': [],
'Performance & Optimization': [],
'Tooling & Features': [],
'Documentation & Process': []
};
const componentMap = {}; // Component -> Change List
entries.forEach(entry => {
// Extract basic info
const lines = entry.split('\n');
const header = lines[0]; // ### Title (Date)
const body = lines.slice(1).join('\n');
const dateMatch = header.match(/\((.*?)\)/);
const dateStr = dateMatch ? dateMatch[1] : '';
const time = dateStr.split(' ')[1] || ''; // HH:mm:ss
// Classify
let category = 'Tooling & Features';
let component = 'System';
let summary = '';
const lowerBody = body.toLowerCase();
// Detect Component
if (lowerBody.includes('feishu-card')) component = 'feishu-card';
else if (lowerBody.includes('feishu-sticker')) component = 'feishu-sticker';
else if (lowerBody.includes('git-sync')) component = 'git-sync';
else if (lowerBody.includes('capability-evolver') || lowerBody.includes('evolve.js')) component = 'capability-evolver';
else if (lowerBody.includes('interaction-logger')) component = 'interaction-logger';
else if (lowerBody.includes('chat-to-image')) component = 'chat-to-image';
else if (lowerBody.includes('safe_publish')) component = 'capability-evolver';
// Detect Category
if (lowerBody.includes('security') || lowerBody.includes('permission') || lowerBody.includes('auth') || lowerBody.includes('harden')) {
category = 'Security & Stability';
} else if (lowerBody.includes('optimiz') || lowerBody.includes('performance') || lowerBody.includes('memory') || lowerBody.includes('fast')) {
category = 'Performance & Optimization';
} else if (lowerBody.includes('doc') || lowerBody.includes('readme')) {
category = 'Documentation & Process';
}
// Extract Human Summary (First meaningful line that isn't Status/Action/Date)
const summaryLines = lines.filter(l =>
!l.startsWith('###') &&
!l.startsWith('Status:') &&
!l.startsWith('Action:') &&
l.trim().length > 10
);
if (summaryLines.length > 0) {
// Clean up the line
summary = summaryLines[0]
.replace(/^-\s*/, '') // Remove bullets
.replace(/\*\*/g, '') // Remove bold
.replace(/`/, '')
.trim();
// Deduplicate
const key = `${component}:${summary.substring(0, 20)}`;
const exists = categories[category].some(i => i.key === key);
if (!exists && !summary.includes("Stability Scan OK") && !summary.includes("Workspace Sync")) {
categories[category].push({ time, component, summary, key });
if (!componentMap[component]) componentMap[component] = [];
componentMap[component].push(summary);
}
}
});
// --- Generate Markdown ---
const today = new Date().toISOString().slice(0, 10);
let md = `# Evolution Summary: The Day in Review (${today})\n\n`;
md += `> Overview: Grouped summary of changes extracted from evolution history.\n\n`;
// Section 1: By Theme (Evolution Direction)
md += `## 1. Evolution Direction\n`;
for (const [cat, items] of Object.entries(categories)) {
if (items.length === 0) continue;
md += `### ${cat}\n`;
// Group by component within theme
const compGroup = {};
items.forEach(i => {
if (!compGroup[i.component]) compGroup[i.component] = [];
compGroup[i.component].push(i.summary);
});
for (const [comp, sums] of Object.entries(compGroup)) {
// Unique summaries only
const uniqueSums = [...new Set(sums)];
uniqueSums.forEach(s => {
md += `- **${comp}**: ${s}\n`;
});
}
md += `\n`;
}
// Section 2: By Timeline (High Level)
md += `## 2. Timeline of Critical Events\n`;
// Flatten and sort all items by time
const allItems = [];
Object.values(categories).forEach(list => allItems.push(...list));
allItems.sort((a, b) => a.time.localeCompare(b.time));
// Filter for "Critical" keywords
const criticalItems = allItems.filter(i =>
i.summary.toLowerCase().includes('fix') ||
i.summary.toLowerCase().includes('patch') ||
i.summary.toLowerCase().includes('create') ||
i.summary.toLowerCase().includes('optimiz')
);
criticalItems.forEach(i => {
md += `- \`${i.time}\` (${i.component}): ${i.summary}\n`;
});
// Section 3: Package Adjustments
md += `\n## 3. Package & Documentation Adjustments\n`;
const comps = Object.keys(componentMap).sort();
comps.forEach(comp => {
const count = new Set(componentMap[comp]).size;
md += `- **${comp}**: Received ${count} significant updates.\n`;
});
fs.writeFileSync(OUT_FILE, md);
console.log("Human report generated.");
}
generateHumanReport();
// Canary script: run in a forked child process to verify index.js loads
// without crashing. Exit 0 = safe, non-zero = broken.
//
// This is the last safety net before solidify commits an evolution.
// If a patch broke index.js (syntax error, missing require, etc.),
// the canary catches it BEFORE the daemon restarts with broken code.
try {
require('../index.js');
process.exit(0);
} catch (e) {
process.stderr.write(String(e.message || e).slice(0, 500));
process.exit(1);
}
Related skills
FAQ
How does it reach the EvoMap Hub?
Exclusively through a local Proxy; the agent only reads and writes a local mailbox.
Can it roll back a bad change?
Yes, it supports rollback modes: hard, stash, or none.