@evomap/evolver-proxy 2.0.47 → 2.0.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/bin/evolver-proxy.js +86 -50
  2. package/dist/daemon/backgroundCuration.d.ts +53 -0
  3. package/dist/daemon/backgroundCuration.js +156 -0
  4. package/dist/daemon/curationGit.d.ts +5 -0
  5. package/dist/daemon/curationGit.js +140 -0
  6. package/dist/daemon/localRecall.js +38 -3
  7. package/dist/daemon/observedEvidence.d.ts +43 -0
  8. package/dist/daemon/observedEvidence.js +116 -0
  9. package/dist/daemon/proxyDaemon.d.ts +31 -0
  10. package/dist/daemon/proxyDaemon.js +201 -28
  11. package/dist/daemon/publishBindingLedger.d.ts +38 -0
  12. package/dist/daemon/publishBindingLedger.js +171 -1
  13. package/dist/daemon/recallContext.js +2 -1
  14. package/dist/lifecycle/claimNudge.js +1 -1
  15. package/dist/lifecycle/deployGuard.js +1 -1
  16. package/dist/lifecycle/legacyNodeId.js +1 -1
  17. package/dist/lifecycle/manager.js +1 -1
  18. package/dist/llm/index.js +1 -1
  19. package/dist/llm/server.js +1 -1
  20. package/dist/llm/traceBackfill.js +1 -1
  21. package/dist/llm/traceConfig.js +1 -1
  22. package/dist/llm/traceControl.js +1 -1
  23. package/dist/llm/traceEnvelope.js +1 -1
  24. package/dist/llm/traceSink.js +1 -1
  25. package/dist/llm/traceUploadPayload.js +1 -1
  26. package/dist/llm/upstream.js +1 -1
  27. package/dist/router/cachePassthrough.js +1 -1
  28. package/dist/router/features.js +1 -1
  29. package/dist/router/index.js +1 -1
  30. package/dist/router/messagesRoute.js +1 -1
  31. package/dist/router/modelRouter.js +1 -1
  32. package/dist/router/providerRoutes.js +1 -1
  33. package/dist/router/sseScan.js +1 -1
  34. package/dist/selfUpdate/recoveryChildStartGate.js +4 -2
  35. package/dist/sync/engine.js +1 -1
  36. package/package.json +3 -3
@@ -0,0 +1,116 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { isAbsolute, join } from 'node:path';
4
+ import { algo, assetstore, hub as hubNs, verify } from '@evomap/evolver-core';
5
+ const MAX_DIFF_BYTES = 256 * 1024;
6
+ export class VerificationContextStore {
7
+ dir;
8
+ constructor(assetStoreDir) {
9
+ this.dir = join(assetStoreDir, 'verification-context');
10
+ }
11
+ pathOf(geneAssetId) {
12
+ return join(this.dir, `${createHash('sha256').update(geneAssetId).digest('hex').slice(0, 40)}.json`);
13
+ }
14
+ get(geneAssetId) {
15
+ const path = this.pathOf(geneAssetId);
16
+ if (!existsSync(path))
17
+ return undefined;
18
+ try {
19
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
20
+ return parsed.geneAssetId === geneAssetId ? parsed : undefined;
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ /** A Gene is addressed by its content, so once it is published a later plan for it keeps that mark. */
27
+ put(context) {
28
+ mkdirSync(this.dir, { recursive: true, mode: 0o700 });
29
+ const path = this.pathOf(context.geneAssetId);
30
+ const published = context.published ?? this.get(context.geneAssetId)?.published;
31
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
32
+ writeFileSync(tmp, `${JSON.stringify(published ? { ...context, published } : context)}\n`, { mode: 0o600 });
33
+ renameSync(tmp, path);
34
+ }
35
+ list() {
36
+ if (!existsSync(this.dir))
37
+ return [];
38
+ const out = [];
39
+ for (const name of readdirSync(this.dir)) {
40
+ if (!name.endsWith('.json'))
41
+ continue;
42
+ try {
43
+ out.push(JSON.parse(readFileSync(join(this.dir, name), 'utf8')));
44
+ }
45
+ catch { /* a torn file is skipped, never fatal */ }
46
+ }
47
+ return out;
48
+ }
49
+ }
50
+ function record(value) {
51
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
52
+ }
53
+ function planDigest({ root, head, diff, checks }) {
54
+ return hubNs.publishBindingDigest('observed-validation-plan.v1', { root, head, diff: diff ?? '', checks });
55
+ }
56
+ function checkMatchesCommand(check, command) {
57
+ return Boolean(check && typeof check.command === 'string' && check.command === command
58
+ && check.command.length <= 180 && verify.isValidationCommandAllowed(check.command)
59
+ && (check.cwd === undefined || (typeof check.cwd === 'string' && !isAbsolute(check.cwd))));
60
+ }
61
+ /** Old sidecars may already have lost cwd occurrences and must be observed again. */
62
+ export function hasVerificationPlan(context) {
63
+ if (typeof context.root !== 'string' || !isAbsolute(context.root)
64
+ || typeof context.head !== 'string' || !/^[0-9a-f]{7,64}$/.test(context.head)
65
+ || (context.diff !== undefined && (typeof context.diff !== 'string' || Buffer.byteLength(context.diff, 'utf8') > MAX_DIFF_BYTES))
66
+ || !Array.isArray(context.commands) || !Array.isArray(context.checks)
67
+ || context.checks.length < 1 || context.checks.length > 8 || context.commands.length !== context.checks.length)
68
+ return false;
69
+ return context.checks.every((check, index) => checkMatchesCommand(check, context.commands[index]))
70
+ && typeof context.planDigest === 'string' && context.planDigest === planDigest(context);
71
+ }
72
+ /** The project state a host hook recorded with an observed distillation, or none when it cannot be replayed. */
73
+ export function verificationContextOf(body, gene, now, checks) {
74
+ const project = record(body['project']);
75
+ const root = typeof project['root'] === 'string' ? project['root'] : '';
76
+ const head = typeof project['head'] === 'string' ? project['head'] : '';
77
+ if (!checks?.length || project['diff_omitted'] !== undefined)
78
+ return undefined;
79
+ if (project['diff'] !== undefined && typeof project['diff'] !== 'string')
80
+ return undefined;
81
+ const diff = project['diff'];
82
+ const validation = Array.isArray(gene['validation']) ? gene['validation'] : [];
83
+ if (validation.includes('node --version'))
84
+ return undefined;
85
+ const plan = { root, head, ...(diff ? { diff } : {}), checks: checks.map((check) => ({ ...check })) };
86
+ const { project: _project, execution: _execution, persist: _persist, publish: _publish, ...distillInput } = body;
87
+ const context = {
88
+ geneAssetId: gene.asset_id,
89
+ geneId: String(gene['id'] ?? gene.asset_id),
90
+ ...plan, commands: validation, planDigest: planDigest(plan), distillInput, recordedAt: now.toISOString(),
91
+ };
92
+ return hasVerificationPlan(context) ? context : undefined;
93
+ }
94
+ /** Whether a host hook observed the reused turn's last check and its result; agent-reported evidence never qualifies. */
95
+ export function isObservedCheckEvidence(evidence) {
96
+ return evidence?.['source'] === 'observed' && evidence['tier'] === 'L1' && typeof record(evidence['check'])['passed'] === 'boolean';
97
+ }
98
+ export async function recordObservedReuse(store, assetId, taskId, passed) {
99
+ if (!taskId)
100
+ return 'no_task';
101
+ const gene = await store.get(assetId);
102
+ if (!gene || gene.type !== 'Gene')
103
+ return 'not_local';
104
+ const capsule = algo.observedReuseCapsule({
105
+ geneId: String(gene['id'] ?? gene.asset_id),
106
+ geneAssetId: gene.asset_id,
107
+ trigger: Array.isArray(gene['signals_match']) ? gene['signals_match'].map(String).slice(0, 8) : [],
108
+ taskId,
109
+ passed,
110
+ });
111
+ const existing = await store.search({ kind: 'Capsule', gene: String(gene['id'] ?? gene.asset_id), limit: 10_000 });
112
+ if (existing.some((c) => c['id'] === capsule.id))
113
+ return 'duplicate';
114
+ await store.put(capsule);
115
+ return 'recorded';
116
+ }
@@ -5,6 +5,7 @@ import { type SelfUpdateDeps } from '../selfUpdate/executor.js';
5
5
  import type { AtpOrderConsentGate } from './atpConsent.js';
6
6
  import type { PrivateBoundReuseFeedback } from '../private/adapterLoader.js';
7
7
  import { type ReuseTallies } from './localRecall.js';
8
+ import { type VerificationPlan } from './backgroundCuration.js';
8
9
  import { type PublishRecallVerifierPort } from './publishRecallVerifier.js';
9
10
  type HubCapability = hubNs.HubCapability;
10
11
  type AssetStoreProvider = assetstore.AssetStoreProvider;
@@ -102,6 +103,8 @@ export interface ProxyDaemonDeps {
102
103
  * 宿主专属的真实执行验证器。缺失时,conversation distill 只能返回草稿,绝不持久化或排队发布。
103
104
  */
104
105
  publishExecutionVerifier?: ConversationDistillExecutionVerifier;
106
+ /** Builds a verifier bound to one validation copy; the background curation pass verifies each Gene in its own copy. */
107
+ publishVerifierForRoot?: (root: string, plan?: VerificationPlan) => ConversationDistillExecutionVerifier;
105
108
  /** 验证器响应的硬超时,防止发布请求因宿主执行器挂起而永久占用连接。 */
106
109
  publishExecutionVerifierTimeoutMs?: number;
107
110
  }
@@ -210,6 +213,10 @@ export declare class ProxyDaemon {
210
213
  /** A poke that arrived between ticks (no sleep in flight) parks the wake here so it is not lost. */
211
214
  private wakeRunnerPending;
212
215
  private started;
216
+ private readonly verificationContexts;
217
+ private lastRouteAt;
218
+ private curationTimer;
219
+ private curationRunning;
213
220
  private feedbackRecovery;
214
221
  private lifecycleArmed;
215
222
  private lastTickAt;
@@ -237,6 +244,13 @@ export declare class ProxyDaemon {
237
244
  private recordTickError;
238
245
  /** 启动: 锁 + IPC 监听 + 初次 hello. 返回 IPC 端口. */
239
246
  start(): Promise<number>;
247
+ private scheduleCuration;
248
+ private curateWhenIdle;
249
+ private enqueueVerifiedDistillation;
250
+ private trackStoredDraft;
251
+ private enqueueDistillPublication;
252
+ private registerDistillPublication;
253
+ private distillPublicationEnvelope;
240
254
  private listenIpc;
241
255
  private drainTriggerFeedbackRecovery;
242
256
  /** 单轮: core pump/TTL/wake + proxy 出站 + hub 入站 + 到点心跳. */
@@ -294,6 +308,23 @@ export declare class ProxyDaemon {
294
308
  private publishAssetSubmitSynchronously;
295
309
  private createSynchronousAssetSubmitEnvelope;
296
310
  private composeRecipeAfterAcceptedSubmit;
311
+ /**
312
+ * 记住本节点已发布的 Gene:之后单独发布引用它的 Capsule 时,parent 有本机发布事实可查。
313
+ * 只在 Hub 接受发布后登记;本机记账失败不得让已接受的发布变成失败。
314
+ */
315
+ private recordPublishedParents;
316
+ /**
317
+ * 记下本节点正在为这些 Gene 提交发布。
318
+ * 单独发布的 Gene 从来不需要 binding,也就不会在 ledger 里登记任何 parent 事实;
319
+ * 没有这条事实,之后单独发布引用它的 Capsule 必然被 publish_binding_missing 拒绝。
320
+ */
321
+ private recordPublishingParents;
322
+ /**
323
+ * parent 发布终态失败:这份 parent 不再授权单独发布的 Capsule。
324
+ * 可重试的失败不算终态,发布仍会继续。
325
+ */
326
+ private recordFailedParents;
327
+ private submitEnvelopeAssets;
297
328
  private currentHubMode;
298
329
  private handleHubModeBoundOutbound;
299
330
  private publishSynchronousBundle;
@@ -14,8 +14,12 @@ import { classifyDiscoveryUpstreamError } from './discoveryErrors.js';
14
14
  import { LOCAL_RECALL_STALE_MS, LOCAL_RECALL_TIMEOUT_MS, MAX_OUTSTANDING_LOCAL_READS, recallFromLocalStore, rootEventReuseTallies } from './localRecall.js';
15
15
  import { PublishBindingLedger } from './publishBindingLedger.js';
16
16
  import { recallContextOf } from './recallContext.js';
17
+ import { CURATION_IDLE_MS, CURATION_INTERVAL_MS, curationStatus, runCurationTick } from './backgroundCuration.js';
18
+ import { VerificationContextStore, isObservedCheckEvidence, recordObservedReuse, verificationContextOf } from './observedEvidence.js';
17
19
  import { PublishRecallVerifier, resolvePublishRecallConfig, } from './publishRecallVerifier.js';
18
20
  const DEFAULT_PUBLISH_EXECUTION_VERIFY_TIMEOUT_MS = 30_000;
21
+ // A host-observed distillation carries the turn's diff (≤256 KiB) beside the conversation itself.
22
+ const MAX_DISTILL_BODY_BYTES = 512 * 1024;
19
23
  export const DEFAULT_IPC_PORT = 19820;
20
24
  // V1 local-proxy compatibility contract; independent of the V2 mailbox envelope schema.
21
25
  const PROXY_PROTOCOL_VERSION = '0.1.0';
@@ -137,6 +141,10 @@ export class ProxyDaemon {
137
141
  /** A poke that arrived between ticks (no sleep in flight) parks the wake here so it is not lost. */
138
142
  wakeRunnerPending = false;
139
143
  started = false;
144
+ verificationContexts;
145
+ lastRouteAt = 0;
146
+ curationTimer;
147
+ curationRunning = false;
140
148
  feedbackRecovery;
141
149
  lifecycleArmed = false;
142
150
  lastTickAt;
@@ -192,6 +200,8 @@ export class ProxyDaemon {
192
200
  ? new assetstore.ProvenanceStore(this.assetStore.baseDir) : undefined);
193
201
  this.sourceReview = deps.sourceReview ?? (this.assetStore instanceof assetstore.LocalJsonlProvider
194
202
  ? new assetstore.ReviewLedger(this.assetStore.baseDir) : undefined);
203
+ this.verificationContexts = this.assetStore instanceof assetstore.LocalJsonlProvider
204
+ ? new VerificationContextStore(this.assetStore.baseDir) : undefined;
195
205
  const referenceBase = assetStoreDir ?? deps.assetStore?.baseDir;
196
206
  this.referenceStore = referenceBase ? new reference.ReferenceStore(join(referenceBase, 'references')) : undefined;
197
207
  this.referenceStore?.search({ max_assets: 1 });
@@ -203,7 +213,13 @@ export class ProxyDaemon {
203
213
  ...(deps.publishSanitizeEnv ? { sanitize: { env: deps.publishSanitizeEnv } } : {}),
204
214
  verifyPublishBinding: (bundle, receipt) => { this.publishBindingLedger.verify(bundle, receipt); },
205
215
  });
206
- this.proxyHandler = hubBindings.asProxyHandler();
216
+ const hubProxyHandler = hubBindings.asProxyHandler();
217
+ // Hub 接受是"本节点已发布这份 Gene"的唯一事实来源,出站与同步提交都走这一个出口。
218
+ this.proxyHandler = async (envelope) => {
219
+ const result = await hubProxyHandler(envelope);
220
+ this.recordPublishedParents(envelope, result);
221
+ return result;
222
+ };
207
223
  const proxyHandler = this.proxyHandler;
208
224
  const syncProxyHandler = (envelope) => this.handleHubModeBoundOutbound(envelope);
209
225
  const assetByIdSource = isAssetByIdFetcher(deps.hub) ? deps.hub : (isAssetByIdFetcher(hubToUse) ? hubToUse : undefined);
@@ -282,6 +298,7 @@ export class ProxyDaemon {
282
298
  },
283
299
  onOutboundTerminal: (envelope, error) => {
284
300
  this.collaborationFacade.handleOutboundTerminal(envelope, error);
301
+ this.recordFailedParents(envelope);
285
302
  try {
286
303
  this.cacheSynchronousAssetSubmitTerminal(envelope, error);
287
304
  }
@@ -364,7 +381,7 @@ export class ProxyDaemon {
364
381
  this.publishBindingLedger.verify(assets, publishReceipt);
365
382
  },
366
383
  ...(this.deps.onIpcAuthFailure ? { onAuthFailure: this.deps.onIpcAuthFailure } : {}),
367
- routeBodyLimits: hubNs.recipeIpcBodyLimits,
384
+ routeBodyLimits: { ...hubNs.recipeIpcBodyLimits, 'POST /conversation/distill': MAX_DISTILL_BODY_BYTES },
368
385
  extraRoutes: [(ctx) => reference.withReferenceScope(this.referenceStore?.scope, () => this.handleProxyRoute(ctx))],
369
386
  });
370
387
  const port = await this.listenIpc(this.ipc);
@@ -382,6 +399,7 @@ export class ProxyDaemon {
382
399
  }
383
400
  catch { /* verifier availability must not block proxy startup */ }
384
401
  this.started = true;
402
+ this.scheduleCuration();
385
403
  return port;
386
404
  }
387
405
  catch (err) {
@@ -399,6 +417,107 @@ export class ProxyDaemon {
399
417
  throw err;
400
418
  }
401
419
  }
420
+ scheduleCuration() {
421
+ if (!this.assetStore || !this.sourceReview || !this.verificationContexts)
422
+ return;
423
+ this.curationTimer = setInterval(() => { void this.curateWhenIdle(); }, CURATION_INTERVAL_MS);
424
+ this.curationTimer.unref?.();
425
+ }
426
+ async curateWhenIdle() {
427
+ if (!this.started || this.curationRunning || this.now() - this.lastRouteAt < CURATION_IDLE_MS)
428
+ return;
429
+ if (!this.assetStore || !this.sourceReview || !this.verificationContexts)
430
+ return;
431
+ this.curationRunning = true;
432
+ try {
433
+ const verifierForRoot = this.deps.publishVerifierForRoot;
434
+ await runCurationTick({
435
+ store: this.assetStore,
436
+ review: this.sourceReview,
437
+ contexts: this.verificationContexts,
438
+ verifierForRoot,
439
+ verify: (body, verifier, planDigest) => resolveVerifiedExecutionAfterPreflight(verifier, body, this.deps.publishExecutionVerifierTimeoutMs, [this.publishAbortController.signal], this.publishBindingLedger.runtimeDomain, undefined, planDigest),
440
+ enqueue: (body, verified, planDigest, commit) => this.enqueueVerifiedDistillation(body, verified, planDigest, commit),
441
+ now: () => new Date(this.now()),
442
+ });
443
+ }
444
+ catch (err) {
445
+ this.recordTickError('core', err instanceof Error ? err : new Error(String(err)));
446
+ }
447
+ finally {
448
+ this.curationRunning = false;
449
+ }
450
+ }
451
+ async enqueueVerifiedDistillation(body, verifiedExecution, validationPlanDigest, commit) {
452
+ if (this.hubAuthFailed())
453
+ return { queued: false, reason: 'hub_auth_failed' };
454
+ const signal = this.publishAbortController.signal;
455
+ const distill = await hubNs.distillConversation(body, {
456
+ persist: true,
457
+ store: this.assetStore,
458
+ verifiedExecution,
459
+ validationPlanDigest,
460
+ // Distillation verifies the receipt before persistence; only the final review fence may register it.
461
+ registerPublishReceipt: (receipt, bundle) => hubNs.assertPublishBindingReceipt(bundle, receipt, this.publishBindingLedger.runtimeDigest),
462
+ publishSignal: signal,
463
+ ...(this.deps.publishSanitizeEnv ? { publishSanitizeEnv: this.deps.publishSanitizeEnv } : {}),
464
+ });
465
+ if (!distill.ok)
466
+ return { queued: false, reason: distill.reason ?? 'distill_failed' };
467
+ if (distill.publishable !== true || !distill.event || !distill.publish_receipt)
468
+ return { queued: false, reason: 'publish_binding_missing' };
469
+ if (signal.aborted)
470
+ return { queued: false, reason: 'publish_binding_aborted' };
471
+ const envelope = this.distillPublicationEnvelope(body, distill, this.now());
472
+ const receipt = distill.publish_receipt;
473
+ const outcome = commit(() => this.store.sendWithState(envelope, () => this.registerDistillPublication(envelope, receipt)).stored);
474
+ if (outcome !== 'stored' && outcome !== 'not_stored')
475
+ return { queued: false, reason: outcome };
476
+ if (outcome === 'stored')
477
+ this.notifyNewOutbound();
478
+ return { queued: outcome === 'stored', envelopeId: envelope.id,
479
+ assetIds: [distill.gene.asset_id, distill.capsule.asset_id, distill.event.asset_id] };
480
+ }
481
+ trackStoredDraft(body, gene, capsule, checks) {
482
+ this.sourceReview?.quarantineIfAbsent(gene.asset_id, 'host-observed distillation — on trial until promoted');
483
+ if (capsule['outcome']?.status !== 'success')
484
+ return;
485
+ const context = verificationContextOf(body, gene, new Date(this.now()), checks);
486
+ if (context)
487
+ this.verificationContexts?.put(context);
488
+ }
489
+ enqueueDistillPublication(body, distill, now) {
490
+ const env = this.distillPublicationEnvelope(body, distill, now);
491
+ this.registerDistillPublication(env, distill.publish_receipt);
492
+ const r = this.store.send(env);
493
+ if (r.stored)
494
+ this.notifyNewOutbound();
495
+ return { id: env.id, message_id: env.id, receiptId: r.receiptId, status: 'pending', stored: r.stored };
496
+ }
497
+ registerDistillPublication(envelope, receipt) {
498
+ const bundle = this.submitEnvelopeAssets(envelope);
499
+ this.publishBindingLedger.register(receipt, bundle);
500
+ this.publishBindingLedger.verify(bundle, receipt);
501
+ }
502
+ distillPublicationEnvelope(body, distill, now) {
503
+ const publicationBundle = [distill.gene, distill.capsule, distill.event];
504
+ hubNs.assertEvolutionEventPublishBundle(publicationBundle);
505
+ return mailbox.createEnvelope({
506
+ type: 'asset_submit',
507
+ payload: {
508
+ source: 'conversation_distillation',
509
+ distill_id: distill.distill_id,
510
+ assets: publicationBundle,
511
+ publish_receipt: distill.publish_receipt,
512
+ compose_recipe: body['publish_recipe'] !== false,
513
+ title: typeof body.title === 'string' ? body.title : undefined,
514
+ description: typeof body.summary === 'string' ? body.summary : undefined,
515
+ [OUTBOUND_HUB_MODE_FIELD]: this.currentHubMode(),
516
+ },
517
+ runtimeNamespace: this.deps.runtimeNamespace ?? 'default',
518
+ now,
519
+ });
520
+ }
402
521
  async listenIpc(ipc) {
403
522
  const requestedPort = this.deps.ipcPort ?? DEFAULT_IPC_PORT;
404
523
  if (requestedPort !== 0)
@@ -637,6 +756,10 @@ export class ProxyDaemon {
637
756
  this.publishAbortController.abort(new Error('proxy_daemon_stopped'));
638
757
  }
639
758
  this.nextTickDueAt = undefined;
759
+ if (this.curationTimer) {
760
+ clearInterval(this.curationTimer);
761
+ this.curationTimer = undefined;
762
+ }
640
763
  if (this.forceUpdateTimer) {
641
764
  clearTimeout(this.forceUpdateTimer);
642
765
  this.forceUpdateTimer = undefined;
@@ -1036,6 +1159,7 @@ export class ProxyDaemon {
1036
1159
  }
1037
1160
  }
1038
1161
  async handleProxyRoute(ctx) {
1162
+ this.lastRouteAt = this.now();
1039
1163
  const expectedHeader = singleHeader(ctx.req.headers['x-evomap-expected-hub-mode']);
1040
1164
  if (hubModeMismatch(expectedHeader, this.deps.hubMode)) {
1041
1165
  ctx.json(409, { error: 'proxy_hub_mode_mismatch' });
@@ -1092,6 +1216,9 @@ export class ProxyDaemon {
1092
1216
  feedback_destination_id_format: 'proxy-bound.v1',
1093
1217
  } : {}),
1094
1218
  recipe_execution_scope: recipeIpcScope(this.hub.recipes?.execution),
1219
+ ...(this.verificationContexts && this.sourceReview ? {
1220
+ background_curation: curationStatus(this.verificationContexts, this.sourceReview, this.deps.publishVerifierForRoot !== undefined),
1221
+ } : {}),
1095
1222
  outbound_pending: this.store.countPending('proxy', this.deps.runtimeNamespace),
1096
1223
  inbound_pending: this.store.countPending('agent', this.deps.runtimeNamespace) + this.store.countPending('core', this.deps.runtimeNamespace),
1097
1224
  last_sync_at: this.store.getState('sync:last_sync_at') ?? null,
@@ -1273,11 +1400,13 @@ export class ProxyDaemon {
1273
1400
  const q = [body.q, body.query, body.text].find((value) => typeof value === 'string' && value.trim().length > 0);
1274
1401
  const cursor = typeof body.cursor === 'string' && body.cursor.trim() ? body.cursor.trim() : undefined;
1275
1402
  const sort = typeof body.sort === 'string' && body.sort.trim() ? body.sort.trim() : undefined;
1403
+ const context = q ? recallContextOf(body.context) : undefined;
1276
1404
  const request = {
1277
1405
  ...(q ? { q } : {}),
1278
1406
  limit,
1279
1407
  ...(cursor ? { cursor } : {}),
1280
1408
  ...(sort ? { sort } : {}),
1409
+ ...(context ? { context } : {}),
1281
1410
  };
1282
1411
  let receipt;
1283
1412
  try {
@@ -1294,6 +1423,7 @@ export class ProxyDaemon {
1294
1423
  recipes: receipt.recipes,
1295
1424
  ...(receipt.nextCursor ? { nextCursor: receipt.nextCursor } : {}),
1296
1425
  ...(receipt.hasMore !== undefined ? { hasMore: receipt.hasMore } : {}),
1426
+ ...(receipt.contextFit ? { context_fit: receipt.contextFit } : {}),
1297
1427
  query: body,
1298
1428
  });
1299
1429
  return true;
@@ -1517,6 +1647,7 @@ export class ProxyDaemon {
1517
1647
  now: ctx.now,
1518
1648
  });
1519
1649
  const r = this.store.send(env);
1650
+ this.recordPublishingParents(outboundBundle);
1520
1651
  if (r.stored)
1521
1652
  this.notifyNewOutbound();
1522
1653
  ctx.json(202, {
@@ -1602,8 +1733,11 @@ export class ProxyDaemon {
1602
1733
  ctx.json(400, { recorded: false, error: parsed.error });
1603
1734
  return true;
1604
1735
  }
1736
+ const local = isObservedCheckEvidence(parsed.report.evidence) && this.assetStore
1737
+ ? await recordObservedReuse(this.assetStore, parsed.report.assetId, parsed.report.taskId, parsed.report.outcome === 'success').catch(() => 'failed')
1738
+ : undefined;
1605
1739
  if (expectedDestination === undefined && !this.reuseResultReporter) {
1606
- ctx.json(200, { recorded: false, reason: 'reuse_result_not_configured' });
1740
+ ctx.json(200, { recorded: false, reason: 'reuse_result_not_configured', ...(local ? { local } : {}) });
1607
1741
  return true;
1608
1742
  }
1609
1743
  try {
@@ -1642,7 +1776,9 @@ export class ProxyDaemon {
1642
1776
  return normalized.record;
1643
1777
  });
1644
1778
  const authorization = this.publishBindingLedger.verify(bundle);
1779
+ // binding_exempt 只表示 ledger 按 parent 规则放行,不是宿主执行回执。
1645
1780
  ctx.json(200, { ok: true, binding_verified: authorization !== undefined,
1781
+ binding_exempt: authorization === undefined && this.publishBindingLedger.authorizesByParentBinding(bundle),
1646
1782
  binding_required: hubNs.requiresPublishBinding(bundle), bundle_digest: hubNs.publishBundleDigest(bundle) });
1647
1783
  }
1648
1784
  catch {
@@ -1751,7 +1887,9 @@ export class ProxyDaemon {
1751
1887
  : undefined;
1752
1888
  if (publishRequested && abortPublish())
1753
1889
  return true;
1890
+ let observedChecks;
1754
1891
  const distill = await hubNs.distillConversation(body, {
1892
+ onObservedValidationPlan: (checks) => { observedChecks = checks; },
1755
1893
  // 调用方明确要求持久化时,即使发布被证据或质量闸门拦截,也保留可审查草稿;永不因此进入队列。
1756
1894
  persist: body.persist === true,
1757
1895
  store: this.assetStore,
@@ -1771,6 +1909,8 @@ export class ProxyDaemon {
1771
1909
  });
1772
1910
  return true;
1773
1911
  }
1912
+ if (!publishRequested && distill.status === 'stored')
1913
+ this.trackStoredDraft(body, distill.gene, distill.capsule, observedChecks);
1774
1914
  let submission = null;
1775
1915
  if (publishRequested) {
1776
1916
  if (abortPublish())
@@ -1802,29 +1942,7 @@ export class ProxyDaemon {
1802
1942
  ctx.json(422, { error: 'publish_binding_missing', stored: false, queued: false });
1803
1943
  return true;
1804
1944
  }
1805
- const publicationBundle = [distill.gene, distill.capsule, distill.event];
1806
- hubNs.assertEvolutionEventPublishBundle(publicationBundle);
1807
- this.publishBindingLedger.register(distill.publish_receipt, publicationBundle);
1808
- this.publishBindingLedger.verify(publicationBundle, distill.publish_receipt);
1809
- const env = mailbox.createEnvelope({
1810
- type: 'asset_submit',
1811
- payload: {
1812
- source: 'conversation_distillation',
1813
- distill_id: distill.distill_id,
1814
- assets: publicationBundle,
1815
- publish_receipt: distill.publish_receipt,
1816
- compose_recipe: body['publish_recipe'] !== false,
1817
- title: typeof body.title === 'string' ? body.title : undefined,
1818
- description: typeof body.summary === 'string' ? body.summary : undefined,
1819
- [OUTBOUND_HUB_MODE_FIELD]: this.currentHubMode(),
1820
- },
1821
- runtimeNamespace: this.deps.runtimeNamespace ?? 'default',
1822
- now: ctx.now,
1823
- });
1824
- const r = this.store.send(env);
1825
- if (r.stored)
1826
- this.notifyNewOutbound();
1827
- submission = { id: env.id, message_id: env.id, receiptId: r.receiptId, status: 'pending', stored: r.stored };
1945
+ submission = this.enqueueDistillPublication(body, { ...distill, event: distill.event, publish_receipt: distill.publish_receipt }, ctx.now);
1828
1946
  }
1829
1947
  ctx.json(200, {
1830
1948
  ...distill,
@@ -2107,6 +2225,56 @@ export class ProxyDaemon {
2107
2225
  this.recipeComposeStarted.add(key);
2108
2226
  void hubNs.composeRecipeAfterAssetPublish(this.hub, asRecord(envelope.payload)).catch(() => { });
2109
2227
  }
2228
+ /**
2229
+ * 记住本节点已发布的 Gene:之后单独发布引用它的 Capsule 时,parent 有本机发布事实可查。
2230
+ * 只在 Hub 接受发布后登记;本机记账失败不得让已接受的发布变成失败。
2231
+ */
2232
+ recordPublishedParents(envelope, result) {
2233
+ try {
2234
+ if (envelope.type !== 'asset_submit')
2235
+ return;
2236
+ const receipt = asRecord(result);
2237
+ if (receipt['status'] !== 'accepted')
2238
+ return;
2239
+ const { assets } = hubNs.splitAssetSubmitPayload(envelope.payload);
2240
+ const publishedIds = Array.isArray(receipt['submittedAssetIds']) ? receipt['submittedAssetIds'] : [];
2241
+ assets.forEach((asset, index) => {
2242
+ const publishedId = typeof publishedIds[index] === 'string' ? publishedIds[index] : undefined;
2243
+ this.publishBindingLedger.recordPublishedParent(asset, publishedId);
2244
+ });
2245
+ }
2246
+ catch { /* best-effort: a local bookkeeping failure must not fail an accepted publish */ }
2247
+ }
2248
+ /**
2249
+ * 记下本节点正在为这些 Gene 提交发布。
2250
+ * 单独发布的 Gene 从来不需要 binding,也就不会在 ledger 里登记任何 parent 事实;
2251
+ * 没有这条事实,之后单独发布引用它的 Capsule 必然被 publish_binding_missing 拒绝。
2252
+ */
2253
+ recordPublishingParents(assets) {
2254
+ try {
2255
+ for (const asset of assets)
2256
+ this.publishBindingLedger.recordPublishingParent(asset);
2257
+ }
2258
+ catch { /* best-effort: 本机记账失败不得让发布失败 */ }
2259
+ }
2260
+ /**
2261
+ * parent 发布终态失败:这份 parent 不再授权单独发布的 Capsule。
2262
+ * 可重试的失败不算终态,发布仍会继续。
2263
+ */
2264
+ recordFailedParents(envelope) {
2265
+ try {
2266
+ if (envelope.type !== 'asset_submit')
2267
+ return;
2268
+ for (const asset of this.submitEnvelopeAssets(envelope))
2269
+ this.publishBindingLedger.recordFailedParent(asset);
2270
+ }
2271
+ catch { /* best-effort: 本机记账失败不得让发布失败 */ }
2272
+ }
2273
+ submitEnvelopeAssets(envelope) {
2274
+ if (envelope.type !== 'asset_submit')
2275
+ return [];
2276
+ return hubNs.splitAssetSubmitPayload(envelope.payload).assets;
2277
+ }
2110
2278
  currentHubMode() {
2111
2279
  return this.deps.hubMode ?? 'public';
2112
2280
  }
@@ -2145,6 +2313,7 @@ export class ProxyDaemon {
2145
2313
  if (inflight)
2146
2314
  return this.waitForSynchronousAssetSubmit(inflight, envelope.id);
2147
2315
  const { stored } = this.store.send(envelope);
2316
+ this.recordPublishingParents(this.submitEnvelopeAssets(envelope));
2148
2317
  const cachedAfterInsert = this.readSynchronousAssetSubmitOutcome(envelope);
2149
2318
  if (cachedAfterInsert)
2150
2319
  return cachedAfterInsert;
@@ -2219,6 +2388,8 @@ export class ProxyDaemon {
2219
2388
  const outcome = { kind: 'failed', ...failure, error };
2220
2389
  if (this.shadowMode)
2221
2390
  return outcome;
2391
+ if (isTerminalSynchronousPublishFailure(error))
2392
+ this.recordFailedParents(envelope);
2222
2393
  if (current?.status !== 'in_flight') {
2223
2394
  const message = safeDaemonMessage(JSON.stringify(failure.body), MAX_PROXY_TICK_ERROR_LENGTH);
2224
2395
  const outcomeKey = synchronousAssetSubmitOutcomeKey(envelope.idempotencyKey);
@@ -2711,7 +2882,7 @@ function declaredValidationCommands(input) {
2711
2882
  }
2712
2883
  return commands;
2713
2884
  }
2714
- async function resolveVerifiedExecutionAfterPreflight(verifier, input, timeoutMs, parentSignals = [], runtimeDomain = 'standalone', genePolicy) {
2885
+ async function resolveVerifiedExecutionAfterPreflight(verifier, input, timeoutMs, parentSignals = [], runtimeDomain = 'standalone', genePolicy, validationPlanDigest) {
2715
2886
  if (!verifier)
2716
2887
  return undefined;
2717
2888
  if (parentSignals.some((signal) => signal.aborted))
@@ -2723,7 +2894,7 @@ async function resolveVerifiedExecutionAfterPreflight(verifier, input, timeoutMs
2723
2894
  if (!validation)
2724
2895
  return undefined;
2725
2896
  // 只把通过质量与命令策略预检的最小验证输入交给宿主,绝不转发调用方的 execution/status/trace。
2726
- const verificationRequest = Object.freeze(hubNs.createConversationVerificationRequest(input, validation, runtimeDomain, randomUUID(), genePolicy));
2897
+ const verificationRequest = Object.freeze(hubNs.createConversationVerificationRequest(input, validation, runtimeDomain, randomUUID(), genePolicy, validationPlanDigest));
2727
2898
  return resolveVerifiedExecution(verifier, { validation, verification_request: verificationRequest }, validation, timeoutMs, parentSignals);
2728
2899
  }
2729
2900
  async function convertLegacyLooseAsset(value, verifyExecution, verifyExecutionTimeoutMs, ledger, sanitizeEnv = process.env, ...parentSignals) {
@@ -3188,6 +3359,7 @@ function parseReuseResultReport(value) {
3188
3359
  if ('error' in timeSavedSecondsParsed)
3189
3360
  return { error: timeSavedSecondsParsed.error };
3190
3361
  const reason = stringBody(body, 'reason');
3362
+ const idempotencyKey = stringBody(body, 'idempotencyKey') ?? stringBody(body, 'idempotency_key');
3191
3363
  const evidence = optionalEvidenceBody(body);
3192
3364
  if ('error' in evidence)
3193
3365
  return { error: evidence.error };
@@ -3195,6 +3367,7 @@ function parseReuseResultReport(value) {
3195
3367
  report: {
3196
3368
  assetId,
3197
3369
  outcome,
3370
+ ...(idempotencyKey ? { idempotencyKey } : {}),
3198
3371
  ...(taskId ? { taskId } : {}),
3199
3372
  ...(traceId ? { traceId } : {}),
3200
3373
  ...(timeSavedSecondsParsed.value !== undefined ? { timeSavedSeconds: timeSavedSecondsParsed.value } : {}),
@@ -10,8 +10,46 @@ export declare class PublishBindingLedger {
10
10
  readonly runtimeDigest: string;
11
11
  constructor(store: StateStore, runtimeDomain: string);
12
12
  register(receipt: hub.PublishBindingReceipt, bundle: readonly assetstore.AssetRecord[]): void;
13
+ /**
14
+ * 记下本节点正在为这份 Gene 提交发布。
15
+ * 单独发布的 Gene 从来不需要 binding,也就不会在 ledger 里登记任何 parent 事实;
16
+ * 没有这条事实,之后单独发布引用它的 Capsule 必然被 publish_binding_missing 拒绝。
17
+ */
18
+ recordPublishingParent(asset: assetstore.AssetRecord): void;
19
+ /**
20
+ * 记下本节点已发布的 Gene,供之后单独发布的 Capsule 证明其 parent 出过本节点。
21
+ * 只记录 Gene 资产,且只登记可解析的引用(逻辑 id / 内容 id)。
22
+ */
23
+ recordPublishedParent(asset: assetstore.AssetRecord, publishedAssetId?: string): void;
24
+ /**
25
+ * parent 发布终态失败:这份 parent 不再能授权单独发布的 Capsule。
26
+ * 已经发布成功的事实不会被这条回退。
27
+ */
28
+ recordFailedParent(asset: assetstore.AssetRecord): void;
13
29
  verify(bundle: readonly assetstore.AssetRecord[], supplied?: unknown): hub.PublishBindingAuthorization | undefined;
30
+ /**
31
+ * 该 bundle 是否由 parent 规则授权:只对"引用的 Gene 确实已在本节点发布"放行。
32
+ * 可解析的 parent 关系只有一条:单独发布的 Capsule 引用本机已提交发布的 Gene——
33
+ * ledger 里有对应的本机发布事实,引用必须真的解析到那份 Gene。
34
+ * 它只满足 parent 关系,不构成宿主执行回执。
35
+ */
36
+ authorizesByParentBinding(bundle: readonly assetstore.AssetRecord[]): boolean;
37
+ private verifyRegistered;
38
+ /**
39
+ * parent 关系是否成立:单独发布的 Capsule 引用的是本节点已经提交发布的 Gene。
40
+ *
41
+ * 只有"这次发布就是这一个 Capsule"才适用:把 Gene 和 Capsule 放进同一个 bundle
42
+ * 仍然要求这个 bundle 自己的回执,否则改名重算 id 的未验证 Capsule 就能借同包 Gene
43
+ * 冒充可广播证据(见 test/publish-binding.ipc.test.ts)。
44
+ */
45
+ private parentBindingSatisfied;
46
+ /** 可被 Capsule 引用的 parent 标识:Gene 的逻辑 id 与本机内容 id。 */
47
+ private parentReferences;
48
+ private writeParent;
49
+ private readParent;
50
+ private contentId;
14
51
  private key;
15
52
  private memberKey;
53
+ private parentKey;
16
54
  }
17
55
  export {};