@evomap/evolver-proxy 2.0.46 → 2.0.48

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 (44) hide show
  1. package/dist/bin/evolver-proxy.d.ts +4 -0
  2. package/dist/bin/evolver-proxy.js +49 -5
  3. package/dist/bin/proxyStopSignal.d.ts +8 -0
  4. package/dist/bin/proxyStopSignal.js +13 -0
  5. package/dist/bin/triggerFeedbackStartup.d.ts +8 -0
  6. package/dist/bin/triggerFeedbackStartup.js +23 -0
  7. package/dist/daemon/localRecall.d.ts +37 -0
  8. package/dist/daemon/localRecall.js +112 -0
  9. package/dist/daemon/proxyDaemon.d.ts +33 -1
  10. package/dist/daemon/proxyDaemon.js +263 -18
  11. package/dist/daemon/publishBindingLedger.d.ts +38 -0
  12. package/dist/daemon/publishBindingLedger.js +171 -1
  13. package/dist/daemon/recallContext.d.ts +3 -0
  14. package/dist/daemon/recallContext.js +10 -0
  15. package/dist/lifecycle/claimNudge.js +1 -1
  16. package/dist/lifecycle/deployGuard.js +1 -1
  17. package/dist/lifecycle/legacyNodeId.js +1 -1
  18. package/dist/lifecycle/manager.js +1 -1
  19. package/dist/llm/index.js +1 -1
  20. package/dist/llm/server.js +1 -1
  21. package/dist/llm/traceBackfill.js +1 -1
  22. package/dist/llm/traceConfig.js +1 -1
  23. package/dist/llm/traceControl.js +1 -1
  24. package/dist/llm/traceEnvelope.js +1 -1
  25. package/dist/llm/traceSink.js +1 -1
  26. package/dist/llm/traceUploadPayload.js +1 -1
  27. package/dist/llm/upstream.js +1 -1
  28. package/dist/router/cachePassthrough.js +1 -1
  29. package/dist/router/features.js +1 -1
  30. package/dist/router/index.js +1 -1
  31. package/dist/router/messagesRoute.js +1 -1
  32. package/dist/router/modelRouter.js +1 -1
  33. package/dist/router/providerRoutes.js +1 -1
  34. package/dist/router/sseScan.js +1 -1
  35. package/dist/selfUpdate/bootstrap.js +29 -23
  36. package/dist/selfUpdate/bootstrapReadiness.js +4 -1
  37. package/dist/selfUpdate/fileMetadata.d.ts +2 -0
  38. package/dist/selfUpdate/fileMetadata.js +25 -0
  39. package/dist/selfUpdate/migration.js +19 -13
  40. package/dist/selfUpdate/recoveryChildStartGate.js +4 -2
  41. package/dist/selfUpdate/transaction.js +278 -64
  42. package/dist/selfUpdate/windowsUpdater.js +2 -1
  43. package/dist/sync/engine.js +1 -1
  44. package/package.json +3 -3
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { dirname, join } from 'node:path';
3
- import { reference, mailbox, hub as hubNs, shadow as shadow_, assetstore, wire, util, verify } from '@evomap/evolver-core';
3
+ import { reference, mailbox, hub as hubNs, shadow as shadow_, assetstore, wire, util, verify, events } from '@evomap/evolver-core';
4
4
  import { AuthError, HubClientError, HubUnreachableError, terminalHubRejection } from '@evomap/evolver-adapter-public';
5
5
  import { SyncEngine, SYNC_INTERVALS } from '../sync/engine.js';
6
6
  import { LifecycleManager } from '../lifecycle/manager.js';
@@ -11,7 +11,9 @@ import { invokeRecipeIpc, recipeIpcScope } from './recipeExecution.js';
11
11
  import { hubAuthFailureHint } from './selectHub.js';
12
12
  import { CollaborationFacade } from './collaborationFacade.js';
13
13
  import { classifyDiscoveryUpstreamError } from './discoveryErrors.js';
14
+ import { LOCAL_RECALL_STALE_MS, LOCAL_RECALL_TIMEOUT_MS, MAX_OUTSTANDING_LOCAL_READS, recallFromLocalStore, rootEventReuseTallies } from './localRecall.js';
14
15
  import { PublishBindingLedger } from './publishBindingLedger.js';
16
+ import { recallContextOf } from './recallContext.js';
15
17
  import { PublishRecallVerifier, resolvePublishRecallConfig, } from './publishRecallVerifier.js';
16
18
  const DEFAULT_PUBLISH_EXECUTION_VERIFY_TIMEOUT_MS = 30_000;
17
19
  export const DEFAULT_IPC_PORT = 19820;
@@ -93,6 +95,11 @@ export class ProxyDaemon {
93
95
  sync;
94
96
  lifecycle;
95
97
  assetStore;
98
+ localReuseTallies;
99
+ localRecallTimeoutMs;
100
+ localRecallStartedAt;
101
+ localReadsOutstanding = 0;
102
+ localRecallCleanup = new Set();
96
103
  benchmark;
97
104
  sourceProvenance;
98
105
  sourceReview;
@@ -130,6 +137,7 @@ export class ProxyDaemon {
130
137
  /** A poke that arrived between ticks (no sleep in flight) parks the wake here so it is not lost. */
131
138
  wakeRunnerPending = false;
132
139
  started = false;
140
+ feedbackRecovery;
133
141
  lifecycleArmed = false;
134
142
  lastTickAt;
135
143
  runtimeProcessIdentity = util.readFileLockProcessStartIdentity(process.pid);
@@ -178,9 +186,11 @@ export class ProxyDaemon {
178
186
  ]));
179
187
  const assetStoreDir = deps.assetStoreDir ?? (deps.storePath ? join(dirname(deps.storePath), 'assets') : undefined);
180
188
  this.assetStore = deps.assetStore ?? (assetStoreDir ? new assetstore.LocalJsonlProvider(assetStoreDir) : undefined);
181
- this.sourceProvenance = deps.sourceProvenance ?? (this.benchmark && this.assetStore instanceof assetstore.LocalJsonlProvider
189
+ this.localReuseTallies = deps.localReuseTallies ?? rootEventReuseTallies();
190
+ this.localRecallTimeoutMs = deps.localRecallTimeoutMs ?? LOCAL_RECALL_TIMEOUT_MS;
191
+ this.sourceProvenance = deps.sourceProvenance ?? (this.assetStore instanceof assetstore.LocalJsonlProvider
182
192
  ? new assetstore.ProvenanceStore(this.assetStore.baseDir) : undefined);
183
- this.sourceReview = deps.sourceReview ?? (this.benchmark && this.assetStore instanceof assetstore.LocalJsonlProvider
193
+ this.sourceReview = deps.sourceReview ?? (this.assetStore instanceof assetstore.LocalJsonlProvider
184
194
  ? new assetstore.ReviewLedger(this.assetStore.baseDir) : undefined);
185
195
  const referenceBase = assetStoreDir ?? deps.assetStore?.baseDir;
186
196
  this.referenceStore = referenceBase ? new reference.ReferenceStore(join(referenceBase, 'references')) : undefined;
@@ -193,7 +203,13 @@ export class ProxyDaemon {
193
203
  ...(deps.publishSanitizeEnv ? { sanitize: { env: deps.publishSanitizeEnv } } : {}),
194
204
  verifyPublishBinding: (bundle, receipt) => { this.publishBindingLedger.verify(bundle, receipt); },
195
205
  });
196
- this.proxyHandler = hubBindings.asProxyHandler();
206
+ const hubProxyHandler = hubBindings.asProxyHandler();
207
+ // Hub 接受是"本节点已发布这份 Gene"的唯一事实来源,出站与同步提交都走这一个出口。
208
+ this.proxyHandler = async (envelope) => {
209
+ const result = await hubProxyHandler(envelope);
210
+ this.recordPublishedParents(envelope, result);
211
+ return result;
212
+ };
197
213
  const proxyHandler = this.proxyHandler;
198
214
  const syncProxyHandler = (envelope) => this.handleHubModeBoundOutbound(envelope);
199
215
  const assetByIdSource = isAssetByIdFetcher(deps.hub) ? deps.hub : (isAssetByIdFetcher(hubToUse) ? hubToUse : undefined);
@@ -272,6 +288,7 @@ export class ProxyDaemon {
272
288
  },
273
289
  onOutboundTerminal: (envelope, error) => {
274
290
  this.collaborationFacade.handleOutboundTerminal(envelope, error);
291
+ this.recordFailedParents(envelope);
275
292
  try {
276
293
  this.cacheSynchronousAssetSubmitTerminal(envelope, error);
277
294
  }
@@ -405,6 +422,33 @@ export class ProxyDaemon {
405
422
  }
406
423
  throw new Error('proxy_ipc_safe_port_unavailable');
407
424
  }
425
+ drainTriggerFeedbackRecovery() {
426
+ if (!this.started || this.publishAbortController.signal.aborted || this.feedbackRecovery || !this.deps.triggerFeedback?.recover)
427
+ return;
428
+ const source = this.deps.triggerFeedback;
429
+ const recover = source.recover;
430
+ if (!recover)
431
+ return;
432
+ const signal = this.publishAbortController.signal;
433
+ const attempt = (async () => {
434
+ try {
435
+ const recovery = await recover.call(source, signal);
436
+ if (!this.started || signal.aborted || recovery['deferred'] === true)
437
+ return;
438
+ const count = (key) => typeof recovery[key] === 'number' && Number.isSafeInteger(recovery[key]) && Number(recovery[key]) >= 0 && Number(recovery[key]) <= 800 ? recovery[key] : undefined;
439
+ const valid = ['scanned', 'localChanged', 'hubConfirmed', 'pending', 'blocked'].every((key) => count(key) !== undefined);
440
+ this.store.setState('trigger_feedback:last_recovery', JSON.stringify({ ok: recovery['ok'] === true && valid, partial: recovery['partial'] === true,
441
+ scanned: count('scanned'), localChanged: count('localChanged'), hubConfirmed: count('hubConfirmed'), pending: count('pending'), blocked: count('blocked') }));
442
+ }
443
+ catch {
444
+ if (this.started && !signal.aborted)
445
+ this.recordTickError('core', new Error('trigger_feedback_recovery_unverified'));
446
+ }
447
+ })();
448
+ this.feedbackRecovery = attempt;
449
+ void attempt.finally(() => { if (this.feedbackRecovery === attempt)
450
+ this.feedbackRecovery = undefined; });
451
+ }
408
452
  /** 单轮: core pump/TTL/wake + proxy 出站 + hub 入站 + 到点心跳. */
409
453
  async tick() {
410
454
  const errors = [];
@@ -419,6 +463,7 @@ export class ProxyDaemon {
419
463
  catch (err) {
420
464
  addFailure('core', this.recordTickError('core', err));
421
465
  }
466
+ this.drainTriggerFeedbackRecovery();
422
467
  let outbound = emptyOutboundResult();
423
468
  let heartbeat;
424
469
  try {
@@ -612,6 +657,8 @@ export class ProxyDaemon {
612
657
  await this.publishRecallVerifier.stop();
613
658
  }
614
659
  catch { /* best-effort verifier shutdown */ }
660
+ if (this.feedbackRecovery)
661
+ await this.feedbackRecovery;
615
662
  let stopError;
616
663
  try {
617
664
  await this.closeIpc();
@@ -846,17 +893,18 @@ export class ProxyDaemon {
846
893
  const local = this.assetStore ? await this.assetStore.search(query) : [];
847
894
  return local.filter((asset) => asset.type !== 'AntiGene').slice(0, limit);
848
895
  }
849
- qualifyAssets(assets, limit = assets.length) {
896
+ qualifyAssets(assets, limit = assets.length, rawAssets) {
850
897
  if (!this.benchmark)
851
898
  return { assets: assets.slice(0, limit) };
852
899
  // 放在缓存、远端await之后;普通审批或cache TTL不能覆盖刚撤销的来源资格。
853
900
  const snapshot = this.sourceProvenance?.snapshot();
854
901
  const reviewed = this.sourceReview?.snapshot();
855
902
  const sourceQualifications = assets.map((asset) => {
856
- const decision = assetstore.assessSourceEligibility(asset, snapshot?.get(asset.asset_id), this.benchmark);
857
- const review = reviewed?.get(asset.asset_id);
858
- const withheld = snapshot?.get(asset.asset_id)?.trusted === false ? 'trust_rejected'
859
- : (review && review.state !== 'approved') || (reviewed && asset.type === 'AntiGene' && !review) ? 'review_rejected'
903
+ const raw = rawAssets?.get(asset) ?? asset;
904
+ const decision = assetstore.assessSourceEligibility(raw, snapshot?.get(raw.asset_id), this.benchmark);
905
+ const review = reviewed?.get(raw.asset_id);
906
+ const withheld = snapshot?.get(raw.asset_id)?.trusted === false ? 'trust_rejected'
907
+ : (review && review.state !== 'approved') || (reviewed && raw.type === 'AntiGene' && !review) ? 'review_rejected'
860
908
  : decision.allowed && !reviewed ? 'review_unavailable' : undefined;
861
909
  return { ...decision, ...(withheld ? { allowed: false, reason: withheld } : {}),
862
910
  assetId: asset.asset_id, benchmarkId: this.benchmark.benchmarkId };
@@ -867,10 +915,10 @@ export class ProxyDaemon {
867
915
  const qualified = this.qualifyAssets(assets, limit);
868
916
  ctx.json(200, { results: qualified.assets, ...qualified, query, ...extra, ...(this.benchmark ? { benchmarkId: this.benchmark.benchmarkId } : {}) });
869
917
  }
870
- qualifyFetch(ids, assets, missing) {
918
+ qualifyFetch(ids, assets, missing, rawAssets) {
871
919
  if (!this.benchmark)
872
920
  return { assets: [...assets], missing: [...missing] };
873
- const qualified = this.qualifyAssets(assets);
921
+ const qualified = this.qualifyAssets(assets, assets.length, rawAssets);
874
922
  return { ...qualified, missing: ids.filter((id) => !qualified.assets.some((asset) => assetMatchesId(asset, id))) };
875
923
  }
876
924
  async recallAssets(query) {
@@ -885,6 +933,92 @@ export class ProxyDaemon {
885
933
  return null;
886
934
  }
887
935
  }
936
+ retryLocalRecallCleanup() {
937
+ for (const reservation of this.localRecallCleanup) {
938
+ void reservation.failure.retryCleanup().then(() => {
939
+ if (reservation.failure.cleanupComplete && this.localRecallCleanup.delete(reservation))
940
+ reservation.release();
941
+ }, () => { });
942
+ }
943
+ }
944
+ async localRecall(text, projectDir, beforeFinish = Promise.resolve()) {
945
+ const store = this.assetStore, provenance = this.sourceProvenance, review = this.sourceReview;
946
+ if (!store)
947
+ return undefined;
948
+ // One mutable ledger pair cannot authorize Union sources or a read-only foreign pool.
949
+ if (store instanceof assetstore.UnionReadStore || store instanceof assetstore.ForeignJsonlSource
950
+ || !provenance || !review) {
951
+ return { assets: [], diagnostics: { considered: 0, injected: 0, error: 'local_recall_qualification_unavailable' } };
952
+ }
953
+ this.retryLocalRecallCleanup();
954
+ // A store read cannot be cancelled once started; after a timeout it may still be running, and a second one on
955
+ // top would only pile up.
956
+ const startedAt = this.now();
957
+ const recentlyStarted = this.localRecallStartedAt !== undefined && startedAt - this.localRecallStartedAt < LOCAL_RECALL_STALE_MS;
958
+ if (recentlyStarted || this.localReadsOutstanding >= MAX_OUTSTANDING_LOCAL_READS) {
959
+ return { assets: [], diagnostics: { considered: 0, injected: 0, error: 'local_recall_busy' } };
960
+ }
961
+ this.localRecallStartedAt = startedAt;
962
+ this.localReadsOutstanding += 1;
963
+ const preparationStarted = performance.now();
964
+ const controller = new AbortController();
965
+ let timer;
966
+ const timedOut = new Promise((_resolve, reject) => {
967
+ controller.signal.addEventListener('abort', () => reject(controller.signal.reason), { once: true });
968
+ });
969
+ const expire = () => controller.abort(new Error('local_recall_timeout'));
970
+ timer = setTimeout(expire, this.localRecallTimeoutMs);
971
+ const recall = (async () => {
972
+ const read = await recallFromLocalStore(store, text, projectDir);
973
+ clearTimeout(timer);
974
+ const remaining = this.localRecallTimeoutMs - (performance.now() - preparationStarted);
975
+ controller.signal.throwIfAborted();
976
+ if (remaining <= 0)
977
+ throw new Error('local_recall_timeout');
978
+ // Hub owns its own wait; resume only the unused local-work budget after its page settles.
979
+ await beforeFinish;
980
+ controller.signal.throwIfAborted();
981
+ const deadline = performance.now() + remaining;
982
+ timer = setTimeout(expire, remaining);
983
+ const reuse = await this.localReuseTallies({ signal: controller.signal, deadlineAt: Date.now() + remaining });
984
+ controller.signal.throwIfAborted();
985
+ if (performance.now() >= deadline)
986
+ throw new Error('local_recall_timeout');
987
+ // Take fresh approval only after asynchronous history work, with no await before ranking.
988
+ const outcome = read.finish({ provenance: provenance.snapshotNow(), review: review.snapshotNow(),
989
+ referenceScope: store.referenceScope, ...(this.benchmark ? { benchmark: this.benchmark } : {}) }, reuse);
990
+ if (performance.now() >= deadline)
991
+ throw new Error('local_recall_timeout');
992
+ return outcome;
993
+ })();
994
+ // Timeout can return Hub while a read or its cleanup is still owned by this reservation.
995
+ void Promise.allSettled([recall, beforeFinish]).then(([result]) => {
996
+ const release = () => {
997
+ this.localReadsOutstanding -= 1;
998
+ if (this.localRecallStartedAt === startedAt)
999
+ this.localRecallStartedAt = undefined;
1000
+ };
1001
+ if (result.status === 'rejected' && result.reason instanceof events.AuditCleanupError && !result.reason.cleanupComplete) {
1002
+ this.localRecallCleanup.add({ failure: result.reason, release });
1003
+ this.retryLocalRecallCleanup();
1004
+ }
1005
+ else
1006
+ release();
1007
+ });
1008
+ try {
1009
+ return await Promise.race([recall, timedOut]);
1010
+ }
1011
+ catch (error) {
1012
+ // A cooperative deadline can reject before the timer gets its event-loop turn.
1013
+ if (error instanceof Error && error.message === 'local_recall_timeout')
1014
+ controller.abort(error);
1015
+ // Local recall only adds candidates: a store it cannot read must not cost the Hub's recall.
1016
+ return { assets: [], diagnostics: { considered: 0, injected: 0, error: safeDaemonErrorMessage(error, 200) } };
1017
+ }
1018
+ finally {
1019
+ clearTimeout(timer);
1020
+ }
1021
+ }
888
1022
  async localFetchAssets(ids) {
889
1023
  const assets = [];
890
1024
  const missing = [];
@@ -917,6 +1051,27 @@ export class ProxyDaemon {
917
1051
  const handledAtp = await this.handleAtpRoute(ctx);
918
1052
  if (handledAtp)
919
1053
  return true;
1054
+ if (ctx.route === 'POST /trigger-feedback/sync' || ctx.route === 'POST /trigger-feedback/get') {
1055
+ const action = ctx.route.endsWith('/sync') ? 'sync' : 'get';
1056
+ const body = asRecord(await ctx.readJson());
1057
+ const runId = body['run_id'];
1058
+ const remote = body['remote'] ?? false;
1059
+ if (typeof runId !== 'string' || !runId.trim() || Buffer.byteLength(runId) > 256 || typeof remote !== 'boolean'
1060
+ || Object.keys(body).some((key) => key !== 'run_id' && key !== 'remote') || (action === 'get' && remote)) {
1061
+ ctx.json(400, { ok: false, reason: 'trigger_feedback_invalid_input' });
1062
+ return true;
1063
+ }
1064
+ if (action === 'sync' && this.shadowMode) {
1065
+ ctx.json(403, { ok: false, reason: 'shadow_mode' });
1066
+ return true;
1067
+ }
1068
+ if (!this.deps.triggerFeedback) {
1069
+ ctx.json(501, { ok: false, reason: 'trigger_feedback_source_unbound' });
1070
+ return true;
1071
+ }
1072
+ ctx.json(200, await this.deps.triggerFeedback.invoke(action, runId, remote));
1073
+ return true;
1074
+ }
920
1075
  if (ctx.route === 'GET /proxy/status') {
921
1076
  const publishReceiptDiagnostics = safePublishReceiptDiagnostics(this.hub);
922
1077
  const nodeId = this.deps.hubMode === 'private' ? this.feedbackNodeId() : this.lifecycle.nodeId;
@@ -1125,11 +1280,13 @@ export class ProxyDaemon {
1125
1280
  const q = [body.q, body.query, body.text].find((value) => typeof value === 'string' && value.trim().length > 0);
1126
1281
  const cursor = typeof body.cursor === 'string' && body.cursor.trim() ? body.cursor.trim() : undefined;
1127
1282
  const sort = typeof body.sort === 'string' && body.sort.trim() ? body.sort.trim() : undefined;
1283
+ const context = q ? recallContextOf(body.context) : undefined;
1128
1284
  const request = {
1129
1285
  ...(q ? { q } : {}),
1130
1286
  limit,
1131
1287
  ...(cursor ? { cursor } : {}),
1132
1288
  ...(sort ? { sort } : {}),
1289
+ ...(context ? { context } : {}),
1133
1290
  };
1134
1291
  let receipt;
1135
1292
  try {
@@ -1146,6 +1303,7 @@ export class ProxyDaemon {
1146
1303
  recipes: receipt.recipes,
1147
1304
  ...(receipt.nextCursor ? { nextCursor: receipt.nextCursor } : {}),
1148
1305
  ...(receipt.hasMore !== undefined ? { hasMore: receipt.hasMore } : {}),
1306
+ ...(receipt.contextFit ? { context_fit: receipt.contextFit } : {}),
1149
1307
  query: body,
1150
1308
  });
1151
1309
  return true;
@@ -1174,11 +1332,24 @@ export class ProxyDaemon {
1174
1332
  ctx.json(400, { error: 'invalid_limit' });
1175
1333
  return true;
1176
1334
  }
1335
+ const recallText = typeof body.text === 'string' && body.text.trim() ? body.text.trim() : undefined;
1336
+ const recallContext = recallContextOf(body.context);
1337
+ const recallSignals = Array.isArray(body.signals) ? body.signals.filter((s) => typeof s === 'string') : [];
1338
+ const recallByContent = ids.length === 0 && (recallText !== undefined || recallSignals.length > 0);
1177
1339
  if (this.hubAuthFailed()) {
1178
1340
  if (this.hubAuthFailurePolicy === 'deny') {
1179
1341
  ctx.json(401, this.hubAuthFailureBody());
1180
1342
  return true;
1181
1343
  }
1344
+ if (recallByContent) {
1345
+ const local = await this.localRecall([recallText ?? '', ...recallSignals].join('\n'), body.project_dir);
1346
+ ctx.json(200, {
1347
+ ...this.qualifyFetch([], withinLimit(local?.assets ?? [], body.limit), [], local?.rawAssets), query: body,
1348
+ ...localRecallReport(local),
1349
+ degraded: true, local_fallback: true, auth_status: HUB_AUTH_FAILED, warning: HUB_AUTH_FAILURE_WARNING,
1350
+ });
1351
+ return true;
1352
+ }
1182
1353
  const local = await this.localFetchAssets(ids);
1183
1354
  ctx.json(200, {
1184
1355
  ...local,
@@ -1190,21 +1361,26 @@ export class ProxyDaemon {
1190
1361
  });
1191
1362
  return true;
1192
1363
  }
1193
- const recallText = typeof body.text === 'string' && body.text.trim() ? body.text.trim() : undefined;
1194
- const recallSignals = Array.isArray(body.signals) ? body.signals.filter((s) => typeof s === 'string') : [];
1195
- if (ids.length === 0 && (recallText !== undefined || recallSignals.length > 0)) {
1196
- const recalled = await this.recallAssets({
1364
+ if (recallByContent) {
1365
+ const recalledPage = this.recallAssets({
1197
1366
  ...(recallText !== undefined ? { text: recallText } : {}),
1367
+ ...(recallText !== undefined && recallContext !== undefined ? { context: recallContext } : {}),
1198
1368
  ...(recallSignals.length > 0 ? { signalsAny: recallSignals } : {}),
1199
1369
  ...(typeof body.limit === 'number' ? { limit: body.limit } : {}),
1200
1370
  });
1371
+ const [recalled, local] = await Promise.all([
1372
+ recalledPage,
1373
+ this.localRecall([recallText ?? '', ...recallSignals].join('\n'), body.project_dir, recalledPage),
1374
+ ]);
1375
+ const localAssets = withinLimit(local?.assets ?? [], body.limit);
1376
+ const localRecall = localRecallReport(local);
1201
1377
  if (recalled === null) {
1202
1378
  if (this.hubAuthFailurePolicy === 'deny') {
1203
1379
  ctx.json(401, this.hubAuthFailureBody());
1204
1380
  return true;
1205
1381
  }
1206
1382
  ctx.json(200, {
1207
- assets: [], missing: [], query: body,
1383
+ ...this.qualifyFetch([], localAssets, [], local?.rawAssets), query: body, ...localRecall,
1208
1384
  degraded: true, local_fallback: true,
1209
1385
  auth_status: HUB_AUTH_FAILED, warning: HUB_AUTH_FAILURE_WARNING,
1210
1386
  });
@@ -1212,13 +1388,16 @@ export class ProxyDaemon {
1212
1388
  }
1213
1389
  const recalledBy = recallText !== undefined ? 'text' : 'signals';
1214
1390
  if (recalled.confirmRequired) {
1391
+ // Confirmation gates Hub credit spending; the caller's labelled local methods are free.
1215
1392
  ctx.json(200, {
1216
- assets: [], missing: [], query: body, recalled_by: recalledBy,
1393
+ ...this.qualifyFetch([], localAssets, [], local?.rawAssets), query: body, recalled_by: recalledBy, ...localRecall,
1217
1394
  confirm_required: true, credit_cost_preview: recalled.creditCostPreview,
1218
1395
  });
1219
1396
  return true;
1220
1397
  }
1221
- ctx.json(200, { ...this.qualifyFetch([], recalled.assets, []), query: body, recalled_by: recalledBy });
1398
+ const localIds = new Set(localAssets.map((asset) => asset.asset_id));
1399
+ const merged = withinLimit([...localAssets, ...recalled.assets.filter((asset) => !localIds.has(asset.asset_id))], body.limit);
1400
+ ctx.json(200, { ...this.qualifyFetch([], merged, [], local?.rawAssets), query: body, recalled_by: recalledBy, ...localRecall });
1222
1401
  return true;
1223
1402
  }
1224
1403
  const assets = [];
@@ -1348,6 +1527,7 @@ export class ProxyDaemon {
1348
1527
  now: ctx.now,
1349
1528
  });
1350
1529
  const r = this.store.send(env);
1530
+ this.recordPublishingParents(outboundBundle);
1351
1531
  if (r.stored)
1352
1532
  this.notifyNewOutbound();
1353
1533
  ctx.json(202, {
@@ -1473,7 +1653,9 @@ export class ProxyDaemon {
1473
1653
  return normalized.record;
1474
1654
  });
1475
1655
  const authorization = this.publishBindingLedger.verify(bundle);
1656
+ // binding_exempt 只表示 ledger 按 parent 规则放行,不是宿主执行回执。
1476
1657
  ctx.json(200, { ok: true, binding_verified: authorization !== undefined,
1658
+ binding_exempt: authorization === undefined && this.publishBindingLedger.authorizesByParentBinding(bundle),
1477
1659
  binding_required: hubNs.requiresPublishBinding(bundle), bundle_digest: hubNs.publishBundleDigest(bundle) });
1478
1660
  }
1479
1661
  catch {
@@ -1938,6 +2120,56 @@ export class ProxyDaemon {
1938
2120
  this.recipeComposeStarted.add(key);
1939
2121
  void hubNs.composeRecipeAfterAssetPublish(this.hub, asRecord(envelope.payload)).catch(() => { });
1940
2122
  }
2123
+ /**
2124
+ * 记住本节点已发布的 Gene:之后单独发布引用它的 Capsule 时,parent 有本机发布事实可查。
2125
+ * 只在 Hub 接受发布后登记;本机记账失败不得让已接受的发布变成失败。
2126
+ */
2127
+ recordPublishedParents(envelope, result) {
2128
+ try {
2129
+ if (envelope.type !== 'asset_submit')
2130
+ return;
2131
+ const receipt = asRecord(result);
2132
+ if (receipt['status'] !== 'accepted')
2133
+ return;
2134
+ const { assets } = hubNs.splitAssetSubmitPayload(envelope.payload);
2135
+ const publishedIds = Array.isArray(receipt['submittedAssetIds']) ? receipt['submittedAssetIds'] : [];
2136
+ assets.forEach((asset, index) => {
2137
+ const publishedId = typeof publishedIds[index] === 'string' ? publishedIds[index] : undefined;
2138
+ this.publishBindingLedger.recordPublishedParent(asset, publishedId);
2139
+ });
2140
+ }
2141
+ catch { /* best-effort: a local bookkeeping failure must not fail an accepted publish */ }
2142
+ }
2143
+ /**
2144
+ * 记下本节点正在为这些 Gene 提交发布。
2145
+ * 单独发布的 Gene 从来不需要 binding,也就不会在 ledger 里登记任何 parent 事实;
2146
+ * 没有这条事实,之后单独发布引用它的 Capsule 必然被 publish_binding_missing 拒绝。
2147
+ */
2148
+ recordPublishingParents(assets) {
2149
+ try {
2150
+ for (const asset of assets)
2151
+ this.publishBindingLedger.recordPublishingParent(asset);
2152
+ }
2153
+ catch { /* best-effort: 本机记账失败不得让发布失败 */ }
2154
+ }
2155
+ /**
2156
+ * parent 发布终态失败:这份 parent 不再授权单独发布的 Capsule。
2157
+ * 可重试的失败不算终态,发布仍会继续。
2158
+ */
2159
+ recordFailedParents(envelope) {
2160
+ try {
2161
+ if (envelope.type !== 'asset_submit')
2162
+ return;
2163
+ for (const asset of this.submitEnvelopeAssets(envelope))
2164
+ this.publishBindingLedger.recordFailedParent(asset);
2165
+ }
2166
+ catch { /* best-effort: 本机记账失败不得让发布失败 */ }
2167
+ }
2168
+ submitEnvelopeAssets(envelope) {
2169
+ if (envelope.type !== 'asset_submit')
2170
+ return [];
2171
+ return hubNs.splitAssetSubmitPayload(envelope.payload).assets;
2172
+ }
1941
2173
  currentHubMode() {
1942
2174
  return this.deps.hubMode ?? 'public';
1943
2175
  }
@@ -1976,6 +2208,7 @@ export class ProxyDaemon {
1976
2208
  if (inflight)
1977
2209
  return this.waitForSynchronousAssetSubmit(inflight, envelope.id);
1978
2210
  const { stored } = this.store.send(envelope);
2211
+ this.recordPublishingParents(this.submitEnvelopeAssets(envelope));
1979
2212
  const cachedAfterInsert = this.readSynchronousAssetSubmitOutcome(envelope);
1980
2213
  if (cachedAfterInsert)
1981
2214
  return cachedAfterInsert;
@@ -2050,6 +2283,8 @@ export class ProxyDaemon {
2050
2283
  const outcome = { kind: 'failed', ...failure, error };
2051
2284
  if (this.shadowMode)
2052
2285
  return outcome;
2286
+ if (isTerminalSynchronousPublishFailure(error))
2287
+ this.recordFailedParents(envelope);
2053
2288
  if (current?.status !== 'in_flight') {
2054
2289
  const message = safeDaemonMessage(JSON.stringify(failure.body), MAX_PROXY_TICK_ERROR_LENGTH);
2055
2290
  const outcomeKey = synchronousAssetSubmitOutcomeKey(envelope.idempotencyKey);
@@ -2281,6 +2516,14 @@ export class ProxyDaemon {
2281
2516
  ctx.json(status, body);
2282
2517
  }
2283
2518
  }
2519
+ function withinLimit(assets, limit) {
2520
+ return typeof limit === 'number' && Number.isFinite(limit) && limit >= 1 ? assets.slice(0, Math.floor(limit)) : [...assets];
2521
+ }
2522
+ function localRecallReport(local) {
2523
+ if (!local || (local.diagnostics.considered === 0 && !local.diagnostics.error))
2524
+ return {};
2525
+ return { local_recall: local.diagnostics };
2526
+ }
2284
2527
  function isAssetByIdFetcher(value) {
2285
2528
  return Boolean(value && typeof value === 'object' && typeof value.fetchAssetById === 'function');
2286
2529
  }
@@ -3011,6 +3254,7 @@ function parseReuseResultReport(value) {
3011
3254
  if ('error' in timeSavedSecondsParsed)
3012
3255
  return { error: timeSavedSecondsParsed.error };
3013
3256
  const reason = stringBody(body, 'reason');
3257
+ const idempotencyKey = stringBody(body, 'idempotencyKey') ?? stringBody(body, 'idempotency_key');
3014
3258
  const evidence = optionalEvidenceBody(body);
3015
3259
  if ('error' in evidence)
3016
3260
  return { error: evidence.error };
@@ -3018,6 +3262,7 @@ function parseReuseResultReport(value) {
3018
3262
  report: {
3019
3263
  assetId,
3020
3264
  outcome,
3265
+ ...(idempotencyKey ? { idempotencyKey } : {}),
3021
3266
  ...(taskId ? { taskId } : {}),
3022
3267
  ...(traceId ? { traceId } : {}),
3023
3268
  ...(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 {};