@evomap/evolver-cli 2.0.0-beta.14 → 2.0.0-beta.16

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.
@@ -1,10 +1,11 @@
1
1
  import { existsSync, readFileSync, statSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { inspect, format } from 'node:util';
4
- import { assetstore, events, hub, wire } from '@evomap/evolver-core';
4
+ import { assetstore, events, hub, wire, algo } from '@evomap/evolver-core';
5
5
  import { AuthError, HubClientError, HubFetch, HubUnreachableError, connectPublicHub, gepEnvelope, globalFetchLike, resolveHubUrl, } from '@evomap/evolver-adapter-public';
6
- import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
7
- import { resolveAtpHome, resolveAtpSenderId } from './atp.js';
6
+ import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
7
+ import { resolveAtpSenderId } from './atp.js';
8
+ import { resolveExplicitNodeCredentials, resolveIdentityHome } from './identityHome.js';
8
9
  const REUSE_CONTRACT = 'reuse.v1';
9
10
  const PUBLISH_CONTRACT = 'publish.v1';
10
11
  const REVERSIBILITY = 'irreversible';
@@ -27,6 +28,7 @@ const STABLE_CONTRACT_REASONS = new Set([
27
28
  'schema_invalid',
28
29
  'bundle_required',
29
30
  'quality_gate_failed',
31
+ 'gene_unproven',
30
32
  'insufficient_credits',
31
33
  ]);
32
34
  const HUB_METADATA_KEYS = new Set([
@@ -64,23 +66,38 @@ class ContractError extends Error {
64
66
  export async function runReuseCommand(args, deps = {}) {
65
67
  const out = deps.out ?? process.stdout;
66
68
  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);
69
+ if (!parsed.ok || !parsed.assetId) {
70
+ return writeJson(out, reuseFailure(parsed.reason ?? 'missing_id', parsed.message ?? 'reuse requires --id <asset_id>'), 1, deps);
71
+ }
72
+ let runtimeDeps;
73
+ try {
74
+ runtimeDeps = { ...deps, env: loadContractEnv(deps) };
75
+ }
76
+ catch (err) {
77
+ const failure = classifyError(err, 'reuse');
78
+ return writeJson(out, reuseFailure(failure.reason, failure.message), 1, deps);
79
+ }
80
+ const write = (value, code) => writeJson(out, value, code, runtimeDeps);
70
81
  const assetId = parsed.assetId;
71
- return withMachineJsonConsole(Boolean(parsed.jsonOut), deps, async () => {
82
+ return withMachineJsonConsole(Boolean(parsed.jsonOut), runtimeDeps, async () => {
72
83
  try {
73
- const fetcher = deps.fetchAssetById ?? deps.transport?.fetchAssetById ?? createDefaultTransport(deps).fetchAssetById;
84
+ const fetcher = runtimeDeps.fetchAssetById
85
+ ?? runtimeDeps.transport?.fetchAssetById
86
+ ?? createDefaultTransport(runtimeDeps).fetchAssetById;
74
87
  const asset = await fetcher(assetId);
75
88
  if (!asset)
76
89
  return write(reuseFailure('not_found', 'asset not found'), 1);
77
90
  const cleaned = stripHubMetadata(asset);
78
- if (wire.computeAssetId(cleaned) !== assetId) {
91
+ const computedAssetId = wire.computeAssetId(cleaned);
92
+ const identityMatches = assetId.startsWith('sha256:')
93
+ ? computedAssetId === assetId
94
+ : stringField(cleaned, 'id') === assetId && computedAssetId === cleaned.asset_id;
95
+ if (!identityMatches) {
79
96
  return write(reuseFailure('internal_error', 'asset integrity verification failed'), 1);
80
97
  }
81
- const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir());
98
+ const store = runtimeDeps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(runtimeDeps));
82
99
  await assertNoLocalReuseIdConflict(cleaned, store);
83
- const provenance = new assetstore.ProvenanceStore(storeBaseDir(store, deps));
100
+ const provenance = new assetstore.ProvenanceStore(storeBaseDir(store, runtimeDeps));
84
101
  const stored = await assetstore.ingestUntrusted(store, provenance, cleaned, 'hub');
85
102
  return write({
86
103
  ok: true,
@@ -111,14 +128,27 @@ export async function runPublishCommand(args, deps = {}) {
111
128
  return 0;
112
129
  }
113
130
  const parsed = parsePublishArgs(args);
114
- const write = (value, code) => writeJson(out, value, code, deps);
115
131
  if (!parsed.ok || !parsed.assetRefs) {
116
- return write(publishFailure(parsed.reason ?? 'bundle_required', parsed.message ?? publishReasonMessage('bundle_required'), { retryable: false }), 1);
132
+ return writeJson(out, publishFailure(parsed.reason ?? 'bundle_required', parsed.message ?? publishReasonMessage('bundle_required'), { retryable: false }), 1, deps);
117
133
  }
118
134
  const assetRefs = parsed.assetRefs;
119
- return withMachineJsonConsole(Boolean(parsed.jsonOut), deps, async () => {
135
+ let runtimeDeps;
136
+ try {
137
+ const inheritedEnv = deps.env ?? process.env;
138
+ const runtimeEnv = loadContractEnv(deps);
139
+ runtimeDeps = { ...deps, env: preserveInheritedSecrets(runtimeEnv, inheritedEnv) };
140
+ }
141
+ catch (err) {
142
+ const failure = classifyError(err, 'publish');
143
+ return writeJson(out, publishFailure(failure.reason, failure.message, {
144
+ retryable: failure.retryable,
145
+ mode: parsed.dryRun ? 'dry_run' : 'publish',
146
+ }), 1, deps);
147
+ }
148
+ const write = (value, code) => writeJson(out, value, code, runtimeDeps);
149
+ return withMachineJsonConsole(Boolean(parsed.jsonOut), runtimeDeps, async () => {
120
150
  try {
121
- const bundle = await buildPublishBundle(assetRefs, deps);
151
+ const bundle = await buildPublishBundle(assetRefs, runtimeDeps);
122
152
  if (!bundle.ok) {
123
153
  return write(publishFailure(bundle.reason, bundle.message, { retryable: false, gates: bundle.gates }), 1);
124
154
  }
@@ -133,11 +163,22 @@ export async function runPublishCommand(args, deps = {}) {
133
163
  assets: bundle.assets,
134
164
  }), 1);
135
165
  }
136
- const transport = deps.transport ?? createDefaultTransport(deps);
166
+ const transport = deps.transport ?? createDefaultTransport(runtimeDeps);
137
167
  const validate = deps.validate ?? transport.validate;
138
168
  const validation = await validate(bundle.sanitized);
139
169
  const validationCredits = extractCredits(validation.body);
140
- if (!validation.ok) {
170
+ const validationUnavailable = transport.validationCapabilityOptional === true
171
+ && isValidationCapabilityUnavailable(validation.body);
172
+ if (!validation.ok && !(validationUnavailable && !parsed.dryRun)) {
173
+ if (validationUnavailable) {
174
+ return write(publishFailure('unsupported', publishReasonMessage('unsupported'), {
175
+ retryable: false,
176
+ mode: 'dry_run',
177
+ gates: bundle.gates,
178
+ assets: bundle.assets,
179
+ detail: 'Private Hub validation is not configured',
180
+ }), 1);
181
+ }
141
182
  const reason = publishReasonFromResponse(validation.status, validation.body);
142
183
  const detail = hubDetailFromBody(validation.body);
143
184
  if (parsed.dryRun && reason === 'quality_gate_failed') {
@@ -173,16 +214,21 @@ export async function runPublishCommand(args, deps = {}) {
173
214
  }), 1);
174
215
  }
175
216
  const payload = payloadRecord(published.body);
176
- if (stringField(payload, 'decision') === 'quarantine') {
217
+ const decision = stringField(payload, 'decision');
218
+ const hubReason = stringField(payload, 'reason');
219
+ const safetyCandidate = decision === 'quarantine' && hubReason === 'safety_candidate';
220
+ if (decision === 'quarantine' && !safetyCandidate) {
221
+ const detail = hubDetailFromBody(published.body);
177
222
  return write(publishFailure('quality_gate_failed', publishReasonMessage('quality_gate_failed'), {
178
223
  retryable: false,
179
224
  mode: 'publish',
180
225
  gates: { ...bundle.gates, quality: 'fail' },
181
226
  assets: bundle.assets,
227
+ ...(detail ? { detail } : {}),
182
228
  ...(publishCredits ? { credits: publishCredits } : {}),
183
229
  }), 1);
184
230
  }
185
- const status = normalizePublishStatus(published.body);
231
+ const status = safetyCandidate ? 'queued' : normalizePublishStatus(published.body);
186
232
  if (!status) {
187
233
  return write(publishFailure('internal_error', 'Hub publish response missing lifecycle status', {
188
234
  retryable: false,
@@ -202,6 +248,7 @@ export async function runPublishCommand(args, deps = {}) {
202
248
  reversibility: REVERSIBILITY,
203
249
  ...(receiptId ? { receipt_id: receiptId } : {}),
204
250
  ...(bundleId ? { bundle_id: bundleId } : {}),
251
+ ...(safetyCandidate ? { hub_reason: hubReason } : {}),
205
252
  assets: bundle.assets,
206
253
  ...(publishCredits ? { credits: publishCredits } : {}),
207
254
  }, 0);
@@ -317,22 +364,65 @@ export async function buildPublishBundle(refs, deps = {}) {
317
364
  return { ok: false, reason: 'bundle_required', message: finalBundleCheck.message, gates: { redaction: 'pass', schema: 'pass', bundle: 'fail' } };
318
365
  }
319
366
  const leak = finalPayloadLeakCheck(sanitized, deps.env ?? process.env);
367
+ // Local quality gate: a gene may only publish once it has TRULY succeeded at
368
+ // least once. Minting sets `confidence` from self-report / text completeness,
369
+ // which never proves the gene worked; without this check an unproven gene
370
+ // leaks to the Hub and comes back as an opaque `quality_gate_failed` after a
371
+ // round-trip. Assessing the gene's outcome evidence here fails fast, locally,
372
+ // with a precise reason. Read-only: aggregates the local capsule history.
373
+ const geneEvidence = await assessPublishGeneEvidence(original, deps);
374
+ const geneProven = geneEvidence?.eligible ?? true;
320
375
  const gates = {
321
376
  redaction: 'pass',
322
377
  leak: leak.blocked ? 'fail' : 'pass',
323
378
  schema: 'pass',
324
379
  bundle: 'pass',
325
- quality: 'pass',
380
+ quality: geneProven ? 'pass' : 'fail',
326
381
  };
382
+ const blockReasons = [];
383
+ if (leak.blocked)
384
+ blockReasons.push('leak_detected');
385
+ if (!geneProven)
386
+ blockReasons.push('gene_unproven');
327
387
  return {
328
388
  ok: true,
329
389
  original,
330
390
  sanitized,
331
- blockReasons: leak.blocked ? ['leak_detected'] : [],
391
+ blockReasons,
332
392
  gates,
333
393
  assets: summarizePublishAssets(sanitized),
334
394
  };
335
395
  }
396
+ // Assess whether the bundle's Gene has proven success in the local capsule
397
+ // history. Fail-open (returns null) when there is no gene id or the store read
398
+ // throws — the pre-check only ADDS a local gate; the Hub still gates, so an
399
+ // infra hiccup must not block an otherwise-valid publish.
400
+ async function assessPublishGeneEvidence(original, deps) {
401
+ const gene = original.find((asset) => asset.type === 'Gene');
402
+ if (!gene)
403
+ return null;
404
+ const businessId = stringField(gene, 'id');
405
+ const assetId = typeof gene.asset_id === 'string' ? gene.asset_id : undefined;
406
+ const geneId = businessId ?? assetId;
407
+ if (!geneId)
408
+ return null;
409
+ try {
410
+ const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(deps));
411
+ const primary = await algo.assessGenePublishEvidence(store, geneId);
412
+ // Capsules key their `gene` link by the gene's business id in production;
413
+ // some stores (and legacy fixtures) key it by asset_id. If the business-id
414
+ // lookup found no history, retry by asset_id before concluding "unproven".
415
+ if (primary.total === 0 && assetId && assetId !== geneId) {
416
+ const byAssetId = await algo.assessGenePublishEvidence(store, assetId);
417
+ if (byAssetId.total > 0)
418
+ return byAssetId;
419
+ }
420
+ return primary;
421
+ }
422
+ catch {
423
+ return null;
424
+ }
425
+ }
336
426
  function sanitizePublishBundle(original) {
337
427
  const sanitized = original.map((asset) => hub.sanitizeAsset(stripPublishMetadata(asset)));
338
428
  const finalGeneIdByOriginalRef = new Map();
@@ -372,7 +462,7 @@ async function loadAssetRef(ref, deps) {
372
462
  throw new ContractError('schema_invalid', 'asset not found');
373
463
  return normalizeAsset(fromStore);
374
464
  }
375
- const readOnly = loadLocalAssetsReadOnly(deps.assetsDir ?? events.assetsDir());
465
+ const readOnly = loadLocalAssetsReadOnly(contractAssetsDir(deps));
376
466
  const found = readOnly.find((asset) => asset.asset_id === ref || stringField(asset, 'id') === ref);
377
467
  if (!found)
378
468
  throw new ContractError('schema_invalid', 'asset not found');
@@ -490,7 +580,10 @@ function stripPublishMetadata(asset) {
490
580
  return stripHubMetadata(asset);
491
581
  }
492
582
  function storeBaseDir(store, deps) {
493
- return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : deps.assetsDir ?? events.assetsDir();
583
+ return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : contractAssetsDir(deps);
584
+ }
585
+ function contractAssetsDir(deps) {
586
+ return deps.assetsDir ?? events.assetsDir(deps.env ?? process.env);
494
587
  }
495
588
  function dryRunEnvelope(bundle, credits, blockDetail) {
496
589
  const suppressPayload = bundle.blockReasons.includes('leak_detected');
@@ -595,13 +688,19 @@ async function withMachineJsonConsole(enabled, deps, fn) {
595
688
  }
596
689
  }
597
690
  function createDefaultTransport(deps) {
598
- const env = deps.env ?? process.env;
599
- loadEnvFileFromEnv(env);
691
+ const env = loadContractEnv(deps);
692
+ const hubMode = configuredHubMode(env);
693
+ if (hubMode === 'private') {
694
+ return createPrivateTransport(env, deps.resolveProxyClient ?? resolveDefaultPrivateProxy);
695
+ }
600
696
  const hubUrl = resolveHubUrl(env);
601
- const evomapDir = resolveAtpHome(env);
602
- const sender = resolveAtpSenderId(env);
603
- const senderId = () => sender ?? env['A2A_NODE_ID']?.trim();
604
- const nodeSecret = env['EVOMAP_NODE_SECRET']?.trim() || env['A2A_NODE_SECRET']?.trim();
697
+ const evomapDir = resolveIdentityHome(env);
698
+ const explicitCredentials = resolveExplicitNodeCredentials(env);
699
+ const { nodeSecret } = explicitCredentials;
700
+ const sender = nodeSecret
701
+ ? explicitCredentials.senderId ?? resolveAtpSenderId(env)
702
+ : resolveAtpSenderId(env);
703
+ const senderId = () => sender;
605
704
  const connected = nodeSecret
606
705
  ? connectPublicHub({ hubUrl, authMode: 'legacy', evomapDir, nodeSecret, senderId })
607
706
  : connectPublicHub({ hubUrl, authMode: 'oauth', evomapDir, senderId });
@@ -631,6 +730,127 @@ function createDefaultTransport(deps) {
631
730
  publish: (bundle) => call('/a2a/publish', 'publish', bundle),
632
731
  };
633
732
  }
733
+ function loadContractEnv(deps) {
734
+ const env = { ...(deps.env ?? process.env) };
735
+ const envFile = loadEnvFileFromEnv(env);
736
+ if (envFile.error)
737
+ throw new Error('failed to load EVOLVER_ENV_FILE');
738
+ return env;
739
+ }
740
+ function preserveInheritedSecrets(runtimeEnv, inheritedEnv) {
741
+ const env = { ...runtimeEnv };
742
+ let index = 0;
743
+ for (const [key, value] of Object.entries(inheritedEnv)) {
744
+ if (!value || value === runtimeEnv[key] || !/SECRET|TOKEN|API[_-]?KEY|PASSWORD|AUTH|CREDENTIAL/i.test(key))
745
+ continue;
746
+ env[`EVOLVER_INHERITED_SECRET_${index++}`] = value;
747
+ }
748
+ return env;
749
+ }
750
+ function configuredHubMode(env) {
751
+ const value = String(env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase();
752
+ if (value === 'public' || value === 'private')
753
+ return value;
754
+ throw new Error('EVOMAP_HUB_MODE must be public or private');
755
+ }
756
+ function resolveDefaultPrivateProxy(env) {
757
+ return proxyClientFromEnv(env);
758
+ }
759
+ function createPrivateTransport(env, resolveProxy) {
760
+ const proxy = resolveProxy(env);
761
+ if (!proxy)
762
+ throw new Error('private Hub proxy credentials are not configured');
763
+ const privateModeReady = assertPrivateProxyMode(proxy);
764
+ return {
765
+ validationCapabilityOptional: true,
766
+ fetchAssetById: async (assetId) => {
767
+ try {
768
+ await privateModeReady;
769
+ const body = await proxy.fetchAsset({ assetId, expectedHubMode: 'private' });
770
+ return privateProxyAssets(body).find((asset) => (asset.asset_id === assetId || stringField(asset, 'id') === assetId)) ?? null;
771
+ }
772
+ catch (err) {
773
+ if (err instanceof ContractError)
774
+ throw err;
775
+ const message = err instanceof Error ? err.message : String(err);
776
+ if (message === 'proxy_hub_mode_mismatch' || isAuthLikeError(err)) {
777
+ throw new ContractError('auth_required', 'private Hub proxy authentication required');
778
+ }
779
+ throw new ContractError('network_error', 'Hub unreachable');
780
+ }
781
+ },
782
+ validate: async (bundle) => {
783
+ try {
784
+ await privateModeReady;
785
+ const body = await proxy.validateAssetBundle({ assets: [...bundle], expected_hub_mode: 'private' });
786
+ return { ok: hasExplicitValidatePass(body), status: 200, body };
787
+ }
788
+ catch (err) {
789
+ if (err instanceof ContractError)
790
+ throw err;
791
+ return privateProxyFailure(err);
792
+ }
793
+ },
794
+ publish: async (bundle) => {
795
+ try {
796
+ await privateModeReady;
797
+ const body = normalizePrivatePublishBody(await proxy.submitAssetBundle({
798
+ assets: [...bundle],
799
+ expected_hub_mode: 'private',
800
+ }));
801
+ return { ok: !privatePublishExplicitFailure(body) && normalizePublishStatus(body) !== undefined, status: 200, body };
802
+ }
803
+ catch (err) {
804
+ if (err instanceof ContractError)
805
+ throw err;
806
+ return privateProxyFailure(err);
807
+ }
808
+ },
809
+ };
810
+ }
811
+ async function assertPrivateProxyMode(proxy) {
812
+ const status = asRecord(await proxy.status()) ?? {};
813
+ if (status['hub_mode'] !== 'private') {
814
+ throw new ContractError('auth_required', 'private Hub proxy mode mismatch');
815
+ }
816
+ }
817
+ function isValidationCapabilityUnavailable(body) {
818
+ const root = asRecord(body) ?? {};
819
+ const payload = asRecord(root['payload']) ?? {};
820
+ return (root['reason'] ?? payload['reason']) === 'validate_not_configured';
821
+ }
822
+ function privateProxyAssets(body) {
823
+ const root = asRecord(body) ?? {};
824
+ const payload = asRecord(root['payload']) ?? {};
825
+ const rows = Array.isArray(root['assets']) ? root['assets'] : Array.isArray(payload['assets']) ? payload['assets'] : [];
826
+ return rows.filter((asset) => Boolean(asset && typeof asset === 'object' && !Array.isArray(asset)));
827
+ }
828
+ function normalizePrivatePublishBody(body) {
829
+ const root = asRecord(body);
830
+ if (!root)
831
+ return body;
832
+ const payload = asRecord(root['payload']);
833
+ if (payload) {
834
+ return { ...root, payload: normalizePrivatePublishLayer(payload) };
835
+ }
836
+ return normalizePrivatePublishLayer(root);
837
+ }
838
+ function normalizePrivatePublishLayer(body) {
839
+ const receiptId = stringField(body, 'receipt_id') ?? stringField(body, 'receiptId');
840
+ return {
841
+ ...body,
842
+ ...(stringField(body, 'status') === 'pending' ? { status: 'queued' } : {}),
843
+ ...(receiptId ? { receipt_id: receiptId } : {}),
844
+ };
845
+ }
846
+ function privatePublishExplicitFailure(body) {
847
+ const root = asRecord(body) ?? {};
848
+ const payload = asRecord(root['payload']) ?? {};
849
+ return root['ok'] === false || root['stored'] === false || payload['ok'] === false || payload['stored'] === false;
850
+ }
851
+ function privateProxyFailure(err) {
852
+ return { ok: false, status: isAuthLikeError(err) ? 401 : 0 };
853
+ }
634
854
  function isAuthLikeError(err) {
635
855
  const message = err instanceof Error ? err.message : String(err);
636
856
  return /oauth|login|credential|auth|401|403|node_secret/i.test(message);
@@ -691,6 +911,7 @@ function publishReasonMessage(reason) {
691
911
  schema_invalid: 'asset schema is invalid',
692
912
  bundle_required: 'publish requires a complete asset bundle',
693
913
  quality_gate_failed: 'Hub quality gate failed',
914
+ gene_unproven: 'gene has no proven success yet — run it to a successful outcome before publishing',
694
915
  insufficient_credits: 'insufficient credits',
695
916
  };
696
917
  return map[reason] ?? map.internal_error;
@@ -746,6 +967,8 @@ export function hasExplicitValidatePass(body) {
746
967
  function normalizePublishStatus(body) {
747
968
  const payload = payloadRecord(body);
748
969
  const status = stringField(payload, 'status');
970
+ if (status === 'candidate')
971
+ return 'queued';
749
972
  if (status === 'queued' || status === 'accepted' || status === 'published')
750
973
  return status;
751
974
  if (status)
@@ -0,0 +1,9 @@
1
+ export interface ExplicitNodeCredentials {
2
+ senderId?: string;
3
+ nodeSecret?: string;
4
+ nodeSecretVersion?: string;
5
+ }
6
+ /** Select explicit node credentials without combining conflicting alias namespaces. */
7
+ export declare function resolveExplicitNodeCredentials(env?: NodeJS.ProcessEnv): ExplicitNodeCredentials;
8
+ /** Resolve the public Hub identity root without coupling credentials to Evolver state. */
9
+ export declare function resolveIdentityHome(env?: NodeJS.ProcessEnv, homeDir?: string): string;
@@ -0,0 +1,46 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ function nonBlank(value) {
4
+ const trimmed = value?.trim();
5
+ return trimmed ? trimmed : undefined;
6
+ }
7
+ /** Select explicit node credentials without combining conflicting alias namespaces. */
8
+ export function resolveExplicitNodeCredentials(env = process.env) {
9
+ const evomap = credentialNamespace(env, 'EVOMAP');
10
+ const a2a = credentialNamespace(env, 'A2A');
11
+ if (evomap.senderId && evomap.nodeSecret)
12
+ return evomap;
13
+ if (a2a.senderId && a2a.nodeSecret)
14
+ return a2a;
15
+ if (evomap.senderId && a2a.senderId && evomap.senderId === a2a.senderId) {
16
+ const selected = evomap.nodeSecret ? evomap : a2a.nodeSecret ? a2a : evomap;
17
+ return selected.nodeSecret ? selected : { senderId: selected.senderId };
18
+ }
19
+ const senderId = evomap.senderId ?? a2a.senderId;
20
+ if (senderId)
21
+ return { senderId };
22
+ const selected = evomap.nodeSecret ? evomap : a2a;
23
+ return selected.nodeSecret
24
+ ? {
25
+ nodeSecret: selected.nodeSecret,
26
+ ...(selected.nodeSecretVersion ? { nodeSecretVersion: selected.nodeSecretVersion } : {}),
27
+ }
28
+ : {};
29
+ }
30
+ function credentialNamespace(env, prefix) {
31
+ const senderId = nonBlank(env[`${prefix}_NODE_ID`]);
32
+ const nodeSecret = nonBlank(env[`${prefix}_NODE_SECRET`]);
33
+ const nodeSecretVersion = nonBlank(env[`${prefix}_NODE_SECRET_VERSION`]);
34
+ return {
35
+ ...(senderId ? { senderId } : {}),
36
+ ...(nodeSecret ? { nodeSecret } : {}),
37
+ ...(nodeSecretVersion ? { nodeSecretVersion } : {}),
38
+ };
39
+ }
40
+ /** Resolve the public Hub identity root without coupling credentials to Evolver state. */
41
+ export function resolveIdentityHome(env = process.env, homeDir) {
42
+ const explicit = [env['EVOMAP_HOME'], env['EVOMAP_DIR'], env['EVOLVER_HOME']]
43
+ .map(nonBlank)
44
+ .filter((value) => value !== undefined);
45
+ return explicit[0] ?? join(homeDir ?? homedir(), '.evomap');
46
+ }
@@ -0,0 +1,11 @@
1
+ import { trace } from '@evomap/evolver-core';
2
+ export interface LearningTraceWiring {
3
+ enabled: boolean;
4
+ upload: 'on' | 'off' | 'no_credentials';
5
+ config: {
6
+ packetSink: trace.LearningPacketSink;
7
+ traceSink?: trace.TraceSink;
8
+ sourceRepo?: string;
9
+ } | null;
10
+ }
11
+ export declare function resolveLearningTrace(env?: NodeJS.ProcessEnv): LearningTraceWiring;
@@ -0,0 +1,46 @@
1
+ // Learning-trace wiring for the autoexec daemon (Learning Ops slices 2+3). Local file sinks are the
2
+ // always-on durability layer — per-run LearningPacket drafts land under ~/.evomap/evolution/learning-trace/
3
+ // (kill switch: EVOLVER_LEARNING_TRACE=0). Hub upload (slice 3) is opt-in via EVOLVER_LEARNING_TRACE_UPLOAD=1
4
+ // and rides the same OAuth credential as the other hub links; when enabled + credentialed, packets are teed
5
+ // file-first then uploaded best-effort, so a hub outage never loses the local record or affects a verdict.
6
+ import { events, trace } from '@evomap/evolver-core';
7
+ import { join } from 'node:path';
8
+ import { homedir } from 'node:os';
9
+ import { existsSync } from 'node:fs';
10
+ import { HubLearningPacketSink, TeeLearningPacketSink, connectPublicHub, resolveHubUrl, globalFetchLike, } from '@evomap/evolver-adapter-public';
11
+ import { resolveAtpHome, resolveAtpSenderId } from './atp.js';
12
+ function resolveHubUpload(env) {
13
+ if (env['EVOLVER_LEARNING_TRACE_UPLOAD'] !== '1')
14
+ return { sink: null, state: 'off' };
15
+ const dir = resolveAtpHome(env) ?? join(homedir(), '.evomap');
16
+ if (!existsSync(join(dir, 'token.json')))
17
+ return { sink: null, state: 'no_credentials' };
18
+ try {
19
+ const hubUrl = resolveHubUrl(env);
20
+ const senderId = resolveAtpSenderId(env);
21
+ const { auth } = connectPublicHub({ hubUrl, authMode: 'oauth', evomapDir: dir, senderId: () => senderId });
22
+ return {
23
+ sink: new HubLearningPacketSink({ baseUrl: hubUrl, auth, fetchFn: globalFetchLike, nodeId: () => senderId }),
24
+ state: 'on',
25
+ };
26
+ }
27
+ catch {
28
+ return { sink: null, state: 'no_credentials' };
29
+ }
30
+ }
31
+ export function resolveLearningTrace(env = process.env) {
32
+ if (env['EVOLVER_LEARNING_TRACE'] === '0')
33
+ return { enabled: false, upload: 'off', config: null };
34
+ const dir = events.learningTraceDir(env);
35
+ const fileSink = new trace.FileLearningPacketSink(dir);
36
+ const upload = resolveHubUpload(env);
37
+ return {
38
+ enabled: true,
39
+ upload: upload.state,
40
+ config: {
41
+ packetSink: upload.sink ? new TeeLearningPacketSink(fileSink, upload.sink) : fileSink,
42
+ traceSink: new trace.FileTraceSink(join(dir, 'trace-events.jsonl')),
43
+ sourceRepo: 'evolver-v2',
44
+ },
45
+ };
46
+ }
package/dist/login.d.ts CHANGED
@@ -18,7 +18,7 @@ export declare function publicOAuthTokenPath(opts?: PublicAuthPathOptions): stri
18
18
  *
19
19
  * Hub URL follows A2A_HUB_URL -> EVOMAP_HUB_URL -> EVOLVER_DEFAULT_HUB_URL -> https://evomap.ai. Credential
20
20
  * home follows the same public Hub precedence as publish/ATP:
21
- * EVOMAP_DIR → EVOLVER_HOME → EVOMAP_HOME → ~/.evomap. The token replaces
21
+ * EVOMAP_HOME → EVOMAP_DIR → EVOLVER_HOME → ~/.evomap. The token replaces
22
22
  * node_secret for publish + /a2a calls (it carries the `a2a` scope).
23
23
  */
24
24
  export declare function runLogin(argv: readonly string[]): Promise<number>;
package/dist/login.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { existsSync, unlinkSync } from 'node:fs';
2
- import { homedir } from 'node:os';
3
2
  import { join } from 'node:path';
4
3
  import { PublicOAuthProvider, createOAuthHttpTransport, resolveHubUrl } from '@evomap/evolver-adapter-public';
5
4
  import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
5
+ import { resolveIdentityHome } from './identityHome.js';
6
6
  const LOGIN_USAGE = 'usage: evolver login\n';
7
7
  function publicAuthDir(opts = {}) {
8
8
  const env = opts.env ?? process.env;
9
- return env.EVOMAP_DIR ?? env.EVOLVER_HOME ?? env.EVOMAP_HOME ?? join(opts.homeDir ?? homedir(), '.evomap');
9
+ return resolveIdentityHome(env, opts.homeDir);
10
10
  }
11
11
  export function publicOAuthTokenPath(opts = {}) {
12
12
  return join(publicAuthDir(opts), 'token.json');
@@ -18,7 +18,7 @@ export function publicOAuthTokenPath(opts = {}) {
18
18
  *
19
19
  * Hub URL follows A2A_HUB_URL -> EVOMAP_HUB_URL -> EVOLVER_DEFAULT_HUB_URL -> https://evomap.ai. Credential
20
20
  * home follows the same public Hub precedence as publish/ATP:
21
- * EVOMAP_DIR → EVOLVER_HOME → EVOMAP_HOME → ~/.evomap. The token replaces
21
+ * EVOMAP_HOME → EVOMAP_DIR → EVOLVER_HOME → ~/.evomap. The token replaces
22
22
  * node_secret for publish + /a2a calls (it carries the `a2a` scope).
23
23
  */
24
24
  export async function runLogin(argv) {
package/dist/recipe.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { assetstore, events, type hub as hubNs } from '@evomap/evolver-core';
1
+ import { assetstore, events, verify, type hub as hubNs } from '@evomap/evolver-core';
2
2
  import type { ConnectPublicOptions, PublicHubCapability } from '@evomap/evolver-adapter-public';
3
3
  export interface RecipeCliDeps {
4
4
  hub?: RecipeHub;
@@ -8,6 +8,7 @@ export interface RecipeCliDeps {
8
8
  err?: (line: string) => void;
9
9
  ingestor?: events.Ingestor;
10
10
  review?: assetstore.ReviewLedger;
11
+ runValidation?: typeof verify.runSandboxedValidation;
11
12
  connectHub?: (opts: ConnectPublicOptions) => {
12
13
  hub: PublicHubCapability;
13
14
  auth: hubNs.AuthProvider;
@@ -15,12 +16,15 @@ export interface RecipeCliDeps {
15
16
  }
16
17
  export interface RecipeHub {
17
18
  recipes?: hubNs.RecipeCapability;
19
+ publish(bundle: assetstore.AssetRecord[]): Promise<hubNs.PublishReceipt>;
18
20
  hello?(opts: {
19
21
  rotate: boolean;
20
22
  evolverVersion?: string;
23
+ preserveCredentials?: boolean;
21
24
  }): Promise<{
22
25
  ok: boolean;
23
26
  error?: string;
27
+ nodeId?: string;
24
28
  }>;
25
29
  }
26
30
  type ParseResult<T> = {