@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,922 @@
|
|
|
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
|
+
* TOP3 经营任务(设计 v1.1 §13–§16 / M4)。
|
|
18
|
+
*
|
|
19
|
+
* - EventInbox:同 ID 同摘要幂等、异摘要冲突;旧版本不覆盖新状态。
|
|
20
|
+
* - prepareRule 双模式只返回候选(requires_confirmation=true);activate 才
|
|
21
|
+
* 创建不可变规则版本;暂停递增 enable_epoch 并取消未提交任务。
|
|
22
|
+
* - 调度:next_due_at 是唯一到期依据;内存 timer 只唤醒。评估 no_change
|
|
23
|
+
* 不调用模型;eligible 在同一事务内写评估 + 创建任务;预算不足保持
|
|
24
|
+
* PENDING/记录 budget_exhausted。
|
|
25
|
+
* - 执行:CAS 领取(READY→RUNNING + fencing/attempt),commitInternalResult
|
|
26
|
+
* 在同一事务写唯一产物、结束 attempt、更新任务、保存 receipt;旧 worker
|
|
27
|
+
* 或失效快照不能提交。
|
|
28
|
+
*/
|
|
29
|
+
import { randomUUID } from "node:crypto";
|
|
30
|
+
import { contentDigest } from "../../negotiation/jcs.js";
|
|
31
|
+
import { BackgroundBudgetStore, BackgroundBudgetError } from "../budget/background-budget.js";
|
|
32
|
+
import { inImmediateTransaction } from "../storage/transaction.js";
|
|
33
|
+
export class OperationsJobsError extends Error {
|
|
34
|
+
code;
|
|
35
|
+
reason;
|
|
36
|
+
constructor(code, reason, message) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = "OperationsJobsError";
|
|
39
|
+
this.code = code;
|
|
40
|
+
this.reason = reason;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export const RULE_TEMPLATES = [
|
|
44
|
+
"unfinished_inquiry_digest",
|
|
45
|
+
"missing_info_draft",
|
|
46
|
+
"quote_expiry_review",
|
|
47
|
+
"data_availability_check",
|
|
48
|
+
];
|
|
49
|
+
export const RULE_ACTION_TYPES = [
|
|
50
|
+
"internal_summary",
|
|
51
|
+
"internal_draft",
|
|
52
|
+
"merchant_todo",
|
|
53
|
+
];
|
|
54
|
+
/** 来源版本只接受纯数字或 vN;其他形式按“无权威版本”处理(不回滚事实)。 */
|
|
55
|
+
export function parseSourceVersionRank(value) {
|
|
56
|
+
if (value === undefined)
|
|
57
|
+
return undefined;
|
|
58
|
+
const match = /^v?(\d+)$/.exec(value.trim());
|
|
59
|
+
if (match === null)
|
|
60
|
+
return undefined;
|
|
61
|
+
const rank = Number(match[1]);
|
|
62
|
+
return Number.isSafeInteger(rank) ? rank : undefined;
|
|
63
|
+
}
|
|
64
|
+
/** 评估优先级:日报摘要 > 草稿 > 待办(C16)。 */
|
|
65
|
+
const ACTION_PRIORITY = {
|
|
66
|
+
internal_summary: 0,
|
|
67
|
+
internal_draft: 1,
|
|
68
|
+
merchant_todo: 2,
|
|
69
|
+
};
|
|
70
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
71
|
+
/** C03:停机跨过的日报窗口数(只补最新窗口,不重复 occurrence)。 */
|
|
72
|
+
function dailyMissedWindows(nextDueAt, now) {
|
|
73
|
+
if (nextDueAt === null)
|
|
74
|
+
return 0;
|
|
75
|
+
const delta = Date.parse(now) - Date.parse(nextDueAt);
|
|
76
|
+
if (!Number.isFinite(delta) || delta < DAY_MS)
|
|
77
|
+
return 0;
|
|
78
|
+
return Math.floor(delta / DAY_MS);
|
|
79
|
+
}
|
|
80
|
+
const MAX_EVENT_DIGEST_CHARS = 128;
|
|
81
|
+
const DEFAULT_RUN_DEADLINE_MS = 30_000;
|
|
82
|
+
function text(value, field, max = 256) {
|
|
83
|
+
if (typeof value !== "string" || value.length === 0 || value.length > max) {
|
|
84
|
+
throw new OperationsJobsError("validation", `${field}_invalid`, `${field} 必须是 1..${max} 字符`);
|
|
85
|
+
}
|
|
86
|
+
// eslint-disable-next-line no-control-regex
|
|
87
|
+
if (/[\u0000-\u001f\u007f]/.test(value)) {
|
|
88
|
+
throw new OperationsJobsError("validation", `${field}_invalid`, `${field} 含控制字符`);
|
|
89
|
+
}
|
|
90
|
+
return value;
|
|
91
|
+
}
|
|
92
|
+
function nowUtc(now) {
|
|
93
|
+
const ms = Date.parse(now());
|
|
94
|
+
if (!Number.isFinite(ms)) {
|
|
95
|
+
throw new OperationsJobsError("validation", "now_invalid", "时钟输出必须是可解析的 RFC3339 时间");
|
|
96
|
+
}
|
|
97
|
+
return new Date(ms).toISOString();
|
|
98
|
+
}
|
|
99
|
+
function localParts(ms, timezone) {
|
|
100
|
+
const formatter = new Intl.DateTimeFormat("en-CA", {
|
|
101
|
+
timeZone: timezone,
|
|
102
|
+
year: "numeric",
|
|
103
|
+
month: "2-digit",
|
|
104
|
+
day: "2-digit",
|
|
105
|
+
});
|
|
106
|
+
const parts = formatter.formatToParts(new Date(ms));
|
|
107
|
+
const pick = (type) => Number(parts.find((part) => part.type === type)?.value);
|
|
108
|
+
return { year: pick("year"), month: pick("month"), day: pick("day") };
|
|
109
|
+
}
|
|
110
|
+
function zoneOffsetMs(ms, timezone) {
|
|
111
|
+
const formatter = new Intl.DateTimeFormat("en-CA", {
|
|
112
|
+
timeZone: timezone,
|
|
113
|
+
year: "numeric",
|
|
114
|
+
month: "2-digit",
|
|
115
|
+
day: "2-digit",
|
|
116
|
+
hour: "2-digit",
|
|
117
|
+
minute: "2-digit",
|
|
118
|
+
second: "2-digit",
|
|
119
|
+
hourCycle: "h23",
|
|
120
|
+
});
|
|
121
|
+
const parts = formatter.formatToParts(new Date(ms));
|
|
122
|
+
const pick = (type) => Number(parts.find((part) => part.type === type)?.value);
|
|
123
|
+
const asUtc = Date.UTC(pick("year"), pick("month") - 1, pick("day"), pick("hour"), pick("minute"), pick("second"));
|
|
124
|
+
return asUtc - ms;
|
|
125
|
+
}
|
|
126
|
+
/** 下一次本地 daily 时间(60 秒粒度);夏令时/时区变更靠重算 offset 收敛。 */
|
|
127
|
+
export function nextDailyDueAt(input) {
|
|
128
|
+
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(input.local_time);
|
|
129
|
+
if (match === null) {
|
|
130
|
+
throw new OperationsJobsError("validation", "local_time_invalid", "local_time 必须是 HH:MM");
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
new Intl.DateTimeFormat("en-CA", { timeZone: input.timezone }).format(new Date());
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
throw new OperationsJobsError("validation", "timezone_invalid", "无法识别的时区");
|
|
137
|
+
}
|
|
138
|
+
const nowMs = Date.parse(input.now);
|
|
139
|
+
if (!Number.isFinite(nowMs)) {
|
|
140
|
+
throw new OperationsJobsError("validation", "now_invalid", "now 必须是 RFC3339");
|
|
141
|
+
}
|
|
142
|
+
const hour = Number(match[1]);
|
|
143
|
+
const minute = Number(match[2]);
|
|
144
|
+
for (let dayOffset = 0; dayOffset <= 2; dayOffset++) {
|
|
145
|
+
const local = localParts(nowMs + dayOffset * 24 * 60 * 60 * 1000, input.timezone);
|
|
146
|
+
let guess = Date.UTC(local.year, local.month - 1, local.day, hour, minute, 0);
|
|
147
|
+
// 两次校正覆盖 offset 在目标时刻与 guess 时刻不同的边界。
|
|
148
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
149
|
+
const offset = zoneOffsetMs(guess, input.timezone);
|
|
150
|
+
guess = Date.UTC(local.year, local.month - 1, local.day, hour, minute, 0) - offset;
|
|
151
|
+
}
|
|
152
|
+
if (guess > nowMs)
|
|
153
|
+
return new Date(guess).toISOString();
|
|
154
|
+
}
|
|
155
|
+
throw new OperationsJobsError("validation", "next_due_unresolved", "无法计算下一次到期时间");
|
|
156
|
+
}
|
|
157
|
+
export class OperationsJobsService {
|
|
158
|
+
db;
|
|
159
|
+
now;
|
|
160
|
+
budgetStore;
|
|
161
|
+
constructor(options) {
|
|
162
|
+
if (options.budgetStore !== undefined && !options.budgetStore.usesDatabase(options.db)) {
|
|
163
|
+
throw new OperationsJobsError("validation", "budget_database_mismatch", "预算与任务必须使用同一数据库连接");
|
|
164
|
+
}
|
|
165
|
+
this.db = options.db;
|
|
166
|
+
this.now = options.now;
|
|
167
|
+
this.budgetStore = options.budgetStore;
|
|
168
|
+
}
|
|
169
|
+
ingestTrustedEvent(input) {
|
|
170
|
+
const merchantId = text(input.merchant_id, "merchant_id");
|
|
171
|
+
const sourceScope = text(input.source_scope, "source_scope", 64);
|
|
172
|
+
const externalId = text(input.external_event_id, "external_event_id", 128);
|
|
173
|
+
const digest = text(input.payload_digest, "payload_digest", MAX_EVENT_DIGEST_CHARS);
|
|
174
|
+
const entityRef = text(input.entity_ref, "entity_ref");
|
|
175
|
+
const occurredAt = text(input.occurred_at, "occurred_at", 64);
|
|
176
|
+
const receivedAt = input.received_at ?? nowUtc(this.now);
|
|
177
|
+
return inImmediateTransaction(this.db, () => {
|
|
178
|
+
const existing = this.db
|
|
179
|
+
.prepare(`SELECT inbox_id, payload_digest, source_version FROM event_inbox
|
|
180
|
+
WHERE merchant_id = ? AND source_scope = ? AND external_event_id = ?`)
|
|
181
|
+
.get(merchantId, sourceScope, externalId);
|
|
182
|
+
if (existing !== undefined) {
|
|
183
|
+
if (existing.payload_digest !== digest) {
|
|
184
|
+
throw new OperationsJobsError("conflict", "event_payload_conflict", "同一来源事件 ID 的摘要不同;保留原记录等待核验");
|
|
185
|
+
}
|
|
186
|
+
return { status: "duplicate", inbox_id: existing.inbox_id };
|
|
187
|
+
}
|
|
188
|
+
const inboxId = `evt_${randomUUID()}`;
|
|
189
|
+
const rank = parseSourceVersionRank(input.source_version);
|
|
190
|
+
const current = rank === undefined
|
|
191
|
+
? undefined
|
|
192
|
+
: this.db
|
|
193
|
+
.prepare(`SELECT version_rank FROM source_entity_versions
|
|
194
|
+
WHERE merchant_id = ? AND source_scope = ? AND entity_ref = ?`)
|
|
195
|
+
.get(merchantId, sourceScope, entityRef);
|
|
196
|
+
// C02:v8 之后收到 v7 不回滚当前事实;记录为 superseded 供审计,
|
|
197
|
+
// 后续评估只能给出缺证待办(data_incomplete),不能当作新事实。
|
|
198
|
+
const superseded = rank !== undefined && current !== undefined && current.version_rank > rank;
|
|
199
|
+
this.db
|
|
200
|
+
.prepare(`INSERT INTO event_inbox
|
|
201
|
+
(inbox_id, merchant_id, source_scope, external_event_id, payload_digest,
|
|
202
|
+
entity_ref, source_version, source_version_rank, superseded,
|
|
203
|
+
occurred_at, received_at, evidence_ref, created_at)
|
|
204
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
205
|
+
.run(inboxId, merchantId, sourceScope, externalId, digest, entityRef, input.source_version ?? null, rank ?? null, superseded ? 1 : 0, occurredAt, receivedAt, input.evidence_ref ?? null, receivedAt);
|
|
206
|
+
if (rank !== undefined && !superseded) {
|
|
207
|
+
this.db
|
|
208
|
+
.prepare(`INSERT INTO source_entity_versions
|
|
209
|
+
(merchant_id, source_scope, entity_ref, version_rank, inbox_id, updated_at)
|
|
210
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
211
|
+
ON CONFLICT(merchant_id, source_scope, entity_ref) DO UPDATE SET
|
|
212
|
+
version_rank = excluded.version_rank,
|
|
213
|
+
inbox_id = excluded.inbox_id,
|
|
214
|
+
updated_at = excluded.updated_at
|
|
215
|
+
WHERE excluded.version_rank > source_entity_versions.version_rank`)
|
|
216
|
+
.run(merchantId, sourceScope, entityRef, rank, inboxId, receivedAt);
|
|
217
|
+
}
|
|
218
|
+
return { status: superseded ? "superseded" : "accepted", inbox_id: inboxId };
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
prepareRule(input) {
|
|
222
|
+
const merchantId = text(input.merchant_id, "merchant_id");
|
|
223
|
+
if (!RULE_TEMPLATES.includes(input.template)) {
|
|
224
|
+
throw new OperationsJobsError("validation", "template_invalid", "未知规则模板");
|
|
225
|
+
}
|
|
226
|
+
if (!RULE_ACTION_TYPES.includes(input.action_type)) {
|
|
227
|
+
throw new OperationsJobsError("validation", "action_type_invalid", "未知动作类型");
|
|
228
|
+
}
|
|
229
|
+
if (input.mode !== "template" && input.mode !== "goal") {
|
|
230
|
+
throw new OperationsJobsError("validation", "mode_invalid", "mode 只能是 template/goal");
|
|
231
|
+
}
|
|
232
|
+
if (input.trigger_spec.kind !== "daily_local") {
|
|
233
|
+
throw new OperationsJobsError("validation", "trigger_invalid", "P0 只支持 daily_local");
|
|
234
|
+
}
|
|
235
|
+
nextDailyDueAt({
|
|
236
|
+
now: nowUtc(this.now),
|
|
237
|
+
local_time: input.trigger_spec.local_time,
|
|
238
|
+
timezone: input.trigger_spec.timezone,
|
|
239
|
+
});
|
|
240
|
+
if (input.scope.window !== "previous_local_day" && input.scope.window !== "last_7_days") {
|
|
241
|
+
throw new OperationsJobsError("validation", "scope_invalid", "未知窗口");
|
|
242
|
+
}
|
|
243
|
+
if (input.predicate_spec.kind !== "fixed_template") {
|
|
244
|
+
throw new OperationsJobsError("validation", "predicate_invalid", "只允许固定模板 predicate");
|
|
245
|
+
}
|
|
246
|
+
if (!Number.isSafeInteger(input.budget.max_runs_per_day) ||
|
|
247
|
+
input.budget.max_runs_per_day < 1 ||
|
|
248
|
+
input.budget.max_runs_per_day > 20) {
|
|
249
|
+
throw new OperationsJobsError("validation", "budget_invalid", "max_runs_per_day 必须在 1..20");
|
|
250
|
+
}
|
|
251
|
+
const goalText = input.goal_text === undefined ? null : text(input.goal_text, "goal_text", 500);
|
|
252
|
+
const stamp = nowUtc(this.now);
|
|
253
|
+
const contentHash = contentDigest({
|
|
254
|
+
kind: "automation.rule",
|
|
255
|
+
mode: input.mode,
|
|
256
|
+
template: input.template,
|
|
257
|
+
trigger: input.trigger_spec,
|
|
258
|
+
scope: input.scope,
|
|
259
|
+
predicate: input.predicate_spec,
|
|
260
|
+
action_type: input.action_type,
|
|
261
|
+
budget: input.budget,
|
|
262
|
+
goal_text: goalText,
|
|
263
|
+
});
|
|
264
|
+
const candidateRef = `rulec_${randomUUID()}`;
|
|
265
|
+
this.db
|
|
266
|
+
.prepare(`INSERT INTO automation_rule_candidates
|
|
267
|
+
(candidate_ref, merchant_id, mode, template, trigger_spec_json, timezone,
|
|
268
|
+
scope_json, predicate_spec_json, action_type, budget_json, goal_text,
|
|
269
|
+
content_hash, requires_confirmation, consumed_at, created_at)
|
|
270
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NULL, ?)`)
|
|
271
|
+
.run(candidateRef, merchantId, input.mode, input.template, JSON.stringify(input.trigger_spec), input.trigger_spec.timezone, JSON.stringify(input.scope), JSON.stringify(input.predicate_spec), input.action_type, JSON.stringify(input.budget), goalText, contentHash, stamp);
|
|
272
|
+
return {
|
|
273
|
+
candidate_ref: candidateRef,
|
|
274
|
+
merchant_id: merchantId,
|
|
275
|
+
mode: input.mode,
|
|
276
|
+
template: input.template,
|
|
277
|
+
trigger_spec: input.trigger_spec,
|
|
278
|
+
timezone: input.trigger_spec.timezone,
|
|
279
|
+
scope: input.scope,
|
|
280
|
+
predicate_spec: input.predicate_spec,
|
|
281
|
+
action_type: input.action_type,
|
|
282
|
+
budget: input.budget,
|
|
283
|
+
goal_text: goalText,
|
|
284
|
+
content_hash: contentHash,
|
|
285
|
+
requires_confirmation: true,
|
|
286
|
+
created_at: stamp,
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
activateRule(input) {
|
|
290
|
+
const merchantId = text(input.merchant_id, "merchant_id");
|
|
291
|
+
const candidateRef = text(input.candidate_ref, "candidate_ref");
|
|
292
|
+
return inImmediateTransaction(this.db, () => {
|
|
293
|
+
const candidate = this.db
|
|
294
|
+
.prepare("SELECT * FROM automation_rule_candidates WHERE merchant_id = ? AND candidate_ref = ?")
|
|
295
|
+
.get(merchantId, candidateRef);
|
|
296
|
+
if (candidate === undefined) {
|
|
297
|
+
throw new OperationsJobsError("not_found", "candidate_not_found", "规则候选不存在或不可见");
|
|
298
|
+
}
|
|
299
|
+
if (candidate.consumed_at !== null) {
|
|
300
|
+
throw new OperationsJobsError("conflict", "candidate_consumed", "规则候选已启用");
|
|
301
|
+
}
|
|
302
|
+
const stamp = nowUtc(this.now);
|
|
303
|
+
const trigger = JSON.parse(candidate.trigger_spec_json);
|
|
304
|
+
const nextDue = nextDailyDueAt({
|
|
305
|
+
now: stamp,
|
|
306
|
+
local_time: trigger.local_time,
|
|
307
|
+
timezone: trigger.timezone,
|
|
308
|
+
});
|
|
309
|
+
const rule = {
|
|
310
|
+
rule_id: `rule_${randomUUID()}`,
|
|
311
|
+
merchant_id: merchantId,
|
|
312
|
+
version: 1,
|
|
313
|
+
template: candidate.template,
|
|
314
|
+
trigger_spec: trigger,
|
|
315
|
+
timezone: candidate.timezone,
|
|
316
|
+
scope: JSON.parse(candidate.scope_json),
|
|
317
|
+
predicate_spec: JSON.parse(candidate.predicate_spec_json),
|
|
318
|
+
action_type: candidate.action_type,
|
|
319
|
+
budget: JSON.parse(candidate.budget_json),
|
|
320
|
+
authorization_ref: null,
|
|
321
|
+
effective_at: stamp,
|
|
322
|
+
expires_at: new Date(Date.parse(stamp) + 365 * 24 * 60 * 60 * 1000).toISOString(),
|
|
323
|
+
content_hash: candidate.content_hash,
|
|
324
|
+
state: "ACTIVE",
|
|
325
|
+
enable_epoch: 1,
|
|
326
|
+
next_due_at: nextDue,
|
|
327
|
+
missed_count: 0,
|
|
328
|
+
created_at: stamp,
|
|
329
|
+
updated_at: stamp,
|
|
330
|
+
};
|
|
331
|
+
this.db
|
|
332
|
+
.prepare(`INSERT INTO automation_rules
|
|
333
|
+
(rule_id, merchant_id, version, template, trigger_spec_json, timezone,
|
|
334
|
+
scope_json, predicate_spec_json, action_type, budget_json, authorization_ref,
|
|
335
|
+
effective_at, expires_at, content_hash, state, enable_epoch, next_due_at,
|
|
336
|
+
missed_count, created_at, updated_at)
|
|
337
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, 'ACTIVE', 1, ?, 0, ?, ?)`)
|
|
338
|
+
.run(rule.rule_id, merchantId, rule.version, rule.template, JSON.stringify(rule.trigger_spec), rule.timezone, JSON.stringify(rule.scope), JSON.stringify(rule.predicate_spec), rule.action_type, JSON.stringify(rule.budget), rule.effective_at, rule.expires_at, rule.content_hash, rule.next_due_at, stamp, stamp);
|
|
339
|
+
this.db
|
|
340
|
+
.prepare("UPDATE automation_rule_candidates SET consumed_at = ? WHERE merchant_id = ? AND candidate_ref = ?")
|
|
341
|
+
.run(stamp, merchantId, candidateRef);
|
|
342
|
+
return rule;
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
pauseRule(input) {
|
|
346
|
+
const merchantId = text(input.merchant_id, "merchant_id");
|
|
347
|
+
const ruleId = text(input.rule_id, "rule_id");
|
|
348
|
+
return inImmediateTransaction(this.db, () => {
|
|
349
|
+
const stamp = nowUtc(this.now);
|
|
350
|
+
const rule = this.requireRule(merchantId, ruleId);
|
|
351
|
+
if (rule.version !== input.expected_version) {
|
|
352
|
+
throw new OperationsJobsError("version_conflict", "rule_version_mismatch", "规则版本已变化");
|
|
353
|
+
}
|
|
354
|
+
if (rule.state !== "PAUSED") {
|
|
355
|
+
this.db
|
|
356
|
+
.prepare(`UPDATE automation_rules SET state = 'PAUSED', enable_epoch = enable_epoch + 1,
|
|
357
|
+
next_due_at = NULL, updated_at = ?
|
|
358
|
+
WHERE merchant_id = ? AND rule_id = ?`)
|
|
359
|
+
.run(stamp, merchantId, ruleId);
|
|
360
|
+
const cancelled = this.db.prepare(`SELECT * FROM followup_tasks WHERE merchant_id = ? AND rule_id = ?
|
|
361
|
+
AND status IN ('PENDING','READY')`).all(merchantId, ruleId);
|
|
362
|
+
for (const task of cancelled)
|
|
363
|
+
this.closeReservation(task);
|
|
364
|
+
this.db
|
|
365
|
+
.prepare(`UPDATE followup_tasks SET status = 'CANCELLED', cancel_epoch = cancel_epoch + 1,
|
|
366
|
+
revision = revision + 1, lease_owner = NULL, lease_expires_at = NULL,
|
|
367
|
+
updated_at = ?
|
|
368
|
+
WHERE merchant_id = ? AND rule_id = ? AND status IN ('PENDING','READY')`)
|
|
369
|
+
.run(stamp, merchantId, ruleId);
|
|
370
|
+
}
|
|
371
|
+
return this.requireRule(merchantId, ruleId);
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
listRules(merchantId) {
|
|
375
|
+
return this.db
|
|
376
|
+
.prepare("SELECT * FROM automation_rules WHERE merchant_id = ? ORDER BY created_at DESC")
|
|
377
|
+
.all(text(merchantId, "merchant_id")).map(toRule);
|
|
378
|
+
}
|
|
379
|
+
getRule(merchantId, ruleId) {
|
|
380
|
+
const row = this.db
|
|
381
|
+
.prepare("SELECT * FROM automation_rules WHERE merchant_id = ? AND rule_id = ?")
|
|
382
|
+
.get(text(merchantId, "merchant_id"), text(ruleId, "rule_id"));
|
|
383
|
+
return row === undefined ? undefined : toRule(row);
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* 评估到期规则。prefilter 缺失时记为 data_incomplete(不伪造 no_change)。
|
|
387
|
+
* eligible 在同事务写评估 + 创建 READY 任务;预算不足只记 blocked。
|
|
388
|
+
*/
|
|
389
|
+
evaluateDue(input) {
|
|
390
|
+
const merchantId = text(input.merchant_id, "merchant_id");
|
|
391
|
+
const stamp = input.now ?? nowUtc(this.now);
|
|
392
|
+
const due = this.db
|
|
393
|
+
.prepare(`SELECT * FROM automation_rules
|
|
394
|
+
WHERE merchant_id = ? AND state = 'ACTIVE' AND next_due_at IS NOT NULL
|
|
395
|
+
AND next_due_at <= ?`)
|
|
396
|
+
.all(merchantId, stamp);
|
|
397
|
+
// C16:额度有限时先处理优先级高的动作(日报摘要 > 草稿 > 待办)。
|
|
398
|
+
due.sort((left, right) => {
|
|
399
|
+
const byAction = (ACTION_PRIORITY[left.action_type] ?? 9) - (ACTION_PRIORITY[right.action_type] ?? 9);
|
|
400
|
+
if (byAction !== 0)
|
|
401
|
+
return byAction;
|
|
402
|
+
return String(left.next_due_at).localeCompare(String(right.next_due_at));
|
|
403
|
+
});
|
|
404
|
+
const evaluations = [];
|
|
405
|
+
for (const row of due) {
|
|
406
|
+
const rule = toRule(row);
|
|
407
|
+
const missedWindows = dailyMissedWindows(rule.next_due_at, stamp);
|
|
408
|
+
const triggerKey = `${rule.rule_id}:${rule.version}:${rule.next_due_at}`;
|
|
409
|
+
const existing = this.db
|
|
410
|
+
.prepare(`SELECT * FROM rule_evaluations
|
|
411
|
+
WHERE merchant_id = ? AND rule_id = ? AND rule_version = ? AND trigger_key = ?`)
|
|
412
|
+
.get(merchantId, rule.rule_id, rule.version, triggerKey);
|
|
413
|
+
if (existing !== undefined) {
|
|
414
|
+
this.advanceRule(rule, stamp);
|
|
415
|
+
evaluations.push(toEvaluation(existing));
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
const evaluated = input.prefilter === undefined
|
|
419
|
+
? {
|
|
420
|
+
result: "data_incomplete",
|
|
421
|
+
reason_code: "prefilter_unavailable",
|
|
422
|
+
detail: { missing: "projection" },
|
|
423
|
+
}
|
|
424
|
+
: input.prefilter(rule);
|
|
425
|
+
const evaluation = inImmediateTransaction(this.db, () => {
|
|
426
|
+
const evaluationId = `reval_${randomUUID()}`;
|
|
427
|
+
const detail = {
|
|
428
|
+
...(evaluated.detail ?? {}),
|
|
429
|
+
content_hash: rule.content_hash,
|
|
430
|
+
next_due_at: rule.next_due_at,
|
|
431
|
+
...(missedWindows > 0 ? { missed_windows: missedWindows } : {}),
|
|
432
|
+
};
|
|
433
|
+
let finalResult = evaluated.result;
|
|
434
|
+
let finalReason = evaluated.reason_code ?? null;
|
|
435
|
+
if (evaluated.result === "eligible" || evaluated.result === "data_incomplete") {
|
|
436
|
+
try {
|
|
437
|
+
this.enqueueEligibleTask(rule, triggerKey, detail, stamp);
|
|
438
|
+
}
|
|
439
|
+
catch (err) {
|
|
440
|
+
if (err instanceof OperationsJobsError && err.code === "budget_exhausted") {
|
|
441
|
+
// C16:额度不足不丢事件;保留 PENDING 任务等待配额,评估标记
|
|
442
|
+
// blocked + budget_exhausted,工作台可展示原因。
|
|
443
|
+
finalResult = "blocked";
|
|
444
|
+
finalReason = err.reason;
|
|
445
|
+
this.enqueueBudgetWaitingTask(rule, triggerKey, detail, stamp, err.reason);
|
|
446
|
+
}
|
|
447
|
+
else {
|
|
448
|
+
throw err;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
this.db
|
|
453
|
+
.prepare(`INSERT INTO rule_evaluations
|
|
454
|
+
(evaluation_id, merchant_id, rule_id, rule_version, trigger_key, result,
|
|
455
|
+
reason_code, window_start, window_end, detail_json, evaluated_at)
|
|
456
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
457
|
+
.run(evaluationId, merchantId, rule.rule_id, rule.version, triggerKey, finalResult, finalReason, evaluated.window_start ?? null, evaluated.window_end ?? null, JSON.stringify(detail), stamp);
|
|
458
|
+
this.advanceRule(rule, stamp);
|
|
459
|
+
return toEvaluation({
|
|
460
|
+
evaluation_id: evaluationId,
|
|
461
|
+
merchant_id: merchantId,
|
|
462
|
+
rule_id: rule.rule_id,
|
|
463
|
+
rule_version: rule.version,
|
|
464
|
+
trigger_key: triggerKey,
|
|
465
|
+
result: finalResult,
|
|
466
|
+
reason_code: finalReason,
|
|
467
|
+
window_start: evaluated.window_start ?? null,
|
|
468
|
+
window_end: evaluated.window_end ?? null,
|
|
469
|
+
detail_json: JSON.stringify(detail),
|
|
470
|
+
evaluated_at: stamp,
|
|
471
|
+
});
|
|
472
|
+
});
|
|
473
|
+
evaluations.push(evaluation);
|
|
474
|
+
}
|
|
475
|
+
return evaluations;
|
|
476
|
+
}
|
|
477
|
+
/** CAS 领取一个到期 READY 任务;创建 RUNNING attempt 并记录 worker/fencing。 */
|
|
478
|
+
claimDue(input) {
|
|
479
|
+
const merchantId = text(input.merchant_id, "merchant_id");
|
|
480
|
+
const workerId = text(input.worker_id, "worker_id");
|
|
481
|
+
const leaseMs = input.lease_ms ?? 60_000;
|
|
482
|
+
if (!Number.isSafeInteger(leaseMs) || leaseMs <= 0) {
|
|
483
|
+
throw new OperationsJobsError("validation", "lease_invalid", "lease_ms 必须是正整数");
|
|
484
|
+
}
|
|
485
|
+
return inImmediateTransaction(this.db, () => {
|
|
486
|
+
const stamp = input.now ?? nowUtc(this.now);
|
|
487
|
+
this.sweepRuleTasks(merchantId, stamp);
|
|
488
|
+
// 规则任务必须持有有效预留;普通 follow-up 保持原有行为。
|
|
489
|
+
// 退避后的 PENDING 到期即提升为 READY。
|
|
490
|
+
const reservationGate = this.budgetStore === undefined
|
|
491
|
+
? "operation_ref IS NOT NULL"
|
|
492
|
+
: `EXISTS (SELECT 1 FROM background_budget_reservations b
|
|
493
|
+
WHERE b.merchant_id = followup_tasks.merchant_id
|
|
494
|
+
AND b.run_id = followup_tasks.operation_ref AND b.state = 'RESERVED')`;
|
|
495
|
+
this.db
|
|
496
|
+
.prepare(`UPDATE followup_tasks SET status = 'READY', updated_at = ?
|
|
497
|
+
WHERE merchant_id = ? AND status = 'PENDING'
|
|
498
|
+
AND due_at IS NOT NULL AND due_at <= ?
|
|
499
|
+
AND (rule_id IS NULL OR ${reservationGate})`)
|
|
500
|
+
.run(stamp, merchantId, stamp);
|
|
501
|
+
let admittedWaiting = false;
|
|
502
|
+
let task = this.db
|
|
503
|
+
.prepare(`SELECT * FROM followup_tasks
|
|
504
|
+
WHERE merchant_id = ? AND status = 'READY'
|
|
505
|
+
AND (due_at IS NULL OR due_at <= ?)
|
|
506
|
+
AND (deadline_at IS NULL OR deadline_at > ?)
|
|
507
|
+
AND (rule_id IS NULL OR ${reservationGate})
|
|
508
|
+
ORDER BY due_at ASC, created_at ASC LIMIT 1`)
|
|
509
|
+
.get(merchantId, stamp, stamp);
|
|
510
|
+
if (task === undefined && this.budgetStore !== undefined) {
|
|
511
|
+
// 仅在没有可领取任务时尝试补额;已有预留不被等待任务抢占。
|
|
512
|
+
const waiting = this.db.prepare(`SELECT t.*, r.template FROM followup_tasks t
|
|
513
|
+
JOIN automation_rules r ON r.merchant_id = t.merchant_id AND r.rule_id = t.rule_id
|
|
514
|
+
WHERE t.merchant_id = ? AND t.status = 'PENDING' AND t.operation_ref IS NULL
|
|
515
|
+
AND t.due_at IS NOT NULL AND t.due_at <= ?
|
|
516
|
+
AND (t.deadline_at IS NULL OR t.deadline_at > ?)
|
|
517
|
+
AND t.stop_requested = 0 AND r.state = 'ACTIVE' AND r.version = t.rule_version
|
|
518
|
+
AND r.effective_at <= ? AND r.expires_at > ?`)
|
|
519
|
+
.all(merchantId, stamp, stamp, stamp, stamp);
|
|
520
|
+
waiting.sort((a, b) => (ACTION_PRIORITY[a.action_type] ?? 9) - (ACTION_PRIORITY[b.action_type] ?? 9) ||
|
|
521
|
+
String(a.due_at).localeCompare(String(b.due_at)) ||
|
|
522
|
+
a.created_at.localeCompare(b.created_at) || a.task_id.localeCompare(b.task_id));
|
|
523
|
+
const candidate = waiting[0];
|
|
524
|
+
if (candidate !== undefined) {
|
|
525
|
+
const runId = `run_${randomUUID()}`;
|
|
526
|
+
try {
|
|
527
|
+
this.budgetStore.reserveRun({ merchant_id: merchantId, run_id: runId,
|
|
528
|
+
day_key: stamp.slice(0, 10), template: candidate.template });
|
|
529
|
+
const admitted = this.db.prepare(`UPDATE followup_tasks
|
|
530
|
+
SET operation_ref = ?, status = 'READY', updated_at = ?
|
|
531
|
+
WHERE merchant_id = ? AND task_id = ? AND status = 'PENDING' AND operation_ref IS NULL`)
|
|
532
|
+
.run(runId, stamp, merchantId, candidate.task_id);
|
|
533
|
+
if (Number(admitted.changes) !== 1)
|
|
534
|
+
throw new Error("budget admission task changed");
|
|
535
|
+
task = this.db.prepare("SELECT * FROM followup_tasks WHERE merchant_id = ? AND task_id = ?")
|
|
536
|
+
.get(merchantId, candidate.task_id);
|
|
537
|
+
admittedWaiting = true;
|
|
538
|
+
}
|
|
539
|
+
catch (err) {
|
|
540
|
+
if (!(err instanceof BackgroundBudgetError &&
|
|
541
|
+
(err.code === "budget_exhausted" || err.code === "concurrency_limit")))
|
|
542
|
+
throw err;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
if (task === undefined)
|
|
547
|
+
return undefined;
|
|
548
|
+
const expires = new Date(Date.parse(stamp) + leaseMs).toISOString();
|
|
549
|
+
const updated = this.db
|
|
550
|
+
.prepare(`UPDATE followup_tasks
|
|
551
|
+
SET status = 'RUNNING', lease_owner = ?, lease_expires_at = ?,
|
|
552
|
+
fencing_token = fencing_token + 1, attempts = attempts + 1, updated_at = ?
|
|
553
|
+
WHERE merchant_id = ? AND task_id = ? AND status = 'READY'`)
|
|
554
|
+
.run(workerId, expires, stamp, merchantId, task.task_id);
|
|
555
|
+
if (Number(updated.changes) !== 1) {
|
|
556
|
+
if (admittedWaiting)
|
|
557
|
+
throw new Error("budget admission claim failed");
|
|
558
|
+
return undefined;
|
|
559
|
+
}
|
|
560
|
+
const fresh = this.db
|
|
561
|
+
.prepare("SELECT * FROM followup_tasks WHERE merchant_id = ? AND task_id = ?")
|
|
562
|
+
.get(merchantId, task.task_id);
|
|
563
|
+
this.db
|
|
564
|
+
.prepare(`INSERT INTO followup_attempts
|
|
565
|
+
(attempt_id, task_id, merchant_id, attempt_no, status, started_at, worker_id,
|
|
566
|
+
fencing, input_snapshot_digest)
|
|
567
|
+
VALUES (?, ?, ?, ?, 'RUNNING', ?, ?, ?, ?)`)
|
|
568
|
+
.run(`att_${randomUUID()}`, task.task_id, merchantId, fresh.attempts, stamp, workerId, fresh.fencing_token, fresh.snapshot_digest);
|
|
569
|
+
return toClaimed(fresh);
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* 原子提交内部结果:校验 owner/fencing/revision/cancel_epoch/租约/截止/规则;
|
|
574
|
+
* 唯一产物 + attempt 回执 + 任务 SUCCEEDED 同事务;重复提交返回原回执。
|
|
575
|
+
*/
|
|
576
|
+
commitInternalResult(input) {
|
|
577
|
+
const merchantId = text(input.merchant_id, "merchant_id");
|
|
578
|
+
const taskId = text(input.task_id, "task_id");
|
|
579
|
+
const workerId = text(input.worker_id, "worker_id");
|
|
580
|
+
const resultKind = text(input.result_kind, "result_kind", 64);
|
|
581
|
+
return inImmediateTransaction(this.db, () => {
|
|
582
|
+
const stamp = input.now ?? nowUtc(this.now);
|
|
583
|
+
const existing = this.db
|
|
584
|
+
.prepare(`SELECT receipt_ref, artifact_id, content_digest FROM operation_artifacts
|
|
585
|
+
WHERE merchant_id = ? AND task_id = ? AND result_kind = ?`)
|
|
586
|
+
.get(merchantId, taskId, resultKind);
|
|
587
|
+
const digest = contentDigest({ result_kind: resultKind, payload: input.payload });
|
|
588
|
+
if (existing !== undefined) {
|
|
589
|
+
if (existing.content_digest !== digest) {
|
|
590
|
+
throw new OperationsJobsError("idempotency_conflict", "artifact_digest_conflict", "同一结果类型已提交不同内容");
|
|
591
|
+
}
|
|
592
|
+
return {
|
|
593
|
+
receipt_ref: existing.receipt_ref,
|
|
594
|
+
artifact_id: existing.artifact_id,
|
|
595
|
+
task_id: taskId,
|
|
596
|
+
result_kind: resultKind,
|
|
597
|
+
content_digest: digest,
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
const task = this.db
|
|
601
|
+
.prepare("SELECT * FROM followup_tasks WHERE merchant_id = ? AND task_id = ?")
|
|
602
|
+
.get(merchantId, taskId);
|
|
603
|
+
if (task === undefined) {
|
|
604
|
+
throw new OperationsJobsError("not_found", "task_not_found", "任务不存在或不可见");
|
|
605
|
+
}
|
|
606
|
+
if (task.status !== "RUNNING" ||
|
|
607
|
+
task.lease_owner !== workerId ||
|
|
608
|
+
task.fencing_token !== input.fencing ||
|
|
609
|
+
task.revision !== input.expected_revision ||
|
|
610
|
+
task.cancel_epoch !== input.expected_cancel_epoch ||
|
|
611
|
+
task.stop_requested === 1) {
|
|
612
|
+
throw new OperationsJobsError("invalid_transition", "commit_guard_failed", "提交者、fencing、revision 或取消标记已变化");
|
|
613
|
+
}
|
|
614
|
+
if (task.lease_expires_at === null || task.lease_expires_at <= stamp) {
|
|
615
|
+
throw new OperationsJobsError("invalid_transition", "lease_expired", "租约已过期");
|
|
616
|
+
}
|
|
617
|
+
if (task.deadline_at !== null && task.deadline_at <= stamp) {
|
|
618
|
+
throw new OperationsJobsError("invalid_transition", "deadline_exceeded", "已超过运行截止");
|
|
619
|
+
}
|
|
620
|
+
if (task.rule_id !== null) {
|
|
621
|
+
const rule = this.db
|
|
622
|
+
.prepare("SELECT state, version FROM automation_rules WHERE merchant_id = ? AND rule_id = ?")
|
|
623
|
+
.get(merchantId, task.rule_id);
|
|
624
|
+
if (rule === undefined ||
|
|
625
|
+
rule.state !== "ACTIVE" ||
|
|
626
|
+
(task.rule_version !== null && rule.version !== task.rule_version)) {
|
|
627
|
+
throw new OperationsJobsError("invalid_transition", "rule_changed", "规则已暂停或版本变化");
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
const artifactId = `art_${randomUUID()}`;
|
|
631
|
+
const receiptRef = `rcpt_${randomUUID()}`;
|
|
632
|
+
this.db
|
|
633
|
+
.prepare(`INSERT INTO operation_artifacts
|
|
634
|
+
(artifact_id, merchant_id, task_id, result_kind, content_digest,
|
|
635
|
+
payload_json, receipt_ref, created_at)
|
|
636
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
637
|
+
.run(artifactId, merchantId, taskId, resultKind, digest, JSON.stringify(input.payload), receiptRef, stamp);
|
|
638
|
+
this.db
|
|
639
|
+
.prepare(`INSERT INTO operation_receipts
|
|
640
|
+
(receipt_ref, merchant_id, task_id, result_kind, content_digest, created_at)
|
|
641
|
+
VALUES (?, ?, ?, ?, ?, ?)`)
|
|
642
|
+
.run(receiptRef, merchantId, taskId, resultKind, digest, stamp);
|
|
643
|
+
this.db
|
|
644
|
+
.prepare(`UPDATE followup_tasks
|
|
645
|
+
SET status = 'SUCCEEDED', revision = revision + 1, lease_owner = NULL,
|
|
646
|
+
lease_expires_at = NULL, updated_at = ?
|
|
647
|
+
WHERE merchant_id = ? AND task_id = ?`)
|
|
648
|
+
.run(stamp, merchantId, taskId);
|
|
649
|
+
this.db
|
|
650
|
+
.prepare(`UPDATE followup_attempts
|
|
651
|
+
SET status = 'SUCCEEDED', ended_at = ?, receipt_json = ?, outcome_evidence_json = ?
|
|
652
|
+
WHERE merchant_id = ? AND task_id = ? AND attempt_no = ?`)
|
|
653
|
+
.run(stamp, JSON.stringify({ receipt_ref: receiptRef, artifact_id: artifactId }), JSON.stringify(input.payload.evidence ?? {}), merchantId, taskId, task.attempts);
|
|
654
|
+
if (task.operation_ref !== null && this.budgetStore !== undefined) {
|
|
655
|
+
try {
|
|
656
|
+
this.budgetStore.settleRun({
|
|
657
|
+
merchant_id: merchantId,
|
|
658
|
+
run_id: task.operation_ref,
|
|
659
|
+
input_tokens: input.usage?.input ?? 0,
|
|
660
|
+
output_tokens: input.usage?.output ?? 0,
|
|
661
|
+
usage_state: input.usage === undefined ? "unknown" : "known",
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
catch {
|
|
665
|
+
// 预算对账失败不回滚已提交的业务结果;运行记录保留可重试。
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
return {
|
|
669
|
+
receipt_ref: receiptRef,
|
|
670
|
+
artifact_id: artifactId,
|
|
671
|
+
task_id: taskId,
|
|
672
|
+
result_kind: resultKind,
|
|
673
|
+
content_digest: digest,
|
|
674
|
+
};
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
/** FAILED 且仍可重试:持久化退避后的 due_at,回到 PENDING。 */
|
|
678
|
+
retryTask(input) {
|
|
679
|
+
const merchantId = text(input.merchant_id, "merchant_id");
|
|
680
|
+
const taskId = text(input.task_id, "task_id");
|
|
681
|
+
const backoffMs = input.backoff_ms ?? 15_000;
|
|
682
|
+
const retryAfterMs = input.retry_after_ms ?? 0;
|
|
683
|
+
if (!Number.isSafeInteger(retryAfterMs) || retryAfterMs < 0) {
|
|
684
|
+
throw new OperationsJobsError("validation", "retry_after_invalid", "retry_after_ms 必须是非负整数");
|
|
685
|
+
}
|
|
686
|
+
const stamp = input.now ?? nowUtc(this.now);
|
|
687
|
+
const dueAt = new Date(Date.parse(stamp) + Math.max(backoffMs, retryAfterMs)).toISOString();
|
|
688
|
+
const result = this.db
|
|
689
|
+
.prepare(`UPDATE followup_tasks
|
|
690
|
+
SET status = 'PENDING', due_at = ?, revision = revision + 1,
|
|
691
|
+
lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
|
|
692
|
+
WHERE merchant_id = ? AND task_id = ? AND status = 'FAILED'
|
|
693
|
+
AND attempts < max_attempts`)
|
|
694
|
+
.run(dueAt, stamp, merchantId, taskId);
|
|
695
|
+
if (Number(result.changes) !== 1) {
|
|
696
|
+
throw new OperationsJobsError("invalid_transition", "retry_not_allowed", "任务状态或重试次数不允许重试");
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
listArtifacts(merchantId, taskId) {
|
|
700
|
+
const rows = (taskId === undefined
|
|
701
|
+
? this.db
|
|
702
|
+
.prepare("SELECT * FROM operation_artifacts WHERE merchant_id = ? ORDER BY created_at DESC LIMIT 200")
|
|
703
|
+
.all(text(merchantId, "merchant_id"))
|
|
704
|
+
: this.db
|
|
705
|
+
.prepare("SELECT * FROM operation_artifacts WHERE merchant_id = ? AND task_id = ? ORDER BY created_at DESC")
|
|
706
|
+
.all(text(merchantId, "merchant_id"), text(taskId, "task_id")));
|
|
707
|
+
return rows.map((row) => ({
|
|
708
|
+
artifact_id: row.artifact_id,
|
|
709
|
+
task_id: row.task_id,
|
|
710
|
+
result_kind: row.result_kind,
|
|
711
|
+
content_digest: row.content_digest,
|
|
712
|
+
receipt_ref: row.receipt_ref,
|
|
713
|
+
created_at: row.created_at,
|
|
714
|
+
payload: JSON.parse(row.payload_json),
|
|
715
|
+
}));
|
|
716
|
+
}
|
|
717
|
+
/** 未启动才归还;已经领取或结果不明则按预留额保守结算。 */
|
|
718
|
+
closeReservation(task) {
|
|
719
|
+
if (this.budgetStore === undefined || task.rule_id === null || task.operation_ref === null)
|
|
720
|
+
return;
|
|
721
|
+
const run = this.budgetStore.getRun(task.merchant_id, task.operation_ref);
|
|
722
|
+
if (run === undefined || run.state !== "RESERVED")
|
|
723
|
+
return;
|
|
724
|
+
if (task.attempts === 0 && task.external_call_started === 0 && task.status !== "UNKNOWN" && task.status !== "SUCCEEDED") {
|
|
725
|
+
this.budgetStore.releaseRun({ merchant_id: task.merchant_id, run_id: task.operation_ref });
|
|
726
|
+
}
|
|
727
|
+
else {
|
|
728
|
+
this.budgetStore.settleRun({ merchant_id: task.merchant_id, run_id: task.operation_ref,
|
|
729
|
+
input_tokens: 0, output_tokens: 0, usage_state: "unknown" });
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* 执行器明确失败(模型错误/超时/证据无效):只允许当前 worker/fencing 在
|
|
734
|
+
* 租约内把 RUNNING 任务置为 FAILED;之后由 retryTask 持久化退避。外部调用
|
|
735
|
+
* 结果不明时不得调用本方法(应保留 UNKNOWN 供核对)。
|
|
736
|
+
*/
|
|
737
|
+
failClaimedTask(input) {
|
|
738
|
+
const merchantId = text(input.merchant_id, "merchant_id");
|
|
739
|
+
const taskId = text(input.task_id, "task_id");
|
|
740
|
+
const workerId = text(input.worker_id, "worker_id");
|
|
741
|
+
const errorCode = text(input.error_code, "error_code", 128);
|
|
742
|
+
const stamp = input.now ?? nowUtc(this.now);
|
|
743
|
+
inImmediateTransaction(this.db, () => {
|
|
744
|
+
const task = this.db
|
|
745
|
+
.prepare("SELECT * FROM followup_tasks WHERE merchant_id = ? AND task_id = ?")
|
|
746
|
+
.get(merchantId, taskId);
|
|
747
|
+
if (task === undefined ||
|
|
748
|
+
task.status !== "RUNNING" ||
|
|
749
|
+
task.lease_owner !== workerId ||
|
|
750
|
+
task.fencing_token !== input.fencing) {
|
|
751
|
+
throw new OperationsJobsError("invalid_transition", "fail_guard_failed", "任务状态、执行者或 fencing 已变化");
|
|
752
|
+
}
|
|
753
|
+
this.db
|
|
754
|
+
.prepare(`UPDATE followup_tasks SET status = 'FAILED', last_error = ?,
|
|
755
|
+
lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
|
|
756
|
+
WHERE merchant_id = ? AND task_id = ? AND status = 'RUNNING'`)
|
|
757
|
+
.run(errorCode, stamp, merchantId, taskId);
|
|
758
|
+
this.db
|
|
759
|
+
.prepare(`UPDATE followup_attempts SET status = 'FAILED', ended_at = ?, error_code = ?
|
|
760
|
+
WHERE merchant_id = ? AND task_id = ? AND attempt_no = ?`)
|
|
761
|
+
.run(stamp, errorCode, merchantId, taskId, task.attempts);
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
/** 仅处理规则任务;过期 worker 不可继续提交,未知消耗不重试。 */
|
|
765
|
+
sweepRuleTasks(merchantId, stamp) {
|
|
766
|
+
const terminalReservations = this.budgetStore === undefined ? "0" : `EXISTS (
|
|
767
|
+
SELECT 1 FROM background_budget_reservations b
|
|
768
|
+
WHERE b.merchant_id = followup_tasks.merchant_id AND b.run_id = followup_tasks.operation_ref
|
|
769
|
+
AND b.state = 'RESERVED')`;
|
|
770
|
+
const tasks = this.db.prepare(`SELECT * FROM followup_tasks
|
|
771
|
+
WHERE merchant_id = ? AND rule_id IS NOT NULL AND (
|
|
772
|
+
(status = 'RUNNING' AND lease_expires_at IS NOT NULL AND lease_expires_at <= ?) OR
|
|
773
|
+
(status IN ('PENDING','READY') AND deadline_at IS NOT NULL AND deadline_at <= ?) OR
|
|
774
|
+
(status = 'FAILED' AND deadline_at IS NOT NULL AND deadline_at <= ? AND ${terminalReservations}) OR
|
|
775
|
+
(status = 'FAILED' AND attempts >= max_attempts AND ${terminalReservations}) OR
|
|
776
|
+
(status IN ('UNKNOWN','CANCELLED','SUCCEEDED') AND ${terminalReservations}))`)
|
|
777
|
+
.all(merchantId, stamp, stamp, stamp);
|
|
778
|
+
for (const task of tasks) {
|
|
779
|
+
this.closeReservation(task);
|
|
780
|
+
if (task.status === "RUNNING") {
|
|
781
|
+
this.db.prepare(`UPDATE followup_attempts SET status = 'UNKNOWN', ended_at = ?
|
|
782
|
+
WHERE merchant_id = ? AND task_id = ? AND attempt_no = ? AND status = 'RUNNING'`)
|
|
783
|
+
.run(stamp, merchantId, task.task_id, task.attempts);
|
|
784
|
+
this.db.prepare(`UPDATE followup_tasks SET status = 'UNKNOWN', revision = revision + 1,
|
|
785
|
+
lease_owner = NULL, lease_expires_at = NULL, updated_at = ? WHERE merchant_id = ? AND task_id = ?`)
|
|
786
|
+
.run(stamp, merchantId, task.task_id);
|
|
787
|
+
}
|
|
788
|
+
else if ((task.status === "PENDING" || task.status === "READY") && task.deadline_at !== null && task.deadline_at <= stamp) {
|
|
789
|
+
this.db.prepare(`UPDATE followup_tasks SET status = 'CANCELLED', cancel_epoch = cancel_epoch + 1,
|
|
790
|
+
revision = revision + 1, updated_at = ? WHERE merchant_id = ? AND task_id = ?`)
|
|
791
|
+
.run(stamp, merchantId, task.task_id);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
requireRule(merchantId, ruleId) {
|
|
796
|
+
const rule = this.getRule(merchantId, ruleId);
|
|
797
|
+
if (rule === undefined) {
|
|
798
|
+
throw new OperationsJobsError("not_found", "rule_not_found", "规则不存在或不可见");
|
|
799
|
+
}
|
|
800
|
+
return rule;
|
|
801
|
+
}
|
|
802
|
+
/** C16:额度不足时保留 PENDING 任务(不占配额),等待下一次准入。 */
|
|
803
|
+
enqueueBudgetWaitingTask(rule, triggerKey, detail, stamp, reason) {
|
|
804
|
+
const taskId = `fu_${randomUUID()}`;
|
|
805
|
+
const deadlineAt = new Date(Date.parse(stamp) + DEFAULT_RUN_DEADLINE_MS).toISOString();
|
|
806
|
+
this.db
|
|
807
|
+
.prepare(`INSERT INTO followup_tasks
|
|
808
|
+
(task_id, merchant_id, opportunity_id, trigger_event, action_type, target_version,
|
|
809
|
+
status, due_at, attempts, max_attempts, fencing_token, external_call_started,
|
|
810
|
+
stop_requested, idempotency_key, payload_json, rule_id, rule_version, revision,
|
|
811
|
+
cancel_epoch, deadline_at, snapshot_digest, candidate_ref, operation_ref,
|
|
812
|
+
created_at, updated_at)
|
|
813
|
+
VALUES (?, ?, NULL, ?, ?, NULL, 'PENDING', ?, 0, 3, 0, 0, 0, ?, ?, ?, ?, 1, 0, ?, ?, NULL, NULL, ?, ?)`)
|
|
814
|
+
.run(taskId, rule.merchant_id, `automation:${rule.template}`, rule.action_type, stamp, `rule:${triggerKey}`, JSON.stringify({
|
|
815
|
+
rule_id: rule.rule_id,
|
|
816
|
+
rule_version: rule.version,
|
|
817
|
+
...detail,
|
|
818
|
+
budget_exhausted: reason,
|
|
819
|
+
}), rule.rule_id, rule.version, deadlineAt, contentDigest(detail), stamp, stamp);
|
|
820
|
+
}
|
|
821
|
+
enqueueEligibleTask(rule, triggerKey, detail, stamp) {
|
|
822
|
+
const taskId = `fu_${randomUUID()}`;
|
|
823
|
+
const runId = `run_${randomUUID()}`;
|
|
824
|
+
if (this.budgetStore !== undefined) {
|
|
825
|
+
try {
|
|
826
|
+
this.budgetStore.reserveRun({
|
|
827
|
+
merchant_id: rule.merchant_id,
|
|
828
|
+
run_id: runId,
|
|
829
|
+
day_key: stamp.slice(0, 10),
|
|
830
|
+
template: rule.template,
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
catch (err) {
|
|
834
|
+
if (err instanceof BackgroundBudgetError) {
|
|
835
|
+
throw new OperationsJobsError("budget_exhausted", `budget:${err.reason}`, "后台预算不足;任务保持待处理");
|
|
836
|
+
}
|
|
837
|
+
throw err;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
const deadlineAt = new Date(Date.parse(stamp) + DEFAULT_RUN_DEADLINE_MS).toISOString();
|
|
841
|
+
this.db
|
|
842
|
+
.prepare(`INSERT INTO followup_tasks
|
|
843
|
+
(task_id, merchant_id, opportunity_id, trigger_event, action_type, target_version,
|
|
844
|
+
status, due_at, attempts, max_attempts, fencing_token, external_call_started,
|
|
845
|
+
stop_requested, idempotency_key, payload_json, rule_id, rule_version, revision,
|
|
846
|
+
cancel_epoch, deadline_at, snapshot_digest, candidate_ref, operation_ref,
|
|
847
|
+
created_at, updated_at)
|
|
848
|
+
VALUES (?, ?, NULL, ?, ?, NULL, 'READY', ?, 0, 3, 0, 0, 0, ?, ?, ?, ?, 1, 0, ?, ?, NULL, ?, ?, ?)`)
|
|
849
|
+
.run(taskId, rule.merchant_id, `automation:${rule.template}`, rule.action_type, stamp, `rule:${triggerKey}`, JSON.stringify({ rule_id: rule.rule_id, rule_version: rule.version, ...detail }), rule.rule_id, rule.version, deadlineAt, contentDigest(detail), runId, stamp, stamp);
|
|
850
|
+
}
|
|
851
|
+
advanceRule(rule, stamp) {
|
|
852
|
+
const next = nextDailyDueAt({
|
|
853
|
+
now: stamp,
|
|
854
|
+
local_time: rule.trigger_spec.local_time,
|
|
855
|
+
timezone: rule.trigger_spec.timezone,
|
|
856
|
+
});
|
|
857
|
+
const missedWindows = dailyMissedWindows(rule.next_due_at, stamp);
|
|
858
|
+
const missed = rule.missed_count + (missedWindows > 0 ? missedWindows : 0);
|
|
859
|
+
this.db
|
|
860
|
+
.prepare(`UPDATE automation_rules SET next_due_at = ?, missed_count = ?, updated_at = ?
|
|
861
|
+
WHERE merchant_id = ? AND rule_id = ?`)
|
|
862
|
+
.run(next, missed, stamp, rule.merchant_id, rule.rule_id);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
function toRule(row) {
|
|
866
|
+
return {
|
|
867
|
+
rule_id: row.rule_id,
|
|
868
|
+
merchant_id: row.merchant_id,
|
|
869
|
+
version: row.version,
|
|
870
|
+
template: row.template,
|
|
871
|
+
trigger_spec: JSON.parse(row.trigger_spec_json),
|
|
872
|
+
timezone: row.timezone,
|
|
873
|
+
scope: JSON.parse(row.scope_json),
|
|
874
|
+
predicate_spec: JSON.parse(row.predicate_spec_json),
|
|
875
|
+
action_type: row.action_type,
|
|
876
|
+
budget: JSON.parse(row.budget_json),
|
|
877
|
+
authorization_ref: row.authorization_ref,
|
|
878
|
+
effective_at: row.effective_at,
|
|
879
|
+
expires_at: row.expires_at,
|
|
880
|
+
content_hash: row.content_hash,
|
|
881
|
+
state: row.state,
|
|
882
|
+
enable_epoch: row.enable_epoch,
|
|
883
|
+
next_due_at: row.next_due_at,
|
|
884
|
+
missed_count: row.missed_count,
|
|
885
|
+
created_at: row.created_at,
|
|
886
|
+
updated_at: row.updated_at,
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
function toEvaluation(row) {
|
|
890
|
+
return {
|
|
891
|
+
evaluation_id: row.evaluation_id,
|
|
892
|
+
merchant_id: row.merchant_id,
|
|
893
|
+
rule_id: row.rule_id,
|
|
894
|
+
rule_version: row.rule_version,
|
|
895
|
+
trigger_key: row.trigger_key,
|
|
896
|
+
result: row.result,
|
|
897
|
+
reason_code: row.reason_code,
|
|
898
|
+
window_start: row.window_start,
|
|
899
|
+
window_end: row.window_end,
|
|
900
|
+
detail: JSON.parse(row.detail_json),
|
|
901
|
+
evaluated_at: row.evaluated_at,
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
function toClaimed(row) {
|
|
905
|
+
return {
|
|
906
|
+
task_id: row.task_id,
|
|
907
|
+
merchant_id: row.merchant_id,
|
|
908
|
+
rule_id: row.rule_id,
|
|
909
|
+
rule_version: row.rule_version,
|
|
910
|
+
status: row.status,
|
|
911
|
+
due_at: row.due_at,
|
|
912
|
+
attempts: row.attempts,
|
|
913
|
+
max_attempts: row.max_attempts,
|
|
914
|
+
fencing_token: row.fencing_token,
|
|
915
|
+
revision: row.revision,
|
|
916
|
+
cancel_epoch: row.cancel_epoch,
|
|
917
|
+
deadline_at: row.deadline_at,
|
|
918
|
+
snapshot_digest: row.snapshot_digest,
|
|
919
|
+
payload: JSON.parse(row.payload_json),
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
//# sourceMappingURL=service.js.map
|