@evomap/evolver-cli 2.0.37 → 2.0.38

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/autoexec.js CHANGED
@@ -79,6 +79,13 @@ function validationCommandDisplay(cmd) {
79
79
  }
80
80
  export function summarizeSandboxedValidation(result) {
81
81
  const parts = [];
82
+ if (result.failureReason)
83
+ parts.push(result.failureReason);
84
+ if (result.isolationTier !== undefined) {
85
+ parts.push(result.isolationTier === 'no-network'
86
+ ? 'isolation: no-network (private root, read-only source; no aggregate cgroup limits)'
87
+ : `isolation: ${result.isolationTier}`);
88
+ }
82
89
  if (result.skipped.length > 0) {
83
90
  const skipped = result.skipped.map((item) => clippedValidationText(`node ${item.script} (${item.reason})`));
84
91
  parts.push(`skipped ${result.skipped.length} validation command(s): ${skipped.join('; ')}`);
@@ -1661,6 +1668,8 @@ export async function runAutoExec(argv) {
1661
1668
  results: r.results,
1662
1669
  skipped: r.skipped,
1663
1670
  isolated: r.isolated,
1671
+ ...(r.isolationTier !== undefined ? { isolationTier: r.isolationTier } : {}),
1672
+ ...(r.failureReason !== undefined ? { failureReason: r.failureReason } : {}),
1664
1673
  },
1665
1674
  };
1666
1675
  },
@@ -1,8 +1,9 @@
1
1
  import { assetstore, hub } from '@evomap/evolver-core';
2
+ import { type LocalPublishVerifierClient } from './localPublishBinding.js';
2
3
  type WritableLike = {
3
4
  write(chunk: string): unknown;
4
5
  };
5
- type ContractReason = 'missing_id' | 'cli_unavailable' | 'auth_required' | 'not_found' | 'network_error' | 'unsupported' | 'internal_error' | 'redaction_unavailable' | 'leak_detected' | 'schema_invalid' | 'bundle_required' | 'quality_gate_failed' | 'gene_unproven' | 'insufficient_credits' | 'unsafe_validation_command';
6
+ type ContractReason = 'missing_id' | 'cli_unavailable' | 'auth_required' | 'not_found' | 'network_error' | 'unsupported' | 'internal_error' | 'redaction_unavailable' | 'leak_detected' | 'schema_invalid' | 'bundle_required' | 'quality_gate_failed' | 'gene_unproven' | 'insufficient_credits' | 'unsafe_validation_command' | 'verification_required';
6
7
  export interface ReuseParseResult {
7
8
  ok: boolean;
8
9
  assetId?: string;
@@ -18,6 +19,7 @@ export interface PublishParseResult {
18
19
  dryRun?: boolean;
19
20
  repair?: boolean;
20
21
  noRecipe?: boolean;
22
+ reverify?: boolean;
21
23
  jsonOut?: boolean;
22
24
  reason?: ContractReason;
23
25
  message?: string;
@@ -31,7 +33,7 @@ interface GateSummary {
31
33
  quality_evidence?: PublishQualityEvidenceSource;
32
34
  validation_command?: 'pass' | 'fail';
33
35
  }
34
- type PublishQualityEvidenceSource = 'local_history' | 'bundle_seed' | 'none' | 'unavailable';
36
+ type PublishQualityEvidenceSource = 'local_history' | 'bundle_seed' | 'reference_integrity' | 'none' | 'unavailable';
35
37
  interface PublishAssetSummary {
36
38
  asset_id?: string;
37
39
  type?: assetstore.AssetKind;
@@ -63,6 +65,8 @@ interface ContractHubTransport {
63
65
  composeRecipe?(payload: hub.RecipeComposeInput): Promise<hub.RecipeComposeResult>;
64
66
  }
65
67
  interface PrivateContractProxy {
68
+ authorizeAssetPublication?: LocalPublishVerifierClient['authorizeAssetPublication'];
69
+ reverifyAssets?: LocalPublishVerifierClient['reverifyAssets'];
66
70
  status(): Promise<unknown>;
67
71
  fetchAsset(args: {
68
72
  assetId: string;
@@ -96,6 +100,7 @@ export declare function runPublishCommand(args: readonly string[], deps?: CliCon
96
100
  export declare function parseReuseArgs(args: readonly string[]): ReuseParseResult;
97
101
  export declare function parsePublishArgs(args: readonly string[]): PublishParseResult;
98
102
  export declare function buildPublishBundle(refs: readonly string[], deps?: CliContractDeps): Promise<PublishBundleResult>;
103
+ export declare function assessPublishRecords(original: assetstore.AssetRecord[], deps: CliContractDeps): Promise<PublishBundleResult>;
99
104
  /** Resolve `<asset_id|logical_id|path>` the way publish does. Shared so `asset-repair` speaks the same refs. */
100
105
  export declare function loadAssetRef(ref: string, deps: CliContractDeps): Promise<assetstore.AssetRecord>;
101
106
  export declare function hasExplicitValidatePass(body: unknown): boolean;
@@ -1,12 +1,14 @@
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 { assetrepair, assetstore, events, hub, wire, algo, verify } from '@evomap/evolver-core';
5
- import { AuthError, HubClientError, HubFetch, HubUnreachableError, connectPublicHub, gepEnvelope, globalFetchLike, resolveHubUrl, } from '@evomap/evolver-adapter-public';
4
+ import { assetrepair, assetstore, events, hub, wire, algo, verify, reference } from '@evomap/evolver-core';
5
+ import { hasReferenceEvidenceMode, validateReferencePublishBundle, validReferenceReceipt } from './referencePublish.js';
6
+ import { AuthError, HubClientError, HubFetch, HubUnreachableError, connectPublicHub, gepEnvelope, globalFetchLike, isHubDryRunEnabled, resolveHubUrl, } from '@evomap/evolver-adapter-public';
6
7
  import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
7
8
  import { resolveAtpSenderId } from './atp.js';
8
9
  import { storeRepairedAsset } from './repairedAssetStore.js';
9
10
  import { resolveExplicitNodeCredentials, resolveIdentityHome } from './identityHome.js';
11
+ import { LocalPublishBindingError, reverifyPublishBundle, withLocalPublishBinding, } from './localPublishBinding.js';
10
12
  const REUSE_CONTRACT = 'reuse.v1';
11
13
  const PUBLISH_CONTRACT = 'publish.v1';
12
14
  const REVERSIBILITY = 'irreversible';
@@ -19,6 +21,8 @@ const PUBLISH_USAGE = [
19
21
  'usage: evolver publish --asset <gene_id_or_path> --asset <capsule_id_or_path> --json [--dry-run] [--repair] [--no-recipe]',
20
22
  ' evolver publish --gene <id_or_path> --capsule <id_or_path> --json [--dry-run] [--no-recipe]',
21
23
  ' evolver publish --gene <id_or_path> --auto-pair --json [--dry-run] [--no-recipe]',
24
+ ' evolver publish --gene <id_or_path> --capsule <id_or_path> --reverify --json [--no-recipe]',
25
+ ' --reverify 明确请求本机宿主重新验证并保存新资产;不改写原资产,不与 --dry-run/--repair 合用。',
22
26
  ].join('\n');
23
27
  const ASSET_FLAGS = new Set(['--asset', '--gene', '--capsule', '--event']);
24
28
  const STABLE_CONTRACT_REASONS = new Set([
@@ -37,6 +41,7 @@ const STABLE_CONTRACT_REASONS = new Set([
37
41
  'gene_unproven',
38
42
  'insufficient_credits',
39
43
  'unsafe_validation_command',
44
+ 'verification_required',
40
45
  ]);
41
46
  const HUB_METADATA_KEYS = new Set([
42
47
  'credit_cost',
@@ -136,7 +141,7 @@ export async function runPublishCommand(args, deps = {}) {
136
141
  }
137
142
  const parsed = parsePublishArgs(args);
138
143
  if (!parsed.ok || !parsed.assetRefs) {
139
- return writeJson(out, publishFailure(parsed.reason ?? 'bundle_required', parsed.message ?? publishReasonMessage('bundle_required'), { retryable: false }), 1, deps);
144
+ return writeJson(out, publishFailure(parsed.reason ?? 'bundle_required', parsed.message ?? publishReasonMessage('bundle_required'), { retryable: false, mode: parsed.dryRun ? 'dry_run' : 'publish' }), 1, deps);
140
145
  }
141
146
  const assetRefs = parsed.assetRefs;
142
147
  let runtimeDeps;
@@ -152,16 +157,38 @@ export async function runPublishCommand(args, deps = {}) {
152
157
  mode: parsed.dryRun ? 'dry_run' : 'publish',
153
158
  }), 1, deps);
154
159
  }
155
- const write = (value, code) => writeJson(out, value, code, runtimeDeps);
160
+ if (parsed.reverify && isHubDryRunEnabled(runtimeDeps.env ?? {})) {
161
+ return writeJson(out, publishFailure('unsupported', '--reverify cannot be combined with HUB_DRY_RUN', {
162
+ retryable: false, mode: 'dry_run',
163
+ }), 1, runtimeDeps);
164
+ }
165
+ let reverification;
166
+ const write = (value, code) => writeJson(out, reverification && asRecord(value) ? { ...asRecord(value), reverification } : value, code, runtimeDeps);
156
167
  return withMachineJsonConsole(Boolean(parsed.jsonOut), runtimeDeps, async () => {
157
168
  try {
158
169
  const effectiveRefs = parsed.autoPair
159
170
  ? await autoPairPublishRefs(assetRefs, parsed.geneRef, runtimeDeps)
160
171
  : assetRefs;
161
- const bundle = await buildPublishBundle(effectiveRefs, runtimeDeps);
172
+ let bundle = await buildPublishBundle(effectiveRefs, runtimeDeps);
162
173
  if (!bundle.ok) {
163
174
  return write(publishFailure(bundle.reason, bundle.message, { retryable: false, gates: bundle.gates }), 1);
164
175
  }
176
+ const referenceOnly = bundle.gates.quality_evidence === 'reference_integrity';
177
+ if (referenceOnly && (parsed.reverify || parsed.repair || configuredHubMode(runtimeDeps.env ?? {}) === 'private')) {
178
+ return write(publishFailure('unsupported', 'reference publication requires the public Hub and immutable assets; execution reverify and repair are not supported', {
179
+ retryable: false, mode: parsed.dryRun ? 'dry_run' : 'publish', gates: bundle.gates,
180
+ }), 1);
181
+ }
182
+ if (parsed.reverify && bundle.blockReasons.every((reason) => reason === 'gene_unproven')) {
183
+ const verified = await reverifyPublishBundle(bundle.original, runtimeDeps.env ?? {}, runtimeDeps.resolveProxyClient);
184
+ reverification = {
185
+ applied: true, original_assets_unchanged: true, stored: verified.stored,
186
+ source_asset_ids: verified.sourceAssetIds, asset_ids: verified.assets.map((asset) => asset.asset_id),
187
+ };
188
+ bundle = await assessPublishRecords(verified.assets.map(normalizeAsset), runtimeDeps);
189
+ if (!bundle.ok)
190
+ return write(publishFailure(bundle.reason, bundle.message, { retryable: false, gates: bundle.gates }), 1);
191
+ }
165
192
  if (bundle.blockReasons.length > 0) {
166
193
  if (parsed.dryRun)
167
194
  return write(dryRunEnvelope(bundle), 0);
@@ -175,7 +202,7 @@ export async function runPublishCommand(args, deps = {}) {
175
202
  }), 1);
176
203
  }
177
204
  const transport = deps.transport ?? createDefaultTransport(runtimeDeps, {
178
- composeRecipe: parsed.noRecipe !== true,
205
+ composeRecipe: !referenceOnly && parsed.noRecipe !== true,
179
206
  });
180
207
  const validate = deps.validate ?? transport.validate;
181
208
  // A field-level refusal is a defect in the RECORD, not a verdict on the work in it. Read the Hub's own
@@ -215,6 +242,11 @@ export async function runPublishCommand(args, deps = {}) {
215
242
  ...repairEnvelopeField(validationAttempt),
216
243
  }), 1);
217
244
  }
245
+ if (referenceOnly && !validReferenceReceipt(validation.body, bundle.sanitized, true)) {
246
+ return write(publishFailure('quality_gate_failed', 'reference validation response does not attest the submitted non-execution pair', {
247
+ retryable: false, mode: parsed.dryRun ? 'dry_run' : 'publish', gates: { ...bundle.gates, quality: 'fail' },
248
+ }), 1);
249
+ }
218
250
  if (parsed.dryRun)
219
251
  return write(dryRunEnvelope(bundle, validationCredits, undefined, validationAttempt), 0);
220
252
  const publish = deps.publish ?? transport.publish;
@@ -236,6 +268,20 @@ export async function runPublishCommand(args, deps = {}) {
236
268
  ...repairEnvelopeField(repairApplied),
237
269
  }), 1);
238
270
  }
271
+ if (referenceOnly) {
272
+ if (!validReferenceReceipt(published.body, bundle.sanitized, false)) {
273
+ return write(publishFailure('quality_gate_failed', 'reference publication lacks a matching stored_reference receipt; persistence is unconfirmed', {
274
+ retryable: false, mode: 'publish', gates: { ...bundle.gates, quality: 'fail' }, assets: bundle.assets,
275
+ }), 1);
276
+ }
277
+ const payload = payloadRecord(published.body);
278
+ return write({
279
+ ok: true, contract: PUBLISH_CONTRACT, mode: 'publish', status: 'stored_reference',
280
+ reversibility: REVERSIBILITY, evidence_mode: 'reference_only', ...reference.REFERENCE_ELIGIBILITY,
281
+ bundle_id: payload['bundle_id'], gene_asset_id: payload['gene_asset_id'], capsule_asset_id: payload['capsule_asset_id'],
282
+ credit_reward: 0, gates: bundle.gates, assets: bundle.assets,
283
+ }, 0);
284
+ }
239
285
  // The repaired records are what the network now holds. Persist them so the local library and the Hub do
240
286
  // not silently diverge; a storage failure is reported, never fatal — the publish already happened.
241
287
  const repairPersisted = repairApplied?.applied === true
@@ -292,10 +338,10 @@ export async function runPublishCommand(args, deps = {}) {
292
338
  }
293
339
  catch (err) {
294
340
  const failure = classifyError(err, 'publish', runtimeDeps.env ?? process.env);
295
- return write(publishFailure(failure.reason, failure.message, {
296
- retryable: failure.retryable,
297
- mode: parsed.dryRun ? 'dry_run' : 'publish',
298
- }), 1);
341
+ return write({ ...publishFailure(failure.reason, failure.message, {
342
+ retryable: failure.retryable,
343
+ mode: parsed.dryRun ? 'dry_run' : 'publish',
344
+ }), ...(err instanceof LocalPublishBindingError && err.recovery ? { recovery: err.recovery } : {}) }, 1);
299
345
  }
300
346
  });
301
347
  }
@@ -443,6 +489,7 @@ export function parsePublishArgs(args) {
443
489
  let dryRun = false;
444
490
  let repair = false;
445
491
  let noRecipe = false;
492
+ let reverify = false;
446
493
  let jsonOut = false;
447
494
  for (let i = 0; i < args.length; i++) {
448
495
  const token = args[i];
@@ -468,6 +515,10 @@ export function parsePublishArgs(args) {
468
515
  noRecipe = true;
469
516
  continue;
470
517
  }
518
+ if (token === '--reverify') {
519
+ reverify = true;
520
+ continue;
521
+ }
471
522
  const equalFlag = [...ASSET_FLAGS].find((flag) => token.startsWith(`${flag}=`));
472
523
  if (equalFlag) {
473
524
  const value = token.slice(equalFlag.length + 1).trim();
@@ -512,6 +563,10 @@ export function parsePublishArgs(args) {
512
563
  }
513
564
  if (!jsonOut)
514
565
  return { ok: false, reason: 'unsupported', message: 'publish requires --json' };
566
+ if (reverify && (dryRun || repair))
567
+ return {
568
+ ok: false, dryRun, reason: 'unsupported', message: '--reverify cannot be combined with --dry-run or --repair; verification never runs implicitly',
569
+ };
515
570
  if (autoPair && (geneCount !== 1 || !geneRef || capsuleRef || hasUntypedAsset)) {
516
571
  return { ok: false, reason: 'bundle_required', message: '--auto-pair requires exactly one explicit --gene and no --asset or --capsule' };
517
572
  }
@@ -528,6 +583,7 @@ export function parsePublishArgs(args) {
528
583
  dryRun,
529
584
  repair,
530
585
  ...(noRecipe ? { noRecipe: true } : {}),
586
+ ...(reverify ? { reverify: true } : {}),
531
587
  jsonOut,
532
588
  };
533
589
  }
@@ -550,12 +606,26 @@ export async function buildPublishBundle(refs, deps = {}) {
550
606
  gates: reason === 'schema_invalid' ? { schema: 'fail' } : {},
551
607
  };
552
608
  }
609
+ return assessPublishRecords(original, deps);
610
+ }
611
+ export async function assessPublishRecords(original, deps) {
553
612
  const bundleCheck = checkBundle(original);
554
613
  if (!bundleCheck.ok)
555
614
  return { ok: false, reason: 'bundle_required', message: bundleCheck.message, gates: { schema: 'pass', bundle: 'fail' } };
615
+ const referenceOnly = hasReferenceEvidenceMode(original);
616
+ if (referenceOnly) {
617
+ try {
618
+ validateReferencePublishBundle(original);
619
+ }
620
+ catch (error) {
621
+ const message = error instanceof Error && /^reference_[a-z_]+$/.test(error.message)
622
+ ? error.message : 'reference_integrity_invalid';
623
+ return { ok: false, reason: 'schema_invalid', message, gates: { schema: 'fail', quality: 'fail' } };
624
+ }
625
+ }
556
626
  let sanitized;
557
627
  try {
558
- sanitized = sanitizePublishBundle(original);
628
+ sanitized = referenceOnly ? structuredClone(original) : sanitizePublishBundle(original);
559
629
  }
560
630
  catch {
561
631
  return { ok: false, reason: 'redaction_unavailable', message: 'redaction unavailable', gates: { redaction: 'unavailable' } };
@@ -571,7 +641,9 @@ export async function buildPublishBundle(refs, deps = {}) {
571
641
  // leaks to the Hub and comes back as an opaque `quality_gate_failed` after a
572
642
  // round-trip. Assessing the gene's outcome evidence here fails fast, locally,
573
643
  // with a precise reason. Read-only: aggregates the local capsule history.
574
- const geneEvidence = await assessPublishGeneEvidence(original, deps);
644
+ const geneEvidence = referenceOnly
645
+ ? { eligible: true, source: 'reference_integrity' }
646
+ : await assessPublishGeneEvidence(original, deps);
575
647
  const geneProven = geneEvidence?.eligible ?? true;
576
648
  // Local quality gate: validation command safety check.
577
649
  // Only applies to Gene assets. Checks that all validation commands are safe
@@ -727,6 +799,10 @@ function checkValidationCommands(original) {
727
799
  }
728
800
  function sanitizePublishBundle(original) {
729
801
  const sanitized = original.map((asset) => hub.sanitizeAsset(stripPublishMetadata(asset)));
802
+ // 已绑定记录的 business-id 引用同样属于完整内容,不能在验证后改成另一种引用并重算资产。
803
+ // 脱敏若真正改变内容,后续 host ledger 会要求重新验证;人工无声明路径保留旧引用规范化。
804
+ if (hub.requiresPublishBinding(original))
805
+ return sanitized;
730
806
  const finalGeneIdByOriginalRef = new Map();
731
807
  for (let i = 0; i < original.length; i++) {
732
808
  const source = original[i];
@@ -1006,6 +1082,8 @@ function dryRunEnvelope(bundle, credits, blockDetail, repairAttempt) {
1006
1082
  mode: 'dry_run',
1007
1083
  reversibility: REVERSIBILITY,
1008
1084
  blocked: bundle.blockReasons.length > 0,
1085
+ ...(bundle.gates.quality_evidence === 'reference_integrity'
1086
+ ? { evidence_mode: 'reference_only', ...reference.REFERENCE_ELIGIBILITY } : {}),
1009
1087
  block_reasons: bundle.blockReasons,
1010
1088
  ...(blockDetails.length > 0 ? { block_details: blockDetails } : {}),
1011
1089
  assets: bundle.assets,
@@ -1156,7 +1234,7 @@ function createDefaultTransport(deps, opts = {}) {
1156
1234
  return {
1157
1235
  fetchAssetById: (assetId) => connected.hub.fetchAssetById(assetId),
1158
1236
  validate: (bundle) => call('/a2a/validate', 'validate', bundle),
1159
- publish: (bundle) => call('/a2a/publish', 'publish', bundle),
1237
+ publish: (bundle) => withLocalPublishBinding(bundle, env, (authorized) => call('/a2a/publish', 'publish', authorized), deps.resolveProxyClient),
1160
1238
  ...(opts.composeRecipe === false ? {} : {
1161
1239
  composeRecipe: (payload) => hub.composeRecipeAfterAssetPublish(connected.hub, payload),
1162
1240
  }),
@@ -1282,6 +1360,9 @@ function privatePublishExplicitFailure(body) {
1282
1360
  return root['ok'] === false || root['stored'] === false || payload['ok'] === false || payload['stored'] === false;
1283
1361
  }
1284
1362
  function privateProxyFailure(err) {
1363
+ if (err instanceof Error && /^publish_(?:binding|reverification|verification)_/.test(err.message)) {
1364
+ return { ok: false, status: 422, body: { ok: false, reason: 'verification_required' } };
1365
+ }
1285
1366
  return { ok: false, status: isAuthLikeError(err) ? 401 : 0 };
1286
1367
  }
1287
1368
  function isAuthLikeError(err) {
@@ -1289,6 +1370,8 @@ function isAuthLikeError(err) {
1289
1370
  return /oauth|login|credential|auth|401|403|node_secret/i.test(message);
1290
1371
  }
1291
1372
  function classifyError(err, command, env = {}) {
1373
+ if (err instanceof LocalPublishBindingError)
1374
+ return { reason: 'verification_required', message: err.message, retryable: false };
1292
1375
  if (err instanceof ContractError)
1293
1376
  return { reason: err.reason, message: err.safeMessage, retryable: err.reason === 'network_error' };
1294
1377
  if (err instanceof AuthError)
@@ -1366,6 +1449,7 @@ function publishReasonMessage(reason, env = {}) {
1366
1449
  gene_unproven: 'gene has no proven success yet — run it to a successful outcome before publishing',
1367
1450
  insufficient_credits: 'insufficient credits',
1368
1451
  unsafe_validation_command: 'validation command contains unsafe patterns (e.g., node -e, shell metacharacters) blocked by sandbox security policy',
1452
+ verification_required: '资产需要当前本机宿主验证;请使用 --reverify 或本机重新验证接口',
1369
1453
  };
1370
1454
  return map[reason] ?? map.internal_error;
1371
1455
  }
@@ -0,0 +1,25 @@
1
+ import { assetstore } from '@evomap/evolver-core';
2
+ import { type ProxyAssetBundle, type ProxyAssetReverification, type ProxyReverificationRecovery } from '@evomap/evolver-mcp';
3
+ export interface LocalPublishVerifierClient {
4
+ authorizeAssetPublication(input: ProxyAssetBundle, opts?: {
5
+ signal?: AbortSignal;
6
+ }): Promise<unknown>;
7
+ reverifyAssets(input: ProxyAssetReverification, opts?: {
8
+ signal?: AbortSignal;
9
+ }): Promise<unknown>;
10
+ }
11
+ export type LocalPublishVerifierResolver = (env: NodeJS.ProcessEnv) => Partial<LocalPublishVerifierClient> | undefined;
12
+ export declare class LocalPublishBindingError extends Error {
13
+ readonly reason: string;
14
+ readonly recovery?: ProxyReverificationRecovery;
15
+ constructor(reason: string, recovery?: ProxyReverificationRecovery);
16
+ }
17
+ /** 只消费本机 ledger 的判定;不把客户端 hash、外部 receipt 或未验证的历史声明当作授权。 */
18
+ export declare function withLocalPublishBinding<T>(bundle: readonly assetstore.AssetRecord[], env: NodeJS.ProcessEnv, publish: (assets: assetstore.AssetRecord[]) => Promise<T>, resolveProxy?: LocalPublishVerifierResolver): Promise<T>;
19
+ export interface ReverifiedPublishBundle {
20
+ assets: assetstore.AssetRecord[];
21
+ sourceAssetIds: string[];
22
+ stored: boolean;
23
+ }
24
+ /** 显式迁移产生新记录;原始资产和历史 trace 不原地更新,也不自动广播。 */
25
+ export declare function reverifyPublishBundle(bundle: readonly assetstore.AssetRecord[], env: NodeJS.ProcessEnv, resolveProxy?: LocalPublishVerifierResolver): Promise<ReverifiedPublishBundle>;
@@ -0,0 +1,139 @@
1
+ import { assetstore, hub, wire } from '@evomap/evolver-core';
2
+ import { proxyClientFromEnv, ProxyReverificationError, safeReverificationRecovery, } from '@evomap/evolver-mcp';
3
+ export class LocalPublishBindingError extends Error {
4
+ reason;
5
+ recovery;
6
+ constructor(reason, recovery) {
7
+ super(recovery
8
+ ? `${reason}: 请先检查 source_asset_ids、asset_ids 对应的本机资产与 ledger;状态不明确时勿盲目重新执行 --reverify,不回滚已保存资产或撤销合法回执`
9
+ : reason === 'publish_reverification_unavailable'
10
+ ? `${reason}: 当前本机没有可用的隔离验证器;需配置受支持的 native verifier,不支持的平台保持 draft-only`
11
+ : `${reason}: 请通过当前本机宿主重新验证;使用 evolver publish --gene <id|path> --capsule <id|path> --reverify --json`);
12
+ this.reason = reason;
13
+ if (recovery)
14
+ this.recovery = safeReverificationRecovery(recovery);
15
+ }
16
+ }
17
+ function safeFailureReason(error, fallback, operation = 'reverification') {
18
+ if (error instanceof Error) {
19
+ if (/^publish_(?:binding|reverification)_[a-z_]{1,70}$/.test(error.message))
20
+ return error.message;
21
+ if (error.message === 'proxy_hub_mode_mismatch')
22
+ return 'publish_binding_hub_mode_mismatch';
23
+ if (error.name === 'TimeoutError')
24
+ return `publish_${operation}_timeout`;
25
+ if (error.name === 'AbortError')
26
+ return `publish_${operation}_aborted`;
27
+ }
28
+ return fallback;
29
+ }
30
+ function mode(env) {
31
+ const value = (env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase();
32
+ if (value !== 'public' && value !== 'private')
33
+ throw new LocalPublishBindingError('publish_binding_hub_mode_invalid');
34
+ return value;
35
+ }
36
+ function record(value) {
37
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
38
+ ? value : {};
39
+ }
40
+ function snapshot(bundle) {
41
+ return structuredClone(bundle).map((asset) => assetstore.normalizeForPut(asset).record);
42
+ }
43
+ /** 只消费本机 ledger 的判定;不把客户端 hash、外部 receipt 或未验证的历史声明当作授权。 */
44
+ export async function withLocalPublishBinding(bundle, env, publish, resolveProxy = proxyClientFromEnv) {
45
+ const assets = snapshot(bundle);
46
+ if (!hub.requiresPublishBinding(assets))
47
+ return publish(assets);
48
+ const expectedHubMode = mode(env);
49
+ await authorizeSnapshot(assets, expectedHubMode, resolveProxy(env));
50
+ return publish(assets);
51
+ }
52
+ async function authorizeSnapshot(assets, expectedHubMode, proxy) {
53
+ if (!proxy?.authorizeAssetPublication)
54
+ throw new LocalPublishBindingError('publish_verification_required');
55
+ const digest = hub.publishBundleDigest(assets);
56
+ // 授权 callback 只能持有独立副本;即使其在返回后修改请求,也不能污染 publisher 私有数据。
57
+ const requestAssets = structuredClone(assets);
58
+ const requestDigest = hub.publishBundleDigest(requestAssets);
59
+ let response;
60
+ try {
61
+ response = record(await proxy.authorizeAssetPublication({
62
+ assets: requestAssets, expected_hub_mode: expectedHubMode,
63
+ }, { signal: AbortSignal.timeout(30_000) }));
64
+ }
65
+ catch (error) {
66
+ throw new LocalPublishBindingError(safeFailureReason(error, 'publish_binding_authorization_unavailable', 'binding_authorization'));
67
+ }
68
+ if (response['ok'] !== true || response['binding_verified'] !== true || response['bundle_digest'] !== digest
69
+ || requestDigest !== digest || hub.publishBundleDigest(requestAssets) !== requestDigest
70
+ || hub.publishBundleDigest(assets) !== digest) {
71
+ throw new LocalPublishBindingError('publish_binding_authorization_invalid');
72
+ }
73
+ }
74
+ /** 显式迁移产生新记录;原始资产和历史 trace 不原地更新,也不自动广播。 */
75
+ export async function reverifyPublishBundle(bundle, env, resolveProxy = proxyClientFromEnv) {
76
+ if (bundle.length !== 2)
77
+ throw new LocalPublishBindingError('publish_reverification_pair_required');
78
+ let assets;
79
+ try {
80
+ assets = structuredClone(bundle).map(hub.normalizePublishReverificationSource);
81
+ }
82
+ catch (error) {
83
+ throw new LocalPublishBindingError(safeFailureReason(error, 'publish_reverification_invalid_wire'));
84
+ }
85
+ if (assets.length !== 2 || assets.filter((asset) => asset.type === 'Gene').length !== 1
86
+ || assets.filter((asset) => asset.type === 'Capsule').length !== 1) {
87
+ throw new LocalPublishBindingError('publish_reverification_pair_required');
88
+ }
89
+ const expectedHubMode = mode(env);
90
+ const proxy = resolveProxy(env);
91
+ if (!proxy?.reverifyAssets)
92
+ throw new LocalPublishBindingError('publish_reverification_unavailable');
93
+ const sourceIds = assets.map((asset) => asset.asset_id).sort();
94
+ let response;
95
+ try {
96
+ response = record(await proxy.reverifyAssets({
97
+ assets, persist: true, expected_hub_mode: expectedHubMode,
98
+ }, { signal: AbortSignal.timeout(30_000) }));
99
+ }
100
+ catch (error) {
101
+ throw new LocalPublishBindingError(safeFailureReason(error, 'publish_reverification_failed'), safeReverificationRecovery({
102
+ ...(error instanceof ProxyReverificationError ? error.recovery : {}), source_asset_ids: sourceIds,
103
+ }));
104
+ }
105
+ const recovery = safeReverificationRecovery({
106
+ ...response, source_asset_ids: sourceIds,
107
+ asset_ids: Array.isArray(response['assets']) ? response['assets'].slice(0, 2).map((asset) => record(asset)['asset_id']) : [],
108
+ });
109
+ const returnedSourceIds = response['source_asset_ids'];
110
+ if (response['ok'] !== true || response['status'] !== 'reverified' || response['publishable'] !== true
111
+ || response['queued'] !== false || response['stored'] !== true
112
+ || !Array.isArray(response['assets']) || response['assets'].length !== 2
113
+ || !Array.isArray(returnedSourceIds) || returnedSourceIds.length !== sourceIds.length
114
+ || returnedSourceIds.some((id) => typeof id !== 'string')
115
+ || JSON.stringify([...returnedSourceIds].sort()) !== JSON.stringify(sourceIds)) {
116
+ throw new LocalPublishBindingError('publish_reverification_invalid_response', recovery);
117
+ }
118
+ let verified;
119
+ try {
120
+ verified = snapshot(response['assets']);
121
+ if (verified.filter((asset) => asset.type === 'Gene').length !== 1
122
+ || verified.filter((asset) => asset.type === 'Capsule').length !== 1
123
+ || verified.some((asset) => !wire.validateWireDeep(asset.type === 'Gene' ? wire.stripGeneHints(asset) : asset).ok)) {
124
+ throw new Error('publish_reverification_invalid_assets');
125
+ }
126
+ hub.assertPublishBindingReceipt(verified, response['publish_receipt']);
127
+ }
128
+ catch (error) {
129
+ throw new LocalPublishBindingError(safeFailureReason(error, 'publish_reverification_invalid_assets'), recovery);
130
+ }
131
+ // 显式重新验证无条件读取同一 host ledger,不借用普通人工发布的“无需绑定”早退。
132
+ try {
133
+ await authorizeSnapshot(verified, expectedHubMode, proxy);
134
+ }
135
+ catch (error) {
136
+ throw new LocalPublishBindingError(error instanceof LocalPublishBindingError ? error.reason : 'publish_binding_authorization_unavailable', recovery);
137
+ }
138
+ return { assets: verified, sourceAssetIds: sourceIds, stored: true };
139
+ }
@@ -23,6 +23,7 @@ const PROMPT_RECALL_SIGNAL_ALIAS_TOKENS = 12;
23
23
  const PROMPT_RECALL_TOKEN_CHARS = 96;
24
24
  const PROMPT_RECALL_GENE_FIELD_CHARS = 512;
25
25
  const PROMPT_RECALL_YIELD_EVERY_GENES = 8;
26
+ const NON_SPACE_SCRIPT = /[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Thai}]/u;
26
27
  const PROMPT_RECALL_LOCAL_FILES = [
27
28
  'genes.jsonl',
28
29
  'capsules.jsonl',
@@ -134,6 +135,63 @@ function promptTokenSegments(prompt) {
134
135
  tailTokens,
135
136
  ];
136
137
  }
138
+ function promptLiteralSegments(prompt) {
139
+ const limit = PROMPT_RECALL_MATCH_CHARS;
140
+ const segments = prompt.length <= limit
141
+ ? [prompt]
142
+ : [prompt.slice(0, limit / 2), prompt.slice(-limit / 2)];
143
+ // Keep the windows separate: a signal must never span the omitted middle. Bound normalization expansion too.
144
+ return segments.flatMap((segment, index) => {
145
+ const normalized = segment.toLowerCase().normalize('NFKC');
146
+ if (segments.length === 1 && normalized.length > limit) {
147
+ return [
148
+ { text: normalized.slice(0, limit / 2), cutStart: false, cutEnd: true },
149
+ { text: normalized.slice(-limit / 2), cutStart: true, cutEnd: false },
150
+ ];
151
+ }
152
+ const maxChars = limit / segments.length;
153
+ const isTail = index > 0;
154
+ return [{
155
+ // Preserve the real prompt end when normalization expands the tail window.
156
+ text: isTail ? normalized.slice(-maxChars) : normalized.slice(0, maxChars),
157
+ cutStart: isTail,
158
+ cutEnd: !isTail && (normalized.length > maxChars || segments.length > 1),
159
+ }];
160
+ }).filter((segment) => NON_SPACE_SCRIPT.test(segment.text));
161
+ }
162
+ function hasNonSpaceLetter(text) {
163
+ return Array.from(text).some((character) => NON_SPACE_SCRIPT.test(character) && /\p{L}/u.test(character));
164
+ }
165
+ function containsNonSpaceLiteral(segments, alias) {
166
+ const literal = alias.toLowerCase().normalize('NFKC');
167
+ if (!NON_SPACE_SCRIPT.test(literal))
168
+ return false;
169
+ // Script_Extensions also includes shared punctuation and combining marks, which are not useful signals alone.
170
+ if (!hasNonSpaceLetter(literal) || /^\p{M}/u.test(literal))
171
+ return false;
172
+ const characters = Array.from(literal);
173
+ const runs = literal.match(/[\p{L}\p{N}\p{M}]+/gu) ?? [];
174
+ if (runs.length > PROMPT_RECALL_SIGNAL_ALIAS_TOKENS
175
+ || runs.some((run) => run.length > PROMPT_RECALL_TOKEN_CHARS))
176
+ return false;
177
+ const needsBoundary = (character) => /[\p{L}\p{N}\p{M}]/u.test(character)
178
+ && !NON_SPACE_SCRIPT.test(character);
179
+ const leftBoundary = needsBoundary(characters[0]);
180
+ const rightBoundary = needsBoundary(characters.at(-1));
181
+ for (const { text, cutStart, cutEnd } of segments) {
182
+ for (let at = text.indexOf(literal); at !== -1; at = text.indexOf(literal, at + 1)) {
183
+ if ((at === 0 && cutStart) || (at + literal.length === text.length && cutEnd))
184
+ continue;
185
+ const before = Array.from(text.slice(Math.max(0, at - 2), at)).at(-1) ?? '';
186
+ const after = String.fromCodePoint(text.codePointAt(at + literal.length) ?? 0);
187
+ // Mixed aliases retain Latin word boundaries; a Thai/Kana combining mark must not be cut off.
188
+ if ((!leftBoundary || !needsBoundary(before))
189
+ && (!rightBoundary || !needsBoundary(after)) && !/\p{M}/u.test(after))
190
+ return true;
191
+ }
192
+ }
193
+ return false;
194
+ }
137
195
  function buildPromptSequenceIndex(segments) {
138
196
  const root = { children: new Map() };
139
197
  for (const tokens of segments) {
@@ -173,10 +231,11 @@ function boundedSignalPatterns(gene) {
173
231
  }
174
232
  /**
175
233
  * V1 required a real local signals_match hit before prompt-time injection. Keep that conservative gate: aliases
176
- * separated by `|` are matched as normalized token sequences, while regex-looking patterns are never evaluated
234
+ * separated by `|` are matched as normalized token sequences, with bounded literal matching for scripts that
235
+ * do not require spaces between words. Regex-looking patterns are never evaluated
177
236
  * (a persisted pattern must not be able to run an expensive regular expression on a private prompt).
178
237
  */
179
- function literalSignalHits(promptIndex, patterns) {
238
+ function literalSignalHits(promptIndex, patterns, literalSegments) {
180
239
  let hits = 0;
181
240
  for (const pattern of patterns) {
182
241
  const aliases = pattern.split('|', PROMPT_RECALL_SIGNAL_ALIASES + 1).slice(0, PROMPT_RECALL_SIGNAL_ALIASES);
@@ -186,7 +245,8 @@ function literalSignalHits(promptIndex, patterns) {
186
245
  || trimmed.length > PROMPT_RECALL_SIGNAL_ALIAS_CHARS
187
246
  || (trimmed.startsWith('/') && trimmed.lastIndexOf('/') > 0))
188
247
  return false;
189
- return containsSequence(promptIndex, normalizedAliasTokens(trimmed));
248
+ return containsSequence(promptIndex, normalizedAliasTokens(trimmed))
249
+ || (literalSegments.length > 0 && containsNonSpaceLiteral(literalSegments, trimmed));
190
250
  });
191
251
  if (matched)
192
252
  hits += 1;
@@ -238,7 +298,8 @@ function yieldToEventLoop() {
238
298
  async function selectPromptGenes(prompt, store, review, provenance, maxGenes, budget, benchmark) {
239
299
  const tokenSegments = promptTokenSegments(prompt);
240
300
  const promptTokens = tokenSegments.flat();
241
- if (promptTokens.length === 0)
301
+ const literalSegments = promptLiteralSegments(prompt);
302
+ if (promptTokens.length === 0 && literalSegments.length === 0)
242
303
  return [];
243
304
  const promptIndex = buildPromptSequenceIndex(tokenSegments);
244
305
  const boundedPrompt = promptTokens.join(' ');
@@ -256,7 +317,7 @@ async function selectPromptGenes(prompt, store, review, provenance, maxGenes, bu
256
317
  return [];
257
318
  const gene = approved[index];
258
319
  const signalsMatch = boundedSignalPatterns(gene);
259
- const literalHits = literalSignalHits(promptIndex, signalsMatch);
320
+ const literalHits = literalSignalHits(promptIndex, signalsMatch, literalSegments);
260
321
  if (literalHits > 0) {
261
322
  const semanticScore = signals.tagOverlapScore(promptTokens, {
262
323
  signalsMatch,
@@ -398,8 +459,16 @@ export async function runPromptRecallHook(argv, deps = {}) {
398
459
  throw new Error('unexpected hook event');
399
460
  }
400
461
  const prompt = input.prompt;
401
- if (typeof prompt !== 'string' || prompt.trim().length < 8)
462
+ if (typeof prompt !== 'string')
402
463
  throw new Error('prompt is not recallable');
464
+ const trimmedPrompt = prompt.trim();
465
+ if (trimmedPrompt.length < 8) {
466
+ const normalizedPrompt = trimmedPrompt.toLowerCase().normalize('NFKC');
467
+ if (!hasNonSpaceLetter(normalizedPrompt)
468
+ || (normalizedPrompt.match(/[\p{L}\p{N}]/gu)?.length ?? 0) < 2) {
469
+ throw new Error('prompt is not recallable');
470
+ }
471
+ }
403
472
  const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
404
473
  // These cold-loaded JSONL files are parsed synchronously inside the existing store/ledger APIs. Preflight
405
474
  // their footprint before entering those APIs so an append-only sidecar cannot defeat the hook deadline.
package/dist/recipe.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { assetstore, events, verify, type hub as hubNs } from '@evomap/evolver-core';
1
+ import { assetstore, events, verify, hub as hubNs } from '@evomap/evolver-core';
2
2
  import type { ConnectPublicOptions, PublicHubCapability } from '@evomap/evolver-adapter-public';
3
+ import { type LocalPublishVerifierResolver } from './localPublishBinding.js';
3
4
  export interface RecipeCliDeps {
4
5
  hub?: RecipeHub;
5
6
  store?: assetstore.AssetStoreProvider;
@@ -9,6 +10,8 @@ export interface RecipeCliDeps {
9
10
  ingestor?: events.Ingestor;
10
11
  review?: assetstore.ReviewLedger;
11
12
  runValidation?: typeof verify.runSandboxedValidation;
13
+ /** 仅可信宿主/test composition 可以提供;manifest 和外部 receipt 不能注入此授权。 */
14
+ resolvePublishVerifier?: LocalPublishVerifierResolver;
12
15
  connectHub?: (opts: ConnectPublicOptions) => {
13
16
  hub: PublicHubCapability;
14
17
  auth: hubNs.AuthProvider;
@@ -53,6 +56,7 @@ export interface RecipeFromSkillsOptions {
53
56
  manifestPath: string;
54
57
  publish: boolean;
55
58
  jsonOut: boolean;
59
+ reverify?: boolean;
56
60
  }
57
61
  export interface RecipeSearchOptions {
58
62
  sub: 'search';
package/dist/recipe.js CHANGED
@@ -2,14 +2,15 @@ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, unlinkSync
2
2
  import { createHash } from 'node:crypto';
3
3
  import { homedir } from 'node:os';
4
4
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
- import { assetstore, events, mailbox, verify } from '@evomap/evolver-core';
5
+ import { assetstore, events, mailbox, verify, hub as hubNs } from '@evomap/evolver-core';
6
6
  import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled, isNodeSecret, parseNodeSecretVersion, resolveHubUrl } from '@evomap/evolver-adapter-public';
7
- import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
7
+ import { loadEnvFileFromEnv, safeReverificationRecovery } from '@evomap/evolver-mcp';
8
8
  import { resolveExplicitNodeCredentials } from './identityHome.js';
9
9
  import { getCliVersion } from './version.js';
10
10
  import { parseSkillMd, reverseDistill, synthesizeGene } from './skill2gep.js';
11
11
  import { recordSkillDistillation } from './skillDistill.js';
12
- import { buildPublishBundle } from './cliContracts.js';
12
+ import { assessPublishRecords, buildPublishBundle } from './cliContracts.js';
13
+ import { LocalPublishBindingError, reverifyPublishBundle, withLocalPublishBinding, } from './localPublishBinding.js';
13
14
  const MAX_RECIPE_STEPS = 20;
14
15
  const MAX_RECIPE_VALIDATION_COMMANDS = 5;
15
16
  const MAX_RECIPE_INPUT_BYTES = 1024 * 1024;
@@ -333,9 +334,29 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
333
334
  capsuleId: res.capsuleId,
334
335
  });
335
336
  }
336
- const publishPrepared = await prepareRecipeFromSkillsAssets(distilled, store, dryRun ? undefined : hub, deps.env ?? process.env, io);
337
+ const publishPrepared = await prepareRecipeFromSkillsAssets(distilled, store, dryRun ? undefined : hub, deps.env ?? process.env, io, {
338
+ reverify: opts.reverify === true,
339
+ ...(deps.resolvePublishVerifier ? { resolvePublishVerifier: deps.resolvePublishVerifier } : {}),
340
+ });
337
341
  if (!publishPrepared.ok) {
338
- io.err(publishPrepared.error);
342
+ const failure = {
343
+ ...recipeFromSkillsPayload({
344
+ ok: false, mode: 'failed', title: loaded.value.title, publish: opts.publish,
345
+ steps: publishPrepared.completedSteps, error: publishPrepared.reason,
346
+ }),
347
+ failedPosition: publishPrepared.failedPosition,
348
+ ...(publishPrepared.recovery ? { recovery: publishPrepared.recovery,
349
+ recovery_action: 'inspect_assets_and_ledger_before_retry' } : {}),
350
+ };
351
+ if (opts.jsonOut)
352
+ io.log(JSON.stringify(failure, null, 2));
353
+ else {
354
+ io.err(publishPrepared.error);
355
+ // 文本调用者同样需要前序结果和三态写入信息;只输出已收敛的安全恢复字段。
356
+ if (publishPrepared.recovery || publishPrepared.completedSteps.length > 0) {
357
+ io.err(JSON.stringify(failure, null, 2));
358
+ }
359
+ }
339
360
  return 1;
340
361
  }
341
362
  steps.splice(0, steps.length, ...publishPrepared.value.steps);
@@ -355,6 +376,8 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
355
376
  io.log('[recipe from-skills] dry-run: would publish the recipe after creation.');
356
377
  else
357
378
  io.log('[recipe from-skills] dry-run: would leave the recipe as draft.');
379
+ if (opts.reverify)
380
+ io.log('[recipe from-skills] dry-run: --reverify would request additional local-host validation; no host request was sent.');
358
381
  }
359
382
  return 0;
360
383
  }
@@ -369,7 +392,19 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
369
392
  ...(loaded.value.pricePerExecution !== undefined ? { pricePerExecution: loaded.value.pricePerExecution } : {}),
370
393
  };
371
394
  createRequest.idempotencyKey = recipeIdempotencyKey('create', createRequest);
372
- const createReceipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills', () => hub.recipes.create(createRequest), io);
395
+ let createReceipt;
396
+ try {
397
+ createReceipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills', () => hub.recipes.create(createRequest), io);
398
+ }
399
+ catch (error) {
400
+ if (!opts.jsonOut)
401
+ throw error;
402
+ io.log(JSON.stringify(recipeFromSkillsPayload({
403
+ ok: false, mode: 'failed', title: loaded.value.title, publish: opts.publish,
404
+ steps: distilled, error: 'create_failed',
405
+ }), null, 2));
406
+ return 1;
407
+ }
373
408
  const recipeId = createReceipt.recipeId;
374
409
  if (createReceipt.status !== 'draft') {
375
410
  if (opts.jsonOut) {
@@ -589,49 +624,92 @@ function preflightRecipeFromSkillsSteps(steps) {
589
624
  }
590
625
  return { ok: true, value: prepared };
591
626
  }
592
- async function prepareRecipeFromSkillsAssets(distilled, store, hub, env, io) {
627
+ async function prepareRecipeFromSkillsAssets(distilled, store, hub, env, io, options) {
593
628
  const steps = [];
594
629
  const prepared = [];
595
630
  const publishedByBundle = new Map();
631
+ const reverifiedBySource = new Map();
596
632
  for (const step of distilled) {
597
- const bundle = await buildPublishBundle([step.geneAssetId, step.capsuleId], { assetStore: store, env });
598
- if (!bundle.ok) {
599
- return { ok: false, error: `recipe from-skills step ${step.position + 1} asset bundle rejected: ${bundle.reason}` };
600
- }
601
- if (bundle.blockReasons.length > 0) {
602
- return { ok: false, error: `recipe from-skills step ${step.position + 1} asset bundle rejected: ${bundle.blockReasons.join(',')}` };
603
- }
604
- const gene = bundle.sanitized.find((asset) => asset.type === 'Gene');
605
- const capsule = bundle.sanitized.find((asset) => asset.type === 'Capsule');
606
- if (!gene?.asset_id || !capsule?.asset_id) {
607
- return { ok: false, error: `recipe from-skills step ${step.position + 1} asset bundle is missing Gene or Capsule` };
608
- }
609
- const bundleKey = `${gene.asset_id}\n${capsule.asset_id}`;
610
- let geneAssetId = publishedByBundle.get(bundleKey);
611
- if (!geneAssetId && hub) {
612
- const receipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills asset publish', () => hub.publish(bundle.sanitized), io);
613
- if (!assetPublishSucceeded(receipt, bundle.sanitized)) {
614
- const duplicateIsIncomplete = receipt.status === 'rejected' &&
615
- (receipt.reason === 'already_published' || receipt.reason === 'duplicate');
616
- return {
617
- ok: false,
618
- error: duplicateIsIncomplete
619
- ? `recipe from-skills step ${step.position + 1} duplicate asset publish did not identify the published Gene and Capsule bundle`
620
- : `recipe from-skills step ${step.position + 1} asset publish rejected: ${receipt.reason ?? receipt.status}`,
621
- };
633
+ let recovery;
634
+ const fail = (error, reason = 'asset_prepare_failed') => ({
635
+ ok: false, error, reason, completedSteps: [...prepared], failedPosition: step.position,
636
+ ...(recovery ? { recovery } : {}),
637
+ });
638
+ try {
639
+ let bundle = await buildPublishBundle([step.geneAssetId, step.capsuleId], { assetStore: store, env });
640
+ if (!bundle.ok) {
641
+ return fail(`recipe from-skills step ${step.position + 1} asset bundle rejected: ${bundle.reason}`);
622
642
  }
623
- geneAssetId = publishedGeneAssetId(receipt, gene.asset_id);
624
- if (!geneAssetId) {
625
- return {
626
- ok: false,
627
- error: `recipe from-skills step ${step.position + 1} duplicate asset publish did not identify the published Gene`,
643
+ let reverification;
644
+ if (hub && options.reverify && bundle.blockReasons.every((reason) => reason === 'gene_unproven')) {
645
+ const sourceKey = hubNs.publishBundleDigest(bundle.original);
646
+ let reverified = reverifiedBySource.get(sourceKey);
647
+ if (!reverified) {
648
+ reverified = await reverifyPublishBundle(bundle.original, env, options.resolvePublishVerifier);
649
+ reverifiedBySource.set(sourceKey, reverified);
650
+ }
651
+ reverification = {
652
+ sourceAssetIds: [...reverified.sourceAssetIds],
653
+ assetIds: reverified.assets.map((asset) => asset.asset_id),
654
+ stored: reverified.stored,
628
655
  };
656
+ recovery = safeReverificationRecovery({
657
+ stored: reverified.stored, binding_registered: true,
658
+ source_asset_ids: reverified.sourceAssetIds, asset_ids: reverification.assetIds,
659
+ });
660
+ bundle = await assessPublishRecords(reverified.assets, { assetStore: store, env });
661
+ if (!bundle.ok) {
662
+ return fail(`recipe from-skills step ${step.position + 1} reverified asset bundle rejected: ${bundle.reason}`);
663
+ }
664
+ }
665
+ if (bundle.blockReasons.length > 0) {
666
+ return fail(`recipe from-skills step ${step.position + 1} asset bundle rejected: ${bundle.blockReasons.join(',')}`);
667
+ }
668
+ const publishAssets = bundle.sanitized;
669
+ const gene = publishAssets.find((asset) => asset.type === 'Gene');
670
+ const capsule = publishAssets.find((asset) => asset.type === 'Capsule');
671
+ if (!gene?.asset_id || !capsule?.asset_id) {
672
+ return fail(`recipe from-skills step ${step.position + 1} asset bundle is missing Gene or Capsule`);
673
+ }
674
+ const bundleKey = `${gene.asset_id}\n${capsule.asset_id}`;
675
+ let geneAssetId = publishedByBundle.get(bundleKey);
676
+ if (!geneAssetId && hub) {
677
+ const receipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills asset publish', () => withLocalPublishBinding(publishAssets, env, (authorized) => hub.publish(authorized), options.resolvePublishVerifier), io);
678
+ if (!assetPublishSucceeded(receipt, publishAssets)) {
679
+ const duplicateIsIncomplete = receipt.status === 'rejected' &&
680
+ (receipt.reason === 'already_published' || receipt.reason === 'duplicate');
681
+ return fail(duplicateIsIncomplete
682
+ ? `recipe from-skills step ${step.position + 1} duplicate asset publish did not identify the published Gene and Capsule bundle`
683
+ : `recipe from-skills step ${step.position + 1} asset publish rejected: ${receipt.reason ?? receipt.status}`);
684
+ }
685
+ geneAssetId = publishedGeneAssetId(receipt, gene.asset_id);
686
+ if (!geneAssetId) {
687
+ return fail(`recipe from-skills step ${step.position + 1} duplicate asset publish did not identify the published Gene`);
688
+ }
689
+ publishedByBundle.set(bundleKey, geneAssetId);
690
+ }
691
+ geneAssetId ??= gene.asset_id;
692
+ steps.push({ assetId: geneAssetId, assetType: 'Gene', position: step.position });
693
+ prepared.push({
694
+ ...step,
695
+ geneId: typeof gene['id'] === 'string' ? gene['id'] : geneAssetId,
696
+ geneAssetId,
697
+ capsuleId: typeof capsule['id'] === 'string' ? capsule['id'] : capsule.asset_id,
698
+ ...(reverification ? { reverification } : {}),
699
+ });
700
+ }
701
+ catch (error) {
702
+ if (error instanceof LocalPublishBindingError) {
703
+ recovery = error.recovery ?? recovery;
704
+ return fail(error.message, error.reason);
629
705
  }
630
- publishedByBundle.set(bundleKey, geneAssetId);
706
+ // 网络/存储异常可能包含私有路径或响应;保留固定分类,不反射原始 message/body。
707
+ return fail(error instanceof AuthError
708
+ ? `recipe Hub auth failed (HTTP ${error.status}); run "evolver login" or refresh EVOMAP_NODE_SECRET`
709
+ : error instanceof HubClientError
710
+ ? `recipe Hub call failed (HTTP ${error.status}); 请先核对资产及发布状态,勿盲目重试`
711
+ : `recipe from-skills step ${step.position + 1}: asset_prepare_failed; 请先核对资产及发布状态,勿盲目重试`);
631
712
  }
632
- geneAssetId ??= gene.asset_id;
633
- steps.push({ assetId: geneAssetId, assetType: 'Gene', position: step.position });
634
- prepared.push({ ...step, geneAssetId });
635
713
  }
636
714
  return { ok: true, value: { steps, distilled: prepared } };
637
715
  }
@@ -887,6 +965,7 @@ function recipeFromSkillsPayload(opts) {
887
965
  geneId: step.geneId,
888
966
  geneAssetId: step.geneAssetId,
889
967
  capsuleId: step.capsuleId,
968
+ ...(step.reverification ? { reverification: step.reverification } : {}),
890
969
  })),
891
970
  };
892
971
  }
@@ -949,6 +1028,7 @@ function parseFromSkillsArgs(args) {
949
1028
  manifestPath,
950
1029
  publish: args.includes('--publish'),
951
1030
  jsonOut: args.includes('--json'),
1031
+ ...(args.includes('--reverify') ? { reverify: true } : {}),
952
1032
  },
953
1033
  };
954
1034
  }
@@ -1378,8 +1458,9 @@ function recipeUsage() {
1378
1458
  'Recipe subcommands:',
1379
1459
  ' evolver recipe build --title <title> --genes <asset_id,...> [--description <text>] [--price <n>] [--publish]',
1380
1460
  ' Creates a draft recipe by default. --publish is explicit.',
1381
- ' evolver recipe from-skills --manifest <file> [--publish] [--json]',
1461
+ ' evolver recipe from-skills --manifest <file> [--reverify] [--publish] [--json]',
1382
1462
  ' Distills ordered SKILL.md steps with execution evidence, then creates a recipe.',
1463
+ ' --reverify explicitly reruns validation under the local host before publishing fresh assets; dry-run never calls the host.',
1383
1464
  ' evolver recipe reuse --id <recipe_id> [--input <json-object>] [--json]',
1384
1465
  ' evolver recipe search [--q <text>] [--limit <n>] [--json]',
1385
1466
  ` Default agent lookup. Express a hit with \`${RECIPE_REUSE_COMMAND}\`. Gene/Capsule search is fallback.`,
@@ -0,0 +1,4 @@
1
+ import { assetstore, reference } from '@evomap/evolver-core';
2
+ export declare function hasReferenceEvidenceMode(assets: readonly assetstore.AssetRecord[]): boolean;
3
+ export declare function validateReferencePublishBundle(assets: readonly assetstore.AssetRecord[]): reference.ReferencePair;
4
+ export declare function validReferenceReceipt(body: unknown, assets: readonly assetstore.AssetRecord[], dryRun: boolean): boolean;
@@ -0,0 +1,40 @@
1
+ import { assetstore, hub, reference, wire } from '@evomap/evolver-core';
2
+ export function hasReferenceEvidenceMode(assets) {
3
+ return assets.some((asset) => asset.type === 'Capsule' && asset['evidence_mode'] !== undefined);
4
+ }
5
+ export function validateReferencePublishBundle(assets) {
6
+ if (assets.length !== 2)
7
+ throw new Error('reference_pair_required');
8
+ const pair = reference.decodeReferencePair({
9
+ gene: assets.find((asset) => asset.type === 'Gene'),
10
+ capsule: assets.find((asset) => asset.type === 'Capsule'),
11
+ });
12
+ if (hub.requiresPublishBinding(assets))
13
+ throw new Error('reference_execution_claim_forbidden');
14
+ for (const asset of assets) {
15
+ if (wire.canonicalize(hub.sanitizeAsset(asset)) !== wire.canonicalize(asset)) {
16
+ throw new Error('reference_sanitization_would_change_asset');
17
+ }
18
+ }
19
+ return pair;
20
+ }
21
+ export function validReferenceReceipt(body, assets, dryRun) {
22
+ if (!body || typeof body !== 'object' || Array.isArray(body))
23
+ return false;
24
+ const envelope = body;
25
+ const value = envelope['payload'] ?? envelope;
26
+ if (!value || typeof value !== 'object' || Array.isArray(value))
27
+ return false;
28
+ const payload = value;
29
+ const pair = validateReferencePublishBundle(assets);
30
+ const status = dryRun ? 'validated_reference' : 'stored_reference';
31
+ return payload['decision'] === 'accept' && payload['valid'] === true
32
+ && payload['reason'] === status && payload['status'] === status
33
+ && payload['dry_run'] === dryRun && payload['credit_reward'] === 0
34
+ && payload['evidence_mode'] === 'reference_only'
35
+ && Object.keys(reference.REFERENCE_ELIGIBILITY).every((key) => payload[key] === false)
36
+ && payload['gene_asset_id'] === pair.gene.asset_id
37
+ && payload['capsule_asset_id'] === pair.capsule.asset_id
38
+ && payload['asset_id'] === pair.capsule.asset_id
39
+ && payload['bundle_id'] === reference.referenceBundleId(pair);
40
+ }
@@ -17,10 +17,15 @@ export async function runRequiredSandboxedValidation(commands, cwd, options = {}
17
17
  })),
18
18
  skipped: [],
19
19
  isolated: false,
20
+ isolationTier: 'none',
20
21
  };
21
22
  }
22
23
  const safeCommands = sanitizedPlan.map((command) => command.value);
23
- const result = await runner(safeCommands, cwd, { ...options, requireIsolation: true });
24
+ // AutoExec、distill 与 workflow 共用此入口。默认接受 no-network 的独立根、只读源码和断网边界,
25
+ // 不要求宿主能够只读重挂整棵文件系统或提供聚合 cgroup 限额。调用方明确要求 read-only 时不能降档;
26
+ // 实际采用的档位由 core 回执报告,不能用这里的最低要求代替。无效的运行时值原样交给 core 拒绝。
27
+ const minimumIsolation = options.minimumIsolation === undefined ? 'no-network' : options.minimumIsolation;
28
+ const result = await runner(safeCommands, cwd, { ...options, requireIsolation: true, minimumIsolation });
24
29
  const sanitized = verify.sanitizeExecutionPayload(result);
25
30
  if (!sanitized.blocked)
26
31
  return sanitized.value;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evomap/evolver-cli",
3
- "version": "2.0.37",
3
+ "version": "2.0.38",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -23,12 +23,12 @@
23
23
  }
24
24
  },
25
25
  "dependencies": {
26
- "@evomap/evolver-core": "2.0.37",
27
- "@evomap/evolver-adapter-public": "2.0.37",
28
- "@evomap/evolver-mcp": "2.0.37",
29
- "@evomap/evolver-proxy": "2.0.37",
30
- "@evomap/evolver-runtime-adapters": "2.0.37",
31
- "@evomap/evolver-webui": "2.0.37"
26
+ "@evomap/evolver-core": "2.0.38",
27
+ "@evomap/evolver-adapter-public": "2.0.38",
28
+ "@evomap/evolver-mcp": "2.0.38",
29
+ "@evomap/evolver-proxy": "2.0.38",
30
+ "@evomap/evolver-runtime-adapters": "2.0.38",
31
+ "@evomap/evolver-webui": "2.0.38"
32
32
  },
33
33
  "repository": {
34
34
  "type": "git",