@evomap/evolver-cli 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 (91) hide show
  1. package/dist/antiGeneBenchmark.d.ts +9 -0
  2. package/dist/antiGeneBenchmark.js +173 -0
  3. package/dist/antiGeneRollout.d.ts +14 -0
  4. package/dist/antiGeneRollout.js +276 -0
  5. package/dist/atp.d.ts +122 -0
  6. package/dist/atp.js +413 -0
  7. package/dist/atpAutoDeliver.d.ts +53 -0
  8. package/dist/atpAutoDeliver.js +197 -0
  9. package/dist/atpAutobuyPrompt.d.ts +48 -0
  10. package/dist/atpAutobuyPrompt.js +109 -0
  11. package/dist/autoDistillAntiGene.d.ts +63 -0
  12. package/dist/autoDistillAntiGene.js +396 -0
  13. package/dist/autoDistillLlm.d.ts +94 -0
  14. package/dist/autoDistillLlm.js +510 -0
  15. package/dist/autoDistillTranscript.d.ts +87 -0
  16. package/dist/autoDistillTranscript.js +364 -0
  17. package/dist/autoRecall.d.ts +25 -0
  18. package/dist/autoRecall.js +80 -0
  19. package/dist/autoexec.d.ts +237 -0
  20. package/dist/autoexec.js +1041 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +7 -0
  23. package/dist/cliContracts.d.ts +72 -0
  24. package/dist/cliContracts.js +815 -0
  25. package/dist/commands.d.ts +9 -0
  26. package/dist/commands.js +10 -0
  27. package/dist/cursorRewrite.d.ts +42 -0
  28. package/dist/cursorRewrite.js +65 -0
  29. package/dist/cycleConsumer.d.ts +42 -0
  30. package/dist/cycleConsumer.js +519 -0
  31. package/dist/daemonLoop.d.ts +33 -0
  32. package/dist/daemonLoop.js +72 -0
  33. package/dist/dispatch.d.ts +10 -0
  34. package/dist/dispatch.js +75 -0
  35. package/dist/distillObserver.d.ts +33 -0
  36. package/dist/distillObserver.js +146 -0
  37. package/dist/distillPrimitives.d.ts +48 -0
  38. package/dist/distillPrimitives.js +142 -0
  39. package/dist/doctor.d.ts +54 -0
  40. package/dist/doctor.js +931 -0
  41. package/dist/geneValue.d.ts +37 -0
  42. package/dist/geneValue.js +97 -0
  43. package/dist/index.d.ts +193 -0
  44. package/dist/index.js +1135 -0
  45. package/dist/lifecycle.d.ts +75 -0
  46. package/dist/lifecycle.js +859 -0
  47. package/dist/login.d.ts +10 -0
  48. package/dist/login.js +38 -0
  49. package/dist/migrate/divergenceAudit.d.ts +29 -0
  50. package/dist/migrate/divergenceAudit.js +37 -0
  51. package/dist/migrate/fieldMap.d.ts +18 -0
  52. package/dist/migrate/fieldMap.js +68 -0
  53. package/dist/migrate/v1Import.d.ts +16 -0
  54. package/dist/migrate/v1Import.js +118 -0
  55. package/dist/phub.d.ts +18 -0
  56. package/dist/phub.js +284 -0
  57. package/dist/recall.d.ts +26 -0
  58. package/dist/recall.js +162 -0
  59. package/dist/recipe.d.ts +61 -0
  60. package/dist/recipe.js +564 -0
  61. package/dist/reflectionObserver.d.ts +8 -0
  62. package/dist/reflectionObserver.js +6 -0
  63. package/dist/reuse.d.ts +48 -0
  64. package/dist/reuse.js +300 -0
  65. package/dist/reuseReport.d.ts +20 -0
  66. package/dist/reuseReport.js +255 -0
  67. package/dist/reviewFilter.d.ts +4 -0
  68. package/dist/reviewFilter.js +6 -0
  69. package/dist/runtimeSessionSource.d.ts +9 -0
  70. package/dist/runtimeSessionSource.js +29 -0
  71. package/dist/setupHooks.d.ts +2 -0
  72. package/dist/setupHooks.js +410 -0
  73. package/dist/skill2gep.d.ts +144 -0
  74. package/dist/skill2gep.js +321 -0
  75. package/dist/skillDistill.d.ts +75 -0
  76. package/dist/skillDistill.js +342 -0
  77. package/dist/solo/breaker.d.ts +14 -0
  78. package/dist/solo/breaker.js +21 -0
  79. package/dist/solo/gitGuard.d.ts +17 -0
  80. package/dist/solo/gitGuard.js +62 -0
  81. package/dist/solo/mode.d.ts +12 -0
  82. package/dist/solo/mode.js +55 -0
  83. package/dist/thesis.d.ts +43 -0
  84. package/dist/thesis.js +179 -0
  85. package/dist/trajectoryExport.d.ts +1 -0
  86. package/dist/trajectoryExport.js +895 -0
  87. package/dist/valueDigest.d.ts +33 -0
  88. package/dist/valueDigest.js +94 -0
  89. package/dist/version.d.ts +2 -0
  90. package/dist/version.js +14 -0
  91. package/package.json +38 -0
@@ -0,0 +1,1041 @@
1
+ // `evolver autoexec` — the deployable form of the autonomous-exec daemon. A resident loop that drains a
2
+ // directory task queue through the productized kernel (exec.runAutoExecTask) with all safety controls, guarded
3
+ // by single-flight so a slow pass never stacks. DENY-BY-DEFAULT: allowedRoots starts empty (refuses every
4
+ // repo) until the operator explicitly allowlists one — autonomous edits to a real repo never happen by accident.
5
+ import { homedir } from 'node:os';
6
+ import { readdirSync, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs';
7
+ import { join, dirname } from 'node:path';
8
+ import { events, assetstore, algo, exec, ops, observers, hooks, material as materialNs, util, verify, hub as hubNs, daemon as daemonNs, personality } from '@evomap/evolver-core';
9
+ import { startResidentLoop } from './daemonLoop.js';
10
+ import { connectPublicHub, createSolidifyPermitCheck, ReuseCache, reuseBeforeSolve } from '@evomap/evolver-adapter-public';
11
+ import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
12
+ import { resolveValueDigestObserver } from './valueDigest.js';
13
+ import { resolveReflectionObserver } from './reflectionObserver.js';
14
+ import { resolveCursorRewriteObserver } from './cursorRewrite.js';
15
+ import { resolveDistillObserver } from './distillObserver.js';
16
+ import { resolveAutoDistillLlm } from './autoDistillLlm.js';
17
+ import { resolveAutoDistillAntiGene as resolveAntiGeneDistill } from './autoDistillAntiGene.js';
18
+ import { runTranscriptDistillTick, transcriptDistillMode } from './autoDistillTranscript.js';
19
+ import { runSessionIngestTick, scanSessionDirs } from './index.js';
20
+ import { resolveAtpAutoDeliver } from './atpAutoDeliver.js';
21
+ import { resolveAtpHome, resolveAtpSenderId } from './atp.js';
22
+ import { runAutobuyPrompt } from './atpAutobuyPrompt.js';
23
+ import * as solomode from './solo/mode.js';
24
+ import * as gitGuard from './solo/gitGuard.js';
25
+ import * as breaker from './solo/breaker.js';
26
+ /** Create the queue layout under <home>/autoexec/{tasks,done,refused}. */
27
+ export function ensureAutoExecDirs(base) {
28
+ const dirs = { base, tasks: join(base, 'tasks'), done: join(base, 'done'), refused: join(base, 'refused') };
29
+ for (const d of [dirs.tasks, dirs.done, dirs.refused])
30
+ mkdirSync(d, { recursive: true });
31
+ return dirs;
32
+ }
33
+ /** Read <base>/config.json; deny-by-default (empty allowedRoots) when absent. Default runner 'claude' (#66). */
34
+ export function readAutoExecConfig(base) {
35
+ const p = join(base, 'config.json');
36
+ const def = { allowedRoots: [], pollMs: 60_000, timeoutMs: 600_000, runner: 'claude' };
37
+ if (!existsSync(p))
38
+ return def;
39
+ try {
40
+ const c = JSON.parse(readFileSync(p, 'utf8'));
41
+ // Coerce runner to the known set — an unknown value falls back to claude rather than reaching the registry.
42
+ // cursor is a scaffold runner (#66, unverified flags); selectable here but its safe default keeps skip OFF.
43
+ const runner = c.runner === 'codex' ? 'codex' : c.runner === 'cursor' ? 'cursor' : 'claude';
44
+ return { ...def, ...c, allowedRoots: Array.isArray(c.allowedRoots) ? c.allowedRoots : [], runner };
45
+ }
46
+ catch {
47
+ return def;
48
+ }
49
+ }
50
+ function clippedValidationText(value) {
51
+ return value.length <= 160 ? value : `${value.slice(0, 157)}...`;
52
+ }
53
+ function validationCommandDisplay(cmd) {
54
+ const script = verify.validationScriptPath(cmd);
55
+ if (script)
56
+ return `node ${script}`;
57
+ const executable = String(cmd ?? '').trim().split(/\s+/)[0] ?? '';
58
+ return executable || '<empty>';
59
+ }
60
+ export function summarizeSandboxedValidation(result) {
61
+ const parts = [];
62
+ if (result.skipped.length > 0) {
63
+ const skipped = result.skipped.map((item) => clippedValidationText(`node ${item.script} (${item.reason})`));
64
+ parts.push(`skipped ${result.skipped.length} validation command(s): ${skipped.join('; ')}`);
65
+ }
66
+ const failed = result.results.filter((item) => !item.allowed || !item.passed);
67
+ if (failed.length > 0) {
68
+ const failures = failed.map((item) => {
69
+ const status = item.allowed ? `exit ${String(item.exitCode)}` : 'denied';
70
+ return clippedValidationText(`${validationCommandDisplay(item.cmd)} (${status})`);
71
+ });
72
+ parts.push(`failed ${failed.length} validation command(s): ${failures.join('; ')}`);
73
+ }
74
+ return parts.length > 0 ? parts.join(' | ') : null;
75
+ }
76
+ function createAutoExecPersonalityStore() {
77
+ return new personality.PersonalityStore();
78
+ }
79
+ /**
80
+ * One queue pass: drain every tasks/*.json through `runOne`, route the verdict to done/ (success or failure)
81
+ * or refused/ (deny-by-default), and move the task file out of the queue. Sequential; returns the verdicts.
82
+ */
83
+ export async function autoExecPass(dirs, runOne) {
84
+ const files = readdirSync(dirs.tasks).filter((f) => f.endsWith('.json'));
85
+ const out = [];
86
+ for (const f of files) {
87
+ const task = exec.normalizeAutoExecTask(JSON.parse(readFileSync(join(dirs.tasks, f), 'utf8')));
88
+ const v = await runOne(task).catch((e) => ({ taskId: task.id, status: 'failed', reason: e instanceof Error ? e.message : String(e) }));
89
+ const dest = v.status === 'refused' ? dirs.refused : dirs.done;
90
+ writeFileSync(join(dest, f), JSON.stringify(v, null, 2));
91
+ renameSync(join(dirs.tasks, f), join(dest, `task-${f}`));
92
+ out.push(v);
93
+ }
94
+ return out;
95
+ }
96
+ /**
97
+ * Build the reuse-before-solve seam (#110) — THE real injection point. This is the public-repo composition
98
+ * layer that owns BOTH core's autoexec kernel and the adapter's hub capability, so it is where the adapter's
99
+ * `reuseBeforeSolve` is adapted into core's hub-agnostic `HubReuseSeam` (core never imports the adapter).
100
+ * Flow: free hub search → core's pure score/decide → paid fetch for AT MOST ONE winner → the winner enters the
101
+ * SAME selection pool as local genes (trust-first). The two-layer cache is owned HERE so it warms across passes
102
+ * (a repeat signal set → zero hub calls). Off by default: only wired when EVOLVER_REUSE_BEFORE_SOLVE === '1'
103
+ * AND a hub credential exists (no token → no seam → zero hub calls, exactly today's behavior).
104
+ */
105
+ export function makeHubReuseSeam(cap, cache, ingestor, onAssetReused) {
106
+ return async (signals, ctx) => {
107
+ // Pending value.reuse_hit ingests (#112). The onReuseHit callback is synchronous, so it cannot await the
108
+ // ingest itself; it stashes the (error-swallowing) promise here and the seam awaits them before returning,
109
+ // making the emission deterministically durable without letting an ingest error ever break reuse.
110
+ const pending = [];
111
+ const r = await reuseBeforeSolve(cap, cache, signals, {
112
+ ...(ctx?.cycleId ? { cycleId: ctx.cycleId } : {}),
113
+ // Two consumers hang off a reuse HIT:
114
+ // - value-ledger emission (#112): a `value.reuse_hit` root_event so the ledger derives a real
115
+ // source=reuse entry (refs → assetId + cycleId) — live wiring, not a fixture;
116
+ // - used-asset tracking: the assetId feeds the fetch->outcome attribution claim the outcome
117
+ // report sends back to the hub (used_asset_ids). Fires on cache hits too — a cached payload
118
+ // is still a USE of that asset.
119
+ onReuseHit: (hit) => {
120
+ try {
121
+ onAssetReused?.(hit.assetId);
122
+ }
123
+ catch { /* tracking must never break reuse */ }
124
+ if (ingestor)
125
+ pending.push(emitReuseHit(ingestor, hit));
126
+ },
127
+ });
128
+ if (pending.length > 0)
129
+ await Promise.all(pending); // emitReuseHit never rejects (it swallows ingest errors)
130
+ return r.action === 'fetch' && r.candidate ? [r.candidate] : [];
131
+ };
132
+ }
133
+ /** Append a `value.reuse_hit` root_event for a reuse hit (#112). Never throws (reuse stays an optimization). */
134
+ async function emitReuseHit(ingestor, hit) {
135
+ try {
136
+ const payload = {
137
+ assetId: hit.assetId, cycleId: hit.cycleId, signalFingerprint: hit.signalFingerprint, fetchTokens: hit.fetchTokens,
138
+ };
139
+ await ingestor.ingest({
140
+ type: ops.VALUE_REUSE_HIT_EVENT,
141
+ human: { title: `reuse hit: ${hit.assetId}`, detail: `cycle ${hit.cycleId}` },
142
+ payload: payload,
143
+ });
144
+ }
145
+ catch { /* emission must never break the reuse path */ }
146
+ }
147
+ /**
148
+ * Append a `value.inject` root_event for a SessionStart gene injection (#123). Attribution-only — the payload
149
+ * carries the injected gene ids (+ cycle/outcome when known) and NO savings number, exactly per the ledger's
150
+ * weakest-signal contract. Never throws: injection is the agent's critical path, so a failed emission is
151
+ * swallowed (the genes are still injected). Skips an empty gene set — there is nothing to attribute.
152
+ */
153
+ export async function emitInject(ingestor, info) {
154
+ try {
155
+ if (info.geneIds.length === 0)
156
+ return;
157
+ const payload = {
158
+ geneIds: info.geneIds,
159
+ ...(info.cycleId ? { cycleId: info.cycleId } : {}),
160
+ ...(info.sessionId ? { sessionId: info.sessionId } : {}),
161
+ ...(info.outcome ? { outcome: info.outcome } : {}),
162
+ };
163
+ await ingestor.ingest({
164
+ type: ops.VALUE_INJECT_EVENT,
165
+ human: { title: `injected ${info.geneIds.length} gene(s)`, ...(info.cycleId ? { detail: `cycle ${info.cycleId}` } : {}) },
166
+ payload: payload,
167
+ });
168
+ }
169
+ catch { /* emission must never break the injection path */ }
170
+ }
171
+ /**
172
+ * Build the SessionStart inject emission seam (#123) — the public-repo composition point that connects core's
173
+ * sink-agnostic `onInject` callback to the real `value.inject` root_event sink. Core (composeSessionStartWithRecap)
174
+ * never imports the Ingestor; THIS is where the ingestor is wired in, mirroring makeHubReuseSeam for reuse. The
175
+ * returned callback is synchronous (the seam core calls is sync) and fire-and-forget: it stashes the
176
+ * error-swallowing emit promise so the caller can await durability without ever letting an ingest error surface.
177
+ * Returns undefined when there is no ingestor (no sink → no emission, exactly today's behavior).
178
+ */
179
+ export function makeInjectEmitter(ingestor) {
180
+ if (!ingestor)
181
+ return undefined;
182
+ const pending = [];
183
+ return {
184
+ onInject: (info) => { pending.push(emitInject(ingestor, info)); },
185
+ flush: async () => { if (pending.length > 0)
186
+ await Promise.all(pending); }, // emitInject never rejects
187
+ };
188
+ }
189
+ const DEFAULT_QUESTION_SUBMIT_TIMEOUT_MS = 3_000;
190
+ const QUESTION_SUBMIT_TIMEOUT_ENV = 'EVOLVER_QUESTION_SUBMIT_TIMEOUT_MS';
191
+ const SOLIDIFY_VERIFY_ENV = 'EVOLVER_SOLIDIFY_VERIFY';
192
+ const QUESTION_CONTEXT_SENSITIVE_RE = /secret|token|api[_-]?key|password|passwd|credential|bearer|authorization|cookie|session[_-]?id|private[_-]?key|oauth|refresh[_-]?token/i;
193
+ const DISTILL_TICK_EXPLORATION_CONTEXT = 'runtime session material ingestion';
194
+ const DISTILL_TICK_EXPLORATION_SIGNALS = ['stable_success_plateau', 'runtime_session_material'];
195
+ /**
196
+ * Map an autoexec verdict onto the hub outcome vocabulary (success | failed).
197
+ * refused/skipped ran no cycle — there is nothing to attribute, so no report.
198
+ */
199
+ export function verdictToOutcomeStatus(status) {
200
+ if (status === 'solidified' || status === 'innovated')
201
+ return 'success';
202
+ if (status === 'failed')
203
+ return 'failed';
204
+ return null;
205
+ }
206
+ export function questionGeneratorStatePath(home = events.evomapHome()) {
207
+ return join(home, 'evolution', 'question_generator_state.json');
208
+ }
209
+ function readQuestionState(path) {
210
+ try {
211
+ const raw = JSON.parse(readFileSync(path, 'utf8'));
212
+ return {
213
+ lastAskedAt: typeof raw.lastAskedAt === 'string' ? raw.lastAskedAt : null,
214
+ lastUrgentAt: typeof raw.lastUrgentAt === 'string' ? raw.lastUrgentAt : null,
215
+ lastExploreAt: typeof raw.lastExploreAt === 'string' ? raw.lastExploreAt : null,
216
+ recentQuestions: Array.isArray(raw.recentQuestions) ? raw.recentQuestions.map(String).slice(-30) : [],
217
+ };
218
+ }
219
+ catch {
220
+ return { lastAskedAt: null, lastUrgentAt: null, lastExploreAt: null, recentQuestions: [] };
221
+ }
222
+ }
223
+ function writeQuestionState(path, state) {
224
+ mkdirSync(dirname(path), { recursive: true });
225
+ writeFileSync(path, `${JSON.stringify({
226
+ lastAskedAt: state.lastAskedAt ?? null,
227
+ lastUrgentAt: state.lastUrgentAt ?? null,
228
+ lastExploreAt: state.lastExploreAt ?? null,
229
+ recentQuestions: [...(state.recentQuestions ?? [])].slice(-30),
230
+ }, null, 2)}\n`);
231
+ }
232
+ function questionSubmitTimeoutMs(options) {
233
+ const raw = options.timeoutMs ?? Number(options.env?.[QUESTION_SUBMIT_TIMEOUT_ENV]);
234
+ if (Number.isFinite(raw) && raw > 0)
235
+ return Math.round(raw);
236
+ return DEFAULT_QUESTION_SUBMIT_TIMEOUT_MS;
237
+ }
238
+ function observeQuestionSubmit(submitPromise) {
239
+ return submitPromise
240
+ .then((receipts) => ({ status: 'submitted', receipts }))
241
+ .catch(() => ({ status: 'failed', receipts: [] }));
242
+ }
243
+ function hasAcceptedQuestionReceipt(receipts) {
244
+ if (receipts.length === 0)
245
+ return true;
246
+ return receipts.some((r) => !r.error);
247
+ }
248
+ function writeQuestionStateIfAccepted(path, state, receipts) {
249
+ if (!hasAcceptedQuestionReceipt(receipts))
250
+ return false;
251
+ writeQuestionState(path, state);
252
+ return true;
253
+ }
254
+ function writeLateQuestionStateIfAccepted(submitResult, statePath, state) {
255
+ void submitResult.then((submitted) => {
256
+ if (submitted.status !== 'submitted')
257
+ return;
258
+ try {
259
+ writeQuestionStateIfAccepted(statePath, state, submitted.receipts);
260
+ }
261
+ catch {
262
+ // The caller already received a timeout; late cooldown persistence is best-effort.
263
+ }
264
+ });
265
+ }
266
+ async function submitQuestionsWithTimeout(submitResult, timeoutMs) {
267
+ let timer;
268
+ try {
269
+ return await Promise.race([
270
+ submitResult,
271
+ new Promise((resolve) => {
272
+ timer = setTimeout(() => resolve({ status: 'timeout', receipts: [] }), timeoutMs);
273
+ }),
274
+ ]);
275
+ }
276
+ finally {
277
+ if (timer)
278
+ clearTimeout(timer);
279
+ }
280
+ }
281
+ async function submitProactiveQuestions(cap, task, options) {
282
+ if (options.enabled === false || !cap.questions)
283
+ return { status: 'disabled', questionCount: 0 };
284
+ try {
285
+ const statePath = options.statePath ?? questionGeneratorStatePath();
286
+ const context = task.publicQuestionContext?.trim();
287
+ if (!context)
288
+ return { status: 'skipped', questionCount: 0 };
289
+ if (QUESTION_CONTEXT_SENSITIVE_RE.test(context))
290
+ return { status: 'skipped', questionCount: 0 };
291
+ const result = hubNs.generateQuestions({
292
+ signals: task.signals,
293
+ sessionTranscript: context,
294
+ state: readQuestionState(statePath),
295
+ now: options.now?.() ?? Date.now(),
296
+ env: options.env ?? process.env,
297
+ });
298
+ if (!result.changed || result.questions.length === 0)
299
+ return { status: 'skipped', questionCount: 0 };
300
+ const submitResult = observeQuestionSubmit(cap.questions.submit(result.questions));
301
+ const submitted = await submitQuestionsWithTimeout(submitResult, questionSubmitTimeoutMs(options));
302
+ if (submitted.status === 'timeout')
303
+ writeLateQuestionStateIfAccepted(submitResult, statePath, result.state);
304
+ if (submitted.status !== 'submitted')
305
+ return { status: submitted.status, questionCount: result.questions.length };
306
+ if (!writeQuestionStateIfAccepted(statePath, result.state, submitted.receipts))
307
+ return { status: 'not_accepted', questionCount: result.questions.length };
308
+ return { status: 'submitted', questionCount: result.questions.length };
309
+ }
310
+ catch {
311
+ // Proactive questions are optional ecosystem hints; hub failures must not affect task completion.
312
+ return { status: 'failed', questionCount: 0 };
313
+ }
314
+ }
315
+ export function makeHubQuestionLink(cap, options = {}) {
316
+ let queue = Promise.resolve();
317
+ return {
318
+ submitForTask: (task) => {
319
+ const run = queue.then(() => submitProactiveQuestions(cap, task, options));
320
+ queue = run.then(() => undefined, () => undefined);
321
+ return run;
322
+ },
323
+ };
324
+ }
325
+ export function shouldSubmitProactiveQuestionsForTask(task) {
326
+ return typeof task.publicQuestionContext === 'string' && task.publicQuestionContext.trim().length > 0;
327
+ }
328
+ export function urgentQuestionRuntimeWiringStatus() {
329
+ return hubNs.URGENT_QUESTION_RUNTIME_WIRING_STATUS;
330
+ }
331
+ function safeDistillContextToken(value) {
332
+ const token = value.toLowerCase().replace(/[^a-z0-9_-]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 40);
333
+ if (!/^[a-z][a-z0-9_-]{3,40}$/.test(token))
334
+ return null;
335
+ if (QUESTION_CONTEXT_SENSITIVE_RE.test(token))
336
+ return null;
337
+ return token;
338
+ }
339
+ function safeDistillSignalToken(prefix, value) {
340
+ const token = safeDistillContextToken(value)?.replace(/-/g, '_');
341
+ if (!token)
342
+ return null;
343
+ return `${prefix}_${token}`.slice(0, 40);
344
+ }
345
+ function distillTickPublicQuestionContext(source) {
346
+ const safeRecorded = Math.max(1, Math.floor(source.recorded));
347
+ const anchors = [
348
+ ...(source.sourceAgents ?? []).map((agent) => safeDistillContextToken(agent)),
349
+ ...(source.signalKinds ?? []).map((kind) => safeDistillContextToken(kind)),
350
+ ...(source.signalStrengths ?? []).map((strength) => safeDistillContextToken(strength)),
351
+ ].filter((token) => Boolean(token)).slice(0, 6);
352
+ const anchorText = anchors.length > 0 ? anchors.join(' ') : 'healthy runtime session material';
353
+ return `${DISTILL_TICK_EXPLORATION_CONTEXT} recorded ${safeRecorded} material items ${anchorText} ${anchorText}`;
354
+ }
355
+ function distillTickPublicSignals(source) {
356
+ const metadataSignals = [
357
+ ...(source.sourceAgents ?? []).map((agent) => safeDistillSignalToken('agent', agent)),
358
+ ...(source.signalKinds ?? []).map((kind) => safeDistillSignalToken('signal', kind)),
359
+ ...(source.signalStrengths ?? []).map((strength) => safeDistillSignalToken('strength', strength)),
360
+ ].filter((token) => Boolean(token));
361
+ return [...DISTILL_TICK_EXPLORATION_SIGNALS, ...metadataSignals].slice(0, 8);
362
+ }
363
+ export async function submitDistillTickExplorationQuestion(questions, source) {
364
+ if (!questions)
365
+ return { status: 'disabled', questionCount: 0 };
366
+ if (!source || !('recorded' in source))
367
+ return { status: 'skipped', questionCount: 0 };
368
+ const recorded = Math.floor(source.recorded);
369
+ if (!Number.isFinite(recorded) || recorded <= 0)
370
+ return { status: 'skipped', questionCount: 0 };
371
+ return await questions.submitForTask({
372
+ id: `autoexec-session-material-ingest-${recorded}`,
373
+ repo: 'autoexec-runtime',
374
+ target: 'runtime session material ingestion',
375
+ expectedEffect: 'runtime session material ingestion',
376
+ publicQuestionContext: distillTickPublicQuestionContext(source),
377
+ signals: distillTickPublicSignals(source),
378
+ });
379
+ }
380
+ export function scheduleAutoExecHubSideEffects(task, verdict, links) {
381
+ if (links.questions && verdictToOutcomeStatus(verdict.status) !== null && shouldSubmitProactiveQuestionsForTask(task)) {
382
+ void links.questions.submitForTask(task).catch(() => undefined);
383
+ }
384
+ if (links.outcome)
385
+ void links.outcome.reportOutcome(task, verdict).catch(() => undefined);
386
+ }
387
+ /**
388
+ * Compose the reuse seam and the outcome reporter. Reuse HITs still emit value-ledger observability, but the
389
+ * Hub outcome `used_asset_ids` claim comes only from the finished verdict's selected/executed asset. A fetched
390
+ * candidate can be withheld by trust/review gates or lose selection, so fetch-time attribution would overclaim.
391
+ * Reporting never throws and never blocks the verdict.
392
+ */
393
+ export function makeHubLink(cap, ingestor, reportEnabled = true) {
394
+ const seam = makeHubReuseSeam(cap, new ReuseCache(), ingestor);
395
+ return {
396
+ seam,
397
+ reportOutcome: async (task, verdict) => {
398
+ if (!reportEnabled)
399
+ return;
400
+ const status = verdictToOutcomeStatus(verdict.status);
401
+ if (status === null)
402
+ return;
403
+ const usedAssetIds = Array.isArray(verdict.usedAssetIds)
404
+ ? [...new Set(verdict.usedAssetIds.filter((id) => typeof id === 'string' && id.length > 0))]
405
+ : [];
406
+ try {
407
+ await cap.recordOutcome({
408
+ signals: task.signals,
409
+ status,
410
+ ...(verdict.outcome?.score !== undefined ? { score: verdict.outcome.score } : {}),
411
+ ...(usedAssetIds.length > 0 ? { usedAssetIds } : {}),
412
+ });
413
+ }
414
+ catch { /* recordOutcome never throws by contract; belt-and-braces — reporting must never break the pass */ }
415
+ if (usedAssetIds.length > 0 && cap.recordReuseResult) {
416
+ await Promise.all(usedAssetIds.map(async (assetId) => {
417
+ try {
418
+ await cap.recordReuseResult?.({
419
+ assetId,
420
+ outcome: status === 'success' ? 'success' : 'failed',
421
+ taskId: task.id,
422
+ ...(verdict.reason ? { reason: verdict.reason } : {}),
423
+ });
424
+ }
425
+ catch { /* reuse-result is best-effort observability; never fail the task */ }
426
+ }));
427
+ }
428
+ },
429
+ };
430
+ }
431
+ function resolvePublicHub(env = process.env, connectHub = connectPublicHub) {
432
+ const dir = resolveAtpHome(env) ?? join(homedir(), '.evomap');
433
+ if (!existsSync(join(dir, 'token.json')))
434
+ return undefined;
435
+ try {
436
+ const hubUrl = env['EVOMAP_HUB_URL'] ?? 'https://evomap.ai';
437
+ const resolvedSenderId = resolveAtpSenderId(env);
438
+ if (!resolvedSenderId)
439
+ return undefined;
440
+ const { hub } = connectHub({ hubUrl, authMode: 'oauth', evomapDir: dir, senderId: () => resolvedSenderId });
441
+ return hub;
442
+ }
443
+ catch {
444
+ return undefined;
445
+ }
446
+ }
447
+ /**
448
+ * Resolve the hub link (reuse seam + outcome reporter) from the environment, or undefined when reuse is
449
+ * not enabled/credentialed. Default OFF: requires EVOLVER_REUSE_BEFORE_SOLVE === '1' and an OAuth token at
450
+ * <evomapDir>/token.json. Any setup failure degrades to undefined (no link) so the daemon never blocks on
451
+ * hub config — reuse is an optimization. Outcome reporting rides the same gate (it is the read-back half
452
+ * of the same paid hub relationship); EVOLVER_OUTCOME_REPORT=0 turns just the reporting off.
453
+ */
454
+ export function resolveHubLink(env = process.env, ingestor, connectHub = connectPublicHub) {
455
+ const envFile = loadEnvFileFromEnv(env);
456
+ if (envFile.error)
457
+ process.stderr.write(`[evolver-autoexec] failed to load EVOLVER_ENV_FILE: ${envFile.error}\n`);
458
+ if (env['EVOLVER_REUSE_BEFORE_SOLVE'] !== '1')
459
+ return undefined;
460
+ if (String(env['EVOMAP_HUB_MODE'] ?? 'public').toLowerCase() === 'private') {
461
+ const proxy = proxyClientFromEnv(env);
462
+ return proxy ? makeHubLink(makeProxyHubCapability(proxy), ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0') : undefined;
463
+ }
464
+ const hub = resolvePublicHub(env, connectHub);
465
+ if (!hub)
466
+ return undefined;
467
+ // Pass the ingestor so a reuse hit emits a value.reuse_hit root_event (#112) — the live source the value
468
+ // ledger derives source=reuse entries from.
469
+ return makeHubLink(hub, ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0');
470
+ }
471
+ export function resolveHubQuestionLink(env = process.env, connectHub = connectPublicHub) {
472
+ if (env['EVOLVER_OUTCOME_REPORT'] === '0')
473
+ return undefined;
474
+ const hub = resolvePublicHub(env, connectHub);
475
+ if (!hub)
476
+ return undefined;
477
+ if (!hub.questions)
478
+ return undefined;
479
+ return makeHubQuestionLink(hub, { env });
480
+ }
481
+ function solidifyVerifyFlag(env) {
482
+ const raw = env[SOLIDIFY_VERIFY_ENV]?.trim().toLowerCase();
483
+ if (raw === '0' || raw === 'false' || raw === 'off')
484
+ return 'off';
485
+ if (raw === '1' || raw === 'true' || raw === 'on')
486
+ return 'on';
487
+ return 'auto';
488
+ }
489
+ export function offlinePermitDir(env = process.env) {
490
+ return join(resolveAtpHome(env), 'evolution', 'offline-permit');
491
+ }
492
+ export function makeOfflineSolidifyPermitGate(permits) {
493
+ return () => {
494
+ const result = permits.consumeOfflinePermit();
495
+ if (result.ok)
496
+ return { ok: true, reason: 'offline_permit' };
497
+ return {
498
+ ok: false,
499
+ reason: `hub_solidify_offline_denied:${result.error}`,
500
+ ...(result.detail ? { detail: result.detail } : {}),
501
+ };
502
+ };
503
+ }
504
+ export function resolveSolidifyPermitGate(env = process.env, connectHub = connectPublicHub, opts = {}) {
505
+ const flag = solidifyVerifyFlag(env);
506
+ if (flag === 'off')
507
+ return undefined;
508
+ const hubUrl = (env['EVOMAP_HUB_URL'] ?? env['A2A_HUB_URL'] ?? '').replace(/\/+$/, '');
509
+ if (!hubUrl) {
510
+ if (flag === 'on')
511
+ return () => ({ ok: false, reason: 'hub_solidify_verify_unavailable:no_hub_url' });
512
+ return undefined;
513
+ }
514
+ const senderId = resolveAtpSenderId(env);
515
+ if (!senderId) {
516
+ if (flag === 'on')
517
+ return () => ({ ok: false, reason: 'hub_solidify_verify_unavailable:no_sender_id' });
518
+ return undefined;
519
+ }
520
+ const nodeSecret = env['EVOMAP_NODE_SECRET']?.trim() || env['A2A_NODE_SECRET']?.trim();
521
+ const authMode = nodeSecret ? 'legacy' : 'oauth';
522
+ const dir = resolveAtpHome(env);
523
+ if (authMode === 'oauth' && !existsSync(join(dir, 'token.json'))) {
524
+ if (flag === 'on')
525
+ return () => ({ ok: false, reason: 'hub_solidify_verify_unavailable:no_credentials' });
526
+ return undefined;
527
+ }
528
+ try {
529
+ const { auth } = connectHub({
530
+ hubUrl,
531
+ authMode,
532
+ evomapDir: dir,
533
+ senderId: () => senderId,
534
+ ...(nodeSecret ? { nodeSecret } : {}),
535
+ });
536
+ return createSolidifyPermitCheck({
537
+ hubUrl,
538
+ auth,
539
+ senderId: () => senderId,
540
+ dir: offlinePermitDir(env),
541
+ nodeSecret,
542
+ ...(opts.fetchFn ? { fetchFn: opts.fetchFn } : {}),
543
+ ...(opts.now ? { now: opts.now } : {}),
544
+ ...(opts.store ? { store: opts.store } : {}),
545
+ });
546
+ }
547
+ catch {
548
+ if (flag === 'on')
549
+ return () => ({ ok: false, reason: 'hub_solidify_verify_unavailable:no_credentials' });
550
+ return undefined;
551
+ }
552
+ }
553
+ export function makeProxyHubCapability(proxy) {
554
+ const auth = {
555
+ kind: 'enterprise_sso',
556
+ login: async () => ({ id: 'proxy', kind: 'enterprise_sso', token: '' }),
557
+ authenticate: async () => ({ headers: {} }),
558
+ rotate: async () => ({ id: 'proxy', kind: 'enterprise_sso', token: '' }),
559
+ revoke: async () => { },
560
+ };
561
+ return {
562
+ auth,
563
+ search: async (query) => resultAssets(await proxy.search(proxySearchArgs(query))),
564
+ fetch: async (query) => resultAssets(await proxy.search(proxySearchArgs(query))),
565
+ fetchAssetById: async (assetId) => {
566
+ const asset = firstAsset(await proxy.fetchAsset({ assetId }));
567
+ return assetMatchesId(asset, assetId) ? asset : null;
568
+ },
569
+ publish: async () => ({ receiptId: 'proxy-disabled', status: 'rejected', terminal: true, reason: 'proxy_autoexec_publish_disabled' }),
570
+ recordOutcome: async () => ({ recorded: false, reason: 'proxy_outcome_not_configured' }),
571
+ recordReuseResult: async (report) => reuseReceipt(await proxy.recordReuseResult({
572
+ assetId: report.assetId,
573
+ outcome: report.outcome,
574
+ ...(report.taskId ? { taskId: report.taskId } : {}),
575
+ ...(report.traceId ? { traceId: report.traceId } : {}),
576
+ ...(report.timeSavedSeconds !== undefined ? { timeSavedSeconds: report.timeSavedSeconds } : {}),
577
+ ...(report.reason ? { reason: report.reason } : {}),
578
+ })),
579
+ task: {
580
+ claim: async () => ({ claimId: 'proxy-disabled' }),
581
+ complete: async () => ({ status: 'completed' }),
582
+ subscribe: async function* () { },
583
+ },
584
+ mailbox: {
585
+ poll: async () => ({ events: [] }),
586
+ ack: async () => { },
587
+ push: async () => { },
588
+ status: async () => ({ pending: 0 }),
589
+ },
590
+ };
591
+ }
592
+ function proxySearchArgs(query) {
593
+ return {
594
+ ...(query.text ? { text: query.text } : {}),
595
+ ...(query.signalsAny ? { signalsAny: query.signalsAny } : {}),
596
+ ...(query.kind ? { kind: query.kind } : {}),
597
+ ...(query.category ? { category: query.category } : {}),
598
+ ...(query.gene ? { gene: query.gene } : {}),
599
+ ...(query.limit !== undefined ? { limit: query.limit } : {}),
600
+ };
601
+ }
602
+ function resultAssets(value) {
603
+ const r = record(value);
604
+ const payload = record(r['payload']);
605
+ const rows = Array.isArray(r['results']) ? r['results']
606
+ : Array.isArray(r['assets']) ? r['assets']
607
+ : Array.isArray(payload['results']) ? payload['results']
608
+ : Array.isArray(payload['assets']) ? payload['assets']
609
+ : [];
610
+ return rows.filter((row) => Boolean(row && typeof row === 'object' && !Array.isArray(row)));
611
+ }
612
+ function firstAsset(value) {
613
+ return resultAssets(value)[0] ?? null;
614
+ }
615
+ function assetMatchesId(asset, assetId) {
616
+ return Boolean(asset && asset.asset_id === assetId);
617
+ }
618
+ function reuseReceipt(value) {
619
+ const r = record(value);
620
+ const payload = record(r['payload']);
621
+ const source = Object.keys(payload).length > 0 ? payload : r;
622
+ return {
623
+ recorded: source['recorded'] !== false && source['ok'] !== false,
624
+ ...(typeof source['reason'] === 'string' ? { reason: source['reason'] } : {}),
625
+ ...(typeof source['id'] === 'string' ? { id: source['id'] } : {}),
626
+ };
627
+ }
628
+ function record(value) {
629
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
630
+ }
631
+ /** Session-log dirs the auto-distill producer scans: EVOLVER_SESSION_DIRS (comma-sep) overrides; else the
632
+ * standard agent homes. The scanner skips non-existent dirs, so listing cross-platform homes is always safe. */
633
+ export function defaultSessionDirs(env = process.env) {
634
+ const override = env['EVOLVER_SESSION_DIRS'];
635
+ if (override && override.trim())
636
+ return override.split(',').map((s) => s.trim()).filter(Boolean);
637
+ const h = homedir();
638
+ const dirs = [
639
+ join(h, '.claude'),
640
+ join(h, '.cursor'),
641
+ join(h, '.codex'),
642
+ join(h, '.gemini', 'tmp'),
643
+ join(h, '.kimi'),
644
+ join(h, 'Library', 'Application Support', 'Cursor', 'User', 'globalStorage'),
645
+ join(h, 'AppData', 'Roaming', 'Cursor', 'User', 'globalStorage'),
646
+ join(h, '.config', 'Cursor', 'User', 'globalStorage'),
647
+ ];
648
+ const appData = env['APPDATA'];
649
+ if (appData)
650
+ dirs.push(join(appData, 'Cursor', 'User', 'globalStorage'));
651
+ return Array.from(new Set(dirs));
652
+ }
653
+ /**
654
+ * Whether the cross-runtime reuse SIGNAL is folded into selection (#268/#274 soft re-order). **Default ON**: the
655
+ * re-rank is a SMALL, bounded, clamped nudge (±REUSE_WEIGHT) that the controlled A/B (reuseSignalAb.test.ts)
656
+ * proves flips only NEAR-TIES and can never override a gene's health/signal-match — so cross-AI reuse evidence
657
+ * shapes selection by default, not only when an operator opts in. `EVOLVER_REUSE_SIGNAL=0` is the kill switch.
658
+ */
659
+ export function reuseSignalEnabled(env = process.env) {
660
+ return env['EVOLVER_REUSE_SIGNAL'] !== '0';
661
+ }
662
+ /**
663
+ * Whether the gene PROBATION loop is on (#306, phase 2). **Default OFF** — explicit opt-in (EVOLVER_GENE_PROBATION=1),
664
+ * because it lets unproven auto-distilled genes be TRIED with their strategy embedded so the cross-AI reuse loop
665
+ * self-closes (autoexec then also runs the evidence-based auto-promote tick). Unlike the bounded reuse soft re-order,
666
+ * this drives the autonomous agent with an unreviewed strategy — contained by the proven exec hard gates + worktree
667
+ * isolation (#309), but a real increase in what the loop attempts, so it stays opt-in until validated in production.
668
+ */
669
+ export function geneProbationEnabled(env = process.env) {
670
+ return env['EVOLVER_GENE_PROBATION'] === '1';
671
+ }
672
+ /**
673
+ * Wire the auto-distill producer+consumer for the resident daemon (#106 slice2): returns the distillObserver to
674
+ * register on the bus + a `tick()` that scans the session dirs and records material onto the SAME bus Ingestor
675
+ * (→ `material.batch_ready` → the observer auto-drafts a quarantined gene). Off via `EVOLVER_AUTO_DISTILL=0`.
676
+ * All stores/paths are injectable for tests; production defaults to the live ~/.evomap substrate + agent homes.
677
+ */
678
+ export function resolveDistillProducer(env, opts) {
679
+ const sessionDirs = opts.sessionDirs ?? defaultSessionDirs(env);
680
+ if (env['EVOLVER_AUTO_DISTILL'] === '0') {
681
+ return { enabled: false, reason: 'off', observer: null, tick: async () => ({ recorded: 0, sourceAgents: [], signalKinds: [], signalStrengths: [] }), sessionDirs };
682
+ }
683
+ const store = opts.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
684
+ const review = opts.review ?? new assetstore.ReviewLedger(events.assetsDir());
685
+ const materialStore = opts.materialStore ?? new materialNs.MaterialStore({ path: events.materialStorePath() });
686
+ const watermarkStore = opts.watermarkStore ?? new materialNs.WatermarkStore(events.materialWatermarkPath());
687
+ const consumer = opts.consumer ?? new materialNs.ConsumerGroups({ store: materialStore, path: join(dirname(events.materialStorePath()), 'distill-consumer.json') });
688
+ const observer = resolveDistillObserver({ consumer, store, review, ingestor: opts.ingestor, ...(opts.maxPerTick !== undefined ? { maxPerTick: opts.maxPerTick } : {}) });
689
+ const tick = () => runSessionIngestTick(sessionDirs, { materialStore, watermarkStore, ingestor: opts.ingestor });
690
+ return { enabled: true, observer, tick, sessionDirs };
691
+ }
692
+ export function shouldRunIdleDistill(intensity) {
693
+ return intensity === 'aggressive' || intensity === 'deep';
694
+ }
695
+ export async function runIdleLlmDistillForBeat(beat, guardedLlmDistill, write = (message) => { process.stdout.write(message); }) {
696
+ if (!guardedLlmDistill || !shouldRunIdleDistill(beat.intensity))
697
+ return;
698
+ const d = await guardedLlmDistill();
699
+ if (d && !('skipped' in d) && d.ok)
700
+ write(` auto-distill-llm: gene=${String(d.gene['id'] ?? d.gene.asset_id)} stored=${d.stored}\n`);
701
+ }
702
+ export async function runIdleAntiGeneDistillForBeat(beat, guardedAntiGeneDistill, write = (message) => { process.stdout.write(message); }) {
703
+ if (!guardedAntiGeneDistill || !shouldRunIdleDistill(beat.intensity))
704
+ return;
705
+ const d = await guardedAntiGeneDistill();
706
+ if (!d || 'skipped' in d)
707
+ return;
708
+ if (d.ok)
709
+ write(` auto-distill-anti-gene: antiGene=${d.antiGene.id} stored=${d.stored}\n`);
710
+ else if (d.mode === 'shadow' && d.reason === 'shadow_logged')
711
+ write(' auto-distill-anti-gene: shadowed=1\n');
712
+ }
713
+ const EMPTY_TRANSCRIPT_TICK = { scanned: 0, distilled: 0, shadowed: 0, skipped: 0, transient: 0 };
714
+ /**
715
+ * Wire the LLM-over-transcript producer for the resident daemon (#319 slice 2). Default OFF
716
+ * (EVOLVER_AUTO_DISTILL_TRANSCRIPT unset). When on, the tick scans the session dirs and LLM-distills prose-rich,
717
+ * weak/zero-signal sessions (per-session dedup/cooldown + per-tick cap inside runTranscriptDistillTick). Runs in
718
+ * the idle slot only (LLM cost), separate from the every-beat structural ingest.
719
+ */
720
+ export function resolveAutoDistillTranscript(env, opts) {
721
+ const mode = transcriptDistillMode(env);
722
+ if (mode === 'off')
723
+ return { enabled: false, mode, tick: async () => EMPTY_TRANSCRIPT_TICK };
724
+ const sessionDirs = opts.sessionDirs ?? defaultSessionDirs(env);
725
+ return {
726
+ enabled: true, mode,
727
+ tick: () => runTranscriptDistillTick({
728
+ files: scanSessionDirs(sessionDirs), store: opts.store, env, cwd: process.cwd(),
729
+ ...(opts.review ? { review: opts.review } : {}), ...(opts.ingestor ? { ingestor: opts.ingestor } : {}),
730
+ }),
731
+ };
732
+ }
733
+ export function resolveAutoDistillAntiGene(env, opts) {
734
+ return resolveAntiGeneDistill(env, {
735
+ store: opts.store,
736
+ cwd: opts.cwd ?? process.cwd(),
737
+ ...(opts.review ? { review: opts.review } : {}),
738
+ ...(opts.ingestor ? { ingestor: opts.ingestor } : {}),
739
+ ...(opts.statePath ? { statePath: opts.statePath } : {}),
740
+ ...(opts.now ? { now: opts.now } : {}),
741
+ ...(opts.runner ? { runner: opts.runner } : {}),
742
+ });
743
+ }
744
+ export async function runIdleTranscriptDistillForBeat(beat, guarded, write = (message) => { process.stdout.write(message); }) {
745
+ if (!guarded || !shouldRunIdleDistill(beat.intensity))
746
+ return;
747
+ const d = await guarded();
748
+ // singleFlight's busy sentinel is { skipped: true } — our result ALSO has a numeric `skipped`, so discriminate on
749
+ // `distilled` (present only on the real result), not on `skipped`.
750
+ if (!d || !('distilled' in d))
751
+ return;
752
+ // Shadow mode never distills (distilled=0), so surface `shadowed` too — that count IS the probation signal: how
753
+ // many sessions enforce mode would have distilled. Without it, a shadow daemon looks idle when it is in fact working.
754
+ if (d.distilled > 0 || d.shadowed > 0)
755
+ write(` auto-distill-transcript: distilled=${d.distilled} shadowed=${d.shadowed} scanned=${d.scanned} transient=${d.transient}\n`);
756
+ }
757
+ /**
758
+ * `evolver autoexec [home]`: resident daemon. Builds the safe deps from EVOLVER_HOME, then single-flight-guards
759
+ * autoExecPass on an interval. Real agent execution only happens for repos the operator has allowlisted in
760
+ * <home>/autoexec/config.json (allowedRoots) — empty by default = nothing runs.
761
+ */
762
+ export async function runAutoExec(argv) {
763
+ // Load EVOLVER_ENV_FILE into process.env FIRST (PORT v1 #10 fix): the first-run prompt below and ALL ATP
764
+ // home/consent resolution (EVOLVER_ATP_AUTOBUY / EVOLVER_HOME / EVOMAP_DIR / EVOMAP_HOME) read process.env, so an
765
+ // env-file-only setting must be merged before the prompt runs — otherwise the prompt can fire when it should skip,
766
+ // or read/write the ack under the wrong home (the env-file home is invisible until then). resolveHubLink still
767
+ // loads the file too (idempotent re-read) for its standalone callers/tests, so this is the single authoritative
768
+ // early load, not a replacement. This MUST stay above runAutobuyPrompt() (which now runs after the lock below).
769
+ const envFile = loadEnvFileFromEnv(process.env);
770
+ if (envFile.error)
771
+ process.stderr.write(`[evolver-autoexec] failed to load EVOLVER_ENV_FILE: ${envFile.error}\n`);
772
+ const home = argv.find((a) => !a.startsWith('-')) ?? join(events.evomapHome(), 'autoexec');
773
+ const dirs = ensureAutoExecDirs(home);
774
+ const cfg = readAutoExecConfig(home);
775
+ // Solo mode (--solo): the "constrained wild" profile. Hard-cut network + ATP
776
+ // at the SOURCE — in-process, before any resolve* below reads its env gate — so
777
+ // both the startup wiring and any in-cycle path see them disabled. This is the
778
+ // "no escape valve" cut (a user cannot re-enable hub/ATP under --solo). The
779
+ // per-cycle git snapshot/rollback and the failure circuit breaker are wired at
780
+ // the resident-loop tick further down. When !solo, everything below is unchanged.
781
+ const solo = solomode.isSoloRun(argv, process.env);
782
+ const soloRepoRoot = cfg.allowedRoots[0] ?? home;
783
+ if (solo) {
784
+ solomode.applySoloLockdown(process.env);
785
+ for (const line of solomode.soloBanner(soloRepoRoot))
786
+ process.stdout.write(line + '\n');
787
+ }
788
+ const store = new assetstore.LocalJsonlProvider(events.assetsDir());
789
+ // Observer bus (#113): the event total-bus, finally given its FIRST built-in observer. The value-digest
790
+ // observer is hung off the bus and the bus is wired as the Ingestor's sink, so every emitted event fans out to
791
+ // it; its weekly cadence + measured-value gate keep it quiet. Off via EVOLVER_VALUE_DIGEST=0. Fault-isolated:
792
+ // a broken sink quarantines the observer without ever touching the autoexec write path.
793
+ const bus = new observers.ObserverBus();
794
+ const digest = resolveValueDigestObserver(process.env);
795
+ if (digest.observer)
796
+ bus.register(digest.observer);
797
+ // Cursor rewrite observer (#124): cursor has no SessionStart hook, so its injected gene memory
798
+ // (.cursor/rules/evolver.mdc) is kept fresh by REWRITE-ON-CHANGE. This observer fires (debounced) on the same
799
+ // gene-set-change events the CycleEngine already emits through this Ingestor — so a real cycle solidifying a
800
+ // gene re-renders the cursor rules file. Opt-in: only registered when the user installed cursor injection at
801
+ // the project root (the first allowlisted repo); off via EVOLVER_CURSOR_REWRITE=0. Fault-isolated by the bus.
802
+ const provenance = new assetstore.ProvenanceStore(events.assetsDir());
803
+ const review = new assetstore.ReviewLedger(events.assetsDir());
804
+ const cursorRoot = cfg.allowedRoots[0];
805
+ // The cursor rewrite reads the SAME review ledger the exec pool uses, so an auto-distilled draft fired onto this
806
+ // bus (gene.distilled) is withheld from cursor's rules until approved (A2a) — not just by process isolation.
807
+ const cursorRewrite = cursorRoot
808
+ ? resolveCursorRewriteObserver(process.env, { projectRoot: cursorRoot, store, review })
809
+ : { enabled: false, reason: 'not-installed', observer: null };
810
+ if (cursorRewrite.observer)
811
+ bus.register(cursorRewrite.observer);
812
+ const ingestor = new events.Ingestor({ path: events.rootEventsPath(), sink: bus });
813
+ const reflection = resolveReflectionObserver(process.env, { ingestor });
814
+ if (reflection.observer)
815
+ bus.register(reflection.observer);
816
+ const personalityStore = createAutoExecPersonalityStore();
817
+ const engine = new algo.CycleEngine({ ingestor, selection: algo.makeGeneSelectionPoint(), store, now: () => Date.now(), personality: personalityStore });
818
+ // Reuse-before-solve (#110) + outcome report-back: wire the adapter's reuseBeforeSolve as the hub-reuse
819
+ // seam when enabled + credentialed (default OFF → undefined → zero hub calls, exactly today's behavior).
820
+ // The seam injects hub candidates into the same selection pool as local genes, trust-first; the link's
821
+ // reporter closes the loop by sending the cycle outcome + used-asset claim back to the hub.
822
+ const hubLink = resolveHubLink(process.env, ingestor);
823
+ const hubQuestionLink = resolveHubQuestionLink(process.env);
824
+ const solidifyPermit = resolveSolidifyPermitGate(process.env);
825
+ const strategyName = process.env['EVOLVE_STRATEGY'];
826
+ // Surface the cross-platform isolation gap ONCE: where unprivileged namespaces are unavailable (Windows/macOS),
827
+ // the sandbox verifier still hardens (metachar/node-eval reject, env scrub, timeout) but CANNOT cut network or
828
+ // hide home secrets — so a validation command there could phone home / read ~/.ssh. Don't let that be silent.
829
+ let warnedNoIsolation = false;
830
+ const probationOn = geneProbationEnabled();
831
+ const deps = {
832
+ engine, store, provenance, review, personality: personalityStore,
833
+ // Probation (#306, gated, default OFF via EVOLVER_GENE_PROBATION): try unproven auto-distilled genes (with their
834
+ // strategy embedded) so the cross-AI loop self-closes — contained by the proven exec gates + worktree isolation.
835
+ ...(probationOn ? { includeProbation: true } : {}),
836
+ ...(hubLink ? { hubReuse: hubLink.seam } : {}),
837
+ ...(solidifyPermit ? { solidifyPermit } : {}),
838
+ ...(strategyName !== undefined ? { strategyName } : {}),
839
+ // Validate through the hardened sandbox verifier so a validation command can't exfiltrate or phone home to game
840
+ // the result. Validation is bounded by the sandbox's own per-command cap (NOT the agent exec timeout, a
841
+ // different unit) so a long suite is not silently SIGKILL'd against the wrong budget.
842
+ validate: (task) => async (_m, _d, cwd) => {
843
+ const cmds = task.validationCmds ?? [];
844
+ const r = await verify.runSandboxedValidation(cmds, cwd);
845
+ if (cmds.length > 0 && !r.isolated && !warnedNoIsolation) {
846
+ warnedNoIsolation = true;
847
+ process.stdout.write(' warning: validation runs WITHOUT network/FS isolation on this platform (unprivileged namespaces unavailable). Full isolation is Linux-only today; the non-namespace hardening (metachar/node-eval reject, env scrub, timeout) still applies.\n');
848
+ }
849
+ const validationSummary = summarizeSandboxedValidation(r);
850
+ if (validationSummary)
851
+ process.stdout.write(` validation: ${validationSummary}\n`);
852
+ return { passed: r.passed, score: r.score };
853
+ },
854
+ };
855
+ const safety = { allowedRoots: cfg.allowedRoots, timeoutMs: cfg.timeoutMs, runner: cfg.runner };
856
+ // #268/#274 soft re-order — DEFAULT ON (kill switch: EVOLVER_REUSE_SIGNAL=0). Fold the latest cross-runtime reuse
857
+ // outcomes + observed recall into selection as a SMALL, bounded, clamped nudge (±REUSE_WEIGHT); reuseSignalAb.test
858
+ // proves it flips only near-ties and never overrides health/signal-match, so cross-AI reuse evidence shapes
859
+ // selection without an opt-in. On → one readEvents per pass (the whole root_events log): negligible against a
860
+ // multi-minute agent run, and the daemon does one pass per task — revisit only if the log grows large (rotation
861
+ // is still deferred). The recall rail stays empty until EVOLVER_AUTO_RECALL=1 separately enables value.recall.
862
+ const reuseSignalOn = reuseSignalEnabled();
863
+ const runOne = async (task) => {
864
+ // One read of root_events (per pass) feeds BOTH rails: reported reuse outcomes (#268) and observed recall (#274
865
+ // slice 3, folded at a lower weight). value.recall rides the SAME flag — it is the same soft re-order actuator.
866
+ const evts = reuseSignalOn ? events.readEvents(events.rootEventsPath()) : null;
867
+ const taskDeps = evts
868
+ ? { ...deps, reuseOutcomes: ops.summarizeReuseOutcomes(evts), recallEvents: evts.filter((e) => e.type === ops.VALUE_RECALL_EVENT) }
869
+ : deps;
870
+ const v = await exec.runAutoExecTask(taskDeps, task, safety);
871
+ // Hub writes are best-effort side effects. Schedule them after the verdict exists, but never hold the queue's
872
+ // task->done move on network I/O or hub availability.
873
+ scheduleAutoExecHubSideEffects(task, v, { questions: hubQuestionLink, outcome: hubLink });
874
+ return v;
875
+ };
876
+ const guarded = exec.singleFlight(() => autoExecPass(dirs, runOne));
877
+ // Auto-distill producer+consumer (#106): register the distillObserver on THIS bus, then a producer tick scans
878
+ // the session dirs and records material on THIS Ingestor → material.batch_ready → observer drafts a quarantined
879
+ // gene (A1) → human `review --approve` lifts it into inject/cursor (A2a/A2b). Off via EVOLVER_AUTO_DISTILL=0.
880
+ const distill = resolveDistillProducer(process.env, { ingestor, store, review });
881
+ if (distill.observer)
882
+ bus.register(distill.observer);
883
+ const llmDistill = resolveAutoDistillLlm(process.env, { store, review, ingestor, cwd: process.cwd() });
884
+ const antiGeneDistill = resolveAutoDistillAntiGene(process.env, { store, review, ingestor });
885
+ const transcriptDistill = resolveAutoDistillTranscript(process.env, { store, review, ingestor });
886
+ const atpAutoDeliver = resolveAtpAutoDeliver(process.env);
887
+ process.stdout.write(`evolver autoexec: runner=${cfg.runner} queue=${dirs.tasks} allowlist=${JSON.stringify(cfg.allowedRoots)} poll=${cfg.pollMs}ms reuse=${hubLink ? 'on' : 'off'} reuse-signal=${reuseSignalOn ? 'on' : 'off'} probation=${probationOn ? 'on' : 'off'} questions=${hubQuestionLink ? 'on' : 'off'} permit=${solidifyPermit ? 'on' : 'off'} value-digest=${digest.enabled ? 'on' : 'off'} reflection=${reflection.enabled ? 'on' : 'off'} cursor-rewrite=${cursorRewrite.enabled ? 'on' : `off(${cursorRewrite.reason})`} auto-distill=${distill.enabled ? 'on' : 'off'} auto-distill-llm=${llmDistill.enabled ? llmDistill.mode : 'off'} auto-distill-anti-gene=${antiGeneDistill.enabled ? antiGeneDistill.mode : 'off'} auto-distill-transcript=${transcriptDistill.enabled ? transcriptDistill.mode : 'off'} atp-autodeliver=${atpAutoDeliver.enabled ? 'on' : `off(${atpAutoDeliver.reason})`}\n`);
888
+ if (cfg.allowedRoots.length === 0)
889
+ process.stdout.write(' (allowlist empty → deny-by-default: nothing runs until you add a repo to config.json)\n');
890
+ // Single-instance lock (#106): a second daemon on the same home would double-process the queue. That is harmless
891
+ // for correctness (store + event writes are file-locked and watermark-idempotent) but wasteful, so refuse rather
892
+ // than pile on. Stale locks (a crashed prior daemon) are auto-reclaimed by acquireLock's pid-liveness check.
893
+ const lockPath = join(home, 'autoexec.lock');
894
+ // maxTries must allow a stale-lock reclaim (a crashed prior daemon) PLUS the acquire that follows it: reclaim
895
+ // consumes one try (unlink + continue), so maxTries:1 would reclaim then immediately time out, wrongly refusing
896
+ // the FIRST restart (Bugbot #149). A few short tries reclaim a dead owner's lock yet still refuse a LIVE holder
897
+ // fast (~maxTries×waitMs ≈ 50ms) — reclaim/refuse behavior is covered by fileLock.test.
898
+ try {
899
+ util.acquireLock(lockPath, { maxTries: 5 });
900
+ }
901
+ catch {
902
+ process.stderr.write(`evolver autoexec: another daemon holds ${lockPath} — refusing to start a second instance\n`);
903
+ return 1;
904
+ }
905
+ // First-run auto-buyer opt-in (PORT v1 #10): introduce the autonomous spend path to interactive operators once,
906
+ // AFTER the single-instance lock is held so two concurrent `evolver autoexec` starts on the same home cannot both
907
+ // pass the no-ack check, both prompt, and race writing the ack file (Bugbot). Still before the resident loop.
908
+ // No-op under systemd/Docker/CI (non-TTY) and once the ack/env is set, so it never blocks a daemon; wrapped so a
909
+ // prompt failure can never wedge `autoexec`.
910
+ try {
911
+ await runAutobuyPrompt();
912
+ }
913
+ catch (e) {
914
+ process.stderr.write(`[ATP-AutoBuyer] first-run prompt failed: ${e instanceof Error ? e.message : String(e)}\n`);
915
+ }
916
+ const uninstallUnhandledRejectionGuard = daemonNs.installUnhandledRejectionWindow({
917
+ beforeExit: () => { util.releaseLock(lockPath); },
918
+ });
919
+ // SINGLE-FLIGHT the producer tick (same as autoExecPass): a session scan that outlasts pollMs must not let two
920
+ // ticks interleave in recordSessionMaterial (which would re-emit material.batch_ready before watermarks settle).
921
+ const guardedDistill = distill.enabled && distill.observer ? exec.singleFlight(() => distill.tick()) : null;
922
+ const guardedLlmDistill = llmDistill.enabled ? exec.singleFlight(() => llmDistill.tick()) : null;
923
+ const guardedAntiGeneDistill = antiGeneDistill.enabled ? exec.singleFlight(() => antiGeneDistill.tick()) : null;
924
+ const guardedTranscriptDistill = transcriptDistill.enabled ? exec.singleFlight(() => transcriptDistill.tick()) : null;
925
+ const guardedAtpAutoDeliver = atpAutoDeliver.enabled ? exec.singleFlight(() => atpAutoDeliver.tick()) : null;
926
+ if (distill.observer)
927
+ distill.observer.kick(); // recover any un-acked backlog from a prior run (restart)
928
+ // One idle-aware resident beat runs the exec pass, ATP auto-delivery, THEN the distill scan (single-flight
929
+ // guarded). Idle-aware pacing (#106): an idle machine polls more often, an active one backs off to the base
930
+ // cadence. Off via EVOLVER_IDLE_AWARE=0 → fixed cfg.pollMs (exactly the previous behavior).
931
+ const tick = async (beat) => {
932
+ let failed = false;
933
+ const r = await guarded();
934
+ if (r && !('skipped' in r) && r.length) {
935
+ process.stdout.write(` pass: ${r.map((v) => `${v.taskId}=${v.status}`).join(' ')}\n`);
936
+ // A cycle "failed" (for solo rollback) when a task's self-edit did not
937
+ // solidify cleanly — i.e. any verdict is 'failed'. 'refused' (deny-by-
938
+ // default / not in allowlist) is a no-op, not a broken edit.
939
+ if (r.some((v) => v.status === 'failed'))
940
+ failed = true;
941
+ }
942
+ // Evidence-based auto-promote (#306 phase 2): after a pass, a probation gene that has proven itself (>= K clean
943
+ // successes, 0 failures) is auto-approved — the cross-AI loop self-closes without a human quality gate. Bad ones
944
+ // stay quarantined / get banned. Best-effort: promotion never breaks the loop. Only when probation is opted in.
945
+ if (probationOn) {
946
+ try {
947
+ const promoted = await algo.autoPromoteProbationGenes(store, review);
948
+ if (promoted.length > 0)
949
+ process.stdout.write(` auto-promote: ${promoted.length} probation gene(s) proven → approved\n`);
950
+ }
951
+ catch { /* never break the loop on a promotion side-effect */ }
952
+ }
953
+ if (guardedAtpAutoDeliver) {
954
+ const d = await guardedAtpAutoDeliver();
955
+ if (d && !('skipped' in d) && (d.delivered > 0 || d.terminalFailures > 0 || d.transientFailures > 0 || d.cooldownFailures > 0)) {
956
+ process.stdout.write(` atp-autodeliver: checked=${d.checked} delivered=${d.delivered} terminal=${d.terminalFailures} transient=${d.transientFailures} cooldown=${d.cooldownFailures}\n`);
957
+ }
958
+ }
959
+ if (guardedDistill) {
960
+ const d = await guardedDistill();
961
+ void submitDistillTickExplorationQuestion(hubQuestionLink, d).catch(() => undefined);
962
+ }
963
+ await runIdleLlmDistillForBeat(beat, guardedLlmDistill);
964
+ await runIdleAntiGeneDistillForBeat(beat, guardedAntiGeneDistill);
965
+ await runIdleTranscriptDistillForBeat(beat, guardedTranscriptDistill);
966
+ return { failed };
967
+ };
968
+ // Solo tick wrapper: snapshot the target repo before each cycle; on a failed
969
+ // cycle (a 'failed' verdict OR an unexpected throw) roll the repo back to the
970
+ // snapshot and advance the circuit breaker. At the threshold, stop the loop
971
+ // and exit non-zero — the wild loop's blind retry is replaced by a hard stop.
972
+ // The resident loop swallows tick errors, so the breaker owns the exit here.
973
+ const soloMax = solomode.soloMaxFails(process.env);
974
+ let soloState = { consecutiveFailures: 0 };
975
+ let soloTripped = false;
976
+ const soloTick = async (beat) => {
977
+ const snap = gitGuard.snapshot(soloRepoRoot);
978
+ let ok = true;
979
+ try {
980
+ const r = await tick(beat);
981
+ if (r.failed)
982
+ ok = false;
983
+ }
984
+ catch (e) {
985
+ ok = false;
986
+ process.stderr.write(`[Solo] cycle 抛错:${e instanceof Error ? e.message : String(e)}\n`);
987
+ }
988
+ const b = breaker.step(soloState, ok, soloMax);
989
+ soloState = b.state;
990
+ if (!ok) {
991
+ const rolledBack = gitGuard.rollbackTo(soloRepoRoot, snap);
992
+ process.stdout.write(rolledBack
993
+ ? `[Solo] cycle 失败,已 git 回滚目标仓到 ${String(snap).slice(0, 12)} (连续失败 ${soloState.consecutiveFailures}/${soloMax})\n`
994
+ : `[Solo] cycle 失败且回滚未成功(无快照或 git 出错)。连续失败 ${soloState.consecutiveFailures}/${soloMax}\n`);
995
+ }
996
+ if (b.tripped && !soloTripped) {
997
+ soloTripped = true;
998
+ process.stderr.write(`[Solo] 连续失败 ${soloState.consecutiveFailures} 次达阈值,熔断停机(非盲重生)。\n`);
999
+ // Stop scheduling, release the lock, and exit non-zero. Detached so we
1000
+ // don't await our own loop.stop() from inside a tick.
1001
+ void loop.stop().then(() => { uninstallUnhandledRejectionGuard(); util.releaseLock(lockPath); process.exit(1); });
1002
+ }
1003
+ };
1004
+ // Heartbeat (#106): record liveness + pacing on the AE spine for the WebUI console, THROTTLED so a fast poll does
1005
+ // not flood the log — emit on an intensity change or at most once per EVOLVER_HEARTBEAT_MS (default 60s).
1006
+ const heartbeatMinMs = Math.max(0, Number(process.env['EVOLVER_HEARTBEAT_MS'] ?? 60_000));
1007
+ let lastBeatAt = 0;
1008
+ let lastIntensity = '';
1009
+ const loop = startResidentLoop({
1010
+ tick: solo ? soloTick : tick,
1011
+ basePollMs: cfg.pollMs,
1012
+ idleAware: process.env['EVOLVER_IDLE_AWARE'] !== '0',
1013
+ onBeat: (b) => {
1014
+ const now = Date.now();
1015
+ if (b.intensity === lastIntensity && now - lastBeatAt < heartbeatMinMs)
1016
+ return;
1017
+ lastBeatAt = now;
1018
+ lastIntensity = b.intensity;
1019
+ void ingestor.ingest({
1020
+ type: 'cycle.heartbeat', // a registered EVENT_TYPE (an unknown type would throw UnknownEventTypeError)
1021
+ human: { title: `autoexec 心跳 (${b.intensity})`, severity: 'info' },
1022
+ payload: { intensity: b.intensity, idleSeconds: b.idleSeconds, nextDelayMs: b.delayMs, runner: cfg.runner },
1023
+ actor: { kind: 'machine', id: 'autoexec' },
1024
+ }).catch(() => { });
1025
+ },
1026
+ });
1027
+ // Graceful stop (#106): on SIGINT/SIGTERM stop scheduling, await the in-flight beat (no orphaned work), release
1028
+ // the single-instance lock, and exit 0. Idempotent — a second signal during shutdown is ignored.
1029
+ return await new Promise((resolve) => {
1030
+ let stopping = false;
1031
+ const shutdown = (sig) => {
1032
+ if (stopping)
1033
+ return;
1034
+ stopping = true;
1035
+ process.stdout.write(`\nevolver autoexec: ${sig} → graceful stop (finishing in-flight, releasing lock)\n`);
1036
+ void loop.stop().then(() => { uninstallUnhandledRejectionGuard(); util.releaseLock(lockPath); resolve(0); });
1037
+ };
1038
+ process.once('SIGINT', () => shutdown('SIGINT'));
1039
+ process.once('SIGTERM', () => shutdown('SIGTERM'));
1040
+ });
1041
+ }