@evomap/evolver-cli 2.0.0-beta.9 → 2.0.1
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.
- package/dist/antiGeneBenchmark.js +2 -0
- package/dist/antiGeneRollout.js +9 -3
- package/dist/assetHealth.js +2 -0
- package/dist/assetTrust.js +14 -1
- package/dist/atp.d.ts +10 -5
- package/dist/atp.js +119 -26
- package/dist/atpAutoBuyer.d.ts +120 -0
- package/dist/atpAutoBuyer.js +814 -0
- package/dist/atpAutoDeliver.js +2 -2
- package/dist/autoDistillLlm.js +2 -1
- package/dist/autoDistillTranscript.js +3 -2
- package/dist/autoexec.d.ts +101 -13
- package/dist/autoexec.js +794 -91
- package/dist/cli.js +13 -0
- package/dist/cliContracts.d.ts +23 -2
- package/dist/cliContracts.js +504 -54
- package/dist/commands.d.ts +1 -0
- package/dist/commands.js +1 -0
- package/dist/curriculumCapabilityGaps.d.ts +6 -0
- package/dist/curriculumCapabilityGaps.js +24 -0
- package/dist/cycleConsumer.d.ts +13 -0
- package/dist/cycleConsumer.js +186 -20
- package/dist/dashboard.js +47 -9
- package/dist/dispatch.js +8 -2
- package/dist/distillPrimitives.d.ts +3 -2
- package/dist/distillPrimitives.js +80 -12
- package/dist/doctor.js +120 -11
- package/dist/identityHome.d.ts +9 -0
- package/dist/identityHome.js +47 -0
- package/dist/index.d.ts +70 -40
- package/dist/index.js +581 -193
- package/dist/learningTrace.d.ts +15 -0
- package/dist/learningTrace.js +73 -0
- package/dist/lifecycle.d.ts +67 -1
- package/dist/lifecycle.js +738 -44
- package/dist/localMemoryGraph.d.ts +90 -3
- package/dist/localMemoryGraph.js +2031 -231
- package/dist/login.d.ts +1 -1
- package/dist/login.js +3 -3
- package/dist/materialSnapshot.d.ts +9 -1
- package/dist/materialSnapshot.js +23 -6
- package/dist/memoryGraphOps.d.ts +8 -0
- package/dist/memoryGraphOps.js +140 -0
- package/dist/migrate/assetFormatMap.d.ts +61 -0
- package/dist/migrate/assetFormatMap.js +53 -0
- package/dist/migrate/envTranslate.d.ts +26 -0
- package/dist/migrate/envTranslate.js +147 -0
- package/dist/migrate/fieldMap.d.ts +4 -2
- package/dist/migrate/fieldMap.js +9 -5
- package/dist/migrate/oauthImport.d.ts +66 -0
- package/dist/migrate/oauthImport.js +667 -0
- package/dist/migrate/v1Import.d.ts +92 -1
- package/dist/migrate/v1Import.js +1481 -141
- package/dist/promptRecallHook.d.ts +24 -0
- package/dist/promptRecallHook.js +425 -0
- package/dist/recallVerifyReport.d.ts +37 -0
- package/dist/recallVerifyReport.js +244 -0
- package/dist/recipe.d.ts +7 -1
- package/dist/recipe.js +426 -56
- package/dist/requiredSandboxValidation.d.ts +5 -0
- package/dist/requiredSandboxValidation.js +4 -0
- package/dist/reuse.d.ts +9 -0
- package/dist/reuse.js +151 -56
- package/dist/runtimeCapabilities.js +15 -15
- package/dist/runtimeSessionSource.d.ts +3 -2
- package/dist/runtimeSessionSource.js +63 -11
- package/dist/selectionPolicyConfig.d.ts +8 -0
- package/dist/selectionPolicyConfig.js +18 -0
- package/dist/semanticIdfConfig.d.ts +2 -0
- package/dist/semanticIdfConfig.js +4 -0
- package/dist/sessionIngest.d.ts +37 -0
- package/dist/sessionIngest.js +156 -0
- package/dist/setupHooks.js +95 -1
- package/dist/skill2gep.d.ts +13 -9
- package/dist/skill2gep.js +42 -30
- package/dist/skillDistill.d.ts +8 -4
- package/dist/skillDistill.js +38 -9
- package/dist/solo/mode.js +1 -0
- package/dist/sync.d.ts +12 -0
- package/dist/sync.js +1246 -151
- package/dist/thesis.d.ts +1 -1
- package/dist/thesis.js +20 -3
- package/dist/trajectoryExport.js +21 -3
- package/dist/v1Compat.d.ts +1 -0
- package/dist/v1Compat.js +9 -0
- package/dist/workflowRuntime.js +24 -18
- package/package.json +11 -8
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 {
|
|
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,22 +19,50 @@ 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 './
|
|
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';
|
|
27
|
+
import { resolveExplicitNodeCredentials, resolveIdentityHome } from './identityHome.js';
|
|
24
28
|
import { runAutobuyPrompt } from './atpAutobuyPrompt.js';
|
|
25
29
|
import * as solomode from './solo/mode.js';
|
|
26
30
|
import * as gitGuard from './solo/gitGuard.js';
|
|
27
31
|
import * as breaker from './solo/breaker.js';
|
|
28
32
|
import { initializeWorkflowStartupRecovery } from './workflowRuntime.js';
|
|
29
33
|
import { readAutoExecConfig } from './autoexecConfig.js';
|
|
34
|
+
import { makeCurriculumCapabilityGapsProvider } from './curriculumCapabilityGaps.js';
|
|
35
|
+
import { resolveLearningTrace } from './learningTrace.js';
|
|
36
|
+
import { semanticIdfEnabled } from './semanticIdfConfig.js';
|
|
37
|
+
import { selectionFloorFromEnv, selectionGuardFromEnv, selectionPolicyFromEnv, } from './selectionPolicyConfig.js';
|
|
30
38
|
export { readAutoExecConfig } from './autoexecConfig.js';
|
|
39
|
+
export { semanticIdfEnabled } from './semanticIdfConfig.js';
|
|
40
|
+
export { selectionFloorFromEnv, selectionGuardFromEnv, selectionPolicyFromEnv, } from './selectionPolicyConfig.js';
|
|
41
|
+
export function withAutoExecSelectionPolicy(deps, env = process.env) {
|
|
42
|
+
const policy = selectionPolicyFromEnv(env);
|
|
43
|
+
return policy === 'engine-health' ? deps : { ...deps, selectionPolicy: policy };
|
|
44
|
+
}
|
|
45
|
+
export function withAutoExecSelectionConfig(deps, env = process.env) {
|
|
46
|
+
const withPolicy = withAutoExecSelectionPolicy(deps, env);
|
|
47
|
+
const selectionGuard = selectionGuardFromEnv(env);
|
|
48
|
+
const selectionFloor = selectionFloorFromEnv(env);
|
|
49
|
+
return {
|
|
50
|
+
...withPolicy,
|
|
51
|
+
selectionGuard,
|
|
52
|
+
...(selectionFloor !== undefined ? { selectionFloor } : {}),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
31
55
|
const ENV_FILE_UNAVAILABLE_DIAGNOSTIC = '[evolver-autoexec] env_file_unavailable\n';
|
|
32
|
-
/** Create the queue layout under <home>/autoexec/{tasks,done,refused}. */
|
|
56
|
+
/** Create the queue layout under <home>/autoexec/{tasks,inflight,done,refused}. */
|
|
33
57
|
export function ensureAutoExecDirs(base) {
|
|
34
|
-
const dirs = {
|
|
35
|
-
|
|
58
|
+
const dirs = {
|
|
59
|
+
base,
|
|
60
|
+
tasks: join(base, 'tasks'),
|
|
61
|
+
inflight: join(base, 'inflight'),
|
|
62
|
+
done: join(base, 'done'),
|
|
63
|
+
refused: join(base, 'refused'),
|
|
64
|
+
};
|
|
65
|
+
for (const dir of [dirs.tasks, dirs.inflight, receiptDir(dirs), dirs.done, dirs.refused])
|
|
36
66
|
mkdirSync(dir, { recursive: true });
|
|
37
67
|
return dirs;
|
|
38
68
|
}
|
|
@@ -65,40 +95,312 @@ export function summarizeSandboxedValidation(result) {
|
|
|
65
95
|
function createAutoExecPersonalityStore() {
|
|
66
96
|
return new personality.PersonalityStore();
|
|
67
97
|
}
|
|
98
|
+
const CLAIMED_TASK_SUFFIX = '.claimed.json';
|
|
99
|
+
const STARTED_TASK_SUFFIX = '.started.json';
|
|
100
|
+
const AMBIGUOUS_RECOVERY_REASON = 'autoexec_crash_recovery_ambiguous: execution may have started before shutdown; refusing automatic retry, explicitly requeue after inspecting prior side effects';
|
|
101
|
+
function receiptDir(dirs) {
|
|
102
|
+
return join(dirs.base, 'receipts');
|
|
103
|
+
}
|
|
104
|
+
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;
|
|
105
|
+
function receiptArtifactClaimName(name) {
|
|
106
|
+
const tempMatch = RECEIPT_TEMP_SUFFIX.exec(name);
|
|
107
|
+
const claimName = tempMatch?.[1] ?? name;
|
|
108
|
+
const claim = parseAutoExecClaim(claimName);
|
|
109
|
+
if (!claim || claim.name !== claimName)
|
|
110
|
+
return null;
|
|
111
|
+
if (tempMatch)
|
|
112
|
+
return claim.phase === 'started' ? claimName : null;
|
|
113
|
+
return claim.phase === 'started' || claim.phase === 'legacy' ? claimName : null;
|
|
114
|
+
}
|
|
115
|
+
function cleanupReceiptArtifacts(dirs, shouldRemove) {
|
|
116
|
+
const dir = receiptDir(dirs);
|
|
117
|
+
let entries;
|
|
118
|
+
try {
|
|
119
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
for (const entry of entries) {
|
|
125
|
+
if (!entry.isFile())
|
|
126
|
+
continue;
|
|
127
|
+
const claimName = receiptArtifactClaimName(entry.name);
|
|
128
|
+
if (!claimName || !shouldRemove(claimName))
|
|
129
|
+
continue;
|
|
130
|
+
try {
|
|
131
|
+
unlinkSync(join(dir, entry.name));
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
// Cleanup is retried by the next pass after the claim has been archived.
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function cleanupCommittedClaimReceipt(dirs, claimName) {
|
|
139
|
+
const path = join(receiptDir(dirs), claimName);
|
|
140
|
+
try {
|
|
141
|
+
if (lstatSync(path).isFile())
|
|
142
|
+
unlinkSync(path);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
// Orphan cleanup retries this after the claim has been archived.
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
function cleanupOrphanReceiptArtifacts(dirs) {
|
|
149
|
+
let activeClaims;
|
|
150
|
+
try {
|
|
151
|
+
activeClaims = new Set(readdirSync(dirs.inflight, { withFileTypes: true })
|
|
152
|
+
.filter((entry) => entry.isFile())
|
|
153
|
+
.map((entry) => entry.name));
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
cleanupReceiptArtifacts(dirs, (claimName) => !activeClaims.has(claimName));
|
|
159
|
+
}
|
|
160
|
+
function parseAutoExecClaim(name) {
|
|
161
|
+
const separator = name.indexOf('--');
|
|
162
|
+
if (separator < 0 || separator + 2 >= name.length)
|
|
163
|
+
return null;
|
|
164
|
+
const encodedName = name.slice(separator + 2);
|
|
165
|
+
if (encodedName.endsWith(CLAIMED_TASK_SUFFIX)) {
|
|
166
|
+
return {
|
|
167
|
+
name,
|
|
168
|
+
originalName: `${encodedName.slice(0, -CLAIMED_TASK_SUFFIX.length)}.json`,
|
|
169
|
+
phase: 'claimed',
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
if (encodedName.endsWith(STARTED_TASK_SUFFIX)) {
|
|
173
|
+
return {
|
|
174
|
+
name,
|
|
175
|
+
originalName: `${encodedName.slice(0, -STARTED_TASK_SUFFIX.length)}.json`,
|
|
176
|
+
phase: 'started',
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
return encodedName.endsWith('.json') ? { name, originalName: encodedName, phase: 'legacy' } : null;
|
|
180
|
+
}
|
|
181
|
+
function taskClaimName(originalName) {
|
|
182
|
+
return `${randomUUID()}--${originalName.slice(0, -'.json'.length)}${CLAIMED_TASK_SUFFIX}`;
|
|
183
|
+
}
|
|
184
|
+
function archiveTaskPath(dest, originalName, claimName) {
|
|
185
|
+
const defaultArchive = join(dest, `task-${originalName}`);
|
|
186
|
+
return existsSync(defaultArchive) ? join(dest, `task-${claimName}`) : defaultArchive;
|
|
187
|
+
}
|
|
188
|
+
function isAutoExecVerdict(value, taskId) {
|
|
189
|
+
if (!value || typeof value !== 'object')
|
|
190
|
+
return false;
|
|
191
|
+
const candidate = value;
|
|
192
|
+
return candidate.taskId === taskId
|
|
193
|
+
&& (candidate.status === 'refused'
|
|
194
|
+
|| candidate.status === 'skipped'
|
|
195
|
+
|| candidate.status === 'solidified'
|
|
196
|
+
|| candidate.status === 'failed'
|
|
197
|
+
|| candidate.status === 'innovated');
|
|
198
|
+
}
|
|
199
|
+
function persistedClaimReceipt(dirs, claim, taskId) {
|
|
200
|
+
try {
|
|
201
|
+
const path = join(receiptDir(dirs), claim.name);
|
|
202
|
+
if (!lstatSync(path).isFile())
|
|
203
|
+
return null;
|
|
204
|
+
const value = JSON.parse(readFileSync(path, 'utf8'));
|
|
205
|
+
if (!value || typeof value !== 'object')
|
|
206
|
+
return null;
|
|
207
|
+
const receipt = value;
|
|
208
|
+
if (receipt.claimName !== claim.name
|
|
209
|
+
|| (receipt.destination !== 'done' && receipt.destination !== 'refused')
|
|
210
|
+
|| !isAutoExecVerdict(receipt.verdict, taskId))
|
|
211
|
+
return null;
|
|
212
|
+
const expectedDestination = receipt.verdict.status === 'refused' ? 'refused' : 'done';
|
|
213
|
+
if (receipt.destination !== expectedDestination)
|
|
214
|
+
return null;
|
|
215
|
+
return receipt;
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
if (error.code !== 'ENOENT'
|
|
219
|
+
&& !(error instanceof SyntaxError))
|
|
220
|
+
throw error;
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
function persistClaimReceipt(dirs, receipt) {
|
|
225
|
+
const receipts = receiptDir(dirs);
|
|
226
|
+
const receiptPath = join(receipts, receipt.claimName);
|
|
227
|
+
const tempPath = join(receipts, `${receipt.claimName}.${randomUUID()}.tmp`);
|
|
228
|
+
try {
|
|
229
|
+
writeFileSync(tempPath, JSON.stringify(receipt, null, 2), { encoding: 'utf8', flag: 'wx' });
|
|
230
|
+
renameSync(tempPath, receiptPath);
|
|
231
|
+
}
|
|
232
|
+
finally {
|
|
233
|
+
try {
|
|
234
|
+
if (lstatSync(tempPath).isFile())
|
|
235
|
+
unlinkSync(tempPath);
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
// The atomic rename normally removes the temp path.
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
function recoverAmbiguousClaim(dirs, claim) {
|
|
243
|
+
const taskPath = join(dirs.inflight, claim.name);
|
|
244
|
+
let taskId = `recovery-${claim.name.slice(0, 64)}`;
|
|
245
|
+
try {
|
|
246
|
+
taskId = exec.normalizeAutoExecTask(JSON.parse(readFileSync(taskPath, 'utf8'))).id;
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
// The task may have been only partially published before the prior process stopped.
|
|
250
|
+
}
|
|
251
|
+
const receipt = persistedClaimReceipt(dirs, claim, taskId);
|
|
252
|
+
if (receipt) {
|
|
253
|
+
const dest = receipt.destination === 'refused' ? dirs.refused : dirs.done;
|
|
254
|
+
const canonicalVerdict = join(dest, claim.originalName);
|
|
255
|
+
writeFileSync(canonicalVerdict, JSON.stringify(receipt.verdict, null, 2));
|
|
256
|
+
renameSync(taskPath, archiveTaskPath(dest, claim.originalName, claim.name));
|
|
257
|
+
cleanupCommittedClaimReceipt(dirs, claim.name);
|
|
258
|
+
return receipt.verdict;
|
|
259
|
+
}
|
|
260
|
+
const verdict = {
|
|
261
|
+
taskId,
|
|
262
|
+
status: 'refused',
|
|
263
|
+
reason: AMBIGUOUS_RECOVERY_REASON,
|
|
264
|
+
};
|
|
265
|
+
writeFileSync(join(dirs.refused, `recovery-${claim.name}`), JSON.stringify(verdict, null, 2));
|
|
266
|
+
renameSync(taskPath, archiveTaskPath(dirs.refused, claim.originalName, claim.name));
|
|
267
|
+
cleanupCommittedClaimReceipt(dirs, claim.name);
|
|
268
|
+
return verdict;
|
|
269
|
+
}
|
|
68
270
|
/**
|
|
69
|
-
* One queue pass:
|
|
70
|
-
* or refused/ (deny-by-default)
|
|
271
|
+
* One queue pass: atomically claim regular tasks/*.json into inflight/, then route each verdict to done/
|
|
272
|
+
* (success or failure) or refused/ (deny-by-default). A claim is atomically marked started before runOne;
|
|
273
|
+
* after a crash, started and legacy claims are ambiguous and fail closed instead of repeating side effects.
|
|
274
|
+
* Unreadable or incomplete claimed tasks stay pending because the drop-directory has no atomic publish marker.
|
|
71
275
|
*/
|
|
72
|
-
export async function autoExecPass(dirs, runOne) {
|
|
73
|
-
const
|
|
276
|
+
export async function autoExecPass(dirs, runOne, options = {}) {
|
|
277
|
+
const executePendingTasks = options.executePendingTasks ?? true;
|
|
278
|
+
const existingClaims = readdirSync(dirs.inflight, { withFileTypes: true })
|
|
279
|
+
.filter((entry) => entry.isFile() && entry.name.endsWith('.json'))
|
|
280
|
+
.map((entry) => parseAutoExecClaim(entry.name))
|
|
281
|
+
.filter((claim) => claim !== null);
|
|
282
|
+
cleanupOrphanReceiptArtifacts(dirs);
|
|
283
|
+
const pendingClaims = existingClaims.filter((claim) => claim.phase === 'claimed');
|
|
74
284
|
const out = [];
|
|
285
|
+
for (const claim of existingClaims.filter((item) => item.phase !== 'claimed')) {
|
|
286
|
+
try {
|
|
287
|
+
out.push(recoverAmbiguousClaim(dirs, claim));
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
const errorCode = error.code;
|
|
291
|
+
out.push({
|
|
292
|
+
taskId: `recovery-${claim.name.slice(0, claim.name.indexOf('--'))}`,
|
|
293
|
+
status: 'failed',
|
|
294
|
+
reason: `autoexec_crash_recovery_failed:${errorCode && /^[A-Z0-9_]+$/.test(errorCode) ? errorCode : 'unknown'}`,
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
cleanupOrphanReceiptArtifacts(dirs);
|
|
299
|
+
if (!executePendingTasks)
|
|
300
|
+
return out;
|
|
301
|
+
const files = readdirSync(dirs.tasks, { withFileTypes: true })
|
|
302
|
+
.filter((entry) => entry.isFile() && entry.name.endsWith('.json'))
|
|
303
|
+
.map((entry) => entry.name);
|
|
75
304
|
for (const f of files) {
|
|
76
|
-
const
|
|
305
|
+
const claimName = taskClaimName(f);
|
|
306
|
+
try {
|
|
307
|
+
renameSync(join(dirs.tasks, f), join(dirs.inflight, claimName));
|
|
308
|
+
const claim = parseAutoExecClaim(claimName);
|
|
309
|
+
if (claim)
|
|
310
|
+
pendingClaims.push(claim);
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
if (error.code !== 'ENOENT')
|
|
314
|
+
throw error;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
for (const claim of pendingClaims) {
|
|
318
|
+
const taskPath = join(dirs.inflight, claim.name);
|
|
319
|
+
let task;
|
|
320
|
+
try {
|
|
321
|
+
task = exec.normalizeAutoExecTask(JSON.parse(readFileSync(taskPath, 'utf8')));
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
// A producer may still hold this path open and finish writing it after this pass.
|
|
325
|
+
// Leaving it in place prevents a transient partial read from acknowledging and losing the task.
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
const startedName = claim.name.slice(0, -CLAIMED_TASK_SUFFIX.length) + STARTED_TASK_SUFFIX;
|
|
329
|
+
const startedPath = join(dirs.inflight, startedName);
|
|
330
|
+
renameSync(taskPath, startedPath);
|
|
77
331
|
const v = await runOne(task).catch((e) => ({ taskId: task.id, status: 'failed', reason: e instanceof Error ? e.message : String(e) }));
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
332
|
+
const destination = v.status === 'refused' ? 'refused' : 'done';
|
|
333
|
+
const dest = destination === 'refused' ? dirs.refused : dirs.done;
|
|
334
|
+
persistClaimReceipt(dirs, { claimName: startedName, destination, verdict: v });
|
|
335
|
+
writeFileSync(join(dest, claim.originalName), JSON.stringify(v, null, 2));
|
|
336
|
+
renameSync(startedPath, archiveTaskPath(dest, claim.originalName, startedName));
|
|
337
|
+
cleanupCommittedClaimReceipt(dirs, startedName);
|
|
81
338
|
out.push(v);
|
|
82
339
|
}
|
|
340
|
+
cleanupOrphanReceiptArtifacts(dirs);
|
|
83
341
|
return out;
|
|
84
342
|
}
|
|
85
|
-
/**
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
343
|
+
/** Keep unsupported built-in runners away from the execution queue without stopping the resident daemon. */
|
|
344
|
+
export function runnerBoundAutoExecPass(runner, dirs, runOne) {
|
|
345
|
+
return () => autoExecPass(dirs, runOne, { executePendingTasks: runner === 'gemini' });
|
|
346
|
+
}
|
|
347
|
+
const ATP_CAPABILITY_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,47}$/;
|
|
348
|
+
function atpCapabilityGaps(signals) {
|
|
349
|
+
return signalNs.capabilityGapsFromSignals(signals)
|
|
350
|
+
.filter((capability) => ATP_CAPABILITY_PATTERN.test(capability))
|
|
351
|
+
.slice(0, 8);
|
|
352
|
+
}
|
|
353
|
+
function hasAtpCapabilityGap(signals) {
|
|
354
|
+
return signals.includes('capability_gap') || atpCapabilityGaps(signals).length > 0;
|
|
355
|
+
}
|
|
356
|
+
function normalizedCapabilityGapSignals(signals) {
|
|
357
|
+
if (!hasAtpCapabilityGap(signals))
|
|
358
|
+
return signals;
|
|
359
|
+
const ordinary = signals.filter((signal) => signal !== 'capability_gap'
|
|
360
|
+
&& !signal.startsWith('capability_gap:')
|
|
361
|
+
&& !signal.startsWith('cap:'));
|
|
362
|
+
return [...new Set([...ordinary, ...atpCapabilityGapRequest(signals).signals])];
|
|
363
|
+
}
|
|
364
|
+
/** Build the deliberately small, public-safe ATP request allowed to leave autoexec after a verified Hub miss. */
|
|
365
|
+
export function atpCapabilityGapRequest(signals) {
|
|
366
|
+
const capabilities = atpCapabilityGaps(signals);
|
|
367
|
+
if (capabilities.length === 0)
|
|
368
|
+
capabilities.push('code_evolution');
|
|
369
|
+
const subject = capabilities[0].replace(/[_-]+/g, ' ');
|
|
370
|
+
return {
|
|
371
|
+
kind: 'capability_gap',
|
|
372
|
+
capabilities,
|
|
373
|
+
question: `I need help with ${subject}. Please provide one concrete, actionable solution and state any assumptions.`,
|
|
374
|
+
routingMode: 'fastest',
|
|
375
|
+
verifyMode: 'auto',
|
|
376
|
+
signals: ['capability_gap', ...capabilities.map((capability) => `cap:${capability}`)],
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
/** Schedule economic work outside the reuse/task critical path and contain all asynchronous failures. */
|
|
380
|
+
export function scheduleAtpAutoBuyForVerifiedMiss(miss, buyer) {
|
|
381
|
+
void buyer.consider(atpCapabilityGapRequest(miss.signals)).catch(() => undefined);
|
|
382
|
+
}
|
|
383
|
+
/** Resolve an autonomous buyer only after an explicit env/ack consent check; the buyer checks consent again. */
|
|
384
|
+
export function resolveAtpAutoBuyer(env = process.env, createClient = createAtpClientFromEnv) {
|
|
385
|
+
if (!getAtpConsent(env).enabled)
|
|
386
|
+
return undefined;
|
|
387
|
+
try {
|
|
388
|
+
return new AtpAutoBuyer({ client: createClient(env), env });
|
|
389
|
+
}
|
|
390
|
+
catch {
|
|
391
|
+
return undefined;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
export function makeHubReuseSeam(cap, cache, ingestor, onAssetReused, onVerifiedSearchMiss, audit = {}) {
|
|
95
395
|
return async (signals, ctx) => {
|
|
396
|
+
const searchSignals = normalizedCapabilityGapSignals(signals);
|
|
96
397
|
// Pending value.reuse_hit ingests (#112). The onReuseHit callback is synchronous, so it cannot await the
|
|
97
398
|
// ingest itself; it stashes the (error-swallowing) promise here and the seam awaits them before returning,
|
|
98
399
|
// making the emission deterministically durable without letting an ingest error ever break reuse.
|
|
99
400
|
const pending = [];
|
|
100
|
-
const r = await reuseBeforeSolve(cap, cache,
|
|
401
|
+
const r = await reuseBeforeSolve(cap, cache, searchSignals, {
|
|
101
402
|
...(ctx?.cycleId ? { cycleId: ctx.cycleId } : {}),
|
|
403
|
+
...(audit.env ? { env: audit.env } : {}),
|
|
102
404
|
// Two consumers hang off a reuse HIT:
|
|
103
405
|
// - value-ledger emission (#112): a `value.reuse_hit` root_event so the ledger derives a real
|
|
104
406
|
// source=reuse entry (refs → assetId + cycleId) — live wiring, not a fixture;
|
|
@@ -116,9 +418,149 @@ export function makeHubReuseSeam(cap, cache, ingestor, onAssetReused) {
|
|
|
116
418
|
});
|
|
117
419
|
if (pending.length > 0)
|
|
118
420
|
await Promise.all(pending); // emitReuseHit never rejects (it swallows ingest errors)
|
|
421
|
+
const runId = ctx?.cycleId ?? null;
|
|
422
|
+
const taskId = runId?.startsWith('autoexec-') ? runId.slice('autoexec-'.length) : undefined;
|
|
423
|
+
if (r.action === 'fetch') {
|
|
424
|
+
const rawAsset = r.asset;
|
|
425
|
+
const assetId = r.candidate?.assetId ?? stringField(rawAsset, 'asset_id');
|
|
426
|
+
const assetType = stringField(rawAsset, 'type');
|
|
427
|
+
const sourceNodeId = stringField(rawAsset, 'source_node_id');
|
|
428
|
+
const chainId = stringField(rawAsset, 'chain_id');
|
|
429
|
+
const indexedTokenCost = assetId ? assetTokenCostBestEffort(audit.assetLog, assetId) : undefined;
|
|
430
|
+
const savings = hubNs.reuseSavingsForAsset(rawAsset, r.mode, indexedTokenCost);
|
|
431
|
+
const hit = {
|
|
432
|
+
runId,
|
|
433
|
+
...(assetId ? { assetId } : {}),
|
|
434
|
+
...(assetType ? { assetType } : {}),
|
|
435
|
+
...(sourceNodeId ? { sourceNodeId } : {}),
|
|
436
|
+
...(chainId ? { chainId } : {}),
|
|
437
|
+
...(r.score !== undefined ? { score: r.score } : {}),
|
|
438
|
+
mode: r.mode,
|
|
439
|
+
signals: [...searchSignals],
|
|
440
|
+
tokensSaved: savings.tokens_saved,
|
|
441
|
+
tokensSavedBasis: savings.tokens_saved_basis,
|
|
442
|
+
};
|
|
443
|
+
scheduleAssetCallBestEffort(audit.assetLog, {
|
|
444
|
+
run_id: runId,
|
|
445
|
+
action: 'hub_search_hit',
|
|
446
|
+
...(hit.assetId ? { asset_id: hit.assetId } : {}),
|
|
447
|
+
...(hit.assetType ? { asset_type: hit.assetType } : {}),
|
|
448
|
+
...(hit.sourceNodeId ? { source_node_id: hit.sourceNodeId } : {}),
|
|
449
|
+
...(hit.chainId ? { chain_id: hit.chainId } : {}),
|
|
450
|
+
...(hit.score !== undefined ? { score: hit.score } : {}),
|
|
451
|
+
mode: hit.mode,
|
|
452
|
+
signals: hit.signals,
|
|
453
|
+
...(taskId ? { extra: { task_id: taskId } } : {}),
|
|
454
|
+
});
|
|
455
|
+
try {
|
|
456
|
+
audit.onSearchHit?.(hit);
|
|
457
|
+
}
|
|
458
|
+
catch { /* audit state must never change reuse */ }
|
|
459
|
+
}
|
|
460
|
+
else if (r.reason !== 'no_signals') {
|
|
461
|
+
scheduleAssetCallBestEffort(audit.assetLog, {
|
|
462
|
+
run_id: runId,
|
|
463
|
+
action: 'hub_search_miss',
|
|
464
|
+
mode: r.mode,
|
|
465
|
+
signals: [...searchSignals],
|
|
466
|
+
...(r.reason ? { reason: r.reason } : {}),
|
|
467
|
+
...(taskId ? { extra: { task_id: taskId } } : {}),
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
if (r.action === 'solve-fresh'
|
|
471
|
+
&& (r.reason === 'no_results' || r.reason === 'below_threshold')
|
|
472
|
+
&& hasAtpCapabilityGap(searchSignals)) {
|
|
473
|
+
try {
|
|
474
|
+
onVerifiedSearchMiss?.({
|
|
475
|
+
reason: r.reason,
|
|
476
|
+
signals: [...searchSignals],
|
|
477
|
+
...(ctx?.cycleId ? { cycleId: ctx.cycleId } : {}),
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
catch { /* an optional economic side effect must never change reuse behavior */ }
|
|
481
|
+
}
|
|
119
482
|
return r.action === 'fetch' && r.candidate ? [r.candidate] : [];
|
|
120
483
|
};
|
|
121
484
|
}
|
|
485
|
+
/**
|
|
486
|
+
* Free search-only seam used by ATP auto-buy when reuse injection is disabled. It proves a capability miss with
|
|
487
|
+
* the same dual-leg search and score threshold as reuse, but never performs the paid fetch or contributes a Hub
|
|
488
|
+
* candidate.
|
|
489
|
+
*/
|
|
490
|
+
export function makeHubSearchMissProbe(cap, cache, onVerifiedSearchMiss, enabled, env = process.env, assetLog) {
|
|
491
|
+
return async (signals, ctx) => {
|
|
492
|
+
if (!enabled() || !hasAtpCapabilityGap(signals))
|
|
493
|
+
return [];
|
|
494
|
+
// ATP consent authorizes a bounded capability query, not disclosure of local error signatures/transcripts.
|
|
495
|
+
const signalList = atpCapabilityGapRequest(signals).signals;
|
|
496
|
+
if (signalList.length === 0)
|
|
497
|
+
return [];
|
|
498
|
+
const search = await searchHubMetadata(cap, cache, signalList, { env });
|
|
499
|
+
if (!search.complete) {
|
|
500
|
+
scheduleAssetCallBestEffort(assetLog, {
|
|
501
|
+
run_id: ctx?.cycleId ?? null,
|
|
502
|
+
action: 'hub_search_miss',
|
|
503
|
+
mode: 'direct',
|
|
504
|
+
signals: search.signals,
|
|
505
|
+
reason: 'search_error',
|
|
506
|
+
});
|
|
507
|
+
return [];
|
|
508
|
+
}
|
|
509
|
+
const { metadata, searchCached } = search;
|
|
510
|
+
let reason;
|
|
511
|
+
if (metadata.length === 0) {
|
|
512
|
+
reason = 'no_results';
|
|
513
|
+
}
|
|
514
|
+
else {
|
|
515
|
+
const ranked = hubNs.scoreSearchResults(signalList, metadata);
|
|
516
|
+
if (hubNs.decideReuse(ranked, { threshold: getMinReuseScore(env) }).action === 'solve-fresh') {
|
|
517
|
+
reason = 'below_threshold';
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
if (!reason)
|
|
521
|
+
return [];
|
|
522
|
+
scheduleAssetCallBestEffort(assetLog, {
|
|
523
|
+
run_id: ctx?.cycleId ?? null,
|
|
524
|
+
action: 'hub_search_miss',
|
|
525
|
+
mode: 'direct',
|
|
526
|
+
signals: signalList,
|
|
527
|
+
reason,
|
|
528
|
+
extra: { search_cached: searchCached },
|
|
529
|
+
});
|
|
530
|
+
try {
|
|
531
|
+
onVerifiedSearchMiss({
|
|
532
|
+
reason,
|
|
533
|
+
signals: signalList,
|
|
534
|
+
...(ctx?.cycleId ? { cycleId: ctx.cycleId } : {}),
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
catch { /* ATP scheduling must never change the solve path */ }
|
|
538
|
+
return [];
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
function stringField(record, key) {
|
|
542
|
+
const value = record?.[key];
|
|
543
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
544
|
+
}
|
|
545
|
+
function assetTokenCostBestEffort(log, assetId) {
|
|
546
|
+
try {
|
|
547
|
+
return log?.assetCostIndex?.()[assetId];
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
return undefined;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
function appendAssetCallBestEffort(log, entry) {
|
|
554
|
+
try {
|
|
555
|
+
log?.append(entry);
|
|
556
|
+
}
|
|
557
|
+
catch { /* local audit failure must never break reuse or task completion */ }
|
|
558
|
+
}
|
|
559
|
+
function scheduleAssetCallBestEffort(log, entry) {
|
|
560
|
+
if (!log)
|
|
561
|
+
return;
|
|
562
|
+
setImmediate(() => { appendAssetCallBestEffort(log, entry); });
|
|
563
|
+
}
|
|
122
564
|
/** Append a `value.reuse_hit` root_event for a reuse hit (#112). Never throws (reuse stays an optimization). */
|
|
123
565
|
async function emitReuseHit(ingestor, hit) {
|
|
124
566
|
try {
|
|
@@ -218,6 +660,52 @@ function writeQuestionState(path, state) {
|
|
|
218
660
|
recentQuestions: [...(state.recentQuestions ?? [])].slice(-30),
|
|
219
661
|
}, null, 2)}\n`);
|
|
220
662
|
}
|
|
663
|
+
function laterQuestionTimestamp(left, right) {
|
|
664
|
+
if (!left)
|
|
665
|
+
return right ?? null;
|
|
666
|
+
if (!right)
|
|
667
|
+
return left;
|
|
668
|
+
const leftMs = Date.parse(left);
|
|
669
|
+
const rightMs = Date.parse(right);
|
|
670
|
+
if (Number.isFinite(leftMs) && Number.isFinite(rightMs))
|
|
671
|
+
return rightMs >= leftMs ? right : left;
|
|
672
|
+
if (Number.isFinite(leftMs))
|
|
673
|
+
return left;
|
|
674
|
+
if (Number.isFinite(rightMs))
|
|
675
|
+
return right;
|
|
676
|
+
return right >= left ? right : left;
|
|
677
|
+
}
|
|
678
|
+
function mergeQuestionStates(current, incoming) {
|
|
679
|
+
const recency = (state) => Math.max(...[state.lastAskedAt, state.lastUrgentAt, state.lastExploreAt]
|
|
680
|
+
.map((value) => value ? Date.parse(value) : Number.NEGATIVE_INFINITY)
|
|
681
|
+
.filter(Number.isFinite), Number.NEGATIVE_INFINITY);
|
|
682
|
+
const [older, newer] = recency(current) <= recency(incoming)
|
|
683
|
+
? [current, incoming]
|
|
684
|
+
: [incoming, current];
|
|
685
|
+
const recentQuestions = [];
|
|
686
|
+
for (const question of [...(older.recentQuestions ?? []), ...(newer.recentQuestions ?? [])]) {
|
|
687
|
+
const existing = recentQuestions.indexOf(question);
|
|
688
|
+
if (existing >= 0)
|
|
689
|
+
recentQuestions.splice(existing, 1);
|
|
690
|
+
recentQuestions.push(question);
|
|
691
|
+
}
|
|
692
|
+
return {
|
|
693
|
+
lastAskedAt: laterQuestionTimestamp(current.lastAskedAt, incoming.lastAskedAt),
|
|
694
|
+
lastUrgentAt: laterQuestionTimestamp(current.lastUrgentAt, incoming.lastUrgentAt),
|
|
695
|
+
lastExploreAt: laterQuestionTimestamp(current.lastExploreAt, incoming.lastExploreAt),
|
|
696
|
+
recentQuestions: recentQuestions.slice(-30),
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
const MAX_PENDING_QUESTION_STATES = 30;
|
|
700
|
+
function rememberPendingQuestionState(pendingStates, state) {
|
|
701
|
+
pendingStates.add(state);
|
|
702
|
+
while (pendingStates.size > MAX_PENDING_QUESTION_STATES) {
|
|
703
|
+
const oldest = pendingStates.values().next().value;
|
|
704
|
+
if (!oldest)
|
|
705
|
+
break;
|
|
706
|
+
pendingStates.delete(oldest);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
221
709
|
function questionSubmitTimeoutMs(options) {
|
|
222
710
|
const raw = options.timeoutMs ?? Number(options.env?.[QUESTION_SUBMIT_TIMEOUT_ENV]);
|
|
223
711
|
if (Number.isFinite(raw) && raw > 0)
|
|
@@ -237,11 +725,12 @@ function hasAcceptedQuestionReceipt(receipts) {
|
|
|
237
725
|
function writeQuestionStateIfAccepted(path, state, receipts) {
|
|
238
726
|
if (!hasAcceptedQuestionReceipt(receipts))
|
|
239
727
|
return false;
|
|
240
|
-
writeQuestionState(path, state);
|
|
728
|
+
writeQuestionState(path, mergeQuestionStates(readQuestionState(path), state));
|
|
241
729
|
return true;
|
|
242
730
|
}
|
|
243
|
-
function writeLateQuestionStateIfAccepted(submitResult, statePath, state) {
|
|
244
|
-
void submitResult
|
|
731
|
+
function writeLateQuestionStateIfAccepted(submitResult, statePath, state, onSettled) {
|
|
732
|
+
void submitResult
|
|
733
|
+
.then((submitted) => {
|
|
245
734
|
if (submitted.status !== 'submitted')
|
|
246
735
|
return;
|
|
247
736
|
try {
|
|
@@ -250,7 +739,8 @@ function writeLateQuestionStateIfAccepted(submitResult, statePath, state) {
|
|
|
250
739
|
catch {
|
|
251
740
|
// The caller already received a timeout; late cooldown persistence is best-effort.
|
|
252
741
|
}
|
|
253
|
-
})
|
|
742
|
+
})
|
|
743
|
+
.finally(onSettled);
|
|
254
744
|
}
|
|
255
745
|
async function submitQuestionsWithTimeout(submitResult, timeoutMs) {
|
|
256
746
|
let timer;
|
|
@@ -267,7 +757,7 @@ async function submitQuestionsWithTimeout(submitResult, timeoutMs) {
|
|
|
267
757
|
clearTimeout(timer);
|
|
268
758
|
}
|
|
269
759
|
}
|
|
270
|
-
async function submitProactiveQuestions(cap, task, options) {
|
|
760
|
+
async function submitProactiveQuestions(cap, task, options, pendingStates) {
|
|
271
761
|
if (options.enabled === false || !cap.questions)
|
|
272
762
|
return { status: 'disabled', questionCount: 0 };
|
|
273
763
|
try {
|
|
@@ -277,10 +767,11 @@ async function submitProactiveQuestions(cap, task, options) {
|
|
|
277
767
|
return { status: 'skipped', questionCount: 0 };
|
|
278
768
|
if (QUESTION_CONTEXT_SENSITIVE_RE.test(context))
|
|
279
769
|
return { status: 'skipped', questionCount: 0 };
|
|
770
|
+
const effectiveState = [...pendingStates].reduce((state, pending) => mergeQuestionStates(state, pending), readQuestionState(statePath));
|
|
280
771
|
const result = hubNs.generateQuestions({
|
|
281
772
|
signals: task.signals,
|
|
282
773
|
sessionTranscript: context,
|
|
283
|
-
state:
|
|
774
|
+
state: effectiveState,
|
|
284
775
|
now: options.now?.() ?? Date.now(),
|
|
285
776
|
env: options.env ?? process.env,
|
|
286
777
|
});
|
|
@@ -288,8 +779,10 @@ async function submitProactiveQuestions(cap, task, options) {
|
|
|
288
779
|
return { status: 'skipped', questionCount: 0 };
|
|
289
780
|
const submitResult = observeQuestionSubmit(cap.questions.submit(result.questions));
|
|
290
781
|
const submitted = await submitQuestionsWithTimeout(submitResult, questionSubmitTimeoutMs(options));
|
|
291
|
-
if (submitted.status === 'timeout')
|
|
292
|
-
|
|
782
|
+
if (submitted.status === 'timeout') {
|
|
783
|
+
rememberPendingQuestionState(pendingStates, result.state);
|
|
784
|
+
writeLateQuestionStateIfAccepted(submitResult, statePath, result.state, () => pendingStates.delete(result.state));
|
|
785
|
+
}
|
|
293
786
|
if (submitted.status !== 'submitted')
|
|
294
787
|
return { status: submitted.status, questionCount: result.questions.length };
|
|
295
788
|
if (!writeQuestionStateIfAccepted(statePath, result.state, submitted.receipts))
|
|
@@ -303,9 +796,10 @@ async function submitProactiveQuestions(cap, task, options) {
|
|
|
303
796
|
}
|
|
304
797
|
export function makeHubQuestionLink(cap, options = {}) {
|
|
305
798
|
let queue = Promise.resolve();
|
|
799
|
+
const pendingStates = new Set();
|
|
306
800
|
return {
|
|
307
801
|
submitForTask: (task) => {
|
|
308
|
-
const run = queue.then(() => submitProactiveQuestions(cap, task, options));
|
|
802
|
+
const run = queue.then(() => submitProactiveQuestions(cap, task, options, pendingStates));
|
|
309
803
|
queue = run.then(() => undefined, () => undefined);
|
|
310
804
|
return run;
|
|
311
805
|
},
|
|
@@ -348,6 +842,94 @@ export function releaseAutoexecLock(lockPath, deps = {}) {
|
|
|
348
842
|
return false;
|
|
349
843
|
}
|
|
350
844
|
}
|
|
845
|
+
/** Keep a detached daemon alive when its output consumer closes, without hiding other stream failures. */
|
|
846
|
+
export function installAutoexecBrokenPipeGuards(deps = {}) {
|
|
847
|
+
const stdout = deps.stdout ?? process.stdout;
|
|
848
|
+
const stderr = deps.stderr ?? process.stderr;
|
|
849
|
+
const onError = (error) => {
|
|
850
|
+
if (error?.code === 'EPIPE')
|
|
851
|
+
return;
|
|
852
|
+
throw error;
|
|
853
|
+
};
|
|
854
|
+
stdout.on('error', onError);
|
|
855
|
+
stderr.on('error', onError);
|
|
856
|
+
let installed = true;
|
|
857
|
+
return () => {
|
|
858
|
+
if (!installed)
|
|
859
|
+
return;
|
|
860
|
+
installed = false;
|
|
861
|
+
removeAutoexecStreamErrorListener(stdout, onError);
|
|
862
|
+
removeAutoexecStreamErrorListener(stderr, onError);
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
function removeAutoexecStreamErrorListener(stream, listener) {
|
|
866
|
+
if (stream.off) {
|
|
867
|
+
stream.off('error', listener);
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
stream.removeListener?.('error', listener);
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Own autoexec's process-signal lifetime. V2 intentionally has no hot-reload seam: SIGHUP is informational and
|
|
874
|
+
* keeps the current generation alive; SIGINT/SIGTERM drain the resident loop before cleanup and exit.
|
|
875
|
+
*/
|
|
876
|
+
export function waitForAutoexecShutdown(deps) {
|
|
877
|
+
const signals = deps.signals ?? process;
|
|
878
|
+
const write = deps.write ?? ((message) => { process.stdout.write(message); });
|
|
879
|
+
return new Promise((resolve, reject) => {
|
|
880
|
+
let stopping = false;
|
|
881
|
+
let listenersInstalled = true;
|
|
882
|
+
const removeListeners = () => {
|
|
883
|
+
if (!listenersInstalled)
|
|
884
|
+
return;
|
|
885
|
+
listenersInstalled = false;
|
|
886
|
+
for (const [signal, listener] of listeners)
|
|
887
|
+
removeAutoexecSignalListener(signals, signal, listener);
|
|
888
|
+
};
|
|
889
|
+
const finish = (failure) => {
|
|
890
|
+
removeListeners();
|
|
891
|
+
try {
|
|
892
|
+
deps.cleanup();
|
|
893
|
+
}
|
|
894
|
+
catch (cleanupError) {
|
|
895
|
+
reject(cleanupError);
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
if (failure)
|
|
899
|
+
reject(failure.error);
|
|
900
|
+
else
|
|
901
|
+
resolve(0);
|
|
902
|
+
};
|
|
903
|
+
const shutdown = (signal) => {
|
|
904
|
+
if (stopping)
|
|
905
|
+
return;
|
|
906
|
+
stopping = true;
|
|
907
|
+
write(`\nevolver autoexec: ${signal} -> graceful stop (finishing in-flight, releasing lock)\n`);
|
|
908
|
+
void Promise.resolve()
|
|
909
|
+
.then(() => deps.stop())
|
|
910
|
+
.then(() => { finish(); }, (error) => { finish({ error }); });
|
|
911
|
+
};
|
|
912
|
+
const onSighup = () => {
|
|
913
|
+
if (stopping)
|
|
914
|
+
return;
|
|
915
|
+
write('\nevolver autoexec: SIGHUP received; hot reload is not supported, continuing with current configuration (restart the daemon to apply changes)\n');
|
|
916
|
+
};
|
|
917
|
+
const listeners = [
|
|
918
|
+
['SIGINT', () => { shutdown('SIGINT'); }],
|
|
919
|
+
['SIGTERM', () => { shutdown('SIGTERM'); }],
|
|
920
|
+
['SIGHUP', onSighup],
|
|
921
|
+
];
|
|
922
|
+
for (const [signal, listener] of listeners)
|
|
923
|
+
signals.on(signal, listener);
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
function removeAutoexecSignalListener(source, signal, listener) {
|
|
927
|
+
if (source.off) {
|
|
928
|
+
source.off(signal, listener);
|
|
929
|
+
return;
|
|
930
|
+
}
|
|
931
|
+
source.removeListener?.(signal, listener);
|
|
932
|
+
}
|
|
351
933
|
export function urgentQuestionRuntimeWiringStatus() {
|
|
352
934
|
return hubNs.URGENT_QUESTION_RUNTIME_WIRING_STATUS;
|
|
353
935
|
}
|
|
@@ -413,19 +995,60 @@ export function scheduleAutoExecHubSideEffects(task, verdict, links) {
|
|
|
413
995
|
* candidate can be withheld by trust/review gates or lose selection, so fetch-time attribution would overclaim.
|
|
414
996
|
* Reporting never throws and never blocks the verdict.
|
|
415
997
|
*/
|
|
416
|
-
export function makeHubLink(cap, ingestor, reportEnabled = true) {
|
|
417
|
-
const
|
|
998
|
+
export function makeHubLink(cap, ingestor, reportEnabled = true, onVerifiedSearchMiss, assetLog, env) {
|
|
999
|
+
const maxPendingAuditRuns = 256;
|
|
1000
|
+
const searchHitsByRun = new Map();
|
|
1001
|
+
const seam = makeHubReuseSeam(cap, new ReuseCache(), ingestor, undefined, onVerifiedSearchMiss, {
|
|
1002
|
+
assetLog,
|
|
1003
|
+
...(env ? { env } : {}),
|
|
1004
|
+
onSearchHit: (hit) => {
|
|
1005
|
+
if (!hit.runId || !hit.assetId)
|
|
1006
|
+
return;
|
|
1007
|
+
if (!searchHitsByRun.has(hit.runId) && searchHitsByRun.size >= maxPendingAuditRuns) {
|
|
1008
|
+
const oldestRun = searchHitsByRun.keys().next().value;
|
|
1009
|
+
if (oldestRun !== undefined)
|
|
1010
|
+
searchHitsByRun.delete(oldestRun);
|
|
1011
|
+
}
|
|
1012
|
+
// One reuse-before-solve invocation can fetch at most one winner. Replace any stale state left by an
|
|
1013
|
+
// unexpectedly aborted earlier run that reused the same task id.
|
|
1014
|
+
searchHitsByRun.set(hit.runId, new Map([[hit.assetId, hit]]));
|
|
1015
|
+
},
|
|
1016
|
+
});
|
|
418
1017
|
return {
|
|
419
1018
|
seam,
|
|
420
1019
|
reportOutcome: async (task, verdict) => {
|
|
421
|
-
if (!reportEnabled)
|
|
422
|
-
return;
|
|
423
1020
|
const status = verdictToOutcomeStatus(verdict.status);
|
|
424
|
-
|
|
425
|
-
|
|
1021
|
+
const runId = `autoexec-${task.id}`;
|
|
1022
|
+
const searchHits = searchHitsByRun.get(runId);
|
|
1023
|
+
searchHitsByRun.delete(runId);
|
|
426
1024
|
const usedAssetIds = Array.isArray(verdict.usedAssetIds)
|
|
427
1025
|
? [...new Set(verdict.usedAssetIds.filter((id) => typeof id === 'string' && id.length > 0))]
|
|
428
1026
|
: [];
|
|
1027
|
+
// Drain attribution synchronously (before a duplicate task id can start), then yield before the production
|
|
1028
|
+
// sink's synchronous append and all Hub I/O. The detached side effect cannot delay routing to done/.
|
|
1029
|
+
await new Promise((resolve) => { setImmediate(resolve); });
|
|
1030
|
+
if (status !== null) {
|
|
1031
|
+
for (const assetId of usedAssetIds) {
|
|
1032
|
+
const hit = searchHits?.get(assetId);
|
|
1033
|
+
const mode = hit?.mode;
|
|
1034
|
+
appendAssetCallBestEffort(assetLog, {
|
|
1035
|
+
run_id: runId,
|
|
1036
|
+
action: mode === 'reference' ? 'asset_reference' : 'asset_reuse',
|
|
1037
|
+
asset_id: assetId,
|
|
1038
|
+
...(hit?.assetType ? { asset_type: hit.assetType } : {}),
|
|
1039
|
+
...(hit?.sourceNodeId ? { source_node_id: hit.sourceNodeId } : {}),
|
|
1040
|
+
...(hit?.chainId ? { chain_id: hit.chainId } : {}),
|
|
1041
|
+
...(hit?.score !== undefined ? { score: hit.score } : {}),
|
|
1042
|
+
...(mode ? { mode } : {}),
|
|
1043
|
+
...(hit ? { tokens_saved: hit.tokensSaved, tokens_saved_basis: hit.tokensSavedBasis } : {}),
|
|
1044
|
+
signals: hit?.signals ?? task.signals,
|
|
1045
|
+
...(verdict.reason ? { reason: verdict.reason } : {}),
|
|
1046
|
+
extra: { task_id: task.id, verdict_status: verdict.status, outcome_status: status },
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
if (!reportEnabled || status === null)
|
|
1051
|
+
return;
|
|
429
1052
|
try {
|
|
430
1053
|
await cap.recordOutcome({
|
|
431
1054
|
signals: task.signals,
|
|
@@ -438,21 +1061,43 @@ export function makeHubLink(cap, ingestor, reportEnabled = true) {
|
|
|
438
1061
|
if (usedAssetIds.length > 0 && cap.recordReuseResult) {
|
|
439
1062
|
await Promise.all(usedAssetIds.map(async (assetId) => {
|
|
440
1063
|
try {
|
|
441
|
-
await cap.recordReuseResult?.({
|
|
1064
|
+
const receipt = await cap.recordReuseResult?.({
|
|
442
1065
|
assetId,
|
|
443
1066
|
outcome: status === 'success' ? 'success' : 'failed',
|
|
444
1067
|
taskId: task.id,
|
|
445
1068
|
...(verdict.reason ? { reason: verdict.reason } : {}),
|
|
446
1069
|
});
|
|
1070
|
+
appendAssetCallBestEffort(assetLog, {
|
|
1071
|
+
run_id: runId,
|
|
1072
|
+
action: receipt?.recorded ? 'hub_review_submitted' : 'hub_review_rejected',
|
|
1073
|
+
asset_id: assetId,
|
|
1074
|
+
signals: task.signals,
|
|
1075
|
+
...(safeAssetCallReason(receipt?.reason) ? { reason: safeAssetCallReason(receipt?.reason) } : {}),
|
|
1076
|
+
extra: { task_id: task.id, outcome_status: status, ...(receipt?.id ? { receipt_id: receipt.id } : {}) },
|
|
1077
|
+
});
|
|
1078
|
+
}
|
|
1079
|
+
catch {
|
|
1080
|
+
appendAssetCallBestEffort(assetLog, {
|
|
1081
|
+
run_id: runId,
|
|
1082
|
+
action: 'hub_review_failed',
|
|
1083
|
+
asset_id: assetId,
|
|
1084
|
+
signals: task.signals,
|
|
1085
|
+
reason: 'record_reuse_result_failed',
|
|
1086
|
+
extra: { task_id: task.id, outcome_status: status },
|
|
1087
|
+
});
|
|
447
1088
|
}
|
|
448
|
-
catch { /* reuse-result is best-effort observability; never fail the task */ }
|
|
449
1089
|
}));
|
|
450
1090
|
}
|
|
451
1091
|
},
|
|
452
1092
|
};
|
|
453
1093
|
}
|
|
1094
|
+
function safeAssetCallReason(value) {
|
|
1095
|
+
return typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,100}$/.test(value) ? value : undefined;
|
|
1096
|
+
}
|
|
454
1097
|
function resolvePublicHub(env = process.env, connectHub = connectPublicHub) {
|
|
455
|
-
|
|
1098
|
+
if (hubMode(env) !== 'public')
|
|
1099
|
+
return undefined;
|
|
1100
|
+
const dir = resolveIdentityHome(env);
|
|
456
1101
|
if (!existsSync(join(dir, 'token.json')))
|
|
457
1102
|
return undefined;
|
|
458
1103
|
try {
|
|
@@ -468,37 +1113,55 @@ function resolvePublicHub(env = process.env, connectHub = connectPublicHub) {
|
|
|
468
1113
|
}
|
|
469
1114
|
}
|
|
470
1115
|
function hubMode(env) {
|
|
471
|
-
|
|
1116
|
+
const mode = String(env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase();
|
|
1117
|
+
return mode === 'public' || mode === 'private' ? mode : undefined;
|
|
472
1118
|
}
|
|
473
1119
|
/**
|
|
474
|
-
* Resolve
|
|
475
|
-
*
|
|
476
|
-
*
|
|
477
|
-
* hub config — reuse is an optimization. Outcome reporting rides the same gate (it is the read-back half
|
|
478
|
-
* of the same paid hub relationship); EVOLVER_OUTCOME_REPORT=0 turns just the reporting off.
|
|
1120
|
+
* Resolve public/private reuse wiring. Reuse remains default-off. When a public ATP miss handler is supplied,
|
|
1121
|
+
* a consent-gated free search-only seam may still be composed so auto-buy can prove a miss independently of
|
|
1122
|
+
* reuse injection; that seam never fetches or injects Hub assets.
|
|
479
1123
|
*/
|
|
480
|
-
export function resolveHubLink(env = process.env, ingestor, connectHub = connectPublicHub) {
|
|
1124
|
+
export function resolveHubLink(env = process.env, ingestor, connectHub = connectPublicHub, onVerifiedSearchMiss, assetLog) {
|
|
481
1125
|
const envFile = loadEnvFileFromEnv(env);
|
|
482
1126
|
if (envFile.error) {
|
|
483
1127
|
process.stderr.write(ENV_FILE_UNAVAILABLE_DIAGNOSTIC);
|
|
484
1128
|
return undefined;
|
|
485
1129
|
}
|
|
486
|
-
|
|
1130
|
+
const reuseEnabled = env['EVOLVER_REUSE_BEFORE_SOLVE'] === '1';
|
|
1131
|
+
if (!reuseEnabled && !onVerifiedSearchMiss)
|
|
487
1132
|
return undefined;
|
|
1133
|
+
const resolvedAssetLog = assetLog ?? new hubNs.AssetCallLog(events.assetCallLogPath(env));
|
|
488
1134
|
if (hubMode(env) === 'private') {
|
|
1135
|
+
if (!reuseEnabled)
|
|
1136
|
+
return undefined;
|
|
489
1137
|
const proxy = proxyClientFromEnv(env);
|
|
490
|
-
return proxy ? makeHubLink(makeProxyHubCapability(proxy), ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0') : undefined;
|
|
1138
|
+
return proxy ? makeHubLink(makeProxyHubCapability(proxy), ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0', undefined, resolvedAssetLog, env) : undefined;
|
|
491
1139
|
}
|
|
492
1140
|
const hub = resolvePublicHub(env, connectHub);
|
|
493
1141
|
if (!hub)
|
|
494
1142
|
return undefined;
|
|
1143
|
+
if (!reuseEnabled && onVerifiedSearchMiss) {
|
|
1144
|
+
return {
|
|
1145
|
+
seam: makeHubSearchMissProbe(hub, new ReuseCache(), onVerifiedSearchMiss, () => {
|
|
1146
|
+
try {
|
|
1147
|
+
return getAtpConsent(env).enabled;
|
|
1148
|
+
}
|
|
1149
|
+
catch {
|
|
1150
|
+
return false;
|
|
1151
|
+
}
|
|
1152
|
+
}, env, resolvedAssetLog),
|
|
1153
|
+
reportOutcome: async () => undefined,
|
|
1154
|
+
};
|
|
1155
|
+
}
|
|
495
1156
|
// Pass the ingestor so a reuse hit emits a value.reuse_hit root_event (#112) — the live source the value
|
|
496
1157
|
// ledger derives source=reuse entries from.
|
|
497
|
-
return makeHubLink(hub, ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0');
|
|
1158
|
+
return makeHubLink(hub, ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0', onVerifiedSearchMiss, resolvedAssetLog, env);
|
|
498
1159
|
}
|
|
499
1160
|
export function resolveHubQuestionLink(env = process.env, connectHub = connectPublicHub) {
|
|
500
1161
|
if (env['EVOLVER_OUTCOME_REPORT'] === '0')
|
|
501
1162
|
return undefined;
|
|
1163
|
+
if (hubMode(env) !== 'public')
|
|
1164
|
+
return undefined;
|
|
502
1165
|
const hub = resolvePublicHub(env, connectHub);
|
|
503
1166
|
if (!hub)
|
|
504
1167
|
return undefined;
|
|
@@ -542,21 +1205,35 @@ export function resolveSolidifyPermitGate(env = process.env, connectHub = connec
|
|
|
542
1205
|
const flag = solidifyVerifyFlag(env);
|
|
543
1206
|
if (flag === 'off')
|
|
544
1207
|
return undefined;
|
|
1208
|
+
const mode = hubMode(env);
|
|
1209
|
+
if (mode !== 'public') {
|
|
1210
|
+
return flag === 'on'
|
|
1211
|
+
? () => ({
|
|
1212
|
+
ok: false,
|
|
1213
|
+
reason: mode === 'private'
|
|
1214
|
+
? 'hub_solidify_verify_unavailable:private_hub_not_supported'
|
|
1215
|
+
: 'hub_solidify_verify_unavailable:invalid_hub_mode',
|
|
1216
|
+
})
|
|
1217
|
+
: undefined;
|
|
1218
|
+
}
|
|
545
1219
|
const hubUrl = resolveConfiguredHubUrl(env) ?? (flag === 'on' ? resolveHubUrl(env) : undefined);
|
|
546
1220
|
if (!hubUrl) {
|
|
547
1221
|
if (flag === 'on')
|
|
548
1222
|
return () => ({ ok: false, reason: 'hub_solidify_verify_unavailable:no_hub_url' });
|
|
549
1223
|
return undefined;
|
|
550
1224
|
}
|
|
551
|
-
const
|
|
1225
|
+
const explicitCredentials = resolveExplicitNodeCredentials(env);
|
|
1226
|
+
const { nodeSecret } = explicitCredentials;
|
|
1227
|
+
const senderId = nodeSecret
|
|
1228
|
+
? explicitCredentials.senderId ?? resolveAtpSenderId(env)
|
|
1229
|
+
: resolveAtpSenderId(env);
|
|
552
1230
|
if (!senderId) {
|
|
553
1231
|
if (flag === 'on')
|
|
554
1232
|
return () => ({ ok: false, reason: 'hub_solidify_verify_unavailable:no_sender_id' });
|
|
555
1233
|
return undefined;
|
|
556
1234
|
}
|
|
557
|
-
const nodeSecret = env['EVOMAP_NODE_SECRET']?.trim() || env['A2A_NODE_SECRET']?.trim();
|
|
558
1235
|
const authMode = nodeSecret ? 'legacy' : 'oauth';
|
|
559
|
-
const dir =
|
|
1236
|
+
const dir = resolveIdentityHome(env);
|
|
560
1237
|
if (authMode === 'oauth' && !existsSync(join(dir, 'token.json'))) {
|
|
561
1238
|
if (flag === 'on')
|
|
562
1239
|
return () => ({ ok: false, reason: 'hub_solidify_verify_unavailable:no_credentials' });
|
|
@@ -597,10 +1274,16 @@ export function makeProxyHubCapability(proxy) {
|
|
|
597
1274
|
};
|
|
598
1275
|
return {
|
|
599
1276
|
auth,
|
|
600
|
-
search: async (query) => resultAssets(await proxy.search(
|
|
601
|
-
|
|
1277
|
+
search: async (query) => resultAssets(await proxy.search({
|
|
1278
|
+
...proxySearchArgs(query),
|
|
1279
|
+
expectedHubMode: 'private',
|
|
1280
|
+
})),
|
|
1281
|
+
fetch: async (query) => resultAssets(await proxy.search({
|
|
1282
|
+
...proxySearchArgs(query),
|
|
1283
|
+
expectedHubMode: 'private',
|
|
1284
|
+
})),
|
|
602
1285
|
fetchAssetById: async (assetId) => {
|
|
603
|
-
const asset = firstAsset(await proxy.fetchAsset({ assetId }));
|
|
1286
|
+
const asset = firstAsset(await proxy.fetchAsset({ assetId, expectedHubMode: 'private' }));
|
|
604
1287
|
return assetMatchesId(asset, assetId) ? asset : null;
|
|
605
1288
|
},
|
|
606
1289
|
publish: async () => ({ receiptId: 'proxy-disabled', status: 'rejected', terminal: true, reason: 'proxy_autoexec_publish_disabled' }),
|
|
@@ -612,6 +1295,7 @@ export function makeProxyHubCapability(proxy) {
|
|
|
612
1295
|
...(report.traceId ? { traceId: report.traceId } : {}),
|
|
613
1296
|
...(report.timeSavedSeconds !== undefined ? { timeSavedSeconds: report.timeSavedSeconds } : {}),
|
|
614
1297
|
...(report.reason ? { reason: report.reason } : {}),
|
|
1298
|
+
expectedHubMode: 'private',
|
|
615
1299
|
})),
|
|
616
1300
|
task: {
|
|
617
1301
|
claim: async () => ({ claimId: 'proxy-disabled' }),
|
|
@@ -813,6 +1497,9 @@ export async function runAutoExec(argv) {
|
|
|
813
1497
|
const home = argv.find((a) => !a.startsWith('-')) ?? join(events.evomapHome(), 'autoexec');
|
|
814
1498
|
const dirs = ensureAutoExecDirs(home);
|
|
815
1499
|
const cfg = readAutoExecConfig(home);
|
|
1500
|
+
if (cfg.runner !== 'gemini') {
|
|
1501
|
+
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');
|
|
1502
|
+
}
|
|
816
1503
|
// Solo mode (--solo): the "constrained wild" profile. Hard-cut network + ATP
|
|
817
1504
|
// at the SOURCE — in-process, before any resolve* below reads its env gate — so
|
|
818
1505
|
// both the startup wiring and any in-cycle path see them disabled. This is the
|
|
@@ -861,25 +1548,44 @@ export async function runAutoExec(argv) {
|
|
|
861
1548
|
if (memoryEventMirror.observer)
|
|
862
1549
|
bus.register(memoryEventMirror.observer);
|
|
863
1550
|
const personalityStore = createAutoExecPersonalityStore();
|
|
864
|
-
const engine = new algo.CycleEngine({
|
|
1551
|
+
const engine = new algo.CycleEngine({
|
|
1552
|
+
ingestor,
|
|
1553
|
+
selection: algo.makeGeneSelectionPoint(),
|
|
1554
|
+
store,
|
|
1555
|
+
now: () => Date.now(),
|
|
1556
|
+
personality: personalityStore,
|
|
1557
|
+
capabilityGaps: makeCurriculumCapabilityGapsProvider(process.env),
|
|
1558
|
+
});
|
|
865
1559
|
// Reuse-before-solve (#110) + outcome report-back: wire the adapter's reuseBeforeSolve as the hub-reuse
|
|
866
1560
|
// seam when enabled + credentialed (default OFF → undefined → zero hub calls, exactly today's behavior).
|
|
867
1561
|
// The seam injects hub candidates into the same selection pool as local genes, trust-first; the link's
|
|
868
1562
|
// reporter closes the loop by sending the cycle outcome + used-asset claim back to the hub.
|
|
869
|
-
|
|
1563
|
+
let atpAutoBuyer;
|
|
1564
|
+
const onVerifiedHubSearchMiss = (miss) => {
|
|
1565
|
+
// Resolve lazily: the first-run consent prompt happens after the daemon lock is acquired below, while Hub
|
|
1566
|
+
// composition happens here. A later verified miss therefore observes the newly recorded consent correctly.
|
|
1567
|
+
atpAutoBuyer ??= resolveAtpAutoBuyer(process.env);
|
|
1568
|
+
if (atpAutoBuyer)
|
|
1569
|
+
scheduleAtpAutoBuyForVerifiedMiss(miss, atpAutoBuyer);
|
|
1570
|
+
};
|
|
1571
|
+
const hubLink = resolveHubLink(process.env, ingestor, connectPublicHub, onVerifiedHubSearchMiss);
|
|
870
1572
|
const hubQuestionLink = resolveHubQuestionLink(process.env);
|
|
871
1573
|
const solidifyPermit = resolveSolidifyPermitGate(process.env);
|
|
872
1574
|
const strategyName = process.env['EVOLVE_STRATEGY'];
|
|
873
|
-
// Surface the cross-platform isolation gap ONCE: where unprivileged namespaces are unavailable (Windows/macOS),
|
|
874
|
-
// the sandbox verifier still hardens (metachar/node-eval reject, env scrub, timeout) but CANNOT cut network or
|
|
875
|
-
// hide home secrets — so a validation command there could phone home / read ~/.ssh. Don't let that be silent.
|
|
876
|
-
let warnedNoIsolation = false;
|
|
877
1575
|
const probationOn = geneProbationEnabled();
|
|
878
|
-
const
|
|
1576
|
+
const semanticIdfOn = semanticIdfEnabled();
|
|
1577
|
+
const selectionPolicy = selectionPolicyFromEnv();
|
|
1578
|
+
const selectionGuard = selectionGuardFromEnv();
|
|
1579
|
+
const selectionFloor = selectionFloorFromEnv();
|
|
1580
|
+
// File-only and best-effort: tracing must never fail or slow a task.
|
|
1581
|
+
const learningTrace = resolveLearningTrace(process.env);
|
|
1582
|
+
const deps = withAutoExecSelectionConfig({
|
|
879
1583
|
engine, store, provenance, review, personality: personalityStore, memoryGraph,
|
|
1584
|
+
...(learningTrace.config ? { learningTrace: learningTrace.config } : {}),
|
|
880
1585
|
// Probation (#306, gated, default OFF via EVOLVER_GENE_PROBATION): try unproven auto-distilled genes (with their
|
|
881
1586
|
// strategy embedded) so the cross-AI loop self-closes — contained by the proven exec gates + worktree isolation.
|
|
882
1587
|
...(probationOn ? { includeProbation: true } : {}),
|
|
1588
|
+
...(!semanticIdfOn ? { disableSemanticIdf: true } : {}),
|
|
883
1589
|
...(hubLink ? { hubReuse: hubLink.seam } : {}),
|
|
884
1590
|
...(solidifyPermit ? { solidifyPermit } : {}),
|
|
885
1591
|
...(strategyName !== undefined ? { strategyName } : {}),
|
|
@@ -888,17 +1594,13 @@ export async function runAutoExec(argv) {
|
|
|
888
1594
|
// different unit) so a long suite is not silently SIGKILL'd against the wrong budget.
|
|
889
1595
|
validate: (task) => async (_m, _d, cwd) => {
|
|
890
1596
|
const cmds = task.validationCmds ?? [];
|
|
891
|
-
const r = await
|
|
892
|
-
if (cmds.length > 0 && !r.isolated && !warnedNoIsolation) {
|
|
893
|
-
warnedNoIsolation = true;
|
|
894
|
-
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');
|
|
895
|
-
}
|
|
1597
|
+
const r = await runRequiredSandboxedValidation(cmds, cwd);
|
|
896
1598
|
const validationSummary = summarizeSandboxedValidation(r);
|
|
897
1599
|
if (validationSummary)
|
|
898
1600
|
process.stdout.write(` validation: ${validationSummary}\n`);
|
|
899
1601
|
return { passed: r.passed, score: r.score };
|
|
900
1602
|
},
|
|
901
|
-
};
|
|
1603
|
+
}, process.env);
|
|
902
1604
|
const safety = { allowedRoots: cfg.allowedRoots, timeoutMs: cfg.timeoutMs, runner: cfg.runner };
|
|
903
1605
|
// #268/#274 soft re-order — DEFAULT ON (kill switch: EVOLVER_REUSE_SIGNAL=0). Fold the latest cross-runtime reuse
|
|
904
1606
|
// outcomes + observed recall into selection as a SMALL, bounded, clamped nudge (±REUSE_WEIGHT); reuseSignalAb.test
|
|
@@ -920,7 +1622,7 @@ export async function runAutoExec(argv) {
|
|
|
920
1622
|
scheduleAutoExecHubSideEffects(task, v, { questions: hubQuestionLink, outcome: hubLink });
|
|
921
1623
|
return v;
|
|
922
1624
|
};
|
|
923
|
-
const guarded = exec.singleFlight((
|
|
1625
|
+
const guarded = exec.singleFlight(runnerBoundAutoExecPass(cfg.runner, dirs, runOne));
|
|
924
1626
|
// Auto-distill producer+consumer (#106): register the distillObserver on THIS bus, then a producer tick scans
|
|
925
1627
|
// the session dirs and records material on THIS Ingestor → material.batch_ready → observer drafts a quarantined
|
|
926
1628
|
// gene (A1) → human `review --approve` lifts it into inject/cursor (A2a/A2b). Off via EVOLVER_AUTO_DISTILL=0.
|
|
@@ -931,7 +1633,9 @@ export async function runAutoExec(argv) {
|
|
|
931
1633
|
const antiGeneDistill = resolveAutoDistillAntiGene(process.env, { store, review, ingestor });
|
|
932
1634
|
const transcriptDistill = resolveAutoDistillTranscript(process.env, { store, review, ingestor });
|
|
933
1635
|
const atpAutoDeliver = resolveAtpAutoDeliver(process.env);
|
|
934
|
-
|
|
1636
|
+
const uninstallBrokenPipeGuards = installAutoexecBrokenPipeGuards();
|
|
1637
|
+
const reuseEnabled = process.env['EVOLVER_REUSE_BEFORE_SOLVE'] === '1' && hubLink !== undefined;
|
|
1638
|
+
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})`}\n`);
|
|
935
1639
|
if (cfg.allowedRoots.length === 0)
|
|
936
1640
|
process.stdout.write(' (allowlist empty → deny-by-default: nothing runs until you add a repo to config.json)\n');
|
|
937
1641
|
// Single-instance lock (#106): a second daemon on the same home would double-process the queue. That is harmless
|
|
@@ -947,6 +1651,7 @@ export async function runAutoExec(argv) {
|
|
|
947
1651
|
}
|
|
948
1652
|
catch (error) {
|
|
949
1653
|
process.stderr.write(autoexecLockFailureMessage(error));
|
|
1654
|
+
uninstallBrokenPipeGuards();
|
|
950
1655
|
return 1;
|
|
951
1656
|
}
|
|
952
1657
|
// First-run auto-buyer opt-in (PORT v1 #10): introduce the autonomous spend path to interactive operators once,
|
|
@@ -963,6 +1668,15 @@ export async function runAutoExec(argv) {
|
|
|
963
1668
|
const uninstallUnhandledRejectionGuard = daemonNs.installUnhandledRejectionWindow({
|
|
964
1669
|
beforeExit: () => { releaseAutoexecLock(lockPath); },
|
|
965
1670
|
});
|
|
1671
|
+
let runtimeCleaned = false;
|
|
1672
|
+
const cleanupAutoexecRuntime = () => {
|
|
1673
|
+
if (runtimeCleaned)
|
|
1674
|
+
return;
|
|
1675
|
+
runtimeCleaned = true;
|
|
1676
|
+
uninstallUnhandledRejectionGuard();
|
|
1677
|
+
releaseAutoexecLock(lockPath);
|
|
1678
|
+
uninstallBrokenPipeGuards();
|
|
1679
|
+
};
|
|
966
1680
|
// Durable workflow recovery uses the same policy/review-gated runtime factory as `evolver workflow start/resume`.
|
|
967
1681
|
// Pass the already-loaded config so a custom autoexec home uses the same allowlist, runner, and validation profiles.
|
|
968
1682
|
initializeWorkflowStartupRecovery({ autoExecHome: home, autoExecConfig: cfg });
|
|
@@ -1048,7 +1762,7 @@ export async function runAutoExec(argv) {
|
|
|
1048
1762
|
process.stderr.write(`[Solo] 连续失败 ${soloState.consecutiveFailures} 次达阈值,熔断停机(非盲重生)。\n`);
|
|
1049
1763
|
// Stop scheduling, release the lock, and exit non-zero. Detached so we
|
|
1050
1764
|
// don't await our own loop.stop() from inside a tick.
|
|
1051
|
-
void loop.stop().then(() => {
|
|
1765
|
+
void loop.stop().then(() => { cleanupAutoexecRuntime(); process.exit(1); });
|
|
1052
1766
|
}
|
|
1053
1767
|
};
|
|
1054
1768
|
// Heartbeat (#106): record liveness + pacing on the AE spine for the WebUI console, THROTTLED so a fast poll does
|
|
@@ -1074,18 +1788,7 @@ export async function runAutoExec(argv) {
|
|
|
1074
1788
|
}).catch(() => { });
|
|
1075
1789
|
},
|
|
1076
1790
|
});
|
|
1077
|
-
//
|
|
1078
|
-
//
|
|
1079
|
-
return await
|
|
1080
|
-
let stopping = false;
|
|
1081
|
-
const shutdown = (sig) => {
|
|
1082
|
-
if (stopping)
|
|
1083
|
-
return;
|
|
1084
|
-
stopping = true;
|
|
1085
|
-
process.stdout.write(`\nevolver autoexec: ${sig} → graceful stop (finishing in-flight, releasing lock)\n`);
|
|
1086
|
-
void loop.stop().then(() => { uninstallUnhandledRejectionGuard(); releaseAutoexecLock(lockPath); resolve(0); });
|
|
1087
|
-
};
|
|
1088
|
-
process.once('SIGINT', () => shutdown('SIGINT'));
|
|
1089
|
-
process.once('SIGTERM', () => shutdown('SIGTERM'));
|
|
1090
|
-
});
|
|
1791
|
+
// SIGINT/SIGTERM drain the in-flight beat before cleanup. SIGHUP cannot hot-reload this composition safely,
|
|
1792
|
+
// so it is explicit and non-destructive: keep running until the operator performs a normal restart.
|
|
1793
|
+
return await waitForAutoexecShutdown({ stop: loop.stop, cleanup: cleanupAutoexecRuntime });
|
|
1091
1794
|
}
|