@evomap/evolver 1.90.0 → 2.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/README.md +27 -564
  2. package/bin/evolver-llm-proxy.js +3 -0
  3. package/bin/evolver-mcp.js +2 -0
  4. package/bin/evolver-proxy.js +3 -0
  5. package/bin/evolver.js +4 -0
  6. package/index.js +1 -3670
  7. package/package.json +32 -62
  8. package/CONTRIBUTING.md +0 -19
  9. package/LICENSE +0 -641
  10. package/README.ja-JP.md +0 -521
  11. package/README.ko-KR.md +0 -520
  12. package/README.zh-CN.md +0 -531
  13. package/SKILL.md +0 -365
  14. package/assets/cover.png +0 -0
  15. package/assets/gep/genes.seed.json +0 -496
  16. package/conformance/savings-core/constants.json +0 -30
  17. package/conformance/savings-core/golden-vectors.json +0 -333
  18. package/scripts/a2a_export.js +0 -63
  19. package/scripts/a2a_ingest.js +0 -79
  20. package/scripts/a2a_promote.js +0 -118
  21. package/scripts/analyze_by_skill.js +0 -121
  22. package/scripts/build_binaries.js +0 -479
  23. package/scripts/check-changelog.js +0 -166
  24. package/scripts/extract_log.js +0 -85
  25. package/scripts/generate_history.js +0 -75
  26. package/scripts/gep_append_event.js +0 -96
  27. package/scripts/gep_personality_report.js +0 -234
  28. package/scripts/human_report.js +0 -147
  29. package/scripts/recall-verify-report.js +0 -234
  30. package/scripts/recover_loop.js +0 -61
  31. package/scripts/refresh_stars_badge.js +0 -168
  32. package/scripts/seed-merchants.js +0 -91
  33. package/scripts/skill2recipes.js +0 -118
  34. package/scripts/suggest_version.js +0 -89
  35. package/scripts/validate-modules.js +0 -38
  36. package/scripts/validate-suite.js +0 -78
  37. package/src/adapters/claudeCode.js +0 -194
  38. package/src/adapters/codex.js +0 -216
  39. package/src/adapters/cursor.js +0 -91
  40. package/src/adapters/hookAdapter.js +0 -469
  41. package/src/adapters/kiro.js +0 -195
  42. package/src/adapters/opencode.js +0 -326
  43. package/src/adapters/scripts/_lockPaths.js +0 -74
  44. package/src/adapters/scripts/_memoryFiltering.js +0 -35
  45. package/src/adapters/scripts/_runtimePaths.js +0 -440
  46. package/src/adapters/scripts/evolver-session-end.js +0 -321
  47. package/src/adapters/scripts/evolver-session-start.js +0 -587
  48. package/src/adapters/scripts/evolver-signal-detect.js +0 -98
  49. package/src/adapters/scripts/evolver-task-recall.js +0 -173
  50. package/src/atp/atpExecute.js +0 -283
  51. package/src/atp/atpTaskPickup.js +0 -233
  52. package/src/atp/autoBuyer.js +0 -382
  53. package/src/atp/autoDeliver.js +0 -215
  54. package/src/atp/cli.js +0 -354
  55. package/src/atp/cliAutobuyPrompt.js +0 -154
  56. package/src/atp/consumerAgent.js +0 -157
  57. package/src/atp/defaultHandler.js +0 -69
  58. package/src/atp/heartbeatSignalsHandler.js +0 -254
  59. package/src/atp/hubClient.js +0 -317
  60. package/src/atp/index.js +0 -38
  61. package/src/atp/merchantAgent.js +0 -118
  62. package/src/atp/protocol.js +0 -41
  63. package/src/atp/questionComposer.js +0 -133
  64. package/src/atp/serviceHelper.js +0 -92
  65. package/src/canary.js +0 -13
  66. package/src/config.js +0 -351
  67. package/src/evolve/guards.js +0 -1
  68. package/src/evolve/pipeline/collect.js +0 -1
  69. package/src/evolve/pipeline/dispatch.js +0 -1
  70. package/src/evolve/pipeline/enrich.js +0 -1
  71. package/src/evolve/pipeline/hub.js +0 -1
  72. package/src/evolve/pipeline/select.js +0 -1
  73. package/src/evolve/pipeline/signals.js +0 -1
  74. package/src/evolve/utils.js +0 -1
  75. package/src/evolve.js +0 -1
  76. package/src/experiment/agentRunner.js +0 -229
  77. package/src/experiment/cli.js +0 -159
  78. package/src/experiment/comparison.js +0 -233
  79. package/src/experiment/metrics.js +0 -75
  80. package/src/forceUpdate.js +0 -991
  81. package/src/gep/a2a.js +0 -173
  82. package/src/gep/a2aProtocol.js +0 -1
  83. package/src/gep/analyzer.js +0 -35
  84. package/src/gep/antiAbuseTelemetry.js +0 -1
  85. package/src/gep/assetCallLog.js +0 -197
  86. package/src/gep/assetStore.js +0 -723
  87. package/src/gep/assets.js +0 -36
  88. package/src/gep/autoDistillConv.js +0 -1
  89. package/src/gep/autoDistillLlm.js +0 -1
  90. package/src/gep/bridge.js +0 -138
  91. package/src/gep/candidateEval.js +0 -1
  92. package/src/gep/candidates.js +0 -1
  93. package/src/gep/claimNudge.js +0 -121
  94. package/src/gep/cliContracts.js +0 -1190
  95. package/src/gep/contentHash.js +0 -1
  96. package/src/gep/conversationDistiller.js +0 -1
  97. package/src/gep/conversationSniffer.js +0 -1
  98. package/src/gep/crypto.js +0 -1
  99. package/src/gep/curriculum.js +0 -1
  100. package/src/gep/deviceId.js +0 -1
  101. package/src/gep/directoryClient.js +0 -115
  102. package/src/gep/envFingerprint.js +0 -1
  103. package/src/gep/epigenetics.js +0 -1
  104. package/src/gep/execBridge.js +0 -1
  105. package/src/gep/executionTrace.js +0 -291
  106. package/src/gep/explore.js +0 -1
  107. package/src/gep/featureFlags.js +0 -121
  108. package/src/gep/gitOps.js +0 -265
  109. package/src/gep/hash.js +0 -1
  110. package/src/gep/hostErrorClassifier.js +0 -34
  111. package/src/gep/hubFetch.js +0 -1
  112. package/src/gep/hubReview.js +0 -1
  113. package/src/gep/hubSearch.js +0 -1
  114. package/src/gep/hubVerify.js +0 -1
  115. package/src/gep/idleScheduler.js +0 -400
  116. package/src/gep/issueReporter.js +0 -416
  117. package/src/gep/learningSignals.js +0 -1
  118. package/src/gep/llmReview.js +0 -92
  119. package/src/gep/localStateAwareness.js +0 -243
  120. package/src/gep/mailboxTransport.js +0 -119
  121. package/src/gep/memoryGraph.js +0 -1
  122. package/src/gep/memoryGraphAdapter.js +0 -1
  123. package/src/gep/mutation.js +0 -1
  124. package/src/gep/narrativeMemory.js +0 -1
  125. package/src/gep/oauthLogin.js +0 -181
  126. package/src/gep/openPRRegistry.js +0 -1
  127. package/src/gep/paths.js +0 -522
  128. package/src/gep/personality.js +0 -1
  129. package/src/gep/policyCheck.js +0 -1
  130. package/src/gep/portable.js +0 -103
  131. package/src/gep/privacyClient.js +0 -235
  132. package/src/gep/prompt.js +0 -1
  133. package/src/gep/questionGenerator.js +0 -518
  134. package/src/gep/recallInject.js +0 -1
  135. package/src/gep/recallVerifier.js +0 -1
  136. package/src/gep/reflection.js +0 -1
  137. package/src/gep/sanitize.js +0 -264
  138. package/src/gep/savingsCore.js +0 -1
  139. package/src/gep/schemas/capsule.js +0 -170
  140. package/src/gep/schemas/gene.js +0 -154
  141. package/src/gep/schemas/index.js +0 -8
  142. package/src/gep/schemas/protocol.js +0 -51
  143. package/src/gep/schemas/task.js +0 -74
  144. package/src/gep/selector.js +0 -1
  145. package/src/gep/selfPR.js +0 -469
  146. package/src/gep/signals.js +0 -776
  147. package/src/gep/skill2gep.js +0 -1056
  148. package/src/gep/skill2gepAudit.js +0 -303
  149. package/src/gep/skill2recipes.js +0 -511
  150. package/src/gep/skillDistiller.js +0 -1
  151. package/src/gep/skillPublisher.js +0 -358
  152. package/src/gep/solidify.js +0 -1
  153. package/src/gep/strategy.js +0 -1
  154. package/src/gep/taskReceiver.js +0 -575
  155. package/src/gep/tokenSavings.js +0 -1
  156. package/src/gep/trajectoryExport.js +0 -1
  157. package/src/gep/validationReport.js +0 -55
  158. package/src/gep/validator/index.js +0 -411
  159. package/src/gep/validator/reporter.js +0 -210
  160. package/src/gep/validator/sandboxExecutor.js +0 -480
  161. package/src/gep/validator/stakeBootstrap.js +0 -357
  162. package/src/gep/workspaceKeychain.js +0 -1
  163. package/src/ops/cleanup.js +0 -80
  164. package/src/ops/commentary.js +0 -60
  165. package/src/ops/health_check.js +0 -104
  166. package/src/ops/index.js +0 -11
  167. package/src/ops/innovation.js +0 -67
  168. package/src/ops/lifecycle.js +0 -798
  169. package/src/ops/self_repair.js +0 -76
  170. package/src/ops/skills_monitor.js +0 -147
  171. package/src/ops/trigger.js +0 -33
  172. package/src/proxy/clientSettings.js +0 -405
  173. package/src/proxy/envelope.js +0 -59
  174. package/src/proxy/extensions/dmHandler.js +0 -45
  175. package/src/proxy/extensions/sessionHandler.js +0 -141
  176. package/src/proxy/extensions/skillUpdater.js +0 -64
  177. package/src/proxy/extensions/traceControl.js +0 -1
  178. package/src/proxy/index.js +0 -1395
  179. package/src/proxy/inject.js +0 -1
  180. package/src/proxy/lifecycle/manager.js +0 -1568
  181. package/src/proxy/mailbox/state.js +0 -207
  182. package/src/proxy/mailbox/store.js +0 -602
  183. package/src/proxy/router/cache_passthrough.js +0 -26
  184. package/src/proxy/router/features.js +0 -84
  185. package/src/proxy/router/gemini_route.js +0 -154
  186. package/src/proxy/router/messages_route.js +0 -535
  187. package/src/proxy/router/model_router.js +0 -113
  188. package/src/proxy/router/models_route.js +0 -52
  189. package/src/proxy/router/ollama_route.js +0 -103
  190. package/src/proxy/router/responses_route.js +0 -170
  191. package/src/proxy/router/vertex_route.js +0 -110
  192. package/src/proxy/server/http.js +0 -363
  193. package/src/proxy/server/routes.js +0 -558
  194. package/src/proxy/server/settings.js +0 -115
  195. package/src/proxy/sync/engine.js +0 -179
  196. package/src/proxy/sync/inbound.js +0 -211
  197. package/src/proxy/sync/outbound.js +0 -361
  198. package/src/proxy/task/monitor.js +0 -131
  199. package/src/proxy/trace/extractor.js +0 -1
  200. package/src/proxy/trace/usage.js +0 -1
  201. package/src/solo/breaker.js +0 -25
  202. package/src/solo/gitGuard.js +0 -65
  203. package/src/webui/client/clientJs/assets.js +0 -111
  204. package/src/webui/client/clientJs/bootstrap.js +0 -92
  205. package/src/webui/client/clientJs/common.js +0 -77
  206. package/src/webui/client/clientJs/i18n.js +0 -366
  207. package/src/webui/client/clientJs/index.js +0 -35
  208. package/src/webui/client/clientJs/interactions.js +0 -351
  209. package/src/webui/client/clientJs/overview.js +0 -152
  210. package/src/webui/client/clientJs/personality.js +0 -285
  211. package/src/webui/client/clientJs/pipelines.js +0 -330
  212. package/src/webui/client/indexHtml.js +0 -221
  213. package/src/webui/client/static.js +0 -23
  214. package/src/webui/client/stylesCss.js +0 -639
  215. package/src/webui/client/vendor/README.md +0 -15
  216. package/src/webui/client/vendor/echarts.min.js +0 -45
  217. package/src/webui/index.js +0 -14
  218. package/src/webui/observer/assets.js +0 -146
  219. package/src/webui/observer/index.js +0 -37
  220. package/src/webui/observer/interactions.js +0 -127
  221. package/src/webui/observer/jsonl.js +0 -75
  222. package/src/webui/observer/paths.js +0 -46
  223. package/src/webui/observer/personality.js +0 -43
  224. package/src/webui/observer/pipelineEvents.js +0 -58
  225. package/src/webui/observer/redact.js +0 -63
  226. package/src/webui/observer/runs.js +0 -356
  227. package/src/webui/observer/safety.js +0 -57
  228. package/src/webui/observer/skills.js +0 -70
  229. package/src/webui/observer/status.js +0 -71
  230. package/src/webui/server/http.js +0 -138
  231. package/src/webui/server/routes.js +0 -41
package/src/gep/selfPR.js DELETED
@@ -1,469 +0,0 @@
1
- // Self-PR: auto-contribute high-confidence self-mutations back to the public repo.
2
- // When evolver optimizes its own code and the change passes all gates (score, streak,
3
- // blast radius, leak scan, non-obfuscated files only), this module creates a PR on
4
- // the configured public GitHub repo via the `gh` CLI.
5
- //
6
- // Safety: env-gated (EVOLVER_SELF_PR=true), 24h cooldown, diff dedup,
7
- // never auto-merges, only `optimize` + `low` risk mutations qualify.
8
-
9
- const fs = require('fs');
10
- const path = require('path');
11
- const crypto = require('crypto');
12
- const { execSync } = require('child_process');
13
- // 10 MB — prevents RangeError on large child process output (e.g. git log/diff
14
- // on large repos). See GHSA reports / issue #451.
15
- const MAX_EXEC_BUFFER = 10 * 1024 * 1024;
16
-
17
- const { getEvolutionDir, getRepoRoot, getEvolverInstallRoot } = require('./paths');
18
- const { fullLeakCheck, redactString } = require('./sanitize');
19
- const {
20
- SELF_PR_MIN_SCORE,
21
- SELF_PR_MIN_STREAK,
22
- SELF_PR_MAX_FILES,
23
- SELF_PR_MAX_LINES,
24
- SELF_PR_COOLDOWN_MS,
25
- SELF_PR_REPO,
26
- SELF_PR_TIMEOUT_MS,
27
- } = require('../config');
28
-
29
- const STATE_FILE = 'self_pr_state.json';
30
-
31
- // Files obfuscated in public.manifest.json -- PRs touching these would land
32
- // raw source on the public repo where the file ships obfuscated, leaking
33
- // implementation detail. Source of truth: public.manifest.json `obfuscate`
34
- // array, loaded lazily on first use.
35
- //
36
- // public.manifest.json is itself excluded from the npm package (it's a
37
- // build-time artifact for the obfuscation pipeline), so on npm installs the
38
- // file is absent. That is expected — self-PR is dev-only (gated by
39
- // EVOLVER_SELF_PR=true) and a missing manifest correctly produces the
40
- // fail-safe behavior (reject all files). We therefore stay silent on load
41
- // failure here and only surface a warning when maybeCreatePR is actually
42
- // invoked but the manifest cannot be read.
43
- //
44
- // Failed loads are retried after MANIFEST_RETRY_TTL_MS (default 5 min) so a
45
- // transient FS error during process start (build script still writing the
46
- // file, NFS hiccup, permission flap) does not freeze the cache at null for
47
- // the entire daemon lifetime, silently disabling self-PR for days or weeks
48
- // with no recovery. A successful load remains sticky because the manifest is
49
- // effectively read-only at runtime.
50
- let _obfuscatedFilesCache; // undefined = not loaded; Set | null after first attempt
51
- let _manifestLoadError = null;
52
- let _manifestLoadFailedAt = 0; // ms timestamp of the last failed load attempt
53
- let _warnedAboutMissingManifest = false;
54
- let _manifestRetryTtlMs = 5 * 60 * 1000;
55
-
56
- function loadObfuscatedFromManifest() {
57
- // Hit on a successful previous load — manifest does not change at runtime.
58
- if (_obfuscatedFilesCache instanceof Set) return _obfuscatedFilesCache;
59
- // Within the retry window after a failure: skip the FS hit, return cached
60
- // null so callers stay in the fail-safe branch without hammering the disk.
61
- if (_obfuscatedFilesCache === null &&
62
- (Date.now() - _manifestLoadFailedAt) < _manifestRetryTtlMs) {
63
- return null;
64
- }
65
- // First-ever attempt OR retry window elapsed since the last failure.
66
- try {
67
- const manifestPath = path.join(getEvolverInstallRoot(), 'public.manifest.json');
68
- const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
69
- if (!Array.isArray(manifest.obfuscate)) {
70
- throw new Error('public.manifest.json missing `obfuscate` array');
71
- }
72
- // Reject glob patterns: build_public.js may expand them, but Set.has(rel)
73
- // would silently miss matches and reintroduce the drift this PR fixed.
74
- for (const f of manifest.obfuscate) {
75
- if (typeof f !== 'string' || /[*?[\]]/.test(f)) {
76
- throw new Error('public.manifest.json `obfuscate` must contain literal paths, got: ' + JSON.stringify(f));
77
- }
78
- }
79
- _obfuscatedFilesCache = new Set(manifest.obfuscate.map((f) => f.replace(/\\/g, '/').replace(/^\.\/+/, '')));
80
- _manifestLoadError = null;
81
- _manifestLoadFailedAt = 0;
82
- // Allow a future failure (after this success) to surface its warning
83
- // once, instead of staying silent because an earlier failure already
84
- // warned in this process.
85
- _warnedAboutMissingManifest = false;
86
- } catch (e) {
87
- _manifestLoadError = e.message;
88
- _obfuscatedFilesCache = null;
89
- _manifestLoadFailedAt = Date.now();
90
- }
91
- return _obfuscatedFilesCache;
92
- }
93
-
94
- // Test-only: reset the lazy cache so a test can exercise the load path
95
- // (e.g. cover the fail-safe branch after a missing manifest is restored).
96
- function _resetObfuscatedCache() {
97
- _obfuscatedFilesCache = undefined;
98
- _manifestLoadError = null;
99
- _manifestLoadFailedAt = 0;
100
- _warnedAboutMissingManifest = false;
101
- _manifestRetryTtlMs = 5 * 60 * 1000;
102
- }
103
-
104
- // Test-only: shrink (or grow) the retry TTL so a test can exercise the
105
- // retry-after-transient-failure path without sleeping for real time.
106
- function _setManifestRetryTtlForTests(ms) {
107
- _manifestRetryTtlMs = Number(ms) || 0;
108
- }
109
-
110
- // Files that are included in the public manifest (superset patterns).
111
- const PUBLIC_INCLUDE_PREFIXES = ['src/', 'scripts/'];
112
- const PUBLIC_INCLUDE_EXACT = new Set(['index.js', 'package.json']);
113
- const PUBLIC_EXCLUDE_PREFIXES = ['docs/', 'memory/', 'dist-public/'];
114
-
115
- function normalizeRel(filePath) {
116
- return String(filePath || '').replace(/\\/g, '/').replace(/^\.\/+/, '');
117
- }
118
-
119
- function isPublicNonObfuscated(filePath) {
120
- const rel = normalizeRel(filePath);
121
- if (!rel) return false;
122
- const obfuscated = loadObfuscatedFromManifest();
123
- if (obfuscated === null) return false; // fail-safe when manifest is unreadable
124
- if (obfuscated.has(rel)) return false;
125
- for (const excl of PUBLIC_EXCLUDE_PREFIXES) {
126
- if (rel.startsWith(excl)) return false;
127
- }
128
- if (PUBLIC_INCLUDE_EXACT.has(rel)) return true;
129
- for (const incl of PUBLIC_INCLUDE_PREFIXES) {
130
- if (rel.startsWith(incl)) return true;
131
- }
132
- return false;
133
- }
134
-
135
- function getStatePath() {
136
- return path.join(getEvolutionDir(), STATE_FILE);
137
- }
138
-
139
- function readState() {
140
- try {
141
- const p = getStatePath();
142
- if (fs.existsSync(p)) {
143
- return JSON.parse(fs.readFileSync(p, 'utf8'));
144
- }
145
- } catch (_) {}
146
- return { lastPRAt: null, recentDiffHashes: [] };
147
- }
148
-
149
- function writeState(state) {
150
- try {
151
- const dir = getEvolutionDir();
152
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
153
- fs.writeFileSync(getStatePath(), JSON.stringify(state, null, 2) + '\n');
154
- } catch (e) {
155
- if (process.env.DEBUG || process.env.EVOLVER_DEBUG) {
156
- try { process.stderr.write('selfPR.writeState failed: ' + String(e && e.message || e) + '\n'); } catch (_) {}
157
- }
158
- }
159
- }
160
-
161
- function isInCooldown() {
162
- const state = readState();
163
- if (!state.lastPRAt) return false;
164
- const elapsed = Date.now() - new Date(state.lastPRAt).getTime();
165
- return elapsed < SELF_PR_COOLDOWN_MS;
166
- }
167
-
168
- function computeDiffHash(changedFiles, repoRoot) {
169
- const diffParts = [];
170
- for (const f of changedFiles) {
171
- const abs = path.join(repoRoot, f);
172
- try {
173
- if (fs.existsSync(abs)) {
174
- diffParts.push(f + ':' + fs.readFileSync(abs, 'utf8'));
175
- }
176
- } catch (_) {}
177
- }
178
- return crypto.createHash('sha256').update(diffParts.join('\n---\n')).digest('hex').slice(0, 16);
179
- }
180
-
181
- function isDuplicateDiff(diffHash) {
182
- const state = readState();
183
- const recent = Array.isArray(state.recentDiffHashes) ? state.recentDiffHashes : [];
184
- return recent.includes(diffHash);
185
- }
186
-
187
- function recordPR(diffHash) {
188
- const state = readState();
189
- let recent = Array.isArray(state.recentDiffHashes) ? state.recentDiffHashes : [];
190
- recent.push(diffHash);
191
- if (recent.length > 20) recent = recent.slice(-20);
192
- writeState({
193
- lastPRAt: new Date().toISOString(),
194
- recentDiffHashes: recent,
195
- });
196
- }
197
-
198
- function buildPRBody({ capsule, mutation, gene, blastRadius }) {
199
- const score = capsule && capsule.outcome ? capsule.outcome.score : 0;
200
- const streak = capsule ? capsule.success_streak : 0;
201
- const capsuleId = capsule ? capsule.id : 'unknown';
202
- const geneId = gene ? gene.id : 'unknown';
203
- const signals = capsule && Array.isArray(capsule.trigger)
204
- ? capsule.trigger.slice(0, 5).join(', ')
205
- : '';
206
- const category = mutation ? mutation.category : 'unknown';
207
- const risk = mutation ? mutation.risk : 'unknown';
208
- const rationale = mutation && mutation.rationale
209
- ? redactString(String(mutation.rationale).slice(0, 500))
210
- : '';
211
- const files = blastRadius && Array.isArray(blastRadius.all_changed_files)
212
- ? blastRadius.all_changed_files.map(normalizeRel)
213
- : [];
214
- const filesStr = files.map(function (f) { return '- `' + f + '`'; }).join('\n');
215
-
216
- return [
217
- '## Mutation Summary',
218
- '',
219
- '- **Category:** ' + category,
220
- '- **Risk:** ' + risk,
221
- '- **PRM Score:** ' + (typeof score === 'number' ? score.toFixed(3) : String(score)),
222
- '- **Success Streak:** ' + streak,
223
- '- **Gene:** `' + geneId + '`',
224
- '- **Signals:** ' + (signals || 'none'),
225
- '- **Capsule:** `' + capsuleId + '`',
226
- '',
227
- '## Rationale',
228
- '',
229
- rationale || '_No rationale provided._',
230
- '',
231
- '## Changed Files',
232
- '',
233
- filesStr || '_None._',
234
- '',
235
- '## Blast Radius',
236
- '',
237
- '- Files: ' + (blastRadius ? blastRadius.files : 0),
238
- '- Lines: ' + (blastRadius ? blastRadius.lines : 0),
239
- '',
240
- '---',
241
- '',
242
- '_This PR was auto-generated by evolver self-evolution (GEP)._',
243
- '_Capsule: ' + capsuleId + ' | Gene: ' + geneId + '_',
244
- ].join('\n');
245
- }
246
-
247
- function buildPRTitle(mutation) {
248
- const rationale = mutation && mutation.rationale
249
- ? String(mutation.rationale).replace(/[\r\n]+/g, ' ').trim().slice(0, 80)
250
- : 'self-optimization';
251
- return '[Auto-Mutation] ' + rationale;
252
- }
253
-
254
- function runGh(args, opts) {
255
- const timeoutMs = (opts && opts.timeoutMs) || SELF_PR_TIMEOUT_MS;
256
- const cwd = (opts && opts.cwd) || getRepoRoot();
257
- try {
258
- const result = execSync('gh ' + args, {
259
- cwd: cwd,
260
- timeout: timeoutMs,
261
- encoding: 'utf8',
262
- stdio: ['pipe', 'pipe', 'pipe'],
263
- env: Object.assign({}, process.env), maxBuffer: MAX_EXEC_BUFFER
264
- });
265
- return { ok: true, out: String(result || '').trim() };
266
- } catch (e) {
267
- return { ok: false, out: '', err: String(e && e.stderr ? e.stderr : e.message || e).slice(0, 500) };
268
- }
269
- }
270
-
271
- function getGitDiff(changedFiles, repoRoot) {
272
- const parts = [];
273
- for (const f of changedFiles) {
274
- const before = parts.length;
275
- try {
276
- const result = execSync(
277
- 'git diff HEAD -- "' + f + '"',
278
- { cwd: repoRoot, timeout: 10000, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], maxBuffer: MAX_EXEC_BUFFER }
279
- );
280
- if (result && result.trim()) parts.push(result.trim());
281
- } catch (_) {}
282
- if (parts.length === before) {
283
- try {
284
- const result = execSync(
285
- 'git diff -- "' + f + '"',
286
- { cwd: repoRoot, timeout: 10000, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], maxBuffer: MAX_EXEC_BUFFER }
287
- );
288
- if (result && result.trim()) parts.push(result.trim());
289
- } catch (_) {}
290
- }
291
- }
292
- return parts.join('\n');
293
- }
294
-
295
- async function maybeCreatePR({ capsule, event, mutation, gene, blastRadius }) {
296
- if (String(process.env.EVOLVER_SELF_PR || '').toLowerCase() !== 'true') return null;
297
-
298
- // User has explicitly opted into self-PR. Ensure we have the obfuscate
299
- // list so we don't accidentally leak obfuscated source via a "non-obf" PR.
300
- if (loadObfuscatedFromManifest() === null) {
301
- if (!_warnedAboutMissingManifest) {
302
- console.warn('[SelfPR] public.manifest.json not found at ' + getEvolverInstallRoot() + ' — rejecting all self-PRs (manifest is required to identify obfuscated files). Error: ' + _manifestLoadError);
303
- _warnedAboutMissingManifest = true;
304
- }
305
- return null;
306
- }
307
-
308
- const score = capsule && capsule.outcome ? (capsule.outcome.score || 0) : 0;
309
- const streak = capsule ? (capsule.success_streak || 0) : 0;
310
-
311
- if (score < SELF_PR_MIN_SCORE) return null;
312
- if (streak < SELF_PR_MIN_STREAK) return null;
313
-
314
- if (!mutation || mutation.category !== 'optimize') return null;
315
- if (!mutation || mutation.risk !== 'low') return null;
316
-
317
- const filesChanged = blastRadius ? (blastRadius.files || 0) : 0;
318
- const linesChanged = blastRadius ? (blastRadius.lines || 0) : 0;
319
- if (filesChanged > SELF_PR_MAX_FILES || filesChanged === 0) return null;
320
- if (linesChanged > SELF_PR_MAX_LINES || linesChanged === 0) return null;
321
-
322
- const changedFiles = (blastRadius && Array.isArray(blastRadius.all_changed_files)
323
- ? blastRadius.all_changed_files
324
- : []).map(normalizeRel).filter(Boolean);
325
-
326
- if (changedFiles.length === 0) return null;
327
- if (!changedFiles.every(isPublicNonObfuscated)) return null;
328
-
329
- if (isInCooldown()) {
330
- console.log('[SelfPR] Skipping: cooldown active.');
331
- return { attempted: false, reason: 'cooldown' };
332
- }
333
-
334
- const repoRoot = getRepoRoot();
335
- const diffHash = computeDiffHash(changedFiles, repoRoot);
336
- if (isDuplicateDiff(diffHash)) {
337
- console.log('[SelfPR] Skipping: duplicate diff ' + diffHash);
338
- return { attempted: false, reason: 'duplicate_diff' };
339
- }
340
-
341
- const diffContent = getGitDiff(changedFiles, repoRoot);
342
- if (!diffContent) {
343
- console.log('[SelfPR] Skipping: no diff content.');
344
- return { attempted: false, reason: 'no_diff' };
345
- }
346
- const leakResult = fullLeakCheck(diffContent);
347
- if (leakResult.found) {
348
- const leakSummary = leakResult.leaks.map(function (l) { return l.type; }).join(', ');
349
- console.warn('[SelfPR] Skipping: leak detected in diff (' + leakSummary + ')');
350
- return { attempted: false, reason: 'leak_detected', leaks: leakResult.leaks.length };
351
- }
352
-
353
- const repo = SELF_PR_REPO;
354
- const capsuleIdShort = capsule && capsule.id ? String(capsule.id).slice(0, 8) : crypto.randomBytes(4).toString('hex');
355
- const branch = 'evolver-bot/mutation-' + capsuleIdShort;
356
- const title = buildPRTitle(mutation);
357
- const body = buildPRBody({ capsule, mutation, gene, blastRadius });
358
-
359
- try {
360
- console.log('[SelfPR] Creating PR on ' + repo + ' branch ' + branch + '...');
361
-
362
- const forkCheck = runGh('repo view ' + repo + ' --json name', { timeoutMs: 15000 });
363
- if (!forkCheck.ok) {
364
- console.warn('[SelfPR] Cannot access repo ' + repo + ': ' + (forkCheck.err || 'unknown'));
365
- return { attempted: false, reason: 'repo_access_failed' };
366
- }
367
-
368
- const tmpDir = path.join(getEvolutionDir(), 'self_pr_workdir');
369
- if (fs.existsSync(tmpDir)) {
370
- fs.rmSync(tmpDir, { recursive: true, force: true });
371
- }
372
- fs.mkdirSync(tmpDir, { recursive: true });
373
-
374
- const cloneResult = runGh(
375
- 'repo clone ' + repo + ' "' + tmpDir + '" -- --depth 1',
376
- { timeoutMs: 60000 }
377
- );
378
- if (!cloneResult.ok) {
379
- console.warn('[SelfPR] Clone failed: ' + (cloneResult.err || 'unknown'));
380
- return { attempted: false, reason: 'clone_failed' };
381
- }
382
-
383
- try {
384
- execSync('git checkout -b "' + branch + '"', { cwd: tmpDir, timeout: 10000, maxBuffer: MAX_EXEC_BUFFER });
385
- } catch (e) {
386
- console.warn('[SelfPR] Branch creation failed: ' + (e.message || e));
387
- return { attempted: false, reason: 'branch_failed' };
388
- }
389
-
390
- for (const relFile of changedFiles) {
391
- const srcFile = path.join(repoRoot, relFile);
392
- const destFile = path.join(tmpDir, relFile);
393
- const destDir = path.dirname(destFile);
394
- if (!fs.existsSync(destDir)) fs.mkdirSync(destDir, { recursive: true });
395
- if (fs.existsSync(srcFile)) {
396
- fs.copyFileSync(srcFile, destFile);
397
- }
398
- }
399
-
400
- try {
401
- execSync('git add -A', { cwd: tmpDir, timeout: 10000, maxBuffer: MAX_EXEC_BUFFER });
402
- const statusOut = execSync('git status --porcelain', { cwd: tmpDir, timeout: 10000, encoding: 'utf8', maxBuffer: MAX_EXEC_BUFFER });
403
- if (!statusOut || !statusOut.trim()) {
404
- console.log('[SelfPR] No changes to commit in public repo clone.');
405
- return { attempted: false, reason: 'no_public_diff' };
406
- }
407
- execSync(
408
- 'git commit -m "' + title.replace(/"/g, '\\"') + '"',
409
- { cwd: tmpDir, timeout: 10000, env: Object.assign({}, process.env, { GIT_AUTHOR_NAME: 'evolver-bot', GIT_AUTHOR_EMAIL: 'evolver-bot@evomap.ai', GIT_COMMITTER_NAME: 'evolver-bot', GIT_COMMITTER_EMAIL: 'evolver-bot@evomap.ai' }) }
410
- );
411
- } catch (e) {
412
- console.warn('[SelfPR] Commit failed: ' + (e.message || e));
413
- return { attempted: false, reason: 'commit_failed' };
414
- }
415
-
416
- try {
417
- execSync('git push origin "' + branch + '"', { cwd: tmpDir, timeout: 30000 });
418
- } catch (e) {
419
- console.warn('[SelfPR] Push failed: ' + (e.message || e));
420
- return { attempted: false, reason: 'push_failed' };
421
- }
422
-
423
- const bodyFile = path.join(tmpDir, '.pr_body.md');
424
- fs.writeFileSync(bodyFile, body);
425
-
426
- const prResult = runGh(
427
- 'pr create --repo ' + repo +
428
- ' --head "' + branch + '"' +
429
- ' --title "' + title.replace(/"/g, '\\"') + '"' +
430
- ' --body-file "' + bodyFile + '"' +
431
- ' --label "auto-mutation"',
432
- { cwd: tmpDir, timeoutMs: 30000 }
433
- );
434
-
435
- if (fs.existsSync(tmpDir)) {
436
- try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch (_) {}
437
- }
438
-
439
- if (!prResult.ok) {
440
- console.warn('[SelfPR] PR creation failed: ' + (prResult.err || 'unknown'));
441
- return { attempted: true, reason: 'pr_create_failed', error: prResult.err };
442
- }
443
-
444
- const prUrl = prResult.out || '';
445
- console.log('[SelfPR] PR created: ' + prUrl);
446
- recordPR(diffHash);
447
- return { attempted: true, ok: true, pr_url: prUrl, branch: branch, diff_hash: diffHash };
448
- } catch (e) {
449
- console.warn('[SelfPR] Unexpected error (non-fatal): ' + (e && e.message ? e.message : e));
450
- return { attempted: false, reason: 'unexpected_error', error: String(e && e.message || e).slice(0, 200) };
451
- }
452
- }
453
-
454
- module.exports = {
455
- maybeCreatePR,
456
- isPublicNonObfuscated,
457
- isInCooldown,
458
- isDuplicateDiff,
459
- computeDiffHash,
460
- buildPRTitle,
461
- buildPRBody,
462
- readState,
463
- writeState,
464
- recordPR,
465
- // For testing
466
- _loadObfuscatedFromManifest: loadObfuscatedFromManifest,
467
- _resetObfuscatedCache,
468
- _setManifestRetryTtlForTests,
469
- };