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