@criterionx/core 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Tomas Maritano
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # Criterion
2
+
3
+ Criterion is a **universal decision engine** for defining and executing business-critical decisions with:
4
+
5
+ - **Mandatory contracts** (validated inputs & outputs)
6
+ - **Deterministic evaluation** (same inputs → same result)
7
+ - **Explainability first-class** (every result has a reason + trace)
8
+ - **Zero side effects** (no DB, no fetch, no IO inside decisions)
9
+
10
+ > If it's not in Criterion, it's not a decision.
11
+
12
+ ## What Criterion is
13
+
14
+ Criterion is **not** a web framework and it does **not** fetch data.
15
+ It runs decisions against a provided **Context**.
16
+
17
+ A decision is a small, explicit unit of business logic:
18
+ - inputs (schema)
19
+ - outputs (schema)
20
+ - rules (ordered)
21
+ - explanations (trace)
22
+
23
+ ## What Criterion is not
24
+
25
+ Criterion is **not**:
26
+ - a workflow/BPMN engine
27
+ - an enterprise rules platform
28
+ - a plugin marketplace
29
+ - a data pipeline
30
+ - a forecasting system
31
+
32
+ Criterion is a **micro engine**: small core, strict boundaries.
33
+
34
+ ## Decision Profiles (key idea)
35
+
36
+ Criterion supports **Decision Profiles**: the same decision, different thresholds/sensitivity.
37
+
38
+ Profiles are injected explicitly at runtime:
39
+
40
+ ```ts
41
+ engine.run(decision, context, { profile: "high-inflation" })
42
+ ```
43
+
44
+ Profiles are not data. They are interpretation settings.
45
+
46
+ ## Repository structure
47
+
48
+ - `docs/` — foundational documentation
49
+ - `examples/` — decision specs in declarative formats (no code required)
50
+ - `diagrams/` — Mermaid diagrams for architecture (optional early)
51
+ - `src/` — future minimal TS implementation (later)
52
+
53
+ ## Examples (domain-agnostic)
54
+
55
+ Finance:
56
+ - `examples/finance/currency-exposure-risk/` — generic currency risk using profiles
57
+
58
+ Non-financial:
59
+ - `examples/eligibility/user-tier-eligibility/` — user tier eligibility decision
60
+
61
+ ## Start here
62
+
63
+ - `docs/00-manifesto.md`
64
+ - `docs/04-decision-profiles.md`
65
+ - `examples/finance/currency-exposure-risk/decision.xml`
66
+ - `examples/eligibility/user-tier-eligibility/decision.xml`
67
+
68
+ ## License
69
+
70
+ MIT
@@ -0,0 +1,123 @@
1
+ import { ZodSchema } from 'zod';
2
+
3
+ /**
4
+ * Result status codes
5
+ */
6
+ type ResultStatus = "OK" | "NO_MATCH" | "INVALID_INPUT" | "INVALID_OUTPUT";
7
+ /**
8
+ * Trace entry for rule evaluation
9
+ */
10
+ interface RuleTrace {
11
+ ruleId: string;
12
+ matched: boolean;
13
+ explanation?: string;
14
+ }
15
+ /**
16
+ * Result metadata
17
+ */
18
+ interface ResultMeta {
19
+ decisionId: string;
20
+ decisionVersion: string;
21
+ profileId?: string;
22
+ matchedRule?: string;
23
+ evaluatedRules: RuleTrace[];
24
+ explanation: string;
25
+ evaluatedAt: string;
26
+ }
27
+ /**
28
+ * Decision result
29
+ */
30
+ interface Result<TOutput = unknown> {
31
+ status: ResultStatus;
32
+ data: TOutput | null;
33
+ meta: ResultMeta;
34
+ }
35
+ /**
36
+ * Rule definition
37
+ */
38
+ interface Rule<TContext, TProfile, TOutput> {
39
+ id: string;
40
+ when: (context: TContext, profile: TProfile) => boolean;
41
+ emit: (context: TContext, profile: TProfile) => TOutput;
42
+ explain: (context: TContext, profile: TProfile) => string;
43
+ }
44
+ /**
45
+ * Decision metadata
46
+ */
47
+ interface DecisionMeta {
48
+ owner?: string;
49
+ tags?: string[];
50
+ tier?: string;
51
+ description?: string;
52
+ }
53
+ /**
54
+ * Decision definition
55
+ */
56
+ interface Decision<TInput = unknown, TOutput = unknown, TProfile = unknown> {
57
+ id: string;
58
+ version: string;
59
+ inputSchema: ZodSchema<TInput>;
60
+ outputSchema: ZodSchema<TOutput>;
61
+ profileSchema: ZodSchema<TProfile>;
62
+ rules: Rule<TInput, TProfile, TOutput>[];
63
+ meta?: DecisionMeta;
64
+ }
65
+ /**
66
+ * Profile registry interface
67
+ */
68
+ interface ProfileRegistry<TProfile = unknown> {
69
+ get(id: string): TProfile | undefined;
70
+ register(id: string, profile: TProfile): void;
71
+ has(id: string): boolean;
72
+ }
73
+ /**
74
+ * Engine run options
75
+ */
76
+ type RunOptions<TProfile> = {
77
+ profile: string;
78
+ } | {
79
+ profile: TProfile;
80
+ };
81
+ /**
82
+ * Helper to check if profile is inline or ID
83
+ */
84
+ declare function isInlineProfile<TProfile>(options: RunOptions<TProfile>): options is {
85
+ profile: TProfile;
86
+ };
87
+ /**
88
+ * Create a simple in-memory profile registry
89
+ */
90
+ declare function createProfileRegistry<TProfile>(): ProfileRegistry<TProfile>;
91
+ /**
92
+ * Define a decision with type inference
93
+ */
94
+ declare function defineDecision<TInput, TOutput, TProfile>(definition: Decision<TInput, TOutput, TProfile>): Decision<TInput, TOutput, TProfile>;
95
+ /**
96
+ * Create a rule with type inference
97
+ */
98
+ declare function createRule<TContext, TProfile, TOutput>(rule: Rule<TContext, TProfile, TOutput>): Rule<TContext, TProfile, TOutput>;
99
+
100
+ /**
101
+ * Criterion Engine
102
+ *
103
+ * Evaluates decisions against context with profile support.
104
+ * Pure, deterministic, and explainable.
105
+ */
106
+ declare class Engine {
107
+ /**
108
+ * Run a decision against a context
109
+ */
110
+ run<TInput, TOutput, TProfile>(decision: Decision<TInput, TOutput, TProfile>, context: TInput, options: RunOptions<TProfile>, registry?: ProfileRegistry<TProfile>): Result<TOutput>;
111
+ /**
112
+ * Format explanation for display (helper utility)
113
+ */
114
+ explain<TOutput>(result: Result<TOutput>): string;
115
+ private createErrorResult;
116
+ private formatZodError;
117
+ }
118
+ /**
119
+ * Default engine instance
120
+ */
121
+ declare const engine: Engine;
122
+
123
+ export { type Decision, type DecisionMeta, Engine, type ProfileRegistry, type Result, type ResultMeta, type ResultStatus, type Rule, type RuleTrace, type RunOptions, createProfileRegistry, createRule, defineDecision, engine, isInlineProfile };
package/dist/index.js ADDED
@@ -0,0 +1,211 @@
1
+ // src/types.ts
2
+ function isInlineProfile(options) {
3
+ return typeof options.profile !== "string";
4
+ }
5
+ function createProfileRegistry() {
6
+ const profiles = /* @__PURE__ */ new Map();
7
+ return {
8
+ get(id) {
9
+ return profiles.get(id);
10
+ },
11
+ register(id, profile) {
12
+ profiles.set(id, profile);
13
+ },
14
+ has(id) {
15
+ return profiles.has(id);
16
+ }
17
+ };
18
+ }
19
+ function defineDecision(definition) {
20
+ return definition;
21
+ }
22
+ function createRule(rule) {
23
+ return rule;
24
+ }
25
+
26
+ // src/engine.ts
27
+ var Engine = class {
28
+ /**
29
+ * Run a decision against a context
30
+ */
31
+ run(decision, context, options, registry) {
32
+ const evaluatedAt = (/* @__PURE__ */ new Date()).toISOString();
33
+ const evaluatedRules = [];
34
+ let profile;
35
+ let profileId;
36
+ if (isInlineProfile(options)) {
37
+ profile = options.profile;
38
+ } else {
39
+ profileId = options.profile;
40
+ if (!registry) {
41
+ return this.createErrorResult(
42
+ "INVALID_INPUT",
43
+ decision,
44
+ evaluatedRules,
45
+ evaluatedAt,
46
+ "Profile ID provided but no registry supplied",
47
+ profileId
48
+ );
49
+ }
50
+ const resolved = registry.get(profileId);
51
+ if (!resolved) {
52
+ return this.createErrorResult(
53
+ "INVALID_INPUT",
54
+ decision,
55
+ evaluatedRules,
56
+ evaluatedAt,
57
+ `Profile not found: ${profileId}`,
58
+ profileId
59
+ );
60
+ }
61
+ profile = resolved;
62
+ }
63
+ const inputResult = decision.inputSchema.safeParse(context);
64
+ if (!inputResult.success) {
65
+ return this.createErrorResult(
66
+ "INVALID_INPUT",
67
+ decision,
68
+ evaluatedRules,
69
+ evaluatedAt,
70
+ this.formatZodError(inputResult.error, "Input"),
71
+ profileId
72
+ );
73
+ }
74
+ const profileResult = decision.profileSchema.safeParse(profile);
75
+ if (!profileResult.success) {
76
+ return this.createErrorResult(
77
+ "INVALID_INPUT",
78
+ decision,
79
+ evaluatedRules,
80
+ evaluatedAt,
81
+ this.formatZodError(profileResult.error, "Profile"),
82
+ profileId
83
+ );
84
+ }
85
+ const validatedInput = inputResult.data;
86
+ const validatedProfile = profileResult.data;
87
+ for (const rule of decision.rules) {
88
+ let matched = false;
89
+ let explanation;
90
+ try {
91
+ matched = rule.when(validatedInput, validatedProfile);
92
+ if (matched) {
93
+ explanation = rule.explain(validatedInput, validatedProfile);
94
+ }
95
+ } catch (error) {
96
+ return this.createErrorResult(
97
+ "INVALID_INPUT",
98
+ decision,
99
+ evaluatedRules,
100
+ evaluatedAt,
101
+ `Rule evaluation error in ${rule.id}: ${String(error)}`,
102
+ profileId
103
+ );
104
+ }
105
+ evaluatedRules.push({
106
+ ruleId: rule.id,
107
+ matched,
108
+ explanation
109
+ });
110
+ if (matched) {
111
+ let output;
112
+ try {
113
+ output = rule.emit(validatedInput, validatedProfile);
114
+ } catch (error) {
115
+ return this.createErrorResult(
116
+ "INVALID_OUTPUT",
117
+ decision,
118
+ evaluatedRules,
119
+ evaluatedAt,
120
+ `Rule emit error in ${rule.id}: ${String(error)}`,
121
+ profileId
122
+ );
123
+ }
124
+ const outputResult = decision.outputSchema.safeParse(output);
125
+ if (!outputResult.success) {
126
+ return this.createErrorResult(
127
+ "INVALID_OUTPUT",
128
+ decision,
129
+ evaluatedRules,
130
+ evaluatedAt,
131
+ this.formatZodError(outputResult.error, "Output"),
132
+ profileId
133
+ );
134
+ }
135
+ return {
136
+ status: "OK",
137
+ data: outputResult.data,
138
+ meta: {
139
+ decisionId: decision.id,
140
+ decisionVersion: decision.version,
141
+ profileId,
142
+ matchedRule: rule.id,
143
+ evaluatedRules,
144
+ explanation: explanation ?? "",
145
+ evaluatedAt
146
+ }
147
+ };
148
+ }
149
+ }
150
+ return this.createErrorResult(
151
+ "NO_MATCH",
152
+ decision,
153
+ evaluatedRules,
154
+ evaluatedAt,
155
+ "No rule matched the given context",
156
+ profileId
157
+ );
158
+ }
159
+ /**
160
+ * Format explanation for display (helper utility)
161
+ */
162
+ explain(result) {
163
+ const { meta } = result;
164
+ const lines = [];
165
+ lines.push(`Decision: ${meta.decisionId} v${meta.decisionVersion}`);
166
+ if (meta.profileId) {
167
+ lines.push(`Profile: ${meta.profileId}`);
168
+ }
169
+ lines.push(`Status: ${result.status}`);
170
+ if (result.status === "OK" && meta.matchedRule) {
171
+ lines.push(`Matched: ${meta.matchedRule}`);
172
+ lines.push(`Reason: ${meta.explanation}`);
173
+ } else if (result.status !== "OK") {
174
+ lines.push(`Error: ${meta.explanation}`);
175
+ }
176
+ lines.push("");
177
+ lines.push("Evaluation trace:");
178
+ for (const trace of meta.evaluatedRules) {
179
+ const status = trace.matched ? "\u2713" : "\u2717";
180
+ lines.push(` ${status} ${trace.ruleId}`);
181
+ }
182
+ return lines.join("\n");
183
+ }
184
+ createErrorResult(status, decision, evaluatedRules, evaluatedAt, explanation, profileId) {
185
+ return {
186
+ status,
187
+ data: null,
188
+ meta: {
189
+ decisionId: decision.id,
190
+ decisionVersion: decision.version,
191
+ profileId,
192
+ evaluatedRules,
193
+ explanation,
194
+ evaluatedAt
195
+ }
196
+ };
197
+ }
198
+ formatZodError(error, prefix) {
199
+ const issues = error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", ");
200
+ return `${prefix} validation failed: ${issues}`;
201
+ }
202
+ };
203
+ var engine = new Engine();
204
+ export {
205
+ Engine,
206
+ createProfileRegistry,
207
+ createRule,
208
+ defineDecision,
209
+ engine,
210
+ isInlineProfile
211
+ };
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@criterionx/core",
3
+ "version": "0.1.1",
4
+ "description": "Universal decision engine for business-critical decisions",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "LICENSE",
17
+ "README.md"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsup src/index.ts --format esm --dts --clean",
21
+ "test": "vitest run",
22
+ "test:watch": "vitest",
23
+ "test:coverage": "vitest run --coverage",
24
+ "typecheck": "tsc --noEmit",
25
+ "prepublishOnly": "npm run build"
26
+ },
27
+ "keywords": [
28
+ "decision-engine",
29
+ "rules-engine",
30
+ "business-logic",
31
+ "deterministic",
32
+ "explainable",
33
+ "declarative",
34
+ "pure",
35
+ "audit",
36
+ "compliance"
37
+ ],
38
+ "author": {
39
+ "name": "Tomas Maritano",
40
+ "url": "https://github.com/tomymaritano"
41
+ },
42
+ "license": "MIT",
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "https://github.com/tomymaritano/criterion.git"
46
+ },
47
+ "bugs": {
48
+ "url": "https://github.com/tomymaritano/criterion/issues"
49
+ },
50
+ "homepage": "https://github.com/tomymaritano/criterion#readme",
51
+ "devDependencies": {
52
+ "@vitest/coverage-v8": "^2.0.0",
53
+ "tsup": "^8.0.0",
54
+ "typescript": "^5.3.0",
55
+ "vitest": "^2.0.0",
56
+ "zod": "^3.22.0"
57
+ },
58
+ "peerDependencies": {
59
+ "zod": "^3.22.0"
60
+ },
61
+ "engines": {
62
+ "node": ">=18"
63
+ }
64
+ }