@evomap/evolver-cli 2.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/antiGeneBenchmark.d.ts +9 -0
- package/dist/antiGeneBenchmark.js +173 -0
- package/dist/antiGeneRollout.d.ts +14 -0
- package/dist/antiGeneRollout.js +276 -0
- package/dist/atp.d.ts +122 -0
- package/dist/atp.js +413 -0
- package/dist/atpAutoDeliver.d.ts +53 -0
- package/dist/atpAutoDeliver.js +197 -0
- package/dist/atpAutobuyPrompt.d.ts +48 -0
- package/dist/atpAutobuyPrompt.js +109 -0
- package/dist/autoDistillAntiGene.d.ts +63 -0
- package/dist/autoDistillAntiGene.js +396 -0
- package/dist/autoDistillLlm.d.ts +94 -0
- package/dist/autoDistillLlm.js +510 -0
- package/dist/autoDistillTranscript.d.ts +87 -0
- package/dist/autoDistillTranscript.js +364 -0
- package/dist/autoRecall.d.ts +25 -0
- package/dist/autoRecall.js +80 -0
- package/dist/autoexec.d.ts +237 -0
- package/dist/autoexec.js +1041 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +7 -0
- package/dist/cliContracts.d.ts +72 -0
- package/dist/cliContracts.js +815 -0
- package/dist/commands.d.ts +9 -0
- package/dist/commands.js +10 -0
- package/dist/cursorRewrite.d.ts +42 -0
- package/dist/cursorRewrite.js +65 -0
- package/dist/cycleConsumer.d.ts +42 -0
- package/dist/cycleConsumer.js +519 -0
- package/dist/daemonLoop.d.ts +33 -0
- package/dist/daemonLoop.js +72 -0
- package/dist/dispatch.d.ts +10 -0
- package/dist/dispatch.js +75 -0
- package/dist/distillObserver.d.ts +33 -0
- package/dist/distillObserver.js +146 -0
- package/dist/distillPrimitives.d.ts +48 -0
- package/dist/distillPrimitives.js +142 -0
- package/dist/doctor.d.ts +54 -0
- package/dist/doctor.js +931 -0
- package/dist/geneValue.d.ts +37 -0
- package/dist/geneValue.js +97 -0
- package/dist/index.d.ts +193 -0
- package/dist/index.js +1135 -0
- package/dist/lifecycle.d.ts +75 -0
- package/dist/lifecycle.js +859 -0
- package/dist/login.d.ts +10 -0
- package/dist/login.js +38 -0
- package/dist/migrate/divergenceAudit.d.ts +29 -0
- package/dist/migrate/divergenceAudit.js +37 -0
- package/dist/migrate/fieldMap.d.ts +18 -0
- package/dist/migrate/fieldMap.js +68 -0
- package/dist/migrate/v1Import.d.ts +16 -0
- package/dist/migrate/v1Import.js +118 -0
- package/dist/phub.d.ts +18 -0
- package/dist/phub.js +284 -0
- package/dist/recall.d.ts +26 -0
- package/dist/recall.js +162 -0
- package/dist/recipe.d.ts +61 -0
- package/dist/recipe.js +564 -0
- package/dist/reflectionObserver.d.ts +8 -0
- package/dist/reflectionObserver.js +6 -0
- package/dist/reuse.d.ts +48 -0
- package/dist/reuse.js +300 -0
- package/dist/reuseReport.d.ts +20 -0
- package/dist/reuseReport.js +255 -0
- package/dist/reviewFilter.d.ts +4 -0
- package/dist/reviewFilter.js +6 -0
- package/dist/runtimeSessionSource.d.ts +9 -0
- package/dist/runtimeSessionSource.js +29 -0
- package/dist/setupHooks.d.ts +2 -0
- package/dist/setupHooks.js +410 -0
- package/dist/skill2gep.d.ts +144 -0
- package/dist/skill2gep.js +321 -0
- package/dist/skillDistill.d.ts +75 -0
- package/dist/skillDistill.js +342 -0
- package/dist/solo/breaker.d.ts +14 -0
- package/dist/solo/breaker.js +21 -0
- package/dist/solo/gitGuard.d.ts +17 -0
- package/dist/solo/gitGuard.js +62 -0
- package/dist/solo/mode.d.ts +12 -0
- package/dist/solo/mode.js +55 -0
- package/dist/thesis.d.ts +43 -0
- package/dist/thesis.js +179 -0
- package/dist/trajectoryExport.d.ts +1 -0
- package/dist/trajectoryExport.js +895 -0
- package/dist/valueDigest.d.ts +33 -0
- package/dist/valueDigest.js +94 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +14 -0
- package/package.json +38 -0
package/dist/atp.js
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { events, mailbox } from '@evomap/evolver-core';
|
|
5
|
+
import { AtpHubClient, ATP_PROOF_STATUSES, ATP_ROLES, ATP_ROUTING_MODES, ATP_VERIFY_ACTIONS, ATP_VERIFY_MODES, connectPublicHub, globalFetchLike, } from '@evomap/evolver-adapter-public';
|
|
6
|
+
export function parseBuyArgs(args) {
|
|
7
|
+
if (args.length === 0)
|
|
8
|
+
return { ok: false, error: 'buy requires <capabilities>: comma-separated list (e.g. code_review,bug_fix)' };
|
|
9
|
+
const capabilitiesRaw = firstPositional(args);
|
|
10
|
+
if (!capabilitiesRaw)
|
|
11
|
+
return { ok: false, error: 'buy requires <capabilities>: comma-separated list' };
|
|
12
|
+
const capabilities = capabilitiesRaw.split(',').map((s) => s.trim()).filter(Boolean);
|
|
13
|
+
if (capabilities.length === 0)
|
|
14
|
+
return { ok: false, error: `no valid capabilities parsed from: ${capabilitiesRaw}` };
|
|
15
|
+
const budget = Math.max(1, Math.round(Number(parseNamed(args, '--budget', '-b')) || 10));
|
|
16
|
+
const routingMode = enumArg(parseNamed(args, '--routing') ?? 'fastest', ATP_ROUTING_MODES, '--routing');
|
|
17
|
+
if (!routingMode.ok)
|
|
18
|
+
return routingMode;
|
|
19
|
+
const verifyMode = enumArg(parseNamed(args, '--verify') ?? 'auto', ATP_VERIFY_MODES, '--verify');
|
|
20
|
+
if (!verifyMode.ok)
|
|
21
|
+
return verifyMode;
|
|
22
|
+
const timeoutRaw = parseNamed(args, '--timeout');
|
|
23
|
+
const timeoutMs = timeoutRaw ? Math.max(1000, Math.round(Number(timeoutRaw) * 1000)) : 300_000;
|
|
24
|
+
return {
|
|
25
|
+
ok: true,
|
|
26
|
+
opts: {
|
|
27
|
+
capabilities,
|
|
28
|
+
budget,
|
|
29
|
+
question: parseNamed(args, '--question', '-q') ?? '',
|
|
30
|
+
routingMode: routingMode.value,
|
|
31
|
+
verifyMode: verifyMode.value,
|
|
32
|
+
noWait: args.includes('--no-wait'),
|
|
33
|
+
timeoutMs,
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export function parseOrdersArgs(args) {
|
|
38
|
+
const role = enumArg(parseNamed(args, '--role') ?? 'consumer', ATP_ROLES, '--role');
|
|
39
|
+
if (!role.ok)
|
|
40
|
+
return role;
|
|
41
|
+
const statusRaw = parseNamed(args, '--status');
|
|
42
|
+
if (statusRaw !== null) {
|
|
43
|
+
const status = enumArg(statusRaw, ATP_PROOF_STATUSES, '--status');
|
|
44
|
+
if (!status.ok)
|
|
45
|
+
return status;
|
|
46
|
+
}
|
|
47
|
+
const limitRaw = parseNamed(args, '--limit');
|
|
48
|
+
const limit = limitRaw ? Math.max(1, Math.min(100, Math.round(Number(limitRaw)))) : 20;
|
|
49
|
+
return { ok: true, opts: { role: role.value, status: statusRaw, limit, jsonOut: args.includes('--json') } };
|
|
50
|
+
}
|
|
51
|
+
export function parseVerifyArgs(args) {
|
|
52
|
+
const orderId = firstPositional(args);
|
|
53
|
+
if (!orderId)
|
|
54
|
+
return { ok: false, error: 'verify requires <orderId>' };
|
|
55
|
+
const action = enumArg(parseNamed(args, '--action') ?? 'confirm', ATP_VERIFY_ACTIONS, '--action');
|
|
56
|
+
if (!action.ok)
|
|
57
|
+
return action;
|
|
58
|
+
return { ok: true, opts: { orderId, action: action.value } };
|
|
59
|
+
}
|
|
60
|
+
export function parseAtpArgs(args) {
|
|
61
|
+
const sub = firstPositional(args)?.toLowerCase();
|
|
62
|
+
if (sub !== 'enable' && sub !== 'disable' && sub !== 'status') {
|
|
63
|
+
return { ok: false, error: `atp subcommand must be enable|disable|status (got: ${sub ?? '-'})` };
|
|
64
|
+
}
|
|
65
|
+
return { ok: true, opts: { sub } };
|
|
66
|
+
}
|
|
67
|
+
export async function runBuy(opts, deps = {}) {
|
|
68
|
+
const client = deps.client ?? createAtpClientFromEnv(deps.env);
|
|
69
|
+
const log = deps.log ?? ((s) => process.stdout.write(`${s}\n`));
|
|
70
|
+
const err = deps.err ?? ((s) => process.stderr.write(`${s}\n`));
|
|
71
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
72
|
+
log(`[ATP] Placing order: capabilities=${opts.capabilities.join(',')} budget=${opts.budget} mode=${opts.routingMode}`);
|
|
73
|
+
try {
|
|
74
|
+
// Manual `buy` is explicit consent, but it STILL goes through the single enforced gate (#177) so the spend
|
|
75
|
+
// path is the same chokepoint a future autonomous caller must use (and be gated by recorded consent).
|
|
76
|
+
const order = await placeAtpOrderWithConsent(client, {
|
|
77
|
+
capabilities: opts.capabilities,
|
|
78
|
+
budget: opts.budget,
|
|
79
|
+
routingMode: opts.routingMode,
|
|
80
|
+
verifyMode: opts.verifyMode,
|
|
81
|
+
question: opts.question,
|
|
82
|
+
}, { explicit: true, ...(deps.env ? { env: deps.env } : {}), ...(deps.consentPath ? { consentPath: deps.consentPath } : {}) });
|
|
83
|
+
if (!order.ok) {
|
|
84
|
+
err(`[ATP] Order failed: ${order.error ?? 'unknown'}`);
|
|
85
|
+
return { exitCode: 1, data: order };
|
|
86
|
+
}
|
|
87
|
+
const orderId = orderIdFrom(order.data);
|
|
88
|
+
log(`[ATP] Order placed: ${orderId ?? '(id pending)'}`);
|
|
89
|
+
if (opts.noWait || !orderId)
|
|
90
|
+
return { exitCode: 0, data: order.data };
|
|
91
|
+
const deadline = Date.now() + opts.timeoutMs;
|
|
92
|
+
while (Date.now() < deadline) {
|
|
93
|
+
await sleep(opts.pollIntervalMs ?? 10_000);
|
|
94
|
+
const status = await client.getOrderStatus(orderId);
|
|
95
|
+
if (!status.ok)
|
|
96
|
+
continue;
|
|
97
|
+
const proofStatus = proofStatusFrom(status.data);
|
|
98
|
+
if (proofStatus === 'settled' || (proofStatus === 'verified' && opts.verifyMode === 'auto')) {
|
|
99
|
+
log(`[ATP] Order settled: ${orderId}`);
|
|
100
|
+
return { exitCode: 0, data: { order: order.data, finalStatus: status.data } };
|
|
101
|
+
}
|
|
102
|
+
if (proofStatus === 'disputed') {
|
|
103
|
+
err(`[ATP] Order lifecycle failed: order_disputed`);
|
|
104
|
+
return { exitCode: 1, data: { order: order.data, finalStatus: status.data }, error: 'order_disputed' };
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
err('[ATP] Order lifecycle failed: order_timeout');
|
|
108
|
+
return { exitCode: 1, data: order.data, error: 'order_timeout' };
|
|
109
|
+
}
|
|
110
|
+
catch (e) {
|
|
111
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
112
|
+
err(`[ATP] buy error: ${msg}`);
|
|
113
|
+
return { exitCode: 1, error: msg };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
export async function runOrders(opts, deps = {}) {
|
|
117
|
+
const client = deps.client ?? createAtpClientFromEnv(deps.env);
|
|
118
|
+
const log = deps.log ?? ((s) => process.stdout.write(`${s}\n`));
|
|
119
|
+
const err = deps.err ?? ((s) => process.stderr.write(`${s}\n`));
|
|
120
|
+
try {
|
|
121
|
+
const query = { role: opts.role, limit: opts.limit };
|
|
122
|
+
if (opts.status !== null)
|
|
123
|
+
query.status = opts.status;
|
|
124
|
+
const result = await client.listProofs(query);
|
|
125
|
+
if (!result.ok) {
|
|
126
|
+
err(`[ATP] listProofs failed: ${result.error ?? 'unknown'}`);
|
|
127
|
+
return { exitCode: 1, data: result };
|
|
128
|
+
}
|
|
129
|
+
const proofs = proofsFrom(result.data);
|
|
130
|
+
if (opts.jsonOut) {
|
|
131
|
+
log(JSON.stringify(proofs, null, 2));
|
|
132
|
+
return { exitCode: 0, data: proofs };
|
|
133
|
+
}
|
|
134
|
+
if (proofs.length === 0) {
|
|
135
|
+
log(`[ATP] No orders found for role=${opts.role}${opts.status ? ` status=${opts.status}` : ''}`);
|
|
136
|
+
return { exitCode: 0, data: [] };
|
|
137
|
+
}
|
|
138
|
+
log(`[ATP] Showing ${proofs.length} order(s):`);
|
|
139
|
+
for (const p of proofs) {
|
|
140
|
+
const row = asRecord(p);
|
|
141
|
+
const id = row?.['taskId'] ?? row?.['order_id'] ?? row?.['id'] ?? '(unknown)';
|
|
142
|
+
const status = row?.['status'] ?? row?.['proof_status'] ?? 'unknown';
|
|
143
|
+
const when = row?.['createdAt'] ?? row?.['created_at'] ?? 'unknown';
|
|
144
|
+
log(` - ${String(id)} | status=${String(status)} | created=${String(when)}`);
|
|
145
|
+
}
|
|
146
|
+
return { exitCode: 0, data: proofs };
|
|
147
|
+
}
|
|
148
|
+
catch (e) {
|
|
149
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
150
|
+
err(`[ATP] orders error: ${msg}`);
|
|
151
|
+
return { exitCode: 1, error: msg };
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
export async function runVerify(opts, deps = {}) {
|
|
155
|
+
const client = deps.client ?? createAtpClientFromEnv(deps.env);
|
|
156
|
+
const log = deps.log ?? ((s) => process.stdout.write(`${s}\n`));
|
|
157
|
+
const err = deps.err ?? ((s) => process.stderr.write(`${s}\n`));
|
|
158
|
+
try {
|
|
159
|
+
const result = await client.verifyDelivery(opts.orderId, opts.action);
|
|
160
|
+
if (!result.ok) {
|
|
161
|
+
err(`[ATP] verify failed: ${result.error ?? 'unknown'}`);
|
|
162
|
+
return { exitCode: 1, data: result };
|
|
163
|
+
}
|
|
164
|
+
log(`[ATP] verify ok (${opts.action}): ${JSON.stringify(result.data ?? {})}`);
|
|
165
|
+
return { exitCode: 0, data: result.data };
|
|
166
|
+
}
|
|
167
|
+
catch (e) {
|
|
168
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
169
|
+
err(`[ATP] verify error: ${msg}`);
|
|
170
|
+
return { exitCode: 1, error: msg };
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
export async function runAtp(opts, deps = {}) {
|
|
174
|
+
const env = deps.env ?? process.env;
|
|
175
|
+
const log = deps.log ?? ((s) => process.stdout.write(`${s}\n`));
|
|
176
|
+
const err = deps.err ?? ((s) => process.stderr.write(`${s}\n`));
|
|
177
|
+
const ackPath = deps.consentPath ?? atpConsentPath(env);
|
|
178
|
+
try {
|
|
179
|
+
if (opts.sub === 'status') {
|
|
180
|
+
const consent = getAtpConsent(env, ackPath);
|
|
181
|
+
log(`[ATP] auto-spend: ${consent.enabled ? 'ENABLED' : 'DISABLED'} (source: ${consent.source})`);
|
|
182
|
+
log(` ack file: ${consent.ackPath}`);
|
|
183
|
+
return { exitCode: 0, data: consent };
|
|
184
|
+
}
|
|
185
|
+
const enabled = opts.sub === 'enable';
|
|
186
|
+
const body = setAtpConsent(enabled, ackPath, deps.now ?? (() => new Date()));
|
|
187
|
+
log(`[ATP] auto-spend ${enabled ? 'ENABLED' : 'DISABLED'} (consent recorded ${body.acknowledged_at}).`);
|
|
188
|
+
log(' Manual `evolver buy` orders are unaffected; this ack is for future auto-buyer wiring.');
|
|
189
|
+
const override = envOverride(env);
|
|
190
|
+
if (override !== null && override !== enabled) {
|
|
191
|
+
const label = override ? 'on' : 'off';
|
|
192
|
+
log('');
|
|
193
|
+
log(`[ATP] WARNING: EVOLVER_ATP_AUTOBUY=${env['EVOLVER_ATP_AUTOBUY']} is set and will OVERRIDE the ack file at runtime.`);
|
|
194
|
+
return { exitCode: 0, data: body, envOverride: label };
|
|
195
|
+
}
|
|
196
|
+
return { exitCode: 0, data: body };
|
|
197
|
+
}
|
|
198
|
+
catch (e) {
|
|
199
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
200
|
+
err(`[ATP] atp command error: ${msg}`);
|
|
201
|
+
return { exitCode: 1, error: msg };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
export async function runBuyCommand(argv) {
|
|
205
|
+
const parsed = parseBuyArgs(argv);
|
|
206
|
+
if (!parsed.ok)
|
|
207
|
+
return usageError(parsed.error);
|
|
208
|
+
return (await runBuy(parsed.opts)).exitCode;
|
|
209
|
+
}
|
|
210
|
+
export async function runOrdersCommand(argv) {
|
|
211
|
+
const parsed = parseOrdersArgs(argv);
|
|
212
|
+
if (!parsed.ok)
|
|
213
|
+
return usageError(parsed.error);
|
|
214
|
+
return (await runOrders(parsed.opts)).exitCode;
|
|
215
|
+
}
|
|
216
|
+
export async function runVerifyCommand(argv) {
|
|
217
|
+
const parsed = parseVerifyArgs(argv);
|
|
218
|
+
if (!parsed.ok)
|
|
219
|
+
return usageError(parsed.error);
|
|
220
|
+
return (await runVerify(parsed.opts)).exitCode;
|
|
221
|
+
}
|
|
222
|
+
export async function runAtpCommand(argv) {
|
|
223
|
+
const parsed = parseAtpArgs(argv);
|
|
224
|
+
if (!parsed.ok)
|
|
225
|
+
return usageError(parsed.error);
|
|
226
|
+
return (await runAtp(parsed.opts)).exitCode;
|
|
227
|
+
}
|
|
228
|
+
export function createAtpClientFromEnv(env = process.env) {
|
|
229
|
+
const hubUrl = env['EVOMAP_HUB_URL'] ?? 'https://evomap.ai';
|
|
230
|
+
const evomapDir = resolveAtpHome(env);
|
|
231
|
+
const resolvedSenderId = resolveAtpSenderId(env);
|
|
232
|
+
const senderId = () => resolvedSenderId;
|
|
233
|
+
const nodeSecret = env['EVOMAP_NODE_SECRET']?.trim();
|
|
234
|
+
const connected = nodeSecret
|
|
235
|
+
? connectPublicHub({ hubUrl, authMode: 'legacy', evomapDir, nodeSecret, senderId })
|
|
236
|
+
: connectPublicHub({ hubUrl, authMode: 'oauth', evomapDir, senderId });
|
|
237
|
+
return new AtpHubClient({ baseUrl: hubUrl, auth: connected.auth, fetchFn: globalFetchLike, senderId });
|
|
238
|
+
}
|
|
239
|
+
export function resolveAtpHome(env = process.env) {
|
|
240
|
+
return env['EVOMAP_DIR'] ?? env['EVOLVER_HOME'] ?? env['EVOMAP_HOME'] ?? events.evomapHome();
|
|
241
|
+
}
|
|
242
|
+
export function atpConsentPath(env = process.env) {
|
|
243
|
+
return join(resolveAtpHome(env), 'evolution', 'atp-autobuy-ack.json');
|
|
244
|
+
}
|
|
245
|
+
export function getAtpConsent(env = process.env, ackPath = atpConsentPath(env)) {
|
|
246
|
+
const override = envOverride(env);
|
|
247
|
+
if (override !== null)
|
|
248
|
+
return { enabled: override, source: 'env', ackPath };
|
|
249
|
+
const ack = readAck(ackPath);
|
|
250
|
+
if (ack)
|
|
251
|
+
return { enabled: ack.enabled, source: 'ack', ackPath };
|
|
252
|
+
return { enabled: false, source: 'default', ackPath };
|
|
253
|
+
}
|
|
254
|
+
/** Thrown when an autonomous (non-explicit) spend is attempted without recorded/enabled auto-spend consent (#177). */
|
|
255
|
+
export class AtpSpendConsentError extends Error {
|
|
256
|
+
source;
|
|
257
|
+
constructor(source) {
|
|
258
|
+
super(`autonomous ATP spend refused: auto-spend consent is disabled (source: ${source}) — run \`evolver atp enable\` (or set the consent env) before any autonomous spending path`);
|
|
259
|
+
this.source = source;
|
|
260
|
+
this.name = 'AtpSpendConsentError';
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* THE single enforced consent gate every ATP spend path MUST pass through (#177). One door, two callers:
|
|
265
|
+
* - explicit (a human ran `evolver buy`) → the invocation IS the consent, allowed through.
|
|
266
|
+
* - autonomous (future auto-buy / autoexec auto-order / swarm purchase) → must have getAtpConsent().enabled,
|
|
267
|
+
* else refused. This keeps consent enforcement UPSTREAM of money movement instead of a read-only status bit
|
|
268
|
+
* each caller might forget to check (the latent money-safety hole autogame-17 flagged). Any new autonomous
|
|
269
|
+
* spending path is required to call this (NOT client.placeOrder directly) — see placeAtpOrderWithConsent.
|
|
270
|
+
*/
|
|
271
|
+
export function assertAtpSpendConsent(opts = {}) {
|
|
272
|
+
if (opts.explicit)
|
|
273
|
+
return; // a human explicitly invoked the spend → explicit consent (still through this door)
|
|
274
|
+
const env = opts.env ?? process.env;
|
|
275
|
+
const consent = getAtpConsent(env, opts.consentPath ?? atpConsentPath(env));
|
|
276
|
+
if (!consent.enabled)
|
|
277
|
+
throw new AtpSpendConsentError(consent.source);
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Place an ATP order through the enforced consent gate (#177) — the composition layer money movement goes
|
|
281
|
+
* through so consent can't be bypassed. Manual `buy` passes explicit:true; an autonomous caller omits it and is
|
|
282
|
+
* gated by recorded/env consent. Throws AtpSpendConsentError before any order is placed when refused.
|
|
283
|
+
*/
|
|
284
|
+
export async function placeAtpOrderWithConsent(client, order, consent = {}) {
|
|
285
|
+
assertAtpSpendConsent(consent); // throws AtpSpendConsentError → a rejected promise (async), before any spend
|
|
286
|
+
return client.placeOrder(order);
|
|
287
|
+
}
|
|
288
|
+
export function setAtpConsent(enabled, ackPath = atpConsentPath(), now = () => new Date()) {
|
|
289
|
+
const body = { enabled, acknowledged_at: now().toISOString(), version: 1 };
|
|
290
|
+
mkdirSync(dirname(ackPath), { recursive: true });
|
|
291
|
+
const tmp = `${ackPath}.tmp`;
|
|
292
|
+
writeFileSync(tmp, JSON.stringify(body, null, 2));
|
|
293
|
+
renameSync(tmp, ackPath);
|
|
294
|
+
return body;
|
|
295
|
+
}
|
|
296
|
+
export function resolveAtpSenderId(env = process.env) {
|
|
297
|
+
const direct = env['EVOMAP_NODE_ID']?.trim();
|
|
298
|
+
if (direct)
|
|
299
|
+
return direct;
|
|
300
|
+
for (const p of proxyStoreCandidates(env)) {
|
|
301
|
+
if (!existsSync(p))
|
|
302
|
+
continue;
|
|
303
|
+
try {
|
|
304
|
+
const store = new mailbox.MailboxStore({ path: p });
|
|
305
|
+
const nodeId = store.getState('node_id');
|
|
306
|
+
store.close();
|
|
307
|
+
if (nodeId)
|
|
308
|
+
return nodeId;
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
// Best effort only: a corrupt or locked proxy store must not prevent manual ATP commands.
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return undefined;
|
|
315
|
+
}
|
|
316
|
+
export function printAtpUsage() {
|
|
317
|
+
return [
|
|
318
|
+
'ATP subcommands:',
|
|
319
|
+
` evolver buy <caps> [--budget=N] [--question "..."] [--routing=${ATP_ROUTING_MODES.join('|')}]`,
|
|
320
|
+
` [--verify=${ATP_VERIFY_MODES.join('|')}] [--no-wait] [--timeout=<seconds>]`,
|
|
321
|
+
` evolver orders [--role=${ATP_ROLES.join('|')}] [--status=${ATP_PROOF_STATUSES.join('|')}]`,
|
|
322
|
+
' [--limit=N] [--json]',
|
|
323
|
+
` evolver verify <orderId> [--action=${ATP_VERIFY_ACTIONS.join('|')}]`,
|
|
324
|
+
' evolver atp <enable|disable|status> -- manage auto-spend consent',
|
|
325
|
+
].join('\n');
|
|
326
|
+
}
|
|
327
|
+
function parseNamed(args, longFlag, shortFlag) {
|
|
328
|
+
const flags = shortFlag ? [longFlag, shortFlag] : [longFlag];
|
|
329
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
330
|
+
const token = args[i];
|
|
331
|
+
if (token === undefined)
|
|
332
|
+
continue;
|
|
333
|
+
for (const flag of flags) {
|
|
334
|
+
if (token === flag) {
|
|
335
|
+
const next = args[i + 1];
|
|
336
|
+
return next && !next.startsWith('--') ? next : null;
|
|
337
|
+
}
|
|
338
|
+
if (token.startsWith(`${flag}=`))
|
|
339
|
+
return token.slice(flag.length + 1);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return null;
|
|
343
|
+
}
|
|
344
|
+
function firstPositional(args) {
|
|
345
|
+
return args.find((a) => typeof a === 'string' && !a.startsWith('--')) ?? null;
|
|
346
|
+
}
|
|
347
|
+
function enumArg(value, allowed, flag) {
|
|
348
|
+
if (allowed.includes(value))
|
|
349
|
+
return { ok: true, value: value };
|
|
350
|
+
return { ok: false, error: `invalid ${flag}: ${value} (expected ${allowed.join('|')})` };
|
|
351
|
+
}
|
|
352
|
+
function usageError(msg) {
|
|
353
|
+
process.stderr.write(`${msg}\n${printAtpUsage()}\n`);
|
|
354
|
+
return 1;
|
|
355
|
+
}
|
|
356
|
+
function orderIdFrom(value) {
|
|
357
|
+
const rec = asRecord(value);
|
|
358
|
+
const raw = rec?.['order_id'] ?? rec?.['orderId'] ?? rec?.['id'];
|
|
359
|
+
return typeof raw === 'string' && raw.length > 0 ? raw : undefined;
|
|
360
|
+
}
|
|
361
|
+
function proofStatusFrom(value) {
|
|
362
|
+
const rec = asRecord(value);
|
|
363
|
+
const raw = rec?.['proof_status'] ?? rec?.['status'];
|
|
364
|
+
return typeof raw === 'string' ? raw : undefined;
|
|
365
|
+
}
|
|
366
|
+
function proofsFrom(value) {
|
|
367
|
+
if (Array.isArray(value))
|
|
368
|
+
return value;
|
|
369
|
+
const rec = asRecord(value);
|
|
370
|
+
const proofs = rec?.['proofs'] ?? rec?.['orders'] ?? rec?.['results'];
|
|
371
|
+
return Array.isArray(proofs) ? proofs : [];
|
|
372
|
+
}
|
|
373
|
+
function asRecord(value) {
|
|
374
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
375
|
+
}
|
|
376
|
+
function readAck(path) {
|
|
377
|
+
try {
|
|
378
|
+
if (!existsSync(path))
|
|
379
|
+
return null;
|
|
380
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
381
|
+
const rec = asRecord(parsed);
|
|
382
|
+
return typeof rec?.['enabled'] === 'boolean' ? { enabled: rec['enabled'] } : null;
|
|
383
|
+
}
|
|
384
|
+
catch {
|
|
385
|
+
return null;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
// Allowlist-to-ENABLE on a money/spend gate: this toggles AUTONOMOUS spending, so only an explicit enable value
|
|
389
|
+
// turns it on. The old denylist ("anything not off/0/false = enabled") fail-OPENed on ambiguous values — e.g.
|
|
390
|
+
// EVOLVER_ATP_AUTOBUY=no / disable / disabled / n all enabled auto-spend, the opposite of the operator's intent.
|
|
391
|
+
// Unrecognized values now fail CLOSED (not enabled) rather than green-light spending on a typo.
|
|
392
|
+
function envOverride(env) {
|
|
393
|
+
const raw = env['EVOLVER_ATP_AUTOBUY'];
|
|
394
|
+
if (typeof raw !== 'string')
|
|
395
|
+
return null;
|
|
396
|
+
const s = raw.trim().toLowerCase();
|
|
397
|
+
if (!s)
|
|
398
|
+
return null;
|
|
399
|
+
if (s === 'on' || s === '1' || s === 'true' || s === 'yes' || s === 'enable' || s === 'enabled')
|
|
400
|
+
return true;
|
|
401
|
+
if (s === 'off' || s === '0' || s === 'false' || s === 'no' || s === 'disable' || s === 'disabled' || s === 'none')
|
|
402
|
+
return false;
|
|
403
|
+
return false; // ambiguous value on a spend gate → fail closed (never auto-enable spending on an unexpected/typo value)
|
|
404
|
+
}
|
|
405
|
+
function proxyStoreCandidates(env) {
|
|
406
|
+
const home = resolveAtpHome(env);
|
|
407
|
+
const candidates = [
|
|
408
|
+
env['EVOLVER_PROXY_STORE'],
|
|
409
|
+
join(home, 'proxy', 'mailbox.db'),
|
|
410
|
+
join(env['HOME'] ?? homedir(), '.evomap', 'proxy', 'mailbox.db'),
|
|
411
|
+
].filter((x) => typeof x === 'string' && x.length > 0);
|
|
412
|
+
return [...new Set(candidates)];
|
|
413
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { type AtpResult } from '@evomap/evolver-adapter-public';
|
|
2
|
+
type LogFn = (line: string) => void;
|
|
3
|
+
export declare const ATP_AUTODELIVER_DEFAULT_POLL_MS = 60000;
|
|
4
|
+
export declare const ATP_AUTODELIVER_MIN_POLL_MS = 15000;
|
|
5
|
+
export declare const ATP_AUTODELIVER_LEDGER_FILENAME = "atp-autodeliver-ledger.json";
|
|
6
|
+
export declare const ATP_AUTODELIVER_LEDGER_MAX_ENTRIES = 500;
|
|
7
|
+
export declare const ATP_AUTODELIVER_COOLDOWN_BASE_MS: number;
|
|
8
|
+
export declare const ATP_AUTODELIVER_COOLDOWN_CAP_MS: number;
|
|
9
|
+
export interface AtpAutoDeliverClient {
|
|
10
|
+
listMyTasks(limit?: number, nodeId?: string): Promise<AtpResult>;
|
|
11
|
+
submitDelivery(orderId: string, proofPayload?: unknown): Promise<AtpResult>;
|
|
12
|
+
}
|
|
13
|
+
export interface AtpAutoDeliverLedger {
|
|
14
|
+
version: 2;
|
|
15
|
+
/** orderId → epoch ms. positive = delivered-at; negative = terminal-failed-at. Either ⇒ skip forever. */
|
|
16
|
+
submitted: Record<string, number>;
|
|
17
|
+
/** orderId → epoch ms before which we must NOT retry (429 cooldown backoff). Cleared on success/terminal. */
|
|
18
|
+
retryAfter: Record<string, number>;
|
|
19
|
+
/** orderId → consecutive 429 count, drives the exponential backoff. Cleared on success/terminal. */
|
|
20
|
+
cooldownHits: Record<string, number>;
|
|
21
|
+
}
|
|
22
|
+
export interface AtpAutoDeliverTickResult {
|
|
23
|
+
checked: number;
|
|
24
|
+
delivered: number;
|
|
25
|
+
skippedTasks: number;
|
|
26
|
+
terminalFailures: number;
|
|
27
|
+
transientFailures: number;
|
|
28
|
+
/** 429 rate-limit hits this tick — backed off (a subset of "failed", tracked apart for observability). */
|
|
29
|
+
cooldownFailures: number;
|
|
30
|
+
}
|
|
31
|
+
export interface AtpAutoDeliverDeps {
|
|
32
|
+
client?: AtpAutoDeliverClient;
|
|
33
|
+
createClient?: (env: NodeJS.ProcessEnv) => AtpAutoDeliverClient;
|
|
34
|
+
env?: NodeJS.ProcessEnv;
|
|
35
|
+
ledgerPath?: string;
|
|
36
|
+
nowMs?: () => number;
|
|
37
|
+
nowDate?: () => Date;
|
|
38
|
+
log?: LogFn;
|
|
39
|
+
limit?: number;
|
|
40
|
+
}
|
|
41
|
+
export interface AtpAutoDeliverWiring {
|
|
42
|
+
enabled: boolean;
|
|
43
|
+
reason?: 'off' | 'client_error';
|
|
44
|
+
tick: () => Promise<AtpAutoDeliverTickResult>;
|
|
45
|
+
}
|
|
46
|
+
export declare function isAtpAutoDeliverEnabled(env?: NodeJS.ProcessEnv): boolean;
|
|
47
|
+
export declare function atpAutoDeliverLedgerPath(env?: NodeJS.ProcessEnv): string;
|
|
48
|
+
export declare function resolveAtpAutoDeliver(env?: NodeJS.ProcessEnv, deps?: Omit<AtpAutoDeliverDeps, 'env'>): AtpAutoDeliverWiring;
|
|
49
|
+
export declare function runAtpAutoDeliverTick(deps?: AtpAutoDeliverDeps): Promise<AtpAutoDeliverTickResult>;
|
|
50
|
+
export declare function readAtpAutoDeliverLedger(path: string): AtpAutoDeliverLedger;
|
|
51
|
+
export declare function writeAtpAutoDeliverLedger(path: string, ledger: AtpAutoDeliverLedger): void;
|
|
52
|
+
export declare function buildAtpAutoDeliverProofPayload(task: Record<string, unknown>, nowDate?: () => Date): Record<string, unknown>;
|
|
53
|
+
export {};
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { atpRetryClass } from '@evomap/evolver-adapter-public';
|
|
4
|
+
import { createAtpClientFromEnv, resolveAtpHome } from './atp.js';
|
|
5
|
+
export const ATP_AUTODELIVER_DEFAULT_POLL_MS = 60_000;
|
|
6
|
+
export const ATP_AUTODELIVER_MIN_POLL_MS = 15_000;
|
|
7
|
+
export const ATP_AUTODELIVER_LEDGER_FILENAME = 'atp-autodeliver-ledger.json';
|
|
8
|
+
export const ATP_AUTODELIVER_LEDGER_MAX_ENTRIES = 500;
|
|
9
|
+
// Cooldown backoff for a 429 (hub rate-limit). Exponential per consecutive 429 on the same order so we back off
|
|
10
|
+
// well beyond the cooldown window instead of re-submitting every tick (money-safety #177): base doubles each hit,
|
|
11
|
+
// capped. The first 429 waits BASE; subsequent ones BASE*2^(hits-1) up to CAP.
|
|
12
|
+
export const ATP_AUTODELIVER_COOLDOWN_BASE_MS = 5 * 60_000; // 5 min
|
|
13
|
+
export const ATP_AUTODELIVER_COOLDOWN_CAP_MS = 6 * 60 * 60_000; // 6 h
|
|
14
|
+
const EMPTY_TICK = { checked: 0, delivered: 0, skippedTasks: 0, terminalFailures: 0, transientFailures: 0, cooldownFailures: 0 };
|
|
15
|
+
export function isAtpAutoDeliverEnabled(env = process.env) {
|
|
16
|
+
const raw = (env['EVOLVER_ATP_AUTODELIVER'] ?? 'on').toLowerCase().trim();
|
|
17
|
+
return raw !== 'off' && raw !== '0' && raw !== 'false';
|
|
18
|
+
}
|
|
19
|
+
export function atpAutoDeliverLedgerPath(env = process.env) {
|
|
20
|
+
return join(resolveAtpHome(env), 'evolution', ATP_AUTODELIVER_LEDGER_FILENAME);
|
|
21
|
+
}
|
|
22
|
+
export function resolveAtpAutoDeliver(env = process.env, deps = {}) {
|
|
23
|
+
if (!isAtpAutoDeliverEnabled(env))
|
|
24
|
+
return { enabled: false, reason: 'off', tick: async () => EMPTY_TICK };
|
|
25
|
+
let client;
|
|
26
|
+
try {
|
|
27
|
+
client = deps.client ?? (deps.createClient ?? createAtpClientFromEnv)(env);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return { enabled: false, reason: 'client_error', tick: async () => EMPTY_TICK };
|
|
31
|
+
}
|
|
32
|
+
return { enabled: true, tick: () => runAtpAutoDeliverTick({ ...deps, client, env }) };
|
|
33
|
+
}
|
|
34
|
+
export async function runAtpAutoDeliverTick(deps = {}) {
|
|
35
|
+
const env = deps.env ?? process.env;
|
|
36
|
+
const client = deps.client ?? (deps.createClient ?? createAtpClientFromEnv)(env);
|
|
37
|
+
const ledgerPath = deps.ledgerPath ?? atpAutoDeliverLedgerPath(env);
|
|
38
|
+
const nowMs = deps.nowMs ?? (() => Date.now());
|
|
39
|
+
const log = deps.log ?? (() => { });
|
|
40
|
+
const out = { ...EMPTY_TICK };
|
|
41
|
+
try {
|
|
42
|
+
const listed = await client.listMyTasks(deps.limit ?? 20);
|
|
43
|
+
if (!listed.ok)
|
|
44
|
+
return out;
|
|
45
|
+
const tasks = tasksFrom(listed.data);
|
|
46
|
+
out.checked = tasks.length;
|
|
47
|
+
if (tasks.length === 0)
|
|
48
|
+
return out;
|
|
49
|
+
const ledger = readAtpAutoDeliverLedger(ledgerPath);
|
|
50
|
+
let wroteLedger = false;
|
|
51
|
+
for (const task of tasks) {
|
|
52
|
+
const orderId = taskString(task, 'atp_order_id') ?? taskString(task, 'order_id');
|
|
53
|
+
if (!orderId) {
|
|
54
|
+
out.skippedTasks += 1;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (ledger.submitted[orderId]) {
|
|
58
|
+
out.skippedTasks += 1;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
// Still inside a 429 backoff window → skip this tick (do NOT hit the economic endpoint, #177).
|
|
62
|
+
const retryAfter = ledger.retryAfter[orderId];
|
|
63
|
+
if (retryAfter && nowMs() < retryAfter) {
|
|
64
|
+
out.skippedTasks += 1;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (!taskString(task, 'result_asset_id') && !taskString(task, 'resultAssetId')) {
|
|
68
|
+
out.skippedTasks += 1;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
const status = taskString(task, 'status') ?? taskString(task, 'task_status');
|
|
72
|
+
if (status && status !== 'claimed' && status !== 'completed') {
|
|
73
|
+
out.skippedTasks += 1;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const resp = await client.submitDelivery(orderId, buildAtpAutoDeliverProofPayload(task, deps.nowDate));
|
|
77
|
+
if (resp.ok) {
|
|
78
|
+
ledger.submitted[orderId] = nowMs();
|
|
79
|
+
delete ledger.retryAfter[orderId]; // a prior cooldown cleared
|
|
80
|
+
delete ledger.cooldownHits[orderId];
|
|
81
|
+
wroteLedger = true;
|
|
82
|
+
out.delivered += 1;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
// Retry policy comes from the SHARED classifier (adapter-public atpRetryClass) so publish and auto-deliver
|
|
86
|
+
// can't drift on what each status means (#177 root cause). permanent = NO retry ever helps (the proof is
|
|
87
|
+
// structurally dead); cooldown = the hub is rate-limiting (429), so back off exponentially instead of
|
|
88
|
+
// re-submitting every tick (money-safety: stop hammering the economic endpoint AND honor the cooldown);
|
|
89
|
+
// recoverable = environment-recoverable (402 credit / 403 rebind / 5xx), retry next tick is correct.
|
|
90
|
+
const cls = atpRetryClass(resp.status ?? 0);
|
|
91
|
+
if (cls === 'permanent') {
|
|
92
|
+
ledger.submitted[orderId] = -nowMs();
|
|
93
|
+
delete ledger.retryAfter[orderId];
|
|
94
|
+
delete ledger.cooldownHits[orderId];
|
|
95
|
+
wroteLedger = true;
|
|
96
|
+
out.terminalFailures += 1;
|
|
97
|
+
}
|
|
98
|
+
else if (cls === 'cooldown') {
|
|
99
|
+
const hits = (ledger.cooldownHits[orderId] ?? 0) + 1;
|
|
100
|
+
const backoff = Math.min(ATP_AUTODELIVER_COOLDOWN_BASE_MS * 2 ** (hits - 1), ATP_AUTODELIVER_COOLDOWN_CAP_MS);
|
|
101
|
+
ledger.cooldownHits[orderId] = hits;
|
|
102
|
+
ledger.retryAfter[orderId] = nowMs() + backoff;
|
|
103
|
+
wroteLedger = true;
|
|
104
|
+
out.cooldownFailures += 1;
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
out.transientFailures += 1; // recoverable: retry next tick (operator fixes credit/rebind); no ledger write
|
|
108
|
+
}
|
|
109
|
+
log(`[ATP-AutoDeliver] Delivery failed order=${orderId} status=${resp.status ?? 'n/a'} class=${cls} err=${String(resp.error ?? 'unknown_error').slice(0, 120)}`);
|
|
110
|
+
}
|
|
111
|
+
if (wroteLedger)
|
|
112
|
+
writeAtpAutoDeliverLedger(ledgerPath, ledger);
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
117
|
+
log(`[ATP-AutoDeliver] Tick threw (non-fatal): ${msg}`);
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
export function readAtpAutoDeliverLedger(path) {
|
|
122
|
+
try {
|
|
123
|
+
if (!existsSync(path))
|
|
124
|
+
return emptyLedger();
|
|
125
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
126
|
+
const rec = asRecord(parsed);
|
|
127
|
+
const submitted = asRecord(rec?.['submitted']);
|
|
128
|
+
if (!submitted)
|
|
129
|
+
return emptyLedger();
|
|
130
|
+
// retryAfter/cooldownHits are v2 fields — a v1 ledger lacks them, so default to empty (back-compat).
|
|
131
|
+
return { version: 2, submitted: cleanNumberMap(submitted), retryAfter: cleanNumberMap(asRecord(rec?.['retryAfter'])), cooldownHits: cleanNumberMap(asRecord(rec?.['cooldownHits'])) };
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return emptyLedger();
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** Keep only finite-number entries from an unknown record (corrupt/non-number values dropped). */
|
|
138
|
+
function cleanNumberMap(rec) {
|
|
139
|
+
const out = {};
|
|
140
|
+
if (rec)
|
|
141
|
+
for (const [k, v] of Object.entries(rec))
|
|
142
|
+
if (typeof v === 'number' && Number.isFinite(v))
|
|
143
|
+
out[k] = v;
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
export function writeAtpAutoDeliverLedger(path, ledger) {
|
|
147
|
+
try {
|
|
148
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
149
|
+
// Each map is capped independently to the most-recent entries (cooldown orders live in retryAfter/cooldownHits,
|
|
150
|
+
// NOT in submitted, so they must be trimmed on their own — they're cleared on success/terminal in steady state).
|
|
151
|
+
const body = {
|
|
152
|
+
version: 2,
|
|
153
|
+
submitted: capMap(ledger.submitted),
|
|
154
|
+
retryAfter: capMap(ledger.retryAfter),
|
|
155
|
+
cooldownHits: capMap(ledger.cooldownHits),
|
|
156
|
+
};
|
|
157
|
+
const tmp = `${path}.tmp`;
|
|
158
|
+
writeFileSync(tmp, JSON.stringify(body, null, 2));
|
|
159
|
+
renameSync(tmp, path);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
// Best effort: hub-side submitDelivery is idempotent per order id, so a later tick can retry safely.
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/** Keep at most MAX_ENTRIES, dropping the oldest (insertion-order) — bounds unbounded ledger growth. */
|
|
166
|
+
function capMap(rec) {
|
|
167
|
+
const entries = Object.entries(rec);
|
|
168
|
+
return entries.length > ATP_AUTODELIVER_LEDGER_MAX_ENTRIES ? Object.fromEntries(entries.slice(-ATP_AUTODELIVER_LEDGER_MAX_ENTRIES)) : rec;
|
|
169
|
+
}
|
|
170
|
+
export function buildAtpAutoDeliverProofPayload(task, nowDate = () => new Date()) {
|
|
171
|
+
const assetId = taskString(task, 'result_asset_id') ?? taskString(task, 'resultAssetId') ?? null;
|
|
172
|
+
return {
|
|
173
|
+
result: 'completed',
|
|
174
|
+
asset_id: assetId,
|
|
175
|
+
completed_at: taskString(task, 'claimed_at') ?? nowDate().toISOString(),
|
|
176
|
+
pass_rate: 1.0,
|
|
177
|
+
signals: Array.isArray(task['signals']) ? task['signals'].filter((s) => typeof s === 'string').slice(0, 10) : [],
|
|
178
|
+
submitter: 'evolver_auto_deliver',
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
function emptyLedger() {
|
|
182
|
+
return { version: 2, submitted: {}, retryAfter: {}, cooldownHits: {} };
|
|
183
|
+
}
|
|
184
|
+
function tasksFrom(value) {
|
|
185
|
+
if (Array.isArray(value))
|
|
186
|
+
return value.map(asRecord).filter((x) => Boolean(x));
|
|
187
|
+
const rec = asRecord(value);
|
|
188
|
+
const tasks = rec?.['tasks'];
|
|
189
|
+
return Array.isArray(tasks) ? tasks.map(asRecord).filter((x) => Boolean(x)) : [];
|
|
190
|
+
}
|
|
191
|
+
function taskString(task, key) {
|
|
192
|
+
const v = task[key];
|
|
193
|
+
return typeof v === 'string' && v.length > 0 ? v : undefined;
|
|
194
|
+
}
|
|
195
|
+
function asRecord(value) {
|
|
196
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
197
|
+
}
|