@evomap/evolver-cli 2.0.0-beta.18 → 2.0.0-beta.19

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 (63) hide show
  1. package/dist/antiGeneRollout.js +7 -3
  2. package/dist/assetTrust.js +14 -1
  3. package/dist/atp.d.ts +8 -3
  4. package/dist/atp.js +82 -11
  5. package/dist/atpAutoBuyer.d.ts +120 -0
  6. package/dist/atpAutoBuyer.js +814 -0
  7. package/dist/atpAutoDeliver.js +2 -2
  8. package/dist/autoDistillLlm.js +2 -1
  9. package/dist/autoDistillTranscript.js +3 -2
  10. package/dist/autoexec.d.ts +90 -13
  11. package/dist/autoexec.js +731 -84
  12. package/dist/cli.js +13 -0
  13. package/dist/cliContracts.d.ts +5 -2
  14. package/dist/cliContracts.js +135 -8
  15. package/dist/commands.d.ts +1 -0
  16. package/dist/commands.js +1 -0
  17. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  18. package/dist/curriculumCapabilityGaps.js +24 -0
  19. package/dist/cycleConsumer.d.ts +4 -0
  20. package/dist/cycleConsumer.js +175 -20
  21. package/dist/dashboard.js +47 -9
  22. package/dist/dispatch.js +6 -2
  23. package/dist/distillPrimitives.js +18 -6
  24. package/dist/doctor.js +63 -5
  25. package/dist/identityHome.js +2 -1
  26. package/dist/index.d.ts +67 -39
  27. package/dist/index.js +504 -185
  28. package/dist/learningTrace.js +8 -2
  29. package/dist/lifecycle.d.ts +54 -1
  30. package/dist/lifecycle.js +489 -37
  31. package/dist/materialSnapshot.d.ts +9 -1
  32. package/dist/materialSnapshot.js +23 -6
  33. package/dist/migrate/envTranslate.d.ts +26 -0
  34. package/dist/migrate/envTranslate.js +145 -0
  35. package/dist/migrate/oauthImport.d.ts +66 -0
  36. package/dist/migrate/oauthImport.js +667 -0
  37. package/dist/migrate/v1Import.d.ts +13 -1
  38. package/dist/migrate/v1Import.js +621 -122
  39. package/dist/promptRecallHook.d.ts +24 -0
  40. package/dist/promptRecallHook.js +425 -0
  41. package/dist/recallVerifyReport.d.ts +37 -0
  42. package/dist/recallVerifyReport.js +244 -0
  43. package/dist/requiredSandboxValidation.d.ts +5 -0
  44. package/dist/requiredSandboxValidation.js +4 -0
  45. package/dist/reuse.d.ts +1 -0
  46. package/dist/reuse.js +45 -37
  47. package/dist/runtimeCapabilities.js +13 -13
  48. package/dist/runtimeSessionSource.d.ts +3 -2
  49. package/dist/runtimeSessionSource.js +63 -11
  50. package/dist/sessionIngest.d.ts +37 -0
  51. package/dist/sessionIngest.js +156 -0
  52. package/dist/setupHooks.js +95 -1
  53. package/dist/skill2gep.d.ts +4 -7
  54. package/dist/skill2gep.js +4 -21
  55. package/dist/solo/mode.js +1 -0
  56. package/dist/sync.js +125 -23
  57. package/dist/thesis.d.ts +1 -1
  58. package/dist/thesis.js +18 -3
  59. package/dist/trajectoryExport.js +21 -3
  60. package/dist/v1Compat.d.ts +1 -0
  61. package/dist/v1Compat.js +9 -0
  62. package/dist/workflowRuntime.js +24 -18
  63. package/package.json +10 -7
package/dist/autoexec.js CHANGED
@@ -3,11 +3,13 @@
3
3
  // by single-flight so a slow pass never stacks. DENY-BY-DEFAULT: allowedRoots starts empty (refuses every
4
4
  // repo) until the operator explicitly allowlists one — autonomous edits to a real repo never happen by accident.
5
5
  import { homedir } from 'node:os';
6
- import { readdirSync, readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
7
8
  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 { events, assetstore, algo, exec, ops, observers, hooks, material as materialNs, util, verify, hub as hubNs, daemon as daemonNs, personality, signals as signalNs } from '@evomap/evolver-core';
10
+ import { runRequiredSandboxedValidation } from './requiredSandboxValidation.js';
9
11
  import { startResidentLoop } from './daemonLoop.js';
10
- import { connectPublicHub, createSolidifyPermitCheck, ReuseCache, reuseBeforeSolve, resolveConfiguredHubUrl, resolveHubUrl } from '@evomap/evolver-adapter-public';
12
+ import { connectPublicHub, createSolidifyPermitCheck, getMinReuseScore, ReuseCache, reuseBeforeSolve, resolveConfiguredHubUrl, resolveHubUrl, searchHubMetadata, } from '@evomap/evolver-adapter-public';
11
13
  import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
12
14
  import { resolveValueDigestObserver } from './valueDigest.js';
13
15
  import { resolveReflectionObserver } from './reflectionObserver.js';
@@ -17,10 +19,11 @@ import { resolveDistillObserver } from './distillObserver.js';
17
19
  import { resolveAutoDistillLlm } from './autoDistillLlm.js';
18
20
  import { resolveAutoDistillAntiGene as resolveAntiGeneDistill } from './autoDistillAntiGene.js';
19
21
  import { runTranscriptDistillTick, transcriptDistillMode } from './autoDistillTranscript.js';
20
- import { runSessionIngestTick, scanSessionDirs } from './index.js';
22
+ import { runSessionIngestTick, scanSessionDirs } from './sessionIngest.js';
21
23
  import { LocalMemoryGraph, resolveLocalMemoryUserIdentity } from './localMemoryGraph.js';
22
24
  import { resolveAtpAutoDeliver } from './atpAutoDeliver.js';
23
- import { resolveAtpHome, resolveAtpSenderId } from './atp.js';
25
+ import { createAtpClientFromEnv, getAtpConsent, resolveAtpHome, resolveAtpSenderId } from './atp.js';
26
+ import { AtpAutoBuyer } from './atpAutoBuyer.js';
24
27
  import { resolveExplicitNodeCredentials, resolveIdentityHome } from './identityHome.js';
25
28
  import { runAutobuyPrompt } from './atpAutobuyPrompt.js';
26
29
  import * as solomode from './solo/mode.js';
@@ -28,13 +31,20 @@ import * as gitGuard from './solo/gitGuard.js';
28
31
  import * as breaker from './solo/breaker.js';
29
32
  import { initializeWorkflowStartupRecovery } from './workflowRuntime.js';
30
33
  import { readAutoExecConfig } from './autoexecConfig.js';
34
+ import { makeCurriculumCapabilityGapsProvider } from './curriculumCapabilityGaps.js';
31
35
  import { resolveLearningTrace } from './learningTrace.js';
32
36
  export { readAutoExecConfig } from './autoexecConfig.js';
33
37
  const ENV_FILE_UNAVAILABLE_DIAGNOSTIC = '[evolver-autoexec] env_file_unavailable\n';
34
- /** Create the queue layout under <home>/autoexec/{tasks,done,refused}. */
38
+ /** Create the queue layout under <home>/autoexec/{tasks,inflight,done,refused}. */
35
39
  export function ensureAutoExecDirs(base) {
36
- const dirs = { base, tasks: join(base, 'tasks'), done: join(base, 'done'), refused: join(base, 'refused') };
37
- for (const dir of [dirs.tasks, dirs.done, dirs.refused])
40
+ const dirs = {
41
+ base,
42
+ tasks: join(base, 'tasks'),
43
+ inflight: join(base, 'inflight'),
44
+ done: join(base, 'done'),
45
+ refused: join(base, 'refused'),
46
+ };
47
+ for (const dir of [dirs.tasks, dirs.inflight, receiptDir(dirs), dirs.done, dirs.refused])
38
48
  mkdirSync(dir, { recursive: true });
39
49
  return dirs;
40
50
  }
@@ -67,40 +77,312 @@ export function summarizeSandboxedValidation(result) {
67
77
  function createAutoExecPersonalityStore() {
68
78
  return new personality.PersonalityStore();
69
79
  }
80
+ const CLAIMED_TASK_SUFFIX = '.claimed.json';
81
+ const STARTED_TASK_SUFFIX = '.started.json';
82
+ const AMBIGUOUS_RECOVERY_REASON = 'autoexec_crash_recovery_ambiguous: execution may have started before shutdown; refusing automatic retry, explicitly requeue after inspecting prior side effects';
83
+ function receiptDir(dirs) {
84
+ return join(dirs.base, 'receipts');
85
+ }
86
+ const RECEIPT_TEMP_SUFFIX = /^(.*\.started\.json)\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/i;
87
+ function receiptArtifactClaimName(name) {
88
+ const tempMatch = RECEIPT_TEMP_SUFFIX.exec(name);
89
+ const claimName = tempMatch?.[1] ?? name;
90
+ const claim = parseAutoExecClaim(claimName);
91
+ if (!claim || claim.name !== claimName)
92
+ return null;
93
+ if (tempMatch)
94
+ return claim.phase === 'started' ? claimName : null;
95
+ return claim.phase === 'started' || claim.phase === 'legacy' ? claimName : null;
96
+ }
97
+ function cleanupReceiptArtifacts(dirs, shouldRemove) {
98
+ const dir = receiptDir(dirs);
99
+ let entries;
100
+ try {
101
+ entries = readdirSync(dir, { withFileTypes: true });
102
+ }
103
+ catch {
104
+ return;
105
+ }
106
+ for (const entry of entries) {
107
+ if (!entry.isFile())
108
+ continue;
109
+ const claimName = receiptArtifactClaimName(entry.name);
110
+ if (!claimName || !shouldRemove(claimName))
111
+ continue;
112
+ try {
113
+ unlinkSync(join(dir, entry.name));
114
+ }
115
+ catch {
116
+ // Cleanup is retried by the next pass after the claim has been archived.
117
+ }
118
+ }
119
+ }
120
+ function cleanupCommittedClaimReceipt(dirs, claimName) {
121
+ const path = join(receiptDir(dirs), claimName);
122
+ try {
123
+ if (lstatSync(path).isFile())
124
+ unlinkSync(path);
125
+ }
126
+ catch {
127
+ // Orphan cleanup retries this after the claim has been archived.
128
+ }
129
+ }
130
+ function cleanupOrphanReceiptArtifacts(dirs) {
131
+ let activeClaims;
132
+ try {
133
+ activeClaims = new Set(readdirSync(dirs.inflight, { withFileTypes: true })
134
+ .filter((entry) => entry.isFile())
135
+ .map((entry) => entry.name));
136
+ }
137
+ catch {
138
+ return;
139
+ }
140
+ cleanupReceiptArtifacts(dirs, (claimName) => !activeClaims.has(claimName));
141
+ }
142
+ function parseAutoExecClaim(name) {
143
+ const separator = name.indexOf('--');
144
+ if (separator < 0 || separator + 2 >= name.length)
145
+ return null;
146
+ const encodedName = name.slice(separator + 2);
147
+ if (encodedName.endsWith(CLAIMED_TASK_SUFFIX)) {
148
+ return {
149
+ name,
150
+ originalName: `${encodedName.slice(0, -CLAIMED_TASK_SUFFIX.length)}.json`,
151
+ phase: 'claimed',
152
+ };
153
+ }
154
+ if (encodedName.endsWith(STARTED_TASK_SUFFIX)) {
155
+ return {
156
+ name,
157
+ originalName: `${encodedName.slice(0, -STARTED_TASK_SUFFIX.length)}.json`,
158
+ phase: 'started',
159
+ };
160
+ }
161
+ return encodedName.endsWith('.json') ? { name, originalName: encodedName, phase: 'legacy' } : null;
162
+ }
163
+ function taskClaimName(originalName) {
164
+ return `${randomUUID()}--${originalName.slice(0, -'.json'.length)}${CLAIMED_TASK_SUFFIX}`;
165
+ }
166
+ function archiveTaskPath(dest, originalName, claimName) {
167
+ const defaultArchive = join(dest, `task-${originalName}`);
168
+ return existsSync(defaultArchive) ? join(dest, `task-${claimName}`) : defaultArchive;
169
+ }
170
+ function isAutoExecVerdict(value, taskId) {
171
+ if (!value || typeof value !== 'object')
172
+ return false;
173
+ const candidate = value;
174
+ return candidate.taskId === taskId
175
+ && (candidate.status === 'refused'
176
+ || candidate.status === 'skipped'
177
+ || candidate.status === 'solidified'
178
+ || candidate.status === 'failed'
179
+ || candidate.status === 'innovated');
180
+ }
181
+ function persistedClaimReceipt(dirs, claim, taskId) {
182
+ try {
183
+ const path = join(receiptDir(dirs), claim.name);
184
+ if (!lstatSync(path).isFile())
185
+ return null;
186
+ const value = JSON.parse(readFileSync(path, 'utf8'));
187
+ if (!value || typeof value !== 'object')
188
+ return null;
189
+ const receipt = value;
190
+ if (receipt.claimName !== claim.name
191
+ || (receipt.destination !== 'done' && receipt.destination !== 'refused')
192
+ || !isAutoExecVerdict(receipt.verdict, taskId))
193
+ return null;
194
+ const expectedDestination = receipt.verdict.status === 'refused' ? 'refused' : 'done';
195
+ if (receipt.destination !== expectedDestination)
196
+ return null;
197
+ return receipt;
198
+ }
199
+ catch (error) {
200
+ if (error.code !== 'ENOENT'
201
+ && !(error instanceof SyntaxError))
202
+ throw error;
203
+ return null;
204
+ }
205
+ }
206
+ function persistClaimReceipt(dirs, receipt) {
207
+ const receipts = receiptDir(dirs);
208
+ const receiptPath = join(receipts, receipt.claimName);
209
+ const tempPath = join(receipts, `${receipt.claimName}.${randomUUID()}.tmp`);
210
+ try {
211
+ writeFileSync(tempPath, JSON.stringify(receipt, null, 2), { encoding: 'utf8', flag: 'wx' });
212
+ renameSync(tempPath, receiptPath);
213
+ }
214
+ finally {
215
+ try {
216
+ if (lstatSync(tempPath).isFile())
217
+ unlinkSync(tempPath);
218
+ }
219
+ catch {
220
+ // The atomic rename normally removes the temp path.
221
+ }
222
+ }
223
+ }
224
+ function recoverAmbiguousClaim(dirs, claim) {
225
+ const taskPath = join(dirs.inflight, claim.name);
226
+ let taskId = `recovery-${claim.name.slice(0, 64)}`;
227
+ try {
228
+ taskId = exec.normalizeAutoExecTask(JSON.parse(readFileSync(taskPath, 'utf8'))).id;
229
+ }
230
+ catch {
231
+ // The task may have been only partially published before the prior process stopped.
232
+ }
233
+ const receipt = persistedClaimReceipt(dirs, claim, taskId);
234
+ if (receipt) {
235
+ const dest = receipt.destination === 'refused' ? dirs.refused : dirs.done;
236
+ const canonicalVerdict = join(dest, claim.originalName);
237
+ writeFileSync(canonicalVerdict, JSON.stringify(receipt.verdict, null, 2));
238
+ renameSync(taskPath, archiveTaskPath(dest, claim.originalName, claim.name));
239
+ cleanupCommittedClaimReceipt(dirs, claim.name);
240
+ return receipt.verdict;
241
+ }
242
+ const verdict = {
243
+ taskId,
244
+ status: 'refused',
245
+ reason: AMBIGUOUS_RECOVERY_REASON,
246
+ };
247
+ writeFileSync(join(dirs.refused, `recovery-${claim.name}`), JSON.stringify(verdict, null, 2));
248
+ renameSync(taskPath, archiveTaskPath(dirs.refused, claim.originalName, claim.name));
249
+ cleanupCommittedClaimReceipt(dirs, claim.name);
250
+ return verdict;
251
+ }
70
252
  /**
71
- * One queue pass: drain every tasks/*.json through `runOne`, route the verdict to done/ (success or failure)
72
- * or refused/ (deny-by-default), and move the task file out of the queue. Sequential; returns the verdicts.
253
+ * One queue pass: atomically claim regular tasks/*.json into inflight/, then route each verdict to done/
254
+ * (success or failure) or refused/ (deny-by-default). A claim is atomically marked started before runOne;
255
+ * after a crash, started and legacy claims are ambiguous and fail closed instead of repeating side effects.
256
+ * Unreadable or incomplete claimed tasks stay pending because the drop-directory has no atomic publish marker.
73
257
  */
74
- export async function autoExecPass(dirs, runOne) {
75
- const files = readdirSync(dirs.tasks).filter((f) => f.endsWith('.json'));
258
+ export async function autoExecPass(dirs, runOne, options = {}) {
259
+ const executePendingTasks = options.executePendingTasks ?? true;
260
+ const existingClaims = readdirSync(dirs.inflight, { withFileTypes: true })
261
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.json'))
262
+ .map((entry) => parseAutoExecClaim(entry.name))
263
+ .filter((claim) => claim !== null);
264
+ cleanupOrphanReceiptArtifacts(dirs);
265
+ const pendingClaims = existingClaims.filter((claim) => claim.phase === 'claimed');
76
266
  const out = [];
267
+ for (const claim of existingClaims.filter((item) => item.phase !== 'claimed')) {
268
+ try {
269
+ out.push(recoverAmbiguousClaim(dirs, claim));
270
+ }
271
+ catch (error) {
272
+ const errorCode = error.code;
273
+ out.push({
274
+ taskId: `recovery-${claim.name.slice(0, claim.name.indexOf('--'))}`,
275
+ status: 'failed',
276
+ reason: `autoexec_crash_recovery_failed:${errorCode && /^[A-Z0-9_]+$/.test(errorCode) ? errorCode : 'unknown'}`,
277
+ });
278
+ }
279
+ }
280
+ cleanupOrphanReceiptArtifacts(dirs);
281
+ if (!executePendingTasks)
282
+ return out;
283
+ const files = readdirSync(dirs.tasks, { withFileTypes: true })
284
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.json'))
285
+ .map((entry) => entry.name);
77
286
  for (const f of files) {
78
- const task = exec.normalizeAutoExecTask(JSON.parse(readFileSync(join(dirs.tasks, f), 'utf8')));
287
+ const claimName = taskClaimName(f);
288
+ try {
289
+ renameSync(join(dirs.tasks, f), join(dirs.inflight, claimName));
290
+ const claim = parseAutoExecClaim(claimName);
291
+ if (claim)
292
+ pendingClaims.push(claim);
293
+ }
294
+ catch (error) {
295
+ if (error.code !== 'ENOENT')
296
+ throw error;
297
+ }
298
+ }
299
+ for (const claim of pendingClaims) {
300
+ const taskPath = join(dirs.inflight, claim.name);
301
+ let task;
302
+ try {
303
+ task = exec.normalizeAutoExecTask(JSON.parse(readFileSync(taskPath, 'utf8')));
304
+ }
305
+ catch {
306
+ // A producer may still hold this path open and finish writing it after this pass.
307
+ // Leaving it in place prevents a transient partial read from acknowledging and losing the task.
308
+ continue;
309
+ }
310
+ const startedName = claim.name.slice(0, -CLAIMED_TASK_SUFFIX.length) + STARTED_TASK_SUFFIX;
311
+ const startedPath = join(dirs.inflight, startedName);
312
+ renameSync(taskPath, startedPath);
79
313
  const v = await runOne(task).catch((e) => ({ taskId: task.id, status: 'failed', reason: e instanceof Error ? e.message : String(e) }));
80
- const dest = v.status === 'refused' ? dirs.refused : dirs.done;
81
- writeFileSync(join(dest, f), JSON.stringify(v, null, 2));
82
- renameSync(join(dirs.tasks, f), join(dest, `task-${f}`));
314
+ const destination = v.status === 'refused' ? 'refused' : 'done';
315
+ const dest = destination === 'refused' ? dirs.refused : dirs.done;
316
+ persistClaimReceipt(dirs, { claimName: startedName, destination, verdict: v });
317
+ writeFileSync(join(dest, claim.originalName), JSON.stringify(v, null, 2));
318
+ renameSync(startedPath, archiveTaskPath(dest, claim.originalName, startedName));
319
+ cleanupCommittedClaimReceipt(dirs, startedName);
83
320
  out.push(v);
84
321
  }
322
+ cleanupOrphanReceiptArtifacts(dirs);
85
323
  return out;
86
324
  }
87
- /**
88
- * Build the reuse-before-solve seam (#110) — THE real injection point. This is the public-repo composition
89
- * layer that owns BOTH core's autoexec kernel and the adapter's hub capability, so it is where the adapter's
90
- * `reuseBeforeSolve` is adapted into core's hub-agnostic `HubReuseSeam` (core never imports the adapter).
91
- * Flow: free hub search → core's pure score/decide → paid fetch for AT MOST ONE winner → the winner enters the
92
- * SAME selection pool as local genes (trust-first). The two-layer cache is owned HERE so it warms across passes
93
- * (a repeat signal set → zero hub calls). Off by default: only wired when EVOLVER_REUSE_BEFORE_SOLVE === '1'
94
- * AND a hub credential exists (no token → no seam → zero hub calls, exactly today's behavior).
95
- */
96
- export function makeHubReuseSeam(cap, cache, ingestor, onAssetReused) {
325
+ /** Keep unsupported built-in runners away from the execution queue without stopping the resident daemon. */
326
+ export function runnerBoundAutoExecPass(runner, dirs, runOne) {
327
+ return () => autoExecPass(dirs, runOne, { executePendingTasks: runner === 'gemini' });
328
+ }
329
+ const ATP_CAPABILITY_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,47}$/;
330
+ function atpCapabilityGaps(signals) {
331
+ return signalNs.capabilityGapsFromSignals(signals)
332
+ .filter((capability) => ATP_CAPABILITY_PATTERN.test(capability))
333
+ .slice(0, 8);
334
+ }
335
+ function hasAtpCapabilityGap(signals) {
336
+ return signals.includes('capability_gap') || atpCapabilityGaps(signals).length > 0;
337
+ }
338
+ function normalizedCapabilityGapSignals(signals) {
339
+ if (!hasAtpCapabilityGap(signals))
340
+ return signals;
341
+ const ordinary = signals.filter((signal) => signal !== 'capability_gap'
342
+ && !signal.startsWith('capability_gap:')
343
+ && !signal.startsWith('cap:'));
344
+ return [...new Set([...ordinary, ...atpCapabilityGapRequest(signals).signals])];
345
+ }
346
+ /** Build the deliberately small, public-safe ATP request allowed to leave autoexec after a verified Hub miss. */
347
+ export function atpCapabilityGapRequest(signals) {
348
+ const capabilities = atpCapabilityGaps(signals);
349
+ if (capabilities.length === 0)
350
+ capabilities.push('code_evolution');
351
+ const subject = capabilities[0].replace(/[_-]+/g, ' ');
352
+ return {
353
+ kind: 'capability_gap',
354
+ capabilities,
355
+ question: `I need help with ${subject}. Please provide one concrete, actionable solution and state any assumptions.`,
356
+ routingMode: 'fastest',
357
+ verifyMode: 'auto',
358
+ signals: ['capability_gap', ...capabilities.map((capability) => `cap:${capability}`)],
359
+ };
360
+ }
361
+ /** Schedule economic work outside the reuse/task critical path and contain all asynchronous failures. */
362
+ export function scheduleAtpAutoBuyForVerifiedMiss(miss, buyer) {
363
+ void buyer.consider(atpCapabilityGapRequest(miss.signals)).catch(() => undefined);
364
+ }
365
+ /** Resolve an autonomous buyer only after an explicit env/ack consent check; the buyer checks consent again. */
366
+ export function resolveAtpAutoBuyer(env = process.env, createClient = createAtpClientFromEnv) {
367
+ if (!getAtpConsent(env).enabled)
368
+ return undefined;
369
+ try {
370
+ return new AtpAutoBuyer({ client: createClient(env), env });
371
+ }
372
+ catch {
373
+ return undefined;
374
+ }
375
+ }
376
+ export function makeHubReuseSeam(cap, cache, ingestor, onAssetReused, onVerifiedSearchMiss, audit = {}) {
97
377
  return async (signals, ctx) => {
378
+ const searchSignals = normalizedCapabilityGapSignals(signals);
98
379
  // Pending value.reuse_hit ingests (#112). The onReuseHit callback is synchronous, so it cannot await the
99
380
  // ingest itself; it stashes the (error-swallowing) promise here and the seam awaits them before returning,
100
381
  // making the emission deterministically durable without letting an ingest error ever break reuse.
101
382
  const pending = [];
102
- const r = await reuseBeforeSolve(cap, cache, signals, {
383
+ const r = await reuseBeforeSolve(cap, cache, searchSignals, {
103
384
  ...(ctx?.cycleId ? { cycleId: ctx.cycleId } : {}),
385
+ ...(audit.env ? { env: audit.env } : {}),
104
386
  // Two consumers hang off a reuse HIT:
105
387
  // - value-ledger emission (#112): a `value.reuse_hit` root_event so the ledger derives a real
106
388
  // source=reuse entry (refs → assetId + cycleId) — live wiring, not a fixture;
@@ -118,9 +400,149 @@ export function makeHubReuseSeam(cap, cache, ingestor, onAssetReused) {
118
400
  });
119
401
  if (pending.length > 0)
120
402
  await Promise.all(pending); // emitReuseHit never rejects (it swallows ingest errors)
403
+ const runId = ctx?.cycleId ?? null;
404
+ const taskId = runId?.startsWith('autoexec-') ? runId.slice('autoexec-'.length) : undefined;
405
+ if (r.action === 'fetch') {
406
+ const rawAsset = r.asset;
407
+ const assetId = r.candidate?.assetId ?? stringField(rawAsset, 'asset_id');
408
+ const assetType = stringField(rawAsset, 'type');
409
+ const sourceNodeId = stringField(rawAsset, 'source_node_id');
410
+ const chainId = stringField(rawAsset, 'chain_id');
411
+ const indexedTokenCost = assetId ? assetTokenCostBestEffort(audit.assetLog, assetId) : undefined;
412
+ const savings = hubNs.reuseSavingsForAsset(rawAsset, r.mode, indexedTokenCost);
413
+ const hit = {
414
+ runId,
415
+ ...(assetId ? { assetId } : {}),
416
+ ...(assetType ? { assetType } : {}),
417
+ ...(sourceNodeId ? { sourceNodeId } : {}),
418
+ ...(chainId ? { chainId } : {}),
419
+ ...(r.score !== undefined ? { score: r.score } : {}),
420
+ mode: r.mode,
421
+ signals: [...searchSignals],
422
+ tokensSaved: savings.tokens_saved,
423
+ tokensSavedBasis: savings.tokens_saved_basis,
424
+ };
425
+ scheduleAssetCallBestEffort(audit.assetLog, {
426
+ run_id: runId,
427
+ action: 'hub_search_hit',
428
+ ...(hit.assetId ? { asset_id: hit.assetId } : {}),
429
+ ...(hit.assetType ? { asset_type: hit.assetType } : {}),
430
+ ...(hit.sourceNodeId ? { source_node_id: hit.sourceNodeId } : {}),
431
+ ...(hit.chainId ? { chain_id: hit.chainId } : {}),
432
+ ...(hit.score !== undefined ? { score: hit.score } : {}),
433
+ mode: hit.mode,
434
+ signals: hit.signals,
435
+ ...(taskId ? { extra: { task_id: taskId } } : {}),
436
+ });
437
+ try {
438
+ audit.onSearchHit?.(hit);
439
+ }
440
+ catch { /* audit state must never change reuse */ }
441
+ }
442
+ else if (r.reason !== 'no_signals') {
443
+ scheduleAssetCallBestEffort(audit.assetLog, {
444
+ run_id: runId,
445
+ action: 'hub_search_miss',
446
+ mode: r.mode,
447
+ signals: [...searchSignals],
448
+ ...(r.reason ? { reason: r.reason } : {}),
449
+ ...(taskId ? { extra: { task_id: taskId } } : {}),
450
+ });
451
+ }
452
+ if (r.action === 'solve-fresh'
453
+ && (r.reason === 'no_results' || r.reason === 'below_threshold')
454
+ && hasAtpCapabilityGap(searchSignals)) {
455
+ try {
456
+ onVerifiedSearchMiss?.({
457
+ reason: r.reason,
458
+ signals: [...searchSignals],
459
+ ...(ctx?.cycleId ? { cycleId: ctx.cycleId } : {}),
460
+ });
461
+ }
462
+ catch { /* an optional economic side effect must never change reuse behavior */ }
463
+ }
121
464
  return r.action === 'fetch' && r.candidate ? [r.candidate] : [];
122
465
  };
123
466
  }
467
+ /**
468
+ * Free search-only seam used by ATP auto-buy when reuse injection is disabled. It proves a capability miss with
469
+ * the same dual-leg search and score threshold as reuse, but never performs the paid fetch or contributes a Hub
470
+ * candidate.
471
+ */
472
+ export function makeHubSearchMissProbe(cap, cache, onVerifiedSearchMiss, enabled, env = process.env, assetLog) {
473
+ return async (signals, ctx) => {
474
+ if (!enabled() || !hasAtpCapabilityGap(signals))
475
+ return [];
476
+ // ATP consent authorizes a bounded capability query, not disclosure of local error signatures/transcripts.
477
+ const signalList = atpCapabilityGapRequest(signals).signals;
478
+ if (signalList.length === 0)
479
+ return [];
480
+ const search = await searchHubMetadata(cap, cache, signalList, { env });
481
+ if (!search.complete) {
482
+ scheduleAssetCallBestEffort(assetLog, {
483
+ run_id: ctx?.cycleId ?? null,
484
+ action: 'hub_search_miss',
485
+ mode: 'direct',
486
+ signals: search.signals,
487
+ reason: 'search_error',
488
+ });
489
+ return [];
490
+ }
491
+ const { metadata, searchCached } = search;
492
+ let reason;
493
+ if (metadata.length === 0) {
494
+ reason = 'no_results';
495
+ }
496
+ else {
497
+ const ranked = hubNs.scoreSearchResults(signalList, metadata);
498
+ if (hubNs.decideReuse(ranked, { threshold: getMinReuseScore(env) }).action === 'solve-fresh') {
499
+ reason = 'below_threshold';
500
+ }
501
+ }
502
+ if (!reason)
503
+ return [];
504
+ scheduleAssetCallBestEffort(assetLog, {
505
+ run_id: ctx?.cycleId ?? null,
506
+ action: 'hub_search_miss',
507
+ mode: 'direct',
508
+ signals: signalList,
509
+ reason,
510
+ extra: { search_cached: searchCached },
511
+ });
512
+ try {
513
+ onVerifiedSearchMiss({
514
+ reason,
515
+ signals: signalList,
516
+ ...(ctx?.cycleId ? { cycleId: ctx.cycleId } : {}),
517
+ });
518
+ }
519
+ catch { /* ATP scheduling must never change the solve path */ }
520
+ return [];
521
+ };
522
+ }
523
+ function stringField(record, key) {
524
+ const value = record?.[key];
525
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
526
+ }
527
+ function assetTokenCostBestEffort(log, assetId) {
528
+ try {
529
+ return log?.assetCostIndex?.()[assetId];
530
+ }
531
+ catch {
532
+ return undefined;
533
+ }
534
+ }
535
+ function appendAssetCallBestEffort(log, entry) {
536
+ try {
537
+ log?.append(entry);
538
+ }
539
+ catch { /* local audit failure must never break reuse or task completion */ }
540
+ }
541
+ function scheduleAssetCallBestEffort(log, entry) {
542
+ if (!log)
543
+ return;
544
+ setImmediate(() => { appendAssetCallBestEffort(log, entry); });
545
+ }
124
546
  /** Append a `value.reuse_hit` root_event for a reuse hit (#112). Never throws (reuse stays an optimization). */
125
547
  async function emitReuseHit(ingestor, hit) {
126
548
  try {
@@ -220,6 +642,52 @@ function writeQuestionState(path, state) {
220
642
  recentQuestions: [...(state.recentQuestions ?? [])].slice(-30),
221
643
  }, null, 2)}\n`);
222
644
  }
645
+ function laterQuestionTimestamp(left, right) {
646
+ if (!left)
647
+ return right ?? null;
648
+ if (!right)
649
+ return left;
650
+ const leftMs = Date.parse(left);
651
+ const rightMs = Date.parse(right);
652
+ if (Number.isFinite(leftMs) && Number.isFinite(rightMs))
653
+ return rightMs >= leftMs ? right : left;
654
+ if (Number.isFinite(leftMs))
655
+ return left;
656
+ if (Number.isFinite(rightMs))
657
+ return right;
658
+ return right >= left ? right : left;
659
+ }
660
+ function mergeQuestionStates(current, incoming) {
661
+ const recency = (state) => Math.max(...[state.lastAskedAt, state.lastUrgentAt, state.lastExploreAt]
662
+ .map((value) => value ? Date.parse(value) : Number.NEGATIVE_INFINITY)
663
+ .filter(Number.isFinite), Number.NEGATIVE_INFINITY);
664
+ const [older, newer] = recency(current) <= recency(incoming)
665
+ ? [current, incoming]
666
+ : [incoming, current];
667
+ const recentQuestions = [];
668
+ for (const question of [...(older.recentQuestions ?? []), ...(newer.recentQuestions ?? [])]) {
669
+ const existing = recentQuestions.indexOf(question);
670
+ if (existing >= 0)
671
+ recentQuestions.splice(existing, 1);
672
+ recentQuestions.push(question);
673
+ }
674
+ return {
675
+ lastAskedAt: laterQuestionTimestamp(current.lastAskedAt, incoming.lastAskedAt),
676
+ lastUrgentAt: laterQuestionTimestamp(current.lastUrgentAt, incoming.lastUrgentAt),
677
+ lastExploreAt: laterQuestionTimestamp(current.lastExploreAt, incoming.lastExploreAt),
678
+ recentQuestions: recentQuestions.slice(-30),
679
+ };
680
+ }
681
+ const MAX_PENDING_QUESTION_STATES = 30;
682
+ function rememberPendingQuestionState(pendingStates, state) {
683
+ pendingStates.add(state);
684
+ while (pendingStates.size > MAX_PENDING_QUESTION_STATES) {
685
+ const oldest = pendingStates.values().next().value;
686
+ if (!oldest)
687
+ break;
688
+ pendingStates.delete(oldest);
689
+ }
690
+ }
223
691
  function questionSubmitTimeoutMs(options) {
224
692
  const raw = options.timeoutMs ?? Number(options.env?.[QUESTION_SUBMIT_TIMEOUT_ENV]);
225
693
  if (Number.isFinite(raw) && raw > 0)
@@ -239,11 +707,12 @@ function hasAcceptedQuestionReceipt(receipts) {
239
707
  function writeQuestionStateIfAccepted(path, state, receipts) {
240
708
  if (!hasAcceptedQuestionReceipt(receipts))
241
709
  return false;
242
- writeQuestionState(path, state);
710
+ writeQuestionState(path, mergeQuestionStates(readQuestionState(path), state));
243
711
  return true;
244
712
  }
245
- function writeLateQuestionStateIfAccepted(submitResult, statePath, state) {
246
- void submitResult.then((submitted) => {
713
+ function writeLateQuestionStateIfAccepted(submitResult, statePath, state, onSettled) {
714
+ void submitResult
715
+ .then((submitted) => {
247
716
  if (submitted.status !== 'submitted')
248
717
  return;
249
718
  try {
@@ -252,7 +721,8 @@ function writeLateQuestionStateIfAccepted(submitResult, statePath, state) {
252
721
  catch {
253
722
  // The caller already received a timeout; late cooldown persistence is best-effort.
254
723
  }
255
- });
724
+ })
725
+ .finally(onSettled);
256
726
  }
257
727
  async function submitQuestionsWithTimeout(submitResult, timeoutMs) {
258
728
  let timer;
@@ -269,7 +739,7 @@ async function submitQuestionsWithTimeout(submitResult, timeoutMs) {
269
739
  clearTimeout(timer);
270
740
  }
271
741
  }
272
- async function submitProactiveQuestions(cap, task, options) {
742
+ async function submitProactiveQuestions(cap, task, options, pendingStates) {
273
743
  if (options.enabled === false || !cap.questions)
274
744
  return { status: 'disabled', questionCount: 0 };
275
745
  try {
@@ -279,10 +749,11 @@ async function submitProactiveQuestions(cap, task, options) {
279
749
  return { status: 'skipped', questionCount: 0 };
280
750
  if (QUESTION_CONTEXT_SENSITIVE_RE.test(context))
281
751
  return { status: 'skipped', questionCount: 0 };
752
+ const effectiveState = [...pendingStates].reduce((state, pending) => mergeQuestionStates(state, pending), readQuestionState(statePath));
282
753
  const result = hubNs.generateQuestions({
283
754
  signals: task.signals,
284
755
  sessionTranscript: context,
285
- state: readQuestionState(statePath),
756
+ state: effectiveState,
286
757
  now: options.now?.() ?? Date.now(),
287
758
  env: options.env ?? process.env,
288
759
  });
@@ -290,8 +761,10 @@ async function submitProactiveQuestions(cap, task, options) {
290
761
  return { status: 'skipped', questionCount: 0 };
291
762
  const submitResult = observeQuestionSubmit(cap.questions.submit(result.questions));
292
763
  const submitted = await submitQuestionsWithTimeout(submitResult, questionSubmitTimeoutMs(options));
293
- if (submitted.status === 'timeout')
294
- writeLateQuestionStateIfAccepted(submitResult, statePath, result.state);
764
+ if (submitted.status === 'timeout') {
765
+ rememberPendingQuestionState(pendingStates, result.state);
766
+ writeLateQuestionStateIfAccepted(submitResult, statePath, result.state, () => pendingStates.delete(result.state));
767
+ }
295
768
  if (submitted.status !== 'submitted')
296
769
  return { status: submitted.status, questionCount: result.questions.length };
297
770
  if (!writeQuestionStateIfAccepted(statePath, result.state, submitted.receipts))
@@ -305,9 +778,10 @@ async function submitProactiveQuestions(cap, task, options) {
305
778
  }
306
779
  export function makeHubQuestionLink(cap, options = {}) {
307
780
  let queue = Promise.resolve();
781
+ const pendingStates = new Set();
308
782
  return {
309
783
  submitForTask: (task) => {
310
- const run = queue.then(() => submitProactiveQuestions(cap, task, options));
784
+ const run = queue.then(() => submitProactiveQuestions(cap, task, options, pendingStates));
311
785
  queue = run.then(() => undefined, () => undefined);
312
786
  return run;
313
787
  },
@@ -350,6 +824,94 @@ export function releaseAutoexecLock(lockPath, deps = {}) {
350
824
  return false;
351
825
  }
352
826
  }
827
+ /** Keep a detached daemon alive when its output consumer closes, without hiding other stream failures. */
828
+ export function installAutoexecBrokenPipeGuards(deps = {}) {
829
+ const stdout = deps.stdout ?? process.stdout;
830
+ const stderr = deps.stderr ?? process.stderr;
831
+ const onError = (error) => {
832
+ if (error?.code === 'EPIPE')
833
+ return;
834
+ throw error;
835
+ };
836
+ stdout.on('error', onError);
837
+ stderr.on('error', onError);
838
+ let installed = true;
839
+ return () => {
840
+ if (!installed)
841
+ return;
842
+ installed = false;
843
+ removeAutoexecStreamErrorListener(stdout, onError);
844
+ removeAutoexecStreamErrorListener(stderr, onError);
845
+ };
846
+ }
847
+ function removeAutoexecStreamErrorListener(stream, listener) {
848
+ if (stream.off) {
849
+ stream.off('error', listener);
850
+ return;
851
+ }
852
+ stream.removeListener?.('error', listener);
853
+ }
854
+ /**
855
+ * Own autoexec's process-signal lifetime. V2 intentionally has no hot-reload seam: SIGHUP is informational and
856
+ * keeps the current generation alive; SIGINT/SIGTERM drain the resident loop before cleanup and exit.
857
+ */
858
+ export function waitForAutoexecShutdown(deps) {
859
+ const signals = deps.signals ?? process;
860
+ const write = deps.write ?? ((message) => { process.stdout.write(message); });
861
+ return new Promise((resolve, reject) => {
862
+ let stopping = false;
863
+ let listenersInstalled = true;
864
+ const removeListeners = () => {
865
+ if (!listenersInstalled)
866
+ return;
867
+ listenersInstalled = false;
868
+ for (const [signal, listener] of listeners)
869
+ removeAutoexecSignalListener(signals, signal, listener);
870
+ };
871
+ const finish = (failure) => {
872
+ removeListeners();
873
+ try {
874
+ deps.cleanup();
875
+ }
876
+ catch (cleanupError) {
877
+ reject(cleanupError);
878
+ return;
879
+ }
880
+ if (failure)
881
+ reject(failure.error);
882
+ else
883
+ resolve(0);
884
+ };
885
+ const shutdown = (signal) => {
886
+ if (stopping)
887
+ return;
888
+ stopping = true;
889
+ write(`\nevolver autoexec: ${signal} -> graceful stop (finishing in-flight, releasing lock)\n`);
890
+ void Promise.resolve()
891
+ .then(() => deps.stop())
892
+ .then(() => { finish(); }, (error) => { finish({ error }); });
893
+ };
894
+ const onSighup = () => {
895
+ if (stopping)
896
+ return;
897
+ write('\nevolver autoexec: SIGHUP received; hot reload is not supported, continuing with current configuration (restart the daemon to apply changes)\n');
898
+ };
899
+ const listeners = [
900
+ ['SIGINT', () => { shutdown('SIGINT'); }],
901
+ ['SIGTERM', () => { shutdown('SIGTERM'); }],
902
+ ['SIGHUP', onSighup],
903
+ ];
904
+ for (const [signal, listener] of listeners)
905
+ signals.on(signal, listener);
906
+ });
907
+ }
908
+ function removeAutoexecSignalListener(source, signal, listener) {
909
+ if (source.off) {
910
+ source.off(signal, listener);
911
+ return;
912
+ }
913
+ source.removeListener?.(signal, listener);
914
+ }
353
915
  export function urgentQuestionRuntimeWiringStatus() {
354
916
  return hubNs.URGENT_QUESTION_RUNTIME_WIRING_STATUS;
355
917
  }
@@ -415,19 +977,60 @@ export function scheduleAutoExecHubSideEffects(task, verdict, links) {
415
977
  * candidate can be withheld by trust/review gates or lose selection, so fetch-time attribution would overclaim.
416
978
  * Reporting never throws and never blocks the verdict.
417
979
  */
418
- export function makeHubLink(cap, ingestor, reportEnabled = true) {
419
- const seam = makeHubReuseSeam(cap, new ReuseCache(), ingestor);
980
+ export function makeHubLink(cap, ingestor, reportEnabled = true, onVerifiedSearchMiss, assetLog, env) {
981
+ const maxPendingAuditRuns = 256;
982
+ const searchHitsByRun = new Map();
983
+ const seam = makeHubReuseSeam(cap, new ReuseCache(), ingestor, undefined, onVerifiedSearchMiss, {
984
+ assetLog,
985
+ ...(env ? { env } : {}),
986
+ onSearchHit: (hit) => {
987
+ if (!hit.runId || !hit.assetId)
988
+ return;
989
+ if (!searchHitsByRun.has(hit.runId) && searchHitsByRun.size >= maxPendingAuditRuns) {
990
+ const oldestRun = searchHitsByRun.keys().next().value;
991
+ if (oldestRun !== undefined)
992
+ searchHitsByRun.delete(oldestRun);
993
+ }
994
+ // One reuse-before-solve invocation can fetch at most one winner. Replace any stale state left by an
995
+ // unexpectedly aborted earlier run that reused the same task id.
996
+ searchHitsByRun.set(hit.runId, new Map([[hit.assetId, hit]]));
997
+ },
998
+ });
420
999
  return {
421
1000
  seam,
422
1001
  reportOutcome: async (task, verdict) => {
423
- if (!reportEnabled)
424
- return;
425
1002
  const status = verdictToOutcomeStatus(verdict.status);
426
- if (status === null)
427
- return;
1003
+ const runId = `autoexec-${task.id}`;
1004
+ const searchHits = searchHitsByRun.get(runId);
1005
+ searchHitsByRun.delete(runId);
428
1006
  const usedAssetIds = Array.isArray(verdict.usedAssetIds)
429
1007
  ? [...new Set(verdict.usedAssetIds.filter((id) => typeof id === 'string' && id.length > 0))]
430
1008
  : [];
1009
+ // Drain attribution synchronously (before a duplicate task id can start), then yield before the production
1010
+ // sink's synchronous append and all Hub I/O. The detached side effect cannot delay routing to done/.
1011
+ await new Promise((resolve) => { setImmediate(resolve); });
1012
+ if (status !== null) {
1013
+ for (const assetId of usedAssetIds) {
1014
+ const hit = searchHits?.get(assetId);
1015
+ const mode = hit?.mode;
1016
+ appendAssetCallBestEffort(assetLog, {
1017
+ run_id: runId,
1018
+ action: mode === 'reference' ? 'asset_reference' : 'asset_reuse',
1019
+ asset_id: assetId,
1020
+ ...(hit?.assetType ? { asset_type: hit.assetType } : {}),
1021
+ ...(hit?.sourceNodeId ? { source_node_id: hit.sourceNodeId } : {}),
1022
+ ...(hit?.chainId ? { chain_id: hit.chainId } : {}),
1023
+ ...(hit?.score !== undefined ? { score: hit.score } : {}),
1024
+ ...(mode ? { mode } : {}),
1025
+ ...(hit ? { tokens_saved: hit.tokensSaved, tokens_saved_basis: hit.tokensSavedBasis } : {}),
1026
+ signals: hit?.signals ?? task.signals,
1027
+ ...(verdict.reason ? { reason: verdict.reason } : {}),
1028
+ extra: { task_id: task.id, verdict_status: verdict.status, outcome_status: status },
1029
+ });
1030
+ }
1031
+ }
1032
+ if (!reportEnabled || status === null)
1033
+ return;
431
1034
  try {
432
1035
  await cap.recordOutcome({
433
1036
  signals: task.signals,
@@ -440,19 +1043,39 @@ export function makeHubLink(cap, ingestor, reportEnabled = true) {
440
1043
  if (usedAssetIds.length > 0 && cap.recordReuseResult) {
441
1044
  await Promise.all(usedAssetIds.map(async (assetId) => {
442
1045
  try {
443
- await cap.recordReuseResult?.({
1046
+ const receipt = await cap.recordReuseResult?.({
444
1047
  assetId,
445
1048
  outcome: status === 'success' ? 'success' : 'failed',
446
1049
  taskId: task.id,
447
1050
  ...(verdict.reason ? { reason: verdict.reason } : {}),
448
1051
  });
1052
+ appendAssetCallBestEffort(assetLog, {
1053
+ run_id: runId,
1054
+ action: receipt?.recorded ? 'hub_review_submitted' : 'hub_review_rejected',
1055
+ asset_id: assetId,
1056
+ signals: task.signals,
1057
+ ...(safeAssetCallReason(receipt?.reason) ? { reason: safeAssetCallReason(receipt?.reason) } : {}),
1058
+ extra: { task_id: task.id, outcome_status: status, ...(receipt?.id ? { receipt_id: receipt.id } : {}) },
1059
+ });
1060
+ }
1061
+ catch {
1062
+ appendAssetCallBestEffort(assetLog, {
1063
+ run_id: runId,
1064
+ action: 'hub_review_failed',
1065
+ asset_id: assetId,
1066
+ signals: task.signals,
1067
+ reason: 'record_reuse_result_failed',
1068
+ extra: { task_id: task.id, outcome_status: status },
1069
+ });
449
1070
  }
450
- catch { /* reuse-result is best-effort observability; never fail the task */ }
451
1071
  }));
452
1072
  }
453
1073
  },
454
1074
  };
455
1075
  }
1076
+ function safeAssetCallReason(value) {
1077
+ return typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,100}$/.test(value) ? value : undefined;
1078
+ }
456
1079
  function resolvePublicHub(env = process.env, connectHub = connectPublicHub) {
457
1080
  if (hubMode(env) !== 'public')
458
1081
  return undefined;
@@ -476,30 +1099,45 @@ function hubMode(env) {
476
1099
  return mode === 'public' || mode === 'private' ? mode : undefined;
477
1100
  }
478
1101
  /**
479
- * Resolve the hub link (reuse seam + outcome reporter) from the environment, or undefined when reuse is
480
- * not enabled/credentialed. Default OFF: requires EVOLVER_REUSE_BEFORE_SOLVE === '1' and an OAuth token at
481
- * <evomapDir>/token.json. Any setup failure degrades to undefined (no link) so the daemon never blocks on
482
- * hub config — reuse is an optimization. Outcome reporting rides the same gate (it is the read-back half
483
- * of the same paid hub relationship); EVOLVER_OUTCOME_REPORT=0 turns just the reporting off.
1102
+ * Resolve public/private reuse wiring. Reuse remains default-off. When a public ATP miss handler is supplied,
1103
+ * a consent-gated free search-only seam may still be composed so auto-buy can prove a miss independently of
1104
+ * reuse injection; that seam never fetches or injects Hub assets.
484
1105
  */
485
- export function resolveHubLink(env = process.env, ingestor, connectHub = connectPublicHub) {
1106
+ export function resolveHubLink(env = process.env, ingestor, connectHub = connectPublicHub, onVerifiedSearchMiss, assetLog) {
486
1107
  const envFile = loadEnvFileFromEnv(env);
487
1108
  if (envFile.error) {
488
1109
  process.stderr.write(ENV_FILE_UNAVAILABLE_DIAGNOSTIC);
489
1110
  return undefined;
490
1111
  }
491
- if (env['EVOLVER_REUSE_BEFORE_SOLVE'] !== '1')
1112
+ const reuseEnabled = env['EVOLVER_REUSE_BEFORE_SOLVE'] === '1';
1113
+ if (!reuseEnabled && !onVerifiedSearchMiss)
492
1114
  return undefined;
1115
+ const resolvedAssetLog = assetLog ?? new hubNs.AssetCallLog(events.assetCallLogPath(env));
493
1116
  if (hubMode(env) === 'private') {
1117
+ if (!reuseEnabled)
1118
+ return undefined;
494
1119
  const proxy = proxyClientFromEnv(env);
495
- return proxy ? makeHubLink(makeProxyHubCapability(proxy), ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0') : undefined;
1120
+ return proxy ? makeHubLink(makeProxyHubCapability(proxy), ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0', undefined, resolvedAssetLog, env) : undefined;
496
1121
  }
497
1122
  const hub = resolvePublicHub(env, connectHub);
498
1123
  if (!hub)
499
1124
  return undefined;
1125
+ if (!reuseEnabled && onVerifiedSearchMiss) {
1126
+ return {
1127
+ seam: makeHubSearchMissProbe(hub, new ReuseCache(), onVerifiedSearchMiss, () => {
1128
+ try {
1129
+ return getAtpConsent(env).enabled;
1130
+ }
1131
+ catch {
1132
+ return false;
1133
+ }
1134
+ }, env, resolvedAssetLog),
1135
+ reportOutcome: async () => undefined,
1136
+ };
1137
+ }
500
1138
  // Pass the ingestor so a reuse hit emits a value.reuse_hit root_event (#112) — the live source the value
501
1139
  // ledger derives source=reuse entries from.
502
- return makeHubLink(hub, ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0');
1140
+ return makeHubLink(hub, ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0', onVerifiedSearchMiss, resolvedAssetLog, env);
503
1141
  }
504
1142
  export function resolveHubQuestionLink(env = process.env, connectHub = connectPublicHub) {
505
1143
  if (env['EVOLVER_OUTCOME_REPORT'] === '0')
@@ -841,6 +1479,9 @@ export async function runAutoExec(argv) {
841
1479
  const home = argv.find((a) => !a.startsWith('-')) ?? join(events.evomapHome(), 'autoexec');
842
1480
  const dirs = ensureAutoExecDirs(home);
843
1481
  const cfg = readAutoExecConfig(home);
1482
+ if (cfg.runner !== 'gemini') {
1483
+ process.stderr.write('evolver autoexec: execute queue is disabled for the configured built-in runner; non-execution daemon duties remain active. Set "runner":"gemini" only after reviewing its experimental capability boundary\n');
1484
+ }
844
1485
  // Solo mode (--solo): the "constrained wild" profile. Hard-cut network + ATP
845
1486
  // at the SOURCE — in-process, before any resolve* below reads its env gate — so
846
1487
  // both the startup wiring and any in-cycle path see them disabled. This is the
@@ -889,23 +1530,32 @@ export async function runAutoExec(argv) {
889
1530
  if (memoryEventMirror.observer)
890
1531
  bus.register(memoryEventMirror.observer);
891
1532
  const personalityStore = createAutoExecPersonalityStore();
892
- const engine = new algo.CycleEngine({ ingestor, selection: algo.makeGeneSelectionPoint(), store, now: () => Date.now(), personality: personalityStore });
1533
+ const engine = new algo.CycleEngine({
1534
+ ingestor,
1535
+ selection: algo.makeGeneSelectionPoint(),
1536
+ store,
1537
+ now: () => Date.now(),
1538
+ personality: personalityStore,
1539
+ capabilityGaps: makeCurriculumCapabilityGapsProvider(process.env),
1540
+ });
893
1541
  // Reuse-before-solve (#110) + outcome report-back: wire the adapter's reuseBeforeSolve as the hub-reuse
894
1542
  // seam when enabled + credentialed (default OFF → undefined → zero hub calls, exactly today's behavior).
895
1543
  // The seam injects hub candidates into the same selection pool as local genes, trust-first; the link's
896
1544
  // reporter closes the loop by sending the cycle outcome + used-asset claim back to the hub.
897
- const hubLink = resolveHubLink(process.env, ingestor);
1545
+ let atpAutoBuyer;
1546
+ const onVerifiedHubSearchMiss = (miss) => {
1547
+ // Resolve lazily: the first-run consent prompt happens after the daemon lock is acquired below, while Hub
1548
+ // composition happens here. A later verified miss therefore observes the newly recorded consent correctly.
1549
+ atpAutoBuyer ??= resolveAtpAutoBuyer(process.env);
1550
+ if (atpAutoBuyer)
1551
+ scheduleAtpAutoBuyForVerifiedMiss(miss, atpAutoBuyer);
1552
+ };
1553
+ const hubLink = resolveHubLink(process.env, ingestor, connectPublicHub, onVerifiedHubSearchMiss);
898
1554
  const hubQuestionLink = resolveHubQuestionLink(process.env);
899
1555
  const solidifyPermit = resolveSolidifyPermitGate(process.env);
900
1556
  const strategyName = process.env['EVOLVE_STRATEGY'];
901
- // Surface the cross-platform isolation gap ONCE: where unprivileged namespaces are unavailable (Windows/macOS),
902
- // the sandbox verifier still hardens (metachar/node-eval reject, env scrub, timeout) but CANNOT cut network or
903
- // hide home secrets — so a validation command there could phone home / read ~/.ssh. Don't let that be silent.
904
- let warnedNoIsolation = false;
905
1557
  const probationOn = geneProbationEnabled();
906
- // Learning trace (Learning Ops slice 2): per-task trace events + LearningPacket drafts to local files under
907
- // evolution/learning-trace/ (traceId = cycleId). Default ON; kill switch EVOLVER_LEARNING_TRACE=0. Hub upload
908
- // is a later slice — this wiring is file-only and best-effort, so it can never fail or slow a task.
1558
+ // File-only and best-effort: tracing must never fail or slow a task.
909
1559
  const learningTrace = resolveLearningTrace(process.env);
910
1560
  const deps = {
911
1561
  engine, store, provenance, review, personality: personalityStore, memoryGraph,
@@ -921,11 +1571,7 @@ export async function runAutoExec(argv) {
921
1571
  // different unit) so a long suite is not silently SIGKILL'd against the wrong budget.
922
1572
  validate: (task) => async (_m, _d, cwd) => {
923
1573
  const cmds = task.validationCmds ?? [];
924
- const r = await verify.runSandboxedValidation(cmds, cwd);
925
- if (cmds.length > 0 && !r.isolated && !warnedNoIsolation) {
926
- warnedNoIsolation = true;
927
- 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');
928
- }
1574
+ const r = await runRequiredSandboxedValidation(cmds, cwd);
929
1575
  const validationSummary = summarizeSandboxedValidation(r);
930
1576
  if (validationSummary)
931
1577
  process.stdout.write(` validation: ${validationSummary}\n`);
@@ -953,7 +1599,7 @@ export async function runAutoExec(argv) {
953
1599
  scheduleAutoExecHubSideEffects(task, v, { questions: hubQuestionLink, outcome: hubLink });
954
1600
  return v;
955
1601
  };
956
- const guarded = exec.singleFlight(() => autoExecPass(dirs, runOne));
1602
+ const guarded = exec.singleFlight(runnerBoundAutoExecPass(cfg.runner, dirs, runOne));
957
1603
  // Auto-distill producer+consumer (#106): register the distillObserver on THIS bus, then a producer tick scans
958
1604
  // the session dirs and records material on THIS Ingestor → material.batch_ready → observer drafts a quarantined
959
1605
  // gene (A1) → human `review --approve` lifts it into inject/cursor (A2a/A2b). Off via EVOLVER_AUTO_DISTILL=0.
@@ -964,7 +1610,9 @@ export async function runAutoExec(argv) {
964
1610
  const antiGeneDistill = resolveAutoDistillAntiGene(process.env, { store, review, ingestor });
965
1611
  const transcriptDistill = resolveAutoDistillTranscript(process.env, { store, review, ingestor });
966
1612
  const atpAutoDeliver = resolveAtpAutoDeliver(process.env);
967
- 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'} learning-trace=${learningTrace.enabled ? `on(upload=${learningTrace.upload})` : 'off'} memory-event-mirror=${memoryEventMirror.enabled ? 'on' : `off(${memoryEventMirror.reason ?? 'no_hub'})`} 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`);
1613
+ const uninstallBrokenPipeGuards = installAutoexecBrokenPipeGuards();
1614
+ const reuseEnabled = process.env['EVOLVER_REUSE_BEFORE_SOLVE'] === '1' && hubLink !== undefined;
1615
+ process.stdout.write(`evolver autoexec: runner=${cfg.runner} queue=${dirs.tasks} allowlist=${JSON.stringify(cfg.allowedRoots)} poll=${cfg.pollMs}ms reuse=${reuseEnabled ? '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'} learning-trace=${learningTrace.enabled ? `on(upload=${learningTrace.upload})` : 'off'} memory-event-mirror=${memoryEventMirror.enabled ? 'on' : `off(${memoryEventMirror.reason ?? 'no_hub'})`} 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`);
968
1616
  if (cfg.allowedRoots.length === 0)
969
1617
  process.stdout.write(' (allowlist empty → deny-by-default: nothing runs until you add a repo to config.json)\n');
970
1618
  // Single-instance lock (#106): a second daemon on the same home would double-process the queue. That is harmless
@@ -980,6 +1628,7 @@ export async function runAutoExec(argv) {
980
1628
  }
981
1629
  catch (error) {
982
1630
  process.stderr.write(autoexecLockFailureMessage(error));
1631
+ uninstallBrokenPipeGuards();
983
1632
  return 1;
984
1633
  }
985
1634
  // First-run auto-buyer opt-in (PORT v1 #10): introduce the autonomous spend path to interactive operators once,
@@ -996,6 +1645,15 @@ export async function runAutoExec(argv) {
996
1645
  const uninstallUnhandledRejectionGuard = daemonNs.installUnhandledRejectionWindow({
997
1646
  beforeExit: () => { releaseAutoexecLock(lockPath); },
998
1647
  });
1648
+ let runtimeCleaned = false;
1649
+ const cleanupAutoexecRuntime = () => {
1650
+ if (runtimeCleaned)
1651
+ return;
1652
+ runtimeCleaned = true;
1653
+ uninstallUnhandledRejectionGuard();
1654
+ releaseAutoexecLock(lockPath);
1655
+ uninstallBrokenPipeGuards();
1656
+ };
999
1657
  // Durable workflow recovery uses the same policy/review-gated runtime factory as `evolver workflow start/resume`.
1000
1658
  // Pass the already-loaded config so a custom autoexec home uses the same allowlist, runner, and validation profiles.
1001
1659
  initializeWorkflowStartupRecovery({ autoExecHome: home, autoExecConfig: cfg });
@@ -1081,7 +1739,7 @@ export async function runAutoExec(argv) {
1081
1739
  process.stderr.write(`[Solo] 连续失败 ${soloState.consecutiveFailures} 次达阈值,熔断停机(非盲重生)。\n`);
1082
1740
  // Stop scheduling, release the lock, and exit non-zero. Detached so we
1083
1741
  // don't await our own loop.stop() from inside a tick.
1084
- void loop.stop().then(() => { uninstallUnhandledRejectionGuard(); releaseAutoexecLock(lockPath); process.exit(1); });
1742
+ void loop.stop().then(() => { cleanupAutoexecRuntime(); process.exit(1); });
1085
1743
  }
1086
1744
  };
1087
1745
  // Heartbeat (#106): record liveness + pacing on the AE spine for the WebUI console, THROTTLED so a fast poll does
@@ -1107,18 +1765,7 @@ export async function runAutoExec(argv) {
1107
1765
  }).catch(() => { });
1108
1766
  },
1109
1767
  });
1110
- // Graceful stop (#106): on SIGINT/SIGTERM stop scheduling, await the in-flight beat (no orphaned work), release
1111
- // the single-instance lock, and exit 0. Idempotent — a second signal during shutdown is ignored.
1112
- return await new Promise((resolve) => {
1113
- let stopping = false;
1114
- const shutdown = (sig) => {
1115
- if (stopping)
1116
- return;
1117
- stopping = true;
1118
- process.stdout.write(`\nevolver autoexec: ${sig} → graceful stop (finishing in-flight, releasing lock)\n`);
1119
- void loop.stop().then(() => { uninstallUnhandledRejectionGuard(); releaseAutoexecLock(lockPath); resolve(0); });
1120
- };
1121
- process.once('SIGINT', () => shutdown('SIGINT'));
1122
- process.once('SIGTERM', () => shutdown('SIGTERM'));
1123
- });
1768
+ // SIGINT/SIGTERM drain the in-flight beat before cleanup. SIGHUP cannot hot-reload this composition safely,
1769
+ // so it is explicit and non-destructive: keep running until the operator performs a normal restart.
1770
+ return await waitForAutoexecShutdown({ stop: loop.stop, cleanup: cleanupAutoexecRuntime });
1124
1771
  }