@harrylabsj/kiwi-merchant-cloud 0.12.30 → 0.12.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/a2a/node.d.ts +1 -0
- package/app/a2a/node.js +170 -2
- package/app/a2a/node.js.map +1 -1
- package/app/a2a/reception/agent-runtime.d.ts +32 -1
- package/app/a2a/reception/agent-runtime.js +420 -11
- package/app/a2a/reception/agent-runtime.js.map +1 -1
- package/app/a2a/reception/customer-memory-tools.d.ts +73 -0
- package/app/a2a/reception/customer-memory-tools.js +17 -0
- package/app/a2a/reception/customer-memory-tools.js.map +1 -0
- package/app/a2a/reception/engine.d.ts +12 -0
- package/app/a2a/reception/engine.js +42 -1
- package/app/a2a/reception/engine.js.map +1 -1
- package/app/a2a/reception/publish.d.ts +14 -1
- package/app/a2a/reception/publish.js +62 -1
- package/app/a2a/reception/publish.js.map +1 -1
- package/app/a2a/reception/question-spec.d.ts +91 -0
- package/app/a2a/reception/question-spec.js +260 -0
- package/app/a2a/reception/question-spec.js.map +1 -0
- package/app/a2a/reception/reply-outbox.d.ts +6 -0
- package/app/a2a/reception/reply-outbox.js +44 -0
- package/app/a2a/reception/reply-outbox.js.map +1 -1
- package/app/a2a/reception/responder.d.ts +13 -1
- package/app/a2a/reception/responder.js +26 -3
- package/app/a2a/reception/responder.js.map +1 -1
- package/app/a2a/reception/skill-catalog.d.ts +72 -0
- package/app/a2a/reception/skill-catalog.js +85 -0
- package/app/a2a/reception/skill-catalog.js.map +1 -0
- package/app/a2a/reception/skill-contract.d.ts +70 -0
- package/app/a2a/reception/skill-contract.js +183 -0
- package/app/a2a/reception/skill-contract.js.map +1 -0
- package/app/a2a/reception/types.d.ts +12 -0
- package/app/a2a/server/customer-identity-gateway.d.ts +111 -0
- package/app/a2a/server/customer-identity-gateway.js +441 -0
- package/app/a2a/server/customer-identity-gateway.js.map +1 -0
- package/app/a2a/server/merchant-handler.d.ts +56 -1
- package/app/a2a/server/merchant-handler.js +659 -44
- package/app/a2a/server/merchant-handler.js.map +1 -1
- package/app/a2a/server/pipeline.js +74 -29
- package/app/a2a/server/pipeline.js.map +1 -1
- package/app/a2a/server/types.d.ts +2 -0
- package/app/a2a/unit-alias.d.ts +3 -3
- package/app/a2a/unit-alias.js +9 -5
- package/app/a2a/unit-alias.js.map +1 -1
- package/app/agent/buyer/buyer-tools.js +1 -2
- package/app/agent/buyer/buyer-tools.js.map +1 -1
- package/app/agent/buyer/search-loop.js +0 -1
- package/app/agent/buyer/search-loop.js.map +1 -1
- package/app/auth/merchant-sessions.d.ts +3 -0
- package/app/auth/merchant-sessions.js +21 -5
- package/app/auth/merchant-sessions.js.map +1 -1
- package/app/buyer-core/a2a-knp.d.ts +4 -2
- package/app/buyer-core/a2a-knp.js +5 -2
- package/app/buyer-core/a2a-knp.js.map +1 -1
- package/app/buyer-core/a2a-negotiator.d.ts +1 -0
- package/app/buyer-core/a2a-negotiator.js +18 -11
- package/app/buyer-core/a2a-negotiator.js.map +1 -1
- package/app/buyer-core/a2a-quote-fetcher.d.ts +25 -0
- package/app/buyer-core/a2a-quote-fetcher.js +82 -4
- package/app/buyer-core/a2a-quote-fetcher.js.map +1 -1
- package/app/buyer-core/a2a-quote-history.d.ts +94 -0
- package/app/buyer-core/a2a-quote-history.js +149 -0
- package/app/buyer-core/a2a-quote-history.js.map +1 -0
- package/app/buyer-core/build-service.d.ts +19 -0
- package/app/buyer-core/build-service.js +30 -1
- package/app/buyer-core/build-service.js.map +1 -1
- package/app/buyer-core/errors.d.ts +1 -1
- package/app/buyer-core/errors.js +1 -0
- package/app/buyer-core/errors.js.map +1 -1
- package/app/buyer-core/merchant-index.js +0 -1
- package/app/buyer-core/merchant-index.js.map +1 -1
- package/app/buyer-core/open-inquiry-signer.d.ts +1 -0
- package/app/buyer-core/open-inquiry-signer.js +5 -2
- package/app/buyer-core/open-inquiry-signer.js.map +1 -1
- package/app/buyer-core/protocol-recovery.d.ts +2 -1
- package/app/buyer-core/protocol-recovery.js +14 -4
- package/app/buyer-core/protocol-recovery.js.map +1 -1
- package/app/buyer-core/service.d.ts +58 -5
- package/app/buyer-core/service.js +279 -53
- package/app/buyer-core/service.js.map +1 -1
- package/app/buyer-core/store.d.ts +8 -0
- package/app/buyer-core/store.js +37 -7
- package/app/buyer-core/store.js.map +1 -1
- package/app/cli.js +136 -34
- package/app/cli.js.map +1 -1
- package/app/cloud/bootstrap.d.ts +1 -1
- package/app/cloud/bootstrap.js +162 -35
- package/app/cloud/bootstrap.js.map +1 -1
- package/app/cloud/product-import-tabular.js +13 -5
- package/app/cloud/product-import-tabular.js.map +1 -1
- package/app/cloud/trade-platforms-client.d.ts +30 -0
- package/app/cloud/trade-platforms-client.js +34 -1
- package/app/cloud/trade-platforms-client.js.map +1 -1
- package/app/cloud-sample/products.json +3 -3
- package/app/commerce/receipt/dispatcher.d.ts +42 -0
- package/app/commerce/receipt/dispatcher.js +68 -0
- package/app/commerce/receipt/dispatcher.js.map +1 -0
- package/app/commerce/receipt/receipts.d.ts +140 -0
- package/app/commerce/receipt/receipts.js +247 -0
- package/app/commerce/receipt/receipts.js.map +1 -0
- package/app/config/profile.d.ts +2 -2
- package/app/handoff/order-receipts.d.ts +62 -0
- package/app/handoff/order-receipts.js +71 -0
- package/app/handoff/order-receipts.js.map +1 -0
- package/app/handoff/trade-platform-rules.js +5 -2
- package/app/handoff/trade-platform-rules.js.map +1 -1
- package/app/handoff/ucp-checkout/cart-channel.d.ts +2 -1
- package/app/handoff/ucp-checkout/cart-channel.js +1 -0
- package/app/handoff/ucp-checkout/cart-channel.js.map +1 -1
- package/app/handoff/ucp-checkout/channel.d.ts +6 -0
- package/app/handoff/ucp-checkout/channel.js +44 -0
- package/app/handoff/ucp-checkout/channel.js.map +1 -1
- package/app/http/cli.js +6 -0
- package/app/http/cli.js.map +1 -1
- package/app/http/merchant-management/api.d.ts +11 -1
- package/app/http/merchant-management/api.js +471 -3
- package/app/http/merchant-management/api.js.map +1 -1
- package/app/http/merchant-management/draft-store.js +8 -6
- package/app/http/merchant-management/draft-store.js.map +1 -1
- package/app/http/merchant-management/page.js +83 -22
- package/app/http/merchant-management/page.js.map +1 -1
- package/app/mcp/cli.js +6 -0
- package/app/mcp/cli.js.map +1 -1
- package/app/mcp/merchant-runtime-assembly.d.ts +20 -0
- package/app/mcp/merchant-runtime-assembly.js +93 -3
- package/app/mcp/merchant-runtime-assembly.js.map +1 -1
- package/app/mcp/merchant-server.d.ts +5 -0
- package/app/mcp/merchant-server.js +12 -0
- package/app/mcp/merchant-server.js.map +1 -1
- package/app/mcp/tools.js +12 -3
- package/app/mcp/tools.js.map +1 -1
- package/app/merchant/application/actor.d.ts +1 -1
- package/app/merchant/application/actor.js +15 -0
- package/app/merchant/application/actor.js.map +1 -1
- package/app/merchant/workbench-server.d.ts +38 -0
- package/app/merchant/workbench-server.js +428 -0
- package/app/merchant/workbench-server.js.map +1 -0
- package/app/merchant-core/budget/background-budget.d.ts +132 -0
- package/app/merchant-core/budget/background-budget.js +308 -0
- package/app/merchant-core/budget/background-budget.js.map +1 -0
- package/app/merchant-core/context-governance/actor-context.d.ts +56 -0
- package/app/merchant-core/context-governance/actor-context.js +76 -0
- package/app/merchant-core/context-governance/actor-context.js.map +1 -0
- package/app/merchant-core/context-governance/authority.d.ts +39 -0
- package/app/merchant-core/context-governance/authority.js +28 -0
- package/app/merchant-core/context-governance/authority.js.map +1 -0
- package/app/merchant-core/context-governance/context-guard.d.ts +104 -0
- package/app/merchant-core/context-governance/context-guard.js +194 -0
- package/app/merchant-core/context-governance/context-guard.js.map +1 -0
- package/app/merchant-core/context-governance/data-use-grant.d.ts +91 -0
- package/app/merchant-core/context-governance/data-use-grant.js +211 -0
- package/app/merchant-core/context-governance/data-use-grant.js.map +1 -0
- package/app/merchant-core/context-governance/feature-flags.d.ts +32 -0
- package/app/merchant-core/context-governance/feature-flags.js +83 -0
- package/app/merchant-core/context-governance/feature-flags.js.map +1 -0
- package/app/merchant-core/context-governance/pilot-readiness.d.ts +39 -0
- package/app/merchant-core/context-governance/pilot-readiness.js +141 -0
- package/app/merchant-core/context-governance/pilot-readiness.js.map +1 -0
- package/app/merchant-core/context-governance/source-governance.d.ts +157 -0
- package/app/merchant-core/context-governance/source-governance.js +492 -0
- package/app/merchant-core/context-governance/source-governance.js.map +1 -0
- package/app/merchant-core/context-governance/types.d.ts +62 -0
- package/app/merchant-core/context-governance/types.js +92 -0
- package/app/merchant-core/context-governance/types.js.map +1 -0
- package/app/merchant-core/customer-delivery/binding.d.ts +55 -0
- package/app/merchant-core/customer-delivery/binding.js +121 -0
- package/app/merchant-core/customer-delivery/binding.js.map +1 -0
- package/app/merchant-core/customer-delivery/channel.d.ts +75 -0
- package/app/merchant-core/customer-delivery/channel.js +157 -0
- package/app/merchant-core/customer-delivery/channel.js.map +1 -0
- package/app/merchant-core/customer-delivery/consent-repository.d.ts +50 -0
- package/app/merchant-core/customer-delivery/consent-repository.js +160 -0
- package/app/merchant-core/customer-delivery/consent-repository.js.map +1 -0
- package/app/merchant-core/customer-delivery/dispatcher-loop.d.ts +68 -0
- package/app/merchant-core/customer-delivery/dispatcher-loop.js +132 -0
- package/app/merchant-core/customer-delivery/dispatcher-loop.js.map +1 -0
- package/app/merchant-core/customer-delivery/dispatcher.d.ts +118 -0
- package/app/merchant-core/customer-delivery/dispatcher.js +166 -0
- package/app/merchant-core/customer-delivery/dispatcher.js.map +1 -0
- package/app/merchant-core/customer-delivery/email-adapter.d.ts +31 -0
- package/app/merchant-core/customer-delivery/email-adapter.js +90 -0
- package/app/merchant-core/customer-delivery/email-adapter.js.map +1 -0
- package/app/merchant-core/customer-delivery/gate.d.ts +37 -0
- package/app/merchant-core/customer-delivery/gate.js +196 -0
- package/app/merchant-core/customer-delivery/gate.js.map +1 -0
- package/app/merchant-core/customer-delivery/reconciliation.d.ts +13 -0
- package/app/merchant-core/customer-delivery/reconciliation.js +70 -0
- package/app/merchant-core/customer-delivery/reconciliation.js.map +1 -0
- package/app/merchant-core/customer-delivery/repository.d.ts +55 -0
- package/app/merchant-core/customer-delivery/repository.js +235 -0
- package/app/merchant-core/customer-delivery/repository.js.map +1 -0
- package/app/merchant-core/customer-delivery/smtp-adapter.d.ts +30 -0
- package/app/merchant-core/customer-delivery/smtp-adapter.js +183 -0
- package/app/merchant-core/customer-delivery/smtp-adapter.js.map +1 -0
- package/app/merchant-core/customer-delivery/stream-gate.d.ts +45 -0
- package/app/merchant-core/customer-delivery/stream-gate.js +123 -0
- package/app/merchant-core/customer-delivery/stream-gate.js.map +1 -0
- package/app/merchant-core/customer-delivery/types.d.ts +103 -0
- package/app/merchant-core/customer-delivery/types.js +32 -0
- package/app/merchant-core/customer-delivery/types.js.map +1 -0
- package/app/merchant-core/customer-delivery/weixin-adapter.d.ts +35 -0
- package/app/merchant-core/customer-delivery/weixin-adapter.js +56 -0
- package/app/merchant-core/customer-delivery/weixin-adapter.js.map +1 -0
- package/app/merchant-core/customer-memory/auto-identity.d.ts +43 -0
- package/app/merchant-core/customer-memory/auto-identity.js +163 -0
- package/app/merchant-core/customer-memory/auto-identity.js.map +1 -0
- package/app/merchant-core/customer-memory/grants.d.ts +72 -0
- package/app/merchant-core/customer-memory/grants.js +224 -0
- package/app/merchant-core/customer-memory/grants.js.map +1 -0
- package/app/merchant-core/customer-memory/history.d.ts +51 -0
- package/app/merchant-core/customer-memory/history.js +252 -0
- package/app/merchant-core/customer-memory/history.js.map +1 -0
- package/app/merchant-core/customer-memory/identity.d.ts +66 -0
- package/app/merchant-core/customer-memory/identity.js +249 -0
- package/app/merchant-core/customer-memory/identity.js.map +1 -0
- package/app/merchant-core/customer-memory/maintenance.d.ts +51 -0
- package/app/merchant-core/customer-memory/maintenance.js +67 -0
- package/app/merchant-core/customer-memory/maintenance.js.map +1 -0
- package/app/merchant-core/customer-memory/memory.d.ts +119 -0
- package/app/merchant-core/customer-memory/memory.js +502 -0
- package/app/merchant-core/customer-memory/memory.js.map +1 -0
- package/app/merchant-core/customer-memory/private-transport.d.ts +10 -0
- package/app/merchant-core/customer-memory/private-transport.js +108 -0
- package/app/merchant-core/customer-memory/private-transport.js.map +1 -0
- package/app/merchant-core/customer-memory/quote-history.d.ts +160 -0
- package/app/merchant-core/customer-memory/quote-history.js +392 -0
- package/app/merchant-core/customer-memory/quote-history.js.map +1 -0
- package/app/merchant-core/customer-memory/reception-provider.d.ts +69 -0
- package/app/merchant-core/customer-memory/reception-provider.js +250 -0
- package/app/merchant-core/customer-memory/reception-provider.js.map +1 -0
- package/app/merchant-core/customer-memory/reception-writer.d.ts +19 -0
- package/app/merchant-core/customer-memory/reception-writer.js +32 -0
- package/app/merchant-core/customer-memory/reception-writer.js.map +1 -0
- package/app/merchant-core/customer-memory/types.d.ts +111 -0
- package/app/merchant-core/customer-memory/types.js +58 -0
- package/app/merchant-core/customer-memory/types.js.map +1 -0
- package/app/merchant-core/followup/repository.d.ts +2 -1
- package/app/merchant-core/followup/repository.js +29 -23
- package/app/merchant-core/followup/repository.js.map +1 -1
- package/app/merchant-core/learning/evaluation-fixtures.d.ts +38 -0
- package/app/merchant-core/learning/evaluation-fixtures.js +83 -0
- package/app/merchant-core/learning/evaluation-fixtures.js.map +1 -0
- package/app/merchant-core/learning/evaluation-suite-v1.d.ts +56 -0
- package/app/merchant-core/learning/evaluation-suite-v1.js +129 -0
- package/app/merchant-core/learning/evaluation-suite-v1.js.map +1 -0
- package/app/merchant-core/learning/evaluation.d.ts +84 -0
- package/app/merchant-core/learning/evaluation.js +581 -0
- package/app/merchant-core/learning/evaluation.js.map +1 -0
- package/app/merchant-core/learning/initial-skills.d.ts +36 -0
- package/app/merchant-core/learning/initial-skills.js +67 -0
- package/app/merchant-core/learning/initial-skills.js.map +1 -0
- package/app/merchant-core/learning/precheck.d.ts +33 -0
- package/app/merchant-core/learning/precheck.js +56 -0
- package/app/merchant-core/learning/precheck.js.map +1 -0
- package/app/merchant-core/learning/real-evaluation-runner.d.ts +52 -0
- package/app/merchant-core/learning/real-evaluation-runner.js +167 -0
- package/app/merchant-core/learning/real-evaluation-runner.js.map +1 -0
- package/app/merchant-core/learning/reception-skill-catalog.d.ts +39 -0
- package/app/merchant-core/learning/reception-skill-catalog.js +145 -0
- package/app/merchant-core/learning/reception-skill-catalog.js.map +1 -0
- package/app/merchant-core/learning/recovery-gateway.d.ts +27 -0
- package/app/merchant-core/learning/recovery-gateway.js +106 -0
- package/app/merchant-core/learning/recovery-gateway.js.map +1 -0
- package/app/merchant-core/learning/repository.d.ts +130 -0
- package/app/merchant-core/learning/repository.js +588 -0
- package/app/merchant-core/learning/repository.js.map +1 -0
- package/app/merchant-core/learning/service.d.ts +262 -0
- package/app/merchant-core/learning/service.js +1498 -0
- package/app/merchant-core/learning/service.js.map +1 -0
- package/app/merchant-core/learning/test-dispatch-gateway.d.ts +43 -0
- package/app/merchant-core/learning/test-dispatch-gateway.js +145 -0
- package/app/merchant-core/learning/test-dispatch-gateway.js.map +1 -0
- package/app/merchant-core/learning/types.d.ts +217 -0
- package/app/merchant-core/learning/types.js +52 -0
- package/app/merchant-core/learning/types.js.map +1 -0
- package/app/merchant-core/migrations/ledgers.d.ts +40 -0
- package/app/merchant-core/migrations/ledgers.js +824 -0
- package/app/merchant-core/migrations/ledgers.js.map +1 -0
- package/app/merchant-core/migrations/runner.d.ts +55 -0
- package/app/merchant-core/migrations/runner.js +114 -0
- package/app/merchant-core/migrations/runner.js.map +1 -0
- package/app/merchant-core/operations-jobs/advice-runner.d.ts +63 -0
- package/app/merchant-core/operations-jobs/advice-runner.js +199 -0
- package/app/merchant-core/operations-jobs/advice-runner.js.map +1 -0
- package/app/merchant-core/operations-jobs/pilot-evidence.d.ts +64 -0
- package/app/merchant-core/operations-jobs/pilot-evidence.js +109 -0
- package/app/merchant-core/operations-jobs/pilot-evidence.js.map +1 -0
- package/app/merchant-core/operations-jobs/pilot-metrics.d.ts +70 -0
- package/app/merchant-core/operations-jobs/pilot-metrics.js +98 -0
- package/app/merchant-core/operations-jobs/pilot-metrics.js.map +1 -0
- package/app/merchant-core/operations-jobs/projection.d.ts +41 -0
- package/app/merchant-core/operations-jobs/projection.js +158 -0
- package/app/merchant-core/operations-jobs/projection.js.map +1 -0
- package/app/merchant-core/operations-jobs/scheduler.d.ts +68 -0
- package/app/merchant-core/operations-jobs/scheduler.js +233 -0
- package/app/merchant-core/operations-jobs/scheduler.js.map +1 -0
- package/app/merchant-core/operations-jobs/service.d.ts +260 -0
- package/app/merchant-core/operations-jobs/service.js +922 -0
- package/app/merchant-core/operations-jobs/service.js.map +1 -0
- package/app/merchant-core/ops/facade.d.ts +10 -0
- package/app/merchant-core/ops/facade.js +52 -0
- package/app/merchant-core/ops/facade.js.map +1 -1
- package/app/merchant-core/ops/schema.d.ts +1 -1
- package/app/merchant-core/ops/schema.js +119 -2
- package/app/merchant-core/ops/schema.js.map +1 -1
- package/app/merchant-core/ops/surface.d.ts +37 -0
- package/app/merchant-core/ops/surface.js +240 -0
- package/app/merchant-core/ops/surface.js.map +1 -1
- package/app/merchant-core/ownership/instance-ownership.d.ts +122 -0
- package/app/merchant-core/ownership/instance-ownership.js +236 -0
- package/app/merchant-core/ownership/instance-ownership.js.map +1 -0
- package/app/merchant-core/ownership/runtime.d.ts +175 -0
- package/app/merchant-core/ownership/runtime.js +422 -0
- package/app/merchant-core/ownership/runtime.js.map +1 -0
- package/app/merchant-core/storage/transaction.d.ts +102 -7
- package/app/merchant-core/storage/transaction.js +274 -3
- package/app/merchant-core/storage/transaction.js.map +1 -1
- package/app/merchant-credential-rotation.d.ts +4 -1
- package/app/merchant-credential-rotation.js +12 -8
- package/app/merchant-credential-rotation.js.map +1 -1
- package/app/merchant-gateway/catalog-tools.js +4 -2
- package/app/merchant-gateway/catalog-tools.js.map +1 -1
- package/app/merchant-runtime/manager.d.ts +2 -0
- package/app/merchant-runtime/manager.js +5 -0
- package/app/merchant-runtime/manager.js.map +1 -1
- package/app/product-buyer.d.ts +1 -0
- package/app/product-buyer.js +0 -1
- package/app/product-buyer.js.map +1 -1
- package/app/product-cli.js +11 -1
- package/app/product-cli.js.map +1 -1
- package/build-manifest.json +1255 -280
- package/deployment-lock.json +2 -2
- package/package.json +1 -1
- package/prepare.mjs +5 -1
- package/runtime-package.json +1 -1
- package/shipping-sbom.cdx.json +6 -6
- package/shipping-source.json +12 -12
|
@@ -0,0 +1,1498 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* TOP1 经验学习服务:商家主动纠正与案例形成(设计 §5.1 / §17.2 / D-M0-03)。
|
|
18
|
+
*
|
|
19
|
+
* - `submitCorrection`:入库前做 PII/底价/凭据预检;正文有界;编辑走
|
|
20
|
+
* `expected_revision` CAS,产生新 revision 并把旧案例/候选置 STALE;
|
|
21
|
+
* - `promoteCorrection`:商家确认后形成不可重复的案例(每纠正一条);重复
|
|
22
|
+
* 提升同内容幂等返回原案例;案例内容变化时旧候选 STALE;
|
|
23
|
+
* - 所有写命令支持 `command_id` 幂等(merchant + actor + operation +
|
|
24
|
+
* command_id;同键异摘要 `idempotency_conflict`);
|
|
25
|
+
* - merchant/actor/能力全部由服务端注入的 ActorContext 决定,模型与请求
|
|
26
|
+
* 正文不能自报;查询一律带 merchant 作用域。
|
|
27
|
+
*
|
|
28
|
+
* 本文件不持有商务写权限、不写商品/价格事实,也不直接生成候选(M2-3)。
|
|
29
|
+
*/
|
|
30
|
+
import { randomUUID } from "node:crypto";
|
|
31
|
+
import { contentDigest } from "../../negotiation/jcs.js";
|
|
32
|
+
import { compileReceptionSkillArtifact, isValidSkillKey, SkillContractError, } from "../../a2a/reception/skill-contract.js";
|
|
33
|
+
import { hasCapability } from "../context-governance/actor-context.js";
|
|
34
|
+
import { GOVERNANCE_POLICY_VERSION, } from "../context-governance/types.js";
|
|
35
|
+
import { runCandidateEvaluation, validateEvaluationSuite, validateOutcome, } from "./evaluation.js";
|
|
36
|
+
import { LearningRepository } from "./repository.js";
|
|
37
|
+
import { CONTROL_CHARS_PATTERN, detectCorrectionSensitiveContent, } from "./precheck.js";
|
|
38
|
+
import { LearningError, } from "./types.js";
|
|
39
|
+
const MAX_CORRECTION_CHARS = 4_000;
|
|
40
|
+
const MAX_ISSUE_TAGS = 10;
|
|
41
|
+
const MAX_CASE_REFS = 20;
|
|
42
|
+
const MAX_TAG_CHARS = 64;
|
|
43
|
+
const MAX_CASE_IDS = 20;
|
|
44
|
+
const MAX_TRIGGER_CHARS = 400;
|
|
45
|
+
const MAX_REASON_CHARS = 500;
|
|
46
|
+
const MAX_EXCLUSIONS = 10;
|
|
47
|
+
const MAX_EXCLUSION_CHARS = 200;
|
|
48
|
+
const REVIEW_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
49
|
+
const PUBLISH_WINDOW_MS = 24 * 60 * 60 * 1000;
|
|
50
|
+
function requireOpaque(value, field, maxLength = 128) {
|
|
51
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
52
|
+
throw new LearningError("validation", `${field}_empty`, `${field} 必须是非空字符串`);
|
|
53
|
+
}
|
|
54
|
+
if (value.length > maxLength) {
|
|
55
|
+
throw new LearningError("validation", `${field}_too_long`, `${field} 长度超过 ${maxLength}`);
|
|
56
|
+
}
|
|
57
|
+
if (CONTROL_CHARS_PATTERN.test(value)) {
|
|
58
|
+
throw new LearningError("validation", `${field}_invalid`, `${field} 含控制字符`);
|
|
59
|
+
}
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
function requireRevision(value, field) {
|
|
63
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
64
|
+
throw new LearningError("validation", `${field}_invalid`, `${field} 必须是正整数`);
|
|
65
|
+
}
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
68
|
+
function normalizeCorrectionText(raw) {
|
|
69
|
+
if (typeof raw !== "string") {
|
|
70
|
+
throw new LearningError("validation", "correction_text_invalid", "correction_text 必须是字符串");
|
|
71
|
+
}
|
|
72
|
+
const text = raw.replace(/\r\n?/g, "\n").trim();
|
|
73
|
+
if (text.length === 0) {
|
|
74
|
+
throw new LearningError("validation", "correction_text_empty", "correction_text 不能为空");
|
|
75
|
+
}
|
|
76
|
+
if (text.length > MAX_CORRECTION_CHARS) {
|
|
77
|
+
throw new LearningError("validation", "correction_text_too_long", `correction_text 超过 ${MAX_CORRECTION_CHARS} 字符`);
|
|
78
|
+
}
|
|
79
|
+
if (CONTROL_CHARS_PATTERN.test(text)) {
|
|
80
|
+
throw new LearningError("validation", "correction_text_invalid", "correction_text 含控制字符");
|
|
81
|
+
}
|
|
82
|
+
return text;
|
|
83
|
+
}
|
|
84
|
+
function normalizeStringList(raw, field, maxItems, maxChars) {
|
|
85
|
+
if (raw === undefined)
|
|
86
|
+
return [];
|
|
87
|
+
if (!Array.isArray(raw)) {
|
|
88
|
+
throw new LearningError("validation", `${field}_invalid`, `${field} 必须是字符串数组`);
|
|
89
|
+
}
|
|
90
|
+
const seen = new Set();
|
|
91
|
+
for (const item of raw) {
|
|
92
|
+
if (typeof item !== "string") {
|
|
93
|
+
throw new LearningError("validation", `${field}_invalid`, `${field} 必须是字符串数组`);
|
|
94
|
+
}
|
|
95
|
+
const value = item.trim();
|
|
96
|
+
if (value.length === 0) {
|
|
97
|
+
throw new LearningError("validation", `${field}_empty`, `${field} 不能含空字符串`);
|
|
98
|
+
}
|
|
99
|
+
if (value.length > maxChars) {
|
|
100
|
+
throw new LearningError("validation", `${field}_too_long`, `${field} 单项长度超过 ${maxChars}`);
|
|
101
|
+
}
|
|
102
|
+
if (CONTROL_CHARS_PATTERN.test(value)) {
|
|
103
|
+
throw new LearningError("validation", `${field}_invalid`, `${field} 含控制字符`);
|
|
104
|
+
}
|
|
105
|
+
seen.add(value);
|
|
106
|
+
}
|
|
107
|
+
if (seen.size > maxItems) {
|
|
108
|
+
throw new LearningError("validation", `${field}_too_many`, `${field} 最多 ${maxItems} 项`);
|
|
109
|
+
}
|
|
110
|
+
// 稳定排序:同集合不同顺序不应产生不同摘要。
|
|
111
|
+
return [...seen].sort();
|
|
112
|
+
}
|
|
113
|
+
function requireActorCapability(merchantId, actor, capability) {
|
|
114
|
+
if (actor.merchant_id !== merchantId) {
|
|
115
|
+
throw new LearningError("access_denied", "actor_merchant_mismatch", "ActorContext 与商家作用域不一致");
|
|
116
|
+
}
|
|
117
|
+
if (actor.policy_version !== GOVERNANCE_POLICY_VERSION) {
|
|
118
|
+
throw new LearningError("validation", "policy_version_mismatch", "ActorContext policy_version 与当前治理策略不一致");
|
|
119
|
+
}
|
|
120
|
+
if (!hasCapability(actor, capability)) {
|
|
121
|
+
throw new LearningError("access_denied", "capability_missing", `actor 缺少 ${capability}`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function requireActor(merchantId, actor) {
|
|
125
|
+
requireActorCapability(merchantId, actor, "learning:manage");
|
|
126
|
+
}
|
|
127
|
+
function correctionDigest(input) {
|
|
128
|
+
return contentDigest({
|
|
129
|
+
kind: "learning.correction",
|
|
130
|
+
merchant_id: input.merchantId,
|
|
131
|
+
correction_text: input.text,
|
|
132
|
+
issue_tags: input.issueTags,
|
|
133
|
+
case_refs: input.caseRefs,
|
|
134
|
+
base_release_id: input.baseReleaseId,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
function requireBoundedText(value, field, maxLength) {
|
|
138
|
+
if (typeof value !== "string") {
|
|
139
|
+
throw new LearningError("validation", `${field}_invalid`, `${field} 必须是字符串`);
|
|
140
|
+
}
|
|
141
|
+
const text = value.replace(/\r\n?/g, "\n").trim();
|
|
142
|
+
if (text.length === 0) {
|
|
143
|
+
throw new LearningError("validation", `${field}_empty`, `${field} 不能为空`);
|
|
144
|
+
}
|
|
145
|
+
if (text.length > maxLength) {
|
|
146
|
+
throw new LearningError("validation", `${field}_too_long`, `${field} 超过 ${maxLength} 字符`);
|
|
147
|
+
}
|
|
148
|
+
if (CONTROL_CHARS_PATTERN.test(text)) {
|
|
149
|
+
throw new LearningError("validation", `${field}_invalid`, `${field} 含控制字符`);
|
|
150
|
+
}
|
|
151
|
+
return text;
|
|
152
|
+
}
|
|
153
|
+
/** 发布/回滚前复核:冻结产物必须仍与当前编译器与工具/问题契约一致。 */
|
|
154
|
+
function verifyReleaseArtifact(input) {
|
|
155
|
+
const compiled = compileReceptionSkillArtifact({
|
|
156
|
+
skill_key: input.skill_key,
|
|
157
|
+
steps: input.compiled_artifact.steps,
|
|
158
|
+
required_tools: input.compiled_artifact.required_tools,
|
|
159
|
+
});
|
|
160
|
+
if (compiled.artifact_hash !== input.artifact_hash ||
|
|
161
|
+
compiled.tool_contract_digest !== input.tool_contract_digest ||
|
|
162
|
+
compiled.compiler_version !== input.compiler_version) {
|
|
163
|
+
throw new LearningError("unsupported_capability", "release_incompatible", "版本产物与当前工具/问题契约或编译器不兼容;不能发布或回滚");
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function caseDigest(input) {
|
|
167
|
+
return contentDigest({
|
|
168
|
+
kind: "learning.case",
|
|
169
|
+
merchant_id: input.merchantId,
|
|
170
|
+
correction_id: input.correctionId,
|
|
171
|
+
correction_digest: input.correctionDigest,
|
|
172
|
+
source_refs: input.sourceRefs,
|
|
173
|
+
outcome_refs: input.outcomeRefs,
|
|
174
|
+
issue_tags: input.issueTags,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
export class LearningService {
|
|
178
|
+
repository;
|
|
179
|
+
recoveryWriteGuard;
|
|
180
|
+
recoveryVerifier;
|
|
181
|
+
now;
|
|
182
|
+
experienceLearningGrant;
|
|
183
|
+
sourceAvailable;
|
|
184
|
+
available;
|
|
185
|
+
constructor(options) {
|
|
186
|
+
this.repository = options.repository;
|
|
187
|
+
this.recoveryVerifier = options.recoveryVerifier;
|
|
188
|
+
this.recoveryWriteGuard = options.recoveryWriteGuard ?? ((work) => work());
|
|
189
|
+
this.now = options.now;
|
|
190
|
+
this.experienceLearningGrant = options.experienceLearningGrant;
|
|
191
|
+
this.sourceAvailable = options.sourceAvailable;
|
|
192
|
+
this.available = options.available ?? true;
|
|
193
|
+
}
|
|
194
|
+
ensureAvailable() {
|
|
195
|
+
if (!this.available) {
|
|
196
|
+
throw new LearningError("schema_unavailable", "learning_schema_unavailable", "学习域迁移失败或未就绪;新功能保持关闭,现有接待路径不受影响");
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* 提交或编辑商家主动纠正。编辑必须带 `correction_id` 与
|
|
201
|
+
* `expected_revision`;成功返回新 revision,旧案例与候选置 STALE。
|
|
202
|
+
*/
|
|
203
|
+
/**
|
|
204
|
+
* A01/A02:从客户案例蒸馏学习材料。
|
|
205
|
+
*
|
|
206
|
+
* 必须持有 experience_learning 授权(记忆授权不能替代);未授权时只写
|
|
207
|
+
* 最小拒绝登记(原因 + 摘要,不含原文),客户正文不进入模型或学习库。
|
|
208
|
+
* 授权通过后仍走同一纠正经预检/持久化路径;本方法不暴露任何策略或
|
|
209
|
+
* 发布工具,客户文本只作为案例数据。
|
|
210
|
+
*/
|
|
211
|
+
distillCustomerCase(input) {
|
|
212
|
+
const merchantId = requireOpaque(input.merchant_id, "merchant_id");
|
|
213
|
+
requireActorCapability(merchantId, input.actor, "learning:manage");
|
|
214
|
+
const subjectId = requireOpaque(input.subject_id, "subject_id");
|
|
215
|
+
const scopeId = requireOpaque(input.resource_scope_id, "resource_scope_id");
|
|
216
|
+
const authorized = this.experienceLearningGrant?.({
|
|
217
|
+
merchant_id: merchantId,
|
|
218
|
+
subject_id: subjectId,
|
|
219
|
+
resource_scope_id: scopeId,
|
|
220
|
+
}) === true;
|
|
221
|
+
if (!authorized) {
|
|
222
|
+
this.repository.recordRejection({
|
|
223
|
+
merchantId,
|
|
224
|
+
actorId: input.actor.actor_id,
|
|
225
|
+
operation: "learning.distill_customer_case",
|
|
226
|
+
reasonCode: "experience_learning_grant_required",
|
|
227
|
+
subjectDigest: contentDigest({ operation: "customer_case", case_text: input.case_text }),
|
|
228
|
+
createdAt: this.now(),
|
|
229
|
+
});
|
|
230
|
+
throw new LearningError("access_denied", "experience_learning_grant_required", "客户案例蒸馏需要 experience_learning 授权;记忆授权不能替代");
|
|
231
|
+
}
|
|
232
|
+
return this.submitCorrection({
|
|
233
|
+
merchant_id: merchantId,
|
|
234
|
+
actor: input.actor,
|
|
235
|
+
correction_text: input.case_text,
|
|
236
|
+
issue_tags: input.issue_tags ?? ["customer_case"],
|
|
237
|
+
case_refs: [`customer_case:${subjectId}:${scopeId}`],
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
/** A12:来源删除/封存后旧案例派生不能继续审核或发布。 */
|
|
241
|
+
assertCandidateSourcesAvailable(merchantId, candidate) {
|
|
242
|
+
if (this.sourceAvailable === undefined)
|
|
243
|
+
return;
|
|
244
|
+
for (const caseId of candidate.case_ids) {
|
|
245
|
+
const learningCase = this.repository.readCase(merchantId, caseId);
|
|
246
|
+
if (learningCase === undefined)
|
|
247
|
+
continue;
|
|
248
|
+
for (const ref of learningCase.source_refs) {
|
|
249
|
+
if (!this.sourceAvailable(merchantId, ref)) {
|
|
250
|
+
throw new LearningError("version_conflict", "source_unavailable", "来源已删除/封存;旧案例派生失效,需要重新形成候选");
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
submitCorrection(input, command = {}) {
|
|
256
|
+
this.ensureAvailable();
|
|
257
|
+
const merchantId = requireOpaque(input.merchant_id, "merchant_id");
|
|
258
|
+
requireActor(merchantId, input.actor);
|
|
259
|
+
const text = normalizeCorrectionText(input.correction_text);
|
|
260
|
+
const issueTags = normalizeStringList(input.issue_tags, "issue_tags", MAX_ISSUE_TAGS, MAX_TAG_CHARS);
|
|
261
|
+
const caseRefs = normalizeStringList(input.case_refs, "case_refs", MAX_CASE_REFS, 128);
|
|
262
|
+
const baseReleaseId = input.base_release_id === undefined
|
|
263
|
+
? null
|
|
264
|
+
: requireOpaque(input.base_release_id, "base_release_id");
|
|
265
|
+
const correctionId = input.correction_id === undefined
|
|
266
|
+
? undefined
|
|
267
|
+
: requireOpaque(input.correction_id, "correction_id");
|
|
268
|
+
if ((correctionId === undefined) !== (input.expected_revision === undefined)) {
|
|
269
|
+
throw new LearningError("validation", "expected_revision_required", "编辑纠正必须同时提供 correction_id 与 expected_revision");
|
|
270
|
+
}
|
|
271
|
+
if (input.expected_revision !== undefined) {
|
|
272
|
+
requireRevision(input.expected_revision, "expected_revision");
|
|
273
|
+
}
|
|
274
|
+
const sensitive = detectCorrectionSensitiveContent(text);
|
|
275
|
+
if (sensitive !== undefined) {
|
|
276
|
+
// 最小拒绝登记:不存正文,只存原因与不可逆摘要类别。
|
|
277
|
+
this.repository.transaction(() => {
|
|
278
|
+
this.repository.recordRejection({
|
|
279
|
+
merchantId,
|
|
280
|
+
actorId: input.actor.actor_id,
|
|
281
|
+
operation: "learning.submitCorrection",
|
|
282
|
+
reasonCode: `precheck:${sensitive}`,
|
|
283
|
+
subjectDigest: contentDigest({
|
|
284
|
+
operation: "learning.submitCorrection",
|
|
285
|
+
reason_code: sensitive,
|
|
286
|
+
actor_id: input.actor.actor_id,
|
|
287
|
+
text_length: text.length,
|
|
288
|
+
}),
|
|
289
|
+
createdAt: this.now(),
|
|
290
|
+
});
|
|
291
|
+
});
|
|
292
|
+
throw new LearningError("sensitive_content", `precheck:${sensitive}`, "纠正正文包含客户标识、联系方式、凭据或价格底线;请改为抽象流程描述后重试");
|
|
293
|
+
}
|
|
294
|
+
const request = {
|
|
295
|
+
correction_id: correctionId ?? null,
|
|
296
|
+
expected_revision: input.expected_revision ?? 0,
|
|
297
|
+
correction_text: text,
|
|
298
|
+
issue_tags: issueTags,
|
|
299
|
+
case_refs: caseRefs,
|
|
300
|
+
base_release_id: baseReleaseId,
|
|
301
|
+
};
|
|
302
|
+
return this.withCommand(merchantId, input.actor.actor_id, "learning.submitCorrection", request, command, () => {
|
|
303
|
+
const now = this.now();
|
|
304
|
+
const digest = correctionDigest({
|
|
305
|
+
merchantId,
|
|
306
|
+
text,
|
|
307
|
+
issueTags,
|
|
308
|
+
caseRefs,
|
|
309
|
+
baseReleaseId,
|
|
310
|
+
});
|
|
311
|
+
if (correctionId !== undefined) {
|
|
312
|
+
const existing = this.repository.readCorrection(merchantId, correctionId);
|
|
313
|
+
if (existing === undefined) {
|
|
314
|
+
throw new LearningError("not_found", "correction_not_found", "纠正不存在或不可见");
|
|
315
|
+
}
|
|
316
|
+
if (existing.revision !== input.expected_revision) {
|
|
317
|
+
throw new LearningError("version_conflict", "correction_revision_mismatch", `纠正 revision 已变化(当前 ${existing.revision})`);
|
|
318
|
+
}
|
|
319
|
+
const updated = {
|
|
320
|
+
...existing,
|
|
321
|
+
revision: existing.revision + 1,
|
|
322
|
+
status: "DRAFT",
|
|
323
|
+
correction_text: text,
|
|
324
|
+
issue_tags: issueTags,
|
|
325
|
+
case_refs: caseRefs,
|
|
326
|
+
base_release_id: baseReleaseId,
|
|
327
|
+
content_digest: digest,
|
|
328
|
+
updated_at: now,
|
|
329
|
+
};
|
|
330
|
+
this.repository.updateCorrection(updated);
|
|
331
|
+
const staleCase = this.repository.readCaseByCorrection(merchantId, correctionId);
|
|
332
|
+
if (staleCase !== undefined) {
|
|
333
|
+
const staleCases = this.repository.markCaseStale(merchantId, staleCase.case_id, now);
|
|
334
|
+
const staleCandidates = this.repository.markCandidatesStaleForCase(merchantId, staleCase.case_id, now);
|
|
335
|
+
if (staleCases > 0 || staleCandidates > 0) {
|
|
336
|
+
this.repository.appendEvent({
|
|
337
|
+
merchantId,
|
|
338
|
+
subjectKind: "correction",
|
|
339
|
+
subjectId: correctionId,
|
|
340
|
+
event: "case_staled",
|
|
341
|
+
detail: { case_id: staleCase.case_id, stale_candidates: staleCandidates },
|
|
342
|
+
createdAt: now,
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
this.repository.appendEvent({
|
|
347
|
+
merchantId,
|
|
348
|
+
subjectKind: "correction",
|
|
349
|
+
subjectId: correctionId,
|
|
350
|
+
event: "correction_revised",
|
|
351
|
+
detail: { revision: updated.revision },
|
|
352
|
+
createdAt: now,
|
|
353
|
+
});
|
|
354
|
+
return updated;
|
|
355
|
+
}
|
|
356
|
+
const created = {
|
|
357
|
+
correction_id: `corr_${randomUUID()}`,
|
|
358
|
+
merchant_id: merchantId,
|
|
359
|
+
actor_id: input.actor.actor_id,
|
|
360
|
+
revision: 1,
|
|
361
|
+
status: "DRAFT",
|
|
362
|
+
correction_text: text,
|
|
363
|
+
issue_tags: issueTags,
|
|
364
|
+
case_refs: caseRefs,
|
|
365
|
+
base_release_id: baseReleaseId,
|
|
366
|
+
content_digest: digest,
|
|
367
|
+
created_at: now,
|
|
368
|
+
updated_at: now,
|
|
369
|
+
};
|
|
370
|
+
this.repository.insertCorrection(created);
|
|
371
|
+
this.repository.appendEvent({
|
|
372
|
+
merchantId,
|
|
373
|
+
subjectKind: "correction",
|
|
374
|
+
subjectId: created.correction_id,
|
|
375
|
+
event: "correction_drafted",
|
|
376
|
+
detail: { revision: 1 },
|
|
377
|
+
createdAt: now,
|
|
378
|
+
});
|
|
379
|
+
return created;
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* 商家确认形成案例。每纠正一条案例;同内容重复提升幂等返回原案例;
|
|
384
|
+
* 纠正已编辑后重新提升会递增案例 revision 并让旧候选 STALE。
|
|
385
|
+
*/
|
|
386
|
+
promoteCorrection(input, command = {}) {
|
|
387
|
+
this.ensureAvailable();
|
|
388
|
+
const merchantId = requireOpaque(input.merchant_id, "merchant_id");
|
|
389
|
+
requireActor(merchantId, input.actor);
|
|
390
|
+
const correctionId = requireOpaque(input.correction_id, "correction_id");
|
|
391
|
+
const expectedRevision = requireRevision(input.expected_revision, "expected_revision");
|
|
392
|
+
return this.withCommand(merchantId, input.actor.actor_id, "learning.promoteCorrection", { correction_id: correctionId, expected_revision: expectedRevision }, command, () => {
|
|
393
|
+
const now = this.now();
|
|
394
|
+
const correction = this.repository.readCorrection(merchantId, correctionId);
|
|
395
|
+
if (correction === undefined) {
|
|
396
|
+
throw new LearningError("not_found", "correction_not_found", "纠正不存在或不可见");
|
|
397
|
+
}
|
|
398
|
+
if (correction.revision !== expectedRevision) {
|
|
399
|
+
throw new LearningError("version_conflict", "correction_revision_mismatch", `纠正 revision 已变化(当前 ${correction.revision})`);
|
|
400
|
+
}
|
|
401
|
+
const digest = caseDigest({
|
|
402
|
+
merchantId,
|
|
403
|
+
correctionId,
|
|
404
|
+
correctionDigest: correction.content_digest,
|
|
405
|
+
sourceRefs: correction.case_refs,
|
|
406
|
+
outcomeRefs: [],
|
|
407
|
+
issueTags: correction.issue_tags,
|
|
408
|
+
});
|
|
409
|
+
const existing = this.repository.readCaseByCorrection(merchantId, correctionId);
|
|
410
|
+
if (existing !== undefined && existing.content_digest === digest) {
|
|
411
|
+
// 幂等:同纠正内容再次提升返回原案例(案例摘要覆盖纠正摘要)。
|
|
412
|
+
if (existing.status !== "ACTIVE") {
|
|
413
|
+
this.repository.updateCase({ ...existing, status: "ACTIVE", updated_at: now });
|
|
414
|
+
}
|
|
415
|
+
if (correction.status !== "CASE_CREATED") {
|
|
416
|
+
this.repository.updateCorrection({
|
|
417
|
+
...correction,
|
|
418
|
+
status: "CASE_CREATED",
|
|
419
|
+
updated_at: now,
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
return { ...existing, status: "ACTIVE" };
|
|
423
|
+
}
|
|
424
|
+
let promoted;
|
|
425
|
+
if (existing === undefined) {
|
|
426
|
+
promoted = {
|
|
427
|
+
case_id: `case_${randomUUID()}`,
|
|
428
|
+
merchant_id: merchantId,
|
|
429
|
+
correction_id: correctionId,
|
|
430
|
+
revision: 1,
|
|
431
|
+
status: "ACTIVE",
|
|
432
|
+
source_refs: correction.case_refs,
|
|
433
|
+
outcome_refs: [],
|
|
434
|
+
issue_tags: correction.issue_tags,
|
|
435
|
+
content_digest: digest,
|
|
436
|
+
created_at: now,
|
|
437
|
+
updated_at: now,
|
|
438
|
+
};
|
|
439
|
+
this.repository.insertCase(promoted);
|
|
440
|
+
this.repository.appendEvent({
|
|
441
|
+
merchantId,
|
|
442
|
+
subjectKind: "case",
|
|
443
|
+
subjectId: promoted.case_id,
|
|
444
|
+
event: "case_created",
|
|
445
|
+
detail: { correction_id: correctionId, revision: 1 },
|
|
446
|
+
createdAt: now,
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
else {
|
|
450
|
+
promoted = {
|
|
451
|
+
...existing,
|
|
452
|
+
revision: existing.revision + 1,
|
|
453
|
+
status: "ACTIVE",
|
|
454
|
+
source_refs: correction.case_refs,
|
|
455
|
+
outcome_refs: [],
|
|
456
|
+
issue_tags: correction.issue_tags,
|
|
457
|
+
content_digest: digest,
|
|
458
|
+
updated_at: now,
|
|
459
|
+
};
|
|
460
|
+
this.repository.updateCase(promoted);
|
|
461
|
+
const staleCandidates = this.repository.markCandidatesStaleForCase(merchantId, promoted.case_id, now);
|
|
462
|
+
this.repository.appendEvent({
|
|
463
|
+
merchantId,
|
|
464
|
+
subjectKind: "case",
|
|
465
|
+
subjectId: promoted.case_id,
|
|
466
|
+
event: "case_revised",
|
|
467
|
+
detail: { correction_id: correctionId, revision: promoted.revision, stale_candidates: staleCandidates },
|
|
468
|
+
createdAt: now,
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
this.repository.updateCorrection({
|
|
472
|
+
...correction,
|
|
473
|
+
status: "CASE_CREATED",
|
|
474
|
+
updated_at: now,
|
|
475
|
+
});
|
|
476
|
+
return promoted;
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* 形成候选草稿(`learning.propose`):案例必须 ACTIVE;技能步骤按固定
|
|
481
|
+
* 动作/问题/守卫注册表校验,评测前编译并冻结产物(hash/compiler_version/
|
|
482
|
+
* 工具契约摘要)。候选只写草稿,不启用规则、不改商品事实或价格权限。
|
|
483
|
+
*/
|
|
484
|
+
proposeCandidate(input, command = {}) {
|
|
485
|
+
this.ensureAvailable();
|
|
486
|
+
const merchantId = requireOpaque(input.merchant_id, "merchant_id");
|
|
487
|
+
requireActor(merchantId, input.actor);
|
|
488
|
+
const caseIds = normalizeStringList(input.case_ids, "case_ids", MAX_CASE_IDS, 128);
|
|
489
|
+
if (caseIds.length === 0) {
|
|
490
|
+
throw new LearningError("validation", "case_ids_empty", "候选至少关联一个案例");
|
|
491
|
+
}
|
|
492
|
+
if (!isValidSkillKey(input.skill_key)) {
|
|
493
|
+
throw new LearningError("validation", "skill_key_invalid", "skill_key 必须是 lowercase kebab-case");
|
|
494
|
+
}
|
|
495
|
+
const text = this.validateCandidateText(merchantId, input.actor.actor_id, "learning.proposeCandidate", {
|
|
496
|
+
trigger: input.trigger,
|
|
497
|
+
reason: input.reason,
|
|
498
|
+
...(input.exclusions !== undefined ? { exclusions: input.exclusions } : {}),
|
|
499
|
+
});
|
|
500
|
+
const baseReleaseId = input.base_release_id === undefined
|
|
501
|
+
? null
|
|
502
|
+
: requireOpaque(input.base_release_id, "base_release_id");
|
|
503
|
+
const request = {
|
|
504
|
+
case_ids: caseIds,
|
|
505
|
+
skill_key: input.skill_key,
|
|
506
|
+
base_release_id: baseReleaseId,
|
|
507
|
+
trigger: text.trigger,
|
|
508
|
+
proposed_steps: input.proposed_steps,
|
|
509
|
+
exclusions: text.exclusions,
|
|
510
|
+
reason: text.reason,
|
|
511
|
+
required_tools: input.required_tools ?? null,
|
|
512
|
+
};
|
|
513
|
+
return this.withCommand(merchantId, input.actor.actor_id, "learning.proposeCandidate", request, command, () => {
|
|
514
|
+
const content = this.buildCandidateContent(merchantId, {
|
|
515
|
+
skillKey: input.skill_key,
|
|
516
|
+
caseIds,
|
|
517
|
+
trigger: text.trigger,
|
|
518
|
+
steps: input.proposed_steps,
|
|
519
|
+
exclusions: text.exclusions,
|
|
520
|
+
reason: text.reason,
|
|
521
|
+
baseReleaseId,
|
|
522
|
+
...(input.required_tools !== undefined
|
|
523
|
+
? { requiredTools: input.required_tools }
|
|
524
|
+
: {}),
|
|
525
|
+
});
|
|
526
|
+
const now = this.now();
|
|
527
|
+
const candidate = {
|
|
528
|
+
candidate_id: `cand_${randomUUID()}`,
|
|
529
|
+
merchant_id: merchantId,
|
|
530
|
+
revision: 1,
|
|
531
|
+
state: "DRAFT",
|
|
532
|
+
skill_key: input.skill_key,
|
|
533
|
+
audience: "customer_reception",
|
|
534
|
+
base_release_id: baseReleaseId,
|
|
535
|
+
case_ids: caseIds,
|
|
536
|
+
trigger_text: text.trigger,
|
|
537
|
+
proposed_steps: content.compiled.artifact.steps,
|
|
538
|
+
exclusions: text.exclusions,
|
|
539
|
+
reason: text.reason,
|
|
540
|
+
required_tools: content.compiled.artifact.required_tools,
|
|
541
|
+
question_schema_version: content.compiled.artifact.question_schema_version,
|
|
542
|
+
tool_contract_digest: content.compiled.tool_contract_digest,
|
|
543
|
+
compiled_artifact: content.compiled.artifact,
|
|
544
|
+
compiled_artifact_hash: content.compiled.artifact_hash,
|
|
545
|
+
compiler_version: content.compiled.compiler_version,
|
|
546
|
+
content_digest: content.contentDigest,
|
|
547
|
+
eval_report_id: null,
|
|
548
|
+
reviewer_id: null,
|
|
549
|
+
approval_ref: null,
|
|
550
|
+
expires_at: null,
|
|
551
|
+
created_at: now,
|
|
552
|
+
updated_at: now,
|
|
553
|
+
};
|
|
554
|
+
this.repository.insertCandidate(candidate);
|
|
555
|
+
this.repository.replaceCandidateCases({
|
|
556
|
+
merchantId,
|
|
557
|
+
candidateId: candidate.candidate_id,
|
|
558
|
+
caseIds,
|
|
559
|
+
now,
|
|
560
|
+
});
|
|
561
|
+
this.repository.appendEvent({
|
|
562
|
+
merchantId,
|
|
563
|
+
subjectKind: "candidate",
|
|
564
|
+
subjectId: candidate.candidate_id,
|
|
565
|
+
event: "candidate_drafted",
|
|
566
|
+
detail: {
|
|
567
|
+
revision: 1,
|
|
568
|
+
artifact_hash: candidate.compiled_artifact_hash,
|
|
569
|
+
content_digest: candidate.content_digest,
|
|
570
|
+
},
|
|
571
|
+
createdAt: now,
|
|
572
|
+
});
|
|
573
|
+
return candidate;
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* 编辑候选:CAS revision;任何内容变化都产生新 revision 与新的冻结产物,
|
|
578
|
+
* 并清空旧评测/审核/批准(A07/A16)。APPROVED/STALE/EXPIRED 不可编辑。
|
|
579
|
+
*/
|
|
580
|
+
reviseCandidate(input, command = {}) {
|
|
581
|
+
this.ensureAvailable();
|
|
582
|
+
const merchantId = requireOpaque(input.merchant_id, "merchant_id");
|
|
583
|
+
requireActor(merchantId, input.actor);
|
|
584
|
+
const candidateId = requireOpaque(input.candidate_id, "candidate_id");
|
|
585
|
+
const expectedRevision = requireRevision(input.expected_revision, "expected_revision");
|
|
586
|
+
const caseIds = normalizeStringList(input.case_ids, "case_ids", MAX_CASE_IDS, 128);
|
|
587
|
+
if (caseIds.length === 0) {
|
|
588
|
+
throw new LearningError("validation", "case_ids_empty", "候选至少关联一个案例");
|
|
589
|
+
}
|
|
590
|
+
if (!isValidSkillKey(input.skill_key)) {
|
|
591
|
+
throw new LearningError("validation", "skill_key_invalid", "skill_key 必须是 lowercase kebab-case");
|
|
592
|
+
}
|
|
593
|
+
const text = this.validateCandidateText(merchantId, input.actor.actor_id, "learning.reviseCandidate", {
|
|
594
|
+
trigger: input.trigger,
|
|
595
|
+
reason: input.reason,
|
|
596
|
+
...(input.exclusions !== undefined ? { exclusions: input.exclusions } : {}),
|
|
597
|
+
});
|
|
598
|
+
const baseReleaseId = input.base_release_id === undefined
|
|
599
|
+
? null
|
|
600
|
+
: requireOpaque(input.base_release_id, "base_release_id");
|
|
601
|
+
const request = {
|
|
602
|
+
candidate_id: candidateId,
|
|
603
|
+
expected_revision: expectedRevision,
|
|
604
|
+
case_ids: caseIds,
|
|
605
|
+
skill_key: input.skill_key,
|
|
606
|
+
base_release_id: baseReleaseId,
|
|
607
|
+
trigger: text.trigger,
|
|
608
|
+
proposed_steps: input.proposed_steps,
|
|
609
|
+
exclusions: text.exclusions,
|
|
610
|
+
reason: text.reason,
|
|
611
|
+
required_tools: input.required_tools ?? null,
|
|
612
|
+
};
|
|
613
|
+
return this.withCommand(merchantId, input.actor.actor_id, "learning.reviseCandidate", request, command, () => {
|
|
614
|
+
const existing = this.repository.readCandidate(merchantId, candidateId);
|
|
615
|
+
if (existing === undefined) {
|
|
616
|
+
throw new LearningError("not_found", "candidate_not_found", "候选不存在或不可见");
|
|
617
|
+
}
|
|
618
|
+
if (existing.revision !== expectedRevision) {
|
|
619
|
+
throw new LearningError("version_conflict", "candidate_revision_mismatch", `候选 revision 已变化(当前 ${existing.revision})`);
|
|
620
|
+
}
|
|
621
|
+
// P2-6:EVALUATING 期间改 revision 会让待核对 marker 永久变成
|
|
622
|
+
// evaluation_attempt_changed 并阻塞同 artifact 重评。
|
|
623
|
+
if (existing.state === "APPROVED" ||
|
|
624
|
+
existing.state === "STALE" ||
|
|
625
|
+
existing.state === "EXPIRED" ||
|
|
626
|
+
existing.state === "EVALUATING") {
|
|
627
|
+
throw new LearningError("version_conflict", "candidate_state_locked", `候选状态 ${existing.state} 不可编辑;请从新案例形成候选`);
|
|
628
|
+
}
|
|
629
|
+
const content = this.buildCandidateContent(merchantId, {
|
|
630
|
+
skillKey: input.skill_key,
|
|
631
|
+
caseIds,
|
|
632
|
+
trigger: text.trigger,
|
|
633
|
+
steps: input.proposed_steps,
|
|
634
|
+
exclusions: text.exclusions,
|
|
635
|
+
reason: text.reason,
|
|
636
|
+
baseReleaseId,
|
|
637
|
+
...(input.required_tools !== undefined
|
|
638
|
+
? { requiredTools: input.required_tools }
|
|
639
|
+
: {}),
|
|
640
|
+
});
|
|
641
|
+
const now = this.now();
|
|
642
|
+
const updated = {
|
|
643
|
+
...existing,
|
|
644
|
+
revision: existing.revision + 1,
|
|
645
|
+
state: "DRAFT",
|
|
646
|
+
skill_key: input.skill_key,
|
|
647
|
+
base_release_id: baseReleaseId,
|
|
648
|
+
case_ids: caseIds,
|
|
649
|
+
trigger_text: text.trigger,
|
|
650
|
+
proposed_steps: content.compiled.artifact.steps,
|
|
651
|
+
exclusions: text.exclusions,
|
|
652
|
+
reason: text.reason,
|
|
653
|
+
required_tools: content.compiled.artifact.required_tools,
|
|
654
|
+
question_schema_version: content.compiled.artifact.question_schema_version,
|
|
655
|
+
tool_contract_digest: content.compiled.tool_contract_digest,
|
|
656
|
+
compiled_artifact: content.compiled.artifact,
|
|
657
|
+
compiled_artifact_hash: content.compiled.artifact_hash,
|
|
658
|
+
compiler_version: content.compiled.compiler_version,
|
|
659
|
+
content_digest: content.contentDigest,
|
|
660
|
+
eval_report_id: null,
|
|
661
|
+
reviewer_id: null,
|
|
662
|
+
approval_ref: null,
|
|
663
|
+
expires_at: null,
|
|
664
|
+
updated_at: now,
|
|
665
|
+
};
|
|
666
|
+
this.repository.updateCandidate(updated);
|
|
667
|
+
this.repository.replaceCandidateCases({
|
|
668
|
+
merchantId,
|
|
669
|
+
candidateId,
|
|
670
|
+
caseIds,
|
|
671
|
+
now,
|
|
672
|
+
});
|
|
673
|
+
this.repository.appendEvent({
|
|
674
|
+
merchantId,
|
|
675
|
+
subjectKind: "candidate",
|
|
676
|
+
subjectId: candidateId,
|
|
677
|
+
event: "candidate_revised",
|
|
678
|
+
detail: {
|
|
679
|
+
revision: updated.revision,
|
|
680
|
+
artifact_hash: updated.compiled_artifact_hash,
|
|
681
|
+
content_digest: updated.content_digest,
|
|
682
|
+
},
|
|
683
|
+
createdAt: now,
|
|
684
|
+
});
|
|
685
|
+
return updated;
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
getCandidate(merchantId, candidateId) {
|
|
689
|
+
this.ensureAvailable();
|
|
690
|
+
return this.repository.readCandidate(requireOpaque(merchantId, "merchant_id"), requireOpaque(candidateId, "candidate_id"));
|
|
691
|
+
}
|
|
692
|
+
listCandidates(merchantId, limit = 100) {
|
|
693
|
+
this.ensureAvailable();
|
|
694
|
+
const merchant = requireOpaque(merchantId, "merchant_id");
|
|
695
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200) {
|
|
696
|
+
throw new LearningError("validation", "limit_invalid", "limit 必须在 1..200");
|
|
697
|
+
}
|
|
698
|
+
return this.repository.listCandidates(merchant, limit);
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* `learning.evaluate`:在隔离执行器中回放冻结套件;预算不足/中断保留
|
|
702
|
+
* EVALUATING 并可续跑。模型调用由注入的 runner 执行,不在 DB 事务内。
|
|
703
|
+
*/
|
|
704
|
+
async evaluateCandidate(input, command = {}) {
|
|
705
|
+
this.ensureAvailable();
|
|
706
|
+
const merchantId = requireOpaque(input.merchant_id, "merchant_id");
|
|
707
|
+
requireActor(merchantId, input.actor);
|
|
708
|
+
const candidateId = requireOpaque(input.candidate_id, "candidate_id");
|
|
709
|
+
const contentHash = requireOpaque(input.content_hash, "content_hash", 128);
|
|
710
|
+
validateEvaluationSuite(input.suite);
|
|
711
|
+
const commandId = command.command_id === undefined
|
|
712
|
+
? undefined
|
|
713
|
+
: requireOpaque(command.command_id, "command_id");
|
|
714
|
+
const requestDigest = contentDigest({
|
|
715
|
+
operation: "learning.evaluateCandidate",
|
|
716
|
+
request: {
|
|
717
|
+
candidate_id: candidateId,
|
|
718
|
+
content_hash: contentHash,
|
|
719
|
+
suite: input.suite,
|
|
720
|
+
require_improvement: input.require_improvement ?? true,
|
|
721
|
+
},
|
|
722
|
+
});
|
|
723
|
+
if (commandId !== undefined) {
|
|
724
|
+
const existing = this.repository.readIdempotent(merchantId, input.actor.actor_id, "learning.evaluateCandidate", commandId);
|
|
725
|
+
if (existing !== undefined) {
|
|
726
|
+
if (existing.requestDigest !== requestDigest) {
|
|
727
|
+
throw new LearningError("idempotency_conflict", "command_replay_conflict", "同一 command_id 已用于不同评测请求");
|
|
728
|
+
}
|
|
729
|
+
return JSON.parse(existing.result);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
const candidate = this.repository.readCandidate(merchantId, candidateId);
|
|
733
|
+
if (candidate === undefined) {
|
|
734
|
+
throw new LearningError("not_found", "candidate_not_found", "候选不存在或不可见");
|
|
735
|
+
}
|
|
736
|
+
if (candidate.compiled_artifact_hash !== contentHash) {
|
|
737
|
+
throw new LearningError("version_conflict", "content_hash_mismatch", "content_hash 与当前冻结产物不一致;请重新读取候选");
|
|
738
|
+
}
|
|
739
|
+
if (candidate.state === "APPROVED" ||
|
|
740
|
+
candidate.state === "REJECTED" ||
|
|
741
|
+
candidate.state === "STALE" ||
|
|
742
|
+
candidate.state === "EXPIRED") {
|
|
743
|
+
throw new LearningError("version_conflict", "candidate_state_locked", `候选状态 ${candidate.state} 不可评测`);
|
|
744
|
+
}
|
|
745
|
+
const evaluationKey = contentDigest({ merchantId, candidateId,
|
|
746
|
+
artifact: candidate.compiled_artifact_hash, suite: input.suite.suite_version });
|
|
747
|
+
const configDigest = contentDigest({ suite: input.suite, require_improvement: input.require_improvement ?? true });
|
|
748
|
+
const keys = [`evaluation:${evaluationKey}`];
|
|
749
|
+
if (commandId !== undefined)
|
|
750
|
+
keys.push(`command:${contentDigest({ merchantId, actor: input.actor.actor_id, commandId })}`);
|
|
751
|
+
const owner = randomUUID();
|
|
752
|
+
const ttl = 300_000;
|
|
753
|
+
const assertClaim = () => this.repository.assertEvaluationClaim(keys, owner, Date.now());
|
|
754
|
+
this.repository.transaction(() => {
|
|
755
|
+
this.repository.claimEvaluation(keys, owner, requestDigest, Date.now(), ttl);
|
|
756
|
+
const previousEvaluation = this.repository.findEvaluation(merchantId, candidateId, candidate.compiled_artifact_hash, input.suite.suite_version);
|
|
757
|
+
const receipt = this.repository.checkEvaluationConfig(evaluationKey, configDigest, previousEvaluation?.runs_completed ?? 0, Date.parse(this.now()));
|
|
758
|
+
if (receipt !== undefined) {
|
|
759
|
+
const binding = previousEvaluation === undefined ? undefined : this.pendingEvaluation(previousEvaluation).binding;
|
|
760
|
+
if (binding === undefined || contentDigest(receipt.binding) !== contentDigest(binding)) {
|
|
761
|
+
throw new LearningError("version_conflict", "evaluation_evidence_mismatch", "本机回执与待核对调用不匹配");
|
|
762
|
+
}
|
|
763
|
+
const outcome = validateOutcome(receipt.outcome);
|
|
764
|
+
this.recoveryWriteGuard(() => this.applyRecoveredAttempt(evaluationKey, binding, outcome, input.actor.actor_id, `local:${binding.dispatch_id}`));
|
|
765
|
+
}
|
|
766
|
+
if (commandId !== undefined) {
|
|
767
|
+
const existing = this.repository.readIdempotent(merchantId, input.actor.actor_id, "learning.evaluateCandidate", commandId);
|
|
768
|
+
if (existing !== undefined && existing.requestDigest !== requestDigest) {
|
|
769
|
+
throw new LearningError("idempotency_conflict", "command_replay_conflict", "同一 command_id 已用于不同评测请求");
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
});
|
|
773
|
+
const heartbeat = setInterval(() => {
|
|
774
|
+
try {
|
|
775
|
+
this.repository.renewEvaluationClaim(keys, owner, Date.now(), ttl);
|
|
776
|
+
}
|
|
777
|
+
catch { /* The next fenced operation fails closed. */ }
|
|
778
|
+
}, 30_000);
|
|
779
|
+
heartbeat.unref();
|
|
780
|
+
try {
|
|
781
|
+
if (commandId !== undefined) {
|
|
782
|
+
const existing = this.repository.readIdempotent(merchantId, input.actor.actor_id, "learning.evaluateCandidate", commandId);
|
|
783
|
+
if (existing !== undefined)
|
|
784
|
+
return JSON.parse(existing.result);
|
|
785
|
+
}
|
|
786
|
+
const evaluation = await runCandidateEvaluation({
|
|
787
|
+
repository: this.repository, now: this.now, candidate, suite: input.suite, runner: input.runner,
|
|
788
|
+
assertClaim,
|
|
789
|
+
setAttempt: (attempt) => this.repository.setEvaluationAttempt(evaluationKey, attempt),
|
|
790
|
+
transitionAttempt: (expected, next) => this.repository.transitionEvaluationAttempt(evaluationKey, expected, next),
|
|
791
|
+
saveReceipt: (marker, outcome) => this.repository.transaction(() => {
|
|
792
|
+
assertClaim();
|
|
793
|
+
const config = this.repository.readEvaluationConfig(evaluationKey);
|
|
794
|
+
if (config?.config_digest !== configDigest || config.pending_attempt !== JSON.stringify({ ...marker, phase: "dispatched" })) {
|
|
795
|
+
throw new LearningError("version_conflict", "evaluation_attempt_changed", "评测调用已变化");
|
|
796
|
+
}
|
|
797
|
+
const binding = {
|
|
798
|
+
merchant_id: merchantId, candidate_id: candidateId, candidate_revision: candidate.revision,
|
|
799
|
+
artifact_hash: candidate.compiled_artifact_hash, suite_version: input.suite.suite_version,
|
|
800
|
+
config_digest: configDigest, ...marker,
|
|
801
|
+
};
|
|
802
|
+
this.repository.saveEvaluationReceipt(`local:${marker.dispatch_id}`, binding, {
|
|
803
|
+
passed: outcome.passed, hard_gate_failures: outcome.hard_gate_failures,
|
|
804
|
+
...(outcome.improvement_delta !== undefined ? { improvement_delta: outcome.improvement_delta } : {}),
|
|
805
|
+
});
|
|
806
|
+
}),
|
|
807
|
+
clearReceipt: (dispatchId) => this.repository.deleteEvaluationReceipt(`local:${dispatchId}`),
|
|
808
|
+
...(input.budget_cap !== undefined ? { budgetCap: input.budget_cap } : {}),
|
|
809
|
+
...(input.require_improvement !== undefined ? { requireImprovement: input.require_improvement } : {}),
|
|
810
|
+
});
|
|
811
|
+
this.repository.transaction(() => {
|
|
812
|
+
assertClaim();
|
|
813
|
+
if (commandId !== undefined && evaluation.run_status === "completed")
|
|
814
|
+
this.repository.saveIdempotent({
|
|
815
|
+
merchantId, actorId: input.actor.actor_id, operation: "learning.evaluateCandidate",
|
|
816
|
+
commandId, requestDigest, result: evaluation, createdAt: this.now(),
|
|
817
|
+
});
|
|
818
|
+
});
|
|
819
|
+
return evaluation;
|
|
820
|
+
}
|
|
821
|
+
finally {
|
|
822
|
+
clearInterval(heartbeat);
|
|
823
|
+
this.repository.transaction(() => {
|
|
824
|
+
const completed = commandId !== undefined &&
|
|
825
|
+
this.repository.readIdempotent(merchantId, input.actor.actor_id, "learning.evaluateCandidate", commandId)?.requestDigest === requestDigest;
|
|
826
|
+
this.repository.releaseEvaluationClaim(keys, owner, completed);
|
|
827
|
+
});
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
/** 受信应用入口:仅披露当前待核对标识,旧版缺少调用标识时不可自动恢复。 */
|
|
831
|
+
getPendingEvaluation(input) {
|
|
832
|
+
this.ensureAvailable();
|
|
833
|
+
requireActorCapability(input.merchant_id, input.actor, "learning:review");
|
|
834
|
+
const evaluation = this.repository.readEvaluation(input.merchant_id, requireOpaque(input.evaluation_id, "evaluation_id"));
|
|
835
|
+
if (evaluation === undefined)
|
|
836
|
+
throw new LearningError("not_found", "evaluation_not_found", "评测不存在或不可见");
|
|
837
|
+
return this.pendingEvaluation(evaluation);
|
|
838
|
+
}
|
|
839
|
+
pendingEvaluation(evaluation) {
|
|
840
|
+
const merchantId = evaluation.merchant_id;
|
|
841
|
+
const key = contentDigest({ merchantId, candidateId: evaluation.candidate_id, artifact: evaluation.artifact_hash, suite: evaluation.suite_version });
|
|
842
|
+
const config = this.repository.readEvaluationConfig(key);
|
|
843
|
+
if (config === undefined || config.pending_attempt === null)
|
|
844
|
+
return { pending: null };
|
|
845
|
+
let marker;
|
|
846
|
+
try {
|
|
847
|
+
marker = JSON.parse(config.pending_attempt);
|
|
848
|
+
}
|
|
849
|
+
catch {
|
|
850
|
+
return { pending: "legacy_unverifiable" };
|
|
851
|
+
}
|
|
852
|
+
if (marker === null || typeof marker !== "object" || typeof marker.dispatch_id !== "string" || typeof marker.scenario_id !== "string" || !["target", "adjacent", "boundary"].includes(marker.kind) || marker.repetitions !== 3 || !["baseline", "candidate"].includes(marker.variant) || !Number.isSafeInteger(marker.attempt) || marker.attempt < 1 || marker.attempt > marker.repetitions)
|
|
853
|
+
return { pending: "legacy_unverifiable" };
|
|
854
|
+
const binding = { merchant_id: merchantId, candidate_id: evaluation.candidate_id, candidate_revision: evaluation.candidate_revision, artifact_hash: evaluation.artifact_hash, suite_version: evaluation.suite_version, config_digest: config.config_digest, scenario_id: marker.scenario_id, kind: marker.kind, repetitions: marker.repetitions, variant: marker.variant, attempt: marker.attempt, dispatch_id: marker.dispatch_id, ...(typeof marker.dispatched_at === "string" ? { dispatched_at: marker.dispatched_at } : {}), ...(typeof marker.expires_at === "string" ? { expires_at: marker.expires_at } : {}) };
|
|
855
|
+
const evidenceRef = `local:${binding.dispatch_id}`;
|
|
856
|
+
const receipt = this.repository.readEvaluationReceipt(evidenceRef);
|
|
857
|
+
const preparedRef = `local-prepared:${binding.dispatch_id}`;
|
|
858
|
+
const preparedAvailable = marker.phase === "prepared" && receipt === undefined && !this.repository.hasActiveEvaluationClaim(`evaluation:${key}`, Date.now());
|
|
859
|
+
return { pending: "uncertain", binding, ...(receipt !== undefined && contentDigest(receipt.binding) === contentDigest(binding) ? { evidence_ref: evidenceRef } : preparedAvailable ? { evidence_ref: preparedRef } : {}) };
|
|
860
|
+
}
|
|
861
|
+
/** 核验器由可信宿主注入;核验不调用模型,完成后由调用方显式续跑。
|
|
862
|
+
* 恢复仅保存判定必需的 passed、hard_gate_failures、improvement_delta;
|
|
863
|
+
* trace_ref 和 diagnostics 不写入,以免保存未经约束的证据原文。
|
|
864
|
+
*/
|
|
865
|
+
async resolvePendingEvaluation(input) {
|
|
866
|
+
this.ensureAvailable();
|
|
867
|
+
requireOpaque(input.command_id, "command_id");
|
|
868
|
+
const evidenceRef = requireOpaque(input.evidence_ref, "evidence_ref", 512);
|
|
869
|
+
const expectedDispatchId = requireOpaque(input.expected_dispatch_id, "expected_dispatch_id");
|
|
870
|
+
const operation = "learning.resolvePendingEvaluation";
|
|
871
|
+
const digest = contentDigest({ evaluation_id: input.evaluation_id, expected_dispatch_id: expectedDispatchId, evidence_ref: evidenceRef });
|
|
872
|
+
requireActorCapability(input.merchant_id, input.actor, "learning:review");
|
|
873
|
+
const old = this.repository.readIdempotent(input.merchant_id, input.actor.actor_id, operation, input.command_id);
|
|
874
|
+
if (old !== undefined) {
|
|
875
|
+
if (old.requestDigest !== digest)
|
|
876
|
+
throw new LearningError("idempotency_conflict", "command_replay_conflict", "同一 command_id 已用于不同请求");
|
|
877
|
+
return JSON.parse(old.result);
|
|
878
|
+
}
|
|
879
|
+
const pending = this.getPendingEvaluation(input);
|
|
880
|
+
if (pending.binding === undefined)
|
|
881
|
+
throw new LearningError("version_conflict", "evaluation_recovery_unavailable", "缺少可核验调用标识或可信证据来源");
|
|
882
|
+
const binding = pending.binding;
|
|
883
|
+
if (binding.dispatch_id !== expectedDispatchId)
|
|
884
|
+
throw new LearningError("version_conflict", "evaluation_attempt_changed", "调用标识已变化");
|
|
885
|
+
const key = contentDigest({ merchantId: binding.merchant_id, candidateId: binding.candidate_id, artifact: binding.artifact_hash, suite: binding.suite_version });
|
|
886
|
+
const claimKey = `evaluation:${key}`;
|
|
887
|
+
const owner = randomUUID();
|
|
888
|
+
this.recoveryWriteGuard(() => this.repository.transaction(() => this.repository.claimEvaluation([claimKey], owner, digest, Date.now(), 300_000)));
|
|
889
|
+
try {
|
|
890
|
+
const localRef = `local:${binding.dispatch_id}`;
|
|
891
|
+
const receipt = this.repository.readEvaluationReceipt(localRef);
|
|
892
|
+
if (receipt !== undefined && evidenceRef !== localRef) {
|
|
893
|
+
throw new LearningError("version_conflict", "evaluation_evidence_mismatch", "已有本机完成回执,必须使用该回执");
|
|
894
|
+
}
|
|
895
|
+
if (receipt === undefined && evidenceRef.startsWith("local:")) {
|
|
896
|
+
throw new LearningError("version_conflict", "evaluation_recovery_unavailable", "本机回执不存在");
|
|
897
|
+
}
|
|
898
|
+
const config = this.repository.readEvaluationConfig(key);
|
|
899
|
+
let phase;
|
|
900
|
+
try {
|
|
901
|
+
phase = JSON.parse(config?.pending_attempt ?? "null")?.phase;
|
|
902
|
+
}
|
|
903
|
+
catch {
|
|
904
|
+
phase = undefined;
|
|
905
|
+
}
|
|
906
|
+
const preparedRef = `local-prepared:${binding.dispatch_id}`;
|
|
907
|
+
const localPrepared = receipt === undefined && phase === "prepared" && evidenceRef === preparedRef;
|
|
908
|
+
if (evidenceRef.startsWith("local-prepared:") && !localPrepared) {
|
|
909
|
+
throw new LearningError("version_conflict", "evaluation_recovery_unavailable", "缺少本机未派发证明");
|
|
910
|
+
}
|
|
911
|
+
if (phase === "prepared" && receipt === undefined && evidenceRef !== preparedRef) {
|
|
912
|
+
throw new LearningError("version_conflict", "evaluation_evidence_mismatch", "已准备调用必须使用本机证明");
|
|
913
|
+
}
|
|
914
|
+
const verified = receipt !== undefined
|
|
915
|
+
? { status: "completed", binding: receipt.binding, outcome: receipt.outcome }
|
|
916
|
+
: localPrepared ? { status: "not_executed", binding }
|
|
917
|
+
: this.recoveryVerifier !== undefined ? await this.recoveryVerifier(binding, evidenceRef) : { status: "unknown" };
|
|
918
|
+
if (receipt === undefined && !localPrepared && this.recoveryVerifier === undefined)
|
|
919
|
+
throw new LearningError("version_conflict", "evaluation_recovery_unavailable", "缺少可信证据来源");
|
|
920
|
+
if (verified.status !== "completed" && verified.status !== "not_executed")
|
|
921
|
+
throw new LearningError("version_conflict", "evaluation_evidence_unknown", "证据不足,评测仍被阻塞");
|
|
922
|
+
if (contentDigest(verified.binding) !== contentDigest(binding))
|
|
923
|
+
throw new LearningError("version_conflict", "evaluation_evidence_mismatch", "证据与待核对调用不匹配");
|
|
924
|
+
const outcome = verified.status === "completed" ? validateOutcome(verified.outcome) : undefined;
|
|
925
|
+
return this.recoveryWriteGuard(() => this.repository.transaction(() => {
|
|
926
|
+
this.repository.assertEvaluationClaim([claimKey], owner, Date.now());
|
|
927
|
+
const replay = this.repository.readIdempotent(input.merchant_id, input.actor.actor_id, operation, input.command_id);
|
|
928
|
+
if (replay !== undefined) {
|
|
929
|
+
if (replay.requestDigest !== digest)
|
|
930
|
+
throw new LearningError("idempotency_conflict", "command_replay_conflict", "同一 command_id 已用于不同请求");
|
|
931
|
+
return JSON.parse(replay.result);
|
|
932
|
+
}
|
|
933
|
+
const fresh = this.getPendingEvaluation(input);
|
|
934
|
+
if (fresh.binding === undefined || contentDigest(fresh.binding) !== contentDigest(binding))
|
|
935
|
+
throw new LearningError("version_conflict", "evaluation_attempt_changed", "待核对调用已变化");
|
|
936
|
+
if (localPrepared) {
|
|
937
|
+
const current = this.repository.readEvaluationConfig(key);
|
|
938
|
+
if (current?.pending_attempt !== config?.pending_attempt || phase !== "prepared")
|
|
939
|
+
throw new LearningError("version_conflict", "evaluation_attempt_changed", "待核对调用已变化");
|
|
940
|
+
}
|
|
941
|
+
this.applyRecoveredAttempt(key, binding, outcome, input.actor.actor_id, evidenceRef);
|
|
942
|
+
const result = { status: verified.status };
|
|
943
|
+
this.repository.saveIdempotent({ merchantId: binding.merchant_id, actorId: input.actor.actor_id, operation, commandId: input.command_id, requestDigest: digest, result, createdAt: this.now() });
|
|
944
|
+
return result;
|
|
945
|
+
}));
|
|
946
|
+
}
|
|
947
|
+
finally {
|
|
948
|
+
// 写入权已丢失时不再触碰账本;租约过期后可由新写者接管。
|
|
949
|
+
// 清理失败不能覆盖已提交的结果或原本的核验错误。
|
|
950
|
+
try {
|
|
951
|
+
this.recoveryWriteGuard(() => this.repository.transaction(() => this.repository.releaseEvaluationClaim([claimKey], owner)));
|
|
952
|
+
}
|
|
953
|
+
catch { /* lease expiry permits takeover */ }
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
applyRecoveredAttempt(key, binding, outcome, actorId, evidenceRef) {
|
|
957
|
+
const candidate = this.repository.readCandidate(binding.merchant_id, binding.candidate_id);
|
|
958
|
+
const evaluation = this.repository.findEvaluation(binding.merchant_id, binding.candidate_id, binding.artifact_hash, binding.suite_version);
|
|
959
|
+
if (candidate?.state !== "EVALUATING" || candidate.revision !== binding.candidate_revision ||
|
|
960
|
+
evaluation?.candidate_revision !== binding.candidate_revision ||
|
|
961
|
+
evaluation.state !== "EVALUATING" || evaluation.run_status === "completed") {
|
|
962
|
+
throw new LearningError("version_conflict", "evaluation_attempt_changed", "评测或候选已变化");
|
|
963
|
+
}
|
|
964
|
+
const previous = evaluation.results.scenarios[binding.scenario_id];
|
|
965
|
+
const attempts = [...(previous?.attempts ?? [])];
|
|
966
|
+
if (attempts.some((a) => a.variant === binding.variant && a.attempt === binding.attempt) ||
|
|
967
|
+
(binding.variant === "candidate" && !attempts.some((a) => a.variant === "baseline" && a.attempt === binding.attempt))) {
|
|
968
|
+
throw new LearningError("version_conflict", "evaluation_attempt_changed", "评测结果已变化");
|
|
969
|
+
}
|
|
970
|
+
const now = this.now();
|
|
971
|
+
if (outcome !== undefined) {
|
|
972
|
+
attempts.push({
|
|
973
|
+
variant: binding.variant,
|
|
974
|
+
attempt: binding.attempt,
|
|
975
|
+
passed: outcome.passed,
|
|
976
|
+
hard_gate_failures: outcome.hard_gate_failures,
|
|
977
|
+
...(outcome.improvement_delta !== undefined ? { improvement_delta: outcome.improvement_delta } : {}),
|
|
978
|
+
});
|
|
979
|
+
const scenario = { scenario_id: binding.scenario_id, kind: binding.kind, repetitions: binding.repetitions, attempts };
|
|
980
|
+
this.repository.updateEvaluation({
|
|
981
|
+
...evaluation,
|
|
982
|
+
runs_completed: evaluation.runs_completed + 1,
|
|
983
|
+
results: { scenarios: { ...evaluation.results.scenarios, [scenario.scenario_id]: scenario } },
|
|
984
|
+
updated_at: now,
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
this.repository.setEvaluationAttempt(key, null);
|
|
988
|
+
this.repository.deleteEvaluationReceipt(`local:${binding.dispatch_id}`);
|
|
989
|
+
this.repository.appendEvent({
|
|
990
|
+
merchantId: binding.merchant_id,
|
|
991
|
+
subjectKind: "evaluation",
|
|
992
|
+
subjectId: evaluation.evaluation_id,
|
|
993
|
+
event: "evaluation_attempt_reconciled",
|
|
994
|
+
detail: {
|
|
995
|
+
actor_id: actorId,
|
|
996
|
+
status: outcome === undefined ? "not_executed" : "completed",
|
|
997
|
+
dispatch_id: binding.dispatch_id,
|
|
998
|
+
evidence_digest: contentDigest({ evidenceRef }),
|
|
999
|
+
},
|
|
1000
|
+
createdAt: now,
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
getEvaluation(merchantId, evaluationId) {
|
|
1004
|
+
this.ensureAvailable();
|
|
1005
|
+
return this.repository.readEvaluation(requireOpaque(merchantId, "merchant_id"), requireOpaque(evaluationId, "evaluation_id"));
|
|
1006
|
+
}
|
|
1007
|
+
listEvaluations(merchantId, limit = 100) {
|
|
1008
|
+
this.ensureAvailable();
|
|
1009
|
+
const merchant = requireOpaque(merchantId, "merchant_id");
|
|
1010
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200) {
|
|
1011
|
+
throw new LearningError("validation", "limit_invalid", "limit 必须在 1..200");
|
|
1012
|
+
}
|
|
1013
|
+
return this.repository.listEvaluations(merchant, limit);
|
|
1014
|
+
}
|
|
1015
|
+
/**
|
|
1016
|
+
* `learning.review`:真实管理员审核。批准绑定确切内容、冻结产物、评测
|
|
1017
|
+
* 报告与截止(待审 7 天;批准后须在 min(批准+24h, expires_at) 内发布)。
|
|
1018
|
+
*/
|
|
1019
|
+
reviewCandidate(input, command = {}) {
|
|
1020
|
+
this.ensureAvailable();
|
|
1021
|
+
const merchantId = requireOpaque(input.merchant_id, "merchant_id");
|
|
1022
|
+
requireActorCapability(merchantId, input.actor, "learning:review");
|
|
1023
|
+
const candidateId = requireOpaque(input.candidate_id, "candidate_id");
|
|
1024
|
+
const contentHash = requireOpaque(input.content_hash, "content_hash");
|
|
1025
|
+
const evaluationId = requireOpaque(input.evaluation_id, "evaluation_id");
|
|
1026
|
+
if (input.decision !== "approve" && input.decision !== "reject") {
|
|
1027
|
+
throw new LearningError("validation", "decision_invalid", "decision 只能是 approve/reject");
|
|
1028
|
+
}
|
|
1029
|
+
const reason = input.reason === undefined
|
|
1030
|
+
? null
|
|
1031
|
+
: requireBoundedText(input.reason, "reason", MAX_REASON_CHARS);
|
|
1032
|
+
const request = {
|
|
1033
|
+
candidate_id: candidateId,
|
|
1034
|
+
content_hash: contentHash,
|
|
1035
|
+
evaluation_id: evaluationId,
|
|
1036
|
+
decision: input.decision,
|
|
1037
|
+
reason,
|
|
1038
|
+
};
|
|
1039
|
+
return this.withCommand(merchantId, input.actor.actor_id, "learning.reviewCandidate", request, command, () => {
|
|
1040
|
+
const now = this.now();
|
|
1041
|
+
const candidate = this.repository.readCandidate(merchantId, candidateId);
|
|
1042
|
+
if (candidate === undefined) {
|
|
1043
|
+
throw new LearningError("not_found", "candidate_not_found", "候选不存在或不可见");
|
|
1044
|
+
}
|
|
1045
|
+
if (candidate.compiled_artifact_hash !== contentHash) {
|
|
1046
|
+
throw new LearningError("version_conflict", "content_hash_mismatch", "候选内容已变化");
|
|
1047
|
+
}
|
|
1048
|
+
if (candidate.state !== "READY_FOR_REVIEW") {
|
|
1049
|
+
throw new LearningError("version_conflict", "candidate_not_ready", `候选状态 ${candidate.state} 不可审核`);
|
|
1050
|
+
}
|
|
1051
|
+
this.assertCandidateSourcesAvailable(merchantId, candidate);
|
|
1052
|
+
const evaluation = this.repository.readEvaluation(merchantId, evaluationId);
|
|
1053
|
+
if (evaluation === undefined ||
|
|
1054
|
+
evaluation.candidate_id !== candidateId ||
|
|
1055
|
+
evaluation.artifact_hash !== candidate.compiled_artifact_hash ||
|
|
1056
|
+
evaluation.state !== "READY_FOR_REVIEW" ||
|
|
1057
|
+
evaluation.report?.verdict !== "pass") {
|
|
1058
|
+
throw new LearningError("version_conflict", "evaluation_not_passed", "评测报告不存在或未通过;不能审核");
|
|
1059
|
+
}
|
|
1060
|
+
if (candidate.eval_report_id !== evaluationId) {
|
|
1061
|
+
throw new LearningError("version_conflict", "evaluation_mismatch", "候选绑定的评测报告与审核引用不一致");
|
|
1062
|
+
}
|
|
1063
|
+
const approvedAt = now;
|
|
1064
|
+
const expiresAt = new Date(Date.parse(approvedAt) + REVIEW_TTL_MS).toISOString();
|
|
1065
|
+
const review = {
|
|
1066
|
+
review_id: `rev_${randomUUID()}`,
|
|
1067
|
+
merchant_id: merchantId,
|
|
1068
|
+
candidate_id: candidateId,
|
|
1069
|
+
candidate_revision: candidate.revision,
|
|
1070
|
+
content_hash: candidate.content_digest,
|
|
1071
|
+
artifact_hash: candidate.compiled_artifact_hash,
|
|
1072
|
+
compiler_version: candidate.compiler_version,
|
|
1073
|
+
question_schema_version: candidate.question_schema_version,
|
|
1074
|
+
tool_contract_digest: candidate.tool_contract_digest,
|
|
1075
|
+
eval_report_id: evaluationId,
|
|
1076
|
+
reviewer_id: input.actor.actor_id,
|
|
1077
|
+
decision: input.decision === "approve" ? "APPROVE" : "REJECT",
|
|
1078
|
+
approval_ref: `apr_${randomUUID()}`,
|
|
1079
|
+
reason,
|
|
1080
|
+
approved_at: approvedAt,
|
|
1081
|
+
expires_at: expiresAt,
|
|
1082
|
+
created_at: approvedAt,
|
|
1083
|
+
};
|
|
1084
|
+
this.repository.insertReview(review);
|
|
1085
|
+
this.repository.updateCandidate({
|
|
1086
|
+
...candidate,
|
|
1087
|
+
state: input.decision === "approve" ? "APPROVED" : "REJECTED",
|
|
1088
|
+
reviewer_id: input.actor.actor_id,
|
|
1089
|
+
approval_ref: input.decision === "approve" ? review.approval_ref : null,
|
|
1090
|
+
expires_at: input.decision === "approve" ? expiresAt : null,
|
|
1091
|
+
updated_at: approvedAt,
|
|
1092
|
+
});
|
|
1093
|
+
this.repository.appendEvent({
|
|
1094
|
+
merchantId,
|
|
1095
|
+
subjectKind: "candidate",
|
|
1096
|
+
subjectId: candidateId,
|
|
1097
|
+
event: input.decision === "approve" ? "candidate_approved" : "candidate_rejected",
|
|
1098
|
+
detail: { approval_ref: review.approval_ref, reviewer_id: review.reviewer_id },
|
|
1099
|
+
createdAt: approvedAt,
|
|
1100
|
+
});
|
|
1101
|
+
return review;
|
|
1102
|
+
});
|
|
1103
|
+
}
|
|
1104
|
+
/**
|
|
1105
|
+
* `learning.publish`:只核验并激活已批准冻结产物,不重新生成正文;CAS
|
|
1106
|
+
* 生效指针 generation,旧 ACTIVE 版本转 RETIRED。
|
|
1107
|
+
*/
|
|
1108
|
+
publishRelease(input, command = {}) {
|
|
1109
|
+
this.ensureAvailable();
|
|
1110
|
+
const merchantId = requireOpaque(input.merchant_id, "merchant_id");
|
|
1111
|
+
requireActorCapability(merchantId, input.actor, "learning:publish");
|
|
1112
|
+
const approvalRef = requireOpaque(input.approval_ref, "approval_ref");
|
|
1113
|
+
if (!Number.isSafeInteger(input.expected_generation) || input.expected_generation < 0) {
|
|
1114
|
+
throw new LearningError("validation", "expected_generation_invalid", "expected_generation 必须是非负整数");
|
|
1115
|
+
}
|
|
1116
|
+
return this.withCommand(merchantId, input.actor.actor_id, "learning.publishRelease", { approval_ref: approvalRef, expected_generation: input.expected_generation }, command, () => {
|
|
1117
|
+
const existing = this.repository.findReleaseByApproval(merchantId, approvalRef);
|
|
1118
|
+
if (existing !== undefined) {
|
|
1119
|
+
if (existing.state === "REVOKED") {
|
|
1120
|
+
throw new LearningError("unsupported_capability", "release_revoked", "该批准对应的版本已撤回;不能再次发布");
|
|
1121
|
+
}
|
|
1122
|
+
return existing;
|
|
1123
|
+
}
|
|
1124
|
+
const now = this.now();
|
|
1125
|
+
const review = this.repository.readReviewByApproval(merchantId, approvalRef);
|
|
1126
|
+
if (review === undefined || review.decision !== "APPROVE") {
|
|
1127
|
+
throw new LearningError("not_found", "approval_not_found", "批准不存在或不是批准决定");
|
|
1128
|
+
}
|
|
1129
|
+
const candidate = this.repository.readCandidate(merchantId, review.candidate_id);
|
|
1130
|
+
if (candidate === undefined || candidate.state !== "APPROVED") {
|
|
1131
|
+
throw new LearningError("version_conflict", "candidate_not_approved", "候选不再是已批准状态;请重新审核");
|
|
1132
|
+
}
|
|
1133
|
+
this.assertCandidateSourcesAvailable(merchantId, candidate);
|
|
1134
|
+
if (candidate.revision !== review.candidate_revision ||
|
|
1135
|
+
candidate.content_digest !== review.content_hash ||
|
|
1136
|
+
candidate.compiled_artifact_hash !== review.artifact_hash ||
|
|
1137
|
+
candidate.tool_contract_digest !== review.tool_contract_digest ||
|
|
1138
|
+
candidate.compiler_version !== review.compiler_version) {
|
|
1139
|
+
throw new LearningError("version_conflict", "approval_dependency_changed", "批准绑定的内容/产物/工具契约已变化;需要重新评测与审核");
|
|
1140
|
+
}
|
|
1141
|
+
const publishDeadline = Math.min(Date.parse(review.approved_at) + PUBLISH_WINDOW_MS, Date.parse(review.expires_at));
|
|
1142
|
+
if (!(Date.parse(now) < publishDeadline)) {
|
|
1143
|
+
throw new LearningError("version_conflict", "approval_expired", "批准已过发布窗口;需要重新审核");
|
|
1144
|
+
}
|
|
1145
|
+
verifyReleaseArtifact({
|
|
1146
|
+
skill_key: candidate.skill_key,
|
|
1147
|
+
artifact_hash: candidate.compiled_artifact_hash,
|
|
1148
|
+
tool_contract_digest: candidate.tool_contract_digest,
|
|
1149
|
+
compiler_version: candidate.compiler_version,
|
|
1150
|
+
compiled_artifact: candidate.compiled_artifact,
|
|
1151
|
+
});
|
|
1152
|
+
const pointer = this.repository.readPointer(merchantId, candidate.skill_key);
|
|
1153
|
+
const currentGeneration = pointer?.generation ?? 0;
|
|
1154
|
+
if (currentGeneration !== input.expected_generation) {
|
|
1155
|
+
throw new LearningError("version_conflict", "generation_mismatch", `生效指针 generation 已变化(当前 ${currentGeneration})`);
|
|
1156
|
+
}
|
|
1157
|
+
if (pointer?.release_id !== null && pointer?.release_id !== undefined) {
|
|
1158
|
+
const previous = this.repository.readRelease(merchantId, pointer.release_id);
|
|
1159
|
+
if (previous !== undefined && previous.state === "ACTIVE") {
|
|
1160
|
+
this.repository.updateRelease({
|
|
1161
|
+
...previous,
|
|
1162
|
+
state: "RETIRED",
|
|
1163
|
+
retired_at: now,
|
|
1164
|
+
updated_at: now,
|
|
1165
|
+
});
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
const release = {
|
|
1169
|
+
release_id: `rel_${randomUUID()}`,
|
|
1170
|
+
merchant_id: merchantId,
|
|
1171
|
+
skill_key: candidate.skill_key,
|
|
1172
|
+
trigger_text: candidate.trigger_text,
|
|
1173
|
+
generation: currentGeneration + 1,
|
|
1174
|
+
state: "ACTIVE",
|
|
1175
|
+
artifact_hash: candidate.compiled_artifact_hash,
|
|
1176
|
+
content_hash: candidate.content_digest,
|
|
1177
|
+
compiled_artifact: candidate.compiled_artifact,
|
|
1178
|
+
candidate_id: candidate.candidate_id,
|
|
1179
|
+
candidate_revision: candidate.revision,
|
|
1180
|
+
compiler_version: candidate.compiler_version,
|
|
1181
|
+
question_schema_version: candidate.question_schema_version,
|
|
1182
|
+
tool_contract_digest: candidate.tool_contract_digest,
|
|
1183
|
+
eval_report_id: review.eval_report_id,
|
|
1184
|
+
approval_ref: approvalRef,
|
|
1185
|
+
revocation_epoch: 0,
|
|
1186
|
+
retired_at: null,
|
|
1187
|
+
revoked_at: null,
|
|
1188
|
+
created_at: now,
|
|
1189
|
+
updated_at: now,
|
|
1190
|
+
};
|
|
1191
|
+
this.repository.insertRelease(release);
|
|
1192
|
+
this.repository.upsertPointer({
|
|
1193
|
+
merchant_id: merchantId,
|
|
1194
|
+
skill_key: release.skill_key,
|
|
1195
|
+
release_id: release.release_id,
|
|
1196
|
+
generation: release.generation,
|
|
1197
|
+
updated_at: now,
|
|
1198
|
+
});
|
|
1199
|
+
this.repository.appendEvent({
|
|
1200
|
+
merchantId,
|
|
1201
|
+
subjectKind: "release",
|
|
1202
|
+
subjectId: release.release_id,
|
|
1203
|
+
event: "release_published",
|
|
1204
|
+
detail: {
|
|
1205
|
+
skill_key: release.skill_key,
|
|
1206
|
+
generation: release.generation,
|
|
1207
|
+
artifact_hash: release.artifact_hash,
|
|
1208
|
+
// A08:审计真实发布人(服务端 actor,不接受请求正文自报)。
|
|
1209
|
+
publisher_id: input.actor.actor_id,
|
|
1210
|
+
},
|
|
1211
|
+
createdAt: now,
|
|
1212
|
+
});
|
|
1213
|
+
return release;
|
|
1214
|
+
});
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* `learning.rollback`:切回仍兼容且已审核的历史版本;只新增 pointer
|
|
1218
|
+
* generation,不覆盖历史;REVOKED 或不兼容版本拒绝。
|
|
1219
|
+
*/
|
|
1220
|
+
rollbackRelease(input, command = {}) {
|
|
1221
|
+
this.ensureAvailable();
|
|
1222
|
+
const merchantId = requireOpaque(input.merchant_id, "merchant_id");
|
|
1223
|
+
requireActorCapability(merchantId, input.actor, "learning:publish");
|
|
1224
|
+
const targetReleaseId = requireOpaque(input.target_release_id, "target_release_id");
|
|
1225
|
+
if (!Number.isSafeInteger(input.expected_generation) || input.expected_generation < 1) {
|
|
1226
|
+
throw new LearningError("validation", "expected_generation_invalid", "expected_generation 必须是正整数");
|
|
1227
|
+
}
|
|
1228
|
+
const reason = requireBoundedText(input.reason, "reason", MAX_REASON_CHARS);
|
|
1229
|
+
return this.withCommand(merchantId, input.actor.actor_id, "learning.rollbackRelease", { target_release_id: targetReleaseId, expected_generation: input.expected_generation, reason }, command, () => {
|
|
1230
|
+
const now = this.now();
|
|
1231
|
+
const target = this.repository.readRelease(merchantId, targetReleaseId);
|
|
1232
|
+
if (target === undefined) {
|
|
1233
|
+
throw new LearningError("not_found", "release_not_found", "目标版本不存在或不可见");
|
|
1234
|
+
}
|
|
1235
|
+
if (target.state === "REVOKED") {
|
|
1236
|
+
throw new LearningError("unsupported_capability", "release_revoked", "已撤回版本不能回滚;只能回滚到仍兼容的已审核版本");
|
|
1237
|
+
}
|
|
1238
|
+
verifyReleaseArtifact(target);
|
|
1239
|
+
const pointer = this.repository.readPointer(merchantId, target.skill_key);
|
|
1240
|
+
const currentGeneration = pointer?.generation ?? 0;
|
|
1241
|
+
if (currentGeneration !== input.expected_generation) {
|
|
1242
|
+
throw new LearningError("version_conflict", "generation_mismatch", `生效指针 generation 已变化(当前 ${currentGeneration})`);
|
|
1243
|
+
}
|
|
1244
|
+
const previousReleaseId = pointer?.release_id ?? null;
|
|
1245
|
+
if (previousReleaseId === target.release_id) {
|
|
1246
|
+
return {
|
|
1247
|
+
release_id: target.release_id,
|
|
1248
|
+
generation: currentGeneration,
|
|
1249
|
+
skill_key: target.skill_key,
|
|
1250
|
+
previous_release_id: previousReleaseId,
|
|
1251
|
+
};
|
|
1252
|
+
}
|
|
1253
|
+
if (previousReleaseId !== null) {
|
|
1254
|
+
const previous = this.repository.readRelease(merchantId, previousReleaseId);
|
|
1255
|
+
if (previous !== undefined && previous.state === "ACTIVE") {
|
|
1256
|
+
this.repository.updateRelease({
|
|
1257
|
+
...previous,
|
|
1258
|
+
state: "RETIRED",
|
|
1259
|
+
retired_at: now,
|
|
1260
|
+
updated_at: now,
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
// 回滚目标重新成为生效版本;历史内容不变,只切指针与状态。
|
|
1265
|
+
if (target.state !== "ACTIVE") {
|
|
1266
|
+
this.repository.updateRelease({
|
|
1267
|
+
...target,
|
|
1268
|
+
state: "ACTIVE",
|
|
1269
|
+
retired_at: null,
|
|
1270
|
+
updated_at: now,
|
|
1271
|
+
});
|
|
1272
|
+
}
|
|
1273
|
+
this.repository.upsertPointer({
|
|
1274
|
+
merchant_id: merchantId,
|
|
1275
|
+
skill_key: target.skill_key,
|
|
1276
|
+
release_id: target.release_id,
|
|
1277
|
+
generation: currentGeneration + 1,
|
|
1278
|
+
updated_at: now,
|
|
1279
|
+
});
|
|
1280
|
+
this.repository.appendEvent({
|
|
1281
|
+
merchantId,
|
|
1282
|
+
subjectKind: "release",
|
|
1283
|
+
subjectId: target.release_id,
|
|
1284
|
+
event: "release_rolled_back",
|
|
1285
|
+
detail: { generation: currentGeneration + 1, reason },
|
|
1286
|
+
createdAt: now,
|
|
1287
|
+
});
|
|
1288
|
+
return {
|
|
1289
|
+
release_id: target.release_id,
|
|
1290
|
+
generation: currentGeneration + 1,
|
|
1291
|
+
skill_key: target.skill_key,
|
|
1292
|
+
previous_release_id: previousReleaseId,
|
|
1293
|
+
};
|
|
1294
|
+
});
|
|
1295
|
+
}
|
|
1296
|
+
/**
|
|
1297
|
+
* `learning.revoke`:安全撤回。REVOKED 版本在加载/工具/发布门都被拒绝;
|
|
1298
|
+
* 撤回当前生效版本会清空生效指针(回到原接待),并递增 revocation_epoch。
|
|
1299
|
+
*/
|
|
1300
|
+
revokeRelease(input, command = {}) {
|
|
1301
|
+
this.ensureAvailable();
|
|
1302
|
+
const merchantId = requireOpaque(input.merchant_id, "merchant_id");
|
|
1303
|
+
requireActorCapability(merchantId, input.actor, "learning:publish");
|
|
1304
|
+
const releaseId = requireOpaque(input.release_id, "release_id");
|
|
1305
|
+
if (!Number.isSafeInteger(input.expected_generation) || input.expected_generation < 0) {
|
|
1306
|
+
throw new LearningError("validation", "expected_generation_invalid", "expected_generation 必须是非负整数");
|
|
1307
|
+
}
|
|
1308
|
+
const reason = requireBoundedText(input.reason, "reason", MAX_REASON_CHARS);
|
|
1309
|
+
return this.withCommand(merchantId, input.actor.actor_id, "learning.revokeRelease", { release_id: releaseId, expected_generation: input.expected_generation, reason }, command, () => {
|
|
1310
|
+
const now = this.now();
|
|
1311
|
+
const release = this.repository.readRelease(merchantId, releaseId);
|
|
1312
|
+
if (release === undefined) {
|
|
1313
|
+
throw new LearningError("not_found", "release_not_found", "版本不存在或不可见");
|
|
1314
|
+
}
|
|
1315
|
+
if (release.state === "REVOKED")
|
|
1316
|
+
return release;
|
|
1317
|
+
const pointer = this.repository.readPointer(merchantId, release.skill_key);
|
|
1318
|
+
const currentGeneration = pointer?.generation ?? 0;
|
|
1319
|
+
if (currentGeneration !== input.expected_generation) {
|
|
1320
|
+
throw new LearningError("version_conflict", "generation_mismatch", `生效指针 generation 已变化(当前 ${currentGeneration})`);
|
|
1321
|
+
}
|
|
1322
|
+
const revoked = {
|
|
1323
|
+
...release,
|
|
1324
|
+
state: "REVOKED",
|
|
1325
|
+
revocation_epoch: release.revocation_epoch + 1,
|
|
1326
|
+
revoked_at: now,
|
|
1327
|
+
updated_at: now,
|
|
1328
|
+
};
|
|
1329
|
+
this.repository.updateRelease(revoked);
|
|
1330
|
+
if (pointer?.release_id === release.release_id) {
|
|
1331
|
+
this.repository.upsertPointer({
|
|
1332
|
+
merchant_id: merchantId,
|
|
1333
|
+
skill_key: release.skill_key,
|
|
1334
|
+
release_id: null,
|
|
1335
|
+
generation: currentGeneration + 1,
|
|
1336
|
+
updated_at: now,
|
|
1337
|
+
});
|
|
1338
|
+
}
|
|
1339
|
+
this.repository.appendEvent({
|
|
1340
|
+
merchantId,
|
|
1341
|
+
subjectKind: "release",
|
|
1342
|
+
subjectId: release.release_id,
|
|
1343
|
+
event: "release_revoked",
|
|
1344
|
+
detail: { revocation_epoch: revoked.revocation_epoch, reason },
|
|
1345
|
+
createdAt: now,
|
|
1346
|
+
});
|
|
1347
|
+
return revoked;
|
|
1348
|
+
});
|
|
1349
|
+
}
|
|
1350
|
+
getReview(merchantId, reviewId) {
|
|
1351
|
+
this.ensureAvailable();
|
|
1352
|
+
return this.repository.readReview(requireOpaque(merchantId, "merchant_id"), requireOpaque(reviewId, "review_id"));
|
|
1353
|
+
}
|
|
1354
|
+
listReviews(merchantId, limit = 100) {
|
|
1355
|
+
this.ensureAvailable();
|
|
1356
|
+
const merchant = requireOpaque(merchantId, "merchant_id");
|
|
1357
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200) {
|
|
1358
|
+
throw new LearningError("validation", "limit_invalid", "limit 必须在 1..200");
|
|
1359
|
+
}
|
|
1360
|
+
return this.repository.listReviews(merchant, limit);
|
|
1361
|
+
}
|
|
1362
|
+
getRelease(merchantId, releaseId) {
|
|
1363
|
+
this.ensureAvailable();
|
|
1364
|
+
return this.repository.readRelease(requireOpaque(merchantId, "merchant_id"), requireOpaque(releaseId, "release_id"));
|
|
1365
|
+
}
|
|
1366
|
+
listReleases(merchantId, skillKey, limit = 100) {
|
|
1367
|
+
this.ensureAvailable();
|
|
1368
|
+
const merchant = requireOpaque(merchantId, "merchant_id");
|
|
1369
|
+
const key = skillKey === undefined ? undefined : requireOpaque(skillKey, "skill_key");
|
|
1370
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200) {
|
|
1371
|
+
throw new LearningError("validation", "limit_invalid", "limit 必须在 1..200");
|
|
1372
|
+
}
|
|
1373
|
+
return this.repository.listReleases(merchant, key, limit);
|
|
1374
|
+
}
|
|
1375
|
+
getActiveRelease(merchantId, skillKey) {
|
|
1376
|
+
this.ensureAvailable();
|
|
1377
|
+
const merchant = requireOpaque(merchantId, "merchant_id");
|
|
1378
|
+
const key = requireOpaque(skillKey, "skill_key");
|
|
1379
|
+
const pointer = this.repository.readPointer(merchant, key);
|
|
1380
|
+
if (pointer === undefined || pointer.release_id === null)
|
|
1381
|
+
return undefined;
|
|
1382
|
+
return this.repository.readRelease(merchant, pointer.release_id);
|
|
1383
|
+
}
|
|
1384
|
+
getCorrection(merchantId, correctionId) {
|
|
1385
|
+
this.ensureAvailable();
|
|
1386
|
+
return this.repository.readCorrection(requireOpaque(merchantId, "merchant_id"), requireOpaque(correctionId, "correction_id"));
|
|
1387
|
+
}
|
|
1388
|
+
listCorrections(merchantId, limit = 100) {
|
|
1389
|
+
this.ensureAvailable();
|
|
1390
|
+
const merchant = requireOpaque(merchantId, "merchant_id");
|
|
1391
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200) {
|
|
1392
|
+
throw new LearningError("validation", "limit_invalid", "limit 必须在 1..200");
|
|
1393
|
+
}
|
|
1394
|
+
return this.repository.listCorrections(merchant, limit);
|
|
1395
|
+
}
|
|
1396
|
+
getCase(merchantId, caseId) {
|
|
1397
|
+
this.ensureAvailable();
|
|
1398
|
+
return this.repository.readCase(requireOpaque(merchantId, "merchant_id"), requireOpaque(caseId, "case_id"));
|
|
1399
|
+
}
|
|
1400
|
+
/** 候选文本预检:与纠正相同的客户数据/底价/凭据拒绝规则。 */
|
|
1401
|
+
validateCandidateText(merchantId, actorId, operation, input) {
|
|
1402
|
+
const trigger = requireBoundedText(input.trigger, "trigger", MAX_TRIGGER_CHARS);
|
|
1403
|
+
const reason = requireBoundedText(input.reason, "reason", MAX_REASON_CHARS);
|
|
1404
|
+
const exclusions = normalizeStringList(input.exclusions, "exclusions", MAX_EXCLUSIONS, MAX_EXCLUSION_CHARS);
|
|
1405
|
+
const sensitive = detectCorrectionSensitiveContent([trigger, reason, ...exclusions].join("\n"));
|
|
1406
|
+
if (sensitive !== undefined) {
|
|
1407
|
+
this.repository.transaction(() => {
|
|
1408
|
+
this.repository.recordRejection({
|
|
1409
|
+
merchantId,
|
|
1410
|
+
actorId,
|
|
1411
|
+
operation,
|
|
1412
|
+
reasonCode: `precheck:${sensitive}`,
|
|
1413
|
+
subjectDigest: contentDigest({
|
|
1414
|
+
operation,
|
|
1415
|
+
reason_code: sensitive,
|
|
1416
|
+
actor_id: actorId,
|
|
1417
|
+
text_length: trigger.length + reason.length,
|
|
1418
|
+
}),
|
|
1419
|
+
createdAt: this.now(),
|
|
1420
|
+
});
|
|
1421
|
+
});
|
|
1422
|
+
throw new LearningError("sensitive_content", `precheck:${sensitive}`, "候选内容包含客户标识、联系方式、凭据或价格底线;请改为抽象流程描述后重试");
|
|
1423
|
+
}
|
|
1424
|
+
return { trigger, reason, exclusions };
|
|
1425
|
+
}
|
|
1426
|
+
/** 校验案例状态并编译冻结产物;任何内容变化都产生不同 content_digest。 */
|
|
1427
|
+
buildCandidateContent(merchantId, input) {
|
|
1428
|
+
for (const caseId of input.caseIds) {
|
|
1429
|
+
const record = this.repository.readCase(merchantId, caseId);
|
|
1430
|
+
if (record === undefined) {
|
|
1431
|
+
throw new LearningError("not_found", "case_not_found", "案例不存在或不可见");
|
|
1432
|
+
}
|
|
1433
|
+
if (record.status !== "ACTIVE") {
|
|
1434
|
+
throw new LearningError("version_conflict", "case_stale", `案例 ${caseId} 已失效;请先重新提升纠正形成新案例`);
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
let compiled;
|
|
1438
|
+
try {
|
|
1439
|
+
compiled = compileReceptionSkillArtifact({
|
|
1440
|
+
skill_key: input.skillKey,
|
|
1441
|
+
steps: input.steps,
|
|
1442
|
+
...(input.requiredTools !== undefined ? { required_tools: input.requiredTools } : {}),
|
|
1443
|
+
});
|
|
1444
|
+
}
|
|
1445
|
+
catch (err) {
|
|
1446
|
+
if (err instanceof SkillContractError) {
|
|
1447
|
+
throw new LearningError(err.code === "unsupported_capability" ? "unsupported_capability" : "validation", err.reason, err.message);
|
|
1448
|
+
}
|
|
1449
|
+
throw err;
|
|
1450
|
+
}
|
|
1451
|
+
const digest = contentDigest({
|
|
1452
|
+
kind: "learning.candidate",
|
|
1453
|
+
skill_key: input.skillKey,
|
|
1454
|
+
base_release_id: input.baseReleaseId ?? null,
|
|
1455
|
+
case_ids: input.caseIds,
|
|
1456
|
+
trigger: input.trigger,
|
|
1457
|
+
proposed_steps: compiled.artifact.steps,
|
|
1458
|
+
exclusions: input.exclusions,
|
|
1459
|
+
reason: input.reason,
|
|
1460
|
+
required_tools: compiled.artifact.required_tools,
|
|
1461
|
+
question_schema_version: compiled.artifact.question_schema_version,
|
|
1462
|
+
tool_contract_digest: compiled.tool_contract_digest,
|
|
1463
|
+
});
|
|
1464
|
+
return { compiled, contentDigest: digest };
|
|
1465
|
+
}
|
|
1466
|
+
/** 命令幂等:事务内复查(并发同键只执行一次);同键异摘要冲突。 */
|
|
1467
|
+
withCommand(merchantId, actorId, operation, request, command, work) {
|
|
1468
|
+
const commandId = command.command_id === undefined
|
|
1469
|
+
? undefined
|
|
1470
|
+
: requireOpaque(command.command_id, "command_id");
|
|
1471
|
+
const digest = contentDigest({ operation, request });
|
|
1472
|
+
return this.repository.transaction(() => {
|
|
1473
|
+
if (commandId !== undefined) {
|
|
1474
|
+
const existing = this.repository.readIdempotent(merchantId, actorId, operation, commandId);
|
|
1475
|
+
if (existing !== undefined) {
|
|
1476
|
+
if (existing.requestDigest !== digest) {
|
|
1477
|
+
throw new LearningError("idempotency_conflict", "command_replay_conflict", "同一 command_id 已用于不同内容");
|
|
1478
|
+
}
|
|
1479
|
+
return JSON.parse(existing.result);
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
const result = work();
|
|
1483
|
+
if (commandId !== undefined) {
|
|
1484
|
+
this.repository.saveIdempotent({
|
|
1485
|
+
merchantId,
|
|
1486
|
+
actorId,
|
|
1487
|
+
operation,
|
|
1488
|
+
commandId,
|
|
1489
|
+
requestDigest: digest,
|
|
1490
|
+
result,
|
|
1491
|
+
createdAt: this.now(),
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
return result;
|
|
1495
|
+
});
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
//# sourceMappingURL=service.js.map
|