@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
|
@@ -0,0 +1,815 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { inspect, format } from 'node:util';
|
|
4
|
+
import { assetstore, events, hub, wire } from '@evomap/evolver-core';
|
|
5
|
+
import { AuthError, HubClientError, HubFetch, HubUnreachableError, connectPublicHub, gepEnvelope, globalFetchLike, } from '@evomap/evolver-adapter-public';
|
|
6
|
+
import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
|
|
7
|
+
import { resolveAtpHome, resolveAtpSenderId } from './atp.js';
|
|
8
|
+
const REUSE_CONTRACT = 'reuse.v1';
|
|
9
|
+
const PUBLISH_CONTRACT = 'publish.v1';
|
|
10
|
+
const REVERSIBILITY = 'irreversible';
|
|
11
|
+
const MAX_ASSETS = 50;
|
|
12
|
+
const PUBLISH_USAGE = [
|
|
13
|
+
'usage: evolver publish --asset <gene_id_or_path> --asset <capsule_id_or_path> --json [--dry-run]',
|
|
14
|
+
' evolver publish --gene <id_or_path> --capsule <id_or_path> --json [--dry-run]',
|
|
15
|
+
].join('\n');
|
|
16
|
+
const ASSET_FLAGS = new Set(['--asset', '--gene', '--capsule', '--event']);
|
|
17
|
+
const STABLE_CONTRACT_REASONS = new Set([
|
|
18
|
+
'missing_id',
|
|
19
|
+
'cli_unavailable',
|
|
20
|
+
'auth_required',
|
|
21
|
+
'not_found',
|
|
22
|
+
'network_error',
|
|
23
|
+
'unsupported',
|
|
24
|
+
'internal_error',
|
|
25
|
+
'redaction_unavailable',
|
|
26
|
+
'leak_detected',
|
|
27
|
+
'schema_invalid',
|
|
28
|
+
'bundle_required',
|
|
29
|
+
'quality_gate_failed',
|
|
30
|
+
'insufficient_credits',
|
|
31
|
+
]);
|
|
32
|
+
const HUB_METADATA_KEYS = new Set([
|
|
33
|
+
'credit_cost',
|
|
34
|
+
'gdi_score',
|
|
35
|
+
'success_rate',
|
|
36
|
+
'reuse_count',
|
|
37
|
+
'ranking_score',
|
|
38
|
+
'source_node_id',
|
|
39
|
+
'fetched_at',
|
|
40
|
+
'receipt',
|
|
41
|
+
'hub_receipt',
|
|
42
|
+
'already_purchased',
|
|
43
|
+
'_semantic_similarity',
|
|
44
|
+
'semantic_similarity',
|
|
45
|
+
'_search_score',
|
|
46
|
+
'search_score',
|
|
47
|
+
'_match_score',
|
|
48
|
+
'match_score',
|
|
49
|
+
'_retrieval_rank',
|
|
50
|
+
'retrieval_rank',
|
|
51
|
+
'original_asset_id',
|
|
52
|
+
]);
|
|
53
|
+
let machineJsonStdoutBypass;
|
|
54
|
+
class ContractError extends Error {
|
|
55
|
+
reason;
|
|
56
|
+
safeMessage;
|
|
57
|
+
constructor(reason, safeMessage) {
|
|
58
|
+
super(safeMessage);
|
|
59
|
+
this.reason = reason;
|
|
60
|
+
this.safeMessage = safeMessage;
|
|
61
|
+
this.name = 'ContractError';
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export async function runReuseCommand(args, deps = {}) {
|
|
65
|
+
const out = deps.out ?? process.stdout;
|
|
66
|
+
const parsed = parseReuseArgs(args);
|
|
67
|
+
const write = (value, code) => writeJson(out, value, code, deps);
|
|
68
|
+
if (!parsed.ok || !parsed.assetId)
|
|
69
|
+
return write(reuseFailure(parsed.reason ?? 'missing_id', parsed.message ?? 'reuse requires --id <asset_id>'), 1);
|
|
70
|
+
const assetId = parsed.assetId;
|
|
71
|
+
return withMachineJsonConsole(Boolean(parsed.jsonOut), deps, async () => {
|
|
72
|
+
try {
|
|
73
|
+
const fetcher = deps.fetchAssetById ?? deps.transport?.fetchAssetById ?? createDefaultTransport(deps).fetchAssetById;
|
|
74
|
+
const asset = await fetcher(assetId);
|
|
75
|
+
if (!asset)
|
|
76
|
+
return write(reuseFailure('not_found', 'asset not found'), 1);
|
|
77
|
+
const cleaned = stripHubMetadata(asset);
|
|
78
|
+
if (wire.computeAssetId(cleaned) !== assetId) {
|
|
79
|
+
return write(reuseFailure('internal_error', 'asset integrity verification failed'), 1);
|
|
80
|
+
}
|
|
81
|
+
const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
|
|
82
|
+
await assertNoLocalReuseIdConflict(cleaned, store);
|
|
83
|
+
const provenance = new assetstore.ProvenanceStore(storeBaseDir(store, deps));
|
|
84
|
+
const stored = await assetstore.ingestUntrusted(store, provenance, cleaned, 'hub');
|
|
85
|
+
return write({
|
|
86
|
+
ok: true,
|
|
87
|
+
contract: REUSE_CONTRACT,
|
|
88
|
+
status: 'ok',
|
|
89
|
+
asset_id: stored.asset_id,
|
|
90
|
+
action: 'reused',
|
|
91
|
+
}, 0);
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
const failure = classifyError(err, 'reuse');
|
|
95
|
+
return write(reuseFailure(failure.reason, failure.message), 1);
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
export async function runPublishCommand(args, deps = {}) {
|
|
100
|
+
const out = deps.out ?? process.stdout;
|
|
101
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
102
|
+
if (args.includes('--json')) {
|
|
103
|
+
return writeJson(out, {
|
|
104
|
+
ok: true,
|
|
105
|
+
contract: PUBLISH_CONTRACT,
|
|
106
|
+
mode: 'help',
|
|
107
|
+
usage: PUBLISH_USAGE,
|
|
108
|
+
}, 0, deps);
|
|
109
|
+
}
|
|
110
|
+
out.write(`${PUBLISH_USAGE}\n`);
|
|
111
|
+
return 0;
|
|
112
|
+
}
|
|
113
|
+
const parsed = parsePublishArgs(args);
|
|
114
|
+
const write = (value, code) => writeJson(out, value, code, deps);
|
|
115
|
+
if (!parsed.ok || !parsed.assetRefs) {
|
|
116
|
+
return write(publishFailure(parsed.reason ?? 'bundle_required', parsed.message ?? publishReasonMessage('bundle_required'), { retryable: false }), 1);
|
|
117
|
+
}
|
|
118
|
+
const assetRefs = parsed.assetRefs;
|
|
119
|
+
return withMachineJsonConsole(Boolean(parsed.jsonOut), deps, async () => {
|
|
120
|
+
try {
|
|
121
|
+
const bundle = await buildPublishBundle(assetRefs, deps);
|
|
122
|
+
if (!bundle.ok) {
|
|
123
|
+
return write(publishFailure(bundle.reason, bundle.message, { retryable: false, gates: bundle.gates }), 1);
|
|
124
|
+
}
|
|
125
|
+
if (bundle.blockReasons.length > 0) {
|
|
126
|
+
if (parsed.dryRun)
|
|
127
|
+
return write(dryRunEnvelope(bundle), 0);
|
|
128
|
+
const reason = bundle.blockReasons[0] ?? 'internal_error';
|
|
129
|
+
return write(publishFailure(reason, publishReasonMessage(reason), {
|
|
130
|
+
retryable: false,
|
|
131
|
+
mode: 'publish',
|
|
132
|
+
gates: bundle.gates,
|
|
133
|
+
assets: bundle.assets,
|
|
134
|
+
}), 1);
|
|
135
|
+
}
|
|
136
|
+
const transport = deps.transport ?? createDefaultTransport(deps);
|
|
137
|
+
const validate = deps.validate ?? transport.validate;
|
|
138
|
+
const validation = await validate(bundle.sanitized);
|
|
139
|
+
const validationCredits = extractCredits(validation.body);
|
|
140
|
+
if (!validation.ok) {
|
|
141
|
+
const reason = publishReasonFromResponse(validation.status, validation.body);
|
|
142
|
+
if (parsed.dryRun && reason === 'quality_gate_failed') {
|
|
143
|
+
bundle.gates.quality = 'fail';
|
|
144
|
+
if (!bundle.blockReasons.includes('quality_gate_failed'))
|
|
145
|
+
bundle.blockReasons.push('quality_gate_failed');
|
|
146
|
+
return write(dryRunEnvelope(bundle, validationCredits), 0);
|
|
147
|
+
}
|
|
148
|
+
return write(publishFailure(reason, publishReasonMessage(reason), {
|
|
149
|
+
retryable: publishRetryable(reason),
|
|
150
|
+
mode: parsed.dryRun ? 'dry_run' : 'publish',
|
|
151
|
+
gates: parsed.dryRun ? bundle.gates : { ...bundle.gates, quality: 'fail' },
|
|
152
|
+
assets: bundle.assets,
|
|
153
|
+
...(validationCredits ? { credits: validationCredits } : {}),
|
|
154
|
+
}), 1);
|
|
155
|
+
}
|
|
156
|
+
if (parsed.dryRun)
|
|
157
|
+
return write(dryRunEnvelope(bundle, validationCredits), 0);
|
|
158
|
+
const publish = deps.publish ?? transport.publish;
|
|
159
|
+
const published = await publish(bundle.sanitized);
|
|
160
|
+
const publishCredits = extractCredits(published.body);
|
|
161
|
+
if (!published.ok) {
|
|
162
|
+
const reason = publishReasonFromResponse(published.status, published.body);
|
|
163
|
+
return write(publishFailure(reason, publishReasonMessage(reason), {
|
|
164
|
+
retryable: publishRetryable(reason),
|
|
165
|
+
mode: 'publish',
|
|
166
|
+
gates: bundle.gates,
|
|
167
|
+
assets: bundle.assets,
|
|
168
|
+
...(publishCredits ? { credits: publishCredits } : {}),
|
|
169
|
+
}), 1);
|
|
170
|
+
}
|
|
171
|
+
const payload = payloadRecord(published.body);
|
|
172
|
+
if (stringField(payload, 'decision') === 'quarantine') {
|
|
173
|
+
return write(publishFailure('quality_gate_failed', publishReasonMessage('quality_gate_failed'), {
|
|
174
|
+
retryable: false,
|
|
175
|
+
mode: 'publish',
|
|
176
|
+
gates: { ...bundle.gates, quality: 'fail' },
|
|
177
|
+
assets: bundle.assets,
|
|
178
|
+
...(publishCredits ? { credits: publishCredits } : {}),
|
|
179
|
+
}), 1);
|
|
180
|
+
}
|
|
181
|
+
const status = normalizePublishStatus(published.body);
|
|
182
|
+
if (!status) {
|
|
183
|
+
return write(publishFailure('internal_error', 'Hub publish response missing lifecycle status', {
|
|
184
|
+
retryable: false,
|
|
185
|
+
mode: 'publish',
|
|
186
|
+
gates: bundle.gates,
|
|
187
|
+
assets: bundle.assets,
|
|
188
|
+
...(publishCredits ? { credits: publishCredits } : {}),
|
|
189
|
+
}), 1);
|
|
190
|
+
}
|
|
191
|
+
const receiptId = stringField(payload, 'receipt_id');
|
|
192
|
+
const bundleId = stringField(payload, 'bundle_id');
|
|
193
|
+
return write({
|
|
194
|
+
ok: true,
|
|
195
|
+
contract: PUBLISH_CONTRACT,
|
|
196
|
+
mode: 'publish',
|
|
197
|
+
status,
|
|
198
|
+
reversibility: REVERSIBILITY,
|
|
199
|
+
...(receiptId ? { receipt_id: receiptId } : {}),
|
|
200
|
+
...(bundleId ? { bundle_id: bundleId } : {}),
|
|
201
|
+
assets: bundle.assets,
|
|
202
|
+
...(publishCredits ? { credits: publishCredits } : {}),
|
|
203
|
+
}, 0);
|
|
204
|
+
}
|
|
205
|
+
catch (err) {
|
|
206
|
+
const failure = classifyError(err, 'publish');
|
|
207
|
+
return write(publishFailure(failure.reason, failure.message, {
|
|
208
|
+
retryable: failure.retryable,
|
|
209
|
+
mode: parsed.dryRun ? 'dry_run' : 'publish',
|
|
210
|
+
}), 1);
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
export function parseReuseArgs(args) {
|
|
215
|
+
let id;
|
|
216
|
+
let jsonOut = false;
|
|
217
|
+
for (let i = 0; i < args.length; i++) {
|
|
218
|
+
const token = args[i];
|
|
219
|
+
if (!token)
|
|
220
|
+
continue;
|
|
221
|
+
if (token === '--json') {
|
|
222
|
+
jsonOut = true;
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
if (token === '--id') {
|
|
226
|
+
const next = args[i + 1];
|
|
227
|
+
if (!next || next.startsWith('--'))
|
|
228
|
+
return { ok: false, reason: 'missing_id', message: 'reuse requires --id <asset_id>' };
|
|
229
|
+
id = next.trim();
|
|
230
|
+
i++;
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (token.startsWith('--id=')) {
|
|
234
|
+
id = token.slice('--id='.length).trim();
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
return { ok: false, reason: 'unsupported', message: 'unsupported reuse argument' };
|
|
238
|
+
}
|
|
239
|
+
if (!jsonOut)
|
|
240
|
+
return { ok: false, reason: 'unsupported', message: 'reuse requires --json' };
|
|
241
|
+
if (!id)
|
|
242
|
+
return { ok: false, reason: 'missing_id', message: 'reuse requires --id <asset_id>' };
|
|
243
|
+
if (id.length > 200)
|
|
244
|
+
return { ok: false, reason: 'missing_id', message: 'asset id must be <= 200 characters' };
|
|
245
|
+
return { ok: true, assetId: id, jsonOut };
|
|
246
|
+
}
|
|
247
|
+
export function parsePublishArgs(args) {
|
|
248
|
+
const assetRefs = [];
|
|
249
|
+
let dryRun = false;
|
|
250
|
+
let jsonOut = false;
|
|
251
|
+
for (let i = 0; i < args.length; i++) {
|
|
252
|
+
const token = args[i];
|
|
253
|
+
if (!token)
|
|
254
|
+
continue;
|
|
255
|
+
if (token === '--dry-run') {
|
|
256
|
+
dryRun = true;
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (token === '--json') {
|
|
260
|
+
jsonOut = true;
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const equalFlag = [...ASSET_FLAGS].find((flag) => token.startsWith(`${flag}=`));
|
|
264
|
+
if (equalFlag) {
|
|
265
|
+
const value = token.slice(equalFlag.length + 1).trim();
|
|
266
|
+
if (!value)
|
|
267
|
+
return { ok: false, reason: 'bundle_required', message: `${equalFlag} requires a value` };
|
|
268
|
+
assetRefs.push(value);
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
if (ASSET_FLAGS.has(token)) {
|
|
272
|
+
const next = args[i + 1];
|
|
273
|
+
if (!next || next.startsWith('--'))
|
|
274
|
+
return { ok: false, reason: 'bundle_required', message: `${token} requires a value` };
|
|
275
|
+
assetRefs.push(next.trim());
|
|
276
|
+
i++;
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
if (!token.startsWith('--'))
|
|
280
|
+
return { ok: false, reason: 'unsupported', message: 'unsupported publish argument' };
|
|
281
|
+
return { ok: false, reason: 'unsupported', message: 'unsupported publish flag' };
|
|
282
|
+
}
|
|
283
|
+
if (!jsonOut)
|
|
284
|
+
return { ok: false, reason: 'unsupported', message: 'publish requires --json' };
|
|
285
|
+
const refs = assetRefs.filter(Boolean);
|
|
286
|
+
if (refs.length === 0)
|
|
287
|
+
return { ok: false, reason: 'bundle_required', message: 'publish requires --asset <id|path>' };
|
|
288
|
+
if (refs.length > MAX_ASSETS)
|
|
289
|
+
return { ok: false, reason: 'bundle_required', message: `publish supports at most ${MAX_ASSETS} assets` };
|
|
290
|
+
return { ok: true, assetRefs: refs, dryRun, jsonOut };
|
|
291
|
+
}
|
|
292
|
+
export async function buildPublishBundle(refs, deps = {}) {
|
|
293
|
+
let original;
|
|
294
|
+
try {
|
|
295
|
+
original = await Promise.all(refs.map((ref) => loadAssetRef(ref, deps)));
|
|
296
|
+
}
|
|
297
|
+
catch (err) {
|
|
298
|
+
const reason = err instanceof ContractError ? err.reason : 'schema_invalid';
|
|
299
|
+
return { ok: false, reason, message: reason === 'bundle_required' ? publishReasonMessage(reason) : 'asset schema is invalid', gates: { schema: 'fail' } };
|
|
300
|
+
}
|
|
301
|
+
const bundleCheck = checkBundle(original);
|
|
302
|
+
if (!bundleCheck.ok)
|
|
303
|
+
return { ok: false, reason: 'bundle_required', message: bundleCheck.message, gates: { schema: 'pass', bundle: 'fail' } };
|
|
304
|
+
let sanitized;
|
|
305
|
+
try {
|
|
306
|
+
sanitized = sanitizePublishBundle(original);
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
return { ok: false, reason: 'redaction_unavailable', message: 'redaction unavailable', gates: { redaction: 'unavailable' } };
|
|
310
|
+
}
|
|
311
|
+
const finalBundleCheck = checkBundle(sanitized);
|
|
312
|
+
if (!finalBundleCheck.ok) {
|
|
313
|
+
return { ok: false, reason: 'bundle_required', message: finalBundleCheck.message, gates: { redaction: 'pass', schema: 'pass', bundle: 'fail' } };
|
|
314
|
+
}
|
|
315
|
+
const leak = finalPayloadLeakCheck(sanitized, deps.env ?? process.env);
|
|
316
|
+
const gates = {
|
|
317
|
+
redaction: 'pass',
|
|
318
|
+
leak: leak.blocked ? 'fail' : 'pass',
|
|
319
|
+
schema: 'pass',
|
|
320
|
+
bundle: 'pass',
|
|
321
|
+
quality: 'pass',
|
|
322
|
+
};
|
|
323
|
+
return {
|
|
324
|
+
ok: true,
|
|
325
|
+
original,
|
|
326
|
+
sanitized,
|
|
327
|
+
blockReasons: leak.blocked ? ['leak_detected'] : [],
|
|
328
|
+
gates,
|
|
329
|
+
assets: summarizePublishAssets(sanitized),
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
function sanitizePublishBundle(original) {
|
|
333
|
+
const sanitized = original.map((asset) => hub.sanitizeAsset(stripPublishMetadata(asset)));
|
|
334
|
+
const finalGeneIdByOriginalRef = new Map();
|
|
335
|
+
for (let i = 0; i < original.length; i++) {
|
|
336
|
+
const source = original[i];
|
|
337
|
+
const finalAsset = sanitized[i];
|
|
338
|
+
if (source?.type !== 'Gene' || finalAsset?.type !== 'Gene')
|
|
339
|
+
continue;
|
|
340
|
+
for (const ref of [source.asset_id, stringField(source, 'id')]) {
|
|
341
|
+
if (ref)
|
|
342
|
+
finalGeneIdByOriginalRef.set(ref, finalAsset.asset_id);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return sanitized.map((asset, index) => {
|
|
346
|
+
if (asset.type !== 'Capsule')
|
|
347
|
+
return asset;
|
|
348
|
+
const originalGeneRef = stringField(original[index], 'gene');
|
|
349
|
+
const sanitizedGeneRef = stringField(asset, 'gene');
|
|
350
|
+
const finalGeneId = (originalGeneRef ? finalGeneIdByOriginalRef.get(originalGeneRef) : undefined)
|
|
351
|
+
?? (sanitizedGeneRef ? finalGeneIdByOriginalRef.get(sanitizedGeneRef) : undefined);
|
|
352
|
+
if (!finalGeneId || sanitizedGeneRef === finalGeneId)
|
|
353
|
+
return asset;
|
|
354
|
+
return withRecomputedAssetId({ ...asset, gene: finalGeneId });
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
function withRecomputedAssetId(asset) {
|
|
358
|
+
const assetId = wire.computeAssetId(asset);
|
|
359
|
+
return { ...asset, asset_id: assetId ?? asset.asset_id };
|
|
360
|
+
}
|
|
361
|
+
async function loadAssetRef(ref, deps) {
|
|
362
|
+
if (looksLikeFile(ref))
|
|
363
|
+
return normalizeAsset(JSON.parse(readFileSync(resolve(ref), 'utf8')));
|
|
364
|
+
const store = deps.assetStore;
|
|
365
|
+
if (store) {
|
|
366
|
+
const fromStore = await findAssetInStore(ref, store);
|
|
367
|
+
if (!fromStore)
|
|
368
|
+
throw new ContractError('schema_invalid', 'asset not found');
|
|
369
|
+
return normalizeAsset(fromStore);
|
|
370
|
+
}
|
|
371
|
+
const readOnly = loadLocalAssetsReadOnly(deps.assetsDir ?? events.assetsDir());
|
|
372
|
+
const found = readOnly.find((asset) => asset.asset_id === ref || stringField(asset, 'id') === ref);
|
|
373
|
+
if (!found)
|
|
374
|
+
throw new ContractError('schema_invalid', 'asset not found');
|
|
375
|
+
return normalizeAsset(found);
|
|
376
|
+
}
|
|
377
|
+
async function findAssetInStore(ref, store) {
|
|
378
|
+
const byAssetId = await store.get(ref);
|
|
379
|
+
if (byAssetId)
|
|
380
|
+
return byAssetId;
|
|
381
|
+
for (const kind of ['Gene', 'Capsule', 'EvolutionEvent']) {
|
|
382
|
+
const rows = await store.list(kind, 10_000);
|
|
383
|
+
const found = rows.find((asset) => stringField(asset, 'id') === ref);
|
|
384
|
+
if (found)
|
|
385
|
+
return found;
|
|
386
|
+
}
|
|
387
|
+
return null;
|
|
388
|
+
}
|
|
389
|
+
function loadLocalAssetsReadOnly(baseDir) {
|
|
390
|
+
return [
|
|
391
|
+
...readJsonLines(`${baseDir}/genes.jsonl`, 'Gene'),
|
|
392
|
+
...readJsonLines(`${baseDir}/capsules.jsonl`, 'Capsule'),
|
|
393
|
+
...readJsonLines(`${baseDir}/events.jsonl`, 'EvolutionEvent'),
|
|
394
|
+
];
|
|
395
|
+
}
|
|
396
|
+
function readJsonLines(filePath, type) {
|
|
397
|
+
if (!existsSync(filePath))
|
|
398
|
+
return [];
|
|
399
|
+
try {
|
|
400
|
+
return readFileSync(filePath, 'utf8')
|
|
401
|
+
.split('\n')
|
|
402
|
+
.map((line) => line.trim())
|
|
403
|
+
.filter(Boolean)
|
|
404
|
+
.map((line) => JSON.parse(line))
|
|
405
|
+
.filter(isRecord)
|
|
406
|
+
.filter((asset) => asset['type'] === type)
|
|
407
|
+
.map(normalizeAsset);
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
throw new ContractError('schema_invalid', 'asset schema is invalid');
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
function normalizeAsset(value) {
|
|
414
|
+
if (!isRecord(value))
|
|
415
|
+
throw new ContractError('schema_invalid', 'asset is not an object');
|
|
416
|
+
const type = canonicalAssetType(value['type']);
|
|
417
|
+
if (!type)
|
|
418
|
+
throw new ContractError('schema_invalid', 'asset type must be Gene, Capsule, or EvolutionEvent');
|
|
419
|
+
return { ...value, type, asset_id: stringField(value, 'asset_id') ?? 'IGNORED' };
|
|
420
|
+
}
|
|
421
|
+
function checkBundle(bundle) {
|
|
422
|
+
const genes = bundle.filter((asset) => asset.type === 'Gene');
|
|
423
|
+
const capsules = bundle.filter((asset) => asset.type === 'Capsule');
|
|
424
|
+
const eventsFound = bundle.filter((asset) => asset.type === 'EvolutionEvent');
|
|
425
|
+
if (genes.length > 1 || capsules.length > 1 || eventsFound.length > 1) {
|
|
426
|
+
return { ok: false, message: 'publish supports one Gene + one Capsule + optional one EvolutionEvent bundle' };
|
|
427
|
+
}
|
|
428
|
+
if (genes.length === 0 || capsules.length === 0)
|
|
429
|
+
return { ok: false, message: 'publish requires Gene + Capsule bundle' };
|
|
430
|
+
const gene = genes[0];
|
|
431
|
+
const capsule = capsules[0];
|
|
432
|
+
const geneIds = new Set([gene.asset_id, stringField(gene, 'id')].filter((id) => Boolean(id)));
|
|
433
|
+
if (!geneIds.has(String(capsule['gene'] ?? '')))
|
|
434
|
+
return { ok: false, message: 'gene must publish with its capsule' };
|
|
435
|
+
return { ok: true };
|
|
436
|
+
}
|
|
437
|
+
function finalPayloadLeakCheck(bundle, env) {
|
|
438
|
+
const result = hub.fullLeakCheck(JSON.stringify(bundle), env);
|
|
439
|
+
const hardLeaks = result.leaks.filter((leak) => leak.type !== 'local_path');
|
|
440
|
+
return { blocked: hardLeaks.length > 0 };
|
|
441
|
+
}
|
|
442
|
+
async function assertNoLocalReuseIdConflict(asset, store) {
|
|
443
|
+
if (asset.type !== 'Gene' && asset.type !== 'Capsule')
|
|
444
|
+
return;
|
|
445
|
+
const id = stringField(asset, 'id');
|
|
446
|
+
if (!id)
|
|
447
|
+
return;
|
|
448
|
+
const rows = await store.list(asset.type, 10_000);
|
|
449
|
+
const local = rows.find((row) => stringField(row, 'id') === id);
|
|
450
|
+
if (!local)
|
|
451
|
+
return;
|
|
452
|
+
const incomingAssetId = wire.computeAssetId(asset);
|
|
453
|
+
const localAssetId = wire.computeAssetId(local);
|
|
454
|
+
if (incomingAssetId !== localAssetId)
|
|
455
|
+
throw new ContractError('internal_error', 'local asset id conflict');
|
|
456
|
+
}
|
|
457
|
+
function stripHubMetadata(asset) {
|
|
458
|
+
const out = {};
|
|
459
|
+
for (const [key, value] of Object.entries(asset))
|
|
460
|
+
if (!HUB_METADATA_KEYS.has(key))
|
|
461
|
+
out[key] = value;
|
|
462
|
+
return out;
|
|
463
|
+
}
|
|
464
|
+
function stripPublishMetadata(asset) {
|
|
465
|
+
return stripHubMetadata(asset);
|
|
466
|
+
}
|
|
467
|
+
function storeBaseDir(store, deps) {
|
|
468
|
+
return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : deps.assetsDir ?? events.assetsDir();
|
|
469
|
+
}
|
|
470
|
+
function dryRunEnvelope(bundle, credits) {
|
|
471
|
+
const suppressPayload = bundle.blockReasons.includes('leak_detected');
|
|
472
|
+
return {
|
|
473
|
+
ok: true,
|
|
474
|
+
contract: PUBLISH_CONTRACT,
|
|
475
|
+
mode: 'dry_run',
|
|
476
|
+
reversibility: REVERSIBILITY,
|
|
477
|
+
blocked: bundle.blockReasons.length > 0,
|
|
478
|
+
block_reasons: bundle.blockReasons,
|
|
479
|
+
assets: bundle.assets,
|
|
480
|
+
...(suppressPayload ? {} : { payload: { assets: bundle.sanitized } }),
|
|
481
|
+
gates: bundle.gates,
|
|
482
|
+
...(credits ? { credits } : {}),
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
function publishFailure(reason, message, opts) {
|
|
486
|
+
return {
|
|
487
|
+
ok: false,
|
|
488
|
+
contract: PUBLISH_CONTRACT,
|
|
489
|
+
...(opts.mode ? { mode: opts.mode } : {}),
|
|
490
|
+
...(opts.gates ? { gates: opts.gates } : {}),
|
|
491
|
+
...(opts.assets ? { assets: opts.assets } : {}),
|
|
492
|
+
...(opts.credits ? { credits: opts.credits } : {}),
|
|
493
|
+
reason,
|
|
494
|
+
retryable: opts.retryable,
|
|
495
|
+
message,
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
function reuseFailure(reason, message) {
|
|
499
|
+
return { ok: false, contract: REUSE_CONTRACT, reason, message };
|
|
500
|
+
}
|
|
501
|
+
function writeJson(out, value, code, deps) {
|
|
502
|
+
const chunk = `${JSON.stringify(sanitizeForContract(value, deps))}\n`;
|
|
503
|
+
if (out === process.stdout && machineJsonStdoutBypass)
|
|
504
|
+
machineJsonStdoutBypass(chunk);
|
|
505
|
+
else
|
|
506
|
+
out.write(chunk);
|
|
507
|
+
return code;
|
|
508
|
+
}
|
|
509
|
+
async function withMachineJsonConsole(enabled, deps, fn) {
|
|
510
|
+
if (!enabled)
|
|
511
|
+
return fn();
|
|
512
|
+
const original = {
|
|
513
|
+
log: console.log,
|
|
514
|
+
info: console.info,
|
|
515
|
+
warn: console.warn,
|
|
516
|
+
error: console.error,
|
|
517
|
+
debug: console.debug,
|
|
518
|
+
stdoutWrite: process.stdout.write,
|
|
519
|
+
stderrWrite: process.stderr.write,
|
|
520
|
+
};
|
|
521
|
+
const redirected = (...args) => {
|
|
522
|
+
try {
|
|
523
|
+
original.stderrWrite.call(process.stderr, `${sanitizeText(format(...args), deps)}\n`);
|
|
524
|
+
}
|
|
525
|
+
catch { /* ignore logging failures */ }
|
|
526
|
+
};
|
|
527
|
+
const stderrWrite = (chunk, encoding, callback) => {
|
|
528
|
+
const text = Buffer.isBuffer(chunk)
|
|
529
|
+
? chunk.toString(typeof encoding === 'string' ? encoding : 'utf8')
|
|
530
|
+
: String(chunk);
|
|
531
|
+
const clean = sanitizeText(text, deps);
|
|
532
|
+
const cb = typeof encoding === 'function' ? encoding : callback;
|
|
533
|
+
const ok = original.stderrWrite.call(process.stderr, clean);
|
|
534
|
+
cb?.();
|
|
535
|
+
return ok;
|
|
536
|
+
};
|
|
537
|
+
const stdoutWrite = (chunk, encoding, callback) => {
|
|
538
|
+
const text = Buffer.isBuffer(chunk)
|
|
539
|
+
? chunk.toString(typeof encoding === 'string' ? encoding : 'utf8')
|
|
540
|
+
: String(chunk);
|
|
541
|
+
const clean = sanitizeText(text, deps);
|
|
542
|
+
const cb = typeof encoding === 'function' ? encoding : callback;
|
|
543
|
+
const ok = original.stderrWrite.call(process.stderr, clean);
|
|
544
|
+
cb?.();
|
|
545
|
+
return ok;
|
|
546
|
+
};
|
|
547
|
+
const previousBypass = machineJsonStdoutBypass;
|
|
548
|
+
machineJsonStdoutBypass = (chunk) => original.stdoutWrite.call(process.stdout, chunk);
|
|
549
|
+
console.log = redirected;
|
|
550
|
+
console.info = redirected;
|
|
551
|
+
console.warn = redirected;
|
|
552
|
+
console.error = redirected;
|
|
553
|
+
console.debug = redirected;
|
|
554
|
+
process.stdout.write = stdoutWrite;
|
|
555
|
+
process.stderr.write = stderrWrite;
|
|
556
|
+
try {
|
|
557
|
+
return await fn();
|
|
558
|
+
}
|
|
559
|
+
finally {
|
|
560
|
+
console.log = original.log;
|
|
561
|
+
console.info = original.info;
|
|
562
|
+
console.warn = original.warn;
|
|
563
|
+
console.error = original.error;
|
|
564
|
+
console.debug = original.debug;
|
|
565
|
+
process.stdout.write = original.stdoutWrite;
|
|
566
|
+
process.stderr.write = original.stderrWrite;
|
|
567
|
+
machineJsonStdoutBypass = previousBypass;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
function createDefaultTransport(deps) {
|
|
571
|
+
const env = deps.env ?? process.env;
|
|
572
|
+
loadEnvFileFromEnv(env);
|
|
573
|
+
const hubUrl = env['EVOMAP_HUB_URL'] ?? 'https://evomap.ai';
|
|
574
|
+
const evomapDir = resolveAtpHome(env);
|
|
575
|
+
const sender = resolveAtpSenderId(env);
|
|
576
|
+
const senderId = () => sender ?? env['A2A_NODE_ID']?.trim();
|
|
577
|
+
const nodeSecret = env['EVOMAP_NODE_SECRET']?.trim() || env['A2A_NODE_SECRET']?.trim();
|
|
578
|
+
const connected = nodeSecret
|
|
579
|
+
? connectPublicHub({ hubUrl, authMode: 'legacy', evomapDir, nodeSecret, senderId })
|
|
580
|
+
: connectPublicHub({ hubUrl, authMode: 'oauth', evomapDir, senderId });
|
|
581
|
+
const http = new HubFetch({ baseUrl: hubUrl, auth: connected.auth, fetchFn: globalFetchLike, senderId });
|
|
582
|
+
const call = async (path, messageType, bundle) => {
|
|
583
|
+
try {
|
|
584
|
+
const body = await http.call('POST', path, gepEnvelope(messageType, { assets: [...bundle] }));
|
|
585
|
+
if (messageType === 'validate') {
|
|
586
|
+
const valid = hasExplicitValidatePass(body);
|
|
587
|
+
return { ok: valid, status: 200, body };
|
|
588
|
+
}
|
|
589
|
+
return { ok: true, status: 200, body };
|
|
590
|
+
}
|
|
591
|
+
catch (err) {
|
|
592
|
+
if (err instanceof AuthError)
|
|
593
|
+
return { ok: false, status: err.status };
|
|
594
|
+
if (err instanceof HubClientError)
|
|
595
|
+
return { ok: false, status: err.status, body: err.body };
|
|
596
|
+
return { ok: false, status: 0 };
|
|
597
|
+
}
|
|
598
|
+
};
|
|
599
|
+
return {
|
|
600
|
+
fetchAssetById: (assetId) => connected.hub.fetchAssetById(assetId),
|
|
601
|
+
validate: (bundle) => call('/a2a/validate', 'validate', bundle),
|
|
602
|
+
publish: (bundle) => call('/a2a/publish', 'publish', bundle),
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
function classifyError(err, command) {
|
|
606
|
+
if (err instanceof ContractError)
|
|
607
|
+
return { reason: err.reason, message: err.safeMessage, retryable: err.reason === 'network_error' };
|
|
608
|
+
if (err instanceof AuthError)
|
|
609
|
+
return { reason: 'auth_required', message: 'Hub authentication required', retryable: false };
|
|
610
|
+
if (err instanceof HubUnreachableError)
|
|
611
|
+
return { reason: 'network_error', message: 'Hub unreachable', retryable: true };
|
|
612
|
+
if (err instanceof HubClientError) {
|
|
613
|
+
const reason = stableContractReasonFromBody(err.body) ?? (command === 'reuse' ? reuseReasonFromStatus(err.status) : publishReasonFromStatus(err.status));
|
|
614
|
+
return { reason, message: command === 'publish' ? publishReasonMessage(reason) : reuseReasonMessage(reason), retryable: publishRetryable(reason) };
|
|
615
|
+
}
|
|
616
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
617
|
+
if (/oauth|login|credential|auth|401|403|node_secret/i.test(message))
|
|
618
|
+
return { reason: 'auth_required', message: 'Hub authentication required', retryable: false };
|
|
619
|
+
if (/network|fetch failed|ECONN|ENOTFOUND|ETIMEDOUT|hub 5\d\d/i.test(message))
|
|
620
|
+
return { reason: 'network_error', message: 'Hub unreachable', retryable: true };
|
|
621
|
+
return { reason: 'internal_error', message: `evolver ${command} failed`, retryable: false };
|
|
622
|
+
}
|
|
623
|
+
function reuseReasonFromStatus(status) {
|
|
624
|
+
if (status === 401 || status === 403)
|
|
625
|
+
return 'auth_required';
|
|
626
|
+
if (status === 404)
|
|
627
|
+
return 'not_found';
|
|
628
|
+
if (status === 429 || status >= 500 || status === 0)
|
|
629
|
+
return 'network_error';
|
|
630
|
+
return 'internal_error';
|
|
631
|
+
}
|
|
632
|
+
function publishReasonFromStatus(status) {
|
|
633
|
+
if (status === 401 || status === 403)
|
|
634
|
+
return 'auth_required';
|
|
635
|
+
if (status === 402)
|
|
636
|
+
return 'insufficient_credits';
|
|
637
|
+
if (status === 429 || status >= 500 || status === 0)
|
|
638
|
+
return 'network_error';
|
|
639
|
+
return 'quality_gate_failed';
|
|
640
|
+
}
|
|
641
|
+
function publishReasonFromResponse(status, body) {
|
|
642
|
+
return stableContractReasonFromBody(body) ?? publishReasonFromStatus(status);
|
|
643
|
+
}
|
|
644
|
+
function publishRetryable(reason) {
|
|
645
|
+
return reason === 'network_error';
|
|
646
|
+
}
|
|
647
|
+
function publishReasonMessage(reason) {
|
|
648
|
+
const map = {
|
|
649
|
+
missing_id: 'missing asset id',
|
|
650
|
+
cli_unavailable: 'evolver CLI unavailable',
|
|
651
|
+
auth_required: 'Hub authentication required',
|
|
652
|
+
not_found: 'asset not found',
|
|
653
|
+
network_error: 'Hub unreachable',
|
|
654
|
+
unsupported: 'publish unsupported',
|
|
655
|
+
internal_error: 'evolver publish failed',
|
|
656
|
+
redaction_unavailable: 'redaction unavailable',
|
|
657
|
+
leak_detected: 'leak detected after redaction',
|
|
658
|
+
schema_invalid: 'asset schema is invalid',
|
|
659
|
+
bundle_required: 'publish requires a complete asset bundle',
|
|
660
|
+
quality_gate_failed: 'Hub quality gate failed',
|
|
661
|
+
insufficient_credits: 'insufficient credits',
|
|
662
|
+
};
|
|
663
|
+
return map[reason] ?? map.internal_error;
|
|
664
|
+
}
|
|
665
|
+
function reuseReasonMessage(reason) {
|
|
666
|
+
if (reason === 'not_found')
|
|
667
|
+
return 'asset not found';
|
|
668
|
+
if (reason === 'auth_required')
|
|
669
|
+
return 'Hub authentication required';
|
|
670
|
+
if (reason === 'network_error')
|
|
671
|
+
return 'Hub unreachable';
|
|
672
|
+
return 'evolver reuse failed';
|
|
673
|
+
}
|
|
674
|
+
function summarizePublishAssets(assets) {
|
|
675
|
+
return assets.map((asset) => {
|
|
676
|
+
const type = canonicalAssetType(asset.type);
|
|
677
|
+
return {
|
|
678
|
+
...(asset.asset_id ? { asset_id: asset.asset_id } : {}),
|
|
679
|
+
...(type ? { type } : {}),
|
|
680
|
+
};
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
function extractCredits(body) {
|
|
684
|
+
const payload = payloadRecord(body);
|
|
685
|
+
const credits = asRecord(payload['credits']) ?? asRecord(payload['credit_cost']) ?? asRecord(payload['economic']) ?? payload;
|
|
686
|
+
return creditsFromPayload(credits);
|
|
687
|
+
}
|
|
688
|
+
function creditsFromPayload(payload) {
|
|
689
|
+
const required = numberField(payload, 'required');
|
|
690
|
+
const available = numberField(payload, 'available');
|
|
691
|
+
const estimated = numberField(payload, 'estimated') ?? numberField(payload, 'estimate');
|
|
692
|
+
const charged = numberField(payload, 'charged');
|
|
693
|
+
const balanceKind = safeTokenField(stringField(payload, 'balance_kind') ?? stringField(payload, 'balanceKind'));
|
|
694
|
+
const out = {};
|
|
695
|
+
if (required !== undefined)
|
|
696
|
+
out['required'] = required;
|
|
697
|
+
if (available !== undefined)
|
|
698
|
+
out['available'] = available;
|
|
699
|
+
if (estimated !== undefined)
|
|
700
|
+
out['estimated'] = estimated;
|
|
701
|
+
if (charged !== undefined)
|
|
702
|
+
out['charged'] = charged;
|
|
703
|
+
if (balanceKind)
|
|
704
|
+
out['balance_kind'] = balanceKind;
|
|
705
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
706
|
+
}
|
|
707
|
+
export function hasExplicitValidatePass(body) {
|
|
708
|
+
const payload = payloadRecord(body);
|
|
709
|
+
const hasExplicitPass = payload['valid'] === true || payload['ok'] === true;
|
|
710
|
+
const hasExplicitFail = payload['valid'] === false || payload['ok'] === false;
|
|
711
|
+
return hasExplicitPass && !hasExplicitFail;
|
|
712
|
+
}
|
|
713
|
+
function normalizePublishStatus(body) {
|
|
714
|
+
const payload = payloadRecord(body);
|
|
715
|
+
const status = stringField(payload, 'status');
|
|
716
|
+
if (status === 'queued' || status === 'accepted' || status === 'published')
|
|
717
|
+
return status;
|
|
718
|
+
if (status)
|
|
719
|
+
return undefined;
|
|
720
|
+
const decision = stringField(payload, 'decision');
|
|
721
|
+
if (decision === 'accept')
|
|
722
|
+
return 'accepted';
|
|
723
|
+
if (decision === 'accepted')
|
|
724
|
+
return 'accepted';
|
|
725
|
+
if ((decision === 'reject' || decision === 'rejected') && stringField(payload, 'reason') === 'already_published')
|
|
726
|
+
return 'published';
|
|
727
|
+
return undefined;
|
|
728
|
+
}
|
|
729
|
+
function payloadRecord(body) {
|
|
730
|
+
const root = asRecord(body) ?? {};
|
|
731
|
+
return asRecord(root['payload']) ?? root;
|
|
732
|
+
}
|
|
733
|
+
function stableContractReasonFromBody(body) {
|
|
734
|
+
const payload = payloadRecord(body);
|
|
735
|
+
const reason = stringField(payload, 'reason') ?? stringField(payload, 'error');
|
|
736
|
+
return isStableContractReason(reason) ? reason : undefined;
|
|
737
|
+
}
|
|
738
|
+
function isStableContractReason(value) {
|
|
739
|
+
return Boolean(value && STABLE_CONTRACT_REASONS.has(value));
|
|
740
|
+
}
|
|
741
|
+
function sanitizeForContract(value, deps) {
|
|
742
|
+
return redactKnownSecrets(hub.redactDeep(value), deps);
|
|
743
|
+
}
|
|
744
|
+
function sanitizeText(value, deps) {
|
|
745
|
+
return String(redactKnownSecrets(hub.redactString(value), deps));
|
|
746
|
+
}
|
|
747
|
+
function redactKnownSecrets(value, deps, known = knownLocalSecrets(deps)) {
|
|
748
|
+
if (typeof value === 'string')
|
|
749
|
+
return redactKnownSecretsInString(value, known);
|
|
750
|
+
if (!value || typeof value !== 'object')
|
|
751
|
+
return value;
|
|
752
|
+
if (Array.isArray(value))
|
|
753
|
+
return value.map((item) => redactKnownSecrets(item, deps, known));
|
|
754
|
+
const out = {};
|
|
755
|
+
for (const [key, item] of Object.entries(value))
|
|
756
|
+
out[key] = redactKnownSecrets(item, deps, known);
|
|
757
|
+
return out;
|
|
758
|
+
}
|
|
759
|
+
function redactKnownSecretsInString(value, known) {
|
|
760
|
+
let result = value;
|
|
761
|
+
for (const secret of known)
|
|
762
|
+
result = result.split(secret).join('[REDACTED]');
|
|
763
|
+
return result;
|
|
764
|
+
}
|
|
765
|
+
function knownLocalSecrets(deps) {
|
|
766
|
+
const env = deps.env ?? process.env;
|
|
767
|
+
const secrets = new Set();
|
|
768
|
+
for (const [key, value] of Object.entries(env)) {
|
|
769
|
+
if (typeof value === 'string' && value.length >= 8 && /SECRET|TOKEN|API[_-]?KEY|PASSWORD|AUTH|CREDENTIAL/i.test(key)) {
|
|
770
|
+
secrets.add(value);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
return [...secrets].sort((a, b) => b.length - a.length);
|
|
774
|
+
}
|
|
775
|
+
function canonicalAssetType(value) {
|
|
776
|
+
if (value === 'Gene' || value === 'gene')
|
|
777
|
+
return 'Gene';
|
|
778
|
+
if (value === 'Capsule' || value === 'capsule')
|
|
779
|
+
return 'Capsule';
|
|
780
|
+
if (value === 'EvolutionEvent' || value === 'event' || value === 'Evolutionevent')
|
|
781
|
+
return 'EvolutionEvent';
|
|
782
|
+
return undefined;
|
|
783
|
+
}
|
|
784
|
+
function looksLikeFile(value) {
|
|
785
|
+
try {
|
|
786
|
+
return existsSync(value) && statSync(value).isFile();
|
|
787
|
+
}
|
|
788
|
+
catch {
|
|
789
|
+
return false;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
function isRecord(value) {
|
|
793
|
+
return Boolean(value && typeof value === 'object' && !Array.isArray(value));
|
|
794
|
+
}
|
|
795
|
+
function asRecord(value) {
|
|
796
|
+
return isRecord(value) ? value : undefined;
|
|
797
|
+
}
|
|
798
|
+
function stringField(value, key) {
|
|
799
|
+
const record = asRecord(value);
|
|
800
|
+
const raw = record?.[key];
|
|
801
|
+
return typeof raw === 'string' && raw.trim() ? raw.trim() : undefined;
|
|
802
|
+
}
|
|
803
|
+
function numberField(value, key) {
|
|
804
|
+
const raw = asRecord(value)?.[key];
|
|
805
|
+
const n = typeof raw === 'number' ? raw : (typeof raw === 'string' && raw.trim() ? Number(raw) : NaN);
|
|
806
|
+
return Number.isFinite(n) ? n : undefined;
|
|
807
|
+
}
|
|
808
|
+
function safeTokenField(value) {
|
|
809
|
+
if (!value)
|
|
810
|
+
return undefined;
|
|
811
|
+
return /^[A-Za-z0-9_.:-]{1,64}$/.test(value) ? value : undefined;
|
|
812
|
+
}
|
|
813
|
+
export function _inspectCliContractsForTest(value) {
|
|
814
|
+
return inspect(value, { depth: 4, colors: false });
|
|
815
|
+
}
|