@jjh32456/longlive 0.0.0-stage → 2.0.0
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/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,1766 @@
|
|
|
1
|
+
// R1 Router-A — 规则层(纯函数);出错即停,绝不放行。
|
|
2
|
+
//
|
|
3
|
+
// 契约见 R1-DESIGN.md §2.1 / §3.3 / §5:
|
|
4
|
+
// route({
|
|
5
|
+
// caseId?, turn?,
|
|
6
|
+
// kind?: 'tool' | 'memory' | 'session', // 旧入口字段
|
|
7
|
+
// text? | utterance?, // 旧入口用 text,新契约用 utterance
|
|
8
|
+
// ctx?: { tokens?, zone?, activeWorkers?, openRows? },
|
|
9
|
+
// candidates?: Array<string | { tool?, name? }>,
|
|
10
|
+
// override? | overrides?: Array<{ ruleId, reason, by?, at?, action? }>,
|
|
11
|
+
// }) -> {
|
|
12
|
+
// caseId, turn,
|
|
13
|
+
// decisions: Array<{ kind, action, args, ruleId, evidence, writeScope, target, tool, needsHuman, confidence }>,
|
|
14
|
+
// needsHuman, confidence, matchedRule, matchedRules,
|
|
15
|
+
// overrides, overrideAudit, errors,
|
|
16
|
+
// decision: { target, tool }, target, tool, // 旧输出契约的兼容别名
|
|
17
|
+
// level, ctx, failClosed?,
|
|
18
|
+
// }
|
|
19
|
+
//
|
|
20
|
+
// target 取值:core 目标(topics/journal/procedures/live/none)+ adapter 注册的第三方目标
|
|
21
|
+
// decision.kind 取值:tool | memory | session | reply
|
|
22
|
+
//
|
|
23
|
+
// 四条硬性质:
|
|
24
|
+
// 1. 纯净:不读时钟、不写盘、不碰网络;同样输入(含 override.at)永远同样输出。
|
|
25
|
+
// 2. 全函数:任何畸形输入(null / 非字符串 / getter 炸弹 / 10 万字符)退化为 none,不抛错。
|
|
26
|
+
// 3. 可解释:每条决定带 ruleId + evidence(规则表:行 / policy:文档 §节 / ctx:字段)。
|
|
27
|
+
// 4. 可兼容:decisions[] 是新的有序契约;decision/target/tool 是旧契约的别名,旧测试不改。
|
|
28
|
+
//
|
|
29
|
+
// 冲突消解(§2.1):规则按 priority 降序。**同优先级同时命中不再按文件顺序判定**:
|
|
30
|
+
// 判为歧义(E_ROUTE_AMBIGUOUS),整单 refuse 交人判断。
|
|
31
|
+
//
|
|
32
|
+
// fail-closed(2026-11-03 修 R1 静默放行):规则/别名文件缺失、JSON 损坏、结构或字段错误、
|
|
33
|
+
// 未知 action/kind、ctx 缺字段/类型错、override 指向不存在规则、writeScope 越界、
|
|
34
|
+
// 决策或规则数量爆炸、以及任何内部异常,一律返回一条 refuse 决策 + needsHuman=true +
|
|
35
|
+
// 结构化 errors(具体错误码),不允许「空 decisions + needsHuman=false」把「没判断」交给调用方。
|
|
36
|
+
//
|
|
37
|
+
// confidence 是匹配强度的确定映射,不是概率:
|
|
38
|
+
// 候选工具名精确命中 -> 1
|
|
39
|
+
// >= 2 个关键词命中 -> 1
|
|
40
|
+
// 恰好 1 个关键词命中 -> 0.75
|
|
41
|
+
// 纯 ctx 触发 -> 0.9
|
|
42
|
+
// 无匹配 -> 0
|
|
43
|
+
|
|
44
|
+
import { readFileSync } from 'node:fs';
|
|
45
|
+
import {
|
|
46
|
+
E_ROUTE_POLICY_INVALID,
|
|
47
|
+
E_ROUTE_PROFILE_UNKNOWN,
|
|
48
|
+
POLICY_PROFILE_DEFAULT,
|
|
49
|
+
configuredPolicyProfileName,
|
|
50
|
+
loadPolicyProfile,
|
|
51
|
+
} from '../policy-profile.js';
|
|
52
|
+
import {
|
|
53
|
+
loadAdapterAliases,
|
|
54
|
+
loadAdapterRoutingRules,
|
|
55
|
+
isExternalMemoryTarget,
|
|
56
|
+
} from '../adapters/registry.js';
|
|
57
|
+
|
|
58
|
+
const CORE_TARGETS = ['topics', 'journal', 'procedures', 'live', 'none'];
|
|
59
|
+
const ADAPTER_ROUTING = loadAdapterRoutingRules();
|
|
60
|
+
export const TARGETS = Object.freeze([
|
|
61
|
+
...CORE_TARGETS,
|
|
62
|
+
...(ADAPTER_ROUTING.targets || []).filter((target) => !CORE_TARGETS.includes(target)),
|
|
63
|
+
]);
|
|
64
|
+
|
|
65
|
+
// adapter 侧规则/别名数据不可用时:核心照常跑,只记录降级(不 fail-closed)。
|
|
66
|
+
export const ADAPTER_DEGRADED = Object.freeze([
|
|
67
|
+
...(ADAPTER_ROUTING.degraded ? ADAPTER_ROUTING.errors.map((error) => ({ ...error })) : []),
|
|
68
|
+
]);
|
|
69
|
+
|
|
70
|
+
export const KINDS = Object.freeze(['tool', 'memory', 'session', 'reply']);
|
|
71
|
+
|
|
72
|
+
export const LEVELS = Object.freeze(['X', 'D', 'H']);
|
|
73
|
+
|
|
74
|
+
// 失败码:R1 的全部 judge 只用这一张表里的码,前缀统一 E_ROUTE_;
|
|
75
|
+
// J8 起有两个跨层码(身份同意),按判定原文命名,不套 E_ROUTE_ 前缀。
|
|
76
|
+
export const ERROR_CODES = Object.freeze({
|
|
77
|
+
ISOLATION: 'E_ROUTE_ISOLATION',
|
|
78
|
+
SHAPE: 'E_ROUTE_SHAPE',
|
|
79
|
+
ORDER: 'E_ROUTE_ORDER',
|
|
80
|
+
ACTION: 'E_ROUTE_ACTION',
|
|
81
|
+
REFUSAL: 'E_ROUTE_REFUSAL',
|
|
82
|
+
EVIDENCE: 'E_ROUTE_EVIDENCE',
|
|
83
|
+
OVERRIDE_UNJUSTIFIED: 'E_ROUTE_OVERRIDE_UNJUSTIFIED',
|
|
84
|
+
OVERRIDE_UNKNOWN: 'E_ROUTE_OVERRIDE_UNKNOWN',
|
|
85
|
+
SCOPE: 'E_ROUTE_SCOPE',
|
|
86
|
+
AUDIT: 'E_ROUTE_AUDIT',
|
|
87
|
+
HUMAN: 'E_ROUTE_HUMAN',
|
|
88
|
+
POLICY: 'E_ROUTE_POLICY',
|
|
89
|
+
LEVEL: 'E_ROUTE_LEVEL',
|
|
90
|
+
CONTRACT: 'E_ROUTE_CONTRACT',
|
|
91
|
+
DETERMINISM: 'E_ROUTE_DETERMINISM',
|
|
92
|
+
FORBIDDEN: 'E_ROUTE_FORBIDDEN',
|
|
93
|
+
BRIEF: 'E_ROUTE_BRIEF',
|
|
94
|
+
// ── fail-closed(2026-11-03) ───────────────────────────────────────────
|
|
95
|
+
RULES_UNAVAILABLE: 'E_ROUTE_RULES_UNAVAILABLE',
|
|
96
|
+
RULES_INVALID: 'E_ROUTE_RULES_INVALID',
|
|
97
|
+
ALIASES_UNAVAILABLE: 'E_ROUTE_ALIASES_UNAVAILABLE',
|
|
98
|
+
ALIASES_INVALID: 'E_ROUTE_ALIASES_INVALID',
|
|
99
|
+
RULE_FIELD: 'E_ROUTE_RULE_FIELD',
|
|
100
|
+
RULE_UNKNOWN: 'E_ROUTE_RULE_UNKNOWN',
|
|
101
|
+
AMBIGUOUS: 'E_ROUTE_AMBIGUOUS',
|
|
102
|
+
CTX_MISSING: 'E_ROUTE_CTX_MISSING',
|
|
103
|
+
CTX_TYPE: 'E_ROUTE_CTX_TYPE',
|
|
104
|
+
EXPLOSION: 'E_ROUTE_EXPLOSION',
|
|
105
|
+
// ── J8(2026-11-03):身份同意 ────────────────────────────────────────
|
|
106
|
+
IDENTITY_CONSENT_REQUIRED: 'E_IDENTITY_CONSENT_REQUIRED',
|
|
107
|
+
SELF_CONSENT: 'E_SELF_CONSENT',
|
|
108
|
+
// ── 策略 profile(2026-11-03):默认 generic,家规可选 ──────────────────
|
|
109
|
+
PROFILE_UNKNOWN: E_ROUTE_PROFILE_UNKNOWN,
|
|
110
|
+
POLICY_INVALID: E_ROUTE_POLICY_INVALID,
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
// 策略 1:休息 vs 终止的机器口径由生效 profile 提供(generic 默认,owner 可补充词表)。
|
|
114
|
+
// REST_RE 命中且 STOP_RE 不命中才算「可恢复的短暂暂停」。
|
|
115
|
+
function escapeMarker(marker) {
|
|
116
|
+
return String(marker).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function markersRegex(markers) {
|
|
120
|
+
const list = Array.isArray(markers)
|
|
121
|
+
? markers.filter((marker) => typeof marker === 'string' && marker.trim()).map((marker) => marker.trim())
|
|
122
|
+
: [];
|
|
123
|
+
if (!list.length) return null;
|
|
124
|
+
return new RegExp(list.map((marker) => escapeMarker(marker)).join('|'), 'i');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// 硬上限:展开后的决策数、规则表条数、同优先级竞争规则数。
|
|
128
|
+
export const LIMITS = Object.freeze({
|
|
129
|
+
maxRules: 200,
|
|
130
|
+
maxDecisions: 32,
|
|
131
|
+
maxCompeting: 32,
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
// 规则表不可用时,refuse 决策的合成 ruleId(真实规则表里不存在,便于审计识别)。
|
|
135
|
+
export const FAILCLOSED_RULE_ID = 'R-ROUTER-FAILCLOSED';
|
|
136
|
+
|
|
137
|
+
// 证据里的规则定义位置:repo 相对路径,judge 用它回读文件核对行号。
|
|
138
|
+
export const RULE_TABLE_PATH = 'src/router/routing-rules.json';
|
|
139
|
+
|
|
140
|
+
const RULES_URL = new URL('./routing-rules.json', import.meta.url);
|
|
141
|
+
const ALIASES_URL = new URL('./aliases.json', import.meta.url);
|
|
142
|
+
|
|
143
|
+
// 通用默认策略在模块加载期就读:读不到/不合法由 LOAD_ERRORS 统一 fail-closed。
|
|
144
|
+
const GENERIC_LOAD = loadPolicyProfile(POLICY_PROFILE_DEFAULT);
|
|
145
|
+
|
|
146
|
+
function textOr(value) {
|
|
147
|
+
return typeof value === 'string' ? value.trim() : '';
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function makeError(code, message, detail = {}) {
|
|
151
|
+
return { code, message, ...detail };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function safeGet(object, key) {
|
|
155
|
+
try {
|
|
156
|
+
return object[key];
|
|
157
|
+
} catch {
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// ── 动作名归一(aliases.json) ────────────────────────────────
|
|
163
|
+
|
|
164
|
+
function nameVariants(name) {
|
|
165
|
+
const raw = textOr(name).toLowerCase();
|
|
166
|
+
if (!raw) return [];
|
|
167
|
+
return Array.from(new Set([raw, raw.replace(/_/g, '.'), raw.replace(/\./g, '_')]));
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// 别名文件是动作白名单:读不到/解析不了/结构不对 → 整份不可用(fail-closed)。
|
|
171
|
+
export function loadAliases() {
|
|
172
|
+
let text = '';
|
|
173
|
+
try {
|
|
174
|
+
text = readFileSync(ALIASES_URL, 'utf8');
|
|
175
|
+
} catch (cause) {
|
|
176
|
+
return {
|
|
177
|
+
entries: [],
|
|
178
|
+
byVariant: new Map(),
|
|
179
|
+
errors: [makeError(ERROR_CODES.ALIASES_UNAVAILABLE, `aliases.json 读取失败:${cause.code || cause.message},拒绝路由`)],
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
let table;
|
|
183
|
+
try {
|
|
184
|
+
table = JSON.parse(text);
|
|
185
|
+
} catch (cause) {
|
|
186
|
+
return {
|
|
187
|
+
entries: [],
|
|
188
|
+
byVariant: new Map(),
|
|
189
|
+
errors: [makeError(ERROR_CODES.ALIASES_INVALID, `aliases.json JSON 解析失败:${cause.message}`)],
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
const list = table && Array.isArray(table.actions) ? table.actions : null;
|
|
193
|
+
if (!list || list.length === 0) {
|
|
194
|
+
return {
|
|
195
|
+
entries: [],
|
|
196
|
+
byVariant: new Map(),
|
|
197
|
+
errors: [makeError(ERROR_CODES.ALIASES_INVALID, 'aliases.json 的 actions 必须是非空数组')],
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
const byVariant = new Map();
|
|
201
|
+
const entries = [];
|
|
202
|
+
const seen = new Set();
|
|
203
|
+
for (const raw of list) {
|
|
204
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
205
|
+
return {
|
|
206
|
+
entries: [],
|
|
207
|
+
byVariant: new Map(),
|
|
208
|
+
errors: [makeError(ERROR_CODES.ALIASES_INVALID, 'aliases.json 的 actions 里有非对象条目')],
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
const canonical = textOr(raw.canonical);
|
|
212
|
+
if (!canonical) {
|
|
213
|
+
return {
|
|
214
|
+
entries: [],
|
|
215
|
+
byVariant: new Map(),
|
|
216
|
+
errors: [makeError(ERROR_CODES.ALIASES_INVALID, 'aliases.json 有条目缺 canonical')],
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
if (seen.has(canonical)) {
|
|
220
|
+
return {
|
|
221
|
+
entries: [],
|
|
222
|
+
byVariant: new Map(),
|
|
223
|
+
errors: [makeError(ERROR_CODES.ALIASES_INVALID, `aliases.json 里 canonical 重复:${canonical}`)],
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
seen.add(canonical);
|
|
227
|
+
if (raw.legacy !== undefined && typeof raw.legacy !== 'string') {
|
|
228
|
+
return {
|
|
229
|
+
entries: [],
|
|
230
|
+
byVariant: new Map(),
|
|
231
|
+
errors: [makeError(ERROR_CODES.ALIASES_INVALID, `aliases.json 里 ${canonical} 的 legacy 必须是字符串`)],
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
const legacy = textOr(raw.legacy) || canonical;
|
|
235
|
+
if (raw.aliases !== undefined) {
|
|
236
|
+
if (!Array.isArray(raw.aliases) || raw.aliases.some((alias) => typeof alias !== 'string')) {
|
|
237
|
+
return {
|
|
238
|
+
entries: [],
|
|
239
|
+
byVariant: new Map(),
|
|
240
|
+
errors: [makeError(ERROR_CODES.ALIASES_INVALID, `aliases.json 里 ${canonical} 的 aliases 必须是字符串数组`)],
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const aliases = Array.isArray(raw.aliases)
|
|
245
|
+
? raw.aliases.filter((alias) => alias.trim()).map((alias) => alias.trim())
|
|
246
|
+
: [];
|
|
247
|
+
entries.push({ canonical, legacy, aliases });
|
|
248
|
+
for (const name of [canonical, legacy, ...aliases]) {
|
|
249
|
+
for (const variant of nameVariants(name)) {
|
|
250
|
+
if (!byVariant.has(variant)) byVariant.set(variant, canonical);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
// M2-E:并入 adapter 提供的动作别名(旧工具名兼容也在 adapter 侧)。
|
|
255
|
+
const adapterAliases = loadAdapterAliases();
|
|
256
|
+
for (const raw of adapterAliases.actions) {
|
|
257
|
+
const canonical = textOr(raw && raw.canonical);
|
|
258
|
+
if (!canonical || seen.has(canonical)) continue;
|
|
259
|
+
seen.add(canonical);
|
|
260
|
+
const legacy = textOr(raw && raw.legacy) || canonical;
|
|
261
|
+
const aliases = Array.isArray(raw && raw.aliases) ? raw.aliases.filter((alias) => typeof alias === 'string' && alias.trim()).map((alias) => alias.trim()) : [];
|
|
262
|
+
entries.push({ canonical, legacy, aliases });
|
|
263
|
+
for (const name of [canonical, legacy, ...aliases]) {
|
|
264
|
+
for (const variant of nameVariants(name)) {
|
|
265
|
+
if (!byVariant.has(variant)) byVariant.set(variant, canonical);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return { entries, byVariant, errors: [], adapterErrors: adapterAliases.errors };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export const ALIASES = loadAliases();
|
|
273
|
+
|
|
274
|
+
export function canonicalAction(name) {
|
|
275
|
+
if (typeof name !== 'string') return null;
|
|
276
|
+
for (const variant of nameVariants(name)) {
|
|
277
|
+
const hit = ALIASES.byVariant.get(variant);
|
|
278
|
+
if (hit) return hit;
|
|
279
|
+
}
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export function legacyAction(name) {
|
|
284
|
+
const canonical = canonicalAction(name);
|
|
285
|
+
if (!canonical) return null;
|
|
286
|
+
const entry = ALIASES.entries.find((item) => item.canonical === canonical);
|
|
287
|
+
return entry ? entry.legacy : canonical;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// ── 规则表 ────────────────────────────────────────────────────
|
|
291
|
+
|
|
292
|
+
function ruleLines(text) {
|
|
293
|
+
const map = new Map();
|
|
294
|
+
const lines = String(text).split('\n');
|
|
295
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
296
|
+
const match = /^\s*"id":\s*"([^"]+)"/.exec(lines[index]);
|
|
297
|
+
if (match && !map.has(match[1])) map.set(match[1], index + 1);
|
|
298
|
+
}
|
|
299
|
+
return map;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function normalizeScope(list) {
|
|
303
|
+
if (!Array.isArray(list)) return [];
|
|
304
|
+
return list.filter((entry) => typeof entry === 'string' && entry.trim()).map((entry) => entry.trim());
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function normalizeEvidence(list) {
|
|
308
|
+
if (!Array.isArray(list)) return [];
|
|
309
|
+
return list.filter((entry) => typeof entry === 'string' && entry.trim()).map((entry) => entry.trim());
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// 把校验过的 profile 编译成路由层使用的形状。
|
|
313
|
+
function policyFromProfile(policy) {
|
|
314
|
+
return {
|
|
315
|
+
profile: policy.name,
|
|
316
|
+
compressAt: policy.thresholds.compressAt,
|
|
317
|
+
redAt: policy.thresholds.redAt,
|
|
318
|
+
dispatchAt: policy.thresholds.dispatchAt,
|
|
319
|
+
taskboardAt: policy.thresholds.taskboardAt,
|
|
320
|
+
thresholds: { ...policy.thresholds },
|
|
321
|
+
allow: policy.writeScope.allowPrefixes.slice(),
|
|
322
|
+
ask: policy.ask,
|
|
323
|
+
rest: policy.rest,
|
|
324
|
+
privacy: policy.privacy,
|
|
325
|
+
distill: policy.distill,
|
|
326
|
+
identity: policy.identity,
|
|
327
|
+
limits: policy.limits,
|
|
328
|
+
rulings: policy.rulings || [],
|
|
329
|
+
raw: policy,
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// generic 都坏了的时候用的保守占位:allow=[] 让任何 writeScope 都越界,route 由 LOAD_ERRORS 拒单。
|
|
334
|
+
function invalidPolicy(code, message) {
|
|
335
|
+
return Object.freeze({
|
|
336
|
+
profile: POLICY_PROFILE_DEFAULT,
|
|
337
|
+
compressAt: 0,
|
|
338
|
+
redAt: 0,
|
|
339
|
+
dispatchAt: Number.MAX_SAFE_INTEGER,
|
|
340
|
+
taskboardAt: Number.MAX_SAFE_INTEGER,
|
|
341
|
+
allow: [],
|
|
342
|
+
ask: { maxQuestions: 1, maxCandidates: 3, guessAllowed: false, missing: [], prompt: '' },
|
|
343
|
+
rest: {
|
|
344
|
+
markers: [],
|
|
345
|
+
terminators: [],
|
|
346
|
+
kind: 'TEMPORARY',
|
|
347
|
+
resumable: true,
|
|
348
|
+
terminal: false,
|
|
349
|
+
resumePoint: '',
|
|
350
|
+
resumePointRequired: true,
|
|
351
|
+
pendingTask: 'keep',
|
|
352
|
+
forbiddenActions: [],
|
|
353
|
+
},
|
|
354
|
+
privacy: { markers: [], store: 'memory/private/', dataClass: 'LOCAL_ONLY', retention: 'LOCAL', echoBack: false, networkCalls: 0, uploadAllowed: false },
|
|
355
|
+
distill: { preferDistill: true, deleteBeforeConfirm: false, requireSupersedes: true, maxQuestions: 1 },
|
|
356
|
+
identity: { consentHolder: 'assistant', userConsentCounts: false, requireQuote: true, requireQuoteId: true },
|
|
357
|
+
limits: LIMITS,
|
|
358
|
+
rulings: [],
|
|
359
|
+
errors: [makeError(code, message)],
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function basePolicy() {
|
|
364
|
+
return GENERIC_LOAD.ok ? policyFromProfile(GENERIC_LOAD.policy) : invalidPolicy(GENERIC_LOAD.code, GENERIC_LOAD.message);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// 规则表里的 `$policy:<a.b.c>` 在生效 profile 上展开;展开失败 = 整表不可用(不静默留一个永不命中的字符串)。
|
|
368
|
+
function expandPolicyRefs(value, policy) {
|
|
369
|
+
if (typeof value === 'string') {
|
|
370
|
+
const match = /^\$policy:([A-Za-z0-9_.]+)$/.exec(value);
|
|
371
|
+
if (!match) return value;
|
|
372
|
+
let cursor = policy;
|
|
373
|
+
for (const part of match[1].split('.')) {
|
|
374
|
+
if (!cursor || typeof cursor !== 'object' || !(part in cursor)) {
|
|
375
|
+
throw new Error(`无法解析策略引用 ${value}`);
|
|
376
|
+
}
|
|
377
|
+
cursor = cursor[part];
|
|
378
|
+
}
|
|
379
|
+
return cursor && typeof cursor === 'object' ? JSON.parse(JSON.stringify(cursor)) : cursor;
|
|
380
|
+
}
|
|
381
|
+
if (Array.isArray(value)) return value.map((entry) => expandPolicyRefs(entry, policy));
|
|
382
|
+
if (value && typeof value === 'object') {
|
|
383
|
+
const next = {};
|
|
384
|
+
for (const [key, entry] of Object.entries(value)) next[key] = expandPolicyRefs(entry, policy);
|
|
385
|
+
return next;
|
|
386
|
+
}
|
|
387
|
+
return value;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
let RULE_TABLE_RAW = null;
|
|
391
|
+
let RULE_TABLE_TEXT = '';
|
|
392
|
+
let ACTIVE_RUNTIME = null;
|
|
393
|
+
const RUNTIME_CACHE = new Map();
|
|
394
|
+
|
|
395
|
+
export function runtimeFor(name) {
|
|
396
|
+
const requested = typeof name === 'string' && name.trim() ? name.trim() : configuredPolicyProfileName();
|
|
397
|
+
const cached = RUNTIME_CACHE.get(requested);
|
|
398
|
+
if (cached) return cached;
|
|
399
|
+
const loaded = loadPolicyProfile(requested);
|
|
400
|
+
let runtime;
|
|
401
|
+
if (!loaded.ok) {
|
|
402
|
+
runtime = {
|
|
403
|
+
name: requested,
|
|
404
|
+
policy: basePolicy(),
|
|
405
|
+
limits: LIMITS,
|
|
406
|
+
rules: [],
|
|
407
|
+
fallbacks: [],
|
|
408
|
+
byId: new Map(),
|
|
409
|
+
errors: [makeError(loaded.code, loaded.message, { profile: requested })],
|
|
410
|
+
};
|
|
411
|
+
} else {
|
|
412
|
+
const policy = policyFromProfile(loaded.policy);
|
|
413
|
+
const errors = [];
|
|
414
|
+
let rules = [];
|
|
415
|
+
let fallbacks = [];
|
|
416
|
+
if (RULE_TABLE_TEXT) {
|
|
417
|
+
try {
|
|
418
|
+
const expanded = expandPolicyRefs(RULE_TABLE_RAW || {}, policy);
|
|
419
|
+
const result = validateRuleTable(expanded, RULE_TABLE_TEXT, { aliases: ALIASES, policy });
|
|
420
|
+
rules = attachAdapterRuleMeta(result.rules);
|
|
421
|
+
fallbacks = result.fallbacks || [];
|
|
422
|
+
errors.push(...result.errors);
|
|
423
|
+
} catch (cause) {
|
|
424
|
+
errors.push(makeError(ERROR_CODES.POLICY_INVALID, `策略引用展开失败:${cause && cause.message ? cause.message : String(cause)}`, {
|
|
425
|
+
profile: requested,
|
|
426
|
+
}));
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
runtime = {
|
|
430
|
+
name: requested,
|
|
431
|
+
policy,
|
|
432
|
+
limits: policy.limits,
|
|
433
|
+
rules,
|
|
434
|
+
fallbacks,
|
|
435
|
+
byId: new Map([...rules, ...fallbacks].map((rule) => [rule.id, rule])),
|
|
436
|
+
errors,
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
RUNTIME_CACHE.set(requested, runtime);
|
|
440
|
+
return runtime;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function activeRuntime() {
|
|
444
|
+
return ACTIVE_RUNTIME || runtimeFor(POLICY_PROFILE_DEFAULT);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// writeScope 白名单:盘符、绝对路径、..、~、前缀外一律拒绝。
|
|
448
|
+
// 导出给测试与 judge 之外的工具复用(judge 有自己的同口径实现,避免循环依赖)。
|
|
449
|
+
export function writeScopeErrors(scope, policy) {
|
|
450
|
+
const effective = policy || activeRuntime().policy;
|
|
451
|
+
if (!Array.isArray(scope)) return ['writeScope 必须是数组'];
|
|
452
|
+
const errors = [];
|
|
453
|
+
const allow = Array.isArray(effective.allow) ? effective.allow : [];
|
|
454
|
+
for (const raw of scope) {
|
|
455
|
+
if (typeof raw !== 'string' || !raw.trim()) {
|
|
456
|
+
errors.push(`writeScope 含空/非字符串条目:${JSON.stringify(raw)}`);
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
const entry = raw.trim();
|
|
460
|
+
if (/^[A-Za-z]:/.test(entry)) {
|
|
461
|
+
errors.push(`writeScope 不得是盘符路径:${entry}`);
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
if (entry.startsWith('/') || entry.startsWith('\\')) {
|
|
465
|
+
errors.push(`writeScope 不得是绝对路径:${entry}`);
|
|
466
|
+
continue;
|
|
467
|
+
}
|
|
468
|
+
if (entry.includes('..')) {
|
|
469
|
+
errors.push(`writeScope 不得含 ..:${entry}`);
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
if (entry.includes('~')) {
|
|
473
|
+
errors.push(`writeScope 不得含 ~:${entry}`);
|
|
474
|
+
continue;
|
|
475
|
+
}
|
|
476
|
+
if (!allow.some((prefix) => entry.startsWith(prefix))) {
|
|
477
|
+
errors.push(`writeScope 不在允许前缀内(${allow.join('/')}):${entry}`);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
return errors;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function validateCtxMatcher(raw, push, where) {
|
|
484
|
+
if (raw === undefined) return false;
|
|
485
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
486
|
+
push(ERROR_CODES.RULE_FIELD, `${where} 必须是对象`);
|
|
487
|
+
return false;
|
|
488
|
+
}
|
|
489
|
+
const known = new Set(['tokensGte', 'activeWorkersGte', 'openRowsGte', 'zoneIn']);
|
|
490
|
+
for (const key of Object.keys(raw)) {
|
|
491
|
+
if (!known.has(key)) {
|
|
492
|
+
push(ERROR_CODES.RULE_FIELD, `${where} 含未知字段 ${key}(写错字段名会让门控静默失效)`);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
let conditions = 0;
|
|
496
|
+
for (const key of ['tokensGte', 'activeWorkersGte', 'openRowsGte']) {
|
|
497
|
+
if (raw[key] === undefined) continue;
|
|
498
|
+
if (typeof raw[key] !== 'number' || !Number.isFinite(raw[key])) {
|
|
499
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.${key} 必须是有限数字`);
|
|
500
|
+
} else {
|
|
501
|
+
conditions += 1;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
if (raw.zoneIn !== undefined) {
|
|
505
|
+
if (!Array.isArray(raw.zoneIn) || raw.zoneIn.length === 0 || raw.zoneIn.some((zone) => typeof zone !== 'string' || !zone.trim())) {
|
|
506
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.zoneIn 必须是非空字符串数组`);
|
|
507
|
+
} else {
|
|
508
|
+
conditions += 1;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
if (conditions === 0 && !Object.keys(raw).length) push(ERROR_CODES.RULE_FIELD, `${where} 没有任何 ctx 条件`);
|
|
512
|
+
return conditions > 0;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// 一条决定模板:结构不完整 = 整表拒收(半条决定比没有决定更危险)。
|
|
516
|
+
function validateTemplate(raw, where, policy, push) {
|
|
517
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
518
|
+
push(ERROR_CODES.RULE_FIELD, `${where} 必须是对象`);
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
521
|
+
let ok = true;
|
|
522
|
+
const kind = typeof raw.kind === 'string' ? raw.kind.trim().toLowerCase() : '';
|
|
523
|
+
if (!kind) {
|
|
524
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.kind 缺失`);
|
|
525
|
+
ok = false;
|
|
526
|
+
} else if (!KINDS.includes(kind)) {
|
|
527
|
+
push(ERROR_CODES.RULE_UNKNOWN, `${where}.kind 未知:${raw.kind}`);
|
|
528
|
+
ok = false;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
const actionRaw = typeof raw.action === 'string' ? raw.action.trim() : '';
|
|
532
|
+
let action = null;
|
|
533
|
+
if (!actionRaw) {
|
|
534
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.action 缺失`);
|
|
535
|
+
ok = false;
|
|
536
|
+
} else {
|
|
537
|
+
action = canonicalAction(actionRaw);
|
|
538
|
+
if (!action) {
|
|
539
|
+
push(ERROR_CODES.RULE_UNKNOWN, `${where}.action 未知:${raw.action}`);
|
|
540
|
+
ok = false;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
const target = typeof raw.target === 'string' ? raw.target.trim() : '';
|
|
545
|
+
if (!target) {
|
|
546
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.target 缺失`);
|
|
547
|
+
ok = false;
|
|
548
|
+
} else if (!TARGETS.includes(target)) {
|
|
549
|
+
push(ERROR_CODES.RULE_UNKNOWN, `${where}.target 未知:${raw.target}`);
|
|
550
|
+
ok = false;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
if (raw.args !== undefined && (!raw.args || typeof raw.args !== 'object' || Array.isArray(raw.args))) {
|
|
554
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.args 必须是对象`);
|
|
555
|
+
ok = false;
|
|
556
|
+
}
|
|
557
|
+
// tool: null 是「这条决定不绑工具」的合法写法(reply/memory 决定),只拒其它非字符串。
|
|
558
|
+
if (raw.tool !== undefined && raw.tool !== null && typeof raw.tool !== 'string') {
|
|
559
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.tool 必须是字符串或 null`);
|
|
560
|
+
ok = false;
|
|
561
|
+
}
|
|
562
|
+
if (raw.needsHuman !== undefined && typeof raw.needsHuman !== 'boolean') {
|
|
563
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.needsHuman 必须是布尔`);
|
|
564
|
+
ok = false;
|
|
565
|
+
}
|
|
566
|
+
if (raw.evidence !== undefined) {
|
|
567
|
+
if (!Array.isArray(raw.evidence) || raw.evidence.some((entry) => typeof entry !== 'string')) {
|
|
568
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.evidence 必须是字符串数组`);
|
|
569
|
+
ok = false;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
if (raw.writeScope !== undefined) {
|
|
573
|
+
if (!Array.isArray(raw.writeScope)) {
|
|
574
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.writeScope 必须是数组`);
|
|
575
|
+
ok = false;
|
|
576
|
+
} else {
|
|
577
|
+
if (raw.writeScope.some((entry) => typeof entry !== 'string' || !entry.trim())) {
|
|
578
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.writeScope 含空/非字符串条目`);
|
|
579
|
+
ok = false;
|
|
580
|
+
}
|
|
581
|
+
for (const issue of writeScopeErrors(raw.writeScope, policy)) {
|
|
582
|
+
push(ERROR_CODES.SCOPE, `${where} 越界:${issue}`);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
return ok ? { kind, action, target } : null;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
function normalizeTemplate(raw) {
|
|
590
|
+
const kind = textOr(raw.kind).toLowerCase();
|
|
591
|
+
const action = canonicalAction(raw.action);
|
|
592
|
+
const target = textOr(raw.target);
|
|
593
|
+
const args = raw.args && typeof raw.args === 'object' && !Array.isArray(raw.args) ? raw.args : {};
|
|
594
|
+
const hasTool = Object.prototype.hasOwnProperty.call(raw, 'tool');
|
|
595
|
+
const explicitTool = hasTool ? textOr(raw.tool) : '';
|
|
596
|
+
return Object.freeze({
|
|
597
|
+
kind,
|
|
598
|
+
action,
|
|
599
|
+
target,
|
|
600
|
+
args,
|
|
601
|
+
tool: hasTool ? (explicitTool || null) : legacyAction(action),
|
|
602
|
+
writeScope: normalizeScope(raw.writeScope),
|
|
603
|
+
evidence: normalizeEvidence(raw.evidence),
|
|
604
|
+
needsHuman: raw.needsHuman === true,
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function normalizeCtxMatcher(raw) {
|
|
609
|
+
const matcher = {};
|
|
610
|
+
if (typeof raw.tokensGte === 'number' && Number.isFinite(raw.tokensGte)) matcher.tokensGte = raw.tokensGte;
|
|
611
|
+
if (typeof raw.activeWorkersGte === 'number' && Number.isFinite(raw.activeWorkersGte)) {
|
|
612
|
+
matcher.activeWorkersGte = raw.activeWorkersGte;
|
|
613
|
+
}
|
|
614
|
+
if (typeof raw.openRowsGte === 'number' && Number.isFinite(raw.openRowsGte)) matcher.openRowsGte = raw.openRowsGte;
|
|
615
|
+
if (Array.isArray(raw.zoneIn)) {
|
|
616
|
+
const zones = raw.zoneIn.filter((z) => typeof z === 'string' && z.trim()).map((z) => z.trim().toLowerCase());
|
|
617
|
+
if (zones.length) matcher.zoneIn = zones;
|
|
618
|
+
}
|
|
619
|
+
return Object.keys(matcher).length ? matcher : null;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
function normalizeRule(raw, order, line) {
|
|
623
|
+
const id = textOr(raw.id);
|
|
624
|
+
const match = raw.match && typeof raw.match === 'object' ? raw.match : {};
|
|
625
|
+
const keywords = Array.isArray(match.keywords)
|
|
626
|
+
? match.keywords.filter((k) => typeof k === 'string' && k.trim()).map((k) => k.trim())
|
|
627
|
+
: [];
|
|
628
|
+
const notKeywords = Array.isArray(match.notKeywords)
|
|
629
|
+
? match.notKeywords.filter((k) => typeof k === 'string' && k.trim()).map((k) => k.trim())
|
|
630
|
+
: [];
|
|
631
|
+
const requireKeywords = Array.isArray(match.requireKeywords)
|
|
632
|
+
? match.requireKeywords.filter((k) => typeof k === 'string' && k.trim()).map((k) => k.trim())
|
|
633
|
+
: [];
|
|
634
|
+
const matchTool = textOr(match.tool) || null;
|
|
635
|
+
const level = textOr(raw.level).toUpperCase();
|
|
636
|
+
return Object.freeze({
|
|
637
|
+
id,
|
|
638
|
+
order,
|
|
639
|
+
line,
|
|
640
|
+
priority: raw.priority,
|
|
641
|
+
category: textOr(raw.category),
|
|
642
|
+
level: LEVELS.includes(level) ? level : 'X',
|
|
643
|
+
kind: (textOr(match.kind) || '*').toLowerCase(),
|
|
644
|
+
keywords,
|
|
645
|
+
keywordKeys: keywords.map((k) => k.toLowerCase()),
|
|
646
|
+
notKeywords,
|
|
647
|
+
notKeywordKeys: notKeywords.map((k) => k.toLowerCase()),
|
|
648
|
+
requireKeywords,
|
|
649
|
+
requireKeys: requireKeywords.map((k) => k.toLowerCase()),
|
|
650
|
+
matchTool,
|
|
651
|
+
matchToolKey: matchTool ? matchTool.toLowerCase() : null,
|
|
652
|
+
matchCtx: normalizeCtxMatcher(match.ctx || {}),
|
|
653
|
+
ctxOnly: match.ctxOnly === true,
|
|
654
|
+
before: (raw.before || []).map(normalizeTemplate),
|
|
655
|
+
decision: normalizeTemplate(raw.decision),
|
|
656
|
+
after: (raw.after || []).map(normalizeTemplate),
|
|
657
|
+
reason: typeof raw.reason === 'string' ? raw.reason : '',
|
|
658
|
+
policyRef: textOr(raw.policyRef),
|
|
659
|
+
policyTitle: textOr(raw.policyTitle),
|
|
660
|
+
policyQuote: textOr(raw.policyQuote),
|
|
661
|
+
target: textOr(raw.decision.target),
|
|
662
|
+
tool: normalizeTemplate(raw.decision).tool,
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* 校验整张规则表:任何一条规则有任何字段问题 → 整表拒收(不静默丢单条规则)。
|
|
668
|
+
* @returns {{rules: Array, errors: Array}}
|
|
669
|
+
*/
|
|
670
|
+
export function validateRuleTable(table, text = '', options = {}) {
|
|
671
|
+
const errors = [];
|
|
672
|
+
if (!table || typeof table !== 'object' || Array.isArray(table)) {
|
|
673
|
+
return { rules: [], errors: [makeError(ERROR_CODES.RULES_INVALID, 'routing-rules.json 顶层必须是对象')] };
|
|
674
|
+
}
|
|
675
|
+
if (!Array.isArray(table.rules)) {
|
|
676
|
+
return { rules: [], errors: [makeError(ERROR_CODES.RULES_INVALID, 'routing-rules.json 的 rules 必须是数组')] };
|
|
677
|
+
}
|
|
678
|
+
if (table.rules.length === 0) {
|
|
679
|
+
return { rules: [], errors: [makeError(ERROR_CODES.RULES_INVALID, 'routing-rules.json 没有任何规则:空表等于放行一切,拒绝')] };
|
|
680
|
+
}
|
|
681
|
+
const policy = options.policy || basePolicy();
|
|
682
|
+
const maxRules = policy && policy.limits ? policy.limits.maxRules : LIMITS.maxRules;
|
|
683
|
+
if (table.rules.length > maxRules) {
|
|
684
|
+
return {
|
|
685
|
+
rules: [],
|
|
686
|
+
errors: [makeError(ERROR_CODES.EXPLOSION, `规则表 ${table.rules.length} 条,超过上限 ${maxRules}`, {
|
|
687
|
+
count: table.rules.length,
|
|
688
|
+
limit: maxRules,
|
|
689
|
+
})],
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
const lines = ruleLines(text);
|
|
694
|
+
const seen = new Set();
|
|
695
|
+
const rules = [];
|
|
696
|
+
table.rules.forEach((raw, index) => {
|
|
697
|
+
const ruleId = raw && typeof raw === 'object' && typeof raw.id === 'string' ? raw.id.trim() : null;
|
|
698
|
+
const where = `rules[${index}]${ruleId ? `(${ruleId})` : ''}`;
|
|
699
|
+
const local = [];
|
|
700
|
+
const push = (code, message) => local.push(makeError(code, message, ruleId ? { ruleId } : {}));
|
|
701
|
+
|
|
702
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
703
|
+
errors.push(makeError(ERROR_CODES.RULE_FIELD, `${where} 必须是对象`, { index }));
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
if (!ruleId) push(ERROR_CODES.RULE_FIELD, `${where} 缺 id`);
|
|
707
|
+
else if (seen.has(ruleId)) push(ERROR_CODES.RULE_FIELD, `${where} id 重复:${ruleId}`);
|
|
708
|
+
if (ruleId) seen.add(ruleId);
|
|
709
|
+
|
|
710
|
+
if (typeof raw.priority !== 'number' || !Number.isFinite(raw.priority)) {
|
|
711
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.priority 必须是有限数字`);
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
const match = raw.match;
|
|
715
|
+
let ctxValid = false;
|
|
716
|
+
if (!match || typeof match !== 'object' || Array.isArray(match)) {
|
|
717
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.match 必须是对象`);
|
|
718
|
+
} else {
|
|
719
|
+
if (match.kind !== undefined && typeof match.kind !== 'string') {
|
|
720
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.match.kind 必须是字符串`);
|
|
721
|
+
}
|
|
722
|
+
let keywordCount = 0;
|
|
723
|
+
if (match.keywords !== undefined) {
|
|
724
|
+
if (!Array.isArray(match.keywords) || match.keywords.some((k) => typeof k !== 'string' || !k.trim())) {
|
|
725
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.match.keywords 必须是非空字符串数组`);
|
|
726
|
+
} else {
|
|
727
|
+
keywordCount = match.keywords.length;
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
if (match.notKeywords !== undefined) {
|
|
731
|
+
if (!Array.isArray(match.notKeywords) || match.notKeywords.some((k) => typeof k !== 'string' || !k.trim())) {
|
|
732
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.match.notKeywords 必须是非空字符串数组`);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
// requireKeywords:与 keywords 的「或」不同,这是「且」门——至少命中其中一个才
|
|
736
|
+
// 算命中本规则。用于同一 tool 下按参数形态分流(dry-run / confirm / locked),
|
|
737
|
+
// 否则 match.tool 会短路 keywords,优先级最高的那条会吃掉该工具的所有调用。
|
|
738
|
+
if (match.requireKeywords !== undefined) {
|
|
739
|
+
if (!Array.isArray(match.requireKeywords) || match.requireKeywords.some((k) => typeof k !== 'string' || !k.trim())) {
|
|
740
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.match.requireKeywords 必须是非空字符串数组`);
|
|
741
|
+
} else {
|
|
742
|
+
keywordCount += match.requireKeywords.length;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (match.tool !== undefined && typeof match.tool !== 'string') {
|
|
746
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.match.tool 必须是字符串`);
|
|
747
|
+
}
|
|
748
|
+
ctxValid = validateCtxMatcher(match.ctx, push, `${where}.match.ctx`);
|
|
749
|
+
if (match.ctxOnly !== undefined && typeof match.ctxOnly !== 'boolean') {
|
|
750
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.match.ctxOnly 必须是布尔`);
|
|
751
|
+
}
|
|
752
|
+
if (match.ctxOnly === true && !ctxValid) {
|
|
753
|
+
push(ERROR_CODES.RULE_FIELD, `${where} 是 ctxOnly 但没有可用的 match.ctx`);
|
|
754
|
+
}
|
|
755
|
+
const toolHit = typeof match.tool === 'string' && match.tool.trim();
|
|
756
|
+
if (keywordCount === 0 && !toolHit && !ctxValid) {
|
|
757
|
+
push(ERROR_CODES.RULE_FIELD, `${where} 没有任何匹配条件(keywords/tool/ctx 全空),永远不可能命中`);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
const decision = validateTemplate(raw.decision, `${where}.decision`, policy, push);
|
|
762
|
+
for (const key of ['before', 'after']) {
|
|
763
|
+
if (raw[key] === undefined) continue;
|
|
764
|
+
if (!Array.isArray(raw[key])) {
|
|
765
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.${key} 必须是数组`);
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
raw[key].forEach((template, templateIndex) => {
|
|
769
|
+
validateTemplate(template, `${where}.${key}[${templateIndex}]`, policy, push);
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
if (raw.level !== undefined) {
|
|
773
|
+
const level = typeof raw.level === 'string' ? raw.level.trim().toUpperCase() : '';
|
|
774
|
+
if (!LEVELS.includes(level)) push(ERROR_CODES.RULE_FIELD, `${where}.level 未知:${raw.level}`);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
if (local.length === 0 && decision) {
|
|
778
|
+
rules.push(normalizeRule(raw, index, lines.get(ruleId) || 0));
|
|
779
|
+
}
|
|
780
|
+
errors.push(...local);
|
|
781
|
+
});
|
|
782
|
+
|
|
783
|
+
// 兜底规则(策略 5):不进优先级队列,0 命中时由 route 的兜底分支直接取用。
|
|
784
|
+
const fallbacks = [];
|
|
785
|
+
if (table.fallbacks !== undefined) {
|
|
786
|
+
if (!Array.isArray(table.fallbacks)) {
|
|
787
|
+
errors.push(makeError(ERROR_CODES.RULES_INVALID, 'fallbacks 必须是数组'));
|
|
788
|
+
} else {
|
|
789
|
+
table.fallbacks.forEach((raw, index) => {
|
|
790
|
+
const where = `fallbacks[${index}]`;
|
|
791
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
792
|
+
errors.push(makeError(ERROR_CODES.RULE_FIELD, `${where} 必须是对象`));
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
const id = textOr(raw.id);
|
|
796
|
+
const local = [];
|
|
797
|
+
const push = (code, message) => local.push(makeError(code, message, id ? { ruleId: id } : { index }));
|
|
798
|
+
if (!id) push(ERROR_CODES.RULE_FIELD, `${where} 缺 id`);
|
|
799
|
+
else if (seen.has(id)) push(ERROR_CODES.RULE_FIELD, `${where} id 与规则表重复:${id}`);
|
|
800
|
+
if (id) seen.add(id);
|
|
801
|
+
if (!raw.decision || typeof raw.decision !== 'object' || Array.isArray(raw.decision)) {
|
|
802
|
+
push(ERROR_CODES.RULE_FIELD, `${where}.decision 必须是对象`);
|
|
803
|
+
} else {
|
|
804
|
+
validateTemplate(raw.decision, `${where}.decision`, policy, push);
|
|
805
|
+
}
|
|
806
|
+
if (!textOr(raw.reason)) push(ERROR_CODES.RULE_FIELD, `${where}.reason 不能为空`);
|
|
807
|
+
if (!textOr(raw.policyRef)) push(ERROR_CODES.RULE_FIELD, `${where}.policyRef 不能为空`);
|
|
808
|
+
if (!textOr(raw.policyTitle)) push(ERROR_CODES.RULE_FIELD, `${where}.policyTitle 不能为空`);
|
|
809
|
+
if (!textOr(raw.policyQuote)) push(ERROR_CODES.RULE_FIELD, `${where}.policyQuote 不能为空`);
|
|
810
|
+
if (local.length === 0) {
|
|
811
|
+
fallbacks.push(Object.freeze({
|
|
812
|
+
id,
|
|
813
|
+
order: index,
|
|
814
|
+
line: lines.get(id) || 0,
|
|
815
|
+
priority: 0,
|
|
816
|
+
category: textOr(raw.category),
|
|
817
|
+
level: LEVELS.includes(textOr(raw.level).toUpperCase()) ? textOr(raw.level).toUpperCase() : 'X',
|
|
818
|
+
kind: '*',
|
|
819
|
+
keywords: [],
|
|
820
|
+
keywordKeys: [],
|
|
821
|
+
notKeywords: [],
|
|
822
|
+
notKeywordKeys: [],
|
|
823
|
+
matchTool: null,
|
|
824
|
+
matchToolKey: null,
|
|
825
|
+
matchCtx: null,
|
|
826
|
+
ctxOnly: false,
|
|
827
|
+
before: [],
|
|
828
|
+
decision: normalizeTemplate(raw.decision),
|
|
829
|
+
after: [],
|
|
830
|
+
reason: textOr(raw.reason),
|
|
831
|
+
policyRef: textOr(raw.policyRef),
|
|
832
|
+
policyTitle: textOr(raw.policyTitle),
|
|
833
|
+
policyQuote: textOr(raw.policyQuote),
|
|
834
|
+
target: textOr(raw.decision.target),
|
|
835
|
+
tool: normalizeTemplate(raw.decision).tool,
|
|
836
|
+
fallback: true,
|
|
837
|
+
}));
|
|
838
|
+
}
|
|
839
|
+
errors.push(...local);
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
if (errors.length) return { rules: [], fallbacks: [], errors };
|
|
845
|
+
rules.sort((a, b) => (b.priority - a.priority) || (a.order - b.order));
|
|
846
|
+
return { rules, fallbacks, errors: [] };
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/** 解析规则表文本并整表校验;JSON 损坏也是一个明确错误码,不是空表。 */
|
|
850
|
+
export function parseRuleTable(text, options = {}) {
|
|
851
|
+
let table;
|
|
852
|
+
try {
|
|
853
|
+
table = JSON.parse(text);
|
|
854
|
+
} catch (cause) {
|
|
855
|
+
return { rules: [], errors: [makeError(ERROR_CODES.RULES_INVALID, `routing-rules.json JSON 解析失败:${cause.message}`)] };
|
|
856
|
+
}
|
|
857
|
+
const policy = options.policy || basePolicy();
|
|
858
|
+
let expanded;
|
|
859
|
+
try {
|
|
860
|
+
expanded = expandPolicyRefs(table, policy);
|
|
861
|
+
} catch (cause) {
|
|
862
|
+
return { rules: [], errors: [makeError(ERROR_CODES.POLICY_INVALID, `策略引用展开失败:${cause && cause.message ? cause.message : String(cause)}`)] };
|
|
863
|
+
}
|
|
864
|
+
const result = validateRuleTable(expanded, text, { ...options, policy });
|
|
865
|
+
return { ...result, fallbacks: result.fallbacks || [] };
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// M2-E:把 adapter 提供的规则按原表顺序插回核心规则表(_order = 迁移前下标)。
|
|
869
|
+
// 数据不可用/结构异常时 fail-safe:只用核心规则,degraded 记录在 ADAPTER_DEGRADED。
|
|
870
|
+
// adapter 规则的定义行/文件:evidence 必须能回到真实文件,而不是核心规则表。
|
|
871
|
+
const ADAPTER_RULE_META = (() => {
|
|
872
|
+
const lines = new Map();
|
|
873
|
+
const sources = new Map();
|
|
874
|
+
for (const item of ADAPTER_ROUTING.items || []) {
|
|
875
|
+
const text = typeof item.text === 'string' ? item.text : '';
|
|
876
|
+
const sourcePath = typeof item.sourcePath === 'string' ? item.sourcePath : '';
|
|
877
|
+
for (const [id, line] of ruleLines(text)) {
|
|
878
|
+
if (!lines.has(id)) lines.set(id, line);
|
|
879
|
+
if (sourcePath && !sources.has(id)) sources.set(id, sourcePath);
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
return { lines, sources };
|
|
883
|
+
})();
|
|
884
|
+
|
|
885
|
+
function attachAdapterRuleMeta(rules) {
|
|
886
|
+
return rules.map((rule) => {
|
|
887
|
+
const line = ADAPTER_RULE_META.lines.get(rule.id);
|
|
888
|
+
if (!line) return rule;
|
|
889
|
+
const sourcePath = ADAPTER_RULE_META.sources.get(rule.id) || RULE_TABLE_PATH;
|
|
890
|
+
return Object.freeze({ ...rule, line, sourcePath });
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
function mergeAdapterRuleTable(table, coreText = '') {
|
|
895
|
+
const coreRules = Array.isArray(table.rules) ? table.rules : [];
|
|
896
|
+
const loaded = ADAPTER_ROUTING;
|
|
897
|
+
// 核心表本身坏了(rules 非数组/空表)时不要把 adapter 规则补进去掩盖故障:
|
|
898
|
+
// 让核心校验按原来的 fail-closed 语义报错。
|
|
899
|
+
if (!Array.isArray(table.rules) || table.rules.length === 0) {
|
|
900
|
+
return { table, text: coreText };
|
|
901
|
+
}
|
|
902
|
+
if (!loaded.ok || !Array.isArray(loaded.rules) || loaded.rules.length === 0) {
|
|
903
|
+
return { table, text: coreText };
|
|
904
|
+
}
|
|
905
|
+
const adapterByOrder = new Map();
|
|
906
|
+
for (const rule of loaded.rules) {
|
|
907
|
+
const order = rule && Number.isInteger(rule._order) ? rule._order : null;
|
|
908
|
+
if (order === null || adapterByOrder.has(order)) continue;
|
|
909
|
+
const clean = { ...rule };
|
|
910
|
+
delete clean._order;
|
|
911
|
+
adapterByOrder.set(order, clean);
|
|
912
|
+
}
|
|
913
|
+
const mergedRules = [];
|
|
914
|
+
let cursor = 0;
|
|
915
|
+
const total = coreRules.length + adapterByOrder.size;
|
|
916
|
+
for (let index = 0; index < total; index += 1) {
|
|
917
|
+
if (adapterByOrder.has(index)) mergedRules.push(adapterByOrder.get(index));
|
|
918
|
+
else if (cursor < coreRules.length) mergedRules.push(coreRules[cursor++]);
|
|
919
|
+
}
|
|
920
|
+
while (cursor < coreRules.length) mergedRules.push(coreRules[cursor++]);
|
|
921
|
+
const adapterTargets = (loaded.targets || []).filter((target) => typeof target === 'string');
|
|
922
|
+
const targets = Array.isArray(table.targets) ? [...new Set([...table.targets, ...adapterTargets])] : table.targets;
|
|
923
|
+
const mergedTable = { ...table, targets, rules: mergedRules };
|
|
924
|
+
// 行号映射:核心表在前、adapter 规则行号不可考时给 0(evidence 里保留 ruleId 仍可审计)。
|
|
925
|
+
let text = coreText + '\n' + JSON.stringify({ rules: mergedRules.slice(coreRules.length) });
|
|
926
|
+
return { table: mergedTable, text };
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
function loadRulesResult() {
|
|
930
|
+
// 别名不可用时不再逐条报「未知 action」:那只是同一个根因的 17 次回声。
|
|
931
|
+
if (ALIASES.errors.length) return { rules: [], fallbacks: [], errors: [] };
|
|
932
|
+
if (!GENERIC_LOAD.ok) return { rules: [], fallbacks: [], errors: [] };
|
|
933
|
+
let text = '';
|
|
934
|
+
try {
|
|
935
|
+
text = readFileSync(RULES_URL, 'utf8');
|
|
936
|
+
} catch (cause) {
|
|
937
|
+
return {
|
|
938
|
+
rules: [],
|
|
939
|
+
errors: [makeError(ERROR_CODES.RULES_UNAVAILABLE, `routing-rules.json 读取失败:${cause.code || cause.message},拒绝路由`)],
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
let table;
|
|
943
|
+
try {
|
|
944
|
+
table = JSON.parse(text);
|
|
945
|
+
} catch (cause) {
|
|
946
|
+
return { rules: [], fallbacks: [], errors: [makeError(ERROR_CODES.RULES_INVALID, `routing-rules.json JSON 解析失败:${cause.message}`)] };
|
|
947
|
+
}
|
|
948
|
+
RULE_TABLE_RAW = table;
|
|
949
|
+
RULE_TABLE_TEXT = text;
|
|
950
|
+
const policy = policyFromProfile(GENERIC_LOAD.policy);
|
|
951
|
+
try {
|
|
952
|
+
const merged = mergeAdapterRuleTable(table, text);
|
|
953
|
+
RULE_TABLE_RAW = merged.table;
|
|
954
|
+
RULE_TABLE_TEXT = merged.text;
|
|
955
|
+
const expanded = expandPolicyRefs(merged.table, policy);
|
|
956
|
+
const result = validateRuleTable(expanded, merged.text, { aliases: ALIASES, policy });
|
|
957
|
+
return { ...result, rules: attachAdapterRuleMeta(result.rules), fallbacks: result.fallbacks || [] };
|
|
958
|
+
} catch (cause) {
|
|
959
|
+
return {
|
|
960
|
+
rules: [],
|
|
961
|
+
fallbacks: [],
|
|
962
|
+
errors: [makeError(ERROR_CODES.POLICY_INVALID, `策略引用展开失败:${cause && cause.message ? cause.message : String(cause)}`)],
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
const RULES_RESULT = loadRulesResult();
|
|
968
|
+
|
|
969
|
+
// 读表 + 整表校验 + 排序。导出给测试做规则表完整性断言。
|
|
970
|
+
export function loadRules() {
|
|
971
|
+
return RULES_RESULT.rules;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
export const RULES = Object.freeze(RULES_RESULT.rules);
|
|
975
|
+
|
|
976
|
+
// 兜底规则(策略 5):R-SES-ASK 不在 RULES 里,不参与优先级竞争,0 命中时单独取用。
|
|
977
|
+
export const FALLBACKS = Object.freeze(RULES_RESULT.fallbacks || []);
|
|
978
|
+
|
|
979
|
+
const ASK_FALLBACK = FALLBACKS.find((rule) => rule.id === 'R-SES-ASK') || null;
|
|
980
|
+
// 模块加载期就存在的拒绝理由(文件缺失/损坏/字段错误)。route() 每次调用都先看它。
|
|
981
|
+
export const LOAD_ERRORS = Object.freeze([
|
|
982
|
+
...(GENERIC_LOAD.ok ? [] : [makeError(GENERIC_LOAD.code, GENERIC_LOAD.message)]),
|
|
983
|
+
...ALIASES.errors,
|
|
984
|
+
...RULES_RESULT.errors,
|
|
985
|
+
]);
|
|
986
|
+
|
|
987
|
+
export function ruleById(id) {
|
|
988
|
+
const runtime = ACTIVE_RUNTIME || runtimeFor(POLICY_PROFILE_DEFAULT);
|
|
989
|
+
if (runtime.byId.has(id)) return runtime.byId.get(id);
|
|
990
|
+
return RULES.find((rule) => rule.id === id) || FALLBACKS.find((rule) => rule.id === id) || null;
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
// 通用默认策略编译出的 ctx 阈值/白名单(judge 与 CLI 的通用基线)。
|
|
994
|
+
export function loadPolicy() {
|
|
995
|
+
return basePolicy();
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
export const POLICY = Object.freeze(basePolicy());
|
|
999
|
+
|
|
1000
|
+
// 兼容导出:generic 基线的休息/终止词表;route 内部始终用生效 profile。
|
|
1001
|
+
export const REST_RE = markersRegex(POLICY.rest.markers) || /(?!)/;
|
|
1002
|
+
export const STOP_RE = markersRegex(POLICY.rest.terminators) || /(?!)/;
|
|
1003
|
+
|
|
1004
|
+
// ── 输入读取 ─────────────────────────────────────────────────
|
|
1005
|
+
|
|
1006
|
+
function readInput(input) {
|
|
1007
|
+
if (!input || typeof input !== 'object') return { kind: '', text: '' };
|
|
1008
|
+
let kind = '';
|
|
1009
|
+
let text = '';
|
|
1010
|
+
try {
|
|
1011
|
+
kind = typeof input.kind === 'string' ? input.kind.trim().toLowerCase() : '';
|
|
1012
|
+
const raw = input.text !== undefined ? input.text : input.utterance;
|
|
1013
|
+
if (typeof raw === 'string') text = raw;
|
|
1014
|
+
else if (typeof raw === 'number' || typeof raw === 'boolean') text = String(raw);
|
|
1015
|
+
} catch {
|
|
1016
|
+
return { kind: '', text: '' };
|
|
1017
|
+
}
|
|
1018
|
+
return { kind, text };
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
function readCandidates(input) {
|
|
1022
|
+
if (!input || typeof input !== 'object' || !Array.isArray(input.candidates)) return [];
|
|
1023
|
+
const out = [];
|
|
1024
|
+
for (const candidate of input.candidates.slice(0, 64)) {
|
|
1025
|
+
if (typeof candidate === 'string') {
|
|
1026
|
+
const name = candidate.trim();
|
|
1027
|
+
if (name) out.push(name.toLowerCase());
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
if (candidate && typeof candidate === 'object') {
|
|
1031
|
+
const name = textOr(candidate.tool) || textOr(candidate.name);
|
|
1032
|
+
if (name) out.push(name.toLowerCase());
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
return out;
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
/**
|
|
1039
|
+
* 读 ctx,同时把「缺字段」与「类型错」记下来——这两类绝不能被当成「没命中」。
|
|
1040
|
+
* @returns {{ctx: object, raw: object|null, problems: Array<{code,field,message,got?}>}}
|
|
1041
|
+
*/
|
|
1042
|
+
export function readCtxReport(input) {
|
|
1043
|
+
const ctx = {};
|
|
1044
|
+
const problems = [];
|
|
1045
|
+
let raw = null;
|
|
1046
|
+
if (!input || typeof input !== 'object') return { ctx, raw, problems };
|
|
1047
|
+
try {
|
|
1048
|
+
raw = input.ctx;
|
|
1049
|
+
} catch {
|
|
1050
|
+
return { ctx, raw: null, problems };
|
|
1051
|
+
}
|
|
1052
|
+
if (raw === undefined || raw === null) return { ctx, raw: null, problems };
|
|
1053
|
+
if (typeof raw !== 'object' || Array.isArray(raw)) {
|
|
1054
|
+
problems.push(makeError(ERROR_CODES.CTX_TYPE, `ctx 必须是对象,收到 ${raw === null ? 'null' : typeof raw}`, {
|
|
1055
|
+
field: 'ctx',
|
|
1056
|
+
got: Array.isArray(raw) ? 'array' : typeof raw,
|
|
1057
|
+
}));
|
|
1058
|
+
return { ctx, raw: null, problems };
|
|
1059
|
+
}
|
|
1060
|
+
for (const key of ['tokens', 'activeWorkers', 'openRows']) {
|
|
1061
|
+
const value = safeGet(raw, key);
|
|
1062
|
+
if (value === undefined || value === null) continue;
|
|
1063
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
1064
|
+
ctx[key] = value;
|
|
1065
|
+
continue;
|
|
1066
|
+
}
|
|
1067
|
+
problems.push(makeError(ERROR_CODES.CTX_TYPE, `ctx.${key} 必须是有限数字,收到 ${Array.isArray(value) ? 'array' : typeof value}`, {
|
|
1068
|
+
field: key,
|
|
1069
|
+
got: Array.isArray(value) ? 'array' : typeof value,
|
|
1070
|
+
}));
|
|
1071
|
+
}
|
|
1072
|
+
const zone = safeGet(raw, 'zone');
|
|
1073
|
+
if (zone !== undefined && zone !== null) {
|
|
1074
|
+
if (typeof zone === 'string' && zone.trim()) ctx.zone = zone.trim().toLowerCase();
|
|
1075
|
+
else {
|
|
1076
|
+
problems.push(makeError(ERROR_CODES.CTX_TYPE, `ctx.zone 必须是非空字符串,收到 ${Array.isArray(zone) ? 'array' : typeof zone}`, {
|
|
1077
|
+
field: 'zone',
|
|
1078
|
+
got: Array.isArray(zone) ? 'array' : typeof zone,
|
|
1079
|
+
}));
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
return { ctx, raw, problems };
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
function readCtx(input) {
|
|
1086
|
+
return readCtxReport(input).ctx;
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
// override 只有同时给出 ruleId 与 reason 才留痕;没有理由的偏离直接丢弃并计
|
|
1090
|
+
// E_ROUTE_OVERRIDE_UNJUSTIFIED——"悄悄绕开规则"不能是一种可用写法。
|
|
1091
|
+
function readOverrides(input) {
|
|
1092
|
+
const applied = [];
|
|
1093
|
+
const rejected = [];
|
|
1094
|
+
if (!input || typeof input !== 'object') return { applied, rejected };
|
|
1095
|
+
let raw;
|
|
1096
|
+
try {
|
|
1097
|
+
raw = Array.isArray(input.overrides) ? input.overrides : (input.override ? [input.override] : []);
|
|
1098
|
+
} catch {
|
|
1099
|
+
return { applied, rejected };
|
|
1100
|
+
}
|
|
1101
|
+
for (const entry of raw) {
|
|
1102
|
+
if (!entry || typeof entry !== 'object') continue;
|
|
1103
|
+
const ruleId = textOr(entry.ruleId);
|
|
1104
|
+
const reason = textOr(entry.reason);
|
|
1105
|
+
if (!ruleId || !reason) {
|
|
1106
|
+
rejected.push({
|
|
1107
|
+
ruleId: ruleId || null,
|
|
1108
|
+
reason: reason || '',
|
|
1109
|
+
code: ERROR_CODES.OVERRIDE_UNJUSTIFIED,
|
|
1110
|
+
message: 'override 缺 ruleId 或 reason:拒绝并丢弃,判定不变',
|
|
1111
|
+
});
|
|
1112
|
+
continue;
|
|
1113
|
+
}
|
|
1114
|
+
applied.push({
|
|
1115
|
+
ruleId,
|
|
1116
|
+
reason,
|
|
1117
|
+
by: textOr(entry.by) || 'caller',
|
|
1118
|
+
at: textOr(entry.at) || null,
|
|
1119
|
+
action: textOr(entry.action) || null,
|
|
1120
|
+
});
|
|
1121
|
+
}
|
|
1122
|
+
return { applied, rejected };
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
// ── 匹配 ─────────────────────────────────────────────────────
|
|
1126
|
+
|
|
1127
|
+
function countKeyHits(keys, normalized) {
|
|
1128
|
+
let hits = 0;
|
|
1129
|
+
for (const key of keys) {
|
|
1130
|
+
if (normalized.includes(key)) hits += 1;
|
|
1131
|
+
}
|
|
1132
|
+
return hits;
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
function countKeywordHits(rule, normalized) {
|
|
1136
|
+
return countKeyHits(rule.keywordKeys, normalized);
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
function evaluateCtx(matcher, ctx) {
|
|
1140
|
+
if (!matcher) return null;
|
|
1141
|
+
if (typeof matcher.tokensGte === 'number') {
|
|
1142
|
+
if (typeof ctx.tokens !== 'number' || ctx.tokens < matcher.tokensGte) return false;
|
|
1143
|
+
}
|
|
1144
|
+
if (typeof matcher.activeWorkersGte === 'number') {
|
|
1145
|
+
if (typeof ctx.activeWorkers !== 'number' || ctx.activeWorkers < matcher.activeWorkersGte) return false;
|
|
1146
|
+
}
|
|
1147
|
+
if (typeof matcher.openRowsGte === 'number') {
|
|
1148
|
+
if (typeof ctx.openRows !== 'number' || ctx.openRows < matcher.openRowsGte) return false;
|
|
1149
|
+
}
|
|
1150
|
+
if (Array.isArray(matcher.zoneIn)) {
|
|
1151
|
+
if (typeof ctx.zone !== 'string' || !matcher.zoneIn.includes(ctx.zone)) return false;
|
|
1152
|
+
}
|
|
1153
|
+
return true;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
function confidenceFor(hits, toolHit, ctxOnly) {
|
|
1157
|
+
if (toolHit) return 1;
|
|
1158
|
+
if (ctxOnly) return 0.9;
|
|
1159
|
+
if (hits >= 2) return 1;
|
|
1160
|
+
return 0.75;
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
const CTX_FIELDS = Object.freeze([
|
|
1164
|
+
['tokensGte', 'tokens', 'number'],
|
|
1165
|
+
['activeWorkersGte', 'activeWorkers', 'number'],
|
|
1166
|
+
['openRowsGte', 'openRows', 'number'],
|
|
1167
|
+
['zoneIn', 'zone', 'string'],
|
|
1168
|
+
]);
|
|
1169
|
+
|
|
1170
|
+
// 关键词命中、但 ctx 字段缺失/类型错:这是输入错误,不是「条件不满足」。
|
|
1171
|
+
function ctxFieldIssues(rule, normalized, ctxReport) {
|
|
1172
|
+
const issues = [];
|
|
1173
|
+
for (const [matcherKey, field, expected] of CTX_FIELDS) {
|
|
1174
|
+
if (typeof rule.matchCtx[matcherKey] === 'undefined') continue;
|
|
1175
|
+
const rawValue = ctxReport.raw && typeof ctxReport.raw === 'object' ? safeGet(ctxReport.raw, field) : undefined;
|
|
1176
|
+
if (rawValue === undefined || rawValue === null) {
|
|
1177
|
+
issues.push(makeError(ERROR_CODES.CTX_MISSING, `规则 ${rule.id} 关键词命中,但 ctx.${field} 缺失:不能当成没命中`, {
|
|
1178
|
+
ruleId: rule.id,
|
|
1179
|
+
field,
|
|
1180
|
+
}));
|
|
1181
|
+
continue;
|
|
1182
|
+
}
|
|
1183
|
+
if (expected === 'number' ? !(typeof rawValue === 'number' && Number.isFinite(rawValue)) : typeof rawValue !== 'string') {
|
|
1184
|
+
issues.push(makeError(ERROR_CODES.CTX_TYPE, `规则 ${rule.id} 关键词命中,但 ctx.${field} 类型错误(应为 ${expected},收到 ${typeof rawValue})`, {
|
|
1185
|
+
ruleId: rule.id,
|
|
1186
|
+
field,
|
|
1187
|
+
got: Array.isArray(rawValue) ? 'array' : typeof rawValue,
|
|
1188
|
+
}));
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
return issues;
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
function collectCtxIssues(parsed, minPriority = -Infinity) {
|
|
1195
|
+
const issues = [];
|
|
1196
|
+
const normalized = parsed.text.trim().toLowerCase();
|
|
1197
|
+
for (const rule of activeRuntime().rules) {
|
|
1198
|
+
if (!rule.matchCtx || rule.ctxOnly) continue;
|
|
1199
|
+
if (parsed.kind && rule.kind !== '*' && rule.kind !== parsed.kind) continue;
|
|
1200
|
+
// 只追「可能改变结果」的那部分:比当前胜出规则更低优先级的门控规则,
|
|
1201
|
+
// 本来就不会被选中,它的 ctx 缺失不构成歧义(否则一个普通词就会误伤整单)。
|
|
1202
|
+
if (rule.priority < minPriority) continue;
|
|
1203
|
+
if (countKeywordHits(rule, normalized) === 0 && countKeyHits(rule.requireKeys, normalized) === 0) continue;
|
|
1204
|
+
issues.push(...ctxFieldIssues(rule, normalized, parsed.ctxReport));
|
|
1205
|
+
}
|
|
1206
|
+
return issues;
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
function matchRules(parsed, candidates) {
|
|
1210
|
+
const normalized = parsed.text.trim().toLowerCase();
|
|
1211
|
+
const ctx = parsed.ctx;
|
|
1212
|
+
const matched = [];
|
|
1213
|
+
for (const rule of activeRuntime().rules) {
|
|
1214
|
+
if (parsed.kind && rule.kind !== '*' && rule.kind !== parsed.kind) continue;
|
|
1215
|
+
const hits = countKeywordHits(rule, normalized);
|
|
1216
|
+
const requireHits = countKeyHits(rule.requireKeys, normalized);
|
|
1217
|
+
const toolHit = Boolean(rule.matchToolKey && candidates.includes(rule.matchToolKey));
|
|
1218
|
+
const requireOk = rule.requireKeys.length === 0
|
|
1219
|
+
|| (requireHits > 0 && (!rule.matchToolKey || toolHit));
|
|
1220
|
+
const ctxOk = evaluateCtx(rule.matchCtx, ctx);
|
|
1221
|
+
if (rule.ctxOnly) {
|
|
1222
|
+
if (ctxOk !== true) continue;
|
|
1223
|
+
} else {
|
|
1224
|
+
if (hits === 0 && !toolHit && rule.requireKeys.length === 0) continue;
|
|
1225
|
+
if (!requireOk) continue;
|
|
1226
|
+
if (ctxOk === false) continue;
|
|
1227
|
+
}
|
|
1228
|
+
matched.push({
|
|
1229
|
+
rule,
|
|
1230
|
+
hits: hits + requireHits,
|
|
1231
|
+
toolHit,
|
|
1232
|
+
confidence: confidenceFor(hits + requireHits, toolHit, rule.ctxOnly),
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
return matched;
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
// ── 决定构造 ─────────────────────────────────────────────────
|
|
1239
|
+
|
|
1240
|
+
function clone(value) {
|
|
1241
|
+
return JSON.parse(JSON.stringify(value));
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
function dedupe(list) {
|
|
1245
|
+
const seen = new Set();
|
|
1246
|
+
const out = [];
|
|
1247
|
+
for (const entry of list) {
|
|
1248
|
+
if (typeof entry !== 'string' || !entry || seen.has(entry)) continue;
|
|
1249
|
+
seen.add(entry);
|
|
1250
|
+
out.push(entry);
|
|
1251
|
+
}
|
|
1252
|
+
return out;
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
function buildDecision(template, rule, confidence) {
|
|
1256
|
+
return {
|
|
1257
|
+
kind: template.kind,
|
|
1258
|
+
action: template.action,
|
|
1259
|
+
args: clone(template.args || {}),
|
|
1260
|
+
ruleId: rule.id,
|
|
1261
|
+
evidence: dedupe([
|
|
1262
|
+
...template.evidence,
|
|
1263
|
+
rule.line ? `${rule.sourcePath || RULE_TABLE_PATH}:${rule.line}` : '',
|
|
1264
|
+
rule.policyRef ? `policy:${rule.policyRef}` : '',
|
|
1265
|
+
]),
|
|
1266
|
+
writeScope: template.writeScope.slice(),
|
|
1267
|
+
target: template.target,
|
|
1268
|
+
tool: template.tool,
|
|
1269
|
+
needsHuman: template.needsHuman === true,
|
|
1270
|
+
confidence,
|
|
1271
|
+
};
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
// ctx 参与路由的落点:每个用了的字段都要在 evidence 里留 ctx:<field>。
|
|
1275
|
+
function applyCtxToDecision(decision, ctx) {
|
|
1276
|
+
const args = decision.args;
|
|
1277
|
+
const add = (entry) => {
|
|
1278
|
+
if (!decision.evidence.includes(entry)) decision.evidence.push(entry);
|
|
1279
|
+
};
|
|
1280
|
+
if (decision.action === 'acp_status') {
|
|
1281
|
+
if (typeof ctx.tokens === 'number') {
|
|
1282
|
+
args.tokens = ctx.tokens;
|
|
1283
|
+
add('ctx:tokens');
|
|
1284
|
+
}
|
|
1285
|
+
if (typeof ctx.zone === 'string') {
|
|
1286
|
+
args.zone = ctx.zone;
|
|
1287
|
+
add('ctx:zone');
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
if (decision.action === 'session.handover') {
|
|
1291
|
+
if (typeof ctx.tokens === 'number') {
|
|
1292
|
+
args.tokens = ctx.tokens;
|
|
1293
|
+
add('ctx:tokens');
|
|
1294
|
+
}
|
|
1295
|
+
if (typeof ctx.zone === 'string') {
|
|
1296
|
+
args.zone = ctx.zone;
|
|
1297
|
+
add('ctx:zone');
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
if (decision.action === 'worker_spawn') {
|
|
1301
|
+
if (typeof ctx.activeWorkers === 'number') {
|
|
1302
|
+
add('ctx:activeWorkers');
|
|
1303
|
+
if (ctx.activeWorkers >= activeRuntime().policy.dispatchAt) {
|
|
1304
|
+
args.pool = 'existing';
|
|
1305
|
+
args.activeWorkers = ctx.activeWorkers;
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
if (typeof ctx.openRows === 'number') {
|
|
1309
|
+
add('ctx:openRows');
|
|
1310
|
+
args.openRows = ctx.openRows;
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
if (decision.action === 'taskboard.update') {
|
|
1314
|
+
if (typeof ctx.openRows === 'number') {
|
|
1315
|
+
add('ctx:openRows');
|
|
1316
|
+
args.openRows = ctx.openRows;
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
if (decision.action === 'session.compact') {
|
|
1320
|
+
if (typeof ctx.tokens === 'number') {
|
|
1321
|
+
args.tokens = ctx.tokens;
|
|
1322
|
+
add('ctx:tokens');
|
|
1323
|
+
}
|
|
1324
|
+
if (typeof ctx.zone === 'string') {
|
|
1325
|
+
args.zone = ctx.zone;
|
|
1326
|
+
add('ctx:zone');
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
return decision;
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
// 纯 ctx 叠加建议:不抢主决策,只在其后追加"该收口了"的动作。
|
|
1333
|
+
function ctxOverlays(ctx, decisions) {
|
|
1334
|
+
const overlays = [];
|
|
1335
|
+
const has = (action) => decisions.some((decision) => decision.action === action);
|
|
1336
|
+
const tokens = typeof ctx.tokens === 'number' ? ctx.tokens : null;
|
|
1337
|
+
const policy = activeRuntime().policy;
|
|
1338
|
+
const red = ctx.zone === 'red' || (tokens !== null && tokens >= policy.redAt);
|
|
1339
|
+
|
|
1340
|
+
if (red && !has('session.handover')) {
|
|
1341
|
+
const rule = ruleById('R-SES-RED');
|
|
1342
|
+
if (rule) {
|
|
1343
|
+
const prelude = rule.before.find((item) => item.action === 'acp_status');
|
|
1344
|
+
if (prelude && !has('acp_status')) {
|
|
1345
|
+
overlays.push(applyCtxToDecision(buildDecision(prelude, rule, 0.9), ctx));
|
|
1346
|
+
}
|
|
1347
|
+
overlays.push(applyCtxToDecision(buildDecision(rule.decision, rule, 0.9), ctx));
|
|
1348
|
+
}
|
|
1349
|
+
return overlays;
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
const yellow = ctx.zone === 'yellow' || (tokens !== null && tokens >= policy.compressAt);
|
|
1353
|
+
if (yellow && !has('session.compact') && !has('session.handover')) {
|
|
1354
|
+
const rule = ruleById('R-SES-BUDGET');
|
|
1355
|
+
if (rule) overlays.push(applyCtxToDecision(buildDecision(rule.decision, rule, 0.9), ctx));
|
|
1356
|
+
}
|
|
1357
|
+
return overlays;
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
// 严格版:override 必须指向本次决定里真实存在的 ruleId,绝不贴到 decisions[0]。
|
|
1361
|
+
function applyOverrides(decisions, applied) {
|
|
1362
|
+
for (const override of applied) {
|
|
1363
|
+
const target = decisions.find((decision) => decision.ruleId === override.ruleId);
|
|
1364
|
+
if (!target) continue;
|
|
1365
|
+
target.overridden = {
|
|
1366
|
+
ruleId: override.ruleId,
|
|
1367
|
+
reason: override.reason,
|
|
1368
|
+
by: override.by,
|
|
1369
|
+
at: override.at,
|
|
1370
|
+
};
|
|
1371
|
+
if (override.action) {
|
|
1372
|
+
const canonical = canonicalAction(override.action);
|
|
1373
|
+
if (canonical) {
|
|
1374
|
+
target.action = canonical;
|
|
1375
|
+
target.tool = legacyAction(canonical);
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
return decisions;
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
// ── 输出 ─────────────────────────────────────────────────────
|
|
1383
|
+
|
|
1384
|
+
function rejectedErrors(rejected) {
|
|
1385
|
+
return rejected.map((entry) => ({
|
|
1386
|
+
code: entry.code,
|
|
1387
|
+
message: entry.message,
|
|
1388
|
+
ruleId: entry.ruleId,
|
|
1389
|
+
reason: entry.reason,
|
|
1390
|
+
}));
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
function emptyResult(meta, overrides, rejected) {
|
|
1394
|
+
return {
|
|
1395
|
+
caseId: meta.caseId,
|
|
1396
|
+
turn: meta.turn,
|
|
1397
|
+
decisions: [],
|
|
1398
|
+
needsHuman: rejected.length > 0,
|
|
1399
|
+
confidence: 0,
|
|
1400
|
+
matchedRule: null,
|
|
1401
|
+
matchedRules: [],
|
|
1402
|
+
overrides: overrides.slice(),
|
|
1403
|
+
overrideAudit: {
|
|
1404
|
+
applied: overrides.length,
|
|
1405
|
+
rejected: rejected.length,
|
|
1406
|
+
records: overrides.slice(),
|
|
1407
|
+
},
|
|
1408
|
+
errors: rejectedErrors(rejected),
|
|
1409
|
+
decision: { target: 'none', tool: null },
|
|
1410
|
+
target: 'none',
|
|
1411
|
+
tool: null,
|
|
1412
|
+
level: null,
|
|
1413
|
+
ctx: meta.ctx,
|
|
1414
|
+
ruleIds: [],
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
// 出错即停:只给一条 refuse,needsHuman=true,错误码全部带出去。
|
|
1419
|
+
function failClosedResult(meta, overrides, rejected, errors) {
|
|
1420
|
+
// 同一个问题可能同时从全局 ctx 检查和规则门控检查报出来,去重后再暴露给调用方。
|
|
1421
|
+
const allErrors = [...errors, ...rejectedErrors(rejected)];
|
|
1422
|
+
const seen = new Set();
|
|
1423
|
+
const uniqueErrors = allErrors.filter((error) => {
|
|
1424
|
+
const key = `${error.code}\u0000${error.message}`;
|
|
1425
|
+
if (seen.has(key)) return false;
|
|
1426
|
+
seen.add(key);
|
|
1427
|
+
return true;
|
|
1428
|
+
});
|
|
1429
|
+
const codes = Array.from(new Set(uniqueErrors.map((error) => error.code)));
|
|
1430
|
+
const refuse = {
|
|
1431
|
+
kind: 'reply',
|
|
1432
|
+
action: 'guard.refuse',
|
|
1433
|
+
args: { failClosed: true, codes },
|
|
1434
|
+
ruleId: FAILCLOSED_RULE_ID,
|
|
1435
|
+
evidence: codes.map((code) => `fail-closed:${code}`),
|
|
1436
|
+
writeScope: [],
|
|
1437
|
+
target: 'none',
|
|
1438
|
+
tool: null,
|
|
1439
|
+
needsHuman: true,
|
|
1440
|
+
confidence: 0,
|
|
1441
|
+
};
|
|
1442
|
+
return {
|
|
1443
|
+
caseId: meta.caseId,
|
|
1444
|
+
turn: meta.turn,
|
|
1445
|
+
decisions: [refuse],
|
|
1446
|
+
needsHuman: true,
|
|
1447
|
+
confidence: 0,
|
|
1448
|
+
matchedRule: null,
|
|
1449
|
+
matchedRules: [],
|
|
1450
|
+
overrides: overrides.slice(),
|
|
1451
|
+
overrideAudit: {
|
|
1452
|
+
applied: overrides.length,
|
|
1453
|
+
rejected: rejected.length,
|
|
1454
|
+
records: overrides.slice(),
|
|
1455
|
+
},
|
|
1456
|
+
errors: uniqueErrors,
|
|
1457
|
+
decision: { target: 'none', tool: null },
|
|
1458
|
+
target: 'none',
|
|
1459
|
+
tool: null,
|
|
1460
|
+
level: null,
|
|
1461
|
+
ctx: meta.ctx,
|
|
1462
|
+
ruleIds: [FAILCLOSED_RULE_ID],
|
|
1463
|
+
failClosed: true,
|
|
1464
|
+
};
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
function ruleDecisions(rule, confidence, ctx) {
|
|
1468
|
+
const decisions = [];
|
|
1469
|
+
for (const template of rule.before) decisions.push(buildDecision(template, rule, confidence));
|
|
1470
|
+
decisions.push(buildDecision(rule.decision, rule, confidence));
|
|
1471
|
+
for (const template of rule.after) decisions.push(buildDecision(template, rule, confidence));
|
|
1472
|
+
for (const decision of decisions) applyCtxToDecision(decision, ctx);
|
|
1473
|
+
return decisions;
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
// 策略 1:把静态 rest 模板变成真实回复参数——只有 REST_RE 命中且 STOP_RE 不命中才叫「可恢复的暂停」。
|
|
1477
|
+
// 词表、默认 resumePoint 都来自生效 profile(generic 默认;owner 可补充/改写)。
|
|
1478
|
+
function applyRestToDecisions(decisions, normalized) {
|
|
1479
|
+
const restPolicy = activeRuntime().policy.rest;
|
|
1480
|
+
const restRe = markersRegex(restPolicy.markers);
|
|
1481
|
+
const stopRe = markersRegex(restPolicy.terminators);
|
|
1482
|
+
const restHit = restRe ? restRe.test(normalized) : false;
|
|
1483
|
+
const stopHit = stopRe ? stopRe.test(normalized) : false;
|
|
1484
|
+
for (const decision of decisions) {
|
|
1485
|
+
const rest = decision.args && decision.args.rest;
|
|
1486
|
+
if (!rest || typeof rest !== 'object') continue;
|
|
1487
|
+
delete decision.args.rest;
|
|
1488
|
+
if (!restHit || stopHit) continue;
|
|
1489
|
+
decision.args.restKind = rest.kind;
|
|
1490
|
+
decision.args.resumable = rest.resumable === true;
|
|
1491
|
+
decision.args.terminal = rest.terminal === true;
|
|
1492
|
+
decision.args.pendingTask = rest.pendingTask || 'keep';
|
|
1493
|
+
decision.args.resumePoint = typeof rest.resumePoint === 'string' && rest.resumePoint.trim()
|
|
1494
|
+
? rest.resumePoint.trim()
|
|
1495
|
+
: restPolicy.resumePoint;
|
|
1496
|
+
decision.args.forbiddenActions = Array.isArray(rest.forbiddenActions) ? rest.forbiddenActions.slice() : [];
|
|
1497
|
+
}
|
|
1498
|
+
return decisions;
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
// 策略 6:同意权在当前会话的助手本人(consent.holder=assistant)。用户单方面请求(哪怕自己带了 consent 字段)永远不构成同意。
|
|
1502
|
+
// owner profile 可再收窄为「必须引用原话 id(mNNNNN)」。
|
|
1503
|
+
function readAssistantConsent(input, identity = activeRuntime().policy.identity) {
|
|
1504
|
+
const raw = input && typeof input === 'object' ? input.consent : null;
|
|
1505
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
1506
|
+
const holder = typeof raw.holder === 'string' ? raw.holder.trim().toLowerCase() : '';
|
|
1507
|
+
const at = typeof raw.at === 'string' ? raw.at.trim() : '';
|
|
1508
|
+
const quote = typeof raw.quote === 'string' ? raw.quote.trim() : '';
|
|
1509
|
+
const quoteId = typeof raw.quoteId === 'string' ? raw.quoteId.trim() : '';
|
|
1510
|
+
if (holder !== 'assistant' || !at || !quote) return null;
|
|
1511
|
+
if (identity.requireQuoteId === true && !/^m\d{5}$/.test(quoteId)) return null;
|
|
1512
|
+
const granted = { holder: 'assistant', required: true, satisfied: true, at, quote };
|
|
1513
|
+
if (quoteId) granted.quoteId = quoteId;
|
|
1514
|
+
return granted;
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
function applyConsentToDecisions(decisions, input) {
|
|
1518
|
+
if (!decisions.some((decision) => decision.args && decision.args.requiresConsent === true)) return decisions;
|
|
1519
|
+
const granted = readAssistantConsent(input);
|
|
1520
|
+
if (!granted) {
|
|
1521
|
+
const hold = decisions.find((decision) => decision.action === 'identity.hold');
|
|
1522
|
+
if (!hold) return decisions;
|
|
1523
|
+
hold.args.consent = { holder: 'assistant', required: true, satisfied: false };
|
|
1524
|
+
hold.args.errorCode = ERROR_CODES.IDENTITY_CONSENT_REQUIRED;
|
|
1525
|
+
return [hold];
|
|
1526
|
+
}
|
|
1527
|
+
const kept = [];
|
|
1528
|
+
for (const decision of decisions) {
|
|
1529
|
+
if (decision.action === 'identity.hold') continue;
|
|
1530
|
+
if (decision.args && decision.args.requiresConsent === true) {
|
|
1531
|
+
delete decision.args.requiresConsent;
|
|
1532
|
+
decision.args.consent = { ...granted };
|
|
1533
|
+
decision.needsHuman = false;
|
|
1534
|
+
}
|
|
1535
|
+
kept.push(decision);
|
|
1536
|
+
}
|
|
1537
|
+
return kept.length ? kept : decisions;
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
// 策略 5:0 命中兜底——只对会话意图发问;告别/终止语不发问(那不是含糊,是结束)。
|
|
1541
|
+
function askFallbackResult(parsed, normalized) {
|
|
1542
|
+
const runtime = activeRuntime();
|
|
1543
|
+
const rule = runtime.byId.get('R-SES-ASK') || ASK_FALLBACK;
|
|
1544
|
+
const stopRe = markersRegex(runtime.policy.rest.terminators);
|
|
1545
|
+
if (!rule || parsed.kind !== 'session' || !normalized || (stopRe && stopRe.test(normalized))) return null;
|
|
1546
|
+
const decision = buildDecision(rule.decision, rule, 0);
|
|
1547
|
+
return {
|
|
1548
|
+
caseId: parsed.caseId,
|
|
1549
|
+
turn: parsed.turn,
|
|
1550
|
+
decisions: [decision],
|
|
1551
|
+
needsHuman: decision.needsHuman === true,
|
|
1552
|
+
confidence: 0,
|
|
1553
|
+
matchedRule: rule.id,
|
|
1554
|
+
matchedRules: [rule.id],
|
|
1555
|
+
overrides: [],
|
|
1556
|
+
overrideAudit: { applied: 0, rejected: 0, records: [] },
|
|
1557
|
+
errors: [],
|
|
1558
|
+
decision: { target: decision.target, tool: decision.tool ?? null },
|
|
1559
|
+
target: decision.target,
|
|
1560
|
+
tool: decision.tool ?? null,
|
|
1561
|
+
level: rule.level,
|
|
1562
|
+
ctx: parsed.ctx,
|
|
1563
|
+
ruleIds: [rule.id],
|
|
1564
|
+
};
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
function routeValidated(input, parsed, overrides, rejected) {
|
|
1568
|
+
const runtime = activeRuntime();
|
|
1569
|
+
const limits = runtime.limits;
|
|
1570
|
+
const ctx = parsed.ctx;
|
|
1571
|
+
const text = parsed.text;
|
|
1572
|
+
const normalized = text.trim().toLowerCase();
|
|
1573
|
+
const meta = { caseId: parsed.caseId, turn: parsed.turn, ctx };
|
|
1574
|
+
|
|
1575
|
+
// 没有字、也没有 ctx:没什么可路由的(ctx-only 规则在下面另行处理)。
|
|
1576
|
+
if (!normalized && Object.keys(ctx).length === 0) {
|
|
1577
|
+
return emptyResult(meta, overrides, rejected);
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
// override 指向不存在的规则:整单拒绝,绝不改贴 decisions[0]。
|
|
1581
|
+
const unknownOverrides = overrides.filter((override) => !ruleById(override.ruleId));
|
|
1582
|
+
if (unknownOverrides.length) {
|
|
1583
|
+
return failClosedResult(meta, overrides, rejected, unknownOverrides.map((override) => makeError(
|
|
1584
|
+
ERROR_CODES.OVERRIDE_UNKNOWN,
|
|
1585
|
+
`override 指向不存在的规则 ${override.ruleId}:拒绝该 override,且不按它的意思改任何决策`,
|
|
1586
|
+
{ ruleId: override.ruleId },
|
|
1587
|
+
)));
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
const candidates = readCandidates(input);
|
|
1591
|
+
const matches = matchRules(parsed, candidates);
|
|
1592
|
+
|
|
1593
|
+
// 关键词命中了门控规则、但 ctx 缺字段/类型错:这不是「条件不满足」,不能静默当没命中。
|
|
1594
|
+
const ctxIssues = collectCtxIssues(parsed, matches.length ? matches[0].rule.priority : -Infinity);
|
|
1595
|
+
if (ctxIssues.length) return failClosedResult(meta, overrides, rejected, ctxIssues);
|
|
1596
|
+
|
|
1597
|
+
const errors = [];
|
|
1598
|
+
if (matches.length > 0) {
|
|
1599
|
+
const topPriority = matches[0].rule.priority;
|
|
1600
|
+
const top = matches.filter((entry) => entry.rule.priority === topPriority);
|
|
1601
|
+
if (top.length > 1) {
|
|
1602
|
+
const rules = top.map((entry) => entry.rule.id);
|
|
1603
|
+
errors.push(makeError(
|
|
1604
|
+
ERROR_CODES.AMBIGUOUS,
|
|
1605
|
+
`同优先级规则同时命中,拒绝按文件顺序判定:${rules.join(', ')}`,
|
|
1606
|
+
{ rules, priority: topPriority },
|
|
1607
|
+
));
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
if (matches.length > limits.maxCompeting) {
|
|
1611
|
+
errors.push(makeError(ERROR_CODES.EXPLOSION, `竞争规则 ${matches.length} 条,超过上限 ${limits.maxCompeting}`, {
|
|
1612
|
+
count: matches.length,
|
|
1613
|
+
limit: limits.maxCompeting,
|
|
1614
|
+
}));
|
|
1615
|
+
}
|
|
1616
|
+
if (errors.length) return failClosedResult(meta, overrides, rejected, errors);
|
|
1617
|
+
|
|
1618
|
+
if (matches.length === 0) {
|
|
1619
|
+
const asked = askFallbackResult(parsed, normalized);
|
|
1620
|
+
if (asked) {
|
|
1621
|
+
const unmatched = overrides.filter((override) => !asked.decisions.some((decision) => decision.ruleId === override.ruleId));
|
|
1622
|
+
if (unmatched.length) {
|
|
1623
|
+
return failClosedResult(meta, overrides, rejected, unmatched.map((override) => makeError(
|
|
1624
|
+
ERROR_CODES.OVERRIDE_UNKNOWN,
|
|
1625
|
+
`override 指向的兜底规则 ${override.ruleId} 没有产生决策:拒绝该 override`,
|
|
1626
|
+
{ ruleId: override.ruleId },
|
|
1627
|
+
)));
|
|
1628
|
+
}
|
|
1629
|
+
applyOverrides(asked.decisions, overrides);
|
|
1630
|
+
asked.overrides = overrides.slice();
|
|
1631
|
+
asked.overrideAudit = { applied: overrides.length, rejected: rejected.length, records: overrides.slice() };
|
|
1632
|
+
asked.errors = rejectedErrors(rejected);
|
|
1633
|
+
asked.needsHuman = asked.decisions.some((decision) => decision.needsHuman === true) || rejected.length > 0;
|
|
1634
|
+
asked.matchedRules = Array.from(new Set(asked.decisions.map((decision) => decision.ruleId)));
|
|
1635
|
+
return asked;
|
|
1636
|
+
}
|
|
1637
|
+
return emptyResult(meta, overrides, rejected);
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
const winner = matches[0];
|
|
1641
|
+
let decisions = ruleDecisions(winner.rule, winner.confidence, ctx);
|
|
1642
|
+
if (decisions.length > limits.maxDecisions) {
|
|
1643
|
+
return failClosedResult(meta, overrides, rejected, [makeError(
|
|
1644
|
+
ERROR_CODES.EXPLOSION,
|
|
1645
|
+
`规则 ${winner.rule.id} 展开 ${decisions.length} 条决策,超过上限 ${limits.maxDecisions}`,
|
|
1646
|
+
{ count: decisions.length, limit: limits.maxDecisions, ruleId: winner.rule.id },
|
|
1647
|
+
)]);
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
decisions.push(...ctxOverlays(ctx, decisions));
|
|
1651
|
+
decisions = applyConsentToDecisions(applyRestToDecisions(decisions, normalized), input);
|
|
1652
|
+
if (decisions.length > limits.maxDecisions) {
|
|
1653
|
+
return failClosedResult(meta, overrides, rejected, [makeError(
|
|
1654
|
+
ERROR_CODES.EXPLOSION,
|
|
1655
|
+
`加上 ctx 叠加后决策 ${decisions.length} 条,超过上限 ${limits.maxDecisions}`,
|
|
1656
|
+
{ count: decisions.length, limit: limits.maxDecisions },
|
|
1657
|
+
)]);
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
// writeScope 二次校验:任何一条越界都不执行。
|
|
1661
|
+
const scopeErrors = [];
|
|
1662
|
+
for (const decision of decisions) {
|
|
1663
|
+
for (const issue of writeScopeErrors(decision.writeScope, runtime.policy)) {
|
|
1664
|
+
scopeErrors.push(makeError(ERROR_CODES.SCOPE, `${decision.ruleId} ${decision.action} 的 writeScope 越界:${issue}`, {
|
|
1665
|
+
ruleId: decision.ruleId,
|
|
1666
|
+
action: decision.action,
|
|
1667
|
+
}));
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
if (scopeErrors.length) return failClosedResult(meta, overrides, rejected, scopeErrors);
|
|
1671
|
+
|
|
1672
|
+
// override 指向了存在、但本次没有产生决策的规则:同样拒绝(不能静默贴别人身上)。
|
|
1673
|
+
const unmatchedOverrides = overrides.filter((override) => !decisions.some((decision) => decision.ruleId === override.ruleId));
|
|
1674
|
+
if (unmatchedOverrides.length) {
|
|
1675
|
+
return failClosedResult(meta, overrides, rejected, unmatchedOverrides.map((override) => makeError(
|
|
1676
|
+
ERROR_CODES.OVERRIDE_UNKNOWN,
|
|
1677
|
+
`override 指向的规则 ${override.ruleId} 没有产生决策:拒绝该 override,不贴到别的决策上`,
|
|
1678
|
+
{ ruleId: override.ruleId },
|
|
1679
|
+
)));
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
applyOverrides(decisions, overrides);
|
|
1683
|
+
|
|
1684
|
+
const needsHuman = decisions.some((decision) => decision.needsHuman === true) || rejected.length > 0;
|
|
1685
|
+
const primary = decisions.find((decision) => decision.action === winner.rule.decision.action
|
|
1686
|
+
&& decision.ruleId === winner.rule.id) || decisions[0];
|
|
1687
|
+
|
|
1688
|
+
return {
|
|
1689
|
+
caseId: parsed.caseId,
|
|
1690
|
+
turn: parsed.turn,
|
|
1691
|
+
decisions,
|
|
1692
|
+
needsHuman,
|
|
1693
|
+
confidence: primary.confidence,
|
|
1694
|
+
matchedRule: winner.rule.id,
|
|
1695
|
+
matchedRules: Array.from(new Set(decisions.map((decision) => decision.ruleId))),
|
|
1696
|
+
overrides: overrides.slice(),
|
|
1697
|
+
overrideAudit: {
|
|
1698
|
+
applied: overrides.length,
|
|
1699
|
+
rejected: rejected.length,
|
|
1700
|
+
records: overrides.slice(),
|
|
1701
|
+
},
|
|
1702
|
+
errors: rejectedErrors(rejected),
|
|
1703
|
+
decision: { target: primary.target, tool: primary.tool ?? null },
|
|
1704
|
+
target: primary.target,
|
|
1705
|
+
tool: primary.tool ?? null,
|
|
1706
|
+
level: winner.rule.level,
|
|
1707
|
+
ctx,
|
|
1708
|
+
ruleIds: Array.from(new Set(decisions.map((decision) => decision.ruleId))),
|
|
1709
|
+
};
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
function readMeta(input) {
|
|
1713
|
+
const meta = { caseId: null, turn: null };
|
|
1714
|
+
if (!input || typeof input !== 'object') return meta;
|
|
1715
|
+
try {
|
|
1716
|
+
if (typeof input.caseId === 'string' && input.caseId.trim()) meta.caseId = input.caseId.trim();
|
|
1717
|
+
if (typeof input.turn === 'number' && Number.isFinite(input.turn)) meta.turn = input.turn;
|
|
1718
|
+
} catch {
|
|
1719
|
+
/* 元信息读不到不影响路由 */
|
|
1720
|
+
}
|
|
1721
|
+
return meta;
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
/**
|
|
1725
|
+
* 判断一次请求该怎么走:只做匹配,不做执行。
|
|
1726
|
+
* 出错即停:任何规则/输入/override/scope/数量/profile 问题都返回 refuse + needsHuman + 具体错误码。
|
|
1727
|
+
* @param {object} [input] 新契约 { caseId, turn, utterance, ctx, candidates, override };旧契约 { kind, text }
|
|
1728
|
+
* @param {object} [options] { profile }: 本次生效的策略 profile;缺省用配置项 routerPolicyProfile
|
|
1729
|
+
* @returns {object} decisions[] + needsHuman,同时保留 decision/target/tool 兼容别名
|
|
1730
|
+
*/
|
|
1731
|
+
export function route(input, options = {}) {
|
|
1732
|
+
const meta = readMeta(input);
|
|
1733
|
+
let applied = [];
|
|
1734
|
+
let rejected = [];
|
|
1735
|
+
let ctxReport = { ctx: {}, raw: null, problems: [] };
|
|
1736
|
+
try {
|
|
1737
|
+
ACTIVE_RUNTIME = runtimeFor(options && typeof options === 'object' ? options.profile : undefined);
|
|
1738
|
+
({ applied, rejected } = readOverrides(input));
|
|
1739
|
+
const read = readInput(input);
|
|
1740
|
+
ctxReport = readCtxReport(input);
|
|
1741
|
+
const parsed = {
|
|
1742
|
+
kind: read.kind,
|
|
1743
|
+
text: read.text,
|
|
1744
|
+
caseId: meta.caseId,
|
|
1745
|
+
turn: meta.turn,
|
|
1746
|
+
ctx: ctxReport.ctx,
|
|
1747
|
+
ctxReport,
|
|
1748
|
+
};
|
|
1749
|
+
const base = { caseId: parsed.caseId, turn: parsed.turn, ctx: parsed.ctx };
|
|
1750
|
+
|
|
1751
|
+
if (ACTIVE_RUNTIME.errors.length) return failClosedResult(base, applied, rejected, ACTIVE_RUNTIME.errors);
|
|
1752
|
+
if (LOAD_ERRORS.length) return failClosedResult(base, applied, rejected, LOAD_ERRORS);
|
|
1753
|
+
|
|
1754
|
+
// ctx 本身的类型错误:与命中哪条规则无关,直接拒。
|
|
1755
|
+
if (ctxReport.problems.length) return failClosedResult(base, applied, rejected, ctxReport.problems);
|
|
1756
|
+
|
|
1757
|
+
return routeValidated(input, parsed, applied, rejected);
|
|
1758
|
+
} catch (cause) {
|
|
1759
|
+
return failClosedResult({ caseId: meta.caseId, turn: meta.turn, ctx: ctxReport.ctx }, applied, rejected, [makeError(
|
|
1760
|
+
ERROR_CODES.CONTRACT,
|
|
1761
|
+
`route 内部异常(按 fail-closed 处理):${cause && cause.message ? cause.message : String(cause)}`,
|
|
1762
|
+
)]);
|
|
1763
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
export default route;
|