@evomap/evolver-cli 2.0.37 → 2.0.39
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 +9 -0
- package/dist/cliContracts.d.ts +7 -2
- package/dist/cliContracts.js +108 -18
- package/dist/localPublishBinding.d.ts +25 -0
- package/dist/localPublishBinding.js +139 -0
- package/dist/promptRecallHook.js +75 -6
- package/dist/recipe.d.ts +9 -2
- package/dist/recipe.js +185 -54
- package/dist/recipeConsent.d.ts +4 -0
- package/dist/recipeConsent.js +19 -0
- package/dist/referencePublish.d.ts +4 -0
- package/dist/referencePublish.js +40 -0
- package/dist/requiredSandboxValidation.js +6 -1
- package/package.json +7 -7
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
|
},
|
package/dist/cliContracts.d.ts
CHANGED
|
@@ -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;
|
package/dist/cliContracts.js
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
297
|
-
|
|
298
|
-
|
|
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,16 +606,37 @@ 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
|
+
}
|
|
626
|
+
const sourceIntegrity = original.map(hub.checkEmbeddedSourceIntegrity).find((result) => !result.ok);
|
|
627
|
+
if (sourceIntegrity && !sourceIntegrity.ok) {
|
|
628
|
+
return { ok: false, reason: 'schema_invalid', message: sourceIntegrity.reason, gates: { schema: 'fail' } };
|
|
629
|
+
}
|
|
556
630
|
let sanitized;
|
|
557
631
|
try {
|
|
558
|
-
sanitized = sanitizePublishBundle(original);
|
|
632
|
+
sanitized = referenceOnly ? structuredClone(original) : sanitizePublishBundle(original, deps.env ?? process.env);
|
|
559
633
|
}
|
|
560
634
|
catch {
|
|
561
635
|
return { ok: false, reason: 'redaction_unavailable', message: 'redaction unavailable', gates: { redaction: 'unavailable' } };
|
|
562
636
|
}
|
|
637
|
+
if (sanitized.some((asset) => !hub.checkEmbeddedSourceIntegrity(asset).ok)) {
|
|
638
|
+
return { ok: false, reason: 'schema_invalid', message: 'embedded_source_sanitization_changed', gates: { schema: 'fail', redaction: 'fail' } };
|
|
639
|
+
}
|
|
563
640
|
const finalBundleCheck = checkBundle(sanitized);
|
|
564
641
|
if (!finalBundleCheck.ok) {
|
|
565
642
|
return { ok: false, reason: 'bundle_required', message: finalBundleCheck.message, gates: { redaction: 'pass', schema: 'pass', bundle: 'fail' } };
|
|
@@ -571,7 +648,9 @@ export async function buildPublishBundle(refs, deps = {}) {
|
|
|
571
648
|
// leaks to the Hub and comes back as an opaque `quality_gate_failed` after a
|
|
572
649
|
// round-trip. Assessing the gene's outcome evidence here fails fast, locally,
|
|
573
650
|
// with a precise reason. Read-only: aggregates the local capsule history.
|
|
574
|
-
const geneEvidence =
|
|
651
|
+
const geneEvidence = referenceOnly
|
|
652
|
+
? { eligible: true, source: 'reference_integrity' }
|
|
653
|
+
: await assessPublishGeneEvidence(original, deps);
|
|
575
654
|
const geneProven = geneEvidence?.eligible ?? true;
|
|
576
655
|
// Local quality gate: validation command safety check.
|
|
577
656
|
// Only applies to Gene assets. Checks that all validation commands are safe
|
|
@@ -725,8 +804,12 @@ function checkValidationCommands(original) {
|
|
|
725
804
|
message: `validation command rejected: ${[...reasons].join(', ')}`,
|
|
726
805
|
};
|
|
727
806
|
}
|
|
728
|
-
function sanitizePublishBundle(original) {
|
|
729
|
-
const sanitized = original.map((asset) => hub.sanitizeAsset(stripPublishMetadata(asset)));
|
|
807
|
+
function sanitizePublishBundle(original, env) {
|
|
808
|
+
const sanitized = original.map((asset) => hub.sanitizeAsset(stripPublishMetadata(asset), { env }));
|
|
809
|
+
// 已绑定记录的 business-id 引用同样属于完整内容,不能在验证后改成另一种引用并重算资产。
|
|
810
|
+
// 脱敏若真正改变内容,后续 host ledger 会要求重新验证;人工无声明路径保留旧引用规范化。
|
|
811
|
+
if (hub.requiresPublishBinding(original))
|
|
812
|
+
return sanitized;
|
|
730
813
|
const finalGeneIdByOriginalRef = new Map();
|
|
731
814
|
for (let i = 0; i < original.length; i++) {
|
|
732
815
|
const source = original[i];
|
|
@@ -953,9 +1036,8 @@ function checkBundle(bundle) {
|
|
|
953
1036
|
return { ok: true };
|
|
954
1037
|
}
|
|
955
1038
|
function finalPayloadLeakCheck(bundle, env) {
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
return { blocked: hardLeaks.length > 0 };
|
|
1039
|
+
// The shared scan includes assembled source files; serialized fragments can hide scan-only matches.
|
|
1040
|
+
return { blocked: hub.sanitizeBundle(bundle, { env, mode: 'strict' }).blocked };
|
|
959
1041
|
}
|
|
960
1042
|
async function assertNoLocalReuseIdConflict(asset, store) {
|
|
961
1043
|
if (asset.type !== 'Gene' && asset.type !== 'Capsule')
|
|
@@ -1006,6 +1088,8 @@ function dryRunEnvelope(bundle, credits, blockDetail, repairAttempt) {
|
|
|
1006
1088
|
mode: 'dry_run',
|
|
1007
1089
|
reversibility: REVERSIBILITY,
|
|
1008
1090
|
blocked: bundle.blockReasons.length > 0,
|
|
1091
|
+
...(bundle.gates.quality_evidence === 'reference_integrity'
|
|
1092
|
+
? { evidence_mode: 'reference_only', ...reference.REFERENCE_ELIGIBILITY } : {}),
|
|
1009
1093
|
block_reasons: bundle.blockReasons,
|
|
1010
1094
|
...(blockDetails.length > 0 ? { block_details: blockDetails } : {}),
|
|
1011
1095
|
assets: bundle.assets,
|
|
@@ -1156,7 +1240,7 @@ function createDefaultTransport(deps, opts = {}) {
|
|
|
1156
1240
|
return {
|
|
1157
1241
|
fetchAssetById: (assetId) => connected.hub.fetchAssetById(assetId),
|
|
1158
1242
|
validate: (bundle) => call('/a2a/validate', 'validate', bundle),
|
|
1159
|
-
publish: (bundle) => call('/a2a/publish', 'publish',
|
|
1243
|
+
publish: (bundle) => withLocalPublishBinding(bundle, env, (authorized) => call('/a2a/publish', 'publish', authorized), deps.resolveProxyClient),
|
|
1160
1244
|
...(opts.composeRecipe === false ? {} : {
|
|
1161
1245
|
composeRecipe: (payload) => hub.composeRecipeAfterAssetPublish(connected.hub, payload),
|
|
1162
1246
|
}),
|
|
@@ -1282,6 +1366,9 @@ function privatePublishExplicitFailure(body) {
|
|
|
1282
1366
|
return root['ok'] === false || root['stored'] === false || payload['ok'] === false || payload['stored'] === false;
|
|
1283
1367
|
}
|
|
1284
1368
|
function privateProxyFailure(err) {
|
|
1369
|
+
if (err instanceof Error && /^publish_(?:binding|reverification|verification)_/.test(err.message)) {
|
|
1370
|
+
return { ok: false, status: 422, body: { ok: false, reason: 'verification_required' } };
|
|
1371
|
+
}
|
|
1285
1372
|
return { ok: false, status: isAuthLikeError(err) ? 401 : 0 };
|
|
1286
1373
|
}
|
|
1287
1374
|
function isAuthLikeError(err) {
|
|
@@ -1289,6 +1376,8 @@ function isAuthLikeError(err) {
|
|
|
1289
1376
|
return /oauth|login|credential|auth|401|403|node_secret/i.test(message);
|
|
1290
1377
|
}
|
|
1291
1378
|
function classifyError(err, command, env = {}) {
|
|
1379
|
+
if (err instanceof LocalPublishBindingError)
|
|
1380
|
+
return { reason: 'verification_required', message: err.message, retryable: false };
|
|
1292
1381
|
if (err instanceof ContractError)
|
|
1293
1382
|
return { reason: err.reason, message: err.safeMessage, retryable: err.reason === 'network_error' };
|
|
1294
1383
|
if (err instanceof AuthError)
|
|
@@ -1366,6 +1455,7 @@ function publishReasonMessage(reason, env = {}) {
|
|
|
1366
1455
|
gene_unproven: 'gene has no proven success yet — run it to a successful outcome before publishing',
|
|
1367
1456
|
insufficient_credits: 'insufficient credits',
|
|
1368
1457
|
unsafe_validation_command: 'validation command contains unsafe patterns (e.g., node -e, shell metacharacters) blocked by sandbox security policy',
|
|
1458
|
+
verification_required: '资产需要当前本机宿主验证;请使用 --reverify 或本机重新验证接口',
|
|
1369
1459
|
};
|
|
1370
1460
|
return map[reason] ?? map.internal_error;
|
|
1371
1461
|
}
|
|
@@ -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
|
+
}
|
package/dist/promptRecallHook.js
CHANGED
|
@@ -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,
|
|
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
|
-
|
|
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'
|
|
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,
|
|
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;
|
|
@@ -45,7 +48,10 @@ export interface RecipeBuildOptions {
|
|
|
45
48
|
export interface RecipeReuseOptions {
|
|
46
49
|
sub: 'reuse';
|
|
47
50
|
recipeId: string;
|
|
48
|
-
inputPayload:
|
|
51
|
+
inputPayload: hubNs.RecipeJson;
|
|
52
|
+
requestKey: string;
|
|
53
|
+
maxCredits: number;
|
|
54
|
+
executionMode: 'caller' | 'provider';
|
|
49
55
|
jsonOut: boolean;
|
|
50
56
|
}
|
|
51
57
|
export interface RecipeFromSkillsOptions {
|
|
@@ -53,6 +59,7 @@ export interface RecipeFromSkillsOptions {
|
|
|
53
59
|
manifestPath: string;
|
|
54
60
|
publish: boolean;
|
|
55
61
|
jsonOut: boolean;
|
|
62
|
+
reverify?: boolean;
|
|
56
63
|
}
|
|
57
64
|
export interface RecipeSearchOptions {
|
|
58
65
|
sub: 'search';
|
package/dist/recipe.js
CHANGED
|
@@ -2,14 +2,16 @@ 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 recipeExecution, hub as hubNs } from '@evomap/evolver-core';
|
|
6
|
+
import { runRecipeConsentCommand } from './recipeConsent.js';
|
|
6
7
|
import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled, isNodeSecret, parseNodeSecretVersion, resolveHubUrl } from '@evomap/evolver-adapter-public';
|
|
7
|
-
import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
|
|
8
|
+
import { loadEnvFileFromEnv, loadEnvFileFromEnvOrThrow, safeReverificationRecovery } from '@evomap/evolver-mcp';
|
|
8
9
|
import { resolveExplicitNodeCredentials } from './identityHome.js';
|
|
9
10
|
import { getCliVersion } from './version.js';
|
|
10
11
|
import { parseSkillMd, reverseDistill, synthesizeGene } from './skill2gep.js';
|
|
11
12
|
import { recordSkillDistillation } from './skillDistill.js';
|
|
12
|
-
import { buildPublishBundle } from './cliContracts.js';
|
|
13
|
+
import { assessPublishRecords, buildPublishBundle } from './cliContracts.js';
|
|
14
|
+
import { LocalPublishBindingError, reverifyPublishBundle, withLocalPublishBinding, } from './localPublishBinding.js';
|
|
13
15
|
const MAX_RECIPE_STEPS = 20;
|
|
14
16
|
const MAX_RECIPE_VALIDATION_COMMANDS = 5;
|
|
15
17
|
const MAX_RECIPE_INPUT_BYTES = 1024 * 1024;
|
|
@@ -39,13 +41,25 @@ export async function runRecipeCommand(argv, deps = {}) {
|
|
|
39
41
|
const parsed = parseRecipeArgs(argv);
|
|
40
42
|
const err = deps.err ?? ((line) => { process.stderr.write(`${line}\n`); });
|
|
41
43
|
const log = deps.log ?? ((line) => { process.stdout.write(`${line}\n`); });
|
|
44
|
+
if (argv[0] === 'consent') {
|
|
45
|
+
try {
|
|
46
|
+
return runRecipeConsentCommand(argv.slice(1), deps.env ?? process.env, { log });
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
err(recipeErrorMessage(error));
|
|
50
|
+
return 1;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
42
53
|
if (!parsed.ok) {
|
|
43
54
|
err(`${parsed.error}\n${recipeUsage()}`);
|
|
44
55
|
return 1;
|
|
45
56
|
}
|
|
46
57
|
try {
|
|
47
58
|
const env = deps.env ?? process.env;
|
|
48
|
-
|
|
59
|
+
if (parsed.value.sub === 'reuse')
|
|
60
|
+
loadEnvFileFromEnvOrThrow(env);
|
|
61
|
+
else
|
|
62
|
+
loadEnvFileFromEnv(env);
|
|
49
63
|
if (isHubDryRunEnabled(env)) {
|
|
50
64
|
if (parsed.value.sub === 'build')
|
|
51
65
|
return await runRecipeBuildDryRun(parsed.value, deps.store, { log, err });
|
|
@@ -55,6 +69,9 @@ export async function runRecipeCommand(argv, deps = {}) {
|
|
|
55
69
|
return runRecipeSearchDryRun(parsed.value, { log });
|
|
56
70
|
return runRecipeReuseDryRun(parsed.value, { log });
|
|
57
71
|
}
|
|
72
|
+
const governance = new recipeExecution.RecipeExecutionGovernance(recipeExecution.recipeStateDirectory(env));
|
|
73
|
+
if (parsed.value.sub === 'reuse')
|
|
74
|
+
governance.assertSpendAllowed(parsed.value.maxCredits);
|
|
58
75
|
const hub = deps.hub ?? createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
|
|
59
76
|
await recipeIdentityBootstraps.get(hub)?.();
|
|
60
77
|
if (!hub.recipes) {
|
|
@@ -67,7 +84,7 @@ export async function runRecipeCommand(argv, deps = {}) {
|
|
|
67
84
|
return await runRecipeFromSkills(parsed.value, hub, deps, { log, err }, false);
|
|
68
85
|
if (parsed.value.sub === 'search')
|
|
69
86
|
return await runRecipeSearch(parsed.value, hub, { log, err });
|
|
70
|
-
return await runRecipeReuse(parsed.value, hub, { log, err });
|
|
87
|
+
return await runRecipeReuse(parsed.value, hub, { log, err }, governance);
|
|
71
88
|
}
|
|
72
89
|
catch (e) {
|
|
73
90
|
err(recipeErrorMessage(e));
|
|
@@ -333,9 +350,29 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
|
|
|
333
350
|
capsuleId: res.capsuleId,
|
|
334
351
|
});
|
|
335
352
|
}
|
|
336
|
-
const publishPrepared = await prepareRecipeFromSkillsAssets(distilled, store, dryRun ? undefined : hub, deps.env ?? process.env, io
|
|
353
|
+
const publishPrepared = await prepareRecipeFromSkillsAssets(distilled, store, dryRun ? undefined : hub, deps.env ?? process.env, io, {
|
|
354
|
+
reverify: opts.reverify === true,
|
|
355
|
+
...(deps.resolvePublishVerifier ? { resolvePublishVerifier: deps.resolvePublishVerifier } : {}),
|
|
356
|
+
});
|
|
337
357
|
if (!publishPrepared.ok) {
|
|
338
|
-
|
|
358
|
+
const failure = {
|
|
359
|
+
...recipeFromSkillsPayload({
|
|
360
|
+
ok: false, mode: 'failed', title: loaded.value.title, publish: opts.publish,
|
|
361
|
+
steps: publishPrepared.completedSteps, error: publishPrepared.reason,
|
|
362
|
+
}),
|
|
363
|
+
failedPosition: publishPrepared.failedPosition,
|
|
364
|
+
...(publishPrepared.recovery ? { recovery: publishPrepared.recovery,
|
|
365
|
+
recovery_action: 'inspect_assets_and_ledger_before_retry' } : {}),
|
|
366
|
+
};
|
|
367
|
+
if (opts.jsonOut)
|
|
368
|
+
io.log(JSON.stringify(failure, null, 2));
|
|
369
|
+
else {
|
|
370
|
+
io.err(publishPrepared.error);
|
|
371
|
+
// 文本调用者同样需要前序结果和三态写入信息;只输出已收敛的安全恢复字段。
|
|
372
|
+
if (publishPrepared.recovery || publishPrepared.completedSteps.length > 0) {
|
|
373
|
+
io.err(JSON.stringify(failure, null, 2));
|
|
374
|
+
}
|
|
375
|
+
}
|
|
339
376
|
return 1;
|
|
340
377
|
}
|
|
341
378
|
steps.splice(0, steps.length, ...publishPrepared.value.steps);
|
|
@@ -355,6 +392,8 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
|
|
|
355
392
|
io.log('[recipe from-skills] dry-run: would publish the recipe after creation.');
|
|
356
393
|
else
|
|
357
394
|
io.log('[recipe from-skills] dry-run: would leave the recipe as draft.');
|
|
395
|
+
if (opts.reverify)
|
|
396
|
+
io.log('[recipe from-skills] dry-run: --reverify would request additional local-host validation; no host request was sent.');
|
|
358
397
|
}
|
|
359
398
|
return 0;
|
|
360
399
|
}
|
|
@@ -369,7 +408,19 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
|
|
|
369
408
|
...(loaded.value.pricePerExecution !== undefined ? { pricePerExecution: loaded.value.pricePerExecution } : {}),
|
|
370
409
|
};
|
|
371
410
|
createRequest.idempotencyKey = recipeIdempotencyKey('create', createRequest);
|
|
372
|
-
|
|
411
|
+
let createReceipt;
|
|
412
|
+
try {
|
|
413
|
+
createReceipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills', () => hub.recipes.create(createRequest), io);
|
|
414
|
+
}
|
|
415
|
+
catch (error) {
|
|
416
|
+
if (!opts.jsonOut)
|
|
417
|
+
throw error;
|
|
418
|
+
io.log(JSON.stringify(recipeFromSkillsPayload({
|
|
419
|
+
ok: false, mode: 'failed', title: loaded.value.title, publish: opts.publish,
|
|
420
|
+
steps: distilled, error: 'create_failed',
|
|
421
|
+
}), null, 2));
|
|
422
|
+
return 1;
|
|
423
|
+
}
|
|
373
424
|
const recipeId = createReceipt.recipeId;
|
|
374
425
|
if (createReceipt.status !== 'draft') {
|
|
375
426
|
if (opts.jsonOut) {
|
|
@@ -453,12 +504,12 @@ async function runRecipeFromSkills(opts, hub, deps, io, dryRun) {
|
|
|
453
504
|
}
|
|
454
505
|
return 0;
|
|
455
506
|
}
|
|
456
|
-
async function runRecipeReuse(opts, hub, io) {
|
|
457
|
-
|
|
458
|
-
const receipt = await
|
|
459
|
-
io.log(`[recipe reuse]
|
|
507
|
+
async function runRecipeReuse(opts, hub, io, governance) {
|
|
508
|
+
const { sub: _sub, jsonOut: _jsonOut, ...input } = opts;
|
|
509
|
+
const receipt = await governance.invoke(hub.recipes?.execution, 'express', input);
|
|
510
|
+
io.log(`[recipe reuse] Accepted run ${terminalSafeText(receipt.organism.id)}; not completed. Preserve request key ${terminalSafeText(opts.requestKey)} for retries. Use private lifecycle tools for authorized host execution.`);
|
|
460
511
|
if (opts.jsonOut)
|
|
461
|
-
io.log(terminalSafeJson(receipt
|
|
512
|
+
io.log(terminalSafeJson(receipt, 2));
|
|
462
513
|
return 0;
|
|
463
514
|
}
|
|
464
515
|
async function recipeStepsFromLocalAssets(assetIds, store) {
|
|
@@ -589,49 +640,92 @@ function preflightRecipeFromSkillsSteps(steps) {
|
|
|
589
640
|
}
|
|
590
641
|
return { ok: true, value: prepared };
|
|
591
642
|
}
|
|
592
|
-
async function prepareRecipeFromSkillsAssets(distilled, store, hub, env, io) {
|
|
643
|
+
async function prepareRecipeFromSkillsAssets(distilled, store, hub, env, io, options) {
|
|
593
644
|
const steps = [];
|
|
594
645
|
const prepared = [];
|
|
595
646
|
const publishedByBundle = new Map();
|
|
647
|
+
const reverifiedBySource = new Map();
|
|
596
648
|
for (const step of distilled) {
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
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
|
-
};
|
|
649
|
+
let recovery;
|
|
650
|
+
const fail = (error, reason = 'asset_prepare_failed') => ({
|
|
651
|
+
ok: false, error, reason, completedSteps: [...prepared], failedPosition: step.position,
|
|
652
|
+
...(recovery ? { recovery } : {}),
|
|
653
|
+
});
|
|
654
|
+
try {
|
|
655
|
+
let bundle = await buildPublishBundle([step.geneAssetId, step.capsuleId], { assetStore: store, env });
|
|
656
|
+
if (!bundle.ok) {
|
|
657
|
+
return fail(`recipe from-skills step ${step.position + 1} asset bundle rejected: ${bundle.reason}`);
|
|
622
658
|
}
|
|
623
|
-
|
|
624
|
-
if (
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
659
|
+
let reverification;
|
|
660
|
+
if (hub && options.reverify && bundle.blockReasons.every((reason) => reason === 'gene_unproven')) {
|
|
661
|
+
const sourceKey = hubNs.publishBundleDigest(bundle.original);
|
|
662
|
+
let reverified = reverifiedBySource.get(sourceKey);
|
|
663
|
+
if (!reverified) {
|
|
664
|
+
reverified = await reverifyPublishBundle(bundle.original, env, options.resolvePublishVerifier);
|
|
665
|
+
reverifiedBySource.set(sourceKey, reverified);
|
|
666
|
+
}
|
|
667
|
+
reverification = {
|
|
668
|
+
sourceAssetIds: [...reverified.sourceAssetIds],
|
|
669
|
+
assetIds: reverified.assets.map((asset) => asset.asset_id),
|
|
670
|
+
stored: reverified.stored,
|
|
628
671
|
};
|
|
672
|
+
recovery = safeReverificationRecovery({
|
|
673
|
+
stored: reverified.stored, binding_registered: true,
|
|
674
|
+
source_asset_ids: reverified.sourceAssetIds, asset_ids: reverification.assetIds,
|
|
675
|
+
});
|
|
676
|
+
bundle = await assessPublishRecords(reverified.assets, { assetStore: store, env });
|
|
677
|
+
if (!bundle.ok) {
|
|
678
|
+
return fail(`recipe from-skills step ${step.position + 1} reverified asset bundle rejected: ${bundle.reason}`);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
if (bundle.blockReasons.length > 0) {
|
|
682
|
+
return fail(`recipe from-skills step ${step.position + 1} asset bundle rejected: ${bundle.blockReasons.join(',')}`);
|
|
683
|
+
}
|
|
684
|
+
const publishAssets = bundle.sanitized;
|
|
685
|
+
const gene = publishAssets.find((asset) => asset.type === 'Gene');
|
|
686
|
+
const capsule = publishAssets.find((asset) => asset.type === 'Capsule');
|
|
687
|
+
if (!gene?.asset_id || !capsule?.asset_id) {
|
|
688
|
+
return fail(`recipe from-skills step ${step.position + 1} asset bundle is missing Gene or Capsule`);
|
|
689
|
+
}
|
|
690
|
+
const bundleKey = `${gene.asset_id}\n${capsule.asset_id}`;
|
|
691
|
+
let geneAssetId = publishedByBundle.get(bundleKey);
|
|
692
|
+
if (!geneAssetId && hub) {
|
|
693
|
+
const receipt = await callRecipeWithAuthRetry(hub, 'recipe from-skills asset publish', () => withLocalPublishBinding(publishAssets, env, (authorized) => hub.publish(authorized), options.resolvePublishVerifier), io);
|
|
694
|
+
if (!assetPublishSucceeded(receipt, publishAssets)) {
|
|
695
|
+
const duplicateIsIncomplete = receipt.status === 'rejected' &&
|
|
696
|
+
(receipt.reason === 'already_published' || receipt.reason === 'duplicate');
|
|
697
|
+
return fail(duplicateIsIncomplete
|
|
698
|
+
? `recipe from-skills step ${step.position + 1} duplicate asset publish did not identify the published Gene and Capsule bundle`
|
|
699
|
+
: `recipe from-skills step ${step.position + 1} asset publish rejected: ${receipt.reason ?? receipt.status}`);
|
|
700
|
+
}
|
|
701
|
+
geneAssetId = publishedGeneAssetId(receipt, gene.asset_id);
|
|
702
|
+
if (!geneAssetId) {
|
|
703
|
+
return fail(`recipe from-skills step ${step.position + 1} duplicate asset publish did not identify the published Gene`);
|
|
704
|
+
}
|
|
705
|
+
publishedByBundle.set(bundleKey, geneAssetId);
|
|
706
|
+
}
|
|
707
|
+
geneAssetId ??= gene.asset_id;
|
|
708
|
+
steps.push({ assetId: geneAssetId, assetType: 'Gene', position: step.position });
|
|
709
|
+
prepared.push({
|
|
710
|
+
...step,
|
|
711
|
+
geneId: typeof gene['id'] === 'string' ? gene['id'] : geneAssetId,
|
|
712
|
+
geneAssetId,
|
|
713
|
+
capsuleId: typeof capsule['id'] === 'string' ? capsule['id'] : capsule.asset_id,
|
|
714
|
+
...(reverification ? { reverification } : {}),
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
catch (error) {
|
|
718
|
+
if (error instanceof LocalPublishBindingError) {
|
|
719
|
+
recovery = error.recovery ?? recovery;
|
|
720
|
+
return fail(error.message, error.reason);
|
|
629
721
|
}
|
|
630
|
-
|
|
722
|
+
// 网络/存储异常可能包含私有路径或响应;保留固定分类,不反射原始 message/body。
|
|
723
|
+
return fail(error instanceof AuthError
|
|
724
|
+
? `recipe Hub auth failed (HTTP ${error.status}); run "evolver login" or refresh EVOMAP_NODE_SECRET`
|
|
725
|
+
: error instanceof HubClientError
|
|
726
|
+
? `recipe Hub call failed (HTTP ${error.status}); 请先核对资产及发布状态,勿盲目重试`
|
|
727
|
+
: `recipe from-skills step ${step.position + 1}: asset_prepare_failed; 请先核对资产及发布状态,勿盲目重试`);
|
|
631
728
|
}
|
|
632
|
-
geneAssetId ??= gene.asset_id;
|
|
633
|
-
steps.push({ assetId: geneAssetId, assetType: 'Gene', position: step.position });
|
|
634
|
-
prepared.push({ ...step, geneAssetId });
|
|
635
729
|
}
|
|
636
730
|
return { ok: true, value: { steps, distilled: prepared } };
|
|
637
731
|
}
|
|
@@ -887,6 +981,7 @@ function recipeFromSkillsPayload(opts) {
|
|
|
887
981
|
geneId: step.geneId,
|
|
888
982
|
geneAssetId: step.geneAssetId,
|
|
889
983
|
capsuleId: step.capsuleId,
|
|
984
|
+
...(step.reverification ? { reverification: step.reverification } : {}),
|
|
890
985
|
})),
|
|
891
986
|
};
|
|
892
987
|
}
|
|
@@ -949,6 +1044,7 @@ function parseFromSkillsArgs(args) {
|
|
|
949
1044
|
manifestPath,
|
|
950
1045
|
publish: args.includes('--publish'),
|
|
951
1046
|
jsonOut: args.includes('--json'),
|
|
1047
|
+
...(args.includes('--reverify') ? { reverify: true } : {}),
|
|
952
1048
|
},
|
|
953
1049
|
};
|
|
954
1050
|
}
|
|
@@ -970,7 +1066,32 @@ function parseSearchArgs(args) {
|
|
|
970
1066
|
};
|
|
971
1067
|
}
|
|
972
1068
|
function parseReuseArgs(args) {
|
|
973
|
-
const
|
|
1069
|
+
const allowed = new Set(['--id', '--input', '--request-key', '--max-credits', '--execution-mode', '--json']);
|
|
1070
|
+
const seen = new Set();
|
|
1071
|
+
const positional = [];
|
|
1072
|
+
for (let index = 0; index < args.length; index++) {
|
|
1073
|
+
const token = args[index];
|
|
1074
|
+
if (!token.startsWith('--')) {
|
|
1075
|
+
positional.push(token);
|
|
1076
|
+
continue;
|
|
1077
|
+
}
|
|
1078
|
+
const name = token.split('=')[0];
|
|
1079
|
+
if (!allowed.has(name) || seen.has(name))
|
|
1080
|
+
return { ok: false, error: `unknown or duplicate recipe reuse option: ${name}` };
|
|
1081
|
+
seen.add(name);
|
|
1082
|
+
if (name === '--json') {
|
|
1083
|
+
if (token.includes('='))
|
|
1084
|
+
return { ok: false, error: '--json does not accept a value' };
|
|
1085
|
+
}
|
|
1086
|
+
else if (!token.includes('=')) {
|
|
1087
|
+
if (!args[index + 1] || args[index + 1].startsWith('--'))
|
|
1088
|
+
return { ok: false, error: `${name} requires a value` };
|
|
1089
|
+
index++;
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
if (positional.length > 1 || (positional.length && seen.has('--id')))
|
|
1093
|
+
return { ok: false, error: 'recipe reuse accepts exactly one recipe id' };
|
|
1094
|
+
const recipeId = flagValue(args, '--id') ?? positional[0];
|
|
974
1095
|
if (!recipeId)
|
|
975
1096
|
return { ok: false, error: 'recipe reuse requires --id <recipe_id>' };
|
|
976
1097
|
if (recipeId.length > MAX_ID_LENGTH)
|
|
@@ -979,7 +1100,19 @@ function parseReuseArgs(args) {
|
|
|
979
1100
|
const input = inputRaw === null ? { ok: true, value: {} } : parseJsonObject(inputRaw);
|
|
980
1101
|
if (!input.ok)
|
|
981
1102
|
return input;
|
|
982
|
-
|
|
1103
|
+
const maxCredits = flagValue(args, '--max-credits');
|
|
1104
|
+
try {
|
|
1105
|
+
const execution = recipeExecution.parseRecipeExecutionInput('express', {
|
|
1106
|
+
recipeId, inputPayload: input.value,
|
|
1107
|
+
requestKey: flagValue(args, '--request-key') ?? undefined,
|
|
1108
|
+
maxCredits: maxCredits === null || !maxCredits.trim() ? undefined : Number(maxCredits),
|
|
1109
|
+
executionMode: flagValue(args, '--execution-mode') ?? undefined,
|
|
1110
|
+
});
|
|
1111
|
+
return { ok: true, value: { sub: 'reuse', ...execution, inputPayload: execution.inputPayload ?? {}, jsonOut: args.includes('--json') } };
|
|
1112
|
+
}
|
|
1113
|
+
catch (error) {
|
|
1114
|
+
return { ok: false, error: `${recipeErrorMessage(error)}; reuse requires --request-key <stable-intent-key> --max-credits <ceiling> --execution-mode caller|provider` };
|
|
1115
|
+
}
|
|
983
1116
|
}
|
|
984
1117
|
function splitIds(raw) {
|
|
985
1118
|
return raw.split(',').map((s) => s.trim()).filter(Boolean).filter((s) => s.length <= MAX_ID_LENGTH);
|
|
@@ -998,9 +1131,6 @@ function flagValue(args, flag) {
|
|
|
998
1131
|
}
|
|
999
1132
|
return null;
|
|
1000
1133
|
}
|
|
1001
|
-
function firstPositional(args) {
|
|
1002
|
-
return args.find((a) => typeof a === 'string' && !a.startsWith('--')) ?? null;
|
|
1003
|
-
}
|
|
1004
1134
|
function firstSearchPositional(args) {
|
|
1005
1135
|
for (let i = 0; i < args.length; i += 1) {
|
|
1006
1136
|
const token = args[i];
|
|
@@ -1378,8 +1508,9 @@ function recipeUsage() {
|
|
|
1378
1508
|
'Recipe subcommands:',
|
|
1379
1509
|
' evolver recipe build --title <title> --genes <asset_id,...> [--description <text>] [--price <n>] [--publish]',
|
|
1380
1510
|
' Creates a draft recipe by default. --publish is explicit.',
|
|
1381
|
-
' evolver recipe from-skills --manifest <file> [--publish] [--json]',
|
|
1511
|
+
' evolver recipe from-skills --manifest <file> [--reverify] [--publish] [--json]',
|
|
1382
1512
|
' Distills ordered SKILL.md steps with execution evidence, then creates a recipe.',
|
|
1513
|
+
' --reverify explicitly reruns validation under the local host before publishing fresh assets; dry-run never calls the host.',
|
|
1383
1514
|
' evolver recipe reuse --id <recipe_id> [--input <json-object>] [--json]',
|
|
1384
1515
|
' evolver recipe search [--q <text>] [--limit <n>] [--json]',
|
|
1385
1516
|
` Default agent lookup. Express a hit with \`${RECIPE_REUSE_COMMAND}\`. Gene/Capsule search is fallback.`,
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { hub } from '@evomap/evolver-core';
|
|
2
|
+
import { loadEnvFileFromEnvOrThrow } from '@evomap/evolver-mcp';
|
|
3
|
+
export function runRecipeConsentCommand(args, env, io) {
|
|
4
|
+
loadEnvFileFromEnvOrThrow(env);
|
|
5
|
+
const directory = hub.recipeStateDirectory(env);
|
|
6
|
+
if (args.length === 0 || (args.length === 1 && args[0] === '--status')) {
|
|
7
|
+
io.log(JSON.stringify(hub.readRecipeSpendConsent(directory) ?? { version: 1, enabled: false, maxCredits: 0 }));
|
|
8
|
+
return 0;
|
|
9
|
+
}
|
|
10
|
+
if (args.length === 1 && args[0] === '--disable') {
|
|
11
|
+
io.log(JSON.stringify(hub.setRecipeSpendConsent(false, 0, directory)));
|
|
12
|
+
return 0;
|
|
13
|
+
}
|
|
14
|
+
if (args.length !== 4 || args[0] !== '--enable' || args[1] !== '--max-credits' || args[3] !== '--acknowledge-paid-recipe-charges' || !args[2]?.trim()) {
|
|
15
|
+
throw new Error('recipe consent: --status | --disable | --enable --max-credits <ceiling> --acknowledge-paid-recipe-charges. Only the user may opt in; ATP consent is separate.');
|
|
16
|
+
}
|
|
17
|
+
io.log(JSON.stringify(hub.setRecipeSpendConsent(true, Number(args[2]), directory)));
|
|
18
|
+
return 0;
|
|
19
|
+
}
|
|
@@ -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
|
-
|
|
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.
|
|
3
|
+
"version": "2.0.39",
|
|
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.
|
|
27
|
-
"@evomap/evolver-adapter-public": "2.0.
|
|
28
|
-
"@evomap/evolver-mcp": "2.0.
|
|
29
|
-
"@evomap/evolver-proxy": "2.0.
|
|
30
|
-
"@evomap/evolver-runtime-adapters": "2.0.
|
|
31
|
-
"@evomap/evolver-webui": "2.0.
|
|
26
|
+
"@evomap/evolver-core": "2.0.39",
|
|
27
|
+
"@evomap/evolver-adapter-public": "2.0.39",
|
|
28
|
+
"@evomap/evolver-mcp": "2.0.39",
|
|
29
|
+
"@evomap/evolver-proxy": "2.0.39",
|
|
30
|
+
"@evomap/evolver-runtime-adapters": "2.0.39",
|
|
31
|
+
"@evomap/evolver-webui": "2.0.39"
|
|
32
32
|
},
|
|
33
33
|
"repository": {
|
|
34
34
|
"type": "git",
|