@evomap/evolver-proxy 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.
@@ -106,6 +106,8 @@ export declare function createVerifiedPublicSender(initialNodeId?: string): Veri
106
106
  export declare function adoptVerifiedPublicNodeId(store: mailbox.MailboxStore, selection: PublicNodeSecretSelection, sender: VerifiedPublicSender, nodeId: string): void;
107
107
  export interface HubRuntime {
108
108
  hub: ProxyDaemonDeps['hub'];
109
+ /** Identity used by this connected runtime, including explicit credential overrides not yet persisted to the store. */
110
+ currentNodeId?: () => string | undefined;
109
111
  hello: (opts: {
110
112
  rotate: boolean;
111
113
  evolverVersion?: string;
@@ -662,6 +662,7 @@ export function createProxyDaemonDeps(options) {
662
662
  const hubAuthFailurePolicy = resolveHubAuthFailurePolicy(env);
663
663
  return {
664
664
  hub: options.runtime.hub,
665
+ ...(options.runtime.currentNodeId ? { currentNodeId: options.runtime.currentNodeId } : {}),
665
666
  ...(options.hubMode ? { hubMode: options.hubMode } : {}),
666
667
  store: options.store,
667
668
  ipcToken: options.ipcToken,
@@ -703,7 +704,14 @@ function resolveNativePublishExecutionVerifier(env) {
703
704
  const configuredRoot = env['EVOLVER_PUBLISH_VALIDATION_ROOT']?.trim();
704
705
  if (!configuredRoot)
705
706
  return undefined;
706
- const validationRoot = resolve(configuredRoot);
707
+ let validationRoot;
708
+ try {
709
+ validationRoot = realpathSync(resolve(configuredRoot));
710
+ }
711
+ catch {
712
+ return undefined;
713
+ }
714
+ const rootFingerprint = hubNs.publishBindingDigest('publish-validation-root.v1', validationRoot);
707
715
  return async (input, signal) => {
708
716
  const commands = Array.isArray(input.validation)
709
717
  ? input.validation.filter((value) => typeof value === 'string').map((value) => value.trim()).filter(Boolean)
@@ -715,7 +723,9 @@ function resolveNativePublishExecutionVerifier(env) {
715
723
  || commands.some((command) => command.length > 180
716
724
  || !verify.isValidationCommandAllowed(command)
717
725
  || verify.sanitizeExecutionCommand(command).blocked)
718
- || signal.aborted)
726
+ || signal.aborted
727
+ || !hubNs.isPublishVerificationRequest(input['verification_request'])
728
+ || input['verification_request'].validationDigest !== hubNs.publishBindingDigest('publish-validation.v1', commands))
719
729
  return null;
720
730
  const result = await verify.runSandboxedValidation(commands, validationRoot, {
721
731
  requireIsolation: true,
@@ -724,6 +734,7 @@ function resolveNativePublishExecutionVerifier(env) {
724
734
  if (signal.aborted || !result.passed || result.results.length !== commands.length)
725
735
  return null;
726
736
  return {
737
+ binding: { request: structuredClone(input['verification_request']), rootFingerprint },
727
738
  validation: commands,
728
739
  trace: result.results.map((row) => ({
729
740
  command: row.cmd,
@@ -1210,6 +1221,7 @@ export async function connectHubRuntime(deps) {
1210
1221
  });
1211
1222
  return {
1212
1223
  hub: runtime.hub,
1224
+ currentNodeId: deps.senderId,
1213
1225
  hello: runtime.hello,
1214
1226
  heartbeat: (opts) => runtime.hub.heartbeat(opts),
1215
1227
  helloMode: 'enterprise_token',
@@ -1254,6 +1266,7 @@ export async function connectHubRuntime(deps) {
1254
1266
  }));
1255
1267
  return {
1256
1268
  hub,
1269
+ currentNodeId: senderId,
1257
1270
  atp: new AtpHubClient({ baseUrl: deps.hubUrl, auth, fetchFn: globalFetchLike, senderId }),
1258
1271
  hello,
1259
1272
  heartbeat: (opts) => hub.heartbeat(opts),
@@ -11,7 +11,14 @@ export declare const DEFAULT_IPC_PORT = 19820;
11
11
  export type HubAuthFailurePolicy = 'deny' | 'warn';
12
12
  export declare function resolveHubAuthFailurePolicy(env?: Record<string, string | undefined>): HubAuthFailurePolicy;
13
13
  export interface ProxyDaemonDeps {
14
+ /** operator配置,不能由单次搜索请求关闭。 */
15
+ benchmarkId?: string;
16
+ sourceProvenance?: assetstore.ProvenanceStore;
17
+ /** benchmark自定义provider必须接入审核账本;缺账本不等于Gene没有审核记录。 */
18
+ sourceReview?: assetstore.ReviewLedger;
14
19
  hub: HubCapability;
20
+ /** Identity actually presented by the connected Hub runtime; terminal lifecycle state is scoped to it. */
21
+ currentNodeId?: () => string | undefined;
15
22
  /** Immutable Hub selection for IPC callers that must fail closed across public/private runtimes. */
16
23
  hubMode?: 'public' | 'private';
17
24
  /** 二选一: 传 storePath 让 ProxyDaemon 建 store, 或传已建 store(供 hub senderId 共享同一 node_id). */
@@ -148,6 +155,9 @@ export declare class ProxyDaemon {
148
155
  readonly sync: SyncEngine;
149
156
  readonly lifecycle: LifecycleManager;
150
157
  private readonly assetStore;
158
+ private readonly benchmark;
159
+ private readonly sourceProvenance;
160
+ private readonly sourceReview;
151
161
  private readonly referenceStore;
152
162
  private readonly remoteAssetById;
153
163
  private readonly reuseResultReporter;
@@ -167,6 +177,7 @@ export declare class ProxyDaemon {
167
177
  private readonly assetSubmitResponseTimeoutMs;
168
178
  private readonly hubAuthFailurePolicy;
169
179
  private readonly synchronousAssetSubmitScope;
180
+ private readonly publishBindingLedger;
170
181
  private readonly shadowMode;
171
182
  private readonly assetSearchCache;
172
183
  private readonly assetSearchInflight;
@@ -246,6 +257,9 @@ export declare class ProxyDaemon {
246
257
  private markHubAuthFailed;
247
258
  private hubAuthFailureBody;
248
259
  private localSearchAssets;
260
+ private qualifyAssets;
261
+ private respondAssetSearch;
262
+ private qualifyFetch;
249
263
  private localFetchAssets;
250
264
  private handleProxyRoute;
251
265
  private searchAssets;
@@ -9,6 +9,7 @@ import { reportPendingSelfUpdateLastUpdate, reportSelfUpdateLastUpdate } from '.
9
9
  import { backfillProxyTraceUploads } from '../llm/traceBackfill.js';
10
10
  import { hubAuthFailureHint } from './selectHub.js';
11
11
  import { CollaborationFacade } from './collaborationFacade.js';
12
+ import { PublishBindingLedger } from './publishBindingLedger.js';
12
13
  import { PublishRecallVerifier, resolvePublishRecallConfig, } from './publishRecallVerifier.js';
13
14
  const DEFAULT_PUBLISH_EXECUTION_VERIFY_TIMEOUT_MS = 30_000;
14
15
  export const DEFAULT_IPC_PORT = 19820;
@@ -90,6 +91,9 @@ export class ProxyDaemon {
90
91
  sync;
91
92
  lifecycle;
92
93
  assetStore;
94
+ benchmark;
95
+ sourceProvenance;
96
+ sourceReview;
93
97
  referenceStore;
94
98
  remoteAssetById;
95
99
  reuseResultReporter;
@@ -109,6 +113,7 @@ export class ProxyDaemon {
109
113
  assetSubmitResponseTimeoutMs;
110
114
  hubAuthFailurePolicy;
111
115
  synchronousAssetSubmitScope;
116
+ publishBindingLedger;
112
117
  shadowMode;
113
118
  assetSearchCache = new Map();
114
119
  assetSearchInflight = new Map();
@@ -139,6 +144,7 @@ export class ProxyDaemon {
139
144
  publishAbortController = new AbortController();
140
145
  constructor(deps) {
141
146
  this.deps = deps;
147
+ this.benchmark = assetstore.benchmarkContext(deps.benchmarkId ?? process.env['EVOLVER_BENCHMARK_ID']);
142
148
  this.now = deps.now ?? (() => Date.now());
143
149
  this.random = deps.random ?? Math.random;
144
150
  this.assetSearchCacheTtlMs = positiveIntegerOr(deps.assetSearchCacheTtlMs, DEFAULT_ASSET_SEARCH_CACHE_TTL_MS);
@@ -160,8 +166,17 @@ export class ProxyDaemon {
160
166
  if (!existingSynchronousAssetSubmitScope) {
161
167
  this.store.setState(SYNC_ASSET_SUBMIT_SCOPE_STATE_KEY, this.synchronousAssetSubmitScope);
162
168
  }
169
+ this.publishBindingLedger = new PublishBindingLedger(this.store, JSON.stringify([
170
+ this.synchronousAssetSubmitScope, deps.runtimeNamespace ?? 'default', deps.hubMode ?? 'public',
171
+ // 保留既有 enforce 域;shadow 签发记录不能在切换模式后成为真实发布授权。
172
+ ...(shadow ? ['shadow'] : []),
173
+ ]));
163
174
  const assetStoreDir = deps.assetStoreDir ?? (deps.storePath ? join(dirname(deps.storePath), 'assets') : undefined);
164
175
  this.assetStore = deps.assetStore ?? (assetStoreDir ? new assetstore.LocalJsonlProvider(assetStoreDir) : undefined);
176
+ this.sourceProvenance = deps.sourceProvenance ?? (this.benchmark && this.assetStore instanceof assetstore.LocalJsonlProvider
177
+ ? new assetstore.ProvenanceStore(this.assetStore.baseDir) : undefined);
178
+ this.sourceReview = deps.sourceReview ?? (this.benchmark && this.assetStore instanceof assetstore.LocalJsonlProvider
179
+ ? new assetstore.ReviewLedger(this.assetStore.baseDir) : undefined);
165
180
  const referenceBase = assetStoreDir ?? deps.assetStore?.baseDir;
166
181
  this.referenceStore = referenceBase ? new reference.ReferenceStore(join(referenceBase, 'references')) : undefined;
167
182
  this.referenceStore?.search({ max_assets: 1 });
@@ -171,6 +186,7 @@ export class ProxyDaemon {
171
186
  const hubBindings = hubNs.makeHubBindings(hubToUse, {
172
187
  referenceScope: this.referenceStore?.scope,
173
188
  ...(deps.publishSanitizeEnv ? { sanitize: { env: deps.publishSanitizeEnv } } : {}),
189
+ verifyPublishBinding: (bundle, receipt) => { this.publishBindingLedger.verify(bundle, receipt); },
174
190
  });
175
191
  this.proxyHandler = hubBindings.asProxyHandler();
176
192
  const proxyHandler = this.proxyHandler;
@@ -268,6 +284,7 @@ export class ProxyDaemon {
268
284
  });
269
285
  this.lifecycle = new LifecycleManager({
270
286
  store: this.store, auth: hubToUse.auth, hello: deps.hello, heartbeat: deps.heartbeat, now: this.now,
287
+ ...(deps.currentNodeId ? { currentNodeId: deps.currentNodeId } : {}),
271
288
  ...(deps.heartbeatIntervalMs !== undefined ? { heartbeatIntervalMs: deps.heartbeatIntervalMs } : {}),
272
289
  ...(deps.evolverVersion ? { evolverVersion: deps.evolverVersion } : {}),
273
290
  ...(deps.helloMode ? { helloMode: deps.helloMode } : {}),
@@ -320,6 +337,12 @@ export class ProxyDaemon {
320
337
  if (result.stored && env.handler === 'proxy')
321
338
  this.notifyNewOutbound();
322
339
  },
340
+ beforeSend: (envelope) => {
341
+ if (envelope.type !== 'asset_submit')
342
+ return;
343
+ const { assets, publishReceipt } = hubNs.splitAssetSubmitPayload(envelope.payload);
344
+ this.publishBindingLedger.verify(assets, publishReceipt);
345
+ },
323
346
  ...(this.deps.onIpcAuthFailure ? { onAuthFailure: this.deps.onIpcAuthFailure } : {}),
324
347
  extraRoutes: [(ctx) => reference.withReferenceScope(this.referenceStore?.scope, () => this.handleProxyRoute(ctx))],
325
348
  });
@@ -329,6 +352,8 @@ export class ProxyDaemon {
329
352
  }
330
353
  catch { /* local discovery publishing must not block daemon startup */ }
331
354
  await this.lifecycle.doHello();
355
+ if (this.lifecycle.isTerminal)
356
+ this.nextHeartbeatAt = Number.POSITIVE_INFINITY;
332
357
  this.lifecycleArmed = true;
333
358
  this.drainProxyTraceBackfill();
334
359
  try {
@@ -504,7 +529,7 @@ export class ProxyDaemon {
504
529
  * flight from overwriting this reschedule. No-op until the daemon is started.
505
530
  */
506
531
  pokeHeartbeatLoop() {
507
- if (!this.started)
532
+ if (!this.started || this.lifecycle.isTerminal)
508
533
  return;
509
534
  this.heartbeatGeneration += 1;
510
535
  this.heartbeatFailures = 0;
@@ -808,6 +833,33 @@ export class ProxyDaemon {
808
833
  const local = this.assetStore ? await this.assetStore.search(query) : [];
809
834
  return local.filter((asset) => asset.type !== 'AntiGene').slice(0, limit);
810
835
  }
836
+ qualifyAssets(assets, limit = assets.length) {
837
+ if (!this.benchmark)
838
+ return { assets: assets.slice(0, limit) };
839
+ // 放在缓存、远端await之后;普通审批或cache TTL不能覆盖刚撤销的来源资格。
840
+ const snapshot = this.sourceProvenance?.snapshot();
841
+ const reviewed = this.sourceReview?.snapshot();
842
+ const sourceQualifications = assets.map((asset) => {
843
+ const decision = assetstore.assessSourceEligibility(asset, snapshot?.get(asset.asset_id), this.benchmark);
844
+ const review = reviewed?.get(asset.asset_id);
845
+ const withheld = snapshot?.get(asset.asset_id)?.trusted === false ? 'trust_rejected'
846
+ : (review && review.state !== 'approved') || (reviewed && asset.type === 'AntiGene' && !review) ? 'review_rejected'
847
+ : decision.allowed && !reviewed ? 'review_unavailable' : undefined;
848
+ return { ...decision, ...(withheld ? { allowed: false, reason: withheld } : {}),
849
+ assetId: asset.asset_id, benchmarkId: this.benchmark.benchmarkId };
850
+ });
851
+ return { assets: assets.filter((_asset, index) => sourceQualifications[index].allowed).slice(0, limit), sourceQualifications };
852
+ }
853
+ respondAssetSearch(ctx, query, assets, limit, extra = {}) {
854
+ const qualified = this.qualifyAssets(assets, limit);
855
+ ctx.json(200, { results: qualified.assets, ...qualified, query, ...extra, ...(this.benchmark ? { benchmarkId: this.benchmark.benchmarkId } : {}) });
856
+ }
857
+ qualifyFetch(ids, assets, missing) {
858
+ if (!this.benchmark)
859
+ return { assets: [...assets], missing: [...missing] };
860
+ const qualified = this.qualifyAssets(assets);
861
+ return { ...qualified, missing: ids.filter((id) => !qualified.assets.some((asset) => assetMatchesId(asset, id))) };
862
+ }
811
863
  async localFetchAssets(ids) {
812
864
  const assets = [];
813
865
  const missing = [];
@@ -818,7 +870,7 @@ export class ProxyDaemon {
818
870
  else
819
871
  missing.push(id);
820
872
  }
821
- return { assets, missing };
873
+ return this.qualifyFetch(ids, assets, missing);
822
874
  }
823
875
  async handleProxyRoute(ctx) {
824
876
  const expectedHeader = singleHeader(ctx.req.headers['x-evomap-expected-hub-mode']);
@@ -835,6 +887,7 @@ export class ProxyDaemon {
835
887
  running: true,
836
888
  status: 'running',
837
889
  proxy_protocol_version: PROXY_PROTOCOL_VERSION,
890
+ ...(this.benchmark ? { benchmark_id: this.benchmark.benchmarkId, source_qualification_mode: 'enforce' } : {}),
838
891
  schema_version: PROXY_STATUS_SCHEMA_VERSION,
839
892
  hub_mode: this.deps.hubMode ?? 'public',
840
893
  runtime_namespace: this.deps.runtimeNamespace ?? 'default',
@@ -944,15 +997,15 @@ export class ProxyDaemon {
944
997
  ...(kind ? { kind } : {}),
945
998
  ...(typeof body.category === 'string' ? { category: body.category } : {}),
946
999
  ...(typeof body.gene === 'string' ? { gene: body.gene } : {}),
947
- limit,
1000
+ limit: this.benchmark ? 25 : limit,
948
1001
  };
949
1002
  if (kind === 'AntiGene' && !this.assetStore) {
950
- ctx.json(200, { results: [], assets: [], query: body });
1003
+ this.respondAssetSearch(ctx, body, [], limit);
951
1004
  return true;
952
1005
  }
953
1006
  if (kind === 'AntiGene') {
954
1007
  const results = this.assetStore ? await this.assetStore.search(query) : [];
955
- ctx.json(200, { results, assets: results, query: body });
1008
+ this.respondAssetSearch(ctx, body, results, limit);
956
1009
  return true;
957
1010
  }
958
1011
  if (this.hubAuthFailed()) {
@@ -961,10 +1014,7 @@ export class ProxyDaemon {
961
1014
  return true;
962
1015
  }
963
1016
  const results = await this.localSearchAssets(query);
964
- ctx.json(200, {
965
- results,
966
- assets: results,
967
- query: body,
1017
+ this.respondAssetSearch(ctx, body, results, limit, {
968
1018
  degraded: true,
969
1019
  local_fallback: true,
970
1020
  auth_status: HUB_AUTH_FAILED,
@@ -974,7 +1024,7 @@ export class ProxyDaemon {
974
1024
  }
975
1025
  try {
976
1026
  const results = await this.searchAssets(query);
977
- ctx.json(200, { results, assets: results, query: body });
1027
+ this.respondAssetSearch(ctx, body, results, limit);
978
1028
  }
979
1029
  catch (error) {
980
1030
  if (!isAuthLikeError(error))
@@ -985,10 +1035,7 @@ export class ProxyDaemon {
985
1035
  return true;
986
1036
  }
987
1037
  const results = await this.localSearchAssets(query);
988
- ctx.json(200, {
989
- results,
990
- assets: results,
991
- query: body,
1038
+ this.respondAssetSearch(ctx, body, results, limit, {
992
1039
  degraded: true,
993
1040
  local_fallback: true,
994
1041
  auth_status: HUB_AUTH_FAILED,
@@ -1070,6 +1117,10 @@ export class ProxyDaemon {
1070
1117
  ...(Array.isArray(body.asset_ids) ? body.asset_ids : []),
1071
1118
  ...(typeof body.asset_id === 'string' ? [body.asset_id] : []),
1072
1119
  ]);
1120
+ if (this.benchmark && ids.length > 25) {
1121
+ ctx.json(400, { error: 'invalid_limit' });
1122
+ return true;
1123
+ }
1073
1124
  if (this.hubAuthFailed()) {
1074
1125
  if (this.hubAuthFailurePolicy === 'deny') {
1075
1126
  ctx.json(401, this.hubAuthFailureBody());
@@ -1124,7 +1175,7 @@ export class ProxyDaemon {
1124
1175
  missing.push(id);
1125
1176
  }
1126
1177
  }
1127
- ctx.json(200, { assets, missing, query: body });
1178
+ ctx.json(200, { ...this.qualifyFetch(ids, assets, missing), query: body });
1128
1179
  return true;
1129
1180
  }
1130
1181
  if (ctx.route === 'POST /asset/submit') {
@@ -1173,11 +1224,29 @@ export class ProxyDaemon {
1173
1224
  ctx.json(400, { error: 'mode=sync requires a full asset bundle' });
1174
1225
  return true;
1175
1226
  }
1227
+ if (body['publish_receipt'] !== undefined) {
1228
+ try {
1229
+ this.publishBindingLedger.verify(outboundBundle, body['publish_receipt']);
1230
+ }
1231
+ catch {
1232
+ ctx.json(422, { error: 'publish_binding_invalid', stored: false, queued: false });
1233
+ return true;
1234
+ }
1235
+ }
1176
1236
  await this.publishAssetSubmitSynchronously(ctx, outboundBundle, hubNs.recipeComposeRequested(body));
1177
1237
  return true;
1178
1238
  }
1239
+ let publishReceipt;
1240
+ try {
1241
+ publishReceipt = this.publishBindingLedger.verify(outboundBundle, body['publish_receipt']);
1242
+ }
1243
+ catch {
1244
+ ctx.json(422, { error: 'publish_binding_invalid', stored: false, queued: false });
1245
+ return true;
1246
+ }
1179
1247
  const payload = {
1180
1248
  assets: outboundBundle,
1249
+ ...(publishReceipt ? { publish_receipt: publishReceipt } : {}),
1181
1250
  compose_recipe: hubNs.recipeComposeRequested(body),
1182
1251
  [OUTBOUND_HUB_MODE_FIELD]: this.currentHubMode(),
1183
1252
  };
@@ -1267,6 +1336,110 @@ export class ProxyDaemon {
1267
1336
  }
1268
1337
  return true;
1269
1338
  }
1339
+ if (ctx.route === 'POST /asset/authorize-publish') {
1340
+ const body = asRecord(await ctx.readJson());
1341
+ if (hubModeMismatch(body['expected_hub_mode'], this.deps.hubMode)) {
1342
+ ctx.json(409, { error: 'proxy_hub_mode_mismatch', binding_verified: false });
1343
+ return true;
1344
+ }
1345
+ if (ctx.signal?.aborted || this.publishAbortController.signal.aborted) {
1346
+ ctx.json(503, { ok: false, error: 'publish_binding_aborted', binding_verified: false, stored: false, queued: false });
1347
+ return true;
1348
+ }
1349
+ try {
1350
+ if (!Array.isArray(body['assets']) || body['assets'].length === 0 || body['assets'].length > MAX_ASSET_SUBMIT_ITEMS) {
1351
+ throw new Error('publish_binding_invalid_bundle');
1352
+ }
1353
+ const bundle = body['assets'].map((asset) => {
1354
+ const normalized = assetstore.normalizeForPut(asset);
1355
+ // SDK 检查不包含本地 Gene 注解;ledger 仍绑定未删减的完整规范化记录。
1356
+ if (!normalized.verified || !wire.validateWireDeep(normalized.record.type === 'Gene' ? wire.stripGeneHints(normalized.record) : normalized.record).ok) {
1357
+ throw new Error('publish_binding_invalid_bundle');
1358
+ }
1359
+ return normalized.record;
1360
+ });
1361
+ const authorization = this.publishBindingLedger.verify(bundle);
1362
+ ctx.json(200, { ok: true, binding_verified: authorization !== undefined,
1363
+ binding_required: hubNs.requiresPublishBinding(bundle), bundle_digest: hubNs.publishBundleDigest(bundle) });
1364
+ }
1365
+ catch {
1366
+ ctx.json(422, { ok: false, error: 'publish_binding_invalid', binding_verified: false, stored: false, queued: false });
1367
+ }
1368
+ return true;
1369
+ }
1370
+ if (ctx.route === 'POST /asset/reverify') {
1371
+ const body = asRecord(await ctx.readJson());
1372
+ let stored = false;
1373
+ let bindingRegistered = false;
1374
+ let sourceAssetIds = [];
1375
+ let assetIds = [];
1376
+ const safeIds = (ids) => ids.slice(0, 2).filter((id) => /^sha256:[0-9a-f]{64}$/.test(id));
1377
+ const fail = (status, error) => {
1378
+ if (!ctx.signal?.aborted)
1379
+ ctx.json(status, {
1380
+ ok: false, error, publishable: false, stored, queued: false,
1381
+ binding_registered: bindingRegistered, source_asset_ids: sourceAssetIds, asset_ids: assetIds,
1382
+ });
1383
+ return true;
1384
+ };
1385
+ if (hubModeMismatch(body['expected_hub_mode'], this.deps.hubMode)) {
1386
+ return fail(409, 'proxy_hub_mode_mismatch');
1387
+ }
1388
+ if (Object.keys(body).some((key) => !['assets', 'persist', 'expected_hub_mode'].includes(key))
1389
+ || (body['persist'] !== undefined && typeof body['persist'] !== 'boolean')) {
1390
+ return fail(422, 'publish_reverification_invalid_options');
1391
+ }
1392
+ if (!Array.isArray(body['assets']))
1393
+ return fail(422, 'publish_reverification_pair_required');
1394
+ if (!this.deps.publishExecutionVerifier)
1395
+ return fail(409, 'publish_reverification_unavailable');
1396
+ const signal = AbortSignal.any([this.publishAbortController.signal, ...(ctx.signal ? [ctx.signal] : [])]);
1397
+ if (signal.aborted)
1398
+ return fail(503, 'publish_reverification_aborted');
1399
+ if (body['persist'] === true && typeof this.assetStore?.putBundle !== 'function') {
1400
+ return fail(422, 'bundle_persistence_unsupported');
1401
+ }
1402
+ const sanitizeEnv = this.deps.publishSanitizeEnv ?? process.env;
1403
+ let candidate;
1404
+ try {
1405
+ candidate = hubNs.preparePublishReverification(body['assets'], sanitizeEnv);
1406
+ }
1407
+ catch (error) {
1408
+ return fail(422, error instanceof Error && /^publish_reverification_[a-z_]{1,70}$/.test(error.message)
1409
+ ? error.message : 'publish_reverification_invalid_wire');
1410
+ }
1411
+ sourceAssetIds = safeIds(candidate.sourceAssetIds);
1412
+ const request = hubNs.createPublishVerificationRequest(candidate.input, candidate.validation, this.publishBindingLedger.runtimeDomain, randomUUID());
1413
+ const verified = await resolveVerifiedExecution(this.deps.publishExecutionVerifier, { validation: candidate.validation, verification_request: Object.freeze(request) }, candidate.validation, this.deps.publishExecutionVerifierTimeoutMs, [signal]);
1414
+ if (signal.aborted)
1415
+ return fail(503, 'publish_reverification_aborted');
1416
+ if (!verified)
1417
+ return fail(422, 'publish_reverification_execution_failed');
1418
+ try {
1419
+ const result = hubNs.completePublishReverification(candidate, verified, sanitizeEnv);
1420
+ assetIds = safeIds(result.assets.map((asset) => asset.asset_id));
1421
+ // 登记与资产持久化是独立状态,写入抛错后不得声称没有副作用或撤销合法回执。
1422
+ bindingRegistered = null;
1423
+ this.publishBindingLedger.register(result.publish_receipt, result.assets);
1424
+ bindingRegistered = true;
1425
+ if (signal.aborted)
1426
+ return fail(503, 'publish_reverification_aborted');
1427
+ if (body['persist'] === true) {
1428
+ stored = null;
1429
+ await this.assetStore.putBundle(result.assets);
1430
+ stored = true;
1431
+ }
1432
+ if (signal.aborted)
1433
+ return fail(503, 'publish_reverification_aborted');
1434
+ this.publishBindingLedger.verify(result.assets, result.publish_receipt);
1435
+ ctx.json(200, { ok: true, status: 'reverified', ...result, stored, binding_registered: bindingRegistered, queued: false, publishable: true });
1436
+ return true;
1437
+ }
1438
+ catch (error) {
1439
+ return fail(422, error instanceof Error && /^publish_reverification_[a-z_]{1,70}$/.test(error.message)
1440
+ ? error.message : 'publish_reverification_failed');
1441
+ }
1442
+ }
1270
1443
  if (ctx.route === 'POST /conversation/distill') {
1271
1444
  const body = (await ctx.readJson());
1272
1445
  const publishRequested = body['publish'] === true;
@@ -1291,7 +1464,7 @@ export class ProxyDaemon {
1291
1464
  if (publishRequested && abortPublish())
1292
1465
  return true;
1293
1466
  const verifiedExecution = publishRequested
1294
- ? await resolveVerifiedExecutionAfterPreflight(this.deps.publishExecutionVerifier, body, this.deps.publishExecutionVerifierTimeoutMs, [this.publishAbortController.signal, ...(ctx.signal ? [ctx.signal] : [])])
1467
+ ? await resolveVerifiedExecutionAfterPreflight(this.deps.publishExecutionVerifier, body, this.deps.publishExecutionVerifierTimeoutMs, [this.publishAbortController.signal, ...(ctx.signal ? [ctx.signal] : [])], this.publishBindingLedger.runtimeDomain)
1295
1468
  : undefined;
1296
1469
  if (publishRequested && abortPublish())
1297
1470
  return true;
@@ -1300,6 +1473,9 @@ export class ProxyDaemon {
1300
1473
  persist: body.persist === true,
1301
1474
  store: this.assetStore,
1302
1475
  ...(verifiedExecution ? { verifiedExecution } : {}),
1476
+ registerPublishReceipt: (receipt, bundle) => this.publishBindingLedger.register(receipt, bundle),
1477
+ ...(publishRequested ? { publishSignal: AbortSignal.any([this.publishAbortController.signal, ...(ctx.signal ? [ctx.signal] : [])]) } : {}),
1478
+ ...(this.deps.publishSanitizeEnv ? { publishSanitizeEnv: this.deps.publishSanitizeEnv } : {}),
1303
1479
  });
1304
1480
  if (publishRequested && abortPublish())
1305
1481
  return true;
@@ -1335,12 +1511,19 @@ export class ProxyDaemon {
1335
1511
  ctx.json(401, this.hubAuthFailureBody({ publish_status: 'failed', queued: false, stored: false }));
1336
1512
  return true;
1337
1513
  }
1514
+ if (!distill.publish_receipt) {
1515
+ ctx.json(422, { error: 'publish_binding_missing', stored: false, queued: false });
1516
+ return true;
1517
+ }
1518
+ this.publishBindingLedger.register(distill.publish_receipt, [distill.gene, distill.capsule]);
1519
+ this.publishBindingLedger.verify([distill.gene, distill.capsule], distill.publish_receipt);
1338
1520
  const env = mailbox.createEnvelope({
1339
1521
  type: 'asset_submit',
1340
1522
  payload: {
1341
1523
  source: 'conversation_distillation',
1342
1524
  distill_id: distill.distill_id,
1343
1525
  assets: [distill.gene, distill.capsule],
1526
+ publish_receipt: distill.publish_receipt,
1344
1527
  compose_recipe: body['publish_recipe'] !== false,
1345
1528
  title: typeof body.title === 'string' ? body.title : undefined,
1346
1529
  description: typeof body.summary === 'string' ? body.summary : undefined,
@@ -1534,7 +1717,7 @@ export class ProxyDaemon {
1534
1717
  }
1535
1718
  const results = [];
1536
1719
  for (const item of classified.items) {
1537
- const converted = await convertLegacyLooseAsset(item, this.deps.publishExecutionVerifier, this.deps.publishExecutionVerifierTimeoutMs, ctx.signal, this.publishAbortController.signal);
1720
+ const converted = await convertLegacyLooseAsset(item, this.deps.publishExecutionVerifier, this.deps.publishExecutionVerifierTimeoutMs, this.publishBindingLedger, this.deps.publishSanitizeEnv, ctx.signal, this.publishAbortController.signal);
1538
1721
  if (!converted.ok) {
1539
1722
  results.push({ ok: false, error: converted.error, statusCode: 422 });
1540
1723
  continue;
@@ -1581,6 +1764,7 @@ export class ProxyDaemon {
1581
1764
  }
1582
1765
  createSynchronousAssetSubmitEnvelope(bundle, source, now, composeRecipe = true) {
1583
1766
  const canonicalBundle = [...bundle].sort(compareSynchronousAssetSubmitAssets);
1767
+ const publishReceipt = this.publishBindingLedger.verify(canonicalBundle);
1584
1768
  const runtimeNamespace = this.deps.runtimeNamespace ?? 'default';
1585
1769
  const idempotencyKey = synchronousAssetSubmitKey(this.synchronousAssetSubmitScope, runtimeNamespace, this.currentHubMode(), canonicalBundle);
1586
1770
  return mailbox.createEnvelope({
@@ -1589,6 +1773,7 @@ export class ProxyDaemon {
1589
1773
  payload: {
1590
1774
  ...(source ? { source } : {}),
1591
1775
  assets: canonicalBundle,
1776
+ ...(publishReceipt ? { publish_receipt: publishReceipt } : {}),
1592
1777
  compose_recipe: composeRecipe,
1593
1778
  [OUTBOUND_HUB_MODE_FIELD]: this.currentHubMode(),
1594
1779
  },
@@ -2067,7 +2252,9 @@ function classifySynchronousAssetSubmit(items) {
2067
2252
  const bundle = [];
2068
2253
  for (let index = 0; index < items.length; index += 1) {
2069
2254
  const item = items[index];
2070
- if (!wire.validateWire(item).ok) {
2255
+ // 保持既有人工 wire 的结构分类合同;完整 schema/执行授权属于各自明确的准入门。
2256
+ // Gene 本地 hints 只从检查副本剥离,不改变 ledger 绑定的实际记录。
2257
+ if (!wire.validateWire(item['type'] === 'Gene' ? wire.stripGeneHints(item) : item).ok) {
2071
2258
  return { ok: false, error: `asset ${index}: malformed V2 wire asset` };
2072
2259
  }
2073
2260
  try {
@@ -2148,10 +2335,17 @@ async function resolveVerifiedExecution(verifier, input, expectedValidation, tim
2148
2335
  return undefined;
2149
2336
  if (candidate.trace.some((row, index) => row.command.trim() !== expectedValidation[index]))
2150
2337
  return undefined;
2338
+ if (!hubNs.isPublishVerificationRequest(input['verification_request'])
2339
+ || !hubNs.isPublishVerificationEvidence(candidate.binding)
2340
+ || wire.canonicalize(candidate.binding.request) !== wire.canonicalize(input['verification_request']))
2341
+ return undefined;
2151
2342
  // Compare the authoritative raw receipt first, then cross the common execution-evidence outlet exactly once.
2152
2343
  // A command that required redaction no longer identifies the executed program and must not unlock publication.
2153
- const sanitized = verify.sanitizeExecutionPayload({ ...candidate, validation: expectedValidation });
2154
- return sanitized.blocked ? undefined : sanitized.value;
2344
+ const sanitized = verify.sanitizeExecutionPayload({
2345
+ trace: candidate.trace, validation: expectedValidation,
2346
+ ...(candidate.blast_radius ? { blast_radius: candidate.blast_radius } : {}),
2347
+ });
2348
+ return sanitized.blocked ? undefined : { ...sanitized.value, binding: structuredClone(candidate.binding) };
2155
2349
  }
2156
2350
  catch {
2157
2351
  return undefined;
@@ -2180,28 +2374,35 @@ function declaredValidationCommands(input) {
2180
2374
  }
2181
2375
  return commands;
2182
2376
  }
2183
- async function resolveVerifiedExecutionAfterPreflight(verifier, input, timeoutMs, parentSignals = []) {
2377
+ async function resolveVerifiedExecutionAfterPreflight(verifier, input, timeoutMs, parentSignals = [], runtimeDomain = 'standalone', genePolicy) {
2184
2378
  if (!verifier)
2185
2379
  return undefined;
2186
2380
  if (parentSignals.some((signal) => signal.aborted))
2187
2381
  return undefined;
2188
- const preflight = await hubNs.distillConversation(input, { persist: false });
2382
+ const preflight = await hubNs.distillConversation(input, { persist: false, ...(genePolicy ? { genePolicy } : {}) });
2189
2383
  if (parentSignals.some((signal) => signal.aborted) || !preflight.ok || !preflight.quality.ok)
2190
2384
  return undefined;
2191
2385
  const validation = declaredValidationCommands(input);
2192
2386
  if (!validation)
2193
2387
  return undefined;
2194
2388
  // 只把通过质量与命令策略预检的最小验证输入交给宿主,绝不转发调用方的 execution/status/trace。
2195
- return resolveVerifiedExecution(verifier, { validation }, validation, timeoutMs, parentSignals);
2389
+ const verificationRequest = Object.freeze(hubNs.createConversationVerificationRequest(input, validation, runtimeDomain, randomUUID(), genePolicy));
2390
+ return resolveVerifiedExecution(verifier, { validation, verification_request: verificationRequest }, validation, timeoutMs, parentSignals);
2196
2391
  }
2197
- async function convertLegacyLooseAsset(value, verifyExecution, verifyExecutionTimeoutMs, ...parentSignals) {
2392
+ async function convertLegacyLooseAsset(value, verifyExecution, verifyExecutionTimeoutMs, ledger, sanitizeEnv = process.env, ...parentSignals) {
2198
2393
  const normalized = legacyLooseDistillInput(value);
2199
2394
  if (!normalized.ok)
2200
2395
  return normalized;
2396
+ const genePolicy = {
2397
+ ...(normalized.constraints ? { constraints: normalized.constraints } : {}),
2398
+ ...(normalized.category ? { category: normalized.category } : {}),
2399
+ };
2201
2400
  try {
2202
- const verifiedExecution = await resolveVerifiedExecutionAfterPreflight(verifyExecution, normalized.input, verifyExecutionTimeoutMs, parentSignals.filter((signal) => signal !== undefined));
2401
+ const verifiedExecution = await resolveVerifiedExecutionAfterPreflight(verifyExecution, normalized.input, verifyExecutionTimeoutMs, parentSignals.filter((signal) => signal !== undefined), ledger?.runtimeDomain, genePolicy);
2203
2402
  const distilled = await hubNs.distillConversation(normalized.input, {
2204
2403
  persist: false,
2404
+ publishSanitizeEnv: sanitizeEnv,
2405
+ genePolicy,
2205
2406
  ...(verifiedExecution ? { verifiedExecution } : {}),
2206
2407
  });
2207
2408
  if (!distilled.ok)
@@ -2217,17 +2418,20 @@ async function convertLegacyLooseAsset(value, verifyExecution, verifyExecutionTi
2217
2418
  : 'legacy_distill_quality_gate',
2218
2419
  };
2219
2420
  }
2220
- const gene = {
2221
- ...distilled.gene,
2222
- ...(normalized.constraints
2223
- ? { constraints: mergeLegacyConstraints(distilled.gene['constraints'], normalized.constraints) }
2224
- : {}),
2225
- ...(normalized.category ? { category: normalized.category } : {}),
2226
- };
2227
- const bundle = [gene, distilled.capsule].map(deterministicDistilledAsset);
2421
+ const sanitized = hubNs.sanitizeBundle([distilled.gene, distilled.capsule].map(deterministicDistilledAsset), { env: sanitizeEnv });
2422
+ if (sanitized.blocked)
2423
+ return { ok: false, error: 'legacy_distill_leak_blocked' };
2424
+ const bundle = sanitized.bundle;
2228
2425
  if (!bundle.every((asset) => wire.validateWire(asset).ok)) {
2229
2426
  return { ok: false, error: 'legacy_distill_invalid_wire_output' };
2230
2427
  }
2428
+ if (!verifiedExecution?.binding || !ledger)
2429
+ return { ok: false, error: 'legacy_distill_binding_missing' };
2430
+ const receipt = hubNs.createPublishBindingReceipt(bundle, verifiedExecution.binding, {
2431
+ validation: verifiedExecution.validation, trace: verifiedExecution.trace,
2432
+ });
2433
+ ledger.register(receipt, bundle);
2434
+ ledger.verify(bundle, receipt);
2231
2435
  return { ok: true, bundle };
2232
2436
  }
2233
2437
  catch {
@@ -2325,19 +2529,6 @@ function parseLegacyConstraints(value) {
2325
2529
  },
2326
2530
  };
2327
2531
  }
2328
- function mergeLegacyConstraints(base, legacy) {
2329
- const current = isRecordValue(base) ? base : {};
2330
- const currentMax = Number.isInteger(current['max_files']) && Number(current['max_files']) > 0
2331
- ? Number(current['max_files'])
2332
- : 20;
2333
- const currentPaths = Array.isArray(current['forbidden_paths'])
2334
- ? current['forbidden_paths'].filter((path) => typeof path === 'string')
2335
- : [];
2336
- return {
2337
- max_files: Math.min(currentMax, legacy.max_files ?? currentMax),
2338
- forbidden_paths: uniqueStrings([...currentPaths, ...(legacy.forbidden_paths ?? [])]),
2339
- };
2340
- }
2341
2532
  function parseLegacyCategory(value) {
2342
2533
  if (value === undefined)
2343
2534
  return { ok: true };