@wowok/agent-mcp 3.4.0 → 3.4.1
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/README.md +8 -0
- package/dist/chain-semantics/composition-truth.d.ts +102 -0
- package/dist/chain-semantics/composition-truth.js +1 -0
- package/dist/chain-semantics/eval-order.js +1 -1
- package/dist/chain-semantics/fund-flow.js +1 -1
- package/dist/chain-semantics/index.d.ts +1 -0
- package/dist/chain-semantics/index.js +1 -1
- package/dist/composition/audit.js +1 -1
- package/dist/composition/blueprint-view.d.ts +3 -3
- package/dist/composition/blueprint-view.js +1 -1
- package/dist/composition/compile.d.ts +24 -3
- package/dist/composition/compile.js +1 -1
- package/dist/composition/emit-phases.d.ts +206 -0
- package/dist/composition/emit-phases.js +1 -0
- package/dist/composition/generate.d.ts +40 -0
- package/dist/composition/generate.js +1 -0
- package/dist/composition/guard-fill.d.ts +44 -0
- package/dist/composition/guard-fill.js +1 -0
- package/dist/composition/inflight.d.ts +20 -2
- package/dist/composition/inflight.js +1 -1
- package/dist/composition/input-normalize.d.ts +15 -0
- package/dist/composition/input-normalize.js +1 -0
- package/dist/composition/materialize.d.ts +18 -13
- package/dist/composition/materialize.js +1 -1
- package/dist/composition/mode-gates.d.ts +35 -0
- package/dist/composition/mode-gates.js +1 -0
- package/dist/composition/param-disclosure.js +1 -1
- package/dist/composition/plan-retry-ledger.d.ts +21 -0
- package/dist/composition/plan-retry-ledger.js +1 -0
- package/dist/composition/plan.d.ts +7 -2
- package/dist/composition/plan.js +1 -1
- package/dist/composition/product-card.d.ts +94 -0
- package/dist/composition/product-card.js +1 -0
- package/dist/composition/supply-chain-emit.d.ts +46 -0
- package/dist/composition/supply-chain-emit.js +1 -0
- package/dist/config/config-audit.spec.js +1 -1
- package/dist/config/config-warnings.d.ts +2 -0
- package/dist/config/config-warnings.js +1 -0
- package/dist/config/exposure.d.ts +2 -2
- package/dist/config/judgment.d.ts +31 -5
- package/dist/config/judgment.js +1 -1
- package/dist/config/judgment.spec.js +1 -1
- package/dist/config/match-policy-file.d.ts +34 -0
- package/dist/config/match-policy-file.js +1 -0
- package/dist/config/match-policy-file.spec.d.ts +1 -0
- package/dist/config/match-policy-file.spec.js +1 -0
- package/dist/config/rule-engine.d.ts +5 -5
- package/dist/config/rule-engine.js +1 -1
- package/dist/config/runtime.d.ts +0 -1
- package/dist/config/runtime.js +1 -1
- package/dist/config/severity.d.ts +0 -2
- package/dist/config/severity.js +1 -1
- package/dist/config/store-policy.spec.js +1 -1
- package/dist/config/template-params.d.ts +42 -0
- package/dist/config/template-params.js +1 -0
- package/dist/config/template-params.spec.d.ts +1 -0
- package/dist/config/template-params.spec.js +1 -0
- package/dist/data/api/api.spec.js +1 -1
- package/dist/data/api/server.js +1 -1
- package/dist/data/projection/store.d.ts +2 -1
- package/dist/data/projection/store.js +1 -1
- package/dist/data/projection/types.d.ts +22 -0
- package/dist/data/sync/cdc.d.ts +1 -2
- package/dist/data/sync/cdc.js +1 -1
- package/dist/evaluation/acceptance.d.ts +8 -0
- package/dist/evaluation/acceptance.js +1 -1
- package/dist/evaluation/builtins/demand-match.js +1 -1
- package/dist/evaluation/builtins/graph-service.spec.js +1 -1
- package/dist/evaluation/capability.d.ts +2 -0
- package/dist/evaluation/category-match-rules.d.ts +0 -1
- package/dist/evaluation/category-match-rules.js +1 -1
- package/dist/evaluation/composer.d.ts +25 -0
- package/dist/evaluation/composer.js +1 -1
- package/dist/evaluation/engine.js +1 -1
- package/dist/evaluation/extract.d.ts +7 -0
- package/dist/evaluation/extract.js +1 -1
- package/dist/evaluation/game-strategy.d.ts +0 -3
- package/dist/evaluation/game-strategy.js +1 -1
- package/dist/evaluation/match-operation.d.ts +9 -0
- package/dist/evaluation/match-operation.js +1 -1
- package/dist/evaluation/match-policy-resolver.d.ts +9 -0
- package/dist/evaluation/match-policy-resolver.js +1 -0
- package/dist/evaluation/match-policy.d.ts +3 -1
- package/dist/evaluation/match-policy.js +1 -1
- package/dist/evaluation/region.d.ts +0 -6
- package/dist/evaluation/region.js +1 -1
- package/dist/evaluation/standards.d.ts +2 -1
- package/dist/evaluation/standards.js +1 -1
- package/dist/evaluation/structured-lines.d.ts +8 -0
- package/dist/evaluation/structured-lines.js +1 -0
- package/dist/evaluation/types.d.ts +6 -0
- package/dist/experience/realtime-feedback.js +1 -1
- package/dist/extensions/capability-manifest.d.ts +1 -0
- package/dist/extensions/capability-manifest.js +1 -1
- package/dist/extensions/capability.d.ts +91 -0
- package/dist/extensions/capability.js +1 -0
- package/dist/extensions/industry-audit.spec.js +1 -1
- package/dist/extensions/industry-pack.d.ts +13 -0
- package/dist/extensions/industry-pack.js +1 -1
- package/dist/extensions/modes.js +1 -1
- package/dist/extensions/registry.d.ts +0 -2
- package/dist/extensions/registry.js +1 -1
- package/dist/goal/GoalEngine.js +1 -1
- package/dist/graph/onchain/analyze.js +1 -1
- package/dist/graph/onchain/expand.js +1 -1
- package/dist/graph/onchain/exposure.js +1 -1
- package/dist/graph/onchain/facts.js +1 -1
- package/dist/graph/onchain/order-status.d.ts +0 -1
- package/dist/graph/onchain/order-status.js +1 -1
- package/dist/harness/recover.js +1 -1
- package/dist/harness/verify.d.ts +0 -3
- package/dist/harness/verify.js +1 -1
- package/dist/intent/types.d.ts +0 -1
- package/dist/intent/types.js +1 -1
- package/dist/keeper/detectors.js +1 -1
- package/dist/keeper/types.d.ts +0 -1
- package/dist/keeper/types.js +1 -1
- package/dist/knowledge/allocation-risk.d.ts +1 -0
- package/dist/knowledge/allocation-risk.js +1 -1
- package/dist/knowledge/allocator-rail-verifier.d.ts +6 -1
- package/dist/knowledge/allocator-rail-verifier.js +1 -1
- package/dist/knowledge/arbitration-ledger.js +1 -1
- package/dist/knowledge/arbitration-puzzle.js +1 -1
- package/dist/knowledge/audit-rules.d.ts +2 -2
- package/dist/knowledge/audit-rules.js +1 -1
- package/dist/knowledge/baselines/judgment-baselines.json +21 -2
- package/dist/knowledge/baselines/rules/oracle.json +120 -0
- package/dist/knowledge/baselines/rules/plan.json +384 -17
- package/dist/knowledge/baselines/rules/progress.json +20 -2
- package/dist/knowledge/builtin-templates.d.ts +12 -1
- package/dist/knowledge/builtin-templates.js +1 -1
- package/dist/knowledge/component-schema.js +1 -1
- package/dist/knowledge/contact-templates.d.ts +0 -1
- package/dist/knowledge/contact-templates.js +1 -1
- package/dist/knowledge/dynamic-pricing.js +1 -1
- package/dist/knowledge/fee-param-bindings.js +1 -1
- package/dist/knowledge/fund-layer.d.ts +1 -0
- package/dist/knowledge/fund-layer.js +1 -1
- package/dist/knowledge/game-scenarios.js +1 -1
- package/dist/knowledge/getting-started.js +1 -1
- package/dist/knowledge/guard-binding-table.d.ts +52 -0
- package/dist/knowledge/guard-binding-table.js +1 -0
- package/dist/knowledge/guard-binding-verifier.d.ts +30 -0
- package/dist/knowledge/guard-binding-verifier.js +1 -0
- package/dist/knowledge/guard-bindings.js +1 -1
- package/dist/knowledge/guard-blueprint.d.ts +68 -0
- package/dist/knowledge/guard-blueprint.js +1 -0
- package/dist/knowledge/guard-design-patterns.d.ts +1 -1
- package/dist/knowledge/guard-design-patterns.js +1 -1
- package/dist/knowledge/guard-field-cognition.js +1 -1
- package/dist/knowledge/guard-host-context.d.ts +24 -0
- package/dist/knowledge/guard-host-context.js +1 -0
- package/dist/knowledge/guard-lint.js +1 -1
- package/dist/knowledge/guard-node-gates.d.ts +3 -0
- package/dist/knowledge/guard-node-gates.js +1 -1
- package/dist/knowledge/guard-puzzle.js +1 -1
- package/dist/knowledge/guard-render.js +1 -1
- package/dist/knowledge/guard-risk.js +1 -1
- package/dist/knowledge/guard-submission-prompt.d.ts +11 -0
- package/dist/knowledge/guard-submission-prompt.js +1 -1
- package/dist/knowledge/guard-templates.d.ts +1 -1
- package/dist/knowledge/guard-templates.js +1 -1
- package/dist/knowledge/guard-translation.js +1 -1
- package/dist/knowledge/index.d.ts +1 -1
- package/dist/knowledge/index.js +1 -1
- package/dist/knowledge/industry-generalizer.d.ts +6 -1
- package/dist/knowledge/industry-generalizer.js +1 -1
- package/dist/knowledge/industry-registry.js +1 -1
- package/dist/knowledge/jsonrpc-enum.d.ts +38 -0
- package/dist/knowledge/jsonrpc-enum.js +1 -1
- package/dist/knowledge/machine-topology.js +1 -1
- package/dist/knowledge/machine-translation.js +1 -1
- package/dist/knowledge/object-dependency.d.ts +31 -0
- package/dist/knowledge/object-dependency.js +1 -0
- package/dist/knowledge/onchain-constants.d.ts +2 -0
- package/dist/knowledge/onchain-constants.js +1 -1
- package/dist/knowledge/param-schema.d.ts +23 -0
- package/dist/knowledge/param-schema.js +1 -1
- package/dist/knowledge/param-tiers.js +1 -1
- package/dist/knowledge/passport-ledger.js +1 -1
- package/dist/knowledge/path-oracle/coverage.d.ts +16 -0
- package/dist/knowledge/path-oracle/coverage.js +1 -0
- package/dist/knowledge/path-oracle/index.d.ts +5 -0
- package/dist/knowledge/path-oracle/index.js +1 -0
- package/dist/knowledge/path-oracle/products/food-delivery.d.ts +2 -0
- package/dist/knowledge/path-oracle/products/food-delivery.js +1 -0
- package/dist/knowledge/path-oracle/schema.d.ts +188 -0
- package/dist/knowledge/path-oracle/schema.js +1 -0
- package/dist/knowledge/pattern-resolutions.d.ts +2 -0
- package/dist/knowledge/pattern-resolutions.js +1 -1
- package/dist/knowledge/progress-ledger.js +1 -1
- package/dist/knowledge/progress-risk.js +1 -1
- package/dist/knowledge/projection.spec.js +1 -1
- package/dist/knowledge/protocol-facts.js +1 -1
- package/dist/knowledge/requirement-families.d.ts +13 -0
- package/dist/knowledge/requirement-families.js +1 -0
- package/dist/knowledge/reward-ledger.js +1 -1
- package/dist/knowledge/scenario-modes.d.ts +1 -0
- package/dist/knowledge/scenario-modes.js +1 -1
- package/dist/knowledge/semantic-ir.d.ts +4 -0
- package/dist/knowledge/semantic-ir.js +1 -1
- package/dist/knowledge/service-ledger.d.ts +1 -1
- package/dist/knowledge/service-ledger.js +1 -1
- package/dist/knowledge/sku-name-gate.d.ts +17 -0
- package/dist/knowledge/sku-name-gate.js +1 -0
- package/dist/knowledge/supply-chain.d.ts +9 -0
- package/dist/knowledge/supply-chain.js +1 -1
- package/dist/knowledge/template-loader.d.ts +14 -6
- package/dist/knowledge/template-loader.js +1 -1
- package/dist/knowledge/template-nav.d.ts +3 -1
- package/dist/knowledge/template-nav.js +1 -1
- package/dist/knowledge/template-prose.d.ts +1 -1
- package/dist/knowledge/template-registry.js +1 -1
- package/dist/knowledge/template-scanner.d.ts +62 -0
- package/dist/knowledge/template-scanner.js +1 -1
- package/dist/knowledge/template-test-profiles.js +1 -1
- package/dist/knowledge/tools-reference.js +1 -1
- package/dist/knowledge/workflow-guidance.d.ts +5 -0
- package/dist/knowledge/workflow-guidance.js +1 -1
- package/dist/monitor/MonitorLoop.js +1 -1
- package/dist/participation/radar-core.js +1 -1
- package/dist/participation/time-window.js +1 -1
- package/dist/persona/address-format.d.ts +0 -1
- package/dist/persona/address-format.js +1 -1
- package/dist/persona/bridge.js +1 -1
- package/dist/persona/index.d.ts +0 -2
- package/dist/persona/index.js +1 -1
- package/dist/persona/model.js +1 -1
- package/dist/persona/persona-audit.spec.js +1 -1
- package/dist/persona/types.d.ts +6 -0
- package/dist/playbooks/service-build/business-puzzle.js +1 -1
- package/dist/playbooks/service-build/game-theory.d.ts +2 -2
- package/dist/playbooks/service-build/intent-analyzer.js +1 -1
- package/dist/playbooks/service-build/machine-panorama.js +1 -1
- package/dist/playbooks/service-build/merchant-guide.d.ts +50 -23
- package/dist/playbooks/service-build/merchant-guide.js +1 -1
- package/dist/playbooks/service-build/migration-planner.d.ts +2 -0
- package/dist/playbooks/service-build/migration-planner.js +1 -1
- package/dist/playbooks/service-build/mode-actions.js +1 -1
- package/dist/playbooks/service-build/object-panorama.d.ts +8 -0
- package/dist/playbooks/service-build/object-panorama.js +1 -1
- package/dist/playbooks/service-build/participation-radar.js +1 -1
- package/dist/playbooks/service-build/relationship-profile.js +1 -1
- package/dist/playbooks/service-build/reverse-mapping.d.ts +6 -0
- package/dist/playbooks/service-build/reverse-mapping.js +1 -1
- package/dist/playbooks/service-build/service-panorama.d.ts +1 -0
- package/dist/playbooks/service-build/service-panorama.js +1 -1
- package/dist/playbooks/service-build/service-quote.js +1 -1
- package/dist/playbooks/service-build/service-quote.spec.js +1 -1
- package/dist/playbooks/service-build/workflow-design-assessment.d.ts +10 -1
- package/dist/playbooks/service-build/workflow-design-assessment.js +1 -1
- package/dist/review/index.js +1 -1
- package/dist/review/repository.js +1 -1
- package/dist/safety/confirm-gate.js +1 -1
- package/dist/schema/benchmark-migration/index.d.ts +104 -0
- package/dist/schema/benchmark-migration/index.js +1 -1
- package/dist/schema/call/allocation.d.ts +15 -6
- package/dist/schema/call/allocation.js +1 -1
- package/dist/schema/call/base.d.ts +256 -0
- package/dist/schema/call/base.js +1 -1
- package/dist/schema/call/bridge.d.ts +32 -6
- package/dist/schema/call/demand.d.ts +15 -6
- package/dist/schema/call/demand.js +1 -1
- package/dist/schema/call/guard.d.ts +8 -8
- package/dist/schema/call/guard.js +1 -1
- package/dist/schema/call/handler.d.ts +3 -0
- package/dist/schema/call/handler.js +1 -1
- package/dist/schema/call/machine.d.ts +32 -8
- package/dist/schema/call/machine.js +1 -1
- package/dist/schema/call/order.d.ts +26 -8
- package/dist/schema/call/order.js +1 -1
- package/dist/schema/call/payment.d.ts +20 -8
- package/dist/schema/call/payment.js +1 -1
- package/dist/schema/call/permission-handler.js +1 -1
- package/dist/schema/call/permission.d.ts +330 -114
- package/dist/schema/call/permission.js +1 -1
- package/dist/schema/call/personal.d.ts +10 -4
- package/dist/schema/call/personal.js +1 -1
- package/dist/schema/call/progress.d.ts +16 -4
- package/dist/schema/call/reward.d.ts +10 -4
- package/dist/schema/call/reward.js +1 -1
- package/dist/schema/call/semantic.d.ts +1 -0
- package/dist/schema/call/semantic.js +1 -1
- package/dist/schema/call/service.d.ts +128 -40
- package/dist/schema/call/service.js +1 -1
- package/dist/schema/call/treasury.d.ts +15 -6
- package/dist/schema/call/treasury.js +1 -1
- package/dist/schema/common/index.js +1 -1
- package/dist/schema/config/index.d.ts +61 -0
- package/dist/schema/config/index.js +1 -1
- package/dist/schema/envelope-unify.d.ts +4 -0
- package/dist/schema/envelope-unify.js +1 -0
- package/dist/schema/evaluation/index.d.ts +216 -19
- package/dist/schema/evaluation/index.js +1 -1
- package/dist/schema/goal/index.d.ts +47 -0
- package/dist/schema/goal/planning.d.ts +115 -1
- package/dist/schema/goal/planning.js +1 -1
- package/dist/schema/industry-pack/index.d.ts +137 -6
- package/dist/schema/industry-pack/index.js +1 -1
- package/dist/schema/industry-pack/modes.d.ts +6 -6
- package/dist/schema/keeper/index.d.ts +26 -0
- package/dist/schema/local/index.d.ts +137 -0
- package/dist/schema/local/index.js +1 -1
- package/dist/schema/local/wip.d.ts +6 -0
- package/dist/schema/local/wip.js +1 -1
- package/dist/schema/messenger/index.d.ts +26 -0
- package/dist/schema/operations.d.ts +342 -83
- package/dist/schema/operations.js +1 -1
- package/dist/schema/persona/index.d.ts +2907 -640
- package/dist/schema/persona/index.js +1 -1
- package/dist/schema/query/bi.d.ts +145 -4
- package/dist/schema/query/bi.js +1 -1
- package/dist/schema/query/index.d.ts +266 -73
- package/dist/schema/query/index.js +1 -1
- package/dist/schema/schema-query/index.d.ts +1 -1
- package/dist/schema/schema-query/index.js +1 -1
- package/dist/schema/schema-version.js +1 -1
- package/dist/schema/utils/permission-machine-check.d.ts +2 -0
- package/dist/schema/utils/permission-machine-check.js +1 -1
- package/dist/schema/watch/index.d.ts +16 -0
- package/dist/schema/watch/index.js +1 -1
- package/dist/schema/workflow/index.d.ts +2 -2
- package/dist/schema/workflow/index.js +1 -1
- package/dist/schema-query-impl/index.d.ts +1 -1
- package/dist/schema-query-impl/index.js +1 -1
- package/dist/schemas/account_operation.output.json +94 -0
- package/dist/schemas/benchmark_migration_operation.output.json +338 -9
- package/dist/schemas/benchmark_migration_operation.schema.json +26 -1
- package/dist/schemas/bridge_operation.output.json +94 -0
- package/dist/schemas/config_operation.output.json +352 -0
- package/dist/schemas/config_operation.schema.json +20 -2
- package/dist/schemas/evaluation_operation.output.json +570 -4
- package/dist/schemas/evaluation_operation.schema.json +194 -3
- package/dist/schemas/goal_operation.schema.json +183 -0
- package/dist/schemas/index.json +1 -1
- package/dist/schemas/industry_pack_operation.output.json +621 -0
- package/dist/schemas/industry_pack_operation.schema.json +20 -2
- package/dist/schemas/keeper_operation.output.json +94 -0
- package/dist/schemas/local_cache_operation.output.json +94 -0
- package/dist/schemas/local_history_operation.output.json +94 -0
- package/dist/schemas/local_info_operation.output.json +94 -0
- package/dist/schemas/local_mark_operation.output.json +94 -0
- package/dist/schemas/messenger_operation.output.json +94 -0
- package/dist/schemas/monitor_events.output.json +94 -0
- package/dist/schemas/monitor_subscription.output.json +94 -0
- package/dist/schemas/onchain_events.output.json +94 -0
- package/dist/schemas/onchain_operations.output.json +313 -1
- package/dist/schemas/onchain_operations.schema.json +1248 -664
- package/dist/schemas/onchain_operations_allocation.schema.json +30 -15
- package/dist/schemas/onchain_operations_arbitration.schema.json +9 -2
- package/dist/schemas/onchain_operations_contact.schema.json +8 -1
- package/dist/schemas/onchain_operations_demand.schema.json +29 -14
- package/dist/schemas/onchain_operations_gen_passport.schema.json +8 -1
- package/dist/schemas/onchain_operations_guard.schema.json +290 -105
- package/dist/schemas/onchain_operations_machine.schema.json +49 -34
- package/dist/schemas/onchain_operations_order.schema.json +63 -40
- package/dist/schemas/onchain_operations_payment.schema.json +26 -11
- package/dist/schemas/onchain_operations_permission.schema.json +362 -235
- package/dist/schemas/onchain_operations_personal.schema.json +27 -15
- package/dist/schemas/onchain_operations_progress.schema.json +45 -30
- package/dist/schemas/onchain_operations_proof.schema.json +8 -1
- package/dist/schemas/onchain_operations_repository.schema.json +8 -1
- package/dist/schemas/onchain_operations_reward.schema.json +32 -17
- package/dist/schemas/onchain_operations_service.schema.json +221 -124
- package/dist/schemas/onchain_operations_treasury.schema.json +32 -17
- package/dist/schemas/onchain_table_data.output.json +258 -6
- package/dist/schemas/onchain_table_data.schema.json +92 -52
- package/dist/schemas/persona_operation.output.json +7752 -0
- package/dist/schemas/persona_operation.schema.json +1232 -4
- package/dist/schemas/query_toolkit.output.json +756 -116
- package/dist/schemas/query_toolkit.schema.json +138 -7
- package/dist/schemas/schema_query.schema.json +1 -1
- package/dist/schemas/watch_operation.output.json +83 -0
- package/dist/schemas/wip_file.output.json +8 -0
- package/dist/schemas/workflow_operation.schema.json +2 -2
- package/dist/tools/handlers/benchmark-migration.d.ts +11 -3
- package/dist/tools/handlers/benchmark-migration.js +1 -1
- package/dist/tools/handlers/config.js +1 -1
- package/dist/tools/handlers/evaluation.js +1 -1
- package/dist/tools/handlers/evaluation.spec.js +1 -1
- package/dist/tools/handlers/industry-pack.js +1 -1
- package/dist/tools/handlers/onchain.d.ts +20 -0
- package/dist/tools/handlers/onchain.js +1 -1
- package/dist/tools/handlers/persona.js +1 -1
- package/dist/tools/handlers/query.d.ts +8 -0
- package/dist/tools/handlers/query.js +1 -1
- package/dist/tools/handlers/winner-derivation.d.ts +20 -0
- package/dist/tools/handlers/winner-derivation.js +1 -0
- package/dist/tools/handlers/wip-upload.js +1 -1
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.js +1 -1
- package/dist/tools/registry/business.js +1 -1
- package/dist/tools/registry/config.js +1 -1
- package/dist/tools/registry/evaluation.js +1 -1
- package/dist/tools/registry/identity.js +1 -1
- package/dist/tools/registry/query.js +1 -1
- package/dist/tools/transport-integrity.d.ts +7 -0
- package/dist/tools/transport-integrity.js +1 -0
- package/dist/tools/upgrade-check.js +1 -1
- package/dist/tools/wrap.d.ts +5 -0
- package/dist/tools/wrap.js +1 -1
- package/package.json +2 -2
- package/dist/extensions/business-modules.d.ts +0 -54
- package/dist/extensions/business-modules.js +0 -1
- package/dist/schemas/guard-templates.json +0 -379
package/dist/config/judgment.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readFileSync,readdirSync,statSync,writeFileSync,renameSync,mkdirSync,copyFileSync}from'node:fs';import{fileURLToPath}from'node:url';import{dirname,join}from'node:path';import{z}from'zod';import{getWowMcpDir}from'@wowok/wowok';import{SEVERITY_ORDER}from'./severity.js';import{RuleDomainPackSchema,RuleDomainPackInputSchema}from'./rule-engine.js';import{parseFactRef}from'./exposure.js';import{ACTOR_ROLES}from'../role/types.js';export const EXPECTED_JUDGMENT_VERSION=0x1;export const JUDGMENT_SECTION_NAMES=['evaluation','game','match','monitor','mode','scorecard','rules','role_intent'];const SeverityKeySchema=z['enum'](SEVERITY_ORDER);export const DimensionStandardSchema=z['object']({'label':z['string'](),'description':z['string']()})['strict']();const LevelBandSchema=z['object']({'min':z['number'](),'level':z['string']()})['strict'](),GradeWordBandSchema=z['object']({'min':z['number'](),'word':z['string']()})['strict']();export const EvaluationSectionSchema=z['object']({'comment':z['string']()['optional'](),'weights':z['record'](z['string'](),z['number']()),'dimensions':z['record'](z['string'](),DimensionStandardSchema),'severity_deduction':z['record'](SeverityKeySchema,z['number']()),'level_bands':z['array'](LevelBandSchema),'grade_words':z['object']({'comment':z['string']()['optional'](),'trust':z['array'](GradeWordBandSchema),'risk':z['array'](GradeWordBandSchema)})['strict']()})['strict']();export const EvaluationSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'weights':z['record'](z['string'](),z['number']())['optional'](),'dimensions':z['record'](z['string'](),DimensionStandardSchema)['optional'](),'severity_deduction':z['record'](z['string'](),z['number']())['optional'](),'level_bands':z['array'](LevelBandSchema)['optional'](),'grade_words':z['object']({'comment':z['string']()['optional'](),'trust':z['array'](GradeWordBandSchema)['optional'](),'risk':z['array'](GradeWordBandSchema)['optional']()})['strict']()['optional']()})['strict']();const RoleInterestSchema=z['object']({'prefer':z['array'](z['string']()),'avoid':z['array'](z['string']()),'sensitivity':z['number']()})['strict'](),KeywordRuleSchema=z['object']({'id':z['string'](),'keywords':z['array'](z['string']())['min'](0x1),'effect':z['string'](),'anchor':z['enum'](['prefer','avoid']),'when_forbidden':z['boolean']()})['strict']();export const ArbGameSectionSchema=z['object']({'comment':z['string']()['optional'](),'effect_semantics':z['record'](z['string'](),z['array'](z['string']())),'role_interests':z['record'](z['string'](),RoleInterestSchema),'keyword_rules':z['array'](KeywordRuleSchema),'forbid_pattern':z['string'](),'scoring':z['object']({'base':z['number'](),'per_gain':z['number'](),'per_risk':z['number']()})['strict']()})['strict']();export const ArbGameSectionInputSchema=ArbGameSectionSchema['partial']();export const GameSectionSchema=z['object']({'comment':z['string']()['optional'](),'outcome_semantics':z['record'](z['string'](),z['array'](z['string']())),'role_interests':z['record'](z['string'](),RoleInterestSchema),'appetite_multipliers':z['object']({'conservative':z['number'](),'balanced':z['number'](),'aggressive':z['number']()})['strict'](),'scoring':z['object']({'base':z['number'](),'per_gain':z['number'](),'per_risk':z['number']()})['strict'](),'keyword_rules':z['array'](KeywordRuleSchema),'forbid_pattern':z['string'](),'arb':ArbGameSectionSchema})['strict']();export const GameSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'outcome_semantics':z['record'](z['string'](),z['array'](z['string']()))['optional'](),'role_interests':z['record'](z['string'](),RoleInterestSchema)['optional'](),'appetite_multipliers':z['object']({'conservative':z['number']()['optional'](),'balanced':z['number']()['optional'](),'aggressive':z['number']()['optional']()})['strict']()['optional'](),'scoring':z['object']({'base':z['number']()['optional'](),'per_gain':z['number']()['optional'](),'per_risk':z['number']()['optional']()})['strict']()['optional'](),'keyword_rules':z['array'](KeywordRuleSchema)['optional'](),'forbid_pattern':z['string']()['optional'](),'arb':ArbGameSectionInputSchema['optional']()})['strict']();const MatchBandSchema=z['object']({'min':z['number'](),'score':z['number']()})['strict']();export const MatchSectionSchema=z['object']({'comment':z['string']()['optional'](),'region_scores':z['object']({'exact':z['number'](),'contains':z['number'](),'compatible':z['number'](),'overlap':z['number'](),'mismatch':z['number']()})['strict'](),'weights':z['object']({'region':z['number'](),'industry':z['number'](),'price':z['number'](),'trust':z['number'](),'capabilities':z['number'](),'tags':z['number'](),'acceptance':z['number']()})['strict'](),'trust_bands':z['array'](MatchBandSchema),'neutral_score':z['number'](),'price_over_budget_tolerance_pct':z['number'](),'top_n':z['number']()['int']()})['strict']();export const MatchSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'region_scores':z['object']({'exact':z['number']()['optional'](),'contains':z['number']()['optional'](),'compatible':z['number']()['optional'](),'overlap':z['number']()['optional'](),'mismatch':z['number']()['optional']()})['strict']()['optional'](),'weights':z['object']({'region':z['number']()['optional'](),'industry':z['number']()['optional'](),'price':z['number']()['optional'](),'trust':z['number']()['optional'](),'capabilities':z['number']()['optional'](),'tags':z['number']()['optional'](),'acceptance':z['number']()['optional']()})['strict']()['optional'](),'trust_bands':z['array'](MatchBandSchema)['optional'](),'neutral_score':z['number']()['optional'](),'price_over_budget_tolerance_pct':z['number']()['optional'](),'top_n':z['number']()['int']()['optional']()})['strict']();const MonitorThresholdsFullSchema=z['object']({'progress_stall_hours':z['number'](),'compensation_drop_ratio':z['number'](),'compensation_coverage_min':z['number'](),'messenger_timeout_hours':z['number'](),'review_window_closing_days':z['number'](),'arb_window_closing_days':z['number']()})['strict'](),MonitorEscalationSchema=z['object']({'default_expected_progress_hours':z['number'](),'stall_expected_multiplier':z['number'](),'stall_escalation_multiplier':z['number'](),'messenger_escalation_multiplier':z['number'](),'ratio_critical_threshold':z['number']()})['strict']();export const MonitorSectionSchema=z['object']({'comment':z['string']()['optional'](),'thresholds':MonitorThresholdsFullSchema,'escalation':MonitorEscalationSchema})['strict']();export const MonitorSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'thresholds':z['object']({'progress_stall_hours':z['number']()['optional'](),'compensation_drop_ratio':z['number']()['optional'](),'compensation_coverage_min':z['number']()['optional'](),'messenger_timeout_hours':z['number']()['optional'](),'review_window_closing_days':z['number']()['optional'](),'arb_window_closing_days':z['number']()['optional']()})['strict']()['optional'](),'escalation':z['object']({'default_expected_progress_hours':z['number']()['optional'](),'stall_expected_multiplier':z['number']()['optional'](),'stall_escalation_multiplier':z['number']()['optional'](),'messenger_escalation_multiplier':z['number']()['optional'](),'ratio_critical_threshold':z['number']()['optional']()})['strict']()['optional']()})['strict']();const AppetitePostureSchema=z['object']({'max_risk':z['number'](),'min_benefit':z['number']()})['strict']();export const ModeSectionSchema=z['object']({'comment':z['string']()['optional'](),'appetite_thresholds':z['object']({'conservative':AppetitePostureSchema,'balanced':AppetitePostureSchema,'aggressive':AppetitePostureSchema})['strict']()})['strict']();export const ModeSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'appetite_thresholds':z['object']({'conservative':AppetitePostureSchema['optional'](),'balanced':AppetitePostureSchema['optional'](),'aggressive':AppetitePostureSchema['optional']()})['strict']()['optional']()})['strict']();const PostureWeightSchema=z['object']({'volume':z['number'](),'balanced':z['number'](),'margin':z['number']()})['strict'](),MetricTuneSchema=z['object']({'weight':PostureWeightSchema['optional'](),'good_threshold':z['number']()['optional'](),'bad_threshold':z['number']()['optional']()})['strict']();export const ScorecardSectionSchema=z['object']({'comment':z['string']()['optional'](),'metrics':z['record'](z['string'](),MetricTuneSchema),'shop_evidence_metrics':z['array'](z['string']())})['strict']();export const ScorecardSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'metrics':z['record'](z['string'](),MetricTuneSchema)['optional'](),'shop_evidence_metrics':z['array'](z['string']())['optional']()})['strict']();const RoleIntentEntrySchema=z['object']({'comment':z['string']()['optional'](),'intents':z['array'](z['object']({'id':z['string'](),'weight':z['number']()['min'](0x0)['max'](0x1)})['strict']())['min'](0x1),'horizon':z['number']()['int']()['positive']()['optional'](),'risk_appetite':z['enum'](['conservative','balanced','aggressive'])['optional'](),'red_lines':z['array'](z['string']())['optional'](),'strategy_leaning':z['enum'](['cooperative','opportunistic','confrontational'])['optional']()})['strict']();export const RoleIntentSectionSchema=z['object']({'comment':z['string']()['optional'](),'roles':z['record'](z['string'](),RoleIntentEntrySchema)})['strict']();export const RoleIntentSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'roles':z['record'](z['string'](),RoleIntentEntrySchema['partial']())['optional']()})['strict']();export const RulesSectionSchema=z['object']({'comment':z['string']()['optional'](),'domains':z['record'](z['string'](),RuleDomainPackSchema)})['strict']();export const RulesSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'domains':z['record'](z['string'](),RuleDomainPackInputSchema)['optional']()})['strict']();export const JudgmentDocSchema=z['object']({'version':z['number']()['int'](),'description':z['string']()['optional'](),'evaluation':EvaluationSectionSchema,'game':GameSectionSchema,'match':MatchSectionSchema,'monitor':MonitorSectionSchema,'mode':ModeSectionSchema,'scorecard':ScorecardSectionSchema,'rules':RulesSectionSchema,'role_intent':RoleIntentSectionSchema})['strict']();export const JudgmentDocInputSchema=z['object']({'version':z['number']()['int'](),'description':z['string']()['optional'](),'evaluation':EvaluationSectionInputSchema['optional'](),'game':GameSectionInputSchema['optional'](),'match':MatchSectionInputSchema['optional'](),'monitor':MonitorSectionInputSchema['optional'](),'mode':ModeSectionInputSchema['optional'](),'scorecard':ScorecardSectionInputSchema['optional'](),'rules':RulesSectionInputSchema['optional'](),'role_intent':RoleIntentSectionInputSchema['optional']()})['strict']();export const JudgmentFragmentSchema=JudgmentDocInputSchema['omit']({'version':!![]})['extend']({'version':z['number']()['int']()['optional']()});function isPlainObject(a){return typeof a==='object'&&a!==null&&!Array['isArray'](a);}function entryId(a){if(isPlainObject(a)){if(typeof a['rule_id']==='string')return a['rule_id'];if(typeof a['id']==='string')return a['id'];}return null;}export function mergeJudgmentValues(a,b){if(Array['isArray'](a)&&Array['isArray'](b)){if(a['length']===0x0)return[...b];if(b['length']===0x0)return[...a];const c=[...a,...b]['every'](f=>entryId(f)!==null);if(!c)return[...b];const d=new Map();for(const f of a)d['set'](entryId(f),f);for(const g of b){const h=entryId(g),i=d['get'](h);d['set'](h,i===undefined?g:mergeJudgmentValues(i,g));}return[...d['values']()];}if(isPlainObject(a)&&isPlainObject(b)){const j={...a};for(const [l,m]of Object['entries'](b)){j[l]=mergeJudgmentValues(a[l],m);}return j;}return b===undefined?a:b;}const FACTORY_PATH=fileURLToPath(new URL('../knowledge/baselines/judgment-baselines.json',import.meta.url)),USER_DOC_NAME='judgment.json',LEGACY_USER_DOC_NAME='judgment-baselines.json';export function userJudgmentDocPath(){const a=process['env']['WOWOK_CONFIG_DIR']||getWowMcpDir();return join(a,USER_DOC_NAME);}function resolveUserDocPath(){const a=process['env']['WOWOK_CONFIG_DIR']||getWowMcpDir(),b=join(a,USER_DOC_NAME);if(existsSync(b))return b;const c=join(a,LEGACY_USER_DOC_NAME);return existsSync(c)?c:b;}function zodMessage(a){return a['issues']['slice'](0x0,0x5)['map'](b=>(b['path']['join']('.')||'(root)')+':\x20'+b['message'])['join'](';\x20');}function loadFactory(){let a;try{a=readFileSync(FACTORY_PATH,'utf-8');}catch{throw new Error('Judgment\x20baselines\x20document\x20not\x20found\x20(knowledge/baselines/judgment-baselines.json)\x20—\x20broken\x20installation.');}const b=JudgmentDocSchema['parse'](JSON['parse'](a));if(b['version']!==EXPECTED_JUDGMENT_VERSION)throw new Error('Factory\x20judgment\x20document\x20has\x20version\x20'+b['version']+',\x20expected\x20'+EXPECTED_JUDGMENT_VERSION+'\x20—\x20broken\x20installation.');return b;}const FACTORY=loadFactory(),RULE_PACKS_DIR=fileURLToPath(new URL('../knowledge/baselines/rules/',import.meta.url));function loadFactoryRulePacks(){let a=[];try{a=readdirSync(RULE_PACKS_DIR)['filter'](c=>c['endsWith']('.json'));}catch{return{};}const b={};for(const c of a){const d=c['replace'](/\.json$/,''),e=readFileSync(join(RULE_PACKS_DIR,c),'utf-8');b[d]=RuleDomainPackSchema['parse'](JSON['parse'](e));}return b;}const FACTORY_RULE_PACKS=loadFactoryRulePacks();export function factoryRulePack(a){return FACTORY_RULE_PACKS[a]??null;}function withFactoryRulePacks(a){const b=a['rules']??{'domains':{}},c=mergeJudgmentValues(FACTORY_RULE_PACKS,b['domains']??{});return{...a,'rules':{...b,'domains':c}};}function unknownRuleRef(a){for(const [b,c]of Object['entries'](a['rules']?.['domains']??{})){const d=FACTORY_RULE_PACKS[b];if(!d)return'rules.domains:\x20unknown\x20domain\x20\x27'+b+'\x27\x20(not\x20in\x20the\x20factory\x20rule\x20packs\x20—\x20check\x20for\x20a\x20typo)';const e=new Set(d['rules']['map'](f=>f['rule_id']));for(const f of c['rules']){if(!e['has'](f['rule_id']))return'rules.domains.'+b+':\x20unknown\x20rule\x20\x27'+f['rule_id']+'\x27\x20(users\x20may\x20tune\x20or\x20disable\x20factory\x20rules,\x20not\x20invent\x20them)';}}return null;}function unknownDimensionKey(a){for(const b of Object['keys'](a['evaluation']['weights'])){if(!(b in FACTORY['evaluation']['weights']))return'evaluation.weights:\x20unknown\x20dimension\x20\x27'+b+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}for(const c of Object['keys'](a['evaluation']['dimensions'])){if(!(c in FACTORY['evaluation']['dimensions']))return'evaluation.dimensions:\x20unknown\x20dimension\x20\x27'+c+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}return null;}function unknownGameRef(a){for(const d of Object['keys'](a['game']['role_interests'])){if(!(d in FACTORY['game']['role_interests']))return'game.role_interests:\x20unknown\x20role\x20\x27'+d+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}for(const f of Object['keys'](a['game']['outcome_semantics'])){if(!(f in FACTORY['game']['outcome_semantics']))return'game.outcome_semantics:\x20unknown\x20outcome\x20\x27'+f+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}const b=new Set(Object['values'](FACTORY['game']['outcome_semantics'])['flat']());for(const g of a['game']['keyword_rules']){if(!b['has'](g['effect']))return'game.keyword_rules.'+g['id']+':\x20unknown\x20effect\x20\x27'+g['effect']+'\x27\x20(must\x20be\x20an\x20effect\x20defined\x20in\x20game.outcome_semantics)';}const c=a['game']['arb'];if(c){const h=FACTORY['game']['arb'];for(const j of Object['keys'](c['role_interests'])){if(!(j in h['role_interests']))return'game.arb.role_interests:\x20unknown\x20perspective\x20\x27'+j+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}const i=new Set(Object['keys'](h['effect_semantics']));for(const k of c['keyword_rules']){if(!i['has'](k['effect']))return'game.arb.keyword_rules.'+k['id']+':\x20unknown\x20effect\x20\x27'+k['effect']+'\x27\x20(must\x20be\x20an\x20effect\x20defined\x20in\x20game.arb.effect_semantics)';}for(const [l,m]of Object['entries'](c['role_interests'])){for(const n of[...m['prefer'],...m['avoid']]){if(!i['has'](n))return'game.arb.role_interests.'+l+':\x20unknown\x20effect\x20\x27'+n+'\x27\x20(must\x20be\x20an\x20effect\x20defined\x20in\x20game.arb.effect_semantics)';}}}return null;}function unknownScorecardRef(a){for(const b of Object['keys'](a['scorecard']['metrics'])){if(!(b in FACTORY['scorecard']['metrics']))return'scorecard.metrics:\x20unknown\x20metric\x20\x27'+b+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}for(const c of a['scorecard']['shop_evidence_metrics']){if(!(c in FACTORY['scorecard']['metrics']))return'scorecard.shop_evidence_metrics:\x20unknown\x20metric\x20\x27'+c+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}return null;}function unknownRoleIntentRef(a){const b=new Set(ACTOR_ROLES),c=FACTORY['role_intent']?.['roles']??{};for(const [d,e]of Object['entries'](a['role_intent']?.['roles']??{})){if(!b['has'](d))return'role_intent.roles:\x20unknown\x20role\x20\x27'+d+'\x27\x20(must\x20be\x20an\x20ACTOR\x20role\x20—\x20neutral/system\x20hold\x20no\x20intent)';const f=new Set((c[d]?.['intents']??[])['map'](g=>g['id']));for(const g of e['intents']){if(!f['has'](g['id']))return'role_intent.roles.'+d+':\x20unknown\x20intent\x20\x27'+g['id']+'\x27\x20(not\x20in\x20the\x20factory\x20profile\x20—\x20users\x20re-tune\x20weights,\x20they\x20never\x20invent\x20intent\x20vocabulary)';}}return null;}function unknownExposureRef(a){for(const [b,d]of Object['entries'](a['rules']?.['domains']??{})){const e=FACTORY_RULE_PACKS[b];if(!e)continue;const f=new Set(Object['keys'](e['facts']??{}));for(const g of d['rules']){for(const [h,i]of g['cases']['entries']()){const j=parseFactRef(String(i['level']));if(j!==null&&!f['has'](j))return'rules.domains.'+b+'.'+g['rule_id']+'.cases['+h+'].level:\x20unknown\x20fact\x20reference\x20\x27fact:'+j+'\x27\x20(not\x20in\x20the\x20factory\x20\x27'+b+'\x27\x20fact\x20vocabulary)';for(const [k,l]of(i['exposure']?.['gain_paths']??[])['entries']()){const m=parseFactRef(String(l['viability']));if(m!==null&&!f['has'](m))return'rules.domains.'+b+'.'+g['rule_id']+'.cases['+h+'].exposure.gain_paths['+k+'].viability:\x20unknown\x20fact\x20reference\x20\x27fact:'+m+'\x27\x20(not\x20in\x20the\x20factory\x20\x27'+b+'\x27\x20fact\x20vocabulary)';}}}}return null;}let userState=null,lastReloadError=null,effectiveCache=null;function invalidate(){effectiveCache=null;}function probeUserDoc(){const a=resolveUserDocPath();let b=null,c=0x0;try{b=readFileSync(a,'utf-8'),c=statSync(a)['mtimeMs'];}catch{b=null;}if(b===null){if(userState!==null||lastReloadError!==null)return userState=null,lastReloadError=null,invalidate(),!![];return![];}if(userState&&userState['raw']===b)return![];try{const d=JSON['parse'](b),f=JudgmentDocInputSchema['parse'](d);if(f['version']!==EXPECTED_JUDGMENT_VERSION)throw new Error('version:\x20unsupported\x20document\x20version\x20'+f['version']+'\x20(expected\x20'+EXPECTED_JUDGMENT_VERSION+')');const g=withFactoryRulePacks(mergeJudgmentValues(FACTORY,f)),h=unknownDimensionKey(g)??unknownRuleRef(g)??unknownExposureRef(g)??unknownGameRef(g)??unknownScorecardRef(g)??unknownRoleIntentRef(g);if(h)throw new Error(h);const i=JudgmentDocSchema['safeParse'](g);if(!i['success'])throw new Error('schema:\x20'+zodMessage(i['error']));return userState={'raw':b,'mtimeMs':c,'doc':f},lastReloadError=null,invalidate(),!![];}catch(j){return lastReloadError=j instanceof z['ZodError']?'schema:\x20'+zodMessage(j):j instanceof Error?j['message']:String(j),![];}}function effective(){if(!effectiveCache){let a=withFactoryRulePacks(mergeJudgmentValues(mergeJudgmentValues(FACTORY,layerSlots['industry']?.['fragment']??{}),layerSlots['persona']?.['fragment']??{}));a=mergeJudgmentValues(a,userState?.['doc']??{});for(const [b,c]of overrides){a=applyPath(a,b,c);}effectiveCache=JudgmentDocSchema['parse'](a);}return effectiveCache;}const layerSlots={'persona':null,'industry':null},layerErrors={'persona':null,'industry':null};let disableTrace=[];function recordDisableTrace(a,b,c){disableTrace=disableTrace['filter'](d=>d['layer']!==b);for(const [d,e]of Object['entries'](c['rules']?.['domains']??{})){for(const f of e['rules']??[]){f['enabled']===![]&&disableTrace['push']({'layer':b,'domain':d,'rule_id':f['rule_id']});}}}function parseLayerFragment(a,b){let c;try{c=JudgmentFragmentSchema['parse'](a);}catch(h){return{'error':b+':\x20'+(h instanceof z['ZodError']?zodMessage(h):String(h))};}if(c['version']!==undefined&&c['version']!==EXPECTED_JUDGMENT_VERSION)return{'error':b+':\x20unsupported\x20fragment\x20version\x20'+c['version']+'\x20(expected\x20'+EXPECTED_JUDGMENT_VERSION+')'};const d=withFactoryRulePacks(mergeJudgmentValues(FACTORY,c)),f=unknownDimensionKey(d)??unknownRuleRef(d)??unknownExposureRef(d)??unknownGameRef(d)??unknownScorecardRef(d)??unknownRoleIntentRef(d);if(f)return{'error':b+':\x20'+f};const g=JudgmentDocSchema['safeParse'](d);if(!g['success'])return{'error':b+':\x20schema:\x20'+zodMessage(g['error'])};return{'fragment':c};}function setLayerFragment(a,b,c){if(b===null||b===undefined)return(layerSlots[a]!==null||layerErrors[a]!==null)&&(layerSlots[a]=null,layerErrors[a]=null,disableTrace=disableTrace['filter'](f=>f['layer']!==c),invalidate()),{'ok':!![]};let d;try{d=JSON['stringify'](b)??'';}catch{return{'ok':![],'error':c+':\x20fragment\x20is\x20not\x20JSON-serializable'};}if(layerSlots[a]?.['raw']===d)return{'ok':!![]};const e=parseLayerFragment(b,c);if(e['error']||!e['fragment'])return layerErrors[a]=e['error']??'rejected',{'ok':![],'error':layerErrors[a]??undefined};return layerSlots[a]={'raw':d,'fragment':e['fragment'],'label':c},layerErrors[a]=null,recordDisableTrace(a,c,e['fragment']),invalidate(),{'ok':!![]};}export function setJudgmentPersonaFragment(a,b='persona'){return setLayerFragment('persona',a,b);}export function setJudgmentIndustryOverlay(a,b='industry\x20packs'){return setLayerFragment('industry',a,b);}export function judgmentLayerError(a){return layerErrors[a];}export function validateJudgmentFragment(a,b='judgment'){return parseLayerFragment(a,b)['error']??null;}export function judgmentDisableTrace(){return disableTrace['map'](a=>({...a}));}export function clearJudgmentLayers(){layerSlots['persona']=null,layerSlots['industry']=null,layerErrors['persona']=null,layerErrors['industry']=null,disableTrace=[],invalidate();}const overrides=new Map();function resolvePath(a,b){let c=a;for(const d of b){if(!isPlainObject(c))return undefined;c=c[d];if(c===undefined)return undefined;}return c;}function applyPath(a,b,c){const d=b['split']('.'),e=structuredClone(a);let f=e;for(let g=0x0;g<d['length']-0x1;g++){f=f[d[g]];}return f[d[d['length']-0x1]]=c,e;}function typeName(a){if(Array['isArray'](a))return'array';if(a===null)return'null';return typeof a;}function sameShape(a,b){const c=typeName(a),d=typeName(b);if(c==='object'&&d==='object')return isPlainObject(a)&&isPlainObject(b);return c===d;}export function setJudgmentOverride(a,b){const c=typeof a==='string'?a['trim']():'';if(!c)return{'ok':![],'error':'\x27path\x27\x20is\x20required\x20(dotted,\x20e.g.\x20evaluation.weights.trust_reviews)'};if(b===undefined||b===null||!(typeof b==='number'||typeof b==='string'||typeof b==='boolean'||Array['isArray'](b)||isPlainObject(b)))return{'ok':![],'error':'\x27value\x27\x20must\x20be\x20a\x20JSON\x20value\x20(number\x20/\x20string\x20/\x20boolean\x20/\x20array\x20/\x20object)'};const d=c['split']('.')['filter'](Boolean),f=d[0x0];if(!JUDGMENT_SECTION_NAMES['includes'](f))return{'ok':![],'error':'Unknown\x20section\x20\x27'+f+'\x27\x20—\x20sections:\x20'+JUDGMENT_SECTION_NAMES['join'](',\x20')};probeUserDoc();const g=resolvePath(effective(),d);if(g===undefined)return{'ok':![],'error':'Unknown\x20judgment\x20path\x20\x27'+c+'\x27'};if(!sameShape(g,b))return{'ok':![],'error':'Type\x20mismatch\x20at\x20\x27'+c+'\x27\x20—\x20expected\x20'+typeName(g)+',\x20got\x20'+typeName(b)};try{JudgmentDocSchema['parse'](applyPath(effective(),c,b));}catch(h){return{'ok':![],'error':'Rejected:\x20'+(h instanceof z['ZodError']?zodMessage(h):h instanceof Error?h['message']:String(h))};}return overrides['set'](c,b),invalidate(),{'ok':!![]};}export function clearJudgmentOverride(a){const b=overrides['delete'](typeof a==='string'?a['trim']():'');if(b)invalidate();return b;}export function clearJudgmentOverrides(){const a=overrides['size'];return a>0x0&&(overrides['clear'](),invalidate()),a;}export function judgmentOverrides(){return Array['from'](overrides['entries']())['map'](([a,b])=>({'path':a,'value':b}));}export function getJudgmentDoc(){return probeUserDoc(),structuredClone(effective());}let policyRunDoc=null;export function beginPolicyRun(){policyRunDoc=getJudgmentDoc();}export function endPolicyRun(){policyRunDoc=null;}export function policyJudgmentDoc(){return policyRunDoc??getJudgmentDoc();}export function evaluationSection(){return getJudgmentDoc()['evaluation'];}export function factoryJudgmentDoc(){return structuredClone(withFactoryRulePacks(FACTORY));}export function readUserJudgmentDocView(){probeUserDoc();if(userState)return{'user_path':userJudgmentDocPath(),'exists':!![],'version':EXPECTED_JUDGMENT_VERSION,'doc':structuredClone(userState['doc'])};return{'user_path':userJudgmentDocPath(),'exists':![],'version':EXPECTED_JUDGMENT_VERSION,'doc':factoryJudgmentDoc()};}export function judgmentStatus(){probeUserDoc();const a=effective(),b={};for(const c of JUDGMENT_SECTION_NAMES){const d=a[c];if(c==='rules'&&isPlainObject(d)){const e=d['domains']??{};b[c]=Object['values'](e)['reduce']((f,g)=>f+(Array['isArray'](g['rules'])?g['rules']['length']:0x0),0x0);continue;}b[c]=Array['isArray'](d)?d['length']:isPlainObject(d)?Object['keys'](d)['length']:0x0;}return{'version':a['version'],'factory_path':FACTORY_PATH,'user_path':userJudgmentDocPath(),'user_doc_loaded':userState!==null,'user_mtime':userState?new Date(userState['mtimeMs'])['toISOString']():null,'last_reload_error':lastReloadError,'user_doc':userState?structuredClone(userState['doc']):null,'persona_fragment_loaded':layerSlots['persona']!==null,'industry_overlay_loaded':layerSlots['industry']!==null,'layer_errors':{'persona':layerErrors['persona'],'industry':layerErrors['industry']},'disable_trace':judgmentDisableTrace(),'sections':b,'overrides':judgmentOverrides()};}function jsonEqual(c,d){if(c===d)return!![];if(Array['isArray'](c)&&Array['isArray'](d))return JSON['stringify'](c)===JSON['stringify'](d);if(isPlainObject(c)&&isPlainObject(d)){const e=Object['keys'](c);if(e['length']!==Object['keys'](d)['length'])return![];return e['every'](f=>f in d&&jsonEqual(c[f],d[f]));}return![];}function collectChanges(a,c,d,e){if(isPlainObject(c)){const f=isPlainObject(a)?a:{};for(const [g,h]of Object['entries'](c)){collectChanges(f[g],h,d?d+'.'+g:g,e);}return;}!jsonEqual(a,c)&&e['push']({'path':d||'(root)','old':a===undefined?null:a,'new':c});}export function patchUserJudgmentDoc(a){const b=userJudgmentDocPath(),c=join(dirname(b),'judgment.backup.json'),d=resolveUserDocPath();if(!isPlainObject(a))throw new Error('\x27patch\x27\x20must\x20be\x20a\x20partial\x20judgment\x20document\x20object\x20(e.g.\x20{\x22evaluation\x22:\x20{\x22weights\x22:\x20{…}}})');if(a['version']!==undefined&&a['version']!==EXPECTED_JUDGMENT_VERSION)throw new Error('patch.version:\x20unsupported\x20version\x20'+String(a['version'])+'\x20(expected\x20'+EXPECTED_JUDGMENT_VERSION+')');const {version:f,...g}=a;let h;try{h=JudgmentFragmentSchema['parse'](g);}catch(r){throw new Error('patch\x20rejected:\x20'+(r instanceof z['ZodError']?zodMessage(r):r instanceof Error?r['message']:String(r)));}if(Object['keys'](h)['length']===0x0)throw new Error('\x27patch\x27\x20is\x20empty\x20—\x20nothing\x20to\x20apply\x20(sections:\x20'+JUDGMENT_SECTION_NAMES['join'](',\x20')+')');let i=null,j=![];try{const s=readFileSync(d,'utf-8');j=!![];const t=JSON['parse'](s);i=JudgmentDocInputSchema['parse'](t);}catch(u){if(j)throw new Error('the\x20current\x20user\x20document\x20is\x20not\x20a\x20valid\x20judgment\x20document\x20('+(u instanceof Error?u['message']:String(u))+')\x20—\x20fix\x20or\x20remove\x20'+d+'\x20by\x20hand\x20first');i=null;}const k=mergeJudgmentValues(i??{'version':EXPECTED_JUDGMENT_VERSION},h);k['version']=EXPECTED_JUDGMENT_VERSION;const l=withFactoryRulePacks(mergeJudgmentValues(FACTORY,k)),m=unknownDimensionKey(l)??unknownRuleRef(l)??unknownExposureRef(l)??unknownGameRef(l)??unknownScorecardRef(l)??unknownRoleIntentRef(l);if(m)throw new Error('patch\x20rejected:\x20'+m);const n=JudgmentDocSchema['safeParse'](l);if(!n['success'])throw new Error('patch\x20rejected:\x20schema:\x20'+zodMessage(n['error']));const o=[];collectChanges(i??{},h,'',o);if(o['length']===0x0)return{'applied':!![],'user_path':b,'backup_path':null,'version':EXPECTED_JUDGMENT_VERSION,'changed':o,'reload_error':null};const p=JSON['stringify'](k,null,0x2)+'\x0a';mkdirSync(dirname(b),{'recursive':!![]});if(j)copyFileSync(d,c);const q=b+'.tmp';writeFileSync(q,p,'utf-8'),renameSync(q,b);try{userState={'raw':p,'mtimeMs':statSync(b)['mtimeMs'],'doc':k},lastReloadError=null;}catch(v){lastReloadError=v instanceof Error?v['message']:String(v);}return invalidate(),{'applied':!![],'user_path':b,'backup_path':j?c:null,'version':EXPECTED_JUDGMENT_VERSION,'changed':o,'reload_error':lastReloadError};}
|
|
1
|
+
import{existsSync,readFileSync,readdirSync,statSync,writeFileSync,renameSync,mkdirSync,copyFileSync}from'node:fs';import{fileURLToPath}from'node:url';import{dirname,join}from'node:path';import{z}from'zod';import{getWowMcpDir}from'@wowok/wowok';import{SEVERITY_ORDER}from'./severity.js';import{judgmentDocWarnings}from'./config-warnings.js';import{RuleDomainPackSchema,RuleDomainPackInputSchema}from'./rule-engine.js';import{parseFactRef}from'./exposure.js';import{ACTOR_ROLES}from'../role/types.js';export const EXPECTED_JUDGMENT_VERSION=0x1;export const JUDGMENT_SECTION_NAMES=['evaluation','game','match','monitor','mode','scorecard','rules','role_intent'];const SeverityKeySchema=z['enum'](SEVERITY_ORDER);export const DimensionStandardSchema=z['object']({'label':z['string'](),'description':z['string']()})['strict']();const LevelBandSchema=z['object']({'min':z['number'](),'level':z['string']()})['strict'](),GradeWordBandSchema=z['object']({'min':z['number'](),'word':z['string']()})['strict']();export const EvaluationSectionSchema=z['object']({'comment':z['string']()['optional'](),'weights':z['record'](z['string'](),z['number']()),'dimensions':z['record'](z['string'](),DimensionStandardSchema),'severity_deduction':z['record'](SeverityKeySchema,z['number']()),'level_bands':z['array'](LevelBandSchema),'grade_words':z['object']({'comment':z['string']()['optional'](),'trust':z['array'](GradeWordBandSchema),'risk':z['array'](GradeWordBandSchema),'match':z['array'](GradeWordBandSchema)['optional']()})['strict']()})['strict']();export const EvaluationSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'weights':z['record'](z['string'](),z['number']())['optional'](),'dimensions':z['record'](z['string'](),DimensionStandardSchema)['optional'](),'severity_deduction':z['record'](z['string'](),z['number']())['optional'](),'level_bands':z['array'](LevelBandSchema)['optional'](),'grade_words':z['object']({'comment':z['string']()['optional'](),'trust':z['array'](GradeWordBandSchema)['optional'](),'risk':z['array'](GradeWordBandSchema)['optional'](),'match':z['array'](GradeWordBandSchema)['optional']()})['strict']()['optional']()})['strict']();const RoleInterestSchema=z['object']({'prefer':z['array'](z['string']()),'avoid':z['array'](z['string']()),'sensitivity':z['number']()})['strict'](),KeywordRuleSchema=z['object']({'id':z['string'](),'keywords':z['array'](z['string']())['min'](0x1),'effect':z['string'](),'anchor':z['enum'](['prefer','avoid']),'when_forbidden':z['boolean']()})['strict']();export const ArbGameSectionSchema=z['object']({'comment':z['string']()['optional'](),'effect_semantics':z['record'](z['string'](),z['array'](z['string']())),'role_interests':z['record'](z['string'](),RoleInterestSchema),'keyword_rules':z['array'](KeywordRuleSchema),'forbid_pattern':z['string'](),'scoring':z['object']({'base':z['number'](),'per_gain':z['number'](),'per_risk':z['number']()})['strict']()})['strict']();export const ArbGameSectionInputSchema=ArbGameSectionSchema['partial']();export const GameSectionSchema=z['object']({'comment':z['string']()['optional'](),'outcome_semantics':z['record'](z['string'](),z['array'](z['string']())),'role_interests':z['record'](z['string'](),RoleInterestSchema),'appetite_multipliers':z['object']({'conservative':z['number'](),'balanced':z['number'](),'aggressive':z['number']()})['strict'](),'scoring':z['object']({'base':z['number'](),'per_gain':z['number'](),'per_risk':z['number']()})['strict'](),'keyword_rules':z['array'](KeywordRuleSchema),'forbid_pattern':z['string'](),'arb':ArbGameSectionSchema})['strict']();export const GameSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'outcome_semantics':z['record'](z['string'](),z['array'](z['string']()))['optional'](),'role_interests':z['record'](z['string'](),RoleInterestSchema)['optional'](),'appetite_multipliers':z['object']({'conservative':z['number']()['optional'](),'balanced':z['number']()['optional'](),'aggressive':z['number']()['optional']()})['strict']()['optional'](),'scoring':z['object']({'base':z['number']()['optional'](),'per_gain':z['number']()['optional'](),'per_risk':z['number']()['optional']()})['strict']()['optional'](),'keyword_rules':z['array'](KeywordRuleSchema)['optional'](),'forbid_pattern':z['string']()['optional'](),'arb':ArbGameSectionInputSchema['optional']()})['strict']();const MatchBandSchema=z['object']({'min':z['number'](),'score':z['number']()})['strict']();export const MatchSectionSchema=z['object']({'comment':z['string']()['optional'](),'region_scores':z['object']({'exact':z['number'](),'contains':z['number'](),'compatible':z['number'](),'overlap':z['number'](),'mismatch':z['number']()})['strict'](),'weights':z['object']({'region':z['number'](),'industry':z['number'](),'price':z['number'](),'trust':z['number'](),'capabilities':z['number'](),'buyable':z['number'](),'tags':z['number'](),'acceptance':z['number']()})['strict'](),'trust_bands':z['array'](MatchBandSchema),'neutral_score':z['number'](),'price_over_budget_tolerance_pct':z['number'](),'top_n':z['number']()['int']()})['strict']();export const MatchSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'region_scores':z['object']({'exact':z['number']()['optional'](),'contains':z['number']()['optional'](),'compatible':z['number']()['optional'](),'overlap':z['number']()['optional'](),'mismatch':z['number']()['optional']()})['strict']()['optional'](),'weights':z['object']({'region':z['number']()['optional'](),'industry':z['number']()['optional'](),'price':z['number']()['optional'](),'trust':z['number']()['optional'](),'capabilities':z['number']()['optional'](),'buyable':z['number']()['optional'](),'tags':z['number']()['optional'](),'acceptance':z['number']()['optional']()})['strict']()['optional'](),'trust_bands':z['array'](MatchBandSchema)['optional'](),'neutral_score':z['number']()['optional'](),'price_over_budget_tolerance_pct':z['number']()['optional'](),'top_n':z['number']()['int']()['optional']()})['strict']();const MonitorThresholdsFullSchema=z['object']({'progress_stall_hours':z['number'](),'compensation_drop_ratio':z['number'](),'compensation_coverage_min':z['number'](),'messenger_timeout_hours':z['number'](),'review_window_closing_days':z['number'](),'arb_window_closing_days':z['number']()})['strict'](),MonitorEscalationSchema=z['object']({'default_expected_progress_hours':z['number'](),'stall_expected_multiplier':z['number'](),'stall_escalation_multiplier':z['number'](),'messenger_escalation_multiplier':z['number'](),'ratio_critical_threshold':z['number']()})['strict']();export const MonitorSectionSchema=z['object']({'comment':z['string']()['optional'](),'thresholds':MonitorThresholdsFullSchema,'escalation':MonitorEscalationSchema})['strict']();export const MonitorSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'thresholds':z['object']({'progress_stall_hours':z['number']()['optional'](),'compensation_drop_ratio':z['number']()['optional'](),'compensation_coverage_min':z['number']()['optional'](),'messenger_timeout_hours':z['number']()['optional'](),'review_window_closing_days':z['number']()['optional'](),'arb_window_closing_days':z['number']()['optional']()})['strict']()['optional'](),'escalation':z['object']({'default_expected_progress_hours':z['number']()['optional'](),'stall_expected_multiplier':z['number']()['optional'](),'stall_escalation_multiplier':z['number']()['optional'](),'messenger_escalation_multiplier':z['number']()['optional'](),'ratio_critical_threshold':z['number']()['optional']()})['strict']()['optional']()})['strict']();const AppetitePostureSchema=z['object']({'max_risk':z['number'](),'min_benefit':z['number']()})['strict']();export const ModeSectionSchema=z['object']({'comment':z['string']()['optional'](),'appetite_thresholds':z['object']({'conservative':AppetitePostureSchema,'balanced':AppetitePostureSchema,'aggressive':AppetitePostureSchema})['strict']()})['strict']();export const ModeSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'appetite_thresholds':z['object']({'conservative':AppetitePostureSchema['optional'](),'balanced':AppetitePostureSchema['optional'](),'aggressive':AppetitePostureSchema['optional']()})['strict']()['optional']()})['strict']();const PostureWeightSchema=z['object']({'volume':z['number'](),'balanced':z['number'](),'margin':z['number']()})['strict'](),MetricTuneSchema=z['object']({'weight':PostureWeightSchema['optional'](),'good_threshold':z['number']()['optional'](),'bad_threshold':z['number']()['optional']()})['strict']();export const ScorecardSectionSchema=z['object']({'comment':z['string']()['optional'](),'metrics':z['record'](z['string'](),MetricTuneSchema),'shop_evidence_metrics':z['array'](z['string']())})['strict']();export const ScorecardSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'metrics':z['record'](z['string'](),MetricTuneSchema)['optional'](),'shop_evidence_metrics':z['array'](z['string']())['optional']()})['strict']();const RoleIntentEntrySchema=z['object']({'comment':z['string']()['optional'](),'intents':z['array'](z['object']({'id':z['string'](),'weight':z['number']()['min'](0x0)['max'](0x1)})['strict']())['min'](0x1),'horizon':z['number']()['int']()['positive']()['optional'](),'risk_appetite':z['enum'](['conservative','balanced','aggressive'])['optional'](),'red_lines':z['array'](z['string']())['optional'](),'strategy_leaning':z['enum'](['cooperative','opportunistic','confrontational'])['optional']()})['strict']();export const RoleIntentSectionSchema=z['object']({'comment':z['string']()['optional'](),'roles':z['record'](z['string'](),RoleIntentEntrySchema)})['strict']();export const RoleIntentSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'roles':z['record'](z['string'](),RoleIntentEntrySchema['partial']())['optional']()})['strict']();export const RulesSectionSchema=z['object']({'comment':z['string']()['optional'](),'domains':z['record'](z['string'](),RuleDomainPackSchema)})['strict']();export const RulesSectionInputSchema=z['object']({'comment':z['string']()['optional'](),'domains':z['record'](z['string'](),RuleDomainPackInputSchema)['optional']()})['strict']();export const JudgmentDocSchema=z['object']({'version':z['number']()['int'](),'description':z['string']()['optional'](),'evaluation':EvaluationSectionSchema,'game':GameSectionSchema,'match':MatchSectionSchema,'monitor':MonitorSectionSchema,'mode':ModeSectionSchema,'scorecard':ScorecardSectionSchema,'rules':RulesSectionSchema,'role_intent':RoleIntentSectionSchema})['strict']();export const JudgmentDocInputSchema=z['object']({'version':z['number']()['int'](),'description':z['string']()['optional'](),'evaluation':EvaluationSectionInputSchema['optional'](),'game':GameSectionInputSchema['optional'](),'match':MatchSectionInputSchema['optional'](),'monitor':MonitorSectionInputSchema['optional'](),'mode':ModeSectionInputSchema['optional'](),'scorecard':ScorecardSectionInputSchema['optional'](),'rules':RulesSectionInputSchema['optional'](),'role_intent':RoleIntentSectionInputSchema['optional']()})['strict']();export const JudgmentFragmentSchema=JudgmentDocInputSchema['omit']({'version':!![]})['extend']({'version':z['number']()['int']()['optional']()});function isPlainObject(a){return typeof a==='object'&&a!==null&&!Array['isArray'](a);}function entryId(a){if(isPlainObject(a)){if(typeof a['rule_id']==='string')return a['rule_id'];if(typeof a['id']==='string')return a['id'];}return null;}export function mergeJudgmentValues(a,b){if(Array['isArray'](a)&&Array['isArray'](b)){if(a['length']===0x0)return[...b];if(b['length']===0x0)return[...a];const c=[...a,...b]['every'](f=>entryId(f)!==null);if(!c)return[...b];const d=new Map();for(const f of a)d['set'](entryId(f),f);for(const g of b){const h=entryId(g),i=d['get'](h);d['set'](h,i===undefined?g:mergeJudgmentValues(i,g));}return[...d['values']()];}if(isPlainObject(a)&&isPlainObject(b)){const j={...a};for(const [l,m]of Object['entries'](b)){j[l]=mergeJudgmentValues(a[l],m);}return j;}return b===undefined?a:b;}const FACTORY_PATH=fileURLToPath(new URL('../knowledge/baselines/judgment-baselines.json',import.meta.url)),USER_DOC_NAME='judgment.json',LEGACY_USER_DOC_NAME='judgment-baselines.json';export function userJudgmentDocPath(){const a=process['env']['WOWOK_CONFIG_DIR']||getWowMcpDir();return join(a,USER_DOC_NAME);}function resolveUserDocPath(){const a=process['env']['WOWOK_CONFIG_DIR']||getWowMcpDir(),b=join(a,USER_DOC_NAME);if(existsSync(b))return b;const c=join(a,LEGACY_USER_DOC_NAME);return existsSync(c)?c:b;}function zodMessage(a){return a['issues']['slice'](0x0,0x5)['map'](b=>(b['path']['join']('.')||'(root)')+':\x20'+b['message'])['join'](';\x20');}function loadFactory(){let a;try{a=readFileSync(FACTORY_PATH,'utf-8');}catch{throw new Error('Judgment\x20baselines\x20document\x20not\x20found\x20(knowledge/baselines/judgment-baselines.json)\x20—\x20broken\x20installation.');}const b=JudgmentDocSchema['parse'](JSON['parse'](a));if(b['version']!==EXPECTED_JUDGMENT_VERSION)throw new Error('Factory\x20judgment\x20document\x20has\x20version\x20'+b['version']+',\x20expected\x20'+EXPECTED_JUDGMENT_VERSION+'\x20—\x20broken\x20installation.');return b;}const FACTORY=loadFactory(),RULE_PACKS_DIR=fileURLToPath(new URL('../knowledge/baselines/rules/',import.meta.url));function loadFactoryRulePacks(){let a=[];try{a=readdirSync(RULE_PACKS_DIR)['filter'](c=>c['endsWith']('.json'));}catch{return{};}const b={};for(const c of a){const d=c['replace'](/\.json$/,''),e=readFileSync(join(RULE_PACKS_DIR,c),'utf-8');b[d]=RuleDomainPackSchema['parse'](JSON['parse'](e));}return b;}const FACTORY_RULE_PACKS=loadFactoryRulePacks();export function factoryRulePack(a){return FACTORY_RULE_PACKS[a]??null;}function withFactoryRulePacks(a){const b=a['rules']??{'domains':{}},c=mergeJudgmentValues(FACTORY_RULE_PACKS,b['domains']??{});return{...a,'rules':{...b,'domains':c}};}function unknownRuleRef(a){for(const [b,c]of Object['entries'](a['rules']?.['domains']??{})){const d=FACTORY_RULE_PACKS[b];if(!d)return'rules.domains:\x20unknown\x20domain\x20\x27'+b+'\x27\x20(not\x20in\x20the\x20factory\x20rule\x20packs\x20—\x20check\x20for\x20a\x20typo)';const e=new Set(d['rules']['map'](f=>f['rule_id']));for(const f of c['rules']){if(!e['has'](f['rule_id']))return'rules.domains.'+b+':\x20unknown\x20rule\x20\x27'+f['rule_id']+'\x27\x20(users\x20may\x20tune\x20or\x20disable\x20factory\x20rules,\x20not\x20invent\x20them)';}}return null;}function unknownDimensionKey(a){for(const b of Object['keys'](a['evaluation']['weights'])){if(!(b in FACTORY['evaluation']['weights']))return'evaluation.weights:\x20unknown\x20dimension\x20\x27'+b+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}for(const c of Object['keys'](a['evaluation']['dimensions'])){if(!(c in FACTORY['evaluation']['dimensions']))return'evaluation.dimensions:\x20unknown\x20dimension\x20\x27'+c+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}return null;}function unknownGameRef(a){for(const d of Object['keys'](a['game']['role_interests'])){if(!(d in FACTORY['game']['role_interests']))return'game.role_interests:\x20unknown\x20role\x20\x27'+d+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}for(const f of Object['keys'](a['game']['outcome_semantics'])){if(!(f in FACTORY['game']['outcome_semantics']))return'game.outcome_semantics:\x20unknown\x20outcome\x20\x27'+f+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}const b=new Set(Object['values'](FACTORY['game']['outcome_semantics'])['flat']());for(const g of a['game']['keyword_rules']){if(!b['has'](g['effect']))return'game.keyword_rules.'+g['id']+':\x20unknown\x20effect\x20\x27'+g['effect']+'\x27\x20(must\x20be\x20an\x20effect\x20defined\x20in\x20game.outcome_semantics)';}const c=a['game']['arb'];if(c){const h=FACTORY['game']['arb'];for(const j of Object['keys'](c['role_interests'])){if(!(j in h['role_interests']))return'game.arb.role_interests:\x20unknown\x20perspective\x20\x27'+j+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}const i=new Set(Object['keys'](h['effect_semantics']));for(const k of c['keyword_rules']){if(!i['has'](k['effect']))return'game.arb.keyword_rules.'+k['id']+':\x20unknown\x20effect\x20\x27'+k['effect']+'\x27\x20(must\x20be\x20an\x20effect\x20defined\x20in\x20game.arb.effect_semantics)';}for(const [l,m]of Object['entries'](c['role_interests'])){for(const n of[...m['prefer'],...m['avoid']]){if(!i['has'](n))return'game.arb.role_interests.'+l+':\x20unknown\x20effect\x20\x27'+n+'\x27\x20(must\x20be\x20an\x20effect\x20defined\x20in\x20game.arb.effect_semantics)';}}}return null;}function unknownScorecardRef(a){for(const b of Object['keys'](a['scorecard']['metrics'])){if(!(b in FACTORY['scorecard']['metrics']))return'scorecard.metrics:\x20unknown\x20metric\x20\x27'+b+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}for(const c of a['scorecard']['shop_evidence_metrics']){if(!(c in FACTORY['scorecard']['metrics']))return'scorecard.shop_evidence_metrics:\x20unknown\x20metric\x20\x27'+c+'\x27\x20(not\x20in\x20the\x20factory\x20document\x20—\x20check\x20for\x20a\x20typo)';}return null;}function unknownRoleIntentRef(a){const b=new Set(ACTOR_ROLES),c=FACTORY['role_intent']?.['roles']??{};for(const [d,e]of Object['entries'](a['role_intent']?.['roles']??{})){if(!b['has'](d))return'role_intent.roles:\x20unknown\x20role\x20\x27'+d+'\x27\x20(must\x20be\x20an\x20ACTOR\x20role\x20—\x20neutral/system\x20hold\x20no\x20intent)';const f=new Set((c[d]?.['intents']??[])['map'](g=>g['id']));for(const g of e['intents']){if(!f['has'](g['id']))return'role_intent.roles.'+d+':\x20unknown\x20intent\x20\x27'+g['id']+'\x27\x20(not\x20in\x20the\x20factory\x20profile\x20—\x20users\x20re-tune\x20weights,\x20they\x20never\x20invent\x20intent\x20vocabulary)';}}return null;}function unknownExposureRef(a){for(const [b,d]of Object['entries'](a['rules']?.['domains']??{})){const e=FACTORY_RULE_PACKS[b];if(!e)continue;const f=new Set(Object['keys'](e['facts']??{}));for(const g of d['rules']){for(const [h,i]of g['cases']['entries']()){const j=parseFactRef(String(i['level']));if(j!==null&&!f['has'](j))return'rules.domains.'+b+'.'+g['rule_id']+'.cases['+h+'].level:\x20unknown\x20fact\x20reference\x20\x27fact:'+j+'\x27\x20(not\x20in\x20the\x20factory\x20\x27'+b+'\x27\x20fact\x20vocabulary)';for(const [k,l]of(i['exposure']?.['gain_paths']??[])['entries']()){const m=parseFactRef(String(l['viability']));if(m!==null&&!f['has'](m))return'rules.domains.'+b+'.'+g['rule_id']+'.cases['+h+'].exposure.gain_paths['+k+'].viability:\x20unknown\x20fact\x20reference\x20\x27fact:'+m+'\x27\x20(not\x20in\x20the\x20factory\x20\x27'+b+'\x27\x20fact\x20vocabulary)';}}}}return null;}let userState=null,lastReloadError=null,effectiveCache=null;function invalidate(){effectiveCache=null;}function probeUserDoc(){const a=resolveUserDocPath();let b=null,c=0x0;try{b=readFileSync(a,'utf-8'),c=statSync(a)['mtimeMs'];}catch{b=null;}if(b===null){if(userState!==null||lastReloadError!==null)return userState=null,lastReloadError=null,invalidate(),!![];return![];}if(userState&&userState['raw']===b)return![];try{const d=JSON['parse'](b),f=JudgmentDocInputSchema['parse'](d);if(f['version']!==EXPECTED_JUDGMENT_VERSION)throw new Error('version:\x20unsupported\x20document\x20version\x20'+f['version']+'\x20(expected\x20'+EXPECTED_JUDGMENT_VERSION+')');const g=withFactoryRulePacks(mergeJudgmentValues(FACTORY,f)),h=unknownDimensionKey(g)??unknownRuleRef(g)??unknownExposureRef(g)??unknownGameRef(g)??unknownScorecardRef(g)??unknownRoleIntentRef(g);if(h)throw new Error(h);const i=JudgmentDocSchema['safeParse'](g);if(!i['success'])throw new Error('schema:\x20'+zodMessage(i['error']));return userState={'raw':b,'mtimeMs':c,'doc':f},lastReloadError=null,invalidate(),!![];}catch(j){return lastReloadError=j instanceof z['ZodError']?'schema:\x20'+zodMessage(j):j instanceof Error?j['message']:String(j),![];}}function effective(){if(!effectiveCache){let a=withFactoryRulePacks(mergeJudgmentValues(FACTORY,layerSlots['industry']?.['fragment']??{}));a=mergeJudgmentValues(a,userState?.['doc']??{}),a=mergeJudgmentValues(a,layerSlots['persona']?.['fragment']??{});for(const [b,c]of overrides){a=applyPath(a,b,c);}effectiveCache=JudgmentDocSchema['parse'](a);}return effectiveCache;}const layerSlots={'persona':null,'industry':null},layerErrors={'persona':null,'industry':null};let disableTrace=[];function recordDisableTrace(a,b,c){disableTrace=disableTrace['filter'](d=>d['layer']!==b);for(const [d,e]of Object['entries'](c['rules']?.['domains']??{})){for(const f of e['rules']??[]){f['enabled']===![]&&disableTrace['push']({'layer':b,'domain':d,'rule_id':f['rule_id']});}}}function parseLayerFragment(a,b){let c;try{c=JudgmentFragmentSchema['parse'](a);}catch(h){return{'error':b+':\x20'+(h instanceof z['ZodError']?zodMessage(h):String(h))};}if(c['version']!==undefined&&c['version']!==EXPECTED_JUDGMENT_VERSION)return{'error':b+':\x20unsupported\x20fragment\x20version\x20'+c['version']+'\x20(expected\x20'+EXPECTED_JUDGMENT_VERSION+')'};const d=withFactoryRulePacks(mergeJudgmentValues(FACTORY,c)),f=unknownDimensionKey(d)??unknownRuleRef(d)??unknownExposureRef(d)??unknownGameRef(d)??unknownScorecardRef(d)??unknownRoleIntentRef(d);if(f)return{'error':b+':\x20'+f};const g=JudgmentDocSchema['safeParse'](d);if(!g['success'])return{'error':b+':\x20schema:\x20'+zodMessage(g['error'])};return{'fragment':c};}function setLayerFragment(a,b,c){if(b===null||b===undefined)return(layerSlots[a]!==null||layerErrors[a]!==null)&&(layerSlots[a]=null,layerErrors[a]=null,disableTrace=disableTrace['filter'](f=>f['layer']!==c),invalidate()),{'ok':!![]};let d;try{d=JSON['stringify'](b)??'';}catch{return{'ok':![],'error':c+':\x20fragment\x20is\x20not\x20JSON-serializable'};}if(layerSlots[a]?.['raw']===d)return{'ok':!![]};const e=parseLayerFragment(b,c);if(e['error']||!e['fragment'])return layerErrors[a]=e['error']??'rejected',{'ok':![],'error':layerErrors[a]??undefined};return layerSlots[a]={'raw':d,'fragment':e['fragment'],'label':c},layerErrors[a]=null,recordDisableTrace(a,c,e['fragment']),invalidate(),{'ok':!![]};}export function setJudgmentPersonaFragment(a,b='persona'){return setLayerFragment('persona',a,b);}export function setJudgmentIndustryOverlay(a,b='industry\x20packs'){return setLayerFragment('industry',a,b);}export function judgmentLayerError(a){return layerErrors[a];}export function validateJudgmentFragment(a,b='judgment'){return parseLayerFragment(a,b)['error']??null;}export function judgmentDisableTrace(){return disableTrace['map'](a=>({...a}));}export function clearJudgmentLayers(){layerSlots['persona']=null,layerSlots['industry']=null,layerErrors['persona']=null,layerErrors['industry']=null,disableTrace=[],invalidate();}const overrides=new Map();function resolvePath(a,b){let c=a;for(const d of b){if(!isPlainObject(c))return undefined;c=c[d];if(c===undefined)return undefined;}return c;}function applyPath(a,b,c){const d=b['split']('.'),e=structuredClone(a);let f=e;for(let g=0x0;g<d['length']-0x1;g++){f=f[d[g]];}return f[d[d['length']-0x1]]=c,e;}function typeName(a){if(Array['isArray'](a))return'array';if(a===null)return'null';return typeof a;}function sameShape(a,b){const c=typeName(a),d=typeName(b);if(c==='object'&&d==='object')return isPlainObject(a)&&isPlainObject(b);return c===d;}export function setJudgmentOverride(a,b){const c=typeof a==='string'?a['trim']():'';if(!c)return{'ok':![],'error':'\x27path\x27\x20is\x20required\x20(dotted,\x20e.g.\x20evaluation.weights.trust_reviews)'};if(b===undefined||b===null||!(typeof b==='number'||typeof b==='string'||typeof b==='boolean'||Array['isArray'](b)||isPlainObject(b)))return{'ok':![],'error':'\x27value\x27\x20must\x20be\x20a\x20JSON\x20value\x20(number\x20/\x20string\x20/\x20boolean\x20/\x20array\x20/\x20object)'};const d=c['split']('.')['filter'](Boolean),f=d[0x0];if(!JUDGMENT_SECTION_NAMES['includes'](f))return{'ok':![],'error':'Unknown\x20section\x20\x27'+f+'\x27\x20—\x20sections:\x20'+JUDGMENT_SECTION_NAMES['join'](',\x20')};probeUserDoc();const g=resolvePath(effective(),d);if(g===undefined)return{'ok':![],'error':'Unknown\x20judgment\x20path\x20\x27'+c+'\x27'};if(!sameShape(g,b))return{'ok':![],'error':'Type\x20mismatch\x20at\x20\x27'+c+'\x27\x20—\x20expected\x20'+typeName(g)+',\x20got\x20'+typeName(b)};try{JudgmentDocSchema['parse'](applyPath(effective(),c,b));}catch(h){return{'ok':![],'error':'Rejected:\x20'+(h instanceof z['ZodError']?zodMessage(h):h instanceof Error?h['message']:String(h))};}return overrides['set'](c,b),invalidate(),{'ok':!![]};}export function clearJudgmentOverride(a){const b=overrides['delete'](typeof a==='string'?a['trim']():'');if(b)invalidate();return b;}export function clearJudgmentOverrides(){const a=overrides['size'];return a>0x0&&(overrides['clear'](),invalidate()),a;}export function judgmentOverrides(){return Array['from'](overrides['entries']())['map'](([a,b])=>({'path':a,'value':b}));}export function getJudgmentDoc(){return probeUserDoc(),structuredClone(effective());}let policyRunDoc=null;export function beginPolicyRun(){policyRunDoc=getJudgmentDoc();}export function endPolicyRun(){policyRunDoc=null;}export function policyJudgmentDoc(){return policyRunDoc??getJudgmentDoc();}export function evaluationSection(){return getJudgmentDoc()['evaluation'];}export function factoryJudgmentDoc(){return structuredClone(withFactoryRulePacks(FACTORY));}export function readUserJudgmentDocView(){probeUserDoc();if(userState)return{'user_path':userJudgmentDocPath(),'exists':!![],'version':EXPECTED_JUDGMENT_VERSION,'doc':structuredClone(userState['doc'])};return{'user_path':userJudgmentDocPath(),'exists':![],'version':EXPECTED_JUDGMENT_VERSION,'doc':factoryJudgmentDoc()};}export function judgmentStatus(){probeUserDoc();const a=effective(),b={};for(const c of JUDGMENT_SECTION_NAMES){const d=a[c];if(c==='rules'&&isPlainObject(d)){const e=d['domains']??{};b[c]=Object['values'](e)['reduce']((f,g)=>f+(Array['isArray'](g['rules'])?g['rules']['length']:0x0),0x0);continue;}b[c]=Array['isArray'](d)?d['length']:isPlainObject(d)?Object['keys'](d)['length']:0x0;}return{'version':a['version'],'factory_path':FACTORY_PATH,'user_path':userJudgmentDocPath(),'user_doc_loaded':userState!==null,'user_mtime':userState?new Date(userState['mtimeMs'])['toISOString']():null,'last_reload_error':lastReloadError,'user_doc':userState?structuredClone(userState['doc']):null,'persona_fragment_loaded':layerSlots['persona']!==null,'industry_overlay_loaded':layerSlots['industry']!==null,'layer_errors':{'persona':layerErrors['persona'],'industry':layerErrors['industry']},'disable_trace':judgmentDisableTrace(),'sections':b,'overrides':judgmentOverrides()};}function jsonEqual(c,d){if(c===d)return!![];if(Array['isArray'](c)&&Array['isArray'](d))return JSON['stringify'](c)===JSON['stringify'](d);if(isPlainObject(c)&&isPlainObject(d)){const e=Object['keys'](c);if(e['length']!==Object['keys'](d)['length'])return![];return e['every'](f=>f in d&&jsonEqual(c[f],d[f]));}return![];}function collectChanges(a,c,d,e){if(isPlainObject(c)){const f=isPlainObject(a)?a:{};for(const [g,h]of Object['entries'](c)){collectChanges(f[g],h,d?d+'.'+g:g,e);}return;}!jsonEqual(a,c)&&e['push']({'path':d||'(root)','old':a===undefined?null:a,'new':c});}export function patchUserJudgmentDoc(a){const b=userJudgmentDocPath(),c=join(dirname(b),'judgment.backup.json'),d=resolveUserDocPath();if(!isPlainObject(a))throw new Error('\x27patch\x27\x20must\x20be\x20a\x20partial\x20judgment\x20document\x20object\x20(e.g.\x20{\x22evaluation\x22:\x20{\x22weights\x22:\x20{…}}})');if(a['version']!==undefined&&a['version']!==EXPECTED_JUDGMENT_VERSION)throw new Error('patch.version:\x20unsupported\x20version\x20'+String(a['version'])+'\x20(expected\x20'+EXPECTED_JUDGMENT_VERSION+')');const {version:f,...g}=a;let h;try{h=JudgmentFragmentSchema['parse'](g);}catch(s){throw new Error('patch\x20rejected:\x20'+(s instanceof z['ZodError']?zodMessage(s):s instanceof Error?s['message']:String(s)));}if(Object['keys'](h)['length']===0x0)throw new Error('\x27patch\x27\x20is\x20empty\x20—\x20nothing\x20to\x20apply\x20(sections:\x20'+JUDGMENT_SECTION_NAMES['join'](',\x20')+')');let i=null,j=![];try{const t=readFileSync(d,'utf-8');j=!![];const u=JSON['parse'](t);i=JudgmentDocInputSchema['parse'](u);}catch(v){if(j)throw new Error('the\x20current\x20user\x20document\x20is\x20not\x20a\x20valid\x20judgment\x20document\x20('+(v instanceof Error?v['message']:String(v))+')\x20—\x20fix\x20or\x20remove\x20'+d+'\x20by\x20hand\x20first');i=null;}const k=mergeJudgmentValues(i??{'version':EXPECTED_JUDGMENT_VERSION},h);k['version']=EXPECTED_JUDGMENT_VERSION;const l=withFactoryRulePacks(mergeJudgmentValues(FACTORY,k)),m=unknownDimensionKey(l)??unknownRuleRef(l)??unknownExposureRef(l)??unknownGameRef(l)??unknownScorecardRef(l)??unknownRoleIntentRef(l);if(m)throw new Error('patch\x20rejected:\x20'+m);const n=JudgmentDocSchema['safeParse'](l);if(!n['success'])throw new Error('patch\x20rejected:\x20schema:\x20'+zodMessage(n['error']));const o=judgmentDocWarnings(l),p=[];collectChanges(i??{},h,'',p);if(p['length']===0x0)return{'applied':!![],'user_path':b,'backup_path':null,'version':EXPECTED_JUDGMENT_VERSION,'changed':p,'reload_error':null,'warnings':o};const q=JSON['stringify'](k,null,0x2)+'\x0a';mkdirSync(dirname(b),{'recursive':!![]});if(j)copyFileSync(d,c);const r=b+'.tmp';writeFileSync(r,q,'utf-8'),renameSync(r,b);try{userState={'raw':q,'mtimeMs':statSync(b)['mtimeMs'],'doc':k},lastReloadError=null;}catch(w){lastReloadError=w instanceof Error?w['message']:String(w);}return invalidate(),{'applied':!![],'user_path':b,'backup_path':j?c:null,'version':EXPECTED_JUDGMENT_VERSION,'changed':p,'reload_error':lastReloadError,'warnings':o};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{afterEach,beforeEach,describe,expect,it}from'vitest';import{existsSync,mkdtempSync,readFileSync,rmSync,statSync,writeFileSync}from'node:fs';import{tmpdir}from'node:os';import{join}from'node:path';import{EXPECTED_JUDGMENT_VERSION,clearJudgmentOverride,clearJudgmentOverrides,clearJudgmentLayers,getJudgmentDoc,judgmentDisableTrace,judgmentLayerError,judgmentOverrides,judgmentStatus,mergeJudgmentValues,patchUserJudgmentDoc,readUserJudgmentDocView,setJudgmentIndustryOverlay,setJudgmentOverride,setJudgmentPersonaFragment,userJudgmentDocPath}from'./judgment.js';import{defaultWeights}from'../evaluation/standards.js';import{checkUtilRisks}from'../knowledge/util-risk.js';import{appetiteMultiplier,evaluateOutcome,interestsOf,resolveInterests}from'../evaluation/game-strategy.js';import{monitorOrder}from'../customer/order-monitor.js';import{scoreMetricValue,scoreScorecard}from'../strategy/scorecard.js';import{evaluateArbGame}from'../evaluation/arbitration-game.js';let configDir;function userDocPath(){return join(configDir,'judgment.json');}function writeUserDoc(a){writeFileSync(userDocPath(),JSON['stringify'](a,null,0x2),'utf-8');}function userDocText(){return readFileSync(userDocPath(),'utf-8');}beforeEach(()=>{configDir=mkdtempSync(join(tmpdir(),'wowok-judgment-')),process['env']['WOWOK_CONFIG_DIR']=configDir;}),afterEach(()=>{delete process['env']['WOWOK_CONFIG_DIR'];if(existsSync(configDir))rmSync(configDir,{'recursive':!![],'force':!![]});clearJudgmentOverrides(),clearJudgmentLayers();}),describe('judgment\x20baselines\x20—\x20factory\x20document',()=>{it('loads\x20the\x20factory\x20document\x20with\x20every\x20section\x20present',()=>{const a=getJudgmentDoc();expect(a['version'])['toBe'](EXPECTED_JUDGMENT_VERSION),expect(a['evaluation']['weights']['trust_reviews'])['toBe'](0x23),expect(a['evaluation']['severity_deduction']['critical'])['toBe'](0x32),expect(Object['keys'](a['game']['role_interests']))['toContain']('customer'),expect(a['game']['appetite_multipliers']['conservative'])['toBe'](1.5),expect(a['match']['region_scores']['exact'])['toBe'](0x64),expect(a['match']['top_n'])['toBe'](0x5),expect(a['monitor']['thresholds']['messenger_timeout_hours'])['toBe'](0x18),expect(a['mode']['appetite_thresholds']['balanced'])['toEqual']({'max_risk':0x3c,'min_benefit':0x3c}),expect(Object['keys'](a['scorecard']['metrics']))['toContain']('order_count'),expect(a['scorecard']['metrics']['order_count']?.['good_threshold'])['toBe'](0x14),expect(a['scorecard']['shop_evidence_metrics'])['toContain']('completion_rate'),expect(Object['keys'](a['rules']['domains']))['toContain']('util');}),it('reports\x20a\x20healthy\x20status\x20with\x20the\x20user\x20document\x20absent',()=>{const a=judgmentStatus();expect(a['user_doc_loaded'])['toBe'](![]),expect(a['last_reload_error'])['toBeNull'](),expect(a['user_path'])['toBe'](userJudgmentDocPath()),expect(a['sections']['evaluation'])['toBeGreaterThan'](0x0);});}),describe('judgment\x20baselines\x20—\x20user\x20document\x20(hot\x20reload\x20+\x20merge)',()=>{it('merges\x20user\x20keys\x20over\x20the\x20factory\x20at\x20key\x20granularity\x20(no\x20deletion)',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}});const a=getJudgmentDoc();expect(a['evaluation']['weights']['trust_reviews'])['toBe'](0x2d),expect(a['evaluation']['weights']['trust_arbitration'])['toBe'](0x14),expect(a['evaluation']['dimensions']['trust_reviews']?.['label'])['toBe']('Reputation'),expect(a['evaluation']['severity_deduction']['high'])['toBe'](0x19),expect(a['evaluation']['level_bands'][0x0])['toEqual']({'min':0x55,'level':'low'});}),it('reflects\x20a\x20document\x20edit\x20on\x20the\x20next\x20read\x20—\x20no\x20restart\x20(Q6)',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d),writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x32}}}),expect(defaultWeights()['trust_reviews'])['toBe'](0x32);}),it('keeps\x20the\x20last\x20good\x20document\x20when\x20an\x20edit\x20is\x20invalid\x20(parse\x20error)',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d),writeFileSync(userDocPath(),'{\x20not\x20json','utf-8');const a=getJudgmentDoc();expect(a['evaluation']['weights']['trust_reviews'])['toBe'](0x2d);const b=judgmentStatus();expect(b['last_reload_error'])['toBeTruthy'](),expect(b['user_doc_loaded'])['toBe'](!![]);}),it('rejects\x20unknown\x20keys\x20and\x20wrong\x20section\x20shapes\x20loudly',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d,'typoed_weight':0x1}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toMatch'](/unknown dimension 'typoed_weight'/),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d),writeUserDoc({'version':0x1,'evaluation':{'severity_deduction':{'warning':0x19}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toMatch'](/warning/i),expect(getJudgmentDoc()['evaluation']['severity_deduction']['critical'])['toBe'](0x32);}),it('gates\x20on\x20the\x20document\x20version',()=>{writeUserDoc({'version':0x63,'evaluation':{'weights':{'trust_reviews':0x2d}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toMatch'](/version/),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d);}),it('recovers\x20when\x20the\x20invalid\x20edit\x20is\x20fixed,\x20and\x20unloads\x20when\x20the\x20file\x20is\x20removed',()=>{writeUserDoc({'version':0x63}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toMatch'](/version/),writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2a}}}),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2a),expect(judgmentStatus()['last_reload_error'])['toBeNull'](),rmSync(userDocPath()),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x23);const a=judgmentStatus();expect(a['user_doc_loaded'])['toBe'](![]),expect(a['last_reload_error'])['toBeNull']();});}),describe('judgment\x20baselines\x20—\x20user\x20document\x20patch\x20channel\x20(judgment_doc_patch)',()=>{it('merges\x20a\x20patch\x20into\x20the\x20user\x20document\x20and\x20the\x20change\x20is\x20in\x20force\x20immediately',()=>{const a=patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x2d}}});expect(a['applied'])['toBe'](!![]),expect(a['user_path'])['toBe'](userJudgmentDocPath()),expect(a['backup_path'])['toBeNull'](),expect(a['changed'])['toEqual']([{'path':'evaluation.weights.trust_reviews','old':null,'new':0x2d}]),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d);const b=JSON['parse'](userDocText());expect(b['version'])['toBe'](EXPECTED_JUDGMENT_VERSION);}),it('reads\x20the\x20legacy\x20judgment-baselines.json\x20and\x20writes\x20the\x20new\x20judgment.json\x20on\x20patch',()=>{const a=join(configDir,'judgment-baselines.json');writeFileSync(a,JSON['stringify']({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}},null,0x2),'utf-8'),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d);const b=patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x32}}});expect(b['user_path'])['toBe'](userDocPath()),expect(existsSync(userDocPath()))['toBe'](!![]),expect(JSON['parse'](readFileSync(a,'utf-8')))['toEqual']({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x32),expect(judgmentStatus()['user_doc_loaded'])['toBe'](!![]);}),it('reports\x20old\x20values\x20from\x20the\x20CURRENT\x20user\x20document\x20and\x20backs\x20it\x20up',()=>{patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x2d}}});const a=patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x32}}});expect(a['changed'])['toEqual']([{'path':'evaluation.weights.trust_reviews','old':0x2d,'new':0x32}]),expect(a['backup_path'])['toBeTruthy'](),expect(existsSync(a['backup_path']))['toBe'](!![]);const b=JSON['parse'](readFileSync(a['backup_path'],'utf-8'));expect(b['evaluation']?.['weights']?.['trust_reviews'])['toBe'](0x2d),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x32);}),it('rejects\x20a\x20patch\x20without\x20touching\x20the\x20file',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),expect(()=>patchUserJudgmentDoc({'evaluation':{'weights':{'typoed_weight':0x1}}}))['toThrow'](/unknown dimension 'typoed_weight'/),expect(()=>patchUserJudgmentDoc({'rules':{'domains':{'util':{'rules':[{'rule_id':'INVENTED','enabled':![]}]}}}}))['toThrow'](/unknown rule|not a valid judgment fragment|INVENTED/i),expect(()=>patchUserJudgmentDoc({'version':0x63}))['toThrow'](/version/);const a=JSON['parse'](userDocText());expect(a['evaluation']?.['weights']?.['trust_reviews'])['toBe'](0x2d),expect(judgmentStatus()['last_reload_error'])['toBeNull']();}),it('refuses\x20to\x20patch\x20on\x20top\x20of\x20a\x20hand-broken\x20user\x20document',()=>{writeFileSync(userDocPath(),'{\x20not\x20json','utf-8'),expect(()=>getJudgmentDoc())['not']['toThrow'](),expect(()=>patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x2d}}}))['toThrow'](/not a valid judgment document/);}),it('is\x20a\x20no-op\x20when\x20the\x20patch\x20would\x20change\x20nothing',()=>{patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x2d}}});const a=statSync(userDocPath())['mtimeMs'],b=patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x2d}}});expect(b['changed'])['toEqual']([]),expect(b['backup_path'])['toBeNull'](),expect(statSync(userDocPath())['mtimeMs'])['toBe'](a);});}),describe('judgment\x20baselines\x20—\x20editable\x20view\x20(judgment_doc_read)',()=>{it('serves\x20the\x20full\x20factory\x20document\x20when\x20no\x20user\x20document\x20exists',()=>{const a=readUserJudgmentDocView();expect(a['exists'])['toBe'](![]),expect(a['user_path'])['toBe'](userJudgmentDocPath()),expect(a['version'])['toBe'](EXPECTED_JUDGMENT_VERSION);const b=a['doc'];expect(b['version'])['toBe'](EXPECTED_JUDGMENT_VERSION),expect(b['evaluation']?.['weights']?.['trust_reviews'])['toBe'](0x23),expect(Object['keys'](b['rules']?.['domains']??{}))['toContain']('util');}),it('serves\x20the\x20current\x20user\x20document\x20once\x20one\x20exists,\x20and\x20survives\x20a\x20hot\x20reload',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),getJudgmentDoc();const a=readUserJudgmentDocView();expect(a['exists'])['toBe'](!![]);const b=a['doc'];expect(b['evaluation']?.['weights']?.['trust_reviews'])['toBe'](0x2d),expect(Object['keys'](b['evaluation']?.['weights']??{}))['toEqual'](['trust_reviews']),writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x32}}}),expect(readUserJudgmentDocView()['doc']['evaluation']?.['weights']?.['trust_reviews'])['toBe'](0x32);}),it('round-trips:\x20the\x20factory\x20view\x20can\x20be\x20saved\x20back\x20as\x20a\x20valid\x20user\x20document',()=>{const a=readUserJudgmentDocView(),{version:b,...c}=a['doc'];expect(()=>patchUserJudgmentDoc(c))['not']['toThrow'](),expect(existsSync(userDocPath()))['toBe'](!![]);const d=readUserJudgmentDocView();expect(d['exists'])['toBe'](!![]);});}),describe('judgment\x20baselines\x20—\x20session\x20runtime\x20overrides',()=>{it('overrides\x20one\x20value\x20above\x20the\x20user\x20document,\x20type-checked',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),getJudgmentDoc();const a=setJudgmentOverride('evaluation.weights.trust_reviews',0x3c);expect(a)['toEqual']({'ok':!![]}),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x3c),expect(judgmentOverrides())['toEqual']([{'path':'evaluation.weights.trust_reviews','value':0x3c}]),expect(setJudgmentOverride('evaluation.weights.trust_reviews','high')['ok'])['toBe'](![]),expect(setJudgmentOverride('evaluation.weights.does_not_exist',0x1)['ok'])['toBe'](![]),expect(setJudgmentOverride('bogus.weight',0x1)['ok'])['toBe'](![]),expect(clearJudgmentOverride('evaluation.weights.trust_reviews'))['toBe'](!![]),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d);}),it('clears\x20all\x20overrides\x20at\x20once',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),getJudgmentDoc(),setJudgmentOverride('evaluation.weights.trust_reviews',0x3c),setJudgmentOverride('evaluation.severity_deduction.critical',0x28),expect(clearJudgmentOverrides())['toBe'](0x2),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d),expect(getJudgmentDoc()['evaluation']['severity_deduction']['critical'])['toBe'](0x32);});}),describe('judgment\x20baselines\x20—\x20rules\x20namespace\x20(declarative\x20rule\x20book)',()=>{it('loads\x20the\x20util\x20factory\x20pack\x20and\x20evaluates\x20through\x20the\x20live\x20book',()=>{const a=getJudgmentDoc();expect(a['rules']['domains']['util']?.['rules']['map'](c=>c['rule_id']))['toEqual'](['R-UTIL-01','R-UTIL-02','R-UTIL-03','R-UTIL-04','R-UTIL-05']);const b=Object['values'](a['rules']['domains'])['reduce']((c,e)=>c+e['rules']['length'],0x0);expect(b)['toBeGreaterThan'](0x0),expect(judgmentStatus()['sections']['rules'])['toBe'](b),expect(checkUtilRisks({'large_util_import':!![]})['map'](c=>c['id']))['toEqual'](['R-UTIL-03']);}),it('disables\x20a\x20factory\x20rule\x20via\x20a\x20disable-only\x20override\x20—\x20silent\x20+\x20trace\x20(Q12)',()=>{writeUserDoc({'version':0x1,'rules':{'domains':{'util':{'rules':[{'rule_id':'R-UTIL-03','enabled':![]}]}}}}),getJudgmentDoc(),expect(checkUtilRisks({'large_util_import':!![],'expects_util_events':!![]})['map'](b=>b['id']))['toEqual'](['R-UTIL-04']);const a=getJudgmentDoc()['rules']['domains']['util']?.['rules']['find'](b=>b['rule_id']==='R-UTIL-03');expect(a?.['enabled'])['toBe'](![]),expect(a?.['cases']['length'])['toBeGreaterThan'](0x0);}),it('rejects\x20an\x20invented\x20domain\x20with\x20a\x20loud\x20error',()=>{writeUserDoc({'version':0x1,'rules':{'domains':{'typoed_domain':{'rules':[]}}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20domain\x20\x27typoed_domain\x27');}),it('rejects\x20an\x20invented\x20rule\x20id\x20inside\x20a\x20known\x20domain',()=>{writeUserDoc({'version':0x1,'rules':{'domains':{'service':{'rules':[{'rule_id':'R-S-9-99','enabled':![]}]}}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20rule\x20\x27R-S-9-99\x27');});}),describe('judgment\x20baselines\x20—\x20merge\x20kernel',()=>{it('merges\x20plain\x20objects\x20recursively\x20and\x20replaces\x20non-id\x20arrays',()=>{const a=mergeJudgmentValues({'a':{'x':0x1,'y':0x2},'bands':[{'min':0x1,'level':'l'}]},{'a':{'y':0x3},'bands':[{'min':0x0,'level':'zero'}]});expect(a['a'])['toEqual']({'x':0x1,'y':0x3}),expect(a['bands'])['toEqual']([{'min':0x0,'level':'zero'}]);}),it('merges\x20id-bearing\x20arrays\x20by\x20entry\x20id\x20and\x20never\x20deletes\x20base\x20entries',()=>{const a=mergeJudgmentValues({'rules':[{'rule_id':'r1','severity':'high'},{'rule_id':'r2','severity':'low'}]},{'rules':[{'rule_id':'r1','severity':'critical'},{'rule_id':'r3','severity':'medium'}]}),b=new Map(a['rules']['map'](c=>[c['rule_id'],c['severity']]));expect(b['get']('r1'))['toBe']('critical'),expect(b['get']('r2'))['toBe']('low'),expect(b['get']('r3'))['toBe']('medium'),expect(a['rules'])['toHaveLength'](0x3);});}),describe('judgment\x20baselines\x20—\x20phase-3\x20sections\x20(game\x20/\x20match\x20/\x20monitor\x20/\x20mode)',()=>{it('game:\x20a\x20session\x20override\x20to\x20the\x20scoring\x20constants\x20flows\x20into\x20evaluateOutcome\x20hot',()=>{expect(evaluateOutcome('refund','customer')['net_score'])['toBe'](0x50);const a=setJudgmentOverride('game.scoring.per_gain',0x28);expect(a)['toEqual']({'ok':!![]}),expect(evaluateOutcome('refund','customer')['net_score'])['toBe'](0x64),clearJudgmentOverride('game.scoring.per_gain'),expect(evaluateOutcome('refund','customer')['net_score'])['toBe'](0x50);}),it('game:\x20appetite\x20multipliers\x20are\x20live\x20data\x20(Q8\x20numeric\x20rail)',()=>{expect(appetiteMultiplier('conservative'))['toBe'](1.5),setJudgmentOverride('game.appetite_multipliers.conservative',2.5),expect(appetiteMultiplier('conservative'))['toBe'](2.5);const a={'risk_appetite':'conservative','requirements':['never\x20arbitrate']},b=resolveInterests('customer',a);expect(b['sensitivity'])['toBeCloseTo'](2.5,0x5),clearJudgmentOverride('game.appetite_multipliers.conservative'),expect(appetiteMultiplier('conservative'))['toBe'](1.5);}),it('game:\x20a\x20user\x20document\x20can\x20retune\x20one\x20role\x27s\x20anchors\x20(key-granularity)',()=>{writeUserDoc({'version':0x1,'game':{'role_interests':{'customer':{'prefer':['node_advanced'],'avoid':[],'sensitivity':0x1}}}}),expect(interestsOf('customer')['prefer'])['toEqual'](['node_advanced']),expect(interestsOf('merchant')['prefer'])['toEqual'](['fund_released_to_merchant']);}),it('game:\x20the\x20Q5\x20keyword\x20dictionary\x20is\x20data\x20—\x20a\x20user\x20rule\x20lands\x20hot',()=>{writeUserDoc({'version':0x1,'game':{'keyword_rules':[{'id':'kw_testing','keywords':['testing'],'effect':'node_advanced','anchor':'prefer','when_forbidden':![]}]}});const a=resolveInterests('arbitrator',{'requirements':['testing\x20please']});expect(a['prefer'])['toContain']('node_advanced'),expect(resolveInterests('arbitrator',{'requirements':['milestone\x20based']})['prefer'])['toContain']('node_advanced');}),it('game:\x20invented\x20vocabulary\x20is\x20rejected\x20loudly\x20(roles\x20/\x20outcomes\x20/\x20keyword\x20effects)',()=>{writeUserDoc({'version':0x1,'game':{'role_interests':{'custmr':{'prefer':[],'avoid':[],'sensitivity':0x1}}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20role\x20\x27custmr\x27'),writeUserDoc({'version':0x1,'game':{'outcome_semantics':{'frozen':['fund_frozen']}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20outcome\x20\x27frozen\x27'),writeUserDoc({'version':0x1,'game':{'keyword_rules':[{'id':'kw_bad','keywords':['x'],'effect':'fund_frozen_forever','anchor':'avoid','when_forbidden':!![]}]}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20effect\x20\x27fund_frozen_forever\x27');}),it('monitor:\x20a\x20threshold\x20override\x20changes\x20monitorOrder\x20behavior\x20hot',()=>{const a=0x36ee80,b=0x64*a,c={'order_id':'0xorder','service_id':'0xservice','created_at':b-0x2*a,'now':b,'last_user_message_at':b-0x2*a,'has_messenger':!![],'has_arbitration':![]};expect(monitorOrder({'current':c})['map'](g=>g['id']))['not']['toContain']('messenger_unanswered'),setJudgmentOverride('monitor.thresholds.messenger_timeout_hours',0x1);const d=monitorOrder({'current':c}),e=d['find'](g=>g['id']==='messenger_unanswered');expect(e?.['severity'])['toBe']('high'),setJudgmentOverride('monitor.escalation.messenger_escalation_multiplier',1.5),expect(monitorOrder({'current':c})['find'](g=>g['id']==='messenger_unanswered')?.['severity'])['toBe']('critical'),clearJudgmentOverrides();const f=monitorOrder({'current':c,'thresholds':{'messenger_timeout_hours':0x1}});expect(f['find'](g=>g['id']==='messenger_unanswered')?.['severity'])['toBe']('high');}),it('match\x20and\x20mode:\x20parameter\x20overrides\x20land\x20in\x20the\x20effective\x20document',()=>{setJudgmentOverride('match.neutral_score',0x1e),setJudgmentOverride('match.top_n',0x3),setJudgmentOverride('mode.appetite_thresholds.aggressive',{'max_risk':0x5a,'min_benefit':0x46});const a=getJudgmentDoc();expect(a['match']['neutral_score'])['toBe'](0x1e),expect(a['match']['top_n'])['toBe'](0x3),expect(a['mode']['appetite_thresholds']['aggressive'])['toEqual']({'max_risk':0x5a,'min_benefit':0x46}),expect(a['match']['region_scores']['exact'])['toBe'](0x64),expect(a['mode']['appetite_thresholds']['balanced'])['toEqual']({'max_risk':0x3c,'min_benefit':0x3c});});}),describe('judgment\x20baselines\x20—\x20scorecard\x20section\x20(Q7\x20one\x20scoring\x20document)',()=>{function a(b){return{'account':'0xshop','industry':'education','network':'testnet','collected_at':0x0,'metrics':[{'id':'order_count','source':'market_operations','status':'ok','value':b,'collected_at':0x0}],'unavailable':[],'errors':[]};}it('scorecard:\x20anchor\x20override\x20changes\x20scoreMetricValue\x20hot',()=>{expect(scoreMetricValue('order_count',12.5))['toBe'](0x32),setJudgmentOverride('scorecard.metrics.order_count.good_threshold',0xf),expect(scoreMetricValue('order_count',12.5))['toBe'](0x4b),clearJudgmentOverride('scorecard.metrics.order_count.good_threshold'),expect(scoreMetricValue('order_count',12.5))['toBe'](0x32);}),it('scorecard:\x20posture\x20weight\x20override\x20flows\x20into\x20scoreScorecard\x20hot',()=>{const b=scoreScorecard(a(12.5),'margin')['metric_scores'][0x0]['weight'];expect(b)['toBe'](0.05),setJudgmentOverride('scorecard.metrics.order_count.weight',{'volume':0.2,'balanced':0.15,'margin':0.5}),expect(scoreScorecard(a(12.5),'margin')['metric_scores'][0x0]['weight'])['toBe'](0.5),clearJudgmentOverride('scorecard.metrics.order_count.weight');}),it('scorecard:\x20shop-evidence\x20gate\x20set\x20is\x20live\x20data',()=>{writeUserDoc({'version':0x1,'scorecard':{'shop_evidence_metrics':['order_count']}}),expect(getJudgmentDoc()['scorecard']['shop_evidence_metrics'])['toEqual'](['order_count']);}),it('scorecard:\x20invented\x20metric\x20ids\x20are\x20rejected\x20loudly',()=>{writeUserDoc({'version':0x1,'scorecard':{'metrics':{'ordr_count':{'good_threshold':0x1}}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20metric\x20\x27ordr_count\x27'),writeUserDoc({'version':0x1,'scorecard':{'shop_evidence_metrics':['phantom_metric']}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20metric\x20\x27phantom_metric\x27');});}),describe('judgment\x20baselines\x20—\x20persona\x20+\x20industry\x20layers\x20(Q4/Q12)',()=>{it('layers\x20merge\x20in\x20precedence\x20order:\x20factory\x20<\x20industry\x20pack\x20<\x20persona\x20<\x20user\x20document',()=>{expect(getJudgmentDoc()['monitor']['thresholds']['messenger_timeout_hours'])['toBe'](0x18),setJudgmentIndustryOverlay({'monitor':{'thresholds':{'messenger_timeout_hours':0x6}}},'pack:education'),expect(getJudgmentDoc()['monitor']['thresholds']['messenger_timeout_hours'])['toBe'](0x6),setJudgmentPersonaFragment({'monitor':{'thresholds':{'messenger_timeout_hours':0xc}}},'persona'),expect(getJudgmentDoc()['monitor']['thresholds']['messenger_timeout_hours'])['toBe'](0xc),writeUserDoc({'version':0x1,'monitor':{'thresholds':{'messenger_timeout_hours':0x30}}}),expect(getJudgmentDoc()['monitor']['thresholds']['messenger_timeout_hours'])['toBe'](0x30),expect(getJudgmentDoc()['monitor']['thresholds']['progress_stall_hours'])['toBe'](0x0);const a=judgmentStatus();expect(a['industry_overlay_loaded'])['toBe'](!![]),expect(a['persona_fragment_loaded'])['toBe'](!![]),expect(a['layer_errors']['persona'])['toBeNull'](),expect(a['layer_errors']['industry'])['toBeNull']();}),it('persona\x20fragment:\x20invalid\x20edit\x20is\x20rejected,\x20last\x20good\x20stays\x20in\x20force,\x20null\x20clears',()=>{setJudgmentPersonaFragment({'game':{'scoring':{'base':0x46}}}),expect(getJudgmentDoc()['game']['scoring']['base'])['toBe'](0x46);const a=setJudgmentPersonaFragment({'game':{'scoring':{'bse':0x1}}});expect(a['ok'])['toBe'](![]),expect(judgmentLayerError('persona'))['toContain']('bse'),expect(getJudgmentDoc()['game']['scoring']['base'])['toBe'](0x46),setJudgmentPersonaFragment(null),expect(judgmentLayerError('persona'))['toBeNull'](),expect(getJudgmentDoc()['game']['scoring']['base'])['toBe'](0x3c);}),it('industry\x20pack:\x20disabling\x20a\x20factory\x20rule\x20leaves\x20a\x20trace\x20and\x20lands\x20in\x20the\x20book\x20(Q12)',()=>{const a=getJudgmentDoc()['rules']['domains']['util']?.['rules'][0x0]?.['rule_id'];expect(a)['toBeTruthy']();const b=setJudgmentIndustryOverlay({'rules':{'domains':{'util':{'rules':[{'rule_id':a,'enabled':![]}]}}}},'pack:education');expect(b['ok'])['toBe'](!![]);const c=getJudgmentDoc()['rules']['domains']['util']?.['rules']['find'](d=>d['rule_id']===a);expect(c?.['enabled'])['toBe'](![]),expect(judgmentDisableTrace())['toEqual']([{'layer':'pack:education','domain':'util','rule_id':a}]),setJudgmentIndustryOverlay({'rules':{'domains':{'util':{'rules':[{'rule_id':a,'enabled':!![]}]}}}},'pack:education'),expect(judgmentDisableTrace())['toEqual']([]);}),it('layers\x20cannot\x20invent\x20rule\x20ids\x20or\x20vocabulary',()=>{const a=setJudgmentIndustryOverlay({'rules':{'domains':{'util':{'rules':[{'rule_id':'R-X-0-99','enabled':![]}]}}}});expect(a['ok'])['toBe'](![]),expect(judgmentLayerError('industry'))['toContain']('unknown\x20rule\x20\x27R-X-0-99\x27'),expect(judgmentStatus()['industry_overlay_loaded'])['toBe'](![]);const b=setJudgmentPersonaFragment({'game':{'role_interests':{'custmr':{'prefer':[],'avoid':[],'sensitivity':0x1}}}});expect(b['ok'])['toBe'](![]),expect(judgmentLayerError('persona'))['toContain']('unknown\x20role\x20\x27custmr\x27');});}),describe('judgment\x20baselines\x20—\x20arb\x20game\x20tunables\x20(game.arb)',()=>{it('factory\x20anchors\x20are\x20live\x20and\x20scoring\x20retunes\x20hot',()=>{expect(getJudgmentDoc()['game']['arb']['scoring'])['toEqual']({'base':0x3c,'per_gain':0x14,'per_risk':0x19}),expect(evaluateArbGame('Finished','arbitrator')['actions'][0x0]?.['gain_score'])['toBe'](0x28),writeUserDoc({'version':0x1,'game':{'arb':{'scoring':{'base':0x3c,'per_gain':0x28,'per_risk':0x19}}}}),expect(evaluateArbGame('Finished','arbitrator')['actions'][0x0]?.['gain_score'])['toBe'](0x50),expect(getJudgmentDoc()['game']['arb']['effect_semantics']['reversal_chance'])['toBeTruthy']();}),it('arb\x20game:\x20invented\x20perspectives\x20and\x20effects\x20are\x20rejected\x20loudly',()=>{writeUserDoc({'version':0x1,'game':{'arb':{'role_interests':{'judge':{'prefer':[],'avoid':[],'sensitivity':0x1}}}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20perspective\x20\x27judge\x27'),expect(getJudgmentDoc()['game']['arb']['scoring']['per_gain'])['toBe'](0x28),writeUserDoc({'version':0x1,'game':{'arb':{'keyword_rules':[{'id':'kw_x','keywords':['x'],'effect':'case_won','anchor':'prefer','when_forbidden':![]}]}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20effect\x20\x27case_won\x27');});});
|
|
1
|
+
import{afterEach,beforeEach,describe,expect,it}from'vitest';import{existsSync,mkdtempSync,readFileSync,rmSync,statSync,writeFileSync}from'node:fs';import{tmpdir}from'node:os';import{join}from'node:path';import{EXPECTED_JUDGMENT_VERSION,clearJudgmentOverride,clearJudgmentOverrides,clearJudgmentLayers,getJudgmentDoc,judgmentDisableTrace,judgmentLayerError,judgmentOverrides,judgmentStatus,mergeJudgmentValues,patchUserJudgmentDoc,readUserJudgmentDocView,setJudgmentIndustryOverlay,setJudgmentOverride,setJudgmentPersonaFragment,userJudgmentDocPath}from'./judgment.js';import{defaultWeights}from'../evaluation/standards.js';import{checkUtilRisks}from'../knowledge/util-risk.js';import{appetiteMultiplier,evaluateOutcome,interestsOf,resolveInterests}from'../evaluation/game-strategy.js';import{monitorOrder}from'../customer/order-monitor.js';import{scoreMetricValue,scoreScorecard}from'../strategy/scorecard.js';import{evaluateArbGame}from'../evaluation/arbitration-game.js';let configDir;function userDocPath(){return join(configDir,'judgment.json');}function writeUserDoc(a){writeFileSync(userDocPath(),JSON['stringify'](a,null,0x2),'utf-8');}function userDocText(){return readFileSync(userDocPath(),'utf-8');}beforeEach(()=>{configDir=mkdtempSync(join(tmpdir(),'wowok-judgment-')),process['env']['WOWOK_CONFIG_DIR']=configDir;}),afterEach(()=>{delete process['env']['WOWOK_CONFIG_DIR'];if(existsSync(configDir))rmSync(configDir,{'recursive':!![],'force':!![]});clearJudgmentOverrides(),clearJudgmentLayers();}),describe('judgment\x20baselines\x20—\x20factory\x20document',()=>{it('loads\x20the\x20factory\x20document\x20with\x20every\x20section\x20present',()=>{const a=getJudgmentDoc();expect(a['version'])['toBe'](EXPECTED_JUDGMENT_VERSION),expect(a['evaluation']['weights']['trust_reviews'])['toBe'](0x23),expect(a['evaluation']['severity_deduction']['critical'])['toBe'](0x32),expect(Object['keys'](a['game']['role_interests']))['toContain']('customer'),expect(a['game']['appetite_multipliers']['conservative'])['toBe'](1.5),expect(a['match']['region_scores']['exact'])['toBe'](0x64),expect(a['match']['top_n'])['toBe'](0x5),expect(a['monitor']['thresholds']['messenger_timeout_hours'])['toBe'](0x18),expect(a['mode']['appetite_thresholds']['balanced'])['toEqual']({'max_risk':0x3c,'min_benefit':0x3c}),expect(Object['keys'](a['scorecard']['metrics']))['toContain']('order_count'),expect(a['scorecard']['metrics']['order_count']?.['good_threshold'])['toBe'](0x14),expect(a['scorecard']['shop_evidence_metrics'])['toContain']('completion_rate'),expect(Object['keys'](a['rules']['domains']))['toContain']('util');}),it('reports\x20a\x20healthy\x20status\x20with\x20the\x20user\x20document\x20absent',()=>{const a=judgmentStatus();expect(a['user_doc_loaded'])['toBe'](![]),expect(a['last_reload_error'])['toBeNull'](),expect(a['user_path'])['toBe'](userJudgmentDocPath()),expect(a['sections']['evaluation'])['toBeGreaterThan'](0x0);});}),describe('judgment\x20baselines\x20—\x20user\x20document\x20(hot\x20reload\x20+\x20merge)',()=>{it('merges\x20user\x20keys\x20over\x20the\x20factory\x20at\x20key\x20granularity\x20(no\x20deletion)',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}});const a=getJudgmentDoc();expect(a['evaluation']['weights']['trust_reviews'])['toBe'](0x2d),expect(a['evaluation']['weights']['trust_arbitration'])['toBe'](0x14),expect(a['evaluation']['dimensions']['trust_reviews']?.['label'])['toBe']('Reputation'),expect(a['evaluation']['severity_deduction']['high'])['toBe'](0x19),expect(a['evaluation']['level_bands'][0x0])['toEqual']({'min':0x55,'level':'low'});}),it('reflects\x20a\x20document\x20edit\x20on\x20the\x20next\x20read\x20—\x20no\x20restart\x20(Q6)',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d),writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x32}}}),expect(defaultWeights()['trust_reviews'])['toBe'](0x32);}),it('keeps\x20the\x20last\x20good\x20document\x20when\x20an\x20edit\x20is\x20invalid\x20(parse\x20error)',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d),writeFileSync(userDocPath(),'{\x20not\x20json','utf-8');const a=getJudgmentDoc();expect(a['evaluation']['weights']['trust_reviews'])['toBe'](0x2d);const b=judgmentStatus();expect(b['last_reload_error'])['toBeTruthy'](),expect(b['user_doc_loaded'])['toBe'](!![]);}),it('rejects\x20unknown\x20keys\x20and\x20wrong\x20section\x20shapes\x20loudly',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d,'typoed_weight':0x1}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toMatch'](/unknown dimension 'typoed_weight'/),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d),writeUserDoc({'version':0x1,'evaluation':{'severity_deduction':{'warning':0x19}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toMatch'](/warning/i),expect(getJudgmentDoc()['evaluation']['severity_deduction']['critical'])['toBe'](0x32);}),it('gates\x20on\x20the\x20document\x20version',()=>{writeUserDoc({'version':0x63,'evaluation':{'weights':{'trust_reviews':0x2d}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toMatch'](/version/),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d);}),it('recovers\x20when\x20the\x20invalid\x20edit\x20is\x20fixed,\x20and\x20unloads\x20when\x20the\x20file\x20is\x20removed',()=>{writeUserDoc({'version':0x63}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toMatch'](/version/),writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2a}}}),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2a),expect(judgmentStatus()['last_reload_error'])['toBeNull'](),rmSync(userDocPath()),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x23);const a=judgmentStatus();expect(a['user_doc_loaded'])['toBe'](![]),expect(a['last_reload_error'])['toBeNull']();});}),describe('judgment\x20baselines\x20—\x20user\x20document\x20patch\x20channel\x20(judgment_doc_patch)',()=>{it('merges\x20a\x20patch\x20into\x20the\x20user\x20document\x20and\x20the\x20change\x20is\x20in\x20force\x20immediately',()=>{const a=patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x2d}}});expect(a['applied'])['toBe'](!![]),expect(a['user_path'])['toBe'](userJudgmentDocPath()),expect(a['backup_path'])['toBeNull'](),expect(a['changed'])['toEqual']([{'path':'evaluation.weights.trust_reviews','old':null,'new':0x2d}]),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d);const b=JSON['parse'](userDocText());expect(b['version'])['toBe'](EXPECTED_JUDGMENT_VERSION);}),it('reads\x20the\x20legacy\x20judgment-baselines.json\x20and\x20writes\x20the\x20new\x20judgment.json\x20on\x20patch',()=>{const a=join(configDir,'judgment-baselines.json');writeFileSync(a,JSON['stringify']({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}},null,0x2),'utf-8'),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d);const b=patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x32}}});expect(b['user_path'])['toBe'](userDocPath()),expect(existsSync(userDocPath()))['toBe'](!![]),expect(JSON['parse'](readFileSync(a,'utf-8')))['toEqual']({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x32),expect(judgmentStatus()['user_doc_loaded'])['toBe'](!![]);}),it('reports\x20old\x20values\x20from\x20the\x20CURRENT\x20user\x20document\x20and\x20backs\x20it\x20up',()=>{patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x2d}}});const a=patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x32}}});expect(a['changed'])['toEqual']([{'path':'evaluation.weights.trust_reviews','old':0x2d,'new':0x32}]),expect(a['backup_path'])['toBeTruthy'](),expect(existsSync(a['backup_path']))['toBe'](!![]);const b=JSON['parse'](readFileSync(a['backup_path'],'utf-8'));expect(b['evaluation']?.['weights']?.['trust_reviews'])['toBe'](0x2d),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x32);}),it('rejects\x20a\x20patch\x20without\x20touching\x20the\x20file',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),expect(()=>patchUserJudgmentDoc({'evaluation':{'weights':{'typoed_weight':0x1}}}))['toThrow'](/unknown dimension 'typoed_weight'/),expect(()=>patchUserJudgmentDoc({'rules':{'domains':{'util':{'rules':[{'rule_id':'INVENTED','enabled':![]}]}}}}))['toThrow'](/unknown rule|not a valid judgment fragment|INVENTED/i),expect(()=>patchUserJudgmentDoc({'version':0x63}))['toThrow'](/version/);const a=JSON['parse'](userDocText());expect(a['evaluation']?.['weights']?.['trust_reviews'])['toBe'](0x2d),expect(judgmentStatus()['last_reload_error'])['toBeNull']();}),it('refuses\x20to\x20patch\x20on\x20top\x20of\x20a\x20hand-broken\x20user\x20document',()=>{writeFileSync(userDocPath(),'{\x20not\x20json','utf-8'),expect(()=>getJudgmentDoc())['not']['toThrow'](),expect(()=>patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x2d}}}))['toThrow'](/not a valid judgment document/);}),it('is\x20a\x20no-op\x20when\x20the\x20patch\x20would\x20change\x20nothing',()=>{patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x2d}}});const a=statSync(userDocPath())['mtimeMs'],b=patchUserJudgmentDoc({'evaluation':{'weights':{'trust_reviews':0x2d}}});expect(b['changed'])['toEqual']([]),expect(b['backup_path'])['toBeNull'](),expect(statSync(userDocPath())['mtimeMs'])['toBe'](a);});}),describe('judgment\x20baselines\x20—\x20editable\x20view\x20(judgment_doc_read)',()=>{it('serves\x20the\x20full\x20factory\x20document\x20when\x20no\x20user\x20document\x20exists',()=>{const a=readUserJudgmentDocView();expect(a['exists'])['toBe'](![]),expect(a['user_path'])['toBe'](userJudgmentDocPath()),expect(a['version'])['toBe'](EXPECTED_JUDGMENT_VERSION);const b=a['doc'];expect(b['version'])['toBe'](EXPECTED_JUDGMENT_VERSION),expect(b['evaluation']?.['weights']?.['trust_reviews'])['toBe'](0x23),expect(Object['keys'](b['rules']?.['domains']??{}))['toContain']('util');}),it('serves\x20the\x20current\x20user\x20document\x20once\x20one\x20exists,\x20and\x20survives\x20a\x20hot\x20reload',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),getJudgmentDoc();const a=readUserJudgmentDocView();expect(a['exists'])['toBe'](!![]);const b=a['doc'];expect(b['evaluation']?.['weights']?.['trust_reviews'])['toBe'](0x2d),expect(Object['keys'](b['evaluation']?.['weights']??{}))['toEqual'](['trust_reviews']),writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x32}}}),expect(readUserJudgmentDocView()['doc']['evaluation']?.['weights']?.['trust_reviews'])['toBe'](0x32);}),it('round-trips:\x20the\x20factory\x20view\x20can\x20be\x20saved\x20back\x20as\x20a\x20valid\x20user\x20document',()=>{const a=readUserJudgmentDocView(),{version:b,...c}=a['doc'];expect(()=>patchUserJudgmentDoc(c))['not']['toThrow'](),expect(existsSync(userDocPath()))['toBe'](!![]);const d=readUserJudgmentDocView();expect(d['exists'])['toBe'](!![]);});}),describe('judgment\x20baselines\x20—\x20session\x20runtime\x20overrides',()=>{it('overrides\x20one\x20value\x20above\x20the\x20user\x20document,\x20type-checked',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),getJudgmentDoc();const a=setJudgmentOverride('evaluation.weights.trust_reviews',0x3c);expect(a)['toEqual']({'ok':!![]}),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x3c),expect(judgmentOverrides())['toEqual']([{'path':'evaluation.weights.trust_reviews','value':0x3c}]),expect(setJudgmentOverride('evaluation.weights.trust_reviews','high')['ok'])['toBe'](![]),expect(setJudgmentOverride('evaluation.weights.does_not_exist',0x1)['ok'])['toBe'](![]),expect(setJudgmentOverride('bogus.weight',0x1)['ok'])['toBe'](![]),expect(clearJudgmentOverride('evaluation.weights.trust_reviews'))['toBe'](!![]),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d);}),it('clears\x20all\x20overrides\x20at\x20once',()=>{writeUserDoc({'version':0x1,'evaluation':{'weights':{'trust_reviews':0x2d}}}),getJudgmentDoc(),setJudgmentOverride('evaluation.weights.trust_reviews',0x3c),setJudgmentOverride('evaluation.severity_deduction.critical',0x28),expect(clearJudgmentOverrides())['toBe'](0x2),expect(getJudgmentDoc()['evaluation']['weights']['trust_reviews'])['toBe'](0x2d),expect(getJudgmentDoc()['evaluation']['severity_deduction']['critical'])['toBe'](0x32);});}),describe('judgment\x20baselines\x20—\x20rules\x20namespace\x20(declarative\x20rule\x20book)',()=>{it('loads\x20the\x20util\x20factory\x20pack\x20and\x20evaluates\x20through\x20the\x20live\x20book',()=>{const a=getJudgmentDoc();expect(a['rules']['domains']['util']?.['rules']['map'](c=>c['rule_id']))['toEqual'](['R-UTIL-01','R-UTIL-02','R-UTIL-03','R-UTIL-04','R-UTIL-05']);const b=Object['values'](a['rules']['domains'])['reduce']((c,e)=>c+e['rules']['length'],0x0);expect(b)['toBeGreaterThan'](0x0),expect(judgmentStatus()['sections']['rules'])['toBe'](b),expect(checkUtilRisks({'large_util_import':!![]})['map'](c=>c['id']))['toEqual'](['R-UTIL-03']);}),it('disables\x20a\x20factory\x20rule\x20via\x20a\x20disable-only\x20override\x20—\x20silent\x20+\x20trace\x20(Q12)',()=>{writeUserDoc({'version':0x1,'rules':{'domains':{'util':{'rules':[{'rule_id':'R-UTIL-03','enabled':![]}]}}}}),getJudgmentDoc(),expect(checkUtilRisks({'large_util_import':!![],'expects_util_events':!![]})['map'](b=>b['id']))['toEqual'](['R-UTIL-04']);const a=getJudgmentDoc()['rules']['domains']['util']?.['rules']['find'](b=>b['rule_id']==='R-UTIL-03');expect(a?.['enabled'])['toBe'](![]),expect(a?.['cases']['length'])['toBeGreaterThan'](0x0);}),it('rejects\x20an\x20invented\x20domain\x20with\x20a\x20loud\x20error',()=>{writeUserDoc({'version':0x1,'rules':{'domains':{'typoed_domain':{'rules':[]}}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20domain\x20\x27typoed_domain\x27');}),it('rejects\x20an\x20invented\x20rule\x20id\x20inside\x20a\x20known\x20domain',()=>{writeUserDoc({'version':0x1,'rules':{'domains':{'service':{'rules':[{'rule_id':'R-S-9-99','enabled':![]}]}}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20rule\x20\x27R-S-9-99\x27');});}),describe('judgment\x20baselines\x20—\x20merge\x20kernel',()=>{it('merges\x20plain\x20objects\x20recursively\x20and\x20replaces\x20non-id\x20arrays',()=>{const a=mergeJudgmentValues({'a':{'x':0x1,'y':0x2},'bands':[{'min':0x1,'level':'l'}]},{'a':{'y':0x3},'bands':[{'min':0x0,'level':'zero'}]});expect(a['a'])['toEqual']({'x':0x1,'y':0x3}),expect(a['bands'])['toEqual']([{'min':0x0,'level':'zero'}]);}),it('merges\x20id-bearing\x20arrays\x20by\x20entry\x20id\x20and\x20never\x20deletes\x20base\x20entries',()=>{const a=mergeJudgmentValues({'rules':[{'rule_id':'r1','severity':'high'},{'rule_id':'r2','severity':'low'}]},{'rules':[{'rule_id':'r1','severity':'critical'},{'rule_id':'r3','severity':'medium'}]}),b=new Map(a['rules']['map'](c=>[c['rule_id'],c['severity']]));expect(b['get']('r1'))['toBe']('critical'),expect(b['get']('r2'))['toBe']('low'),expect(b['get']('r3'))['toBe']('medium'),expect(a['rules'])['toHaveLength'](0x3);});}),describe('judgment\x20baselines\x20—\x20phase-3\x20sections\x20(game\x20/\x20match\x20/\x20monitor\x20/\x20mode)',()=>{it('game:\x20a\x20session\x20override\x20to\x20the\x20scoring\x20constants\x20flows\x20into\x20evaluateOutcome\x20hot',()=>{expect(evaluateOutcome('refund','customer')['net_score'])['toBe'](0x50);const a=setJudgmentOverride('game.scoring.per_gain',0x28);expect(a)['toEqual']({'ok':!![]}),expect(evaluateOutcome('refund','customer')['net_score'])['toBe'](0x64),clearJudgmentOverride('game.scoring.per_gain'),expect(evaluateOutcome('refund','customer')['net_score'])['toBe'](0x50);}),it('game:\x20appetite\x20multipliers\x20are\x20live\x20data\x20(Q8\x20numeric\x20rail)',()=>{expect(appetiteMultiplier('conservative'))['toBe'](1.5),setJudgmentOverride('game.appetite_multipliers.conservative',2.5),expect(appetiteMultiplier('conservative'))['toBe'](2.5);const a={'risk_appetite':'conservative','requirements':['never\x20arbitrate']},b=resolveInterests('customer',a);expect(b['sensitivity'])['toBeCloseTo'](2.5,0x5),clearJudgmentOverride('game.appetite_multipliers.conservative'),expect(appetiteMultiplier('conservative'))['toBe'](1.5);}),it('game:\x20a\x20user\x20document\x20can\x20retune\x20one\x20role\x27s\x20anchors\x20(key-granularity)',()=>{writeUserDoc({'version':0x1,'game':{'role_interests':{'customer':{'prefer':['node_advanced'],'avoid':[],'sensitivity':0x1}}}}),expect(interestsOf('customer')['prefer'])['toEqual'](['node_advanced']),expect(interestsOf('merchant')['prefer'])['toEqual'](['fund_released_to_merchant']);}),it('game:\x20the\x20Q5\x20keyword\x20dictionary\x20is\x20data\x20—\x20a\x20user\x20rule\x20lands\x20hot',()=>{writeUserDoc({'version':0x1,'game':{'keyword_rules':[{'id':'kw_testing','keywords':['testing'],'effect':'node_advanced','anchor':'prefer','when_forbidden':![]}]}});const a=resolveInterests('arbitrator',{'requirements':['testing\x20please']});expect(a['prefer'])['toContain']('node_advanced'),expect(resolveInterests('arbitrator',{'requirements':['milestone\x20based']})['prefer'])['toContain']('node_advanced');}),it('game:\x20invented\x20vocabulary\x20is\x20rejected\x20loudly\x20(roles\x20/\x20outcomes\x20/\x20keyword\x20effects)',()=>{writeUserDoc({'version':0x1,'game':{'role_interests':{'custmr':{'prefer':[],'avoid':[],'sensitivity':0x1}}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20role\x20\x27custmr\x27'),writeUserDoc({'version':0x1,'game':{'outcome_semantics':{'frozen':['fund_frozen']}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20outcome\x20\x27frozen\x27'),writeUserDoc({'version':0x1,'game':{'keyword_rules':[{'id':'kw_bad','keywords':['x'],'effect':'fund_frozen_forever','anchor':'avoid','when_forbidden':!![]}]}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20effect\x20\x27fund_frozen_forever\x27');}),it('monitor:\x20a\x20threshold\x20override\x20changes\x20monitorOrder\x20behavior\x20hot',()=>{const a=0x36ee80,b=0x64*a,c={'order_id':'0xorder','service_id':'0xservice','created_at':b-0x2*a,'now':b,'last_user_message_at':b-0x2*a,'has_messenger':!![],'has_arbitration':![]};expect(monitorOrder({'current':c})['map'](g=>g['id']))['not']['toContain']('messenger_unanswered'),setJudgmentOverride('monitor.thresholds.messenger_timeout_hours',0x1);const d=monitorOrder({'current':c}),e=d['find'](g=>g['id']==='messenger_unanswered');expect(e?.['severity'])['toBe']('high'),setJudgmentOverride('monitor.escalation.messenger_escalation_multiplier',1.5),expect(monitorOrder({'current':c})['find'](g=>g['id']==='messenger_unanswered')?.['severity'])['toBe']('critical'),clearJudgmentOverrides();const f=monitorOrder({'current':c,'thresholds':{'messenger_timeout_hours':0x1}});expect(f['find'](g=>g['id']==='messenger_unanswered')?.['severity'])['toBe']('high');}),it('match\x20and\x20mode:\x20parameter\x20overrides\x20land\x20in\x20the\x20effective\x20document',()=>{setJudgmentOverride('match.neutral_score',0x1e),setJudgmentOverride('match.top_n',0x3),setJudgmentOverride('mode.appetite_thresholds.aggressive',{'max_risk':0x5a,'min_benefit':0x46});const a=getJudgmentDoc();expect(a['match']['neutral_score'])['toBe'](0x1e),expect(a['match']['top_n'])['toBe'](0x3),expect(a['mode']['appetite_thresholds']['aggressive'])['toEqual']({'max_risk':0x5a,'min_benefit':0x46}),expect(a['match']['region_scores']['exact'])['toBe'](0x64),expect(a['mode']['appetite_thresholds']['balanced'])['toEqual']({'max_risk':0x3c,'min_benefit':0x3c});});}),describe('judgment\x20baselines\x20—\x20scorecard\x20section\x20(Q7\x20one\x20scoring\x20document)',()=>{function a(b){return{'account':'0xshop','industry':'education','network':'testnet','collected_at':0x0,'metrics':[{'id':'order_count','source':'market_operations','status':'ok','value':b,'collected_at':0x0}],'unavailable':[],'errors':[]};}it('scorecard:\x20anchor\x20override\x20changes\x20scoreMetricValue\x20hot',()=>{expect(scoreMetricValue('order_count',12.5))['toBe'](0x32),setJudgmentOverride('scorecard.metrics.order_count.good_threshold',0xf),expect(scoreMetricValue('order_count',12.5))['toBe'](0x4b),clearJudgmentOverride('scorecard.metrics.order_count.good_threshold'),expect(scoreMetricValue('order_count',12.5))['toBe'](0x32);}),it('scorecard:\x20posture\x20weight\x20override\x20flows\x20into\x20scoreScorecard\x20hot',()=>{const b=scoreScorecard(a(12.5),'margin')['metric_scores'][0x0]['weight'];expect(b)['toBe'](0.05),setJudgmentOverride('scorecard.metrics.order_count.weight',{'volume':0.2,'balanced':0.15,'margin':0.5}),expect(scoreScorecard(a(12.5),'margin')['metric_scores'][0x0]['weight'])['toBe'](0.5),clearJudgmentOverride('scorecard.metrics.order_count.weight');}),it('scorecard:\x20shop-evidence\x20gate\x20set\x20is\x20live\x20data',()=>{writeUserDoc({'version':0x1,'scorecard':{'shop_evidence_metrics':['order_count']}}),expect(getJudgmentDoc()['scorecard']['shop_evidence_metrics'])['toEqual'](['order_count']);}),it('scorecard:\x20invented\x20metric\x20ids\x20are\x20rejected\x20loudly',()=>{writeUserDoc({'version':0x1,'scorecard':{'metrics':{'ordr_count':{'good_threshold':0x1}}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20metric\x20\x27ordr_count\x27'),writeUserDoc({'version':0x1,'scorecard':{'shop_evidence_metrics':['phantom_metric']}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20metric\x20\x27phantom_metric\x27');});}),describe('judgment\x20baselines\x20—\x20persona\x20+\x20industry\x20layers\x20(Q4/Q12)',()=>{it('layers\x20merge\x20in\x20precedence\x20order:\x20factory\x20<\x20industry\x20pack\x20<\x20user\x20document\x20<\x20persona',()=>{expect(getJudgmentDoc()['monitor']['thresholds']['messenger_timeout_hours'])['toBe'](0x18),setJudgmentIndustryOverlay({'monitor':{'thresholds':{'messenger_timeout_hours':0x6}}},'pack:education'),expect(getJudgmentDoc()['monitor']['thresholds']['messenger_timeout_hours'])['toBe'](0x6),writeUserDoc({'version':0x1,'monitor':{'thresholds':{'messenger_timeout_hours':0x30}}}),expect(getJudgmentDoc()['monitor']['thresholds']['messenger_timeout_hours'])['toBe'](0x30),setJudgmentPersonaFragment({'monitor':{'thresholds':{'messenger_timeout_hours':0xc}}},'persona'),expect(getJudgmentDoc()['monitor']['thresholds']['messenger_timeout_hours'])['toBe'](0xc),expect(getJudgmentDoc()['monitor']['thresholds']['progress_stall_hours'])['toBe'](0x0);const a=judgmentStatus();expect(a['industry_overlay_loaded'])['toBe'](!![]),expect(a['persona_fragment_loaded'])['toBe'](!![]),expect(a['layer_errors']['persona'])['toBeNull'](),expect(a['layer_errors']['industry'])['toBeNull']();}),it('persona\x20fragment:\x20invalid\x20edit\x20is\x20rejected,\x20last\x20good\x20stays\x20in\x20force,\x20null\x20clears',()=>{setJudgmentPersonaFragment({'game':{'scoring':{'base':0x46}}}),expect(getJudgmentDoc()['game']['scoring']['base'])['toBe'](0x46);const a=setJudgmentPersonaFragment({'game':{'scoring':{'bse':0x1}}});expect(a['ok'])['toBe'](![]),expect(judgmentLayerError('persona'))['toContain']('bse'),expect(getJudgmentDoc()['game']['scoring']['base'])['toBe'](0x46),setJudgmentPersonaFragment(null),expect(judgmentLayerError('persona'))['toBeNull'](),expect(getJudgmentDoc()['game']['scoring']['base'])['toBe'](0x3c);}),it('industry\x20pack:\x20disabling\x20a\x20factory\x20rule\x20leaves\x20a\x20trace\x20and\x20lands\x20in\x20the\x20book\x20(Q12)',()=>{const a=getJudgmentDoc()['rules']['domains']['util']?.['rules'][0x0]?.['rule_id'];expect(a)['toBeTruthy']();const b=setJudgmentIndustryOverlay({'rules':{'domains':{'util':{'rules':[{'rule_id':a,'enabled':![]}]}}}},'pack:education');expect(b['ok'])['toBe'](!![]);const c=getJudgmentDoc()['rules']['domains']['util']?.['rules']['find'](d=>d['rule_id']===a);expect(c?.['enabled'])['toBe'](![]),expect(judgmentDisableTrace())['toEqual']([{'layer':'pack:education','domain':'util','rule_id':a}]),setJudgmentIndustryOverlay({'rules':{'domains':{'util':{'rules':[{'rule_id':a,'enabled':!![]}]}}}},'pack:education'),expect(judgmentDisableTrace())['toEqual']([]);}),it('layers\x20cannot\x20invent\x20rule\x20ids\x20or\x20vocabulary',()=>{const a=setJudgmentIndustryOverlay({'rules':{'domains':{'util':{'rules':[{'rule_id':'R-X-0-99','enabled':![]}]}}}});expect(a['ok'])['toBe'](![]),expect(judgmentLayerError('industry'))['toContain']('unknown\x20rule\x20\x27R-X-0-99\x27'),expect(judgmentStatus()['industry_overlay_loaded'])['toBe'](![]);const b=setJudgmentPersonaFragment({'game':{'role_interests':{'custmr':{'prefer':[],'avoid':[],'sensitivity':0x1}}}});expect(b['ok'])['toBe'](![]),expect(judgmentLayerError('persona'))['toContain']('unknown\x20role\x20\x27custmr\x27');});}),describe('judgment\x20baselines\x20—\x20arb\x20game\x20tunables\x20(game.arb)',()=>{it('factory\x20anchors\x20are\x20live\x20and\x20scoring\x20retunes\x20hot',()=>{expect(getJudgmentDoc()['game']['arb']['scoring'])['toEqual']({'base':0x3c,'per_gain':0x14,'per_risk':0x19}),expect(evaluateArbGame('Finished','arbitrator')['actions'][0x0]?.['gain_score'])['toBe'](0x28),writeUserDoc({'version':0x1,'game':{'arb':{'scoring':{'base':0x3c,'per_gain':0x28,'per_risk':0x19}}}}),expect(evaluateArbGame('Finished','arbitrator')['actions'][0x0]?.['gain_score'])['toBe'](0x50),expect(getJudgmentDoc()['game']['arb']['effect_semantics']['reversal_chance'])['toBeTruthy']();}),it('arb\x20game:\x20invented\x20perspectives\x20and\x20effects\x20are\x20rejected\x20loudly',()=>{writeUserDoc({'version':0x1,'game':{'arb':{'role_interests':{'judge':{'prefer':[],'avoid':[],'sensitivity':0x1}}}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20perspective\x20\x27judge\x27'),expect(getJudgmentDoc()['game']['arb']['scoring']['per_gain'])['toBe'](0x28),writeUserDoc({'version':0x1,'game':{'arb':{'keyword_rules':[{'id':'kw_x','keywords':['x'],'effect':'case_won','anchor':'prefer','when_forbidden':![]}]}}}),getJudgmentDoc(),expect(judgmentStatus()['last_reload_error'])['toContain']('unknown\x20effect\x20\x27case_won\x27');});});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { MatchPolicy } from "../evaluation/match-policy.js";
|
|
2
|
+
export type MatchPolicyDirection = "demand_to_supply" | "supply_to_demand";
|
|
3
|
+
export interface MatchPolicyFileState {
|
|
4
|
+
path: string;
|
|
5
|
+
exists: boolean;
|
|
6
|
+
error: string | null;
|
|
7
|
+
comment?: string;
|
|
8
|
+
demand_to_supply?: MatchPolicy;
|
|
9
|
+
supply_to_demand?: MatchPolicy;
|
|
10
|
+
}
|
|
11
|
+
export declare function matchPolicyFilePath(): string;
|
|
12
|
+
export declare function getMatchPolicyFile(): MatchPolicyFileState;
|
|
13
|
+
export declare function resetMatchPolicyFileCache(): void;
|
|
14
|
+
export interface MatchPolicyPatchChange {
|
|
15
|
+
path: string;
|
|
16
|
+
old: unknown;
|
|
17
|
+
new: unknown;
|
|
18
|
+
}
|
|
19
|
+
export interface MatchPolicyPatchResult {
|
|
20
|
+
applied: true;
|
|
21
|
+
path: string;
|
|
22
|
+
backup_path: string | null;
|
|
23
|
+
changed: MatchPolicyPatchChange[];
|
|
24
|
+
error: string | null;
|
|
25
|
+
warnings: string[];
|
|
26
|
+
}
|
|
27
|
+
export interface MatchPolicyClearResult {
|
|
28
|
+
cleared: boolean;
|
|
29
|
+
path: string;
|
|
30
|
+
scope: "file" | MatchPolicyDirection;
|
|
31
|
+
backup_path: string | null;
|
|
32
|
+
}
|
|
33
|
+
export declare function patchMatchPolicyFile(patch: unknown): MatchPolicyPatchResult;
|
|
34
|
+
export declare function clearMatchPolicyFile(direction?: MatchPolicyDirection): MatchPolicyClearResult;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import*as a34a from'node:fs';import*as a34b from'node:path';import{z}from'zod';import{getWowMcpDir}from'@wowok/wowok';import{MatchPolicySchema}from'../schema/evaluation/index.js';import{matchPolicyWarnings}from'./config-warnings.js';const FILE_NAME='match-policy.json',MatchPolicyFileSchema=z['object']({'version':z['number']()['int']()['nonnegative']()['optional'](),'comment':z['string']()['optional'](),'demand_to_supply':MatchPolicySchema['optional'](),'supply_to_demand':MatchPolicySchema['optional']()})['strict']();export function matchPolicyFilePath(){const a=process['env']['WOWOK_CONFIG_DIR']||getWowMcpDir();return a34b['join'](a,FILE_NAME);}let cache=null;function bindDirection(a,b){if(a['direction']!==undefined&&a['direction']!==b)throw new Error('policy\x20\x27'+a['policy_id']+'\x27\x20declares\x20direction\x20\x27'+a['direction']+'\x27\x20under\x20the\x20\x27'+b+'\x27\x20key');return a['direction']===undefined?{...a,'direction':b}:a;}function carriedPrevious(a){return{'path':a?.['path']??'','exists':!![],'error':'',...a?.['comment']!==undefined?{'comment':a['comment']}:{},...a?.['demand_to_supply']?{'demand_to_supply':a['demand_to_supply']}:{},...a?.['supply_to_demand']?{'supply_to_demand':a['supply_to_demand']}:{}};}function readAndParse(a,b){let c;try{c=a34a['readFileSync'](a,'utf-8');}catch(d){return{...carriedPrevious(b),'path':a,'error':'unreadable:\x20'+(d instanceof Error?d['message']:String(d))};}try{const f=MatchPolicyFileSchema['parse'](JSON['parse'](c));return{'path':a,'exists':!![],'error':null,...f['comment']!==undefined?{'comment':f['comment']}:{},...f['demand_to_supply']?{'demand_to_supply':bindDirection(f['demand_to_supply'],'demand_to_supply')}:{},...f['supply_to_demand']?{'supply_to_demand':bindDirection(f['supply_to_demand'],'supply_to_demand')}:{}};}catch(g){return{...carriedPrevious(b),'path':a,'error':g instanceof z['ZodError']?'schema:\x20'+g['issues']['map'](h=>h['path']['join']('.')+':\x20'+h['message'])['join'](';\x20'):g instanceof Error?g['message']:String(g)};}}export function getMatchPolicyFile(){const a=matchPolicyFilePath();try{const b=a34a['statSync'](a);if(cache&&cache['mtimeMs']===b['mtimeMs'])return cache['state'];const c=readAndParse(a,cache?.['state']);if(c['error']===null)cache={'mtimeMs':b['mtimeMs'],'state':c};return c;}catch{return{'path':a,'exists':![],'error':null};}}export function resetMatchPolicyFileCache(){cache=null;}function isPlainObject(a){return typeof a==='object'&&a!==null&&!Array['isArray'](a);}function zodMessage(a){return a instanceof z['ZodError']?a['issues']['map'](b=>b['path']['join']('.')+':\x20'+b['message'])['join'](';\x20'):a instanceof Error?a['message']:String(a);}function deepMergeValues(a,b){if(isPlainObject(a)&&isPlainObject(b)){const c={...a};for(const [d,e]of Object['entries'](b)){c[d]=d in a?deepMergeValues(a[d],e):e;}return c;}return b;}function collectLeafChanges(a,c,d,e){if(isPlainObject(c)){const f=isPlainObject(a)?a:{};for(const [g,h]of Object['entries'](c)){collectLeafChanges(f[g],h,d?d+'.'+g:g,e);}return;}JSON['stringify'](a)!==JSON['stringify'](c)&&e['push']({'path':d||'(root)','old':a===undefined?null:a,'new':c});}export function patchMatchPolicyFile(a){const b=matchPolicyFilePath(),c=a34b['join'](a34b['dirname'](b),'match-policy.backup.json');if(!isPlainObject(a))throw new Error('\x27patch\x27\x20must\x20be\x20an\x20object\x20like\x20{\x22demand_to_supply\x22:\x20{…},\x20\x22supply_to_demand\x22:\x20{…}}');const d=Object['keys'](a)['filter'](p=>p!=='demand_to_supply'&&p!=='supply_to_demand'&&p!=='comment');if(d['length']>0x0)throw new Error('patch\x20rejected:\x20unknown\x20key(s)\x20'+d['map'](p=>'\x27'+p+'\x27')['join'](',\x20')+'\x20—\x20allowed:\x20demand_to_supply,\x20supply_to_demand,\x20comment');let f={},g=![];try{const p=a34a['readFileSync'](b,'utf-8');g=!![];const q=MatchPolicyFileSchema['parse'](JSON['parse'](p));f={...q['comment']!==undefined?{'comment':q['comment']}:{},...q['demand_to_supply']?{'demand_to_supply':q['demand_to_supply']}:{},...q['supply_to_demand']?{'supply_to_demand':q['supply_to_demand']}:{}};}catch(r){if(g)throw new Error('the\x20current\x20match-policy.json\x20is\x20not\x20a\x20valid\x20match-policy\x20document\x20('+zodMessage(r)+')\x20—\x20fix\x20or\x20remove\x20'+b+'\x20by\x20hand\x20first');f={};}const h={...f};if(a['comment']!==undefined){if(typeof a['comment']!=='string')throw new Error('patch.comment\x20must\x20be\x20a\x20string');h['comment']=a['comment'];}const i=[];for(const s of['demand_to_supply','supply_to_demand']){if(a[s]===undefined)continue;if(!isPlainObject(a[s]))throw new Error('patch.'+s+'\x20must\x20be\x20a\x20policy\x20object\x20(e.g.\x20{\x22policy_id\x22:\x20\x22my_style\x22,\x20…})');const t=f[s],u=deepMergeValues(t??{},a[s]);try{h[s]=MatchPolicySchema['parse'](u);}catch(v){throw new Error('patch.'+s+'\x20rejected:\x20'+zodMessage(v));}collectLeafChanges(t??{},a[s],s,i);}if(i['length']===0x0){const w=[...matchPolicyWarnings('demand_to_supply',f['demand_to_supply']??{}),...matchPolicyWarnings('supply_to_demand',f['supply_to_demand']??{})];return{'applied':!![],'path':b,'backup_path':null,'changed':i,'error':null,'warnings':w};}const j={'version':0x1,...h},k=MatchPolicyFileSchema['parse'](j),l=[...matchPolicyWarnings('demand_to_supply',h['demand_to_supply']??{}),...matchPolicyWarnings('supply_to_demand',h['supply_to_demand']??{})],m={'path':b,'exists':!![],'error':null,...typeof h['comment']==='string'?{'comment':h['comment']}:{},...k['demand_to_supply']?{'demand_to_supply':bindDirection(k['demand_to_supply'],'demand_to_supply')}:{},...k['supply_to_demand']?{'supply_to_demand':bindDirection(k['supply_to_demand'],'supply_to_demand')}:{}},n=JSON['stringify'](j,null,0x2)+'\x0a';a34a['mkdirSync'](a34b['dirname'](b),{'recursive':!![]});if(g)a34a['copyFileSync'](b,c);const o=b+'.tmp';return a34a['writeFileSync'](o,n,'utf-8'),a34a['renameSync'](o,b),cache={'mtimeMs':a34a['statSync'](b)['mtimeMs'],'state':m},{'applied':!![],'path':b,'backup_path':g?c:null,'changed':i,'error':null,'warnings':l};}export function clearMatchPolicyFile(a){const b=matchPolicyFilePath(),c=a34b['join'](a34b['dirname'](b),'match-policy.backup.json');try{a34a['statSync'](b);}catch{return{'cleared':![],'path':b,'scope':a??'file','backup_path':null};}a34a['copyFileSync'](b,c);if(!a)return a34a['rmSync'](b),cache=null,{'cleared':!![],'path':b,'scope':'file','backup_path':c};let d;try{d=JSON['parse'](a34a['readFileSync'](b,'utf-8'));}catch(g){throw new Error('match-policy.json\x20is\x20unreadable\x20('+zodMessage(g)+')\x20—\x20clear\x20the\x20WHOLE\x20file\x20(omit\x20\x27direction\x27)\x20or\x20remove\x20'+b+'\x20by\x20hand');}delete d[a];const f='demand_to_supply'in d||'supply_to_demand'in d;if(f){const h=JSON['stringify'](d,null,0x2)+'\x0a',i=b+'.tmp';a34a['writeFileSync'](i,h,'utf-8'),a34a['renameSync'](i,b);}else a34a['rmSync'](b);return cache=null,{'cleared':!![],'path':b,'scope':a,'backup_path':c};}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{afterEach,beforeEach,describe,expect,it}from'vitest';import*as a35a from'node:fs';import*as a35b from'node:os';import*as a35c from'node:path';import{clearMatchPolicyFile,getMatchPolicyFile,matchPolicyFilePath,patchMatchPolicyFile,resetMatchPolicyFileCache}from'./match-policy-file.js';let dir,prevConfigDir;beforeEach(()=>{dir=a35a['mkdtempSync'](a35c['join'](a35b['tmpdir'](),'wowok-match-policy-file-')),prevConfigDir=process['env']['WOWOK_CONFIG_DIR'],process['env']['WOWOK_CONFIG_DIR']=dir,resetMatchPolicyFileCache();}),afterEach(()=>{if(prevConfigDir===undefined)delete process['env']['WOWOK_CONFIG_DIR'];else process['env']['WOWOK_CONFIG_DIR']=prevConfigDir;resetMatchPolicyFileCache(),a35a['rmSync'](dir,{'recursive':!![],'force':!![]});});function fileText(){return a35a['readFileSync'](matchPolicyFilePath(),'utf-8');}describe('match-policy.json\x20—\x20patch\x20channel',()=>{it('creates\x20the\x20file\x20when\x20absent,\x20stamps\x20the\x20kernel\x20version,\x20and\x20is\x20in\x20force\x20immediately',()=>{const a=patchMatchPolicyFile({'demand_to_supply':{'policy_id':'my_buy','weights':{'region':0x1e}}});expect(a['applied'])['toBe'](!![]),expect(a['path'])['toBe'](matchPolicyFilePath()),expect(a['backup_path'])['toBeNull'](),expect(a['error'])['toBeNull'](),expect(a['changed'])['toEqual']([{'path':'demand_to_supply.policy_id','old':null,'new':'my_buy'},{'path':'demand_to_supply.weights.region','old':null,'new':0x1e}]);const b=getMatchPolicyFile();expect(b['exists'])['toBe'](!![]),expect(b['error'])['toBeNull'](),expect(b['demand_to_supply']?.['policy_id'])['toBe']('my_buy'),expect(b['demand_to_supply']?.['direction'])['toBe']('demand_to_supply');const c=JSON['parse'](fileText());expect(c['version'])['toBe'](0x1);}),it('deep-merges\x20at\x20key\x20granularity\x20and\x20reports\x20old\x20values\x20from\x20the\x20CURRENT\x20file',()=>{patchMatchPolicyFile({'demand_to_supply':{'policy_id':'my_buy','weights':{'region':0x1e,'trust':0xa}},'supply_to_demand':{'policy_id':'my_supply'}});const a=patchMatchPolicyFile({'demand_to_supply':{'weights':{'region':0x28}}});expect(a['backup_path'])['toBeTruthy']();const b=getMatchPolicyFile();expect(b['demand_to_supply']?.['weights'])['toEqual']({'region':0x28,'trust':0xa}),expect(b['supply_to_demand']?.['policy_id'])['toBe']('my_supply'),expect(a['changed'])['toEqual']([{'path':'demand_to_supply.weights.region','old':0x1e,'new':0x28}]);const c=JSON['parse'](a35a['readFileSync'](a['backup_path'],'utf-8'));expect(c['demand_to_supply']?.['weights']?.['region'])['toBe'](0x1e);}),it('rejects\x20a\x20bad\x20patch\x20loudly\x20without\x20touching\x20the\x20file',()=>{patchMatchPolicyFile({'demand_to_supply':{'policy_id':'my_buy'}});const a=fileText();expect(()=>patchMatchPolicyFile({'version':0x63}))['toThrow'](/unknown key/i),expect(()=>patchMatchPolicyFile({'demand_to_supply':{'policy_id':'my_buy','weights':{'region':'high'}}}))['toThrow'](/weights\.region/i),expect(()=>patchMatchPolicyFile({'supply_to_demand':'nope'}))['toThrow'](/policy object/),expect(fileText())['toBe'](a);}),it('never\x20patches\x20over\x20an\x20unreadable\x20existing\x20file',()=>{a35a['writeFileSync'](matchPolicyFilePath(),'{\x20not\x20json','utf-8'),expect(()=>patchMatchPolicyFile({'demand_to_supply':{'policy_id':'my_buy'}}))['toThrow'](/not a valid match-policy document.*by hand first/s);}),it('a\x20no-op\x20patch\x20skips\x20the\x20write\x20entirely',()=>{patchMatchPolicyFile({'demand_to_supply':{'policy_id':'my_buy'}});const a=fileText(),b=patchMatchPolicyFile({'demand_to_supply':{'policy_id':'my_buy'}});expect(b['changed'])['toEqual']([]),expect(b['backup_path'])['toBeNull'](),expect(fileText())['toBe'](a);});}),describe('match-policy.json\x20—\x20clear\x20channel',()=>{it('removes\x20one\x20direction;\x20an\x20empty\x20remainder\x20deletes\x20the\x20file',()=>{patchMatchPolicyFile({'demand_to_supply':{'policy_id':'my_buy'},'supply_to_demand':{'policy_id':'my_supply'}});const a=clearMatchPolicyFile('demand_to_supply');expect(a['cleared'])['toBe'](!![]),expect(a['scope'])['toBe']('demand_to_supply'),expect(a['backup_path'])['toBeTruthy']();const b=getMatchPolicyFile();expect(b['exists'])['toBe'](!![]),expect(b['demand_to_supply'])['toBeUndefined'](),expect(b['supply_to_demand']?.['policy_id'])['toBe']('my_supply');const c=clearMatchPolicyFile('supply_to_demand');expect(c['cleared'])['toBe'](!![]),expect(a35a['existsSync'](matchPolicyFilePath()))['toBe'](![]),expect(getMatchPolicyFile()['exists'])['toBe'](![]);}),it('removes\x20the\x20whole\x20file\x20when\x20no\x20direction\x20is\x20given',()=>{patchMatchPolicyFile({'supply_to_demand':{'policy_id':'my_supply'}});const a=clearMatchPolicyFile();expect(a['cleared'])['toBe'](!![]),expect(a['scope'])['toBe']('file'),expect(a['backup_path'])['toBeTruthy'](),expect(a35a['existsSync'](matchPolicyFilePath()))['toBe'](![]),expect(getMatchPolicyFile())['toMatchObject']({'exists':![],'error':null});}),it('clearing\x20an\x20absent\x20file\x20is\x20an\x20honest\x20no-op',()=>{expect(clearMatchPolicyFile())['toMatchObject']({'cleared':![],'scope':'file','backup_path':null}),expect(clearMatchPolicyFile('demand_to_supply'))['toMatchObject']({'cleared':![],'scope':'demand_to_supply','backup_path':null});}),it('refuses\x20to\x20partially\x20clear\x20an\x20unreadable\x20file',()=>{patchMatchPolicyFile({'demand_to_supply':{'policy_id':'my_buy'}}),a35a['writeFileSync'](matchPolicyFilePath(),'{\x20broken','utf-8'),expect(()=>clearMatchPolicyFile('demand_to_supply'))['toThrow'](/unreadable.*WHOLE file/s);const a=clearMatchPolicyFile();expect(a['cleared'])['toBe'](!![]),expect(a35a['existsSync'](matchPolicyFilePath()))['toBe'](![]);});});
|
|
@@ -54,9 +54,9 @@ export declare const RuleCaseSchema: z.ZodObject<{
|
|
|
54
54
|
}>;
|
|
55
55
|
path: z.ZodString;
|
|
56
56
|
viability: z.ZodUnion<readonly [z.ZodEnum<{
|
|
57
|
+
blocked: "blocked";
|
|
57
58
|
viable: "viable";
|
|
58
59
|
conditional: "conditional";
|
|
59
|
-
blocked: "blocked";
|
|
60
60
|
unverifiable: "unverifiable";
|
|
61
61
|
}>, z.ZodString]>;
|
|
62
62
|
gate: z.ZodString;
|
|
@@ -102,9 +102,9 @@ export declare const RuleEntrySchema: z.ZodObject<{
|
|
|
102
102
|
}>;
|
|
103
103
|
path: z.ZodString;
|
|
104
104
|
viability: z.ZodUnion<readonly [z.ZodEnum<{
|
|
105
|
+
blocked: "blocked";
|
|
105
106
|
viable: "viable";
|
|
106
107
|
conditional: "conditional";
|
|
107
|
-
blocked: "blocked";
|
|
108
108
|
unverifiable: "unverifiable";
|
|
109
109
|
}>, z.ZodString]>;
|
|
110
110
|
gate: z.ZodString;
|
|
@@ -155,9 +155,9 @@ export declare const RuleDomainPackSchema: z.ZodObject<{
|
|
|
155
155
|
}>;
|
|
156
156
|
path: z.ZodString;
|
|
157
157
|
viability: z.ZodUnion<readonly [z.ZodEnum<{
|
|
158
|
+
blocked: "blocked";
|
|
158
159
|
viable: "viable";
|
|
159
160
|
conditional: "conditional";
|
|
160
|
-
blocked: "blocked";
|
|
161
161
|
unverifiable: "unverifiable";
|
|
162
162
|
}>, z.ZodString]>;
|
|
163
163
|
gate: z.ZodString;
|
|
@@ -214,9 +214,9 @@ export declare const RuleEntryInputSchema: z.ZodObject<{
|
|
|
214
214
|
}>;
|
|
215
215
|
path: z.ZodString;
|
|
216
216
|
viability: z.ZodUnion<readonly [z.ZodEnum<{
|
|
217
|
+
blocked: "blocked";
|
|
217
218
|
viable: "viable";
|
|
218
219
|
conditional: "conditional";
|
|
219
|
-
blocked: "blocked";
|
|
220
220
|
unverifiable: "unverifiable";
|
|
221
221
|
}>, z.ZodString]>;
|
|
222
222
|
gate: z.ZodString;
|
|
@@ -267,9 +267,9 @@ export declare const RuleDomainPackInputSchema: z.ZodObject<{
|
|
|
267
267
|
}>;
|
|
268
268
|
path: z.ZodString;
|
|
269
269
|
viability: z.ZodUnion<readonly [z.ZodEnum<{
|
|
270
|
+
blocked: "blocked";
|
|
270
271
|
viable: "viable";
|
|
271
272
|
conditional: "conditional";
|
|
272
|
-
blocked: "blocked";
|
|
273
273
|
unverifiable: "unverifiable";
|
|
274
274
|
}>, z.ZodString]>;
|
|
275
275
|
gate: z.ZodString;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z}from'zod';import{SEVERITY_ORDER}from'./severity.js';import{ExposureFragmentSchema,FactRefSchema,applyExposureGate,parseFactRef,resolveExposureFragment}from'./exposure.js';const LEAF_OPS=['present','missing','truthy','falsy','eq','neq','gt','gte','lt','lte','in','nin','contains','matches','size'];export const RuleConditionSchema=z['lazy'](()=>z['union']([z['object']({'all':z['array'](RuleConditionSchema)})['strict'](),z['object']({'any':z['array'](RuleConditionSchema)})['strict'](),z['object']({'not':RuleConditionSchema})['strict'](),z['object']({'field':z['string'](),'op':z['enum'](LEAF_OPS),'value':z['unknown']()['optional'](),'flags':z['string']()['optional']()})['strict']()]));const CaseLevelSchema=z['union']([z['enum'](SEVERITY_ORDER),FactRefSchema]);export const RuleCaseSchema=z['object']({'when':RuleConditionSchema,'level':CaseLevelSchema,'title':z['string'](),'description':z['string'](),'scenario':z['string']()['optional'](),'mitigation':z['string']()['optional'](),'evidence':z['string']()['optional'](),'stakeholders':z['array'](z['string']())['optional'](),'exposure':ExposureFragmentSchema['optional']()})['strict']();export const RuleEntrySchema=z['object']({'rule_id':z['string'](),'dimension':z['string']()['optional'](),'trigger':z['string']()['optional'](),'cases':z['array'](RuleCaseSchema)['min'](0x1),'enabled':z['boolean']()['optional']()})['strict']();export const RuleDomainPackSchema=z['object']({'comment':z['string']()['optional'](),'facts':z['record'](z['string'](),z['string']())['optional'](),'rules':z['array'](RuleEntrySchema),'severity_overrides':z['record'](z['string'](),z['enum'](['error','warning','info']))['optional']()})['strict']();export const RuleEntryInputSchema=z['object']({'rule_id':z['string'](),'dimension':z['string']()['optional'](),'trigger':z['string']()['optional'](),'cases':z['array'](RuleCaseSchema)['optional'](),'enabled':z['boolean']()['optional']()})['strict']();export const RuleDomainPackInputSchema=z['object']({'comment':z['string']()['optional'](),'facts':z['record'](z['string'](),z['string']())['optional'](),'rules':z['array'](RuleEntryInputSchema)['optional'](),'severity_overrides':z['record'](z['string'](),z['enum'](['error','warning','info']))['optional']()})['strict']();function lookup(a,b){let c=a;for(const d of b['split']('.')){if(c===null||typeof c!=='object')return undefined;c=c[d];if(c===undefined)return undefined;}return c;}function
|
|
1
|
+
import{z}from'zod';import{SEVERITY_ORDER}from'./severity.js';import{ExposureFragmentSchema,FactRefSchema,applyExposureGate,parseFactRef,resolveExposureFragment}from'./exposure.js';const LEAF_OPS=['present','missing','truthy','falsy','eq','neq','gt','gte','lt','lte','in','nin','contains','matches','size'];export const RuleConditionSchema=z['lazy'](()=>z['union']([z['object']({'all':z['array'](RuleConditionSchema)})['strict'](),z['object']({'any':z['array'](RuleConditionSchema)})['strict'](),z['object']({'not':RuleConditionSchema})['strict'](),z['object']({'field':z['string'](),'op':z['enum'](LEAF_OPS),'value':z['unknown']()['optional'](),'flags':z['string']()['optional']()})['strict']()]));const CaseLevelSchema=z['union']([z['enum'](SEVERITY_ORDER),FactRefSchema]);export const RuleCaseSchema=z['object']({'when':RuleConditionSchema,'level':CaseLevelSchema,'title':z['string'](),'description':z['string'](),'scenario':z['string']()['optional'](),'mitigation':z['string']()['optional'](),'evidence':z['string']()['optional'](),'stakeholders':z['array'](z['string']())['optional'](),'exposure':ExposureFragmentSchema['optional']()})['strict']();export const RuleEntrySchema=z['object']({'rule_id':z['string'](),'dimension':z['string']()['optional'](),'trigger':z['string']()['optional'](),'cases':z['array'](RuleCaseSchema)['min'](0x1),'enabled':z['boolean']()['optional']()})['strict']();export const RuleDomainPackSchema=z['object']({'comment':z['string']()['optional'](),'facts':z['record'](z['string'](),z['string']())['optional'](),'rules':z['array'](RuleEntrySchema),'severity_overrides':z['record'](z['string'](),z['enum'](['error','warning','info']))['optional']()})['strict']();export const RuleEntryInputSchema=z['object']({'rule_id':z['string'](),'dimension':z['string']()['optional'](),'trigger':z['string']()['optional'](),'cases':z['array'](RuleCaseSchema)['optional'](),'enabled':z['boolean']()['optional']()})['strict']();export const RuleDomainPackInputSchema=z['object']({'comment':z['string']()['optional'](),'facts':z['record'](z['string'](),z['string']())['optional'](),'rules':z['array'](RuleEntryInputSchema)['optional'](),'severity_overrides':z['record'](z['string'](),z['enum'](['error','warning','info']))['optional']()})['strict']();function lookup(a,b){let c=a;for(const d of b['split']('.')){if(c===null||typeof c!=='object')return undefined;c=c[d];if(c===undefined)return undefined;}return c;}function toNumber(a){if(typeof a==='number'&&Number['isFinite'](a))return a;if(typeof a==='string'&&a['trim']()!==''&&Number['isFinite'](Number(a)))return Number(a);return null;}function matchesOp(c,d){const e=lookup(d,c['field']);switch(c['op']){case'present':return e!==undefined;case'missing':return e===undefined;case'truthy':return Array['isArray'](e)?e['length']>0x0:Boolean(e);case'falsy':return Array['isArray'](e)?e['length']===0x0:!e;case'eq':return e===c['value'];case'neq':return e!==c['value'];case'gt':case'gte':case'lt':case'lte':{const f=toNumber(e),g=toNumber(c['value']);if(f===null||g===null)return![];if(c['op']==='gt')return f>g;if(c['op']==='gte')return f>=g;if(c['op']==='lt')return f<g;return f<=g;}case'in':case'nin':{const h=Array['isArray'](c['value'])?c['value']:[],i=h['some'](j=>j===e);return c['op']==='in'?i:!i;}case'contains':if(Array['isArray'](e))return e['some'](j=>j===c['value']);if(typeof e==='string'&&typeof c['value']==='string')return e['includes'](c['value']);return![];case'matches':{if(typeof e!=='string'||typeof c['value']!=='string')return![];return new RegExp(c['value'],c['flags']??'i')['test'](e);}case'size':if(Array['isArray'](e))return e['length']===c['value'];if(typeof e==='string')return e['length']===c['value'];return![];}}export function evaluateCondition(a,b){if('all'in a)return a['all']['every'](d=>evaluateCondition(d,b));if('any'in a)return a['any']['some'](d=>evaluateCondition(d,b));if('not'in a)return!evaluateCondition(a['not'],b);return matchesOp(a,b);}export function interpolate(a,b){return a['replace'](/\$\{([^}]+)\}/g,(c,d)=>{const e=lookup(b,d['trim']());if(e===undefined)return c;if(typeof e==='object')return JSON['stringify'](e);return String(e);});}function resolveLevel(a,b){const c=parseFactRef(a);if(c===null)return a;const d=b[c];return SEVERITY_ORDER['includes'](String(d))?String(d):'info';}export function evaluateRuleBook(a,b){const d=[],e=[];for(const f of a){if(f['enabled']===![]){e['push'](f['rule_id']);continue;}for(const g of f['cases']){if(!evaluateCondition(g['when'],b))continue;const h=resolveLevel(g['level'],b),i=g['exposure']?resolveExposureFragment(g['exposure'],b,k=>interpolate(k,b)):undefined,j=i?applyExposureGate(h,i,{'downgradeExempt':i['downgradeExempt']}):undefined;d['push']({'rule_id':f['rule_id'],'dimension':f['dimension'],'level':j?j['severity']:h,'title':interpolate(g['title'],b),'description':interpolate(g['description'],b),'scenario':g['scenario']===undefined?undefined:interpolate(g['scenario'],b),'mitigation':g['mitigation']===undefined?undefined:interpolate(g['mitigation'],b),'evidence':g['evidence']===undefined?undefined:interpolate(g['evidence'],b),'stakeholders':g['stakeholders'],...j?{'exposure':j['exposure']}:{}});break;}}return{'findings':d,'disabled_traces':e};}
|
package/dist/config/runtime.d.ts
CHANGED
|
@@ -10,7 +10,6 @@ interface ServiceMeta {
|
|
|
10
10
|
export declare const SERVICE_REGISTRY: ServiceMeta[];
|
|
11
11
|
export declare function getHarnessTier(): HarnessTier;
|
|
12
12
|
export declare function setHarnessTier(tier: HarnessTier): void;
|
|
13
|
-
export declare function resetHarnessTier(): void;
|
|
14
13
|
export declare function isEnabled(service: ServiceName): boolean;
|
|
15
14
|
export declare function setEnabled(service: ServiceName, enabled: boolean): void;
|
|
16
15
|
export declare function toggle(service: ServiceName): boolean;
|
package/dist/config/runtime.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync,writeFileSync,existsSync,mkdirSync}from'fs';import{dirname,join}from'path';import{getWowMcpDir}from'@wowok/wowok';export const SERVICE_REGISTRY=[{'name':'confirm_gate','description':'Security\x20confirmation\x20gate\x20—\x20prompts\x20user\x20confirmation\x20before\x20amount,\x20default\x20account,\x20publish,\x20or\x20irreversible\x20operations','defaultEnabled':!![],'envVar':'WOWOK_CONFIRM_GATE','remindOnToggle':!![]},{'name':'harness','description':'L4\x20Harness\x20wrap-level\x20hooks\x20—\x20auto-escalation,\x20pre-publish/pre-sign\x20gates,\x20legacy-tool\x20recovery\x20guidance.\x20GLM5:\x20default\x20ON\x20with\x20tiered\x20enforcement\x20(off/lightweight/full).','defaultEnabled':!![],'envVar':'WOWOK_HARNESS_ENABLED','remindOnToggle':!![]},{'name':'semantic_rich','description':'Semantic\x20layer\x20enrichment\x20—\x20attaches\x20extra\x20reminder\x20info\x20such\x20as\x20service_status\x20in\x20responses','defaultEnabled':!![],'envVar':'WOWOK_SEMANTIC_RICH','remindOnToggle':![]},{'name':'experience_layer','description':'Real-time\x20experience\x20layer\x20—\x20intent\x20distillation\x20+\x20user\x20profiling\x20+\x20experience\x20reuse,\x20gets\x20smarter\x20with\x20usage','defaultEnabled':!![],'envVar':'WOWOK_EXPERIENCE_LAYER','remindOnToggle':!![]},{'name':'customer_intelligence','description':'Buyer\x20intelligence\x20(Phase\x203\x20C-3)\x20—\x20attaches\x20risk\x20reminders,\x20preference\x20matching,\x20and\x20blocking\x20alerts\x20in\x20semantic.customer_advice\x20for\x20order/query\x20operations','defaultEnabled':!![],'envVar':'WOWOK_CUSTOMER_INTELLIGENCE','remindOnToggle':!![]},{'name':'order_monitor','description':'In-progress\x20order\x20monitoring\x20(Phase\x203\x20C-3.2)\x20—\x20detects\x20Progress\x20stalls\x20/\x20compensation\x20balance\x20changes\x20/\x20Messenger\x20timeouts;\x20disabled\x20by\x20default,\x20must\x20be\x20actively\x20enabled','defaultEnabled':![],'envVar':'WOWOK_ORDER_MONITOR','remindOnToggle':!![]},{'name':'industry_evolution','description':'Industry\x20specialization\x20evolution\x20(Phase\x204)\x20—\x20AI-Human-WOW\x20flywheel\x20loop:\x20captures\x20industry\x20signals\x20+\x20updates\x20knowledge\x20+\x20injects\x20evolution\x20context','defaultEnabled':!![],'envVar':'WOWOK_INDUSTRY_EVOLUTION','remindOnToggle':!![]}];const SERVICE_MAP=new Map(SERVICE_REGISTRY['map'](a=>[a['name'],a])),runtimeOverrides=new Map();let harnessTierOverride;function configFilePath(){if(process['env']['WOWOK_CONFIG_DIR'])return join(process['env']['WOWOK_CONFIG_DIR'],'runtime-config.json');return join(getWowMcpDir(),'runtime-config.json');}function isPersistEnabled(){const a=process['env']['WOWOK_RUNTIME_CONFIG_PERSIST'];return a==='1'||a==='true';}function loadPersisted(){if(!isPersistEnabled())return null;try{const a=configFilePath();if(!existsSync(a))return null;const b=readFileSync(a,'utf-8'),c=JSON['parse'](b);if(c&&typeof c==='object'&&c['services'])return c;}catch{}return null;}function savePersisted(){if(!isPersistEnabled())return;try{const a=configFilePath(),b=dirname(a);if(!existsSync(b))mkdirSync(b,{'recursive':!![]});const c={'version':0x2,'services':Object['fromEntries'](runtimeOverrides),'harness_tier':harnessTierOverride,'updatedAt':Date['now']()};writeFileSync(a,JSON['stringify'](c,null,0x2),'utf-8');}catch{}}{const persisted=loadPersisted();if(persisted){for(const [name,enabled]of Object['entries'](persisted['services'])){SERVICE_MAP['has'](name)&&runtimeOverrides['set'](name,enabled);}persisted['harness_tier']&&(harnessTierOverride=persisted['harness_tier']);}}export function getHarnessTier(){if(!isEnabled('harness'))return'off';if(harnessTierOverride)return harnessTierOverride;const a=process['env']['WOWOK_HARNESS_TIER'];if(a==='off'||a==='lightweight'||a==='full')return a;return'lightweight';}export function setHarnessTier(a){harnessTierOverride=a,savePersisted();}export function
|
|
1
|
+
import{readFileSync,writeFileSync,existsSync,mkdirSync}from'fs';import{dirname,join}from'path';import{getWowMcpDir}from'@wowok/wowok';export const SERVICE_REGISTRY=[{'name':'confirm_gate','description':'Security\x20confirmation\x20gate\x20—\x20prompts\x20user\x20confirmation\x20before\x20amount,\x20default\x20account,\x20publish,\x20or\x20irreversible\x20operations','defaultEnabled':!![],'envVar':'WOWOK_CONFIRM_GATE','remindOnToggle':!![]},{'name':'harness','description':'L4\x20Harness\x20wrap-level\x20hooks\x20—\x20auto-escalation,\x20pre-publish/pre-sign\x20gates,\x20legacy-tool\x20recovery\x20guidance.\x20GLM5:\x20default\x20ON\x20with\x20tiered\x20enforcement\x20(off/lightweight/full).','defaultEnabled':!![],'envVar':'WOWOK_HARNESS_ENABLED','remindOnToggle':!![]},{'name':'semantic_rich','description':'Semantic\x20layer\x20enrichment\x20—\x20attaches\x20extra\x20reminder\x20info\x20such\x20as\x20service_status\x20in\x20responses','defaultEnabled':!![],'envVar':'WOWOK_SEMANTIC_RICH','remindOnToggle':![]},{'name':'experience_layer','description':'Real-time\x20experience\x20layer\x20—\x20intent\x20distillation\x20+\x20user\x20profiling\x20+\x20experience\x20reuse,\x20gets\x20smarter\x20with\x20usage','defaultEnabled':!![],'envVar':'WOWOK_EXPERIENCE_LAYER','remindOnToggle':!![]},{'name':'customer_intelligence','description':'Buyer\x20intelligence\x20(Phase\x203\x20C-3)\x20—\x20attaches\x20risk\x20reminders,\x20preference\x20matching,\x20and\x20blocking\x20alerts\x20in\x20semantic.customer_advice\x20for\x20order/query\x20operations','defaultEnabled':!![],'envVar':'WOWOK_CUSTOMER_INTELLIGENCE','remindOnToggle':!![]},{'name':'order_monitor','description':'In-progress\x20order\x20monitoring\x20(Phase\x203\x20C-3.2)\x20—\x20detects\x20Progress\x20stalls\x20/\x20compensation\x20balance\x20changes\x20/\x20Messenger\x20timeouts;\x20disabled\x20by\x20default,\x20must\x20be\x20actively\x20enabled','defaultEnabled':![],'envVar':'WOWOK_ORDER_MONITOR','remindOnToggle':!![]},{'name':'industry_evolution','description':'Industry\x20specialization\x20evolution\x20(Phase\x204)\x20—\x20AI-Human-WOW\x20flywheel\x20loop:\x20captures\x20industry\x20signals\x20+\x20updates\x20knowledge\x20+\x20injects\x20evolution\x20context','defaultEnabled':!![],'envVar':'WOWOK_INDUSTRY_EVOLUTION','remindOnToggle':!![]}];const SERVICE_MAP=new Map(SERVICE_REGISTRY['map'](a=>[a['name'],a])),runtimeOverrides=new Map();let harnessTierOverride;function configFilePath(){if(process['env']['WOWOK_CONFIG_DIR'])return join(process['env']['WOWOK_CONFIG_DIR'],'runtime-config.json');return join(getWowMcpDir(),'runtime-config.json');}function isPersistEnabled(){const a=process['env']['WOWOK_RUNTIME_CONFIG_PERSIST'];return a==='1'||a==='true';}function loadPersisted(){if(!isPersistEnabled())return null;try{const a=configFilePath();if(!existsSync(a))return null;const b=readFileSync(a,'utf-8'),c=JSON['parse'](b);if(c&&typeof c==='object'&&c['services'])return c;}catch{}return null;}function savePersisted(){if(!isPersistEnabled())return;try{const a=configFilePath(),b=dirname(a);if(!existsSync(b))mkdirSync(b,{'recursive':!![]});const c={'version':0x2,'services':Object['fromEntries'](runtimeOverrides),'harness_tier':harnessTierOverride,'updatedAt':Date['now']()};writeFileSync(a,JSON['stringify'](c,null,0x2),'utf-8');}catch{}}{const persisted=loadPersisted();if(persisted){for(const [name,enabled]of Object['entries'](persisted['services'])){SERVICE_MAP['has'](name)&&runtimeOverrides['set'](name,enabled);}persisted['harness_tier']&&(harnessTierOverride=persisted['harness_tier']);}}export function getHarnessTier(){if(!isEnabled('harness'))return'off';if(harnessTierOverride)return harnessTierOverride;const a=process['env']['WOWOK_HARNESS_TIER'];if(a==='off'||a==='lightweight'||a==='full')return a;return'lightweight';}export function setHarnessTier(a){harnessTierOverride=a,savePersisted();}export function isEnabled(a){if(runtimeOverrides['has'](a))return runtimeOverrides['get'](a);const b=SERVICE_MAP['get'](a);if(b){const c=process['env'][b['envVar']];if(c!==undefined){if(c==='0'||c==='false')return![];if(c==='1'||c==='true')return!![];}return b['defaultEnabled'];}return![];}export function setEnabled(a,b){runtimeOverrides['set'](a,b),savePersisted();}export function toggle(a){const b=!isEnabled(a);return setEnabled(a,b),b;}export function reset(a){runtimeOverrides['delete'](a),savePersisted();}export function listServices(){return SERVICE_REGISTRY['map'](a=>{const b=runtimeOverrides['has'](a['name']),c=isEnabled(a['name']);return{'name':a['name'],'enabled':c,'defaultEnabled':a['defaultEnabled'],'description':a['description'],'overridden':b,'envVar':a['envVar'],'reminder':a['remindOnToggle']?buildReminder(a['name'],c):undefined};});}export function getServiceInfo(a){const b=SERVICE_MAP['get'](a);if(!b)return undefined;return{'name':b['name'],'enabled':isEnabled(b['name']),'defaultEnabled':b['defaultEnabled'],'description':b['description'],'overridden':runtimeOverrides['has'](b['name']),'envVar':b['envVar'],'reminder':b['remindOnToggle']?buildReminder(b['name'],isEnabled(b['name'])):undefined};}function buildReminder(a,b){switch(a){case'confirm_gate':return b?'ConfirmGate\x20is\x20ON:\x20prompts\x20confirmation\x20before\x20amount,\x20default\x20account,\x20publish,\x20or\x20irreversible\x20operations.\x20To\x20disable,\x20call\x20config_operation\x20toggle\x20confirm_gate.':'ConfirmGate\x20is\x20OFF:\x20operations\x20will\x20execute\x20directly\x20without\x20confirmation.\x20Note\x20the\x20risk\x20of\x20irreversible\x20operations.\x20To\x20re-enable,\x20call\x20config_operation\x20toggle\x20confirm_gate.';case'harness':return b?'Harness\x20is\x20ON\x20(tier:\x20'+getHarnessTier()+'):\x20wrap-level\x20safety\x20hooks\x20(auto-escalation,\x20pre-publish/pre-sign\x20gates,\x20legacy-tool\x20recovery\x20guidance).\x20lightweight=post-call\x20checks;\x20full=also\x20pre-publish/pre-sign\x20gates.\x20Recovery\x20and\x20diagnosis\x20on\x20tool\x20outputs\x20always\x20run.\x20To\x20change\x20tier,\x20set\x20WOWOK_HARNESS_TIER\x20or\x20call\x20harness\x20API.\x20To\x20disable,\x20call\x20config_operation\x20toggle\x20harness.':'Harness\x20is\x20OFF.\x20GLM5\x20recommends\x20keeping\x20it\x20ON\x20(lightweight\x20tier)\x20for\x20safety.\x20To\x20enable,\x20call\x20config_operation\x20toggle\x20harness.';case'semantic_rich':return undefined;case'experience_layer':return b?'Experience\x20layer\x20is\x20ON:\x20provides\x20suggestions\x20in\x20semantic.experience\x20based\x20on\x20historical\x20operation\x20experience.\x20To\x20disable,\x20call\x20config_operation\x20toggle\x20experience_layer.':'Experience\x20layer\x20is\x20OFF:\x20no\x20experience\x20suggestions\x20will\x20be\x20attached.\x20To\x20enable,\x20call\x20config_operation\x20toggle\x20experience_layer.';case'customer_intelligence':return b?'Customer\x20intelligence\x20is\x20ON:\x20order/query\x20operations\x20will\x20attach\x20risk/preference/blocking\x20alerts\x20in\x20semantic.customer_advice.\x20To\x20disable,\x20call\x20config_operation\x20toggle\x20customer_intelligence.':'Customer\x20intelligence\x20is\x20OFF:\x20semantic.customer_advice\x20will\x20not\x20be\x20populated.\x20To\x20enable,\x20call\x20config_operation\x20toggle\x20customer_intelligence.';case'order_monitor':return b?'Order\x20monitor\x20is\x20ON:\x20detects\x20Progress\x20stalls,\x20compensation\x20balance\x20changes,\x20and\x20Messenger\x20timeouts.\x20To\x20disable,\x20call\x20config_operation\x20toggle\x20order_monitor.':'Order\x20monitor\x20is\x20OFF:\x20will\x20not\x20actively\x20detect\x20order\x20anomalies.\x20To\x20enable\x20(recommended\x20when\x20there\x20are\x20active\x20orders),\x20call\x20config_operation\x20toggle\x20order_monitor.';}}export const RUNTIME_CONFIG_VERSION=0x1;
|