@evomap/evolver-cli 2.0.41 → 2.0.44

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 (50) hide show
  1. package/dist/autoRecall.d.ts +24 -5
  2. package/dist/autoRecall.js +233 -12
  3. package/dist/autoexec.d.ts +69 -10
  4. package/dist/autoexec.js +847 -137
  5. package/dist/cli.d.ts +1 -1
  6. package/dist/cli.js +71 -26
  7. package/dist/cliContracts.js +29 -7
  8. package/dist/cliEntry.d.ts +3 -0
  9. package/dist/cliEntry.js +63 -0
  10. package/dist/commandCatalog.d.ts +1 -0
  11. package/dist/commandCatalog.js +1 -0
  12. package/dist/contextDelivery.d.ts +12 -0
  13. package/dist/contextDelivery.js +139 -0
  14. package/dist/cycleConsumer.js +9 -1
  15. package/dist/dispatch.js +6 -0
  16. package/dist/feedbackOutbox.d.ts +96 -0
  17. package/dist/feedbackOutbox.js +510 -0
  18. package/dist/feedbackOutboxCli.d.ts +7 -0
  19. package/dist/feedbackOutboxCli.js +208 -0
  20. package/dist/index.d.ts +3 -0
  21. package/dist/index.js +286 -69
  22. package/dist/lifecycle.d.ts +18 -0
  23. package/dist/lifecycle.js +130 -3
  24. package/dist/lifecycleBootstrapTransaction.js +1 -6
  25. package/dist/liveStatus.d.ts +27 -0
  26. package/dist/liveStatus.js +197 -0
  27. package/dist/outboxLock.d.ts +7 -0
  28. package/dist/outboxLock.js +141 -0
  29. package/dist/promptRecallHook.d.ts +7 -22
  30. package/dist/promptRecallHook.js +20 -489
  31. package/dist/promptRecallRuntime.d.ts +24 -0
  32. package/dist/promptRecallRuntime.js +678 -0
  33. package/dist/promptRecallShared.d.ts +18 -0
  34. package/dist/promptRecallShared.js +119 -0
  35. package/dist/recall.js +27 -6
  36. package/dist/runtimeTelemetry.d.ts +9 -0
  37. package/dist/runtimeTelemetry.js +16 -0
  38. package/dist/sessionIngest.d.ts +25 -2
  39. package/dist/sessionIngest.js +196 -32
  40. package/dist/setupHooks.js +63 -13
  41. package/dist/setupHooksLifecycle.js +39 -17
  42. package/dist/skill2gep.d.ts +11 -0
  43. package/dist/skill2gep.js +23 -3
  44. package/dist/solo/mode.js +4 -0
  45. package/dist/taskCommitments.d.ts +4 -2
  46. package/dist/taskCommitments.js +208 -114
  47. package/dist/taskOutcomeOutbox.d.ts +83 -0
  48. package/dist/taskOutcomeOutbox.js +553 -0
  49. package/dist/workflowRuntime.js +12 -0
  50. package/package.json +11 -7
package/dist/autoexec.js CHANGED
@@ -3,13 +3,15 @@
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 { randomUUID } from 'node:crypto';
7
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
8
- import { join, dirname } from 'node:path';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
+ import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
8
+ import { join, dirname, basename } from 'node:path';
9
+ import { isDeepStrictEqual } from 'node:util';
9
10
  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
11
  import { runRequiredSandboxedValidation } from './requiredSandboxValidation.js';
11
12
  import { startResidentLoop } from './daemonLoop.js';
12
- import { connectPublicHub, createSolidifyPermitCheck, getMinReuseScore, ReuseCache, reuseBeforeSolve, resolveConfiguredHubUrl, resolveHubUrl, searchHubMetadata, } from '@evomap/evolver-adapter-public';
13
+ import { autoexecHeartbeatTelemetry } from './runtimeTelemetry.js';
14
+ import { connectPublicHub, OAuthAuthenticationPreflightError, OAuthCredentialBindingError, readPublicOAuthCredentialBinding, createSolidifyPermitCheck, getMinReuseScore, isTerminalHubRejectionStatus, ReuseCache, reuseBeforeSolve, resolveConfiguredHubUrl, resolveHubUrl, searchHubMetadata, } from '@evomap/evolver-adapter-public';
13
15
  import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
14
16
  import { resolveValueDigestObserver } from './valueDigest.js';
15
17
  import { resolveReflectionObserver } from './reflectionObserver.js';
@@ -19,7 +21,7 @@ import { resolveDistillObserver } from './distillObserver.js';
19
21
  import { resolveAutoDistillLlm } from './autoDistillLlm.js';
20
22
  import { resolveAutoDistillAntiGene as resolveAntiGeneDistill } from './autoDistillAntiGene.js';
21
23
  import { runTranscriptDistillTick, transcriptDistillMode } from './autoDistillTranscript.js';
22
- import { runSessionIngestTick, scanSessionDirs } from './sessionIngest.js';
24
+ import { resolveContextObservationWriter, runSessionIngestTick, scanSessionDirs } from './sessionIngest.js';
23
25
  import { LocalMemoryGraph, resolveLocalMemoryUserIdentity } from './localMemoryGraph.js';
24
26
  import { resolveAtpAutoDeliver } from './atpAutoDeliver.js';
25
27
  import { memoryEventsFromCycleLog, resolveTaskReceiver } from './taskReceiver.js';
@@ -35,6 +37,8 @@ import { readAutoExecConfig } from './autoexecConfig.js';
35
37
  import { makeCurriculumCapabilityGapsProvider } from './curriculumCapabilityGaps.js';
36
38
  import { resolveLearningTrace } from './learningTrace.js';
37
39
  import { semanticIdfEnabled } from './semanticIdfConfig.js';
40
+ import { FeedbackNotDispatchedError, FeedbackOutbox } from './feedbackOutbox.js';
41
+ import { TaskOutcomeOutbox, taskOutcomeIdentity } from './taskOutcomeOutbox.js';
38
42
  import { selectionFloorFromEnv, selectionGuardFromEnv, selectionPolicyFromEnv, } from './selectionPolicyConfig.js';
39
43
  export { readAutoExecConfig } from './autoexecConfig.js';
40
44
  export { semanticIdfEnabled } from './semanticIdfConfig.js';
@@ -105,10 +109,22 @@ function createAutoExecPersonalityStore() {
105
109
  }
106
110
  const CLAIMED_TASK_SUFFIX = '.claimed.json';
107
111
  const STARTED_TASK_SUFFIX = '.started.json';
112
+ const FEEDBACK_PREPARATION_FAILURE = /^(?:EIO|ENOSPC|EROFS|EACCES|EPERM|ENOENT|EMFILE|ENFILE|EDQUOT|EEXIST|EBUSY|EINVAL|unknown)$/;
108
113
  const AMBIGUOUS_RECOVERY_REASON = 'autoexec_crash_recovery_ambiguous: execution may have started before shutdown; refusing automatic retry, explicitly requeue after inspecting prior side effects';
109
114
  function receiptDir(dirs) {
110
115
  return join(dirs.base, 'receipts');
111
116
  }
117
+ function syncQueueDirectory(path) {
118
+ if (process.platform === 'win32')
119
+ return;
120
+ const fd = openSync(path, 'r');
121
+ try {
122
+ fsyncSync(fd);
123
+ }
124
+ finally {
125
+ closeSync(fd);
126
+ }
127
+ }
112
128
  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;
113
129
  function receiptArtifactClaimName(name) {
114
130
  const tempMatch = RECEIPT_TEMP_SUFFIX.exec(name);
@@ -163,7 +179,22 @@ function cleanupOrphanReceiptArtifacts(dirs) {
163
179
  catch {
164
180
  return;
165
181
  }
166
- cleanupReceiptArtifacts(dirs, (claimName) => !activeClaims.has(claimName));
182
+ cleanupReceiptArtifacts(dirs, (claimName) => !activeClaims.has(claimName)
183
+ && !hasRecoverableClaimReceipt(dirs, claimName));
184
+ }
185
+ function hasRecoverableClaimReceipt(dirs, claimName) {
186
+ try {
187
+ const path = join(receiptDir(dirs), claimName);
188
+ if (!lstatSync(path).isFile())
189
+ return false;
190
+ const value = JSON.parse(readFileSync(path, 'utf8'));
191
+ return !!value && typeof value === 'object'
192
+ && ('archiveName' in value || 'executionDestinationId' in value || 'taskOutcomeEnabled' in value || 'postCommit' in value);
193
+ }
194
+ catch (error) {
195
+ // Unknown durable bytes are evidence, not disposable temp files.
196
+ return error.code !== 'ENOENT';
197
+ }
167
198
  }
168
199
  function parseAutoExecClaim(name) {
169
200
  const separator = name.indexOf('--');
@@ -226,13 +257,39 @@ function persistedClaimReceipt(dirs, claim, taskId) {
226
257
  if (!value || typeof value !== 'object')
227
258
  return null;
228
259
  const receipt = value;
260
+ const ownerTaskId = taskId ?? receipt.verdict?.taskId;
229
261
  if (receipt.claimName !== claim.name
230
262
  || (receipt.destination !== 'done' && receipt.destination !== 'refused')
231
- || !isAutoExecVerdict(receipt.verdict, taskId))
263
+ || typeof ownerTaskId !== 'string' || !ownerTaskId.trim()
264
+ || !isAutoExecVerdict(receipt.verdict, ownerTaskId))
232
265
  return null;
233
266
  const expectedDestination = receipt.verdict.status === 'refused' || receipt.verdict.status === 'unsafe_to_replay' ? 'refused' : 'done';
234
267
  if (receipt.destination !== expectedDestination)
235
268
  return null;
269
+ if (receipt.archiveName !== undefined
270
+ && (typeof receipt.archiveName !== 'string' || /[\\/]/.test(receipt.archiveName)
271
+ || (receipt.archiveName !== `task-${claim.originalName}` && receipt.archiveName !== `task-${claim.name}`))) {
272
+ throw new Error('claim receipt archive identity mismatch');
273
+ }
274
+ if (receipt.executionDestinationId !== undefined && receipt.executionDestinationId !== null
275
+ && (typeof receipt.executionDestinationId !== 'string'
276
+ || !/^sha256:[a-f0-9]{64}$/.test(receipt.executionDestinationId))) {
277
+ throw new Error('claim receipt execution destination invalid');
278
+ }
279
+ if (receipt.postCommit !== undefined && receipt.postCommit !== 'pending' && receipt.postCommit !== 'dispatching') {
280
+ throw new Error('claim receipt post-commit state invalid');
281
+ }
282
+ if (receipt.taskOutcomeEnabled !== undefined && typeof receipt.taskOutcomeEnabled !== 'boolean') {
283
+ throw new Error('claim receipt task-outcome eligibility invalid');
284
+ }
285
+ if (receipt.feedbackPreparationFailure !== undefined
286
+ && (typeof receipt.feedbackPreparationFailure !== 'string'
287
+ || !FEEDBACK_PREPARATION_FAILURE.test(receipt.feedbackPreparationFailure))) {
288
+ throw new Error('claim receipt feedback-preparation state invalid');
289
+ }
290
+ if (receipt.feedbackPreparationPending !== undefined && typeof receipt.feedbackPreparationPending !== 'boolean') {
291
+ throw new Error('claim receipt feedback-preparation marker invalid');
292
+ }
236
293
  return receipt;
237
294
  }
238
295
  catch (error) {
@@ -246,11 +303,19 @@ function persistClaimReceipt(dirs, receipt) {
246
303
  const receipts = receiptDir(dirs);
247
304
  const receiptPath = join(receipts, receipt.claimName);
248
305
  const tempPath = join(receipts, `${receipt.claimName}.${randomUUID()}.tmp`);
306
+ let fd;
249
307
  try {
250
- writeFileSync(tempPath, JSON.stringify(receipt, null, 2), { encoding: 'utf8', flag: 'wx' });
308
+ fd = openSync(tempPath, 'wx', 0o600);
309
+ writeFileSync(fd, JSON.stringify(receipt, null, 2), 'utf8');
310
+ fsyncSync(fd);
311
+ closeSync(fd);
312
+ fd = undefined;
251
313
  renameSync(tempPath, receiptPath);
314
+ syncQueueDirectory(receipts);
252
315
  }
253
316
  finally {
317
+ if (fd !== undefined)
318
+ closeSync(fd);
254
319
  try {
255
320
  if (lstatSync(tempPath).isFile())
256
321
  unlinkSync(tempPath);
@@ -260,23 +325,154 @@ function persistClaimReceipt(dirs, receipt) {
260
325
  }
261
326
  }
262
327
  }
263
- function recoverAmbiguousClaim(dirs, claim) {
328
+ function finishCommittedClaim(dirs, claim, task, receipt, options, archived, recovering) {
329
+ if (task.id !== receipt.verdict.taskId || task.generation !== receipt.verdict.generation) {
330
+ throw new Error('claim receipt task identity mismatch');
331
+ }
332
+ const dest = receipt.destination === 'refused' ? dirs.refused : dirs.done;
333
+ const archiveName = receipt.archiveName ?? basename(archiveTaskPath(dest, claim.originalName, claim.name));
334
+ const archivePath = join(dest, archiveName);
335
+ if (!archived && existsSync(archivePath))
336
+ throw new Error('claim archive destination occupied');
337
+ receipt.archiveName = archiveName;
338
+ const canonicalVerdict = join(dest, claim.originalName);
339
+ // Queue filenames own the flat archive namespace; snapshots have a disjoint directory.
340
+ const archivedVerdictDir = join(dest, 'verdicts');
341
+ const archivedVerdict = join(archivedVerdictDir, claim.name);
342
+ let verdictPath = canonicalVerdict;
343
+ if (recovering && existsSync(archivedVerdictDir)
344
+ && (!lstatSync(archivedVerdictDir).isDirectory() || lstatSync(archivedVerdictDir).isSymbolicLink())) {
345
+ throw new Error('unsafe archived verdict directory');
346
+ }
347
+ if (recovering && existsSync(archivedVerdict)) {
348
+ if (!lstatSync(archivedVerdict).isFile()
349
+ || !isDeepStrictEqual(JSON.parse(readFileSync(archivedVerdict, 'utf8')), receipt.verdict)) {
350
+ throw new Error('archived claim verdict identity mismatch');
351
+ }
352
+ }
353
+ if (recovering && existsSync(canonicalVerdict)) {
354
+ if (!lstatSync(canonicalVerdict).isFile())
355
+ throw new Error('archived verdict is not a regular file');
356
+ const existing = JSON.parse(readFileSync(canonicalVerdict, 'utf8'));
357
+ // Preparation is owned by the exact receipt and archived task above.
358
+ // The filename-level verdict may already belong to a newer filing; never overwrite it.
359
+ const currentTaskId = existing && typeof existing === 'object' ? existing.taskId : undefined;
360
+ if (typeof currentTaskId !== 'string' || !isAutoExecVerdict(existing, currentTaskId)) {
361
+ throw new Error('archived verdict identity mismatch');
362
+ }
363
+ if (!isDeepStrictEqual(existing, receipt.verdict))
364
+ verdictPath = archivedVerdict;
365
+ }
366
+ // An earlier rename may have succeeded while receipt-directory fsync failed.
367
+ // Recommit the saved identity before reconstructing debt, never today's identity.
368
+ if (options.prepareFeedback && receipt.feedbackPreparationPending !== false)
369
+ receipt.feedbackPreparationPending = true;
370
+ if (recovering)
371
+ persistClaimReceipt(dirs, receipt);
372
+ if (verdictPath === archivedVerdict) {
373
+ mkdirSync(archivedVerdictDir, { recursive: true, mode: 0o700 });
374
+ if (!lstatSync(archivedVerdictDir).isDirectory() || lstatSync(archivedVerdictDir).isSymbolicLink()) {
375
+ throw new Error('unsafe archived verdict directory');
376
+ }
377
+ }
378
+ if (recovering ? !existsSync(verdictPath) : !archived || !existsSync(canonicalVerdict)) {
379
+ // Recovery owns only its saved verdict; a newly appeared path must never be truncated.
380
+ const fd = openSync(verdictPath, recovering ? 'wx' : 'w', 0o600);
381
+ try {
382
+ writeFileSync(fd, JSON.stringify(receipt.verdict, null, 2));
383
+ fsyncSync(fd);
384
+ }
385
+ finally {
386
+ closeSync(fd);
387
+ }
388
+ }
389
+ else if (recovering) {
390
+ // Visible bytes may remain after a failed fsync. Recommit the exact opened file without truncation.
391
+ const fd = openSync(verdictPath, 'r+', 0o600);
392
+ try {
393
+ if (!isDeepStrictEqual(JSON.parse(readFileSync(fd, 'utf8')), receipt.verdict)) {
394
+ throw new Error('claim verdict identity changed');
395
+ }
396
+ fsyncSync(fd);
397
+ }
398
+ finally {
399
+ closeSync(fd);
400
+ }
401
+ }
402
+ if (verdictPath === archivedVerdict)
403
+ syncQueueDirectory(archivedVerdictDir);
404
+ if (!archived) {
405
+ renameSync(join(dirs.inflight, claim.name), archivePath);
406
+ }
407
+ syncQueueDirectory(dest);
408
+ syncQueueDirectory(dirs.inflight);
409
+ if ((receipt.feedbackPreparationPending || receipt.feedbackPreparationFailure !== undefined)
410
+ && !options.prepareFeedback)
411
+ return receipt.verdict;
412
+ try {
413
+ if (receipt.feedbackPreparationPending !== false) {
414
+ options.prepareFeedback?.(claim.name.slice(0, claim.name.indexOf('--')), task, receipt.verdict, receipt.executionDestinationId, receipt.taskOutcomeEnabled === true);
415
+ }
416
+ }
417
+ catch (error) {
418
+ const code = error instanceof Error ? error.code : undefined;
419
+ receipt.feedbackPreparationFailure = typeof code === 'string' && FEEDBACK_PREPARATION_FAILURE.test(code) ? code : 'unknown';
420
+ persistClaimReceipt(dirs, receipt);
421
+ return receipt.verdict;
422
+ }
423
+ if (receipt.feedbackPreparationPending) {
424
+ receipt.feedbackPreparationPending = false;
425
+ delete receipt.feedbackPreparationFailure;
426
+ persistClaimReceipt(dirs, receipt);
427
+ }
428
+ if (receipt.postCommit === 'dispatching')
429
+ return receipt.verdict;
430
+ if (receipt.postCommit === 'pending') {
431
+ if (!options.afterCommit)
432
+ return receipt.verdict;
433
+ receipt.postCommit = 'dispatching';
434
+ persistClaimReceipt(dirs, receipt);
435
+ try {
436
+ options.afterCommit(task, receipt.verdict);
437
+ }
438
+ catch {
439
+ return receipt.verdict; /* unknown optional dispatch remains inspectable and is never replayed */
440
+ }
441
+ }
442
+ cleanupCommittedClaimReceipt(dirs, claim.name);
443
+ return receipt.verdict;
444
+ }
445
+ function recoverArchivedClaim(dirs, claim, options) {
446
+ const receipt = persistedClaimReceipt(dirs, claim);
447
+ if (!receipt?.archiveName)
448
+ throw new Error('archived claim receipt unavailable');
449
+ const dest = receipt.destination === 'refused' ? dirs.refused : dirs.done;
450
+ const path = join(dest, receipt.archiveName);
451
+ if (!lstatSync(path).isFile())
452
+ throw new Error('archived claim task is not a regular file');
453
+ const task = exec.normalizeAutoExecTask(JSON.parse(readFileSync(path, 'utf8')));
454
+ const noNewVerdict = receipt.feedbackPreparationPending === false || receipt.feedbackPreparationFailure !== undefined
455
+ || (receipt.feedbackPreparationPending && !options.prepareFeedback) || receipt.postCommit === 'dispatching'
456
+ || (receipt.postCommit === 'pending' && !options.afterCommit);
457
+ const verdict = finishCommittedClaim(dirs, claim, task, receipt, options, true, true);
458
+ return noNewVerdict ? undefined : verdict;
459
+ }
460
+ function recoverAmbiguousClaim(dirs, claim, options) {
264
461
  const taskPath = join(dirs.inflight, claim.name);
265
462
  let taskId = `recovery-${claim.name.slice(0, 64)}`;
463
+ let task;
266
464
  try {
267
- taskId = exec.normalizeAutoExecTask(JSON.parse(readFileSync(taskPath, 'utf8'))).id;
465
+ task = exec.normalizeAutoExecTask(JSON.parse(readFileSync(taskPath, 'utf8')));
466
+ taskId = task.id;
268
467
  }
269
468
  catch {
270
469
  // The task may have been only partially published before the prior process stopped.
271
470
  }
272
471
  const receipt = persistedClaimReceipt(dirs, claim, taskId);
273
472
  if (receipt) {
274
- const dest = receipt.destination === 'refused' ? dirs.refused : dirs.done;
275
- const canonicalVerdict = join(dest, claim.originalName);
276
- writeFileSync(canonicalVerdict, JSON.stringify(receipt.verdict, null, 2));
277
- renameSync(taskPath, archiveTaskPath(dest, claim.originalName, claim.name));
278
- cleanupCommittedClaimReceipt(dirs, claim.name);
279
- return receipt.verdict;
473
+ if (!task)
474
+ throw new Error('feedback claim task unavailable during recovery');
475
+ return finishCommittedClaim(dirs, claim, task, receipt, options, false, true);
280
476
  }
281
477
  const verdict = {
282
478
  taskId,
@@ -300,12 +496,20 @@ export async function autoExecPass(dirs, runOne, options = {}) {
300
496
  .filter((entry) => entry.isFile() && entry.name.endsWith('.json'))
301
497
  .map((entry) => parseAutoExecClaim(entry.name))
302
498
  .filter((claim) => claim !== null);
303
- cleanupOrphanReceiptArtifacts(dirs);
304
499
  const pendingClaims = existingClaims.filter((claim) => claim.phase === 'claimed');
305
500
  const out = [];
306
- for (const claim of existingClaims.filter((item) => item.phase !== 'claimed')) {
501
+ const activeNames = new Set(existingClaims.map(claim => claim.name));
502
+ const archivedClaims = readdirSync(receiptDir(dirs), { withFileTypes: true })
503
+ .filter(entry => entry.isFile() && receiptArtifactClaimName(entry.name) === entry.name
504
+ && !activeNames.has(entry.name) && hasRecoverableClaimReceipt(dirs, entry.name))
505
+ .map(entry => parseAutoExecClaim(entry.name))
506
+ .filter((claim) => claim !== null);
507
+ for (const claim of [...archivedClaims, ...existingClaims.filter((item) => item.phase !== 'claimed')]) {
307
508
  try {
308
- out.push(recoverAmbiguousClaim(dirs, claim));
509
+ const recovered = activeNames.has(claim.name)
510
+ ? recoverAmbiguousClaim(dirs, claim, options) : recoverArchivedClaim(dirs, claim, options);
511
+ if (recovered)
512
+ out.push(recovered);
309
513
  }
310
514
  catch (error) {
311
515
  const errorCode = error.code;
@@ -349,14 +553,37 @@ export async function autoExecPass(dirs, runOne, options = {}) {
349
553
  const startedName = claim.name.slice(0, -CLAIMED_TASK_SUFFIX.length) + STARTED_TASK_SUFFIX;
350
554
  const startedPath = join(dirs.inflight, startedName);
351
555
  renameSync(taskPath, startedPath);
352
- const v = await runOne(task).catch((e) => ({ taskId: task.id, status: 'failed', reason: e instanceof Error ? e.message : String(e) }));
556
+ const returned = await runOne(task).catch((e) => ({ taskId: task.id, status: 'failed',
557
+ ...(task.generation !== undefined ? { generation: task.generation } : {}),
558
+ reason: e instanceof Error ? e.message : String(e) }));
559
+ // The queue owns the invoked filing. Older/early kernel verdicts may omit
560
+ // this optional field; an explicitly different filing must still fail closed.
561
+ const v = returned.generation === undefined && task.generation !== undefined
562
+ ? { ...returned, generation: task.generation } : returned;
353
563
  const destination = v.status === 'refused' || v.status === 'unsafe_to_replay' ? 'refused' : 'done';
354
564
  const dest = destination === 'refused' ? dirs.refused : dirs.done;
355
- persistClaimReceipt(dirs, { claimName: startedName, destination, verdict: v });
356
- writeFileSync(join(dest, claim.originalName), JSON.stringify(v, null, 2));
357
- renameSync(startedPath, archiveTaskPath(dest, claim.originalName, startedName));
358
- cleanupCommittedClaimReceipt(dirs, startedName);
359
- out.push(v);
565
+ let executionDestinationId;
566
+ try {
567
+ executionDestinationId = options.captureFeedbackDestination?.(task);
568
+ if (executionDestinationId !== undefined && executionDestinationId !== null
569
+ && !/^sha256:[a-f0-9]{64}$/.test(executionDestinationId))
570
+ throw new Error('execution feedback destination invalid');
571
+ }
572
+ catch {
573
+ // Optional destination evidence may fail, but the completed verdict must still converge.
574
+ // Null keeps recovered feedback unbound instead of adopting a later Hub identity.
575
+ executionDestinationId = null;
576
+ }
577
+ const receipt = {
578
+ claimName: startedName, destination, verdict: v,
579
+ archiveName: basename(archiveTaskPath(dest, claim.originalName, startedName)),
580
+ ...(executionDestinationId !== undefined ? { executionDestinationId } : {}),
581
+ taskOutcomeEnabled: options.taskOutcomeEnabled === true,
582
+ ...(options.prepareFeedback ? { feedbackPreparationPending: true } : {}),
583
+ ...(options.afterCommit ? { postCommit: 'pending' } : {}),
584
+ };
585
+ persistClaimReceipt(dirs, receipt);
586
+ out.push(finishCommittedClaim(dirs, { ...claim, name: startedName, phase: 'started' }, task, receipt, options, false, false));
360
587
  }
361
588
  cleanupOrphanReceiptArtifacts(dirs);
362
589
  return out;
@@ -378,8 +605,8 @@ export function canExecuteQueue(runner) {
378
605
  return runner === 'gemini' || runner === 'llm';
379
606
  }
380
607
  /** Keep unsupported built-in runners away from the execution queue without stopping the resident daemon. */
381
- export function runnerBoundAutoExecPass(runner, dirs, runOne) {
382
- return () => autoExecPass(dirs, runOne, { executePendingTasks: canExecuteQueue(runner) });
608
+ export function runnerBoundAutoExecPass(runner, dirs, runOne, options = {}) {
609
+ return () => autoExecPass(dirs, runOne, { executePendingTasks: canExecuteQueue(runner), ...options });
383
610
  }
384
611
  const ATP_CAPABILITY_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,47}$/;
385
612
  function atpCapabilityGaps(signals) {
@@ -428,35 +655,24 @@ export function resolveAtpAutoBuyer(env = process.env, createClient = createAtpC
428
655
  return undefined;
429
656
  }
430
657
  }
431
- export function makeHubReuseSeam(cap, cache, ingestor, onAssetReused, onVerifiedSearchMiss, audit = {}) {
658
+ export function makeHubReuseSeam(cap, cache, _ingestor, onAssetReused, onVerifiedSearchMiss, audit = {}) {
432
659
  return async (signals, ctx) => {
433
660
  const searchSignals = normalizedCapabilityGapSignals(signals);
434
- // Pending value.reuse_hit ingests (#112). The onReuseHit callback is synchronous, so it cannot await the
435
- // ingest itself; it stashes the (error-swallowing) promise here and the seam awaits them before returning,
436
- // making the emission deterministically durable without letting an ingest error ever break reuse.
437
- const pending = [];
438
661
  const r = await reuseBeforeSolve(cap, cache, searchSignals, {
439
662
  ...(ctx?.cycleId ? { cycleId: ctx.cycleId } : {}),
440
663
  ...(audit.env ? { env: audit.env } : {}),
441
- // Two consumers hang off a reuse HIT:
442
- // - value-ledger emission (#112): a `value.reuse_hit` root_event so the ledger derives a real
443
- // source=reuse entry (refs → assetId + cycleId) — live wiring, not a fixture;
444
- // - used-asset tracking: the assetId feeds the fetch->outcome attribution claim the outcome
445
- // report sends back to the hub (used_asset_ids). Fires on cache hits too — a cached payload
446
- // is still a USE of that asset.
664
+ // A fetched candidate is only an acquisition, not an application or a successful reuse.
665
+ // The caller may use this for neutral search telemetry. Terminal feedback is emitted only
666
+ // after the selected asset actually executes and the task has a committed outcome.
447
667
  onReuseHit: (hit) => {
448
668
  try {
449
669
  onAssetReused?.(hit.assetId);
450
670
  }
451
671
  catch { /* tracking must never break reuse */ }
452
- if (ingestor)
453
- pending.push(emitReuseHit(ingestor, hit));
454
672
  },
455
673
  });
456
- if (pending.length > 0)
457
- await Promise.all(pending); // emitReuseHit never rejects (it swallows ingest errors)
458
674
  const runId = ctx?.cycleId ?? null;
459
- const taskId = runId?.startsWith('autoexec-') ? runId.slice('autoexec-'.length) : undefined;
675
+ const taskId = ctx?.taskId ?? (runId?.startsWith('autoexec-') ? runId.slice('autoexec-'.length) : undefined);
460
676
  if (r.action === 'fetch') {
461
677
  const rawAsset = r.asset;
462
678
  const assetId = r.candidate?.assetId ?? stringField(rawAsset, 'asset_id');
@@ -598,19 +814,99 @@ function scheduleAssetCallBestEffort(log, entry) {
598
814
  return;
599
815
  setImmediate(() => { appendAssetCallBestEffort(log, entry); });
600
816
  }
601
- /** Append a `value.reuse_hit` root_event for a reuse hit (#112). Never throws (reuse stays an optimization). */
602
- async function emitReuseHit(ingestor, hit) {
603
- try {
604
- const payload = {
605
- assetId: hit.assetId, cycleId: hit.cycleId, signalFingerprint: hit.signalFingerprint, fetchTokens: hit.fetchTokens,
606
- };
607
- await ingestor.ingest({
817
+ /** Project only a committed, exact selected/executed use, never a fetched candidate. */
818
+ export function committedFeedbackEvent(row) {
819
+ const use = row.appliedUse;
820
+ const payload = {
821
+ assetId: use.assetId, geneId: use.geneId, cycleId: use.cycleId,
822
+ source: use.source, sourceEventId: row.sourceEventId,
823
+ applicationBinding: use.applicationBinding, verification: use.verification,
824
+ producedValue: use.producedValue,
825
+ ...(use.capsuleId ? { capsuleId: use.capsuleId } : {}),
826
+ ...(use.eventId ? { eventId: use.eventId } : {}),
827
+ ...(use.terminalDisposition ? { terminalDisposition: use.terminalDisposition } : {}),
828
+ };
829
+ if (use.outcome === 'success') {
830
+ payload['fetchTokens'] = 0;
831
+ payload['signalFingerprint'] = `sha256:${createHash('sha256').update(JSON.stringify(row.signals)).digest('hex')}`;
832
+ return {
608
833
  type: ops.VALUE_REUSE_HIT_EVENT,
609
- human: { title: `reuse hit: ${hit.assetId}`, detail: `cycle ${hit.cycleId}` },
610
- payload: payload,
611
- });
834
+ human: { title: 'applied reuse success', detail: `cycle ${use.cycleId}` },
835
+ payload,
836
+ };
612
837
  }
613
- catch { /* emission must never break the reuse path */ }
838
+ payload['outcome'] = use.outcome;
839
+ return {
840
+ type: ops.VALUE_REUSE_OUTCOME_EVENT,
841
+ human: { title: `applied reuse ${use.outcome}`, detail: `cycle ${use.cycleId}` },
842
+ payload,
843
+ };
844
+ }
845
+ /** Local projection is owed before network delivery; ambiguous sends are never replayed automatically. */
846
+ export async function flushAutoExecFeedback(outbox, ingestor, sender, destinationId) {
847
+ let projected = 0;
848
+ let delivered = 0;
849
+ let ambiguous = 0;
850
+ const localPending = outbox.localPending();
851
+ if (localPending.length > 0) {
852
+ // A crash may occur after Ingestor durably appends the event but before the
853
+ // outbox acknowledgement. Recover by its stable source id, not by emitting a
854
+ // second RootEvent and hoping every future consumer deduplicates it.
855
+ const existing = new Map();
856
+ for (const event of ingestor.readAll()) {
857
+ const payload = event.payload;
858
+ const sourceId = payload['sourceEventId'];
859
+ if (typeof sourceId === 'string' && sourceId.startsWith('autoexec-applied-use:')) {
860
+ const previous = existing.get(sourceId);
861
+ if (previous && (previous.type !== event.type
862
+ || !isDeepStrictEqual(previous.payload, payload))) {
863
+ throw new Error('conflicting applied-use source event');
864
+ }
865
+ existing.set(sourceId, { type: event.type, payload });
866
+ }
867
+ }
868
+ for (const row of localPending) {
869
+ const expected = committedFeedbackEvent(row);
870
+ const prior = existing.get(row.sourceEventId);
871
+ if (prior) {
872
+ const payload = expected.payload;
873
+ if (prior.type !== expected.type || !isDeepStrictEqual(prior.payload, payload)) {
874
+ throw new Error('conflicting applied-use projection');
875
+ }
876
+ }
877
+ else {
878
+ await ingestor.ingest(expected);
879
+ existing.set(row.sourceEventId, { type: expected.type, payload: expected.payload });
880
+ projected++;
881
+ }
882
+ outbox.acknowledgeLocal(row.operationId);
883
+ }
884
+ }
885
+ if (sender && destinationId) {
886
+ for (const row of outbox.pending()) {
887
+ // A changed Hub endpoint or principal must never inherit another Hub's debt.
888
+ if (row.destinationId !== destinationId)
889
+ continue;
890
+ const result = await outbox.deliver(row.operationId, destinationId, sender);
891
+ if (result.networkStatus === 'acknowledged')
892
+ delivered++;
893
+ if (result.networkStatus === 'ambiguous')
894
+ ambiguous++;
895
+ }
896
+ }
897
+ return { projected, delivered, ambiguous };
898
+ }
899
+ /** A slow durable outbox drain must neither block Hub-task completion nor overlap the next beat. */
900
+ export function makeDeferredAutoExecFeedbackDrain(drain, onFailure) {
901
+ const single = exec.singleFlight(drain);
902
+ return () => {
903
+ try {
904
+ void single().catch(onFailure);
905
+ }
906
+ catch {
907
+ onFailure();
908
+ }
909
+ };
614
910
  }
615
911
  /** Build the same event for byte-budget admission and durable emission. */
616
912
  export function injectEvent(info) {
@@ -656,6 +952,54 @@ export function makeInjectEmitter(ingestor) {
656
952
  await Promise.all(pending); }, // emitInject never rejects
657
953
  };
658
954
  }
955
+ /** Both public HTTP and private proxy must explicitly acknowledge the exact asset use. */
956
+ function exactBoundFeedbackReport(row) {
957
+ const use = row.appliedUse;
958
+ const report = row.report;
959
+ return !!report && use.schemaVersion === 'applied-use.v1'
960
+ && use.applicationBinding === 'selected_execution'
961
+ && use.verification === 'unverified'
962
+ && (use.outcome === 'success' || use.outcome === 'failed')
963
+ && (use.outcome !== 'success' || use.producedValue === true)
964
+ && use.source === 'hub'
965
+ && /^sha256:[a-f0-9]{64}$/.test(row.destinationId ?? '')
966
+ && use.hubOriginDestinationId === row.destinationId
967
+ && report.assetId === use.assetId
968
+ && report.outcome === use.outcome
969
+ && report.taskId === row.taskId
970
+ && report.traceId === use.cycleId;
971
+ }
972
+ export function makeAppliedUseFeedbackSender(cap, expectedDestinationId, reportEnabled = true) {
973
+ if (!/^sha256:[a-f0-9]{64}$/.test(expectedDestinationId)) {
974
+ throw new Error('bound Hub feedback destination required');
975
+ }
976
+ return async (row) => {
977
+ if (!row.report)
978
+ return { status: 'terminal', reason: 'no_reportable_applied_use' };
979
+ // The public sender can also be called directly by an embedder. Never let a
980
+ // forged or stale row escape merely because it carries a report object.
981
+ if (!exactBoundFeedbackReport(row)) {
982
+ return { status: 'terminal', reason: 'hub_origin_destination_mismatch' };
983
+ }
984
+ if (row.destinationId !== expectedDestinationId) {
985
+ throw new FeedbackNotDispatchedError('hub_feedback_destination_changed');
986
+ }
987
+ if (!reportEnabled)
988
+ throw new FeedbackNotDispatchedError('outcome_reporting_disabled');
989
+ if (!cap.recordReuseResult)
990
+ return { status: 'terminal', reason: 'reuse_result_not_supported' };
991
+ try {
992
+ return reuseReceiptSendResult(await cap.recordReuseResult(row.report));
993
+ }
994
+ catch (error) {
995
+ if (error instanceof OAuthCredentialBindingError || error instanceof OAuthAuthenticationPreflightError) {
996
+ throw new FeedbackNotDispatchedError(error instanceof OAuthCredentialBindingError
997
+ ? 'oauth_credential_binding_changed' : 'oauth_authentication_preflight_failed');
998
+ }
999
+ return { status: 'ambiguous', reason: 'reuse_result_transport_unknown' };
1000
+ }
1001
+ };
1002
+ }
659
1003
  const DEFAULT_QUESTION_SUBMIT_TIMEOUT_MS = 3_000;
660
1004
  const QUESTION_SUBMIT_TIMEOUT_ENV = 'EVOLVER_QUESTION_SUBMIT_TIMEOUT_MS';
661
1005
  const SOLIDIFY_VERIFY_ENV = 'EVOLVER_SOLIDIFY_VERIFY';
@@ -1022,19 +1366,19 @@ export async function submitDistillTickExplorationQuestion(questions, source) {
1022
1366
  });
1023
1367
  }
1024
1368
  export function scheduleAutoExecHubSideEffects(task, verdict, links) {
1025
- if (links.questions && verdictToOutcomeStatus(verdict.status) !== null && shouldSubmitProactiveQuestionsForTask(task)) {
1369
+ if (links.questions && verdict.producedValue === true
1370
+ && verdictToOutcomeStatus(verdict.status) !== null && shouldSubmitProactiveQuestionsForTask(task)) {
1026
1371
  void links.questions.submitForTask(task).catch(() => undefined);
1027
1372
  }
1028
1373
  if (links.outcome)
1029
1374
  void links.outcome.reportOutcome(task, verdict).catch(() => undefined);
1030
1375
  }
1031
1376
  /**
1032
- * Compose the reuse seam and the outcome reporter. Reuse HITs still emit value-ledger observability, but the
1033
- * Hub outcome `used_asset_ids` claim comes only from the finished verdict's selected/executed asset. A fetched
1034
- * candidate can be withheld by trust/review gates or lose selection, so fetch-time attribution would overclaim.
1035
- * Reporting never throws and never blocks the verdict.
1377
+ * Compose the reuse seam and the outcome reporters. A fetched candidate is neutral.
1378
+ * Exact applied-use delivery is owned by sendAppliedUse and the durable outbox;
1379
+ * the legacy task-wide outcome path cannot send a duplicate reuse-result claim.
1036
1380
  */
1037
- export function makeHubLink(cap, ingestor, reportEnabled = true, onVerifiedSearchMiss, assetLog, env) {
1381
+ export function makeHubLink(cap, ingestor, reportEnabled = true, onVerifiedSearchMiss, assetLog, env, appliedUseSender, reportingCap = cap, reportingDestinationId) {
1038
1382
  const maxPendingAuditRuns = 256;
1039
1383
  const searchHitsByRun = new Map();
1040
1384
  const seam = makeHubReuseSeam(cap, new ReuseCache(), ingestor, undefined, onVerifiedSearchMiss, {
@@ -1050,25 +1394,105 @@ export function makeHubLink(cap, ingestor, reportEnabled = true, onVerifiedSearc
1050
1394
  }
1051
1395
  // One reuse-before-solve invocation can fetch at most one winner. Replace any stale state left by an
1052
1396
  // unexpectedly aborted earlier run that reused the same task id.
1053
- searchHitsByRun.set(hit.runId, new Map([[hit.assetId, hit]]));
1397
+ searchHitsByRun.set(hit.runId, new Map([[hit.assetId, {
1398
+ ...hit, signals: [...hit.signals], audited: false,
1399
+ }]]));
1054
1400
  },
1055
1401
  });
1402
+ const sendExactUse = appliedUseSender ?? (reportingDestinationId
1403
+ ? makeAppliedUseFeedbackSender(reportingCap, reportingDestinationId, reportEnabled) : undefined);
1056
1404
  return {
1057
1405
  seam,
1406
+ ...(reportingDestinationId ? { feedbackDestinationId: reportingDestinationId } : {}),
1407
+ ...(reportEnabled ? { sendTaskOutcome: async (report) => {
1408
+ let receipt;
1409
+ try {
1410
+ receipt = await reportingCap.recordOutcome(report);
1411
+ }
1412
+ catch (error) {
1413
+ if (error instanceof OAuthCredentialBindingError || error instanceof OAuthAuthenticationPreflightError) {
1414
+ throw new FeedbackNotDispatchedError(error instanceof OAuthCredentialBindingError
1415
+ ? 'oauth_credential_binding_changed' : 'oauth_authentication_preflight_failed');
1416
+ }
1417
+ throw error;
1418
+ }
1419
+ // The public adapter intentionally converts HTTP/transport failures into
1420
+ // recorded:false. Those may have reached the paid endpoint; only a known
1421
+ // local preflight refusal is terminal. Throw to leave other sends ambiguous.
1422
+ if (receipt.recorded === false
1423
+ && receipt.reason !== 'no_signals'
1424
+ && receipt.reason !== 'reference_not_execution_evidence'
1425
+ && receipt.reason !== 'proxy_outcome_not_configured') {
1426
+ throw new Error('outcome_receipt_unconfirmed');
1427
+ }
1428
+ return receipt;
1429
+ } } : {}),
1430
+ ...(reportEnabled && sendExactUse ? { sendAppliedUse: async (row) => {
1431
+ if (row.report && !exactBoundFeedbackReport(row)) {
1432
+ return { status: 'terminal', reason: 'hub_origin_destination_mismatch' };
1433
+ }
1434
+ if (reportingDestinationId && row.destinationId !== reportingDestinationId) {
1435
+ throw new FeedbackNotDispatchedError('hub_feedback_destination_changed');
1436
+ }
1437
+ // The row exists only after a durable queue verdict; a search hit alone is not use.
1438
+ const hit = searchHitsByRun.get(row.appliedUse.cycleId)?.get(row.appliedUse.assetId);
1439
+ if (row.report && hit && !hit.audited) {
1440
+ hit.audited = true;
1441
+ appendAssetCallBestEffort(assetLog, {
1442
+ run_id: row.appliedUse.cycleId,
1443
+ action: hit.mode === 'reference' ? 'asset_reference' : 'asset_reuse',
1444
+ asset_id: row.appliedUse.assetId,
1445
+ ...(hit.assetType ? { asset_type: hit.assetType } : {}),
1446
+ ...(hit.sourceNodeId ? { source_node_id: hit.sourceNodeId } : {}),
1447
+ ...(hit.chainId ? { chain_id: hit.chainId } : {}),
1448
+ ...(hit.score !== undefined ? { score: hit.score } : {}),
1449
+ mode: hit.mode,
1450
+ tokens_saved: hit.tokensSaved, tokens_saved_basis: hit.tokensSavedBasis,
1451
+ signals: hit.signals,
1452
+ extra: { task_id: row.taskId, outcome_status: row.report.outcome },
1453
+ });
1454
+ }
1455
+ return sendExactUse(row);
1456
+ } } : {}),
1058
1457
  reportOutcome: async (task, verdict) => {
1059
- const status = verdictToOutcomeStatus(verdict.status);
1060
- const runId = `autoexec-${task.id}`;
1458
+ const disposition = verdict.execution_terminal?.disposition;
1459
+ const status = verdict.agentInvoked !== true
1460
+ || (verdict.status === 'failed' && verdict.outcome?.status !== 'failed')
1461
+ || verdict.failureKind === 'cancelled' || verdict.failureKind === 'timeout'
1462
+ || verdict.failureKind === 'spawn_failed' || verdict.failureKind === 'permission_denied'
1463
+ || disposition === 'cancelled' || disposition === 'timed_out' || disposition === 'denied'
1464
+ || disposition === 'unsafe_to_replay' || disposition === 'crashed'
1465
+ || (verdict.status === 'solidified' && verdict.producedValue !== true)
1466
+ || (verdict.status === 'solidified' && verdict.appliedUse?.outcome === 'failed')
1467
+ || (verdict.status === 'failed' && verdict.appliedUse?.outcome === 'success')
1468
+ || verdict.appliedUse?.outcome === 'inert'
1469
+ || verdict.appliedUse?.outcome === 'inconclusive'
1470
+ ? null : verdictToOutcomeStatus(verdict.status);
1471
+ const applied = verdict.appliedUse;
1472
+ const runId = applied?.cycleId ?? `autoexec-${task.id}`;
1061
1473
  const searchHits = searchHitsByRun.get(runId);
1062
- searchHitsByRun.delete(runId);
1063
- const usedAssetIds = Array.isArray(verdict.usedAssetIds)
1064
- ? [...new Set(verdict.usedAssetIds.filter((id) => typeof id === 'string' && id.length > 0))]
1065
- : [];
1066
- // Drain attribution synchronously (before a duplicate task id can start), then yield before the production
1067
- // sink's synchronous append and all Hub I/O. The detached side effect cannot delay routing to done/.
1474
+ const usedAssetIds = status !== null && applied?.source === 'hub'
1475
+ && !!reportingDestinationId
1476
+ && applied.hubOriginDestinationId === reportingDestinationId
1477
+ && applied.applicationBinding === 'selected_execution'
1478
+ && applied.verification === 'unverified'
1479
+ && (applied.outcome === 'success' || applied.outcome === 'failed')
1480
+ ? [applied.assetId] : [];
1481
+ // Both reporting paths share one audit claim. Capture and claim its owned
1482
+ // metadata before yielding; the bounded cache retains it for the other path.
1483
+ const audits = usedAssetIds.flatMap(assetId => {
1484
+ const hit = searchHits?.get(assetId);
1485
+ if (hit?.audited)
1486
+ return [];
1487
+ if (hit)
1488
+ hit.audited = true;
1489
+ return [{ assetId, hit }];
1490
+ });
1491
+ // Yield before the production sink's synchronous append and all Hub I/O.
1492
+ // The detached side effect cannot delay routing to done/.
1068
1493
  await new Promise((resolve) => { setImmediate(resolve); });
1069
1494
  if (status !== null) {
1070
- for (const assetId of usedAssetIds) {
1071
- const hit = searchHits?.get(assetId);
1495
+ for (const { assetId, hit } of audits) {
1072
1496
  const mode = hit?.mode;
1073
1497
  appendAssetCallBestEffort(assetLog, {
1074
1498
  run_id: runId,
@@ -1089,7 +1513,7 @@ export function makeHubLink(cap, ingestor, reportEnabled = true, onVerifiedSearc
1089
1513
  if (!reportEnabled || status === null)
1090
1514
  return;
1091
1515
  try {
1092
- await cap.recordOutcome({
1516
+ await reportingCap.recordOutcome({
1093
1517
  signals: task.signals,
1094
1518
  status,
1095
1519
  ...(verdict.outcome?.score !== undefined ? { score: verdict.outcome.score } : {}),
@@ -1097,43 +1521,13 @@ export function makeHubLink(cap, ingestor, reportEnabled = true, onVerifiedSearc
1097
1521
  });
1098
1522
  }
1099
1523
  catch { /* recordOutcome never throws by contract; belt-and-braces — reporting must never break the pass */ }
1100
- if (usedAssetIds.length > 0 && cap.recordReuseResult) {
1101
- await Promise.all(usedAssetIds.map(async (assetId) => {
1102
- try {
1103
- const receipt = await cap.recordReuseResult?.({
1104
- assetId,
1105
- outcome: status === 'success' ? 'success' : 'failed',
1106
- taskId: task.id,
1107
- ...(verdict.reason ? { reason: verdict.reason } : {}),
1108
- });
1109
- appendAssetCallBestEffort(assetLog, {
1110
- run_id: runId,
1111
- action: receipt?.recorded ? 'hub_review_submitted' : 'hub_review_rejected',
1112
- asset_id: assetId,
1113
- signals: task.signals,
1114
- ...(safeAssetCallReason(receipt?.reason) ? { reason: safeAssetCallReason(receipt?.reason) } : {}),
1115
- extra: { task_id: task.id, outcome_status: status, ...(receipt?.id ? { receipt_id: receipt.id } : {}) },
1116
- });
1117
- }
1118
- catch {
1119
- appendAssetCallBestEffort(assetLog, {
1120
- run_id: runId,
1121
- action: 'hub_review_failed',
1122
- asset_id: assetId,
1123
- signals: task.signals,
1124
- reason: 'record_reuse_result_failed',
1125
- extra: { task_id: task.id, outcome_status: status },
1126
- });
1127
- }
1128
- }));
1129
- }
1130
1524
  },
1131
1525
  };
1132
1526
  }
1133
1527
  function safeAssetCallReason(value) {
1134
1528
  return typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,100}$/.test(value) ? value : undefined;
1135
1529
  }
1136
- function resolvePublicHub(env = process.env, connectHub = connectPublicHub) {
1530
+ function resolvePublicHub(env = process.env, connectHub = connectPublicHub, expectedOAuthTokenBinding) {
1137
1531
  if (hubMode(env) !== 'public')
1138
1532
  return undefined;
1139
1533
  const dir = resolveIdentityHome(env);
@@ -1144,7 +1538,10 @@ function resolvePublicHub(env = process.env, connectHub = connectPublicHub) {
1144
1538
  const resolvedSenderId = resolveAtpSenderId(env);
1145
1539
  if (!resolvedSenderId)
1146
1540
  return undefined;
1147
- const { hub } = connectHub({ hubUrl, authMode: 'oauth', evomapDir: dir, senderId: () => resolvedSenderId });
1541
+ const { hub } = connectHub({
1542
+ hubUrl, authMode: 'oauth', evomapDir: dir, senderId: () => resolvedSenderId,
1543
+ ...(expectedOAuthTokenBinding ? { expectedOAuthTokenBinding } : {}),
1544
+ });
1148
1545
  return hub;
1149
1546
  }
1150
1547
  catch {
@@ -1155,6 +1552,112 @@ function hubMode(env) {
1155
1552
  const mode = String(env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase();
1156
1553
  return mode === 'public' || mode === 'private' ? mode : undefined;
1157
1554
  }
1555
+ /** Opaque nonsecret binding to the effective Hub principal and route, never a credential. */
1556
+ export function feedbackDestinationIdentity(mode, endpoint, principal, namespace = '') {
1557
+ if (!endpoint || !principal || [...endpoint, ...principal, ...namespace]
1558
+ .some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127)) {
1559
+ throw new Error('feedback destination identity unavailable');
1560
+ }
1561
+ return `sha256:${createHash('sha256').update(JSON.stringify([mode, endpoint, principal, namespace])).digest('hex')}`;
1562
+ }
1563
+ function publicFeedbackDestinationId(env) {
1564
+ try {
1565
+ const sender = resolveAtpSenderId(env);
1566
+ if (!sender)
1567
+ return undefined;
1568
+ const binding = readPublicOAuthCredentialBinding(join(resolveIdentityHome(env), 'token.json'));
1569
+ return binding ? feedbackDestinationIdentity('public', resolveHubUrl(env), sender, binding) : undefined;
1570
+ }
1571
+ catch {
1572
+ // A missing, malformed, or unsafe credential path cannot establish a reporting principal.
1573
+ return undefined;
1574
+ }
1575
+ }
1576
+ /** The proxy attests the final identity it also checks on the feedback POST. */
1577
+ export function privateFeedbackDestinationIdFromStatus(value) {
1578
+ const status = record(value);
1579
+ const nodeId = status['node_id'];
1580
+ const namespace = status['runtime_namespace'];
1581
+ const destination = status['feedback_destination_id'];
1582
+ // Older proxies expose a raw adapter fingerprint under the same field name.
1583
+ // Only the versioned final identity can be used for a durable outbox claim.
1584
+ if (status['hub_mode'] !== 'private' || status['feedback_destination_id_format'] !== 'proxy-bound.v1'
1585
+ || typeof nodeId !== 'string' || !nodeId.trim()
1586
+ || typeof namespace !== 'string' || !namespace.trim()
1587
+ || typeof destination !== 'string' || !/^sha256:[a-f0-9]{64}$/.test(destination))
1588
+ return undefined;
1589
+ return destination;
1590
+ }
1591
+ /** A private proxy must attest its effective Hub destination, not merely its local node. */
1592
+ export async function resolveFeedbackDestinationId(env) {
1593
+ const mode = hubMode(env);
1594
+ if (mode === 'public') {
1595
+ return publicFeedbackDestinationId(env);
1596
+ }
1597
+ if (mode !== 'private')
1598
+ return undefined;
1599
+ const proxy = proxyClientFromEnv(env);
1600
+ if (!proxy)
1601
+ return undefined;
1602
+ try {
1603
+ return privateFeedbackDestinationIdFromStatus(await proxy.status({ signal: AbortSignal.timeout(1_000) }));
1604
+ }
1605
+ catch {
1606
+ return undefined;
1607
+ }
1608
+ }
1609
+ export function makeAutoExecFeedbackBinding(candidate, mode, probe) {
1610
+ let boundDestinationId;
1611
+ let currentDestinationId;
1612
+ let refreshGeneration = 0;
1613
+ const bound = () => candidate && boundDestinationId ? { link: candidate, destinationId: boundDestinationId } : undefined;
1614
+ const current = () => candidate && currentDestinationId ? { link: candidate, destinationId: currentDestinationId } : undefined;
1615
+ return {
1616
+ bound,
1617
+ current,
1618
+ refresh: async () => {
1619
+ const generation = ++refreshGeneration;
1620
+ currentDestinationId = undefined;
1621
+ if (!candidate || !mode)
1622
+ return undefined;
1623
+ let destinationId;
1624
+ try {
1625
+ destinationId = await probe();
1626
+ }
1627
+ catch {
1628
+ return undefined;
1629
+ }
1630
+ if (generation !== refreshGeneration)
1631
+ return undefined;
1632
+ if (!destinationId || !/^sha256:[a-f0-9]{64}$/.test(destinationId)
1633
+ || (mode === 'public' && candidate.feedbackDestinationId !== destinationId)
1634
+ || (boundDestinationId && boundDestinationId !== destinationId))
1635
+ return undefined;
1636
+ boundDestinationId ??= destinationId;
1637
+ currentDestinationId = destinationId;
1638
+ return current();
1639
+ },
1640
+ };
1641
+ }
1642
+ /** One task may only create Hub debt if its execution and completion saw the same binding. */
1643
+ export function confirmedTaskFeedbackDestination(started, completed) {
1644
+ return started && completed && started.link === completed.link
1645
+ && started.destinationId === completed.destinationId ? started.destinationId : undefined;
1646
+ }
1647
+ /** A recovered claim has no verified execution-time Hub binding; never adopt today's endpoint. */
1648
+ export function committedTaskFeedbackDestination(taskDestination, current) {
1649
+ return taskDestination && current?.destinationId === taskDestination ? taskDestination : undefined;
1650
+ }
1651
+ /** A committed claim can finish recovering an existing row even while its Hub is unavailable. */
1652
+ export function prepareCommittedTaskOutcomeFeedback(outbox, claimRoot, task, verdict, destinationId) {
1653
+ const existing = outbox.get(taskOutcomeIdentity(claimRoot).operationId);
1654
+ const ownerDestination = existing?.destinationId ?? destinationId;
1655
+ if (!ownerDestination)
1656
+ return;
1657
+ const row = outbox.prepare({ claimRoot, task, verdict, destinationId: ownerDestination });
1658
+ if (row)
1659
+ outbox.acknowledgeLocal(row.operationId);
1660
+ }
1158
1661
  /**
1159
1662
  * Resolve public/private reuse wiring. Reuse remains default-off. When a public ATP miss handler is supplied,
1160
1663
  * a consent-gated free search-only seam may still be composed so auto-buy can prove a miss independently of
@@ -1174,9 +1677,52 @@ export function resolveHubLink(env = process.env, ingestor, connectHub = connect
1174
1677
  if (!reuseEnabled)
1175
1678
  return undefined;
1176
1679
  const proxy = proxyClientFromEnv(env);
1177
- return proxy ? makeHubLink(makeProxyHubCapability(proxy), ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0', undefined, resolvedAssetLog, env) : undefined;
1178
- }
1179
- const hub = resolvePublicHub(env, connectHub);
1680
+ if (!proxy)
1681
+ return undefined;
1682
+ const reportEnabled = env['EVOLVER_OUTCOME_REPORT'] !== '0';
1683
+ const privateSender = async (row) => {
1684
+ if (!reportEnabled)
1685
+ throw new FeedbackNotDispatchedError('outcome_reporting_disabled');
1686
+ if (!row.report || !row.destinationId)
1687
+ return { status: 'terminal', reason: 'reuse_result_not_reportable' };
1688
+ try {
1689
+ const receipt = reuseReceipt(await proxy.recordReuseResult({
1690
+ ...row.report,
1691
+ expectedHubMode: 'private', expectedHubDestinationId: row.destinationId,
1692
+ }));
1693
+ return reuseReceiptSendResult(receipt);
1694
+ }
1695
+ catch (error) {
1696
+ // These proxy rejections happen before the bound adapter sees the POST.
1697
+ // Preserve the debt as unsent so a later valid binding can handle it.
1698
+ if (error instanceof Error && (error.message === 'proxy_hub_destination_mismatch'
1699
+ || error.message === 'proxy_hub_mode_mismatch')) {
1700
+ throw new FeedbackNotDispatchedError(error.message);
1701
+ }
1702
+ return { status: 'ambiguous', reason: 'reuse_result_transport_unknown' };
1703
+ }
1704
+ };
1705
+ const link = makeHubLink(makeProxyHubCapability(proxy), ingestor, reportEnabled, undefined, resolvedAssetLog, env, privateSender);
1706
+ // The external private adapter has no task-wide memory endpoint today; its
1707
+ // explicit false stub is not an acknowledgement and must not create debt.
1708
+ delete link.sendTaskOutcome;
1709
+ return link;
1710
+ }
1711
+ // A fetched candidate may become durable provenance for a later feedback claim.
1712
+ // Bind the reuse capability itself to the same exact credential as the reporter:
1713
+ // checking only before a run would allow an OAuth replacement during search/fetch
1714
+ // to attribute an asset from principal B to the stored destination for A.
1715
+ const binding = (() => {
1716
+ try {
1717
+ return readPublicOAuthCredentialBinding(join(resolveIdentityHome(env), 'token.json'));
1718
+ }
1719
+ catch {
1720
+ return undefined;
1721
+ }
1722
+ })();
1723
+ if (reuseEnabled && !binding)
1724
+ return undefined;
1725
+ const hub = resolvePublicHub(env, connectHub, reuseEnabled ? binding : undefined);
1180
1726
  if (!hub)
1181
1727
  return undefined;
1182
1728
  if (!reuseEnabled && onVerifiedSearchMiss) {
@@ -1192,9 +1738,23 @@ export function resolveHubLink(env = process.env, ingestor, connectHub = connect
1192
1738
  reportOutcome: async () => undefined,
1193
1739
  };
1194
1740
  }
1741
+ const reportingHub = binding ? hub : undefined;
1742
+ const boundDestinationId = reportingHub && binding ? (() => {
1743
+ try {
1744
+ const sender = resolveAtpSenderId(env);
1745
+ return sender ? feedbackDestinationIdentity('public', resolveHubUrl(env), sender, binding) : undefined;
1746
+ }
1747
+ catch {
1748
+ return undefined;
1749
+ }
1750
+ })() : undefined;
1195
1751
  // Pass the ingestor so a reuse hit emits a value.reuse_hit root_event (#112) — the live source the value
1196
1752
  // ledger derives source=reuse entries from.
1197
- return makeHubLink(hub, ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0', onVerifiedSearchMiss, resolvedAssetLog, env);
1753
+ const link = makeHubLink(hub, ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0' && !!reportingHub, onVerifiedSearchMiss, resolvedAssetLog, env, undefined, reportingHub, boundDestinationId === publicFeedbackDestinationId(env) ? boundDestinationId : undefined);
1754
+ if (boundDestinationId && boundDestinationId === publicFeedbackDestinationId(env)) {
1755
+ link.feedbackDestinationId = boundDestinationId;
1756
+ }
1757
+ return link;
1198
1758
  }
1199
1759
  export function resolveHubQuestionLink(env = process.env, connectHub = connectPublicHub) {
1200
1760
  if (env['EVOLVER_OUTCOME_REPORT'] === '0')
@@ -1303,6 +1863,21 @@ export function resolveSolidifyPermitGate(env = process.env, connectHub = connec
1303
1863
  return undefined;
1304
1864
  }
1305
1865
  }
1866
+ // Only an accepted duplicate receipt confirms the same (asset, node, task_id) claim.
1867
+ function reuseReceiptSendResult(receipt) {
1868
+ if (receipt.terminal === true) {
1869
+ return receipt.recorded === false && terminalReuseStatus(receipt.status)
1870
+ ? { status: 'terminal', reason: safeAssetCallReason(receipt.reason) ?? 'hub_rejected' }
1871
+ : { status: 'ambiguous', reason: 'reuse_receipt_unconfirmed' };
1872
+ }
1873
+ if (receipt.recorded === true || (receipt.recorded === false && receipt.reason === 'duplicate_report')) {
1874
+ return { status: 'acknowledged', ...(receipt.id ? { receiptId: receipt.id } : {}) };
1875
+ }
1876
+ return { status: 'ambiguous', reason: safeAssetCallReason(receipt.reason) ?? 'reuse_receipt_unconfirmed' };
1877
+ }
1878
+ function terminalReuseStatus(status) {
1879
+ return status === undefined || isTerminalHubRejectionStatus(status);
1880
+ }
1306
1881
  export function makeProxyHubCapability(proxy) {
1307
1882
  const auth = {
1308
1883
  kind: 'enterprise_sso',
@@ -1334,6 +1909,7 @@ export function makeProxyHubCapability(proxy) {
1334
1909
  ...(report.traceId ? { traceId: report.traceId } : {}),
1335
1910
  ...(report.timeSavedSeconds !== undefined ? { timeSavedSeconds: report.timeSavedSeconds } : {}),
1336
1911
  ...(report.reason ? { reason: report.reason } : {}),
1912
+ ...(report.evidence ? { evidence: report.evidence } : {}),
1337
1913
  expectedHubMode: 'private',
1338
1914
  })),
1339
1915
  task: {
@@ -1378,11 +1954,32 @@ function assetMatchesId(asset, assetId) {
1378
1954
  function reuseReceipt(value) {
1379
1955
  const r = record(value);
1380
1956
  const payload = record(r['payload']);
1381
- const source = Object.keys(payload).length > 0 ? payload : r;
1957
+ const source = r['payload'] === undefined ? r : payload;
1958
+ const permitsSuccess = (value) => value === undefined || value === true;
1959
+ const rejected = !permitsSuccess(r['ok']) || !permitsSuccess(payload['ok'])
1960
+ || (source !== r && r['recorded'] !== undefined && r['recorded'] !== source['recorded'])
1961
+ || (source !== r && r['terminal'] !== undefined && source['terminal'] !== undefined
1962
+ && r['terminal'] !== source['terminal'])
1963
+ || (r['error'] !== undefined && r['error'] !== null)
1964
+ || (payload['error'] !== undefined && payload['error'] !== null);
1965
+ const terminalDeclared = source['terminal'] === true || r['terminal'] === true;
1966
+ const recorded = source['recorded'] === true && !rejected && !terminalDeclared;
1967
+ const reason = typeof source['reason'] === 'string' ? source['reason'] : undefined;
1968
+ const confirmedDuplicate = source['recorded'] === false && !rejected && !terminalDeclared;
1969
+ const status = source['status'];
1970
+ const outerStatus = r['status'];
1971
+ const terminal = source['recorded'] === false && !rejected && terminalDeclared
1972
+ && terminalReuseStatus(status) && terminalReuseStatus(outerStatus)
1973
+ && (status === undefined || outerStatus === undefined || status === outerStatus);
1382
1974
  return {
1383
- recorded: source['recorded'] !== false && source['ok'] !== false,
1384
- ...(typeof source['reason'] === 'string' ? { reason: source['reason'] } : {}),
1385
- ...(typeof source['id'] === 'string' ? { id: source['id'] } : {}),
1975
+ recorded,
1976
+ ...(reason !== undefined ? { reason: reason === 'duplicate_report' && !recorded && !confirmedDuplicate && !terminal
1977
+ ? 'reuse_receipt_unconfirmed' : reason } : {}),
1978
+ ...(recorded && typeof source['id'] === 'string' ? { id: source['id'] } : {}),
1979
+ ...(recorded && typeof source['eligible'] === 'boolean' ? { eligible: source['eligible'] } : {}),
1980
+ ...(recorded && typeof source['counted'] === 'boolean' ? { counted: source['counted'] } : {}),
1981
+ ...(recorded && typeof source['weight'] === 'number' && Number.isFinite(source['weight']) ? { weight: source['weight'] } : {}),
1982
+ ...(terminal ? { terminal: true, ...(typeof status === 'number' ? { status } : {}) } : {}),
1386
1983
  };
1387
1984
  }
1388
1985
  function record(value) {
@@ -1448,7 +2045,8 @@ export function resolveDistillProducer(env, opts) {
1448
2045
  const watermarkStore = opts.watermarkStore ?? new materialNs.WatermarkStore(events.materialWatermarkPath());
1449
2046
  const consumer = opts.consumer ?? new materialNs.ConsumerGroups({ store: materialStore, path: join(dirname(events.materialStorePath()), 'distill-consumer.json') });
1450
2047
  const observer = resolveDistillObserver({ consumer, store, review, ingestor: opts.ingestor, ...(opts.maxPerTick !== undefined ? { maxPerTick: opts.maxPerTick } : {}) });
1451
- const tick = () => runSessionIngestTick(sessionDirs, { materialStore, watermarkStore, ingestor: opts.ingestor });
2048
+ const tick = () => runSessionIngestTick(sessionDirs, { materialStore, watermarkStore,
2049
+ ingestor: opts.ingestor, ...(opts.contextIngestor !== undefined ? { contextIngestor: opts.contextIngestor } : {}) });
1452
2050
  return { enabled: true, observer, tick, sessionDirs };
1453
2051
  }
1454
2052
  export function shouldRunIdleDistill(intensity) {
@@ -1580,6 +2178,9 @@ export async function runAutoExec(argv) {
1580
2178
  if (cursorRewrite.observer)
1581
2179
  bus.register(cursorRewrite.observer);
1582
2180
  const ingestor = new events.Ingestor({ path: events.rootEventsPath(), sink: bus });
2181
+ // Material/cycle events still fan out on the bus. Context receipts require a
2182
+ // sink-free built-in writer whose durable result cannot be held by callbacks.
2183
+ const contextIngestor = new events.Ingestor({ path: events.rootEventsPath() });
1583
2184
  const reflection = resolveReflectionObserver(process.env, { ingestor });
1584
2185
  if (reflection.observer)
1585
2186
  bus.register(reflection.observer);
@@ -1598,7 +2199,7 @@ export async function runAutoExec(argv) {
1598
2199
  // Reuse-before-solve (#110) + outcome report-back: wire the adapter's reuseBeforeSolve as the hub-reuse
1599
2200
  // seam when enabled + credentialed (default OFF → undefined → zero hub calls, exactly today's behavior).
1600
2201
  // The seam injects hub candidates into the same selection pool as local genes, trust-first; the link's
1601
- // reporter closes the loop by sending the cycle outcome + used-asset claim back to the hub.
2202
+ // sender is enabled only when the effective Hub principal can be bound to an outbox debt.
1602
2203
  let atpAutoBuyer;
1603
2204
  const onVerifiedHubSearchMiss = (miss) => {
1604
2205
  // Resolve lazily: the first-run consent prompt happens after the daemon lock is acquired below, while Hub
@@ -1607,7 +2208,11 @@ export async function runAutoExec(argv) {
1607
2208
  if (atpAutoBuyer)
1608
2209
  scheduleAtpAutoBuyForVerifiedMiss(miss, atpAutoBuyer);
1609
2210
  };
1610
- const hubLink = resolveHubLink(process.env, ingestor, connectPublicHub, onVerifiedHubSearchMiss);
2211
+ const candidateHubLink = resolveHubLink(process.env, ingestor, connectPublicHub, onVerifiedHubSearchMiss);
2212
+ const feedbackMode = hubMode(process.env);
2213
+ const feedbackBinding = makeAutoExecFeedbackBinding(candidateHubLink, feedbackMode, () => feedbackMode === hubMode(process.env)
2214
+ ? resolveFeedbackDestinationId(process.env) : Promise.resolve(undefined));
2215
+ await feedbackBinding.refresh();
1611
2216
  const hubQuestionLink = resolveHubQuestionLink(process.env);
1612
2217
  const solidifyPermit = resolveSolidifyPermitGate(process.env);
1613
2218
  const strategyName = process.env['EVOLVE_STRATEGY'];
@@ -1626,6 +2231,10 @@ export async function runAutoExec(argv) {
1626
2231
  };
1627
2232
  const deps = withAutoExecSelectionConfig({
1628
2233
  engine, store, provenance, review, personality: personalityStore, memoryGraph,
2234
+ assertPromptAdapter: () => {
2235
+ if (!assetstore.isBuiltInPromptProvider(store))
2236
+ throw new Error('unsupported_unsupervised_prompt_provider_v1');
2237
+ },
1629
2238
  ...(process.env['EVOLVER_BENCHMARK_ID'] !== undefined ? { benchmark: assetstore.benchmarkContext(process.env['EVOLVER_BENCHMARK_ID']) } : {}),
1630
2239
  executionBinding: {
1631
2240
  journal: new exec.ExecutionBindingJournal(ingestor),
@@ -1638,7 +2247,6 @@ export async function runAutoExec(argv) {
1638
2247
  // strategy embedded) so the cross-AI loop self-closes — contained by the proven exec gates + worktree isolation.
1639
2248
  ...(probationOn ? { includeProbation: true } : {}),
1640
2249
  ...(!semanticIdfOn ? { disableSemanticIdf: true } : {}),
1641
- ...(hubLink ? { hubReuse: hubLink.seam } : {}),
1642
2250
  ...(solidifyPermit ? { solidifyPermit } : {}),
1643
2251
  ...(strategyName !== undefined ? { strategyName } : {}),
1644
2252
  // Validate through the hardened sandbox verifier so a validation command can't exfiltrate or phone home to game
@@ -1682,24 +2290,55 @@ export async function runAutoExec(argv) {
1682
2290
  // multi-minute agent run, and the daemon does one pass per task — revisit only if the log grows large (rotation
1683
2291
  // is still deferred). The recall rail stays empty until EVOLVER_AUTO_RECALL=1 separately enables value.recall.
1684
2292
  const reuseSignalOn = reuseSignalEnabled();
2293
+ const feedbackOutbox = new FeedbackOutbox(join(dirs.base, 'feedback-outbox'));
2294
+ const taskOutcomeOutbox = new TaskOutcomeOutbox(join(dirs.base, 'task-outcome-outbox'));
2295
+ // Capture the confirmed run binding in its receipt before feedback preparation.
2296
+ // Recovery uses that saved identity and eligibility, never today's credentials.
2297
+ const taskFeedbackDestinations = new WeakMap();
1685
2298
  const runOne = async (task) => {
2299
+ taskFeedbackDestinations.set(task, null);
1686
2300
  // One read of root_events (per pass) feeds BOTH rails: reported reuse outcomes (#268) and observed recall (#274
1687
2301
  // slice 3, folded at a lower weight). value.recall rides the SAME flag — it is the same soft re-order actuator.
1688
2302
  const evts = reuseSignalOn ? events.readEvents(events.rootEventsPath()) : null;
1689
- const taskDeps = evts
1690
- ? { ...deps, reuseOutcomes: ops.summarizeReuseOutcomes(evts), recallEvents: evts.filter((e) => e.type === ops.VALUE_RECALL_EVENT) }
1691
- : deps;
2303
+ const activeBinding = await feedbackBinding.refresh();
2304
+ const taskDeps = {
2305
+ ...deps,
2306
+ ...(evts ? { reuseOutcomes: ops.summarizeReuseOutcomes(evts),
2307
+ recallEvents: evts.filter((e) => e.type === ops.VALUE_RECALL_EVENT) } : {}),
2308
+ hubReuse: activeBinding?.link.seam,
2309
+ // The private proxy attests report POSTs, but not search/fetch. Never mint
2310
+ // Hub origin evidence for an asset fetched through that unbound path.
2311
+ hubFeedbackDestinationId: feedbackMode === 'public' ? activeBinding?.destinationId : undefined,
2312
+ };
1692
2313
  const v = await exec.runAutoExecTask(taskDeps, task, safety);
1693
- // Hub writes are best-effort side effects. Schedule them after the verdict exists, but never hold the queue's
1694
- // task->done move on network I/O or hub availability.
1695
- scheduleAutoExecHubSideEffects(task, v, { questions: hubQuestionLink, outcome: hubLink });
2314
+ const completedBinding = await feedbackBinding.refresh();
2315
+ taskFeedbackDestinations.set(task, confirmedTaskFeedbackDestination(activeBinding, completedBinding) ?? null);
1696
2316
  return v;
1697
2317
  };
1698
- const guarded = exec.singleFlight(runnerBoundAutoExecPass(cfg.runner, dirs, runOne));
2318
+ const guarded = exec.singleFlight(runnerBoundAutoExecPass(cfg.runner, dirs, runOne, {
2319
+ // Solo may roll the entire worktree back after this pass; no successful applied-use
2320
+ // claim is stable until that decision. It has no Hub egress by design.
2321
+ ...(solo ? {} : {
2322
+ taskOutcomeEnabled: feedbackMode === 'public' && !!candidateHubLink?.sendTaskOutcome,
2323
+ captureFeedbackDestination: (task) => taskFeedbackDestinations.get(task) ?? null,
2324
+ prepareFeedback: (claimRoot, task, verdict, executionDestinationId, taskOutcomeEnabled) => {
2325
+ // The durable receipt owns this snapshot before the volatile entry is consumed.
2326
+ taskFeedbackDestinations.delete(task);
2327
+ feedbackOutbox.prepare({ claimRoot, task, verdict,
2328
+ ...(executionDestinationId ? { destinationId: executionDestinationId } : {}) });
2329
+ // Existing debts retain their original destination even when today's Hub
2330
+ // is absent, private, opted out, or bound to another principal.
2331
+ prepareCommittedTaskOutcomeFeedback(taskOutcomeOutbox, claimRoot, task, verdict, taskOutcomeEnabled ? executionDestinationId ?? undefined : undefined);
2332
+ },
2333
+ }),
2334
+ afterCommit: (task, verdict) => {
2335
+ scheduleAutoExecHubSideEffects(task, verdict, { questions: hubQuestionLink });
2336
+ },
2337
+ }));
1699
2338
  // Auto-distill producer+consumer (#106): register the distillObserver on THIS bus, then a producer tick scans
1700
2339
  // the session dirs and records material on THIS Ingestor → material.batch_ready → observer drafts a quarantined
1701
2340
  // gene (A1) → human `review --approve` lifts it into inject/cursor (A2a/A2b). Off via EVOLVER_AUTO_DISTILL=0.
1702
- const distill = resolveDistillProducer(process.env, { ingestor, store, review });
2341
+ const distill = resolveDistillProducer(process.env, { ingestor, contextIngestor, store, review });
1703
2342
  if (distill.observer)
1704
2343
  bus.register(distill.observer);
1705
2344
  const llmDistill = resolveAutoDistillLlm(process.env, { store, review, ingestor, cwd: process.cwd() });
@@ -1721,7 +2360,7 @@ export async function runAutoExec(argv) {
1721
2360
  } },
1722
2361
  });
1723
2362
  const uninstallBrokenPipeGuards = installAutoexecBrokenPipeGuards();
1724
- const reuseEnabled = process.env['EVOLVER_REUSE_BEFORE_SOLVE'] === '1' && hubLink !== undefined;
2363
+ const reuseEnabled = process.env['EVOLVER_REUSE_BEFORE_SOLVE'] === '1' && feedbackBinding.bound() !== undefined;
1725
2364
  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'} semantic-idf=${semanticIdfOn ? 'on' : 'off'} selection-policy=${selectionPolicy} selection-guard=${selectionGuard} selection-floor=${selectionFloor === undefined ? 'unset' : selectionFloor} 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})`} task-receiver=${taskReceiver.enabled ? `on(repo=${taskReceiverRepo(process.env, cfg.allowedRoots)})` : `off(${taskReceiver.reason})`}\n`);
1726
2365
  if (cfg.allowedRoots.length === 0)
1727
2366
  process.stdout.write(' (allowlist empty → deny-by-default: nothing runs until you add a repo to config.json)\n');
@@ -1733,8 +2372,9 @@ export async function runAutoExec(argv) {
1733
2372
  // consumes one try (unlink + continue), so maxTries:1 would reclaim then immediately time out, wrongly refusing
1734
2373
  // the FIRST restart (Bugbot #149). A few short tries reclaim a dead owner's lock yet still refuse a LIVE holder
1735
2374
  // fast (~maxTries×waitMs ≈ 50ms) — reclaim/refuse behavior is covered by fileLock.test.
2375
+ let runtimeOwner;
1736
2376
  try {
1737
- util.acquireLock(lockPath, { maxTries: 5 });
2377
+ runtimeOwner = util.acquireLock(lockPath, { maxTries: 5 });
1738
2378
  }
1739
2379
  catch (error) {
1740
2380
  process.stderr.write(autoexecLockFailureMessage(error));
@@ -1770,6 +2410,24 @@ export async function runAutoExec(argv) {
1770
2410
  // SINGLE-FLIGHT the producer tick (same as autoExecPass): a session scan that outlasts pollMs must not let two
1771
2411
  // ticks interleave in recordSessionMaterial (which would re-emit material.batch_ready before watermarks settle).
1772
2412
  const guardedDistill = distill.enabled && distill.observer ? exec.singleFlight(() => distill.tick()) : null;
2413
+ const guardedContextDelivery = exec.singleFlight(() => {
2414
+ const writer = resolveContextObservationWriter(ingestor, contextIngestor);
2415
+ return writer ? writer.recoverContextDeliveries({ deadlineAt: Date.now() + 200 }) : Promise.resolve(undefined);
2416
+ });
2417
+ const contextDeliveryRootReady = () => {
2418
+ const writer = resolveContextObservationWriter(ingestor, contextIngestor);
2419
+ if (!writer)
2420
+ return true;
2421
+ try {
2422
+ const journal = events.Ingestor.contextDeliveryStatus(writer.path);
2423
+ return journal.confirmedPending === 0 && !journal.reasons.cleanup_pending;
2424
+ }
2425
+ catch {
2426
+ return false;
2427
+ }
2428
+ };
2429
+ let contextDeliveryTurnReady = false;
2430
+ let ingestionTelemetry = { state: distill.enabled ? 'unknown' : 'disabled' };
1773
2431
  const guardedLlmDistill = llmDistill.enabled ? exec.singleFlight(() => llmDistill.tick()) : null;
1774
2432
  const guardedAntiGeneDistill = antiGeneDistill.enabled ? exec.singleFlight(() => antiGeneDistill.tick()) : null;
1775
2433
  const guardedTranscriptDistill = transcriptDistill.enabled ? exec.singleFlight(() => transcriptDistill.tick()) : null;
@@ -1788,7 +2446,31 @@ export async function runAutoExec(argv) {
1788
2446
  return `commitment expired, asset ${assetId} not sent`;
1789
2447
  return `${ack.pending ? 'owed, will retry' : 'failed'} ${ack.error ?? ''}`;
1790
2448
  };
2449
+ // Reporting has its own durable outboxes and may encounter a slow Hub or an arbitrary backlog.
2450
+ // It must never hold the resident beat ahead of a committed Hub-task completion or its owed retries.
2451
+ const scheduleFeedbackDrain = makeDeferredAutoExecFeedbackDrain(async () => {
2452
+ const activeBinding = await feedbackBinding.refresh();
2453
+ const feedback = await flushAutoExecFeedback(feedbackOutbox, ingestor, activeBinding?.link.sendAppliedUse, activeBinding?.destinationId);
2454
+ if (activeBinding?.link.sendTaskOutcome) {
2455
+ const outcomes = await taskOutcomeOutbox.flush(activeBinding.destinationId, activeBinding.link.sendTaskOutcome);
2456
+ if (outcomes.delivered || outcomes.terminal || outcomes.ambiguous) {
2457
+ process.stdout.write(` task-outcome-feedback: delivered=${outcomes.delivered} terminal=${outcomes.terminal} ambiguous=${outcomes.ambiguous}\n`);
2458
+ }
2459
+ }
2460
+ if (feedback.projected || feedback.delivered || feedback.ambiguous) {
2461
+ process.stdout.write(` applied-use-feedback: projected=${feedback.projected} delivered=${feedback.delivered} ambiguous=${feedback.ambiguous}\n`);
2462
+ }
2463
+ }, () => {
2464
+ process.stderr.write('[autoexec] feedback_drain_failed; durable outbox remains for recovery\n');
2465
+ });
1791
2466
  const tick = async (beat) => {
2467
+ contextDeliveryTurnReady = false;
2468
+ // Join the actual projection/cleanup before any synchronous root writer.
2469
+ // Its 200ms admission deadline remains unchanged; cleanup owns its resources.
2470
+ await guardedContextDelivery().catch(() => undefined);
2471
+ contextDeliveryTurnReady = contextDeliveryRootReady();
2472
+ if (!contextDeliveryTurnReady)
2473
+ return { failed: false };
1792
2474
  let failed = false;
1793
2475
  const r = await guarded();
1794
2476
  if (r && !('skipped' in r) && r.length) {
@@ -1884,6 +2566,11 @@ export async function runAutoExec(argv) {
1884
2566
  }
1885
2567
  if (guardedDistill) {
1886
2568
  const d = await guardedDistill();
2569
+ if (d && !('skipped' in d))
2570
+ ingestionTelemetry = {
2571
+ state: (d.parseFailures ?? 0) > 0 || (d.invalidJsonRows ?? 0) > 0 ? 'degraded' : 'observed',
2572
+ lastTickAt: Date.now(), recorded: d.recorded, parseFailures: d.parseFailures ?? 0,
2573
+ };
1887
2574
  void submitDistillTickExplorationQuestion(hubQuestionLink, d).catch(() => undefined);
1888
2575
  }
1889
2576
  await runIdleLlmDistillForBeat(beat, guardedLlmDistill);
@@ -1928,29 +2615,52 @@ export async function runAutoExec(argv) {
1928
2615
  process.stderr.write(`[Solo] shutdown drain failed: ${error instanceof Error ? error.message : String(error)}\n`);
1929
2616
  }).finally(() => { cleanupAutoexecRuntime(); process.exit(1); });
1930
2617
  }
2618
+ return { failed: !ok };
1931
2619
  };
1932
2620
  // Heartbeat (#106): record liveness + pacing on the AE spine for the WebUI console, THROTTLED so a fast poll does
1933
2621
  // not flood the log — emit on an intensity change or at most once per EVOLVER_HEARTBEAT_MS (default 60s).
1934
2622
  const heartbeatMinMs = Math.max(0, Number(process.env['EVOLVER_HEARTBEAT_MS'] ?? 60_000));
1935
2623
  let lastBeatAt = 0;
1936
2624
  let lastIntensity = '';
2625
+ let lastTickAt = 0;
2626
+ let lastTickOutcome = 'completed';
1937
2627
  await cursorRewrite.start?.();
1938
2628
  const loop = startResidentLoop({
1939
- tick: solo ? soloTick : tick,
2629
+ tick: async (beat) => {
2630
+ try {
2631
+ const result = await (solo ? soloTick(beat) : tick(beat));
2632
+ lastTickOutcome = !contextDeliveryTurnReady ? 'blocked' : result?.failed ? 'failed' : 'completed';
2633
+ }
2634
+ catch (error) {
2635
+ lastTickOutcome = 'failed';
2636
+ throw error;
2637
+ }
2638
+ finally {
2639
+ lastTickAt = Date.now();
2640
+ }
2641
+ },
1940
2642
  basePollMs: cfg.pollMs,
1941
2643
  idleAware: process.env['EVOLVER_IDLE_AWARE'] !== '0',
1942
2644
  onBeat: (b) => {
1943
- const now = Date.now();
1944
- if (b.intensity === lastIntensity && now - lastBeatAt < heartbeatMinMs)
2645
+ // A later session-recovery turn may retain cleanup after SQL committed.
2646
+ // Neither heartbeat nor optional feedback may write through that owner.
2647
+ if (!contextDeliveryTurnReady || !contextDeliveryRootReady())
1945
2648
  return;
1946
- lastBeatAt = now;
1947
- lastIntensity = b.intensity;
1948
- void ingestor.ingest({
1949
- type: 'cycle.heartbeat', // a registered EVENT_TYPE (an unknown type would throw UnknownEventTypeError)
1950
- human: { title: `autoexec 心跳 (${b.intensity})`, severity: 'info' },
1951
- payload: { intensity: b.intensity, idleSeconds: b.idleSeconds, nextDelayMs: b.delayMs, runner: cfg.runner },
1952
- actor: { kind: 'machine', id: 'autoexec' },
1953
- }).catch(() => { });
2649
+ const now = Date.now();
2650
+ if (!(b.intensity === lastIntensity && now - lastBeatAt < heartbeatMinMs)) {
2651
+ lastBeatAt = now;
2652
+ lastIntensity = b.intensity;
2653
+ void ingestor.ingest({
2654
+ type: 'cycle.heartbeat', // a registered EVENT_TYPE (an unknown type would throw UnknownEventTypeError)
2655
+ human: { title: `autoexec 心跳 (${b.intensity})`, severity: 'info' },
2656
+ payload: { intensity: b.intensity, idleSeconds: b.idleSeconds, nextDelayMs: b.delayMs, runner: cfg.runner,
2657
+ runtime: autoexecHeartbeatTelemetry(runtimeOwner, lastTickAt, lastTickOutcome, heartbeatMinMs, ingestionTelemetry) },
2658
+ actor: { kind: 'machine', id: 'autoexec' },
2659
+ }).catch(() => { });
2660
+ }
2661
+ // Mandatory session ingestion and heartbeat admission precede synchronous
2662
+ // optional outbox checks; throttled beats still recover durable feedback.
2663
+ scheduleFeedbackDrain();
1954
2664
  },
1955
2665
  });
1956
2666
  // SIGINT/SIGTERM drain the in-flight beat before cleanup. SIGHUP cannot hot-reload this composition safely,