@evomap/evolver-proxy 2.0.37 → 2.0.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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),
@@ -17,6 +17,8 @@ export interface ProxyDaemonDeps {
17
17
  /** benchmark自定义provider必须接入审核账本;缺账本不等于Gene没有审核记录。 */
18
18
  sourceReview?: assetstore.ReviewLedger;
19
19
  hub: HubCapability;
20
+ /** Identity actually presented by the connected Hub runtime; terminal lifecycle state is scoped to it. */
21
+ currentNodeId?: () => string | undefined;
20
22
  /** Immutable Hub selection for IPC callers that must fail closed across public/private runtimes. */
21
23
  hubMode?: 'public' | 'private';
22
24
  /** 二选一: 传 storePath 让 ProxyDaemon 建 store, 或传已建 store(供 hub senderId 共享同一 node_id). */
@@ -175,6 +177,7 @@ export declare class ProxyDaemon {
175
177
  private readonly assetSubmitResponseTimeoutMs;
176
178
  private readonly hubAuthFailurePolicy;
177
179
  private readonly synchronousAssetSubmitScope;
180
+ private readonly publishBindingLedger;
178
181
  private readonly shadowMode;
179
182
  private readonly assetSearchCache;
180
183
  private readonly assetSearchInflight;
@@ -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;
@@ -112,6 +113,7 @@ export class ProxyDaemon {
112
113
  assetSubmitResponseTimeoutMs;
113
114
  hubAuthFailurePolicy;
114
115
  synchronousAssetSubmitScope;
116
+ publishBindingLedger;
115
117
  shadowMode;
116
118
  assetSearchCache = new Map();
117
119
  assetSearchInflight = new Map();
@@ -164,6 +166,11 @@ export class ProxyDaemon {
164
166
  if (!existingSynchronousAssetSubmitScope) {
165
167
  this.store.setState(SYNC_ASSET_SUBMIT_SCOPE_STATE_KEY, this.synchronousAssetSubmitScope);
166
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
+ ]));
167
174
  const assetStoreDir = deps.assetStoreDir ?? (deps.storePath ? join(dirname(deps.storePath), 'assets') : undefined);
168
175
  this.assetStore = deps.assetStore ?? (assetStoreDir ? new assetstore.LocalJsonlProvider(assetStoreDir) : undefined);
169
176
  this.sourceProvenance = deps.sourceProvenance ?? (this.benchmark && this.assetStore instanceof assetstore.LocalJsonlProvider
@@ -179,6 +186,7 @@ export class ProxyDaemon {
179
186
  const hubBindings = hubNs.makeHubBindings(hubToUse, {
180
187
  referenceScope: this.referenceStore?.scope,
181
188
  ...(deps.publishSanitizeEnv ? { sanitize: { env: deps.publishSanitizeEnv } } : {}),
189
+ verifyPublishBinding: (bundle, receipt) => { this.publishBindingLedger.verify(bundle, receipt); },
182
190
  });
183
191
  this.proxyHandler = hubBindings.asProxyHandler();
184
192
  const proxyHandler = this.proxyHandler;
@@ -276,6 +284,7 @@ export class ProxyDaemon {
276
284
  });
277
285
  this.lifecycle = new LifecycleManager({
278
286
  store: this.store, auth: hubToUse.auth, hello: deps.hello, heartbeat: deps.heartbeat, now: this.now,
287
+ ...(deps.currentNodeId ? { currentNodeId: deps.currentNodeId } : {}),
279
288
  ...(deps.heartbeatIntervalMs !== undefined ? { heartbeatIntervalMs: deps.heartbeatIntervalMs } : {}),
280
289
  ...(deps.evolverVersion ? { evolverVersion: deps.evolverVersion } : {}),
281
290
  ...(deps.helloMode ? { helloMode: deps.helloMode } : {}),
@@ -328,6 +337,12 @@ export class ProxyDaemon {
328
337
  if (result.stored && env.handler === 'proxy')
329
338
  this.notifyNewOutbound();
330
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
+ },
331
346
  ...(this.deps.onIpcAuthFailure ? { onAuthFailure: this.deps.onIpcAuthFailure } : {}),
332
347
  extraRoutes: [(ctx) => reference.withReferenceScope(this.referenceStore?.scope, () => this.handleProxyRoute(ctx))],
333
348
  });
@@ -337,6 +352,8 @@ export class ProxyDaemon {
337
352
  }
338
353
  catch { /* local discovery publishing must not block daemon startup */ }
339
354
  await this.lifecycle.doHello();
355
+ if (this.lifecycle.isTerminal)
356
+ this.nextHeartbeatAt = Number.POSITIVE_INFINITY;
340
357
  this.lifecycleArmed = true;
341
358
  this.drainProxyTraceBackfill();
342
359
  try {
@@ -512,7 +529,7 @@ export class ProxyDaemon {
512
529
  * flight from overwriting this reschedule. No-op until the daemon is started.
513
530
  */
514
531
  pokeHeartbeatLoop() {
515
- if (!this.started)
532
+ if (!this.started || this.lifecycle.isTerminal)
516
533
  return;
517
534
  this.heartbeatGeneration += 1;
518
535
  this.heartbeatFailures = 0;
@@ -1207,11 +1224,29 @@ export class ProxyDaemon {
1207
1224
  ctx.json(400, { error: 'mode=sync requires a full asset bundle' });
1208
1225
  return true;
1209
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
+ }
1210
1236
  await this.publishAssetSubmitSynchronously(ctx, outboundBundle, hubNs.recipeComposeRequested(body));
1211
1237
  return true;
1212
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
+ }
1213
1247
  const payload = {
1214
1248
  assets: outboundBundle,
1249
+ ...(publishReceipt ? { publish_receipt: publishReceipt } : {}),
1215
1250
  compose_recipe: hubNs.recipeComposeRequested(body),
1216
1251
  [OUTBOUND_HUB_MODE_FIELD]: this.currentHubMode(),
1217
1252
  };
@@ -1301,6 +1336,110 @@ export class ProxyDaemon {
1301
1336
  }
1302
1337
  return true;
1303
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
+ }
1304
1443
  if (ctx.route === 'POST /conversation/distill') {
1305
1444
  const body = (await ctx.readJson());
1306
1445
  const publishRequested = body['publish'] === true;
@@ -1325,7 +1464,7 @@ export class ProxyDaemon {
1325
1464
  if (publishRequested && abortPublish())
1326
1465
  return true;
1327
1466
  const verifiedExecution = publishRequested
1328
- ? 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)
1329
1468
  : undefined;
1330
1469
  if (publishRequested && abortPublish())
1331
1470
  return true;
@@ -1334,6 +1473,9 @@ export class ProxyDaemon {
1334
1473
  persist: body.persist === true,
1335
1474
  store: this.assetStore,
1336
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 } : {}),
1337
1479
  });
1338
1480
  if (publishRequested && abortPublish())
1339
1481
  return true;
@@ -1369,12 +1511,19 @@ export class ProxyDaemon {
1369
1511
  ctx.json(401, this.hubAuthFailureBody({ publish_status: 'failed', queued: false, stored: false }));
1370
1512
  return true;
1371
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);
1372
1520
  const env = mailbox.createEnvelope({
1373
1521
  type: 'asset_submit',
1374
1522
  payload: {
1375
1523
  source: 'conversation_distillation',
1376
1524
  distill_id: distill.distill_id,
1377
1525
  assets: [distill.gene, distill.capsule],
1526
+ publish_receipt: distill.publish_receipt,
1378
1527
  compose_recipe: body['publish_recipe'] !== false,
1379
1528
  title: typeof body.title === 'string' ? body.title : undefined,
1380
1529
  description: typeof body.summary === 'string' ? body.summary : undefined,
@@ -1568,7 +1717,7 @@ export class ProxyDaemon {
1568
1717
  }
1569
1718
  const results = [];
1570
1719
  for (const item of classified.items) {
1571
- 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);
1572
1721
  if (!converted.ok) {
1573
1722
  results.push({ ok: false, error: converted.error, statusCode: 422 });
1574
1723
  continue;
@@ -1615,6 +1764,7 @@ export class ProxyDaemon {
1615
1764
  }
1616
1765
  createSynchronousAssetSubmitEnvelope(bundle, source, now, composeRecipe = true) {
1617
1766
  const canonicalBundle = [...bundle].sort(compareSynchronousAssetSubmitAssets);
1767
+ const publishReceipt = this.publishBindingLedger.verify(canonicalBundle);
1618
1768
  const runtimeNamespace = this.deps.runtimeNamespace ?? 'default';
1619
1769
  const idempotencyKey = synchronousAssetSubmitKey(this.synchronousAssetSubmitScope, runtimeNamespace, this.currentHubMode(), canonicalBundle);
1620
1770
  return mailbox.createEnvelope({
@@ -1623,6 +1773,7 @@ export class ProxyDaemon {
1623
1773
  payload: {
1624
1774
  ...(source ? { source } : {}),
1625
1775
  assets: canonicalBundle,
1776
+ ...(publishReceipt ? { publish_receipt: publishReceipt } : {}),
1626
1777
  compose_recipe: composeRecipe,
1627
1778
  [OUTBOUND_HUB_MODE_FIELD]: this.currentHubMode(),
1628
1779
  },
@@ -2101,7 +2252,9 @@ function classifySynchronousAssetSubmit(items) {
2101
2252
  const bundle = [];
2102
2253
  for (let index = 0; index < items.length; index += 1) {
2103
2254
  const item = items[index];
2104
- if (!wire.validateWire(item).ok) {
2255
+ // 保持既有人工 wire 的结构分类合同;完整 schema/执行授权属于各自明确的准入门。
2256
+ // Gene 本地 hints 只从检查副本剥离,不改变 ledger 绑定的实际记录。
2257
+ if (!wire.validateWire(item['type'] === 'Gene' ? wire.stripGeneHints(item) : item).ok) {
2105
2258
  return { ok: false, error: `asset ${index}: malformed V2 wire asset` };
2106
2259
  }
2107
2260
  try {
@@ -2182,10 +2335,17 @@ async function resolveVerifiedExecution(verifier, input, expectedValidation, tim
2182
2335
  return undefined;
2183
2336
  if (candidate.trace.some((row, index) => row.command.trim() !== expectedValidation[index]))
2184
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;
2185
2342
  // Compare the authoritative raw receipt first, then cross the common execution-evidence outlet exactly once.
2186
2343
  // A command that required redaction no longer identifies the executed program and must not unlock publication.
2187
- const sanitized = verify.sanitizeExecutionPayload({ ...candidate, validation: expectedValidation });
2188
- 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) };
2189
2349
  }
2190
2350
  catch {
2191
2351
  return undefined;
@@ -2214,28 +2374,35 @@ function declaredValidationCommands(input) {
2214
2374
  }
2215
2375
  return commands;
2216
2376
  }
2217
- async function resolveVerifiedExecutionAfterPreflight(verifier, input, timeoutMs, parentSignals = []) {
2377
+ async function resolveVerifiedExecutionAfterPreflight(verifier, input, timeoutMs, parentSignals = [], runtimeDomain = 'standalone', genePolicy) {
2218
2378
  if (!verifier)
2219
2379
  return undefined;
2220
2380
  if (parentSignals.some((signal) => signal.aborted))
2221
2381
  return undefined;
2222
- const preflight = await hubNs.distillConversation(input, { persist: false });
2382
+ const preflight = await hubNs.distillConversation(input, { persist: false, ...(genePolicy ? { genePolicy } : {}) });
2223
2383
  if (parentSignals.some((signal) => signal.aborted) || !preflight.ok || !preflight.quality.ok)
2224
2384
  return undefined;
2225
2385
  const validation = declaredValidationCommands(input);
2226
2386
  if (!validation)
2227
2387
  return undefined;
2228
2388
  // 只把通过质量与命令策略预检的最小验证输入交给宿主,绝不转发调用方的 execution/status/trace。
2229
- 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);
2230
2391
  }
2231
- async function convertLegacyLooseAsset(value, verifyExecution, verifyExecutionTimeoutMs, ...parentSignals) {
2392
+ async function convertLegacyLooseAsset(value, verifyExecution, verifyExecutionTimeoutMs, ledger, sanitizeEnv = process.env, ...parentSignals) {
2232
2393
  const normalized = legacyLooseDistillInput(value);
2233
2394
  if (!normalized.ok)
2234
2395
  return normalized;
2396
+ const genePolicy = {
2397
+ ...(normalized.constraints ? { constraints: normalized.constraints } : {}),
2398
+ ...(normalized.category ? { category: normalized.category } : {}),
2399
+ };
2235
2400
  try {
2236
- 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);
2237
2402
  const distilled = await hubNs.distillConversation(normalized.input, {
2238
2403
  persist: false,
2404
+ publishSanitizeEnv: sanitizeEnv,
2405
+ genePolicy,
2239
2406
  ...(verifiedExecution ? { verifiedExecution } : {}),
2240
2407
  });
2241
2408
  if (!distilled.ok)
@@ -2251,17 +2418,20 @@ async function convertLegacyLooseAsset(value, verifyExecution, verifyExecutionTi
2251
2418
  : 'legacy_distill_quality_gate',
2252
2419
  };
2253
2420
  }
2254
- const gene = {
2255
- ...distilled.gene,
2256
- ...(normalized.constraints
2257
- ? { constraints: mergeLegacyConstraints(distilled.gene['constraints'], normalized.constraints) }
2258
- : {}),
2259
- ...(normalized.category ? { category: normalized.category } : {}),
2260
- };
2261
- 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;
2262
2425
  if (!bundle.every((asset) => wire.validateWire(asset).ok)) {
2263
2426
  return { ok: false, error: 'legacy_distill_invalid_wire_output' };
2264
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);
2265
2435
  return { ok: true, bundle };
2266
2436
  }
2267
2437
  catch {
@@ -2359,19 +2529,6 @@ function parseLegacyConstraints(value) {
2359
2529
  },
2360
2530
  };
2361
2531
  }
2362
- function mergeLegacyConstraints(base, legacy) {
2363
- const current = isRecordValue(base) ? base : {};
2364
- const currentMax = Number.isInteger(current['max_files']) && Number(current['max_files']) > 0
2365
- ? Number(current['max_files'])
2366
- : 20;
2367
- const currentPaths = Array.isArray(current['forbidden_paths'])
2368
- ? current['forbidden_paths'].filter((path) => typeof path === 'string')
2369
- : [];
2370
- return {
2371
- max_files: Math.min(currentMax, legacy.max_files ?? currentMax),
2372
- forbidden_paths: uniqueStrings([...currentPaths, ...(legacy.forbidden_paths ?? [])]),
2373
- };
2374
- }
2375
2532
  function parseLegacyCategory(value) {
2376
2533
  if (value === undefined)
2377
2534
  return { ok: true };
@@ -0,0 +1,17 @@
1
+ import { hub, type assetstore } from '@evomap/evolver-core';
2
+ interface StateStore {
3
+ getState(key: string): string | undefined;
4
+ setState(key: string, value: string): void;
5
+ }
6
+ /** 与 durable mailbox 同位;不信任 HTTP 提交的自签名/hash receipt。 */
7
+ export declare class PublishBindingLedger {
8
+ private readonly store;
9
+ readonly runtimeDomain: string;
10
+ readonly runtimeDigest: string;
11
+ constructor(store: StateStore, runtimeDomain: string);
12
+ register(receipt: hub.PublishBindingReceipt, bundle: readonly assetstore.AssetRecord[]): void;
13
+ verify(bundle: readonly assetstore.AssetRecord[], supplied?: unknown): hub.PublishBindingAuthorization | undefined;
14
+ private key;
15
+ private memberKey;
16
+ }
17
+ export {};
@@ -0,0 +1,79 @@
1
+ import { hub, wire } from '@evomap/evolver-core';
2
+ /** 与 durable mailbox 同位;不信任 HTTP 提交的自签名/hash receipt。 */
3
+ export class PublishBindingLedger {
4
+ store;
5
+ runtimeDomain;
6
+ runtimeDigest;
7
+ constructor(store, runtimeDomain) {
8
+ this.store = store;
9
+ this.runtimeDomain = runtimeDomain;
10
+ this.runtimeDigest = hub.publishBindingDigest('publish-runtime.v1', runtimeDomain);
11
+ }
12
+ register(receipt, bundle) {
13
+ // 登记时必须看到实际完整内容;只凭 receipt digest 无法推断任何成员授权。
14
+ hub.assertPublishBindingReceipt(bundle, receipt, this.runtimeDigest);
15
+ const key = this.key(receipt.bundleDigest);
16
+ const previous = this.store.getState(key);
17
+ // 一个 bundle 可有多个合法验证根;每个 receipt 单独保存,索引只用于无 sidecar 的同内容重试。
18
+ this.store.setState(`${key}:${receipt.receiptId}`, JSON.stringify(receipt));
19
+ for (const asset of bundle) {
20
+ const member = hub.createPublishMemberBindingReceipt(asset, receipt);
21
+ const memberKey = this.memberKey(member.bundleDigest);
22
+ this.store.setState(`${memberKey}:${member.receiptId}`, JSON.stringify(member));
23
+ if (!this.store.getState(memberKey))
24
+ this.store.setState(memberKey, member.receiptId);
25
+ }
26
+ if (!previous)
27
+ this.store.setState(key, receipt.receiptId);
28
+ }
29
+ verify(bundle, supplied) {
30
+ const required = supplied !== undefined || hub.requiresPublishBinding(bundle);
31
+ if (!required)
32
+ return undefined;
33
+ const digest = hub.publishBundleDigest(bundle);
34
+ let key = this.key(digest);
35
+ let id = supplied === undefined ? this.store.getState(key) : supplied?.receiptId;
36
+ if (supplied !== undefined && supplied?.version === hub.PUBLISH_MEMBER_BINDING_VERSION) {
37
+ key = this.memberKey(digest);
38
+ }
39
+ else if (supplied === undefined && id === undefined && bundle.length === 1) {
40
+ key = this.memberKey(digest);
41
+ id = this.store.getState(key);
42
+ }
43
+ if (typeof id !== 'string' || !/^sha256:[0-9a-f]{64}$/.test(id))
44
+ throw new Error('publish_binding_missing');
45
+ const raw = this.store.getState(`${key}:${id}`);
46
+ if (!raw || raw.length > 4096)
47
+ throw new Error('publish_binding_unregistered');
48
+ let registered;
49
+ try {
50
+ registered = JSON.parse(raw);
51
+ }
52
+ catch {
53
+ throw new Error('publish_binding_ledger_invalid');
54
+ }
55
+ hub.assertPublishBindingAuthorization(bundle, registered, this.runtimeDigest);
56
+ if (registered.version === hub.PUBLISH_MEMBER_BINDING_VERSION) {
57
+ const parentRaw = this.store.getState(`${this.key(registered.parentBundleDigest)}:${registered.parentReceiptId}`);
58
+ if (!parentRaw || parentRaw.length > 4096)
59
+ throw new Error('publish_binding_parent_unregistered');
60
+ let parent;
61
+ try {
62
+ parent = JSON.parse(parentRaw);
63
+ }
64
+ catch {
65
+ throw new Error('publish_binding_ledger_invalid');
66
+ }
67
+ hub.assertPublishBindingReceiptIdentity(parent, this.runtimeDigest);
68
+ if (parent.receiptId !== registered.parentReceiptId || parent.bundleDigest !== registered.parentBundleDigest) {
69
+ throw new Error('publish_binding_parent_unregistered');
70
+ }
71
+ }
72
+ if (supplied !== undefined && wire.canonicalize(supplied) !== wire.canonicalize(registered)) {
73
+ throw new Error('publish_binding_unregistered');
74
+ }
75
+ return registered;
76
+ }
77
+ key(digest) { return `publish-binding:v1:${this.runtimeDigest}:${digest}`; }
78
+ memberKey(digest) { return `publish-binding-member:v1:${this.runtimeDigest}:${digest}`; }
79
+ }