@evomap/evolver-cli 2.0.0-beta.9 → 2.0.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.
Files changed (87) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +9 -3
  3. package/dist/assetHealth.js +2 -0
  4. package/dist/assetTrust.js +14 -1
  5. package/dist/atp.d.ts +10 -5
  6. package/dist/atp.js +119 -26
  7. package/dist/atpAutoBuyer.d.ts +120 -0
  8. package/dist/atpAutoBuyer.js +814 -0
  9. package/dist/atpAutoDeliver.js +2 -2
  10. package/dist/autoDistillLlm.js +2 -1
  11. package/dist/autoDistillTranscript.js +3 -2
  12. package/dist/autoexec.d.ts +101 -13
  13. package/dist/autoexec.js +794 -91
  14. package/dist/cli.js +13 -0
  15. package/dist/cliContracts.d.ts +23 -2
  16. package/dist/cliContracts.js +504 -54
  17. package/dist/commands.d.ts +1 -0
  18. package/dist/commands.js +1 -0
  19. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  20. package/dist/curriculumCapabilityGaps.js +24 -0
  21. package/dist/cycleConsumer.d.ts +13 -0
  22. package/dist/cycleConsumer.js +186 -20
  23. package/dist/dashboard.js +47 -9
  24. package/dist/dispatch.js +8 -2
  25. package/dist/distillPrimitives.d.ts +3 -2
  26. package/dist/distillPrimitives.js +80 -12
  27. package/dist/doctor.js +120 -11
  28. package/dist/identityHome.d.ts +9 -0
  29. package/dist/identityHome.js +47 -0
  30. package/dist/index.d.ts +70 -40
  31. package/dist/index.js +581 -193
  32. package/dist/learningTrace.d.ts +15 -0
  33. package/dist/learningTrace.js +73 -0
  34. package/dist/lifecycle.d.ts +67 -1
  35. package/dist/lifecycle.js +738 -44
  36. package/dist/localMemoryGraph.d.ts +90 -3
  37. package/dist/localMemoryGraph.js +2031 -231
  38. package/dist/login.d.ts +1 -1
  39. package/dist/login.js +3 -3
  40. package/dist/materialSnapshot.d.ts +9 -1
  41. package/dist/materialSnapshot.js +23 -6
  42. package/dist/memoryGraphOps.d.ts +8 -0
  43. package/dist/memoryGraphOps.js +140 -0
  44. package/dist/migrate/assetFormatMap.d.ts +61 -0
  45. package/dist/migrate/assetFormatMap.js +53 -0
  46. package/dist/migrate/envTranslate.d.ts +26 -0
  47. package/dist/migrate/envTranslate.js +147 -0
  48. package/dist/migrate/fieldMap.d.ts +4 -2
  49. package/dist/migrate/fieldMap.js +9 -5
  50. package/dist/migrate/oauthImport.d.ts +66 -0
  51. package/dist/migrate/oauthImport.js +667 -0
  52. package/dist/migrate/v1Import.d.ts +92 -1
  53. package/dist/migrate/v1Import.js +1481 -141
  54. package/dist/promptRecallHook.d.ts +24 -0
  55. package/dist/promptRecallHook.js +425 -0
  56. package/dist/recallVerifyReport.d.ts +37 -0
  57. package/dist/recallVerifyReport.js +244 -0
  58. package/dist/recipe.d.ts +7 -1
  59. package/dist/recipe.js +426 -56
  60. package/dist/requiredSandboxValidation.d.ts +5 -0
  61. package/dist/requiredSandboxValidation.js +4 -0
  62. package/dist/reuse.d.ts +9 -0
  63. package/dist/reuse.js +151 -56
  64. package/dist/runtimeCapabilities.js +15 -15
  65. package/dist/runtimeSessionSource.d.ts +3 -2
  66. package/dist/runtimeSessionSource.js +63 -11
  67. package/dist/selectionPolicyConfig.d.ts +8 -0
  68. package/dist/selectionPolicyConfig.js +18 -0
  69. package/dist/semanticIdfConfig.d.ts +2 -0
  70. package/dist/semanticIdfConfig.js +4 -0
  71. package/dist/sessionIngest.d.ts +37 -0
  72. package/dist/sessionIngest.js +156 -0
  73. package/dist/setupHooks.js +95 -1
  74. package/dist/skill2gep.d.ts +13 -9
  75. package/dist/skill2gep.js +42 -30
  76. package/dist/skillDistill.d.ts +8 -4
  77. package/dist/skillDistill.js +38 -9
  78. package/dist/solo/mode.js +1 -0
  79. package/dist/sync.d.ts +12 -0
  80. package/dist/sync.js +1246 -151
  81. package/dist/thesis.d.ts +1 -1
  82. package/dist/thesis.js +20 -3
  83. package/dist/trajectoryExport.js +21 -3
  84. package/dist/v1Compat.d.ts +1 -0
  85. package/dist/v1Compat.js +9 -0
  86. package/dist/workflowRuntime.js +24 -18
  87. package/package.json +11 -8
@@ -0,0 +1,5 @@
1
+ import { verify } from '@evomap/evolver-core';
2
+ export type SandboxedValidationRunner = typeof verify.runSandboxedValidation;
3
+ type SandboxedValidationOptions = NonNullable<Parameters<SandboxedValidationRunner>[2]>;
4
+ export declare function runRequiredSandboxedValidation(commands: readonly string[], cwd: string, options?: SandboxedValidationOptions, runner?: SandboxedValidationRunner): ReturnType<SandboxedValidationRunner>;
5
+ export {};
@@ -0,0 +1,4 @@
1
+ import { verify } from '@evomap/evolver-core';
2
+ export function runRequiredSandboxedValidation(commands, cwd, options = {}, runner = verify.runSandboxedValidation) {
3
+ return runner(commands, cwd, { ...options, requireIsolation: true });
4
+ }
package/dist/reuse.d.ts CHANGED
@@ -17,12 +17,19 @@ type AssetByIdFetcher = {
17
17
  fetchAssetById(assetId: string): Promise<assetstore.AssetRecord | null>;
18
18
  hello?(opts: PublicHelloOptions): Promise<unknown>;
19
19
  };
20
+ type PrivateReuseProxy = {
21
+ fetchAsset(args: {
22
+ assetId: string;
23
+ expectedHubMode: 'private';
24
+ }): Promise<unknown>;
25
+ };
20
26
  export interface ReuseCliDeps {
21
27
  store?: assetstore.AssetStoreProvider;
22
28
  assetsDir?: string;
23
29
  hub?: AssetByIdFetcher;
24
30
  callLog?: {
25
31
  append(entry: hubNs.AssetCallEntry): void;
32
+ assetCostIndex?(): Record<string, number>;
26
33
  };
27
34
  env?: NodeJS.ProcessEnv;
28
35
  stdout?: (line: string) => void;
@@ -31,6 +38,8 @@ export interface ReuseCliDeps {
31
38
  hub: PublicHubCapability;
32
39
  auth: hubNs.AuthProvider;
33
40
  };
41
+ /** Test seam for private-mode proxy discovery. */
42
+ resolveProxyClient?: (env: NodeJS.ProcessEnv) => PrivateReuseProxy | undefined;
34
43
  }
35
44
  interface ReuseOptions {
36
45
  id: string;
package/dist/reuse.js CHANGED
@@ -12,7 +12,7 @@
12
12
  // 2. NEVER let a token/secret reach any stream — error text is mapped to fixed messages / redacted.
13
13
  import { assetstore, events, hub as hubNs, wire } from '@evomap/evolver-core';
14
14
  import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled } from '@evomap/evolver-adapter-public';
15
- import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
15
+ import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
16
16
  import { createRecipeHubFromEnv } from './recipe.js';
17
17
  import { getCliVersion } from './version.js';
18
18
  const REUSE_CONTRACT = 'reuse.v1';
@@ -75,11 +75,13 @@ export async function runReuseCommand(argv, deps = {}) {
75
75
  const env = deps.env ?? process.env;
76
76
  // Keep the native reuse path aligned with publish/contract transport: env-file values must be present before
77
77
  // dry-run checks and Hub construction. The loader mutates `env` and does not expose secret values.
78
- loadEnvFileFromEnv(env);
79
- const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
78
+ const envFile = loadEnvFileFromEnv(env);
79
+ if (envFile.error)
80
+ throw new Error('failed to load EVOLVER_ENV_FILE');
81
+ const store = deps.store ?? new assetstore.LocalJsonlProvider(deps.assetsDir ?? events.assetsDir(env));
80
82
  // 1) Already in the local recall library → reuse is idempotent: log + ok, no hub round-trip.
81
83
  const local = await resolveLocalReuseAsset(store, opts.id);
82
- if (local) {
84
+ if (local && !isUnsafeUnverifiedLocalAsset(local, store, deps)) {
83
85
  logReuse(deps, opts, local, 'local');
84
86
  return emit({ ok: true, status: 'ok', message: 'asset already in local recall library' }, ctx);
85
87
  }
@@ -88,7 +90,7 @@ export async function runReuseCommand(argv, deps = {}) {
88
90
  return emit({ ok: true, status: 'dry_run', message: `would fetch ${opts.id} and write it to the local recall library` }, ctx);
89
91
  }
90
92
  // 3) Pull the global asset by id, write it into the local recall library (put dedups → idempotent on repeat).
91
- const hub = deps.hub ?? createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
93
+ const hub = deps.hub ?? createReuseFetcherFromEnv(env, deps);
92
94
  // One-shot CLIs never heartbeat, so the hub may hold no env fingerprint for this node and its anti-abuse
93
95
  // layer then 403s /a2a/fetch (`bulk_fetch_blocked: IP antibody`, #555). A fingerprinted hello
94
96
  // (rotate:false + preserveCredentials:true) neither requests nor applies credential mutation while establishing
@@ -98,14 +100,53 @@ export async function runReuseCommand(argv, deps = {}) {
98
100
  const asset = await hub.fetchAssetById(opts.id);
99
101
  if (!asset)
100
102
  return emit({ ok: false, status: 'not_found', message: `asset ${opts.id} not found on the hub` }, ctx);
101
- const cleaned = await ingestHubAsset(store, deps, asset, opts.id);
102
- logReuse(deps, opts, cleaned, 'hub');
103
- return emit({ ok: true, status: 'ok', message: 'reused into local recall library' }, ctx);
103
+ const { record, verified } = await ingestHubAsset(store, deps, asset, opts.id);
104
+ logReuse(deps, opts, record, 'hub');
105
+ // Both land the asset (exit 0). A verified reuse is a plain success; an unverified one is a first-class
106
+ // success too — the operator's save happened — but carries reason `unverified` so the desktop adapter can
107
+ // surface "added (unverified)" instead of a plain "added". status stays `ok` so older desktop builds, which
108
+ // key success on status==='ok' and ignore reason, keep working unchanged.
109
+ return emit(verified
110
+ ? { ok: true, status: 'ok', message: 'reused into local recall library' }
111
+ : {
112
+ ok: true,
113
+ status: 'ok',
114
+ reason: 'unverified',
115
+ message: 'reused into local recall library as untrusted: hub-delivered content does not match its content fingerprint and could not be verified',
116
+ }, ctx);
104
117
  }
105
118
  catch (e) {
106
119
  return emit(mapError(e), ctx);
107
120
  }
108
121
  }
122
+ function createReuseFetcherFromEnv(env, deps) {
123
+ const hubMode = configuredHubMode(env);
124
+ if (hubMode === 'public') {
125
+ return createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
126
+ }
127
+ const proxy = (deps.resolveProxyClient ?? proxyClientFromEnv)(env);
128
+ if (!proxy)
129
+ throw new Error('private Hub proxy is not configured');
130
+ return {
131
+ fetchAssetById: async (assetId) => {
132
+ const body = await proxy.fetchAsset({ assetId, expectedHubMode: 'private' });
133
+ const root = recordValue(body);
134
+ const payload = recordValue(root['payload']);
135
+ const assets = Array.isArray(root['assets']) ? root['assets'] : Array.isArray(payload['assets']) ? payload['assets'] : [];
136
+ const asset = assets.find((candidate) => {
137
+ const record = recordValue(candidate);
138
+ return record['asset_id'] === assetId || record['id'] === assetId;
139
+ });
140
+ return asset && typeof asset === 'object' && !Array.isArray(asset) ? asset : null;
141
+ },
142
+ };
143
+ }
144
+ function configuredHubMode(env) {
145
+ const value = String(env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase();
146
+ if (value === 'public' || value === 'private')
147
+ return value;
148
+ throw new Error('EVOMAP_HUB_MODE must be public or private');
149
+ }
109
150
  /** Flags this CLI understands. parseReuseArgs walks argv and rejects anything outside this set with reason
110
151
  * `unsupported` so a typoed flag never silently falls through to a Hub round-trip — review blocker on V1 #283
111
152
  * (the previous tightening lived only in cliContracts.ts; dispatch.ts routes `reuse` here, so this is the path
@@ -176,54 +217,67 @@ class ReuseIntegrityError extends Error {
176
217
  const INTEGRITY_MISMATCH_MESSAGE = 'hub-delivered content does not match the asset content fingerprint';
177
218
  const INTEGRITY_BACKFILLED_MESSAGE = 'hub delivered a synthesized payload for this asset; the original published content is unavailable for verification';
178
219
  const INTEGRITY_LOGICAL_ID_MESSAGE = 'hub-delivered asset does not match the requested logical id';
179
- function integrityError(content) {
180
- const backfilled = stringField(content, 'payload_backfill_reason') !== undefined;
181
- return new ReuseIntegrityError(backfilled ? INTEGRITY_BACKFILLED_MESSAGE : INTEGRITY_MISMATCH_MESSAGE);
220
+ function integrityError(synthesized) {
221
+ return new ReuseIntegrityError(synthesized ? INTEGRITY_BACKFILLED_MESSAGE : INTEGRITY_MISMATCH_MESSAGE);
182
222
  }
183
223
  async function ingestHubAsset(store, deps, asset, requestedId) {
184
- const cleaned = stripHubMetadata(unwrapHubAssetContent(asset));
224
+ const delivered = stripHubMetadata(unwrapHubAssetContent(asset));
225
+ // `payload_backfill_reason` is a hub DELIVERY marker (unwrapHubAssetContent lifts it onto the content so a
226
+ // synthesized payload can be classified). It is NOT publisher content, so it must be excluded from EVERY hash
227
+ // — identity, the local-conflict check, AND the stored bytes — and never persisted. Capture the
228
+ // classification fact, then drop the marker ONCE, up front: hashing it here but stripping it before storage
229
+ // made assertNoLocalReuseIdConflict hash a different byte string than what landed on disk, throwing a false
230
+ // id conflict on the second reuse of the same synthesized asset (Bugbot HIGH, broke idempotency).
231
+ const synthesized = stringField(delivered, 'payload_backfill_reason') !== undefined;
232
+ const cleaned = withoutHubDeliveryMarkers(delivered);
185
233
  const actualAssetId = wire.computeAssetId(cleaned);
186
234
  const contentAssetId = stringField(cleaned, 'asset_id');
187
- if (!actualAssetId || !contentAssetId || actualAssetId !== contentAssetId) {
188
- throw integrityError(cleaned);
235
+ if (!actualAssetId || !contentAssetId) {
236
+ // Malformed beyond classification — no computable hash or no declared id — stays a hard reject.
237
+ throw integrityError(synthesized);
189
238
  }
190
- if (isContentAssetId(requestedId) && actualAssetId !== requestedId) {
191
- throw integrityError(cleaned);
239
+ // Identity guards stay STRICT: a hub that returned a DIFFERENT asset than requested (a self-consistent asset
240
+ // B under a request for A, or a different logical id) is a delivery fault, not the hub's known content-rewrite
241
+ // of the RIGHT asset — reject it so a reuse never silently pulls the wrong gene.
242
+ if (isContentAssetId(requestedId)) {
243
+ if (contentAssetId !== requestedId)
244
+ throw integrityError(synthesized);
192
245
  }
193
- if (!isContentAssetId(requestedId) && stringField(cleaned, 'id') !== requestedId) {
246
+ else if (stringField(cleaned, 'id') !== requestedId) {
194
247
  throw new ReuseIntegrityError(INTEGRITY_LOGICAL_ID_MESSAGE);
195
248
  }
196
- await assertNoLocalReuseIdConflict(cleaned, store);
197
249
  const provenance = new assetstore.ProvenanceStore(storeBaseDir(store, deps));
198
- const stored = await assetstore.ingestUntrusted(store, provenance, cleaned, 'hub');
199
- return { ...cleaned, asset_id: stored.asset_id };
200
- }
201
- async function resolveLocalReuseAsset(store, id) {
202
- const direct = await store.get(id);
203
- if (direct)
204
- return direct;
205
- for (const kind of ['Gene', 'Capsule']) {
206
- const rows = await store.list(kind, 10_000);
207
- const match = rows.find((row) => stringField(row, 'id') === id || String(row.asset_id) === id);
208
- if (match)
209
- return match;
250
+ // Identity is confirmed; now content integrity. When the (marker-free) payload hashes to its declared id it
251
+ // lands verified (still sidecar-marked untrusted per #30). When it does NOT, the hub rewrote the delivered
252
+ // bytes of the right asset (#570) — DOWNGRADE instead of reject: freeze it under the network id and mark it
253
+ // unverified so the save actually happens and the loop (which already reuses hub content without
254
+ // re-verifying) can use it, while trust-first selection keeps it out of the reasoning pool until promotion.
255
+ if (actualAssetId === contentAssetId) {
256
+ const stored = await assetstore.ingestUntrustedConditional(store, provenance, cleaned);
257
+ if (stored.status === 'logical_collision')
258
+ throw new Error('local asset id conflict');
259
+ return { record: { ...cleaned, asset_id: stored.asset_id }, verified: true };
210
260
  }
211
- return null;
212
- }
213
- async function assertNoLocalReuseIdConflict(asset, store) {
214
- if (asset.type !== 'Gene' && asset.type !== 'Capsule')
215
- return;
216
- const id = stringField(asset, 'id');
217
- if (!id)
218
- return;
219
- const rows = await store.list(asset.type, 10_000);
220
- const local = rows.find((row) => stringField(row, 'id') === id);
221
- if (!local)
222
- return;
223
- const incomingAssetId = wire.computeAssetId(asset);
224
- const localAssetId = wire.computeAssetId(local);
225
- if (incomingAssetId !== localAssetId)
261
+ const reason = synthesized ? 'unverified_hub_synthesized' : 'unverified_hub_rewrite';
262
+ const stored = await assetstore.ingestUnverifiedConditional(store, provenance, cleaned, reason);
263
+ if (stored.status === 'logical_collision')
226
264
  throw new Error('local asset id conflict');
265
+ return { record: { ...cleaned, asset_id: stored.asset_id }, verified: false };
266
+ }
267
+ /**
268
+ * Drop hub DELIVERY markers that unwrapHubAssetContent lifts onto the content for classification but that must
269
+ * never reach content-addressed storage. Right now that is `payload_backfill_reason`; keeping this as a named
270
+ * helper localizes the "these keys describe HOW the hub delivered the asset, not the asset" rule.
271
+ */
272
+ function withoutHubDeliveryMarkers(asset) {
273
+ const rest = { ...asset };
274
+ delete rest['payload_backfill_reason'];
275
+ return rest;
276
+ }
277
+ async function resolveLocalReuseAsset(store, id) {
278
+ // A logical id does not identify an asset type. Gene and Capsule ids may overlap, so only the Hub can resolve
279
+ // which remote asset the caller requested; treating either local type as a hit can silently reuse the wrong one.
280
+ return isContentAssetId(id) ? store.get(id) : null;
227
281
  }
228
282
  function unwrapHubAssetContent(asset) {
229
283
  const payload = asset.payload;
@@ -245,7 +299,25 @@ function stripHubMetadata(asset) {
245
299
  return out;
246
300
  }
247
301
  function storeBaseDir(store, deps) {
248
- return store instanceof assetstore.LocalJsonlProvider ? store.baseDir : deps.assetsDir ?? events.assetsDir();
302
+ return store instanceof assetstore.LocalJsonlProvider
303
+ ? store.baseDir
304
+ : deps.assetsDir ?? events.assetsDir(deps.env ?? process.env);
305
+ }
306
+ function isUnsafeUnverifiedLocalAsset(asset, store, deps) {
307
+ if (wire.verifyAssetId(asset))
308
+ return false;
309
+ const record = new assetstore.ProvenanceStore(storeBaseDir(store, deps)).get(asset.asset_id);
310
+ if (record?.trusted === true || record?.decision !== undefined)
311
+ return false;
312
+ const supportedReason = (record?.source === 'hub'
313
+ && (record.reason === 'unverified_hub_rewrite' || record.reason === 'unverified_hub_synthesized')) || (record?.source === 'migrated' && record.reason === 'unverified_gepx_import');
314
+ const isActiveWaiver = supportedReason
315
+ && record.trusted === false
316
+ && record.decision === undefined
317
+ && record.decidedBy === undefined
318
+ && record.promotedBy === undefined
319
+ && record.frozenContentId === wire.computeAssetId(asset);
320
+ return !isActiveWaiver;
249
321
  }
250
322
  function stringField(record, key) {
251
323
  const value = record[key];
@@ -256,15 +328,26 @@ function isContentAssetId(value) {
256
328
  }
257
329
  function logReuse(deps, opts, asset, source) {
258
330
  // AssetCallLog.append is best-effort (never throws) — a logging failure must not break the reuse write.
259
- const callLog = deps.callLog ?? new hubNs.AssetCallLog(events.assetCallLogPath());
260
- callLog.append({
261
- action: 'asset_reuse',
262
- asset_id: asset.asset_id,
263
- asset_type: asset.type,
264
- mode: opts.mode,
265
- ...(opts.runId ? { run_id: opts.runId } : {}),
266
- extra: { source },
267
- });
331
+ const callLog = deps.callLog ?? new hubNs.AssetCallLog(events.assetCallLogPath(deps.env ?? process.env));
332
+ let indexedTokenCost;
333
+ try {
334
+ indexedTokenCost = callLog.assetCostIndex?.()[asset.asset_id];
335
+ }
336
+ catch { /* fall back to the estimator */ }
337
+ const savings = hubNs.reuseSavingsForAsset(asset, opts.mode, indexedTokenCost);
338
+ try {
339
+ callLog.append({
340
+ action: opts.mode === 'reference' ? 'asset_reference' : 'asset_reuse',
341
+ asset_id: asset.asset_id,
342
+ asset_type: asset.type,
343
+ mode: opts.mode,
344
+ tokens_saved: savings.tokens_saved,
345
+ tokens_saved_basis: savings.tokens_saved_basis,
346
+ ...(opts.runId ? { run_id: opts.runId } : {}),
347
+ extra: { source },
348
+ });
349
+ }
350
+ catch { /* an injected logger must preserve the production logger's non-fatal contract */ }
268
351
  }
269
352
  async function establishReuseTrust(hub) {
270
353
  if (typeof hub.hello !== 'function')
@@ -287,6 +370,9 @@ function hubErrorField(body) {
287
370
  const err = body['error'];
288
371
  return typeof err === 'string' ? err : undefined;
289
372
  }
373
+ function recordValue(value) {
374
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
375
+ }
290
376
  function mapError(e) {
291
377
  if (e instanceof ReuseIntegrityError) {
292
378
  return { ok: false, status: 'integrity_failed', message: e.message };
@@ -318,6 +404,15 @@ function mapError(e) {
318
404
  // a bad URL is a configuration gap, NOT an auth failure — conflating them would tell the operator/desktop adapter
319
405
  // to "log in" when the real fix is to correct the Hub URL.
320
406
  const msg = e instanceof Error ? e.message : String(e);
407
+ if (/failed to load EVOLVER_ENV_FILE/i.test(msg)) {
408
+ return { ok: false, status: 'unavailable', message: 'failed to load EVOLVER_ENV_FILE' };
409
+ }
410
+ if (/EVOMAP_HUB_MODE must be public or private/i.test(msg)) {
411
+ return { ok: false, status: 'unavailable', message: 'EVOMAP_HUB_MODE must be public or private' };
412
+ }
413
+ if (/private Hub proxy is not configured/i.test(msg)) {
414
+ return { ok: false, status: 'unavailable', message: 'private Hub proxy is not configured' };
415
+ }
321
416
  if (/Hub URL|EVOMAP_HUB_URL|A2A_HUB_URL/i.test(msg)) {
322
417
  return { ok: false, status: 'unavailable', message: redact(msg) };
323
418
  }
@@ -332,7 +427,7 @@ function mapError(e) {
332
427
  function emit(outcome, ctx) {
333
428
  if (ctx.jsonOut) {
334
429
  // stdout ONLY, exactly one object — the desktop adapter json.Unmarshals the whole stdout stream.
335
- const envelope = { ok: outcome.ok, contract: REUSE_CONTRACT, status: outcome.status, reason: outcome.status, message: outcome.message };
430
+ const envelope = { ok: outcome.ok, contract: REUSE_CONTRACT, status: outcome.status, reason: outcome.reason ?? outcome.status, message: outcome.message };
336
431
  ctx.stdout(JSON.stringify(envelope));
337
432
  }
338
433
  else if (outcome.ok) {
@@ -7,32 +7,32 @@ export const RUNTIME_CAPABILITY_MATRIX = {
7
7
  runtime: 'claude-code',
8
8
  ingest: supported('normalized Claude Code JSONL adapter'),
9
9
  inject: supported('MCP registration plus SessionStart hook'),
10
- execute: supported('run-verified claude -p runner'),
11
- verify: supported('git diff proof plus external validation hook'),
12
- resume: unsupported('cycle runner does not bind ingested session ids to claude resume'),
10
+ execute: unsupported('built-in Claude is fail-closed until host filesystem and network containment is verified'),
11
+ verify: unsupported('no safely runnable autonomous Claude verification path'),
12
+ resume: unsupported('native session identity mapping is implemented, but built-in Claude execution is disabled until host containment is verified'),
13
13
  },
14
14
  codex: {
15
15
  runtime: 'codex',
16
16
  ingest: supported('normalized Codex rollout adapter'),
17
17
  inject: supported('project MCP config plus SessionStart hook'),
18
- execute: supported('run-verified codex exec runner'),
19
- verify: supported('git diff proof plus external validation hook'),
18
+ execute: unsupported('built-in Codex is fail-closed because workspace-write does not contain host filesystem reads'),
19
+ verify: unsupported('no safely runnable autonomous Codex verification path without external host containment'),
20
20
  resume: unsupported('cycle runner starts a new codex exec session'),
21
21
  },
22
22
  cursor: {
23
23
  runtime: 'cursor',
24
24
  ingest: supported('Cursor transcript and state.vscdb adapters'),
25
25
  inject: supported('always-on project rules injection'),
26
- execute: experimental('CLI flags are contract-tested but the repository still treats the runner as a scaffold'),
27
- verify: supported('git diff proof plus external validation hook'),
28
- resume: unsupported('no verified headless session resume mapping'),
26
+ execute: unsupported('headless Cursor workspace trust grants uncontained host filesystem and network access'),
27
+ verify: unsupported('no safely runnable autonomous Cursor execution path'),
28
+ resume: unsupported('native session identity mapping is implemented, but autonomous Cursor execution is disabled until host filesystem and network containment are verified'),
29
29
  },
30
30
  gemini: {
31
31
  runtime: 'gemini',
32
32
  ingest: supported('normalized Gemini CLI session adapter'),
33
33
  inject: unsupported('no Evolver Gemini injection installer'),
34
- execute: experimental('hermetic Gemini CLI 0.46.0 headless JSON contract exists, but provider-backed live E2E smoke is not complete'),
35
- verify: experimental('hermetic structured-result and git-diff proof contract exists, but provider-backed live E2E verification is not complete'),
34
+ execute: experimental('Gemini CLI 0.46.0 deterministic real-runtime cycle smoke passed; provider-backed live E2E smoke is not complete'),
35
+ verify: experimental('real CLI edit, independent validation, Git patch proof, and cleanup passed with deterministic responses; provider-backed live E2E verification is not complete'),
36
36
  resume: unsupported('Gemini resume accepts latest/index; ingested UUIDs cannot be mapped reliably'),
37
37
  },
38
38
  antigravity: {
@@ -45,7 +45,7 @@ export const RUNTIME_CAPABILITY_MATRIX = {
45
45
  },
46
46
  kimi: {
47
47
  runtime: 'kimi',
48
- ingest: supported('normalized Kimi session adapter'),
48
+ ingest: experimental('registered parser for the documented Kimi wire.jsonl shape; no sanitized real-log golden fixture'),
49
49
  inject: unsupported('no Evolver Kimi injection installer'),
50
50
  execute: unsupported('no verified Kimi runner contract'),
51
51
  verify: unsupported('no Kimi execution runner exists'),
@@ -53,16 +53,16 @@ export const RUNTIME_CAPABILITY_MATRIX = {
53
53
  },
54
54
  kiro: {
55
55
  runtime: 'kiro',
56
- ingest: supported('normalized Kiro session adapter'),
57
- inject: unsupported('automatic Kiro setup is not available on the current main branch'),
56
+ ingest: unsupported('transcript adapter is not registered; no real-log golden fixture'),
57
+ inject: supported('verified Kiro MCP config installer for tool discovery; no lifecycle prompt injection'),
58
58
  execute: unsupported('no verified Kiro runner contract'),
59
59
  verify: unsupported('no Kiro execution runner exists'),
60
60
  resume: unsupported('no verified Kiro resume contract'),
61
61
  },
62
62
  opencode: {
63
63
  runtime: 'opencode',
64
- ingest: supported('normalized OpenCode session adapter'),
65
- inject: unsupported('automatic OpenCode setup is not available on the current main branch'),
64
+ ingest: unsupported('transcript adapter is not registered; no real-log golden fixture'),
65
+ inject: supported('verified OpenCode MCP config installer for tool discovery; no lifecycle prompt injection'),
66
66
  execute: unsupported('no verified OpenCode runner contract'),
67
67
  verify: unsupported('no OpenCode execution runner exists'),
68
68
  resume: unsupported('no verified OpenCode resume contract'),
@@ -3,6 +3,7 @@ export interface RuntimeSessionSource {
3
3
  agent: string;
4
4
  label: string;
5
5
  sessionId?: string;
6
+ resumeIdentityProvenance?: 'canonical_native_transcript';
6
7
  turns: NormalizedTurn[];
7
8
  }
8
9
  export interface RuntimeSessionParseDiagnostics {
@@ -15,5 +16,5 @@ export interface RuntimeSessionParseResult {
15
16
  diagnostics: RuntimeSessionParseDiagnostics;
16
17
  }
17
18
  export declare function isRuntimeSessionSourcePath(path: string): boolean;
18
- export declare function parseRuntimeSessionSourcesWithDiagnostics(path: string, readSource?: (path: string) => string): RuntimeSessionParseResult;
19
- export declare function parseRuntimeSessionSources(path: string, readSource?: (path: string) => string): RuntimeSessionSource[];
19
+ export declare function parseRuntimeSessionSourcesWithDiagnostics(path: string, readSource?: (path: string) => string, nativeSessionHome?: string): RuntimeSessionParseResult;
20
+ export declare function parseRuntimeSessionSources(path: string, readSource?: (path: string) => string, nativeSessionHome?: string): RuntimeSessionSource[];
@@ -1,7 +1,25 @@
1
- import { readFileSync } from 'node:fs';
2
- import { resolve } from 'node:path';
1
+ import { readFileSync, realpathSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { isAbsolute, join, relative, resolve } from 'node:path';
3
4
  import { adapterForPath, isCursorStateVscdbPath, parseJsonlLinesWithStats, parseCursorStateVscdb, stripUtf8Bom, } from '@evomap/evolver-runtime-adapters';
4
5
  const EMPTY_DIAGNOSTICS = { rowsScanned: 0, rowsRead: 0, invalidJson: 0 };
6
+ function canonicalNativeSessionSource(path, agent, nativeSessionHome) {
7
+ const runtimeRoot = agent === 'claude-code'
8
+ ? join(nativeSessionHome, '.claude', 'projects')
9
+ : agent === 'cursor' ? join(nativeSessionHome, '.cursor', 'projects') : undefined;
10
+ if (!runtimeRoot)
11
+ return path;
12
+ try {
13
+ const canonicalRoot = realpathSync(runtimeRoot);
14
+ const canonicalPath = realpathSync(path);
15
+ const child = relative(canonicalRoot, canonicalPath);
16
+ return child !== '' && !child.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`)
17
+ && child !== '..' && !isAbsolute(child) ? canonicalPath : undefined;
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ }
5
23
  export function isRuntimeSessionSourcePath(path) {
6
24
  return isCursorStateVscdbPath(path) || adapterForPath(path) !== undefined;
7
25
  }
@@ -28,7 +46,7 @@ function diagnosticsForRuntimeSource(raw) {
28
46
  return parseJsonlLinesWithStats(raw).stats;
29
47
  }
30
48
  }
31
- export function parseRuntimeSessionSourcesWithDiagnostics(path, readSource = (p) => readFileSync(p, 'utf8')) {
49
+ export function parseRuntimeSessionSourcesWithDiagnostics(path, readSource = (p) => readFileSync(p, 'utf8'), nativeSessionHome = homedir()) {
32
50
  const absPath = resolve(path);
33
51
  if (isCursorStateVscdbPath(absPath)) {
34
52
  const sources = parseCursorStateVscdb(absPath)
@@ -39,18 +57,52 @@ export function parseRuntimeSessionSourcesWithDiagnostics(path, readSource = (p)
39
57
  const adapter = adapterForPath(absPath);
40
58
  if (!adapter)
41
59
  return { sources: [], diagnostics: { ...EMPTY_DIAGNOSTICS } };
42
- const raw = readSource(absPath);
43
- const sessionId = adapter.sessionIdFromPath?.(absPath)?.trim();
44
- return {
45
- sources: [{
60
+ const canonicalResumeSource = adapter.resumeIdentityFromSource
61
+ ? canonicalNativeSessionSource(absPath, adapter.agent, nativeSessionHome)
62
+ : undefined;
63
+ const raw = readSource(canonicalResumeSource ?? absPath);
64
+ const nativeResumeIdentity = adapter.resumeIdentityFromSource && canonicalResumeSource
65
+ ? adapter.resumeIdentityFromSource(canonicalResumeSource, raw)
66
+ : undefined;
67
+ if (adapter.resumeIdentityFromSource) {
68
+ const sessionId = nativeResumeIdentity?.sessionId.trim();
69
+ return {
70
+ sources: [{
71
+ agent: adapter.agent,
72
+ label: sessionId ? `${adapter.agent}:${sessionId}` : adapter.agent,
73
+ ...(sessionId ? { sessionId } : {}),
74
+ ...(sessionId ? { resumeIdentityProvenance: 'canonical_native_transcript' } : {}),
75
+ turns: adapter.parse(raw),
76
+ }],
77
+ diagnostics: diagnosticsForRuntimeSource(raw),
78
+ };
79
+ }
80
+ const pathSessionId = adapter.sessionIdFromPath?.(absPath)?.trim();
81
+ const parsedSessions = adapter.parseSessions?.(raw)
82
+ ?? (adapter.parseSession ? [adapter.parseSession(raw)] : []);
83
+ const sources = parsedSessions.length > 0
84
+ ? parsedSessions.map((session, index) => {
85
+ const sessionId = pathSessionId ?? session.sessionId?.trim();
86
+ return {
46
87
  agent: adapter.agent,
47
- label: sessionId ? `${adapter.agent}:${sessionId}` : adapter.agent,
88
+ label: sessionId
89
+ ? `${adapter.agent}:${sessionId}`
90
+ : parsedSessions.length > 1 ? `${adapter.agent}:${index + 1}` : adapter.agent,
48
91
  ...(sessionId ? { sessionId } : {}),
92
+ turns: session.turns,
93
+ };
94
+ })
95
+ : [{
96
+ agent: adapter.agent,
97
+ label: pathSessionId ? `${adapter.agent}:${pathSessionId}` : adapter.agent,
98
+ ...(pathSessionId ? { sessionId: pathSessionId } : {}),
49
99
  turns: adapter.parse(raw),
50
- }],
100
+ }];
101
+ return {
102
+ sources,
51
103
  diagnostics: diagnosticsForRuntimeSource(raw),
52
104
  };
53
105
  }
54
- export function parseRuntimeSessionSources(path, readSource = (p) => readFileSync(p, 'utf8')) {
55
- return parseRuntimeSessionSourcesWithDiagnostics(path, readSource).sources;
106
+ export function parseRuntimeSessionSources(path, readSource = (p) => readFileSync(p, 'utf8'), nativeSessionHome = homedir()) {
107
+ return parseRuntimeSessionSourcesWithDiagnostics(path, readSource, nativeSessionHome).sources;
56
108
  }
@@ -0,0 +1,8 @@
1
+ export type ConfiguredSelectionPolicy = 'engine-health' | 'ucb1-shadow' | 'ucb1';
2
+ export type ConfiguredSelectionGuard = 'legacy' | 'shadow' | 'enforce';
3
+ /** Unknown values fail safe to the current production policy. */
4
+ export declare function selectionPolicyFromEnv(env?: NodeJS.ProcessEnv): ConfiguredSelectionPolicy;
5
+ /** Unknown values fail safe to the production relevance guard. */
6
+ export declare function selectionGuardFromEnv(env?: NodeJS.ProcessEnv): ConfiguredSelectionGuard;
7
+ /** Optional score floor. Invalid values are omitted so core keeps its declared default. */
8
+ export declare function selectionFloorFromEnv(env?: NodeJS.ProcessEnv): number | undefined;
@@ -0,0 +1,18 @@
1
+ /** Unknown values fail safe to the current production policy. */
2
+ export function selectionPolicyFromEnv(env = process.env) {
3
+ const value = env['EVOLVER_SELECTION_POLICY']?.trim().toLowerCase();
4
+ return value === 'ucb1-shadow' || value === 'ucb1' ? value : 'engine-health';
5
+ }
6
+ /** Unknown values fail safe to the production relevance guard. */
7
+ export function selectionGuardFromEnv(env = process.env) {
8
+ const value = env['EVOLVER_SELECTION_GUARD']?.trim().toLowerCase();
9
+ return value === 'legacy' || value === 'shadow' ? value : 'enforce';
10
+ }
11
+ /** Optional score floor. Invalid values are omitted so core keeps its declared default. */
12
+ export function selectionFloorFromEnv(env = process.env) {
13
+ const raw = env['EVOLVER_SELECTION_FLOOR']?.trim();
14
+ if (!raw)
15
+ return undefined;
16
+ const value = Number(raw);
17
+ return Number.isFinite(value) && value >= 0 && value <= 1 ? value : undefined;
18
+ }
@@ -0,0 +1,2 @@
1
+ /** Semantic IDF is default-on; exact `0` is the emergency rollback value. */
2
+ export declare function semanticIdfEnabled(env?: NodeJS.ProcessEnv): boolean;
@@ -0,0 +1,4 @@
1
+ /** Semantic IDF is default-on; exact `0` is the emergency rollback value. */
2
+ export function semanticIdfEnabled(env = process.env) {
3
+ return env['EVOLVER_SEMANTIC_IDF'] !== '0';
4
+ }
@@ -0,0 +1,37 @@
1
+ import { events, material as materialNs } from '@evomap/evolver-core';
2
+ import { type RuntimeSessionMaterialSnapshotV1 } from './materialSnapshot.js';
3
+ import { type RuntimeSessionParseDiagnostics } from './runtimeSessionSource.js';
4
+ /** Material consumer group shared by ingestion and the downstream cycle consumer. */
5
+ export declare const INGEST_CONSUMER_GROUP = "cycle";
6
+ /** Injectable substrate dependencies for session and trace ingestion. */
7
+ export interface IngestDeps {
8
+ materialStore?: materialNs.MaterialStore;
9
+ watermarkStore?: materialNs.WatermarkStore;
10
+ ingestor?: events.Ingestor;
11
+ /** User home whose native runtime directories may contribute resumable session identities. */
12
+ nativeSessionHome?: string;
13
+ }
14
+ export interface SessionIngestTickResult {
15
+ recorded: number;
16
+ sourceAgents: string[];
17
+ signalKinds: string[];
18
+ signalStrengths: string[];
19
+ invalidJsonRows?: number;
20
+ /** Cursor databases that could not be opened or parsed; no path or native error text is exposed. */
21
+ parseFailures?: number;
22
+ }
23
+ export declare function resolveIngestDeps(deps: IngestDeps): {
24
+ materialStore: materialNs.MaterialStore;
25
+ watermarkStore: materialNs.WatermarkStore;
26
+ ingestor: events.Ingestor;
27
+ };
28
+ export declare function toMaterialSourceAgent(agent: string): materialNs.BuildMaterialInput['sourceAgent'] | undefined;
29
+ export declare function recordSessionMaterial(sourceAgent: materialNs.BuildMaterialInput['sourceAgent'], absPath: string, signalCount: number, deps: ReturnType<typeof resolveIngestDeps>, recordCount?: number, payload?: RuntimeSessionMaterialSnapshotV1, diagnostics?: RuntimeSessionParseDiagnostics): Promise<{
30
+ recorded: boolean;
31
+ emitted: boolean;
32
+ materialId?: string;
33
+ }>;
34
+ /** Recursively enumerate recognized runtime-session sources, skipping inaccessible directories. */
35
+ export declare function scanSessionDirs(dirs: readonly string[]): string[];
36
+ /** Record all new or changed runtime sessions as material for the auto-distill loop. */
37
+ export declare function runSessionIngestTick(dirs: readonly string[], deps?: IngestDeps): Promise<SessionIngestTickResult>;