@evomap/evolver-cli 2.0.36 → 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.
Files changed (40) hide show
  1. package/dist/antiGeneRollout.d.ts +2 -0
  2. package/dist/antiGeneRollout.js +21 -3
  3. package/dist/assetTrust.js +9 -0
  4. package/dist/atpAutoDeliver.d.ts +10 -0
  5. package/dist/atpAutoDeliver.js +28 -1
  6. package/dist/autoRecall.js +8 -4
  7. package/dist/autoexec.d.ts +15 -0
  8. package/dist/autoexec.js +148 -7
  9. package/dist/autoexecConfig.d.ts +1 -1
  10. package/dist/autoexecConfig.js +1 -1
  11. package/dist/cliContracts.d.ts +7 -2
  12. package/dist/cliContracts.js +97 -13
  13. package/dist/cursorRewrite.d.ts +6 -0
  14. package/dist/cursorRewrite.js +64 -6
  15. package/dist/cycleConsumer.js +1 -0
  16. package/dist/index.js +11 -3
  17. package/dist/localPublishBinding.d.ts +25 -0
  18. package/dist/localPublishBinding.js +139 -0
  19. package/dist/promptRecallHook.js +86 -10
  20. package/dist/recall.d.ts +2 -0
  21. package/dist/recall.js +19 -1
  22. package/dist/recipe.d.ts +5 -1
  23. package/dist/recipe.js +123 -42
  24. package/dist/referenceAccess.d.ts +3 -0
  25. package/dist/referenceAccess.js +232 -0
  26. package/dist/referencePublish.d.ts +4 -0
  27. package/dist/referencePublish.js +40 -0
  28. package/dist/requiredSandboxValidation.js +6 -1
  29. package/dist/reviewFilter.d.ts +1 -1
  30. package/dist/reviewFilter.js +12 -1
  31. package/dist/sourceQualification.d.ts +2 -0
  32. package/dist/sourceQualification.js +120 -0
  33. package/dist/taskCommitments.d.ts +135 -0
  34. package/dist/taskCommitments.js +492 -0
  35. package/dist/taskReceiver.d.ts +151 -0
  36. package/dist/taskReceiver.js +459 -0
  37. package/dist/thesis.d.ts +3 -0
  38. package/dist/thesis.js +122 -100
  39. package/dist/workflowRuntime.js +13 -2
  40. package/package.json +7 -7
@@ -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;
@@ -235,14 +295,20 @@ function localRecallFilesWithinBudget(store) {
235
295
  function yieldToEventLoop() {
236
296
  return new Promise((resolve) => setImmediate(resolve));
237
297
  }
238
- async function selectPromptGenes(prompt, store, review, provenance, maxGenes, budget) {
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(' ');
245
- const approved = await assetstore.listApprovedGenes(store, review, PROMPT_RECALL_SCAN_LIMIT, provenance);
306
+ const receipts = new Map();
307
+ const approved = await assetstore.listApprovedGenes(store, review, PROMPT_RECALL_SCAN_LIMIT, provenance, {
308
+ ...(benchmark ? { benchmark } : {}),
309
+ onQualification: (values) => { for (const receipt of values)
310
+ receipts.set(receipt.assetId, receipt); },
311
+ });
246
312
  if (selectionExpired(budget))
247
313
  return [];
248
314
  const ranked = [];
@@ -251,7 +317,7 @@ async function selectPromptGenes(prompt, store, review, provenance, maxGenes, bu
251
317
  return [];
252
318
  const gene = approved[index];
253
319
  const signalsMatch = boundedSignalPatterns(gene);
254
- const literalHits = literalSignalHits(promptIndex, signalsMatch);
320
+ const literalHits = literalSignalHits(promptIndex, signalsMatch, literalSegments);
255
321
  if (literalHits > 0) {
256
322
  const semanticScore = signals.tagOverlapScore(promptTokens, {
257
323
  signalsMatch,
@@ -264,6 +330,7 @@ async function selectPromptGenes(prompt, store, review, provenance, maxGenes, bu
264
330
  literalHits,
265
331
  semanticScore,
266
332
  assetKey: String(gene.asset_id).slice(0, 128),
333
+ ...(receipts.has(gene.asset_id) ? { sourceQualification: receipts.get(gene.asset_id) } : {}),
267
334
  });
268
335
  }
269
336
  if ((index + 1) % PROMPT_RECALL_YIELD_EVERY_GENES === 0) {
@@ -277,7 +344,7 @@ async function selectPromptGenes(prompt, store, review, provenance, maxGenes, bu
277
344
  ranked.sort((left, right) => (right.literalHits - left.literalHits
278
345
  || right.semanticScore - left.semanticScore
279
346
  || left.assetKey.localeCompare(right.assetKey)));
280
- return ranked.slice(0, maxGenes);
347
+ return ranked.slice(0, benchmark ? Math.min(maxGenes, 8) : maxGenes);
281
348
  }
282
349
  function renderGeneLine(gene) {
283
350
  const id = (typeof gene['id'] === 'string' ? gene['id'] : String(gene.asset_id)).slice(0, 128);
@@ -334,6 +401,7 @@ function logPromptRecallSelections(genes, mode, sessionId, env, injectedLog) {
334
401
  attribution: 'correlational_local',
335
402
  origin: 'local',
336
403
  literal_hits: ranked.literalHits,
404
+ ...(ranked.sourceQualification ? assetstore.compactQualificationReceipts([ranked.sourceQualification]) : {}),
337
405
  },
338
406
  });
339
407
  }
@@ -391,8 +459,16 @@ export async function runPromptRecallHook(argv, deps = {}) {
391
459
  throw new Error('unexpected hook event');
392
460
  }
393
461
  const prompt = input.prompt;
394
- if (typeof prompt !== 'string' || prompt.trim().length < 8)
462
+ if (typeof prompt !== 'string')
395
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
+ }
396
472
  const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
397
473
  // These cold-loaded JSONL files are parsed synchronously inside the existing store/ledger APIs. Preflight
398
474
  // their footprint before entering those APIs so an append-only sidecar cannot defeat the hook deadline.
@@ -401,7 +477,7 @@ export async function runPromptRecallHook(argv, deps = {}) {
401
477
  const review = deps.review ?? assetstore.reviewLedgerForStore(store);
402
478
  const provenance = deps.provenance ?? assetstore.provenanceStoreForStore(store);
403
479
  const timeoutMs = deps.selectionTimeoutMs ?? PROMPT_RECALL_SELECTION_TIMEOUT_MS;
404
- const ranked = await withSelectionBudget(timeoutMs, [], (budget) => selectPromptGenes(prompt, store, review, provenance, promptRecallMaxGenes(env), budget));
480
+ const ranked = await withSelectionBudget(timeoutMs, [], (budget) => selectPromptGenes(prompt, store, review, provenance, promptRecallMaxGenes(env), budget, assetstore.benchmarkContext(env['EVOLVER_BENCHMARK_ID'])));
405
481
  if (ranked.length > 0) {
406
482
  const rendered = renderPromptRecallContext(ranked);
407
483
  if (rendered.text) {
package/dist/recall.d.ts CHANGED
@@ -20,6 +20,8 @@ export declare function sessionIdFromTranscript(p: string): string | undefined;
20
20
  export declare function pickInjectEvent(evts: readonly events.ReportEvent[], sessionId?: string): events.ReportEvent | undefined;
21
21
  export declare function geneIdsOf(e: events.ReportEvent | undefined): string[];
22
22
  export declare function geneFromAsset(a: assetstore.AssetRecord): ops.GeneRecallInput;
23
+ /** 仅来源资格事件中的实际 canonical 引用保留版本身份,历史和独立手动参数仍按 logical ID 归因。 */
24
+ export declare function geneFromRecallSelection(asset: assetstore.AssetRecord, requestedId: string, inject?: events.ReportEvent): ops.GeneRecallInput | null;
23
25
  export declare function resolveGene(store: Pick<assetstore.AssetStoreProvider, 'get' | 'list'>, id: string): Promise<assetstore.AssetRecord | null>;
24
26
  export declare function runRecall(argv: readonly string[], deps?: RecallCliDeps): Promise<number>;
25
27
  /** Registry-shaped handler (argv -> exit code). */
package/dist/recall.js CHANGED
@@ -43,6 +43,17 @@ export function geneFromAsset(a) {
43
43
  const summary = typeof a['summary'] === 'string' ? a['summary'] : undefined;
44
44
  return { geneId, ...(strategy ? { strategy } : {}), ...(summary ? { summary } : {}) };
45
45
  }
46
+ /** 仅来源资格事件中的实际 canonical 引用保留版本身份,历史和独立手动参数仍按 logical ID 归因。 */
47
+ export function geneFromRecallSelection(asset, requestedId, inject) {
48
+ const canonicalReference = inject?.payload?.['sourceQualificationSchema'] === 'benchmark-source-references.v1'
49
+ && geneIdsOf(inject).includes(requestedId);
50
+ if (!canonicalReference)
51
+ return geneFromAsset(asset);
52
+ // 自定义 provider 或旧 logical-ID fallback 返回其他版本时,不能借用被注入资产的身份。
53
+ if (asset.asset_id !== requestedId)
54
+ return null;
55
+ return { ...geneFromAsset(asset), geneId: requestedId };
56
+ }
46
57
  // Resolve a --gene argument to its Gene asset, mirroring `evolver review`: an asset_id (sha256:…) hits the index
47
58
  // directly (guarded to type Gene, since asset_id is a content hash), while a LOGICAL id (the `gene-a` style id that
48
59
  // value.inject records in geneIds) falls back to a bounded Gene-only scan. Resolving via asset_id ALONE would report
@@ -83,6 +94,7 @@ export async function runRecall(argv, deps = {}) {
83
94
  const log = deps.log ?? ((s) => process.stdout.write(`${s}\n`));
84
95
  const err = deps.err ?? ((s) => process.stderr.write(`${s}\n`));
85
96
  const { transcript, geneIds, fromInject } = parseArgs(argv);
97
+ let selectedInject;
86
98
  // --from-inject: pull the geneIds off the most recent value.inject root_event so the operator does not have to
87
99
  // retype them (a semi-automatic step toward the auto-loop, which still needs the inject<->session key #205 to
88
100
  // pick the RIGHT inject for THIS transcript). Union with any explicit --gene; dedupe preserving order.
@@ -90,6 +102,7 @@ export async function runRecall(argv, deps = {}) {
90
102
  const evts = (deps.readEvents ?? events.readEvents)();
91
103
  const wantSession = transcript ? sessionIdFromTranscript(transcript) : undefined;
92
104
  const picked = pickInjectEvent(evts, wantSession);
105
+ selectedInject = picked;
93
106
  const fromEvent = geneIdsOf(picked);
94
107
  // Empty inject is fatal only when there is nothing else to run; with explicit --gene present, honour the union
95
108
  // and continue (just warn) rather than discarding the genes the operator typed.
@@ -142,7 +155,12 @@ export async function runRecall(argv, deps = {}) {
142
155
  err(`recall: gene not found in local store: ${id}`);
143
156
  continue;
144
157
  }
145
- genes.push(geneFromAsset(a));
158
+ const gene = geneFromRecallSelection(a, id, selectedInject);
159
+ if (!gene) {
160
+ err(`recall: injected gene identity mismatch: ${id}`);
161
+ continue;
162
+ }
163
+ genes.push(gene);
146
164
  }
147
165
  if (genes.length === 0) {
148
166
  err('recall: no resolvable genes');
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,3 @@
1
+ import type { AssetTrustDeps } from './assetTrust.js';
2
+ /** CLI composition只拼接runtime证据与core策略;不执行冻结轨迹中的命令。 */
3
+ export declare function runReferenceAccessCommand(argv: readonly string[], deps: AssetTrustDeps): Promise<number>;