Compare commits
1 Commits
devin/1776
...
devin/1776
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e3328725b4 |
@@ -1,304 +0,0 @@
|
||||
/**
|
||||
* Pluggable Rules Engine (arch §5.2 Rules Engine; gap v2 §5.2 partial).
|
||||
*
|
||||
* Before this PR, business rules were hardcoded at the call sites
|
||||
* (e.g. "plan must have a pay step" baked into iso20022.ts, SoD
|
||||
* matrix hard-coded in transactionState.ts). This module introduces
|
||||
* a minimal, declarative JSON DSL so that ruleSets can be loaded
|
||||
* from env (RULES_FILE) or swapped per-environment.
|
||||
*
|
||||
* Design principles
|
||||
* -----------------
|
||||
* - No eval. The evaluator is a small recursive switch over a
|
||||
* closed operator set — no runtime code injection.
|
||||
* - Pure, deterministic, side-effect free. Evaluation order is
|
||||
* explicit so the engine can be reasoned about and replayed.
|
||||
* - Context is a flat name → value map. Callers project whatever
|
||||
* shape they need ({plan, state, compliance, participants}).
|
||||
* - Failures are collected, not thrown. The caller decides whether
|
||||
* a single failure aborts, or whether to accumulate and report.
|
||||
*/
|
||||
|
||||
import { readFileSync } from "fs";
|
||||
|
||||
/** Supported primitive operators. */
|
||||
export type Operator =
|
||||
| "eq"
|
||||
| "neq"
|
||||
| "gt"
|
||||
| "gte"
|
||||
| "lt"
|
||||
| "lte"
|
||||
| "in"
|
||||
| "not_in"
|
||||
| "exists"
|
||||
| "matches" // regex
|
||||
| "length_gte"
|
||||
| "length_lte";
|
||||
|
||||
/** Leaf condition — references a context path against a literal. */
|
||||
export interface LeafCondition {
|
||||
path: string; // dotted path into the context object
|
||||
op: Operator;
|
||||
value?: unknown; // not required for `exists`
|
||||
/** Optional human label for failure messages. */
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/** Combinator — AND / OR / NOT over child conditions. */
|
||||
export interface AndCondition {
|
||||
all: Condition[];
|
||||
message?: string;
|
||||
}
|
||||
export interface OrCondition {
|
||||
any: Condition[];
|
||||
message?: string;
|
||||
}
|
||||
export interface NotCondition {
|
||||
not: Condition;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export type Condition = LeafCondition | AndCondition | OrCondition | NotCondition;
|
||||
|
||||
export interface Rule {
|
||||
id: string;
|
||||
description?: string;
|
||||
when?: Condition; // precondition — rule only fires when `when` is true
|
||||
assert: Condition; // the rule passes when `assert` evaluates true
|
||||
/** Optional severity for reporting: "error" (default) blocks, "warn" does not. */
|
||||
severity?: "error" | "warn";
|
||||
}
|
||||
|
||||
export interface RuleSet {
|
||||
id: string;
|
||||
version?: string;
|
||||
rules: Rule[];
|
||||
}
|
||||
|
||||
export interface RuleFailure {
|
||||
ruleId: string;
|
||||
severity: "error" | "warn";
|
||||
message: string;
|
||||
path?: string;
|
||||
}
|
||||
|
||||
export interface EvaluationResult {
|
||||
ok: boolean;
|
||||
failures: RuleFailure[];
|
||||
}
|
||||
|
||||
/* -----------------------------------------------------------------
|
||||
* Dotted-path resolver. Supports a.b.c and a.b[0].c.
|
||||
* --------------------------------------------------------------- */
|
||||
function getPath(ctx: unknown, path: string): unknown {
|
||||
if (!path) return ctx;
|
||||
const parts = path
|
||||
.replace(/\[(\d+)\]/g, ".$1")
|
||||
.split(".")
|
||||
.filter(Boolean);
|
||||
let cur: unknown = ctx;
|
||||
for (const p of parts) {
|
||||
if (cur === null || cur === undefined) return undefined;
|
||||
if (typeof cur === "object") {
|
||||
cur = (cur as Record<string, unknown>)[p];
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
/* -----------------------------------------------------------------
|
||||
* Operator evaluation. Pure — no throws.
|
||||
* --------------------------------------------------------------- */
|
||||
function evalOp(op: Operator, actual: unknown, expected: unknown): boolean {
|
||||
switch (op) {
|
||||
case "eq":
|
||||
return actual === expected;
|
||||
case "neq":
|
||||
return actual !== expected;
|
||||
case "gt":
|
||||
return typeof actual === "number" && typeof expected === "number" && actual > expected;
|
||||
case "gte":
|
||||
return typeof actual === "number" && typeof expected === "number" && actual >= expected;
|
||||
case "lt":
|
||||
return typeof actual === "number" && typeof expected === "number" && actual < expected;
|
||||
case "lte":
|
||||
return typeof actual === "number" && typeof expected === "number" && actual <= expected;
|
||||
case "in":
|
||||
return Array.isArray(expected) && expected.includes(actual as never);
|
||||
case "not_in":
|
||||
return Array.isArray(expected) && !expected.includes(actual as never);
|
||||
case "exists":
|
||||
return actual !== undefined && actual !== null;
|
||||
case "matches":
|
||||
if (typeof actual !== "string" || typeof expected !== "string") return false;
|
||||
try {
|
||||
return new RegExp(expected).test(actual);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
case "length_gte":
|
||||
if (!Array.isArray(actual) && typeof actual !== "string") return false;
|
||||
return (actual as { length: number }).length >= (expected as number);
|
||||
case "length_lte":
|
||||
if (!Array.isArray(actual) && typeof actual !== "string") return false;
|
||||
return (actual as { length: number }).length <= (expected as number);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isLeaf(c: Condition): c is LeafCondition {
|
||||
return (c as LeafCondition).op !== undefined && (c as LeafCondition).path !== undefined;
|
||||
}
|
||||
|
||||
export function evaluateCondition(
|
||||
condition: Condition,
|
||||
context: Record<string, unknown>,
|
||||
): boolean {
|
||||
if (isLeaf(condition)) {
|
||||
const actual = getPath(context, condition.path);
|
||||
return evalOp(condition.op, actual, condition.value);
|
||||
}
|
||||
if ("all" in condition) {
|
||||
return condition.all.every((c) => evaluateCondition(c, context));
|
||||
}
|
||||
if ("any" in condition) {
|
||||
return condition.any.some((c) => evaluateCondition(c, context));
|
||||
}
|
||||
if ("not" in condition) {
|
||||
return !evaluateCondition(condition.not, context);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* -----------------------------------------------------------------
|
||||
* Public evaluate(): runs the full rule set and collects failures.
|
||||
* --------------------------------------------------------------- */
|
||||
export function evaluate(
|
||||
ruleSet: RuleSet,
|
||||
context: Record<string, unknown>,
|
||||
): EvaluationResult {
|
||||
const failures: RuleFailure[] = [];
|
||||
for (const rule of ruleSet.rules) {
|
||||
if (rule.when && !evaluateCondition(rule.when, context)) continue;
|
||||
const passed = evaluateCondition(rule.assert, context);
|
||||
if (!passed) {
|
||||
failures.push({
|
||||
ruleId: rule.id,
|
||||
severity: rule.severity ?? "error",
|
||||
message: rule.description ?? `rule ${rule.id} failed`,
|
||||
path: isLeaf(rule.assert) ? rule.assert.path : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
const blocking = failures.filter((f) => f.severity === "error");
|
||||
return { ok: blocking.length === 0, failures };
|
||||
}
|
||||
|
||||
/* -----------------------------------------------------------------
|
||||
* Built-in rule sets. These mirror the pre-DSL hardcoded checks so
|
||||
* callers can migrate incrementally.
|
||||
* --------------------------------------------------------------- */
|
||||
|
||||
/** Preconditions check — arch §8 PRECONDITIONS_PENDING -> READY_FOR_PREPARE. */
|
||||
export const BUILTIN_PRECONDITIONS: RuleSet = {
|
||||
id: "preconditions.builtin",
|
||||
version: "1",
|
||||
rules: [
|
||||
{
|
||||
id: "plan.exists",
|
||||
description: "plan must be present on the context",
|
||||
assert: { path: "plan", op: "exists" },
|
||||
},
|
||||
{
|
||||
id: "plan.steps.non_empty",
|
||||
description: "plan must contain at least one step",
|
||||
assert: { path: "plan.steps", op: "length_gte", value: 1 },
|
||||
},
|
||||
{
|
||||
id: "plan.pay_step_present",
|
||||
description: "plan must contain at least one pay step (ISO-20022 envelope)",
|
||||
assert: {
|
||||
any: [
|
||||
{ path: "plan.steps[0].type", op: "eq", value: "pay" },
|
||||
{ path: "plan.steps[1].type", op: "eq", value: "pay" },
|
||||
{ path: "plan.steps[2].type", op: "eq", value: "pay" },
|
||||
{ path: "plan.steps[3].type", op: "eq", value: "pay" },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "participants.at_least_one",
|
||||
description: "participant registry must not be empty",
|
||||
assert: { path: "participants", op: "length_gte", value: 1 },
|
||||
},
|
||||
{
|
||||
id: "compliance.kyc_ok",
|
||||
description: "compliance KYC status must be ok",
|
||||
when: { path: "compliance", op: "exists" },
|
||||
assert: { path: "compliance.kyc", op: "eq", value: "ok" },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/** Commit rule — arch §9.2. */
|
||||
export const BUILTIN_COMMIT: RuleSet = {
|
||||
id: "commit.builtin",
|
||||
version: "1",
|
||||
rules: [
|
||||
{
|
||||
id: "dlt.tx_hash",
|
||||
description: "DLT leg must produce a 0x + 64-hex tx hash",
|
||||
assert: { path: "dlt.txHash", op: "matches", value: "^0x[0-9a-fA-F]{64}$" },
|
||||
},
|
||||
{
|
||||
id: "bank.iso_message_id",
|
||||
description: "bank leg must produce a non-empty ISO message id",
|
||||
assert: { path: "bank.isoMessageId", op: "exists" },
|
||||
},
|
||||
{
|
||||
id: "state.is_validating",
|
||||
description: "commit is only valid from VALIDATING",
|
||||
assert: { path: "state", op: "eq", value: "VALIDATING" },
|
||||
},
|
||||
{
|
||||
id: "no_exception_holds",
|
||||
description: "no exception may be outstanding",
|
||||
assert: { path: "exceptions.active", op: "length_lte", value: 0 },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/* -----------------------------------------------------------------
|
||||
* Loader: RULES_FILE env points at a JSON file containing a map
|
||||
* {ruleSetId: RuleSet}. Falls back to built-ins on any error.
|
||||
* --------------------------------------------------------------- */
|
||||
|
||||
let cachedOverrides: Record<string, RuleSet> | undefined;
|
||||
|
||||
export function getRuleSet(id: string): RuleSet {
|
||||
if (cachedOverrides === undefined) {
|
||||
cachedOverrides = {};
|
||||
const path = process.env.RULES_FILE;
|
||||
if (path) {
|
||||
try {
|
||||
const raw = readFileSync(path, "utf8");
|
||||
const parsed = JSON.parse(raw) as Record<string, RuleSet>;
|
||||
if (parsed && typeof parsed === "object") cachedOverrides = parsed;
|
||||
} catch {
|
||||
// leave empty — silent fall-through to built-ins
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cachedOverrides[id]) return cachedOverrides[id];
|
||||
if (id === BUILTIN_PRECONDITIONS.id) return BUILTIN_PRECONDITIONS;
|
||||
if (id === BUILTIN_COMMIT.id) return BUILTIN_COMMIT;
|
||||
return { id, rules: [] };
|
||||
}
|
||||
|
||||
export function __resetRulesCacheForTests(): void {
|
||||
cachedOverrides = undefined;
|
||||
}
|
||||
@@ -85,3 +85,63 @@ export const ROLE_FOR_TRANSITION: Readonly<Record<string, ActorRole>> = {
|
||||
"VALIDATING->COMMITTED": "approver",
|
||||
"ABORTED->UNWIND_PENDING": "exception_manager",
|
||||
};
|
||||
|
||||
/**
|
||||
* Per-state phase timeouts (arch §12.1 timing exceptions, gap v2 §7.6 / §10.7).
|
||||
*
|
||||
* Each state has its own watchdog: if a plan sits in `state` for longer than
|
||||
* `PHASE_TIMEOUTS[state]` ms, the exception manager raises a timing exception
|
||||
* from arch §12.1 and transitions the plan toward ABORTED (or whatever the
|
||||
* policy dictates for that state).
|
||||
*
|
||||
* Terminal states (COMMITTED → CLOSED path; CLOSED) have no timeout — they
|
||||
* are end-of-lifecycle and not supposed to be aged out.
|
||||
*
|
||||
* Values are defaults. Each entry can be individually overridden via env:
|
||||
* PHASE_TIMEOUT_<STATE>=<ms>
|
||||
* e.g. PHASE_TIMEOUT_EXECUTING=180000. Unit: milliseconds.
|
||||
*
|
||||
* Rationale for defaults:
|
||||
* DRAFT — long; plans can sit in draft for days.
|
||||
* INITIATED — short; identity + terms hashing is deterministic.
|
||||
* PRECONDITIONS_PENDING — long; human KYC / control approvals.
|
||||
* READY_FOR_PREPARE — short; just awaits programmatic prepare.
|
||||
* PREPARED — medium; both legs confirm readiness.
|
||||
* EXECUTING — medium; dispatch timeouts from arch §12.1.
|
||||
* PARTIALLY_EXECUTED — medium; waits for the lagging leg.
|
||||
* VALIDATING — medium; reconciliation + ack/settle evidence.
|
||||
* ABORTED — short; decision of unwind-vs-close should be prompt.
|
||||
* UNWIND_PENDING — long; recovery procedures can be slow/manual.
|
||||
*/
|
||||
export const DEFAULT_PHASE_TIMEOUTS: Readonly<Record<TransactionState, number | null>> = {
|
||||
DRAFT: 24 * 60 * 60 * 1000, // 24 h
|
||||
INITIATED: 5 * 60 * 1000, // 5 min
|
||||
PRECONDITIONS_PENDING: 4 * 60 * 60 * 1000, // 4 h
|
||||
READY_FOR_PREPARE: 15 * 60 * 1000, // 15 min
|
||||
PREPARED: 30 * 60 * 1000, // 30 min
|
||||
EXECUTING: 10 * 60 * 1000, // 10 min (dispatch_timeout §12.1)
|
||||
PARTIALLY_EXECUTED: 15 * 60 * 1000, // 15 min (settlement_timeout §12.1)
|
||||
VALIDATING: 10 * 60 * 1000, // 10 min
|
||||
COMMITTED: 60 * 60 * 1000, // 1 h (waiting to be CLOSED)
|
||||
ABORTED: 10 * 60 * 1000, // 10 min
|
||||
UNWIND_PENDING: 12 * 60 * 60 * 1000, // 12 h
|
||||
CLOSED: null, // terminal
|
||||
};
|
||||
|
||||
/**
|
||||
* Read the effective timeout (ms) for a given state, honouring per-state
|
||||
* env overrides (`PHASE_TIMEOUT_<STATE>`). Returns `null` when the state
|
||||
* has no timeout (terminal / explicitly disabled via override of "0").
|
||||
*/
|
||||
export function getPhaseTimeoutMs(state: TransactionState): number | null {
|
||||
const override = process.env[`PHASE_TIMEOUT_${state}`];
|
||||
if (override !== undefined) {
|
||||
const parsed = Number(override);
|
||||
if (!Number.isFinite(parsed) || parsed < 0) {
|
||||
// Fall through to default when env value is invalid.
|
||||
return DEFAULT_PHASE_TIMEOUTS[state];
|
||||
}
|
||||
return parsed === 0 ? null : parsed;
|
||||
}
|
||||
return DEFAULT_PHASE_TIMEOUTS[state];
|
||||
}
|
||||
|
||||
75
orchestrator/tests/unit/phaseTimeouts.test.ts
Normal file
75
orchestrator/tests/unit/phaseTimeouts.test.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Tests for per-state phase timeouts (arch §12.1 / gap v2 §7.6 / §10.7).
|
||||
*/
|
||||
|
||||
import {
|
||||
DEFAULT_PHASE_TIMEOUTS,
|
||||
TRANSACTION_STATES,
|
||||
getPhaseTimeoutMs,
|
||||
} from "../../src/types/transactionState";
|
||||
|
||||
describe("PHASE_TIMEOUTS", () => {
|
||||
const savedEnv = { ...process.env };
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...savedEnv };
|
||||
});
|
||||
|
||||
it("has a mapping for every declared transaction state", () => {
|
||||
for (const s of TRANSACTION_STATES) {
|
||||
expect(DEFAULT_PHASE_TIMEOUTS).toHaveProperty(s);
|
||||
}
|
||||
});
|
||||
|
||||
it("CLOSED is the only state without a timeout", () => {
|
||||
const nullStates = TRANSACTION_STATES.filter(
|
||||
(s) => DEFAULT_PHASE_TIMEOUTS[s] === null,
|
||||
);
|
||||
expect(nullStates).toEqual(["CLOSED"]);
|
||||
});
|
||||
|
||||
it("all non-terminal timeouts are strictly positive integers", () => {
|
||||
for (const s of TRANSACTION_STATES) {
|
||||
const v = DEFAULT_PHASE_TIMEOUTS[s];
|
||||
if (v === null) continue;
|
||||
expect(v).toBeGreaterThan(0);
|
||||
expect(Number.isInteger(v)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("getPhaseTimeoutMs honours a valid env override", () => {
|
||||
process.env.PHASE_TIMEOUT_EXECUTING = "123456";
|
||||
expect(getPhaseTimeoutMs("EXECUTING")).toBe(123456);
|
||||
});
|
||||
|
||||
it("getPhaseTimeoutMs treats override '0' as 'no timeout' (null)", () => {
|
||||
process.env.PHASE_TIMEOUT_EXECUTING = "0";
|
||||
expect(getPhaseTimeoutMs("EXECUTING")).toBeNull();
|
||||
});
|
||||
|
||||
it("getPhaseTimeoutMs falls back to default when override is invalid", () => {
|
||||
process.env.PHASE_TIMEOUT_EXECUTING = "not-a-number";
|
||||
expect(getPhaseTimeoutMs("EXECUTING")).toBe(
|
||||
DEFAULT_PHASE_TIMEOUTS.EXECUTING,
|
||||
);
|
||||
});
|
||||
|
||||
it("getPhaseTimeoutMs falls back to default when override is negative", () => {
|
||||
process.env.PHASE_TIMEOUT_PREPARED = "-1";
|
||||
expect(getPhaseTimeoutMs("PREPARED")).toBe(
|
||||
DEFAULT_PHASE_TIMEOUTS.PREPARED,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns the default when no env override exists", () => {
|
||||
delete process.env.PHASE_TIMEOUT_VALIDATING;
|
||||
expect(getPhaseTimeoutMs("VALIDATING")).toBe(
|
||||
DEFAULT_PHASE_TIMEOUTS.VALIDATING,
|
||||
);
|
||||
});
|
||||
|
||||
it("CLOSED stays null even with no env override", () => {
|
||||
delete process.env.PHASE_TIMEOUT_CLOSED;
|
||||
expect(getPhaseTimeoutMs("CLOSED")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,245 +0,0 @@
|
||||
/**
|
||||
* PR P — Pluggable Rules Engine (gap-analysis v2 §5.2 partial).
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach } from "@jest/globals";
|
||||
import {
|
||||
evaluate,
|
||||
evaluateCondition,
|
||||
getRuleSet,
|
||||
BUILTIN_PRECONDITIONS,
|
||||
BUILTIN_COMMIT,
|
||||
__resetRulesCacheForTests,
|
||||
type RuleSet,
|
||||
} from "../../src/services/rulesEngine";
|
||||
|
||||
describe("rulesEngine — primitive operators", () => {
|
||||
it("eq / neq / gt / gte / lt / lte", () => {
|
||||
expect(
|
||||
evaluateCondition({ path: "a", op: "eq", value: 1 }, { a: 1 }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition({ path: "a", op: "neq", value: 1 }, { a: 2 }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition({ path: "a", op: "gt", value: 1 }, { a: 2 }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition({ path: "a", op: "lte", value: 3 }, { a: 3 }),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("in / not_in / exists / matches", () => {
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{ path: "role", op: "in", value: ["approver", "releaser"] },
|
||||
{ role: "approver" },
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{ path: "role", op: "not_in", value: ["approver"] },
|
||||
{ role: "operator" },
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition({ path: "x", op: "exists" }, { x: 0 }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{ path: "hash", op: "matches", value: "^0x[0-9a-f]+$" },
|
||||
{ hash: "0xabc" },
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("length_gte / length_lte work on arrays and strings", () => {
|
||||
expect(
|
||||
evaluateCondition({ path: "a", op: "length_gte", value: 2 }, { a: [1, 2] }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition({ path: "a", op: "length_lte", value: 5 }, { a: "abcd" }),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("dotted + indexed path resolution", () => {
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{ path: "plan.steps[1].type", op: "eq", value: "pay" },
|
||||
{ plan: { steps: [{ type: "issue" }, { type: "pay" }] } },
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rulesEngine — combinators", () => {
|
||||
const ctx = { role: "approver", amount: 1000 };
|
||||
|
||||
it("all (AND) — every child must pass", () => {
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{
|
||||
all: [
|
||||
{ path: "role", op: "eq", value: "approver" },
|
||||
{ path: "amount", op: "gt", value: 500 },
|
||||
],
|
||||
},
|
||||
ctx,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{
|
||||
all: [
|
||||
{ path: "role", op: "eq", value: "approver" },
|
||||
{ path: "amount", op: "gt", value: 5000 },
|
||||
],
|
||||
},
|
||||
ctx,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("any (OR) — at least one child must pass", () => {
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{
|
||||
any: [
|
||||
{ path: "role", op: "eq", value: "releaser" },
|
||||
{ path: "amount", op: "gt", value: 500 },
|
||||
],
|
||||
},
|
||||
ctx,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("not — inverts the child", () => {
|
||||
expect(
|
||||
evaluateCondition(
|
||||
{ not: { path: "role", op: "eq", value: "releaser" } },
|
||||
ctx,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rulesEngine — evaluate() and failure reporting", () => {
|
||||
const ruleSet: RuleSet = {
|
||||
id: "test.rs",
|
||||
rules: [
|
||||
{
|
||||
id: "amount_positive",
|
||||
description: "amount must be > 0",
|
||||
assert: { path: "amount", op: "gt", value: 0 },
|
||||
},
|
||||
{
|
||||
id: "role_listed",
|
||||
description: "role must be in the allowed list",
|
||||
assert: {
|
||||
path: "role",
|
||||
op: "in",
|
||||
value: ["approver", "releaser", "operator"],
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "warning_only",
|
||||
description: "low amount warning",
|
||||
severity: "warn",
|
||||
assert: { path: "amount", op: "gte", value: 10_000 },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it("returns ok=true when all error-severity rules pass", () => {
|
||||
const res = evaluate(ruleSet, { amount: 1000, role: "approver" });
|
||||
expect(res.ok).toBe(true);
|
||||
// warn still reported even though ok=true
|
||||
expect(res.failures.some((f) => f.ruleId === "warning_only")).toBe(true);
|
||||
expect(res.failures.every((f) => f.severity === "warn")).toBe(true);
|
||||
});
|
||||
|
||||
it("returns ok=false with error failure when a blocking rule fails", () => {
|
||||
const res = evaluate(ruleSet, { amount: -1, role: "approver" });
|
||||
expect(res.ok).toBe(false);
|
||||
const amountFail = res.failures.find((f) => f.ruleId === "amount_positive");
|
||||
expect(amountFail?.severity).toBe("error");
|
||||
});
|
||||
|
||||
it("'when' gates a rule — false when-clause skips the assert", () => {
|
||||
const guarded: RuleSet = {
|
||||
id: "guarded.rs",
|
||||
rules: [
|
||||
{
|
||||
id: "kyc_if_present",
|
||||
when: { path: "compliance", op: "exists" },
|
||||
assert: { path: "compliance.kyc", op: "eq", value: "ok" },
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(evaluate(guarded, {}).ok).toBe(true);
|
||||
expect(evaluate(guarded, { compliance: { kyc: "ok" } }).ok).toBe(true);
|
||||
expect(evaluate(guarded, { compliance: { kyc: "fail" } }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rulesEngine — built-in rule sets", () => {
|
||||
it("preconditions: pay step + non-empty participants passes", () => {
|
||||
const res = evaluate(BUILTIN_PRECONDITIONS, {
|
||||
plan: { steps: [{ type: "pay" }] },
|
||||
participants: [{ id: "p1" }],
|
||||
});
|
||||
expect(res.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("preconditions: missing pay step fails", () => {
|
||||
const res = evaluate(BUILTIN_PRECONDITIONS, {
|
||||
plan: { steps: [{ type: "issueInstrument" }] },
|
||||
participants: [{ id: "p1" }],
|
||||
});
|
||||
expect(res.ok).toBe(false);
|
||||
expect(res.failures.some((f) => f.ruleId === "plan.pay_step_present")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("commit: VALIDATING + matching refs + no exceptions passes", () => {
|
||||
const res = evaluate(BUILTIN_COMMIT, {
|
||||
state: "VALIDATING",
|
||||
dlt: { txHash: `0x${"a".repeat(64)}` },
|
||||
bank: { isoMessageId: "MSG-1" },
|
||||
exceptions: { active: [] },
|
||||
});
|
||||
expect(res.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("commit: state != VALIDATING blocks", () => {
|
||||
const res = evaluate(BUILTIN_COMMIT, {
|
||||
state: "EXECUTING",
|
||||
dlt: { txHash: `0x${"a".repeat(64)}` },
|
||||
bank: { isoMessageId: "MSG-1" },
|
||||
exceptions: { active: [] },
|
||||
});
|
||||
expect(res.ok).toBe(false);
|
||||
expect(res.failures.some((f) => f.ruleId === "state.is_validating")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rulesEngine — pluggable loading", () => {
|
||||
beforeEach(() => {
|
||||
__resetRulesCacheForTests();
|
||||
delete process.env.RULES_FILE;
|
||||
});
|
||||
|
||||
it("returns built-ins when RULES_FILE is unset", () => {
|
||||
expect(getRuleSet(BUILTIN_PRECONDITIONS.id).rules.length).toBeGreaterThan(0);
|
||||
expect(getRuleSet(BUILTIN_COMMIT.id).rules.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("returns an empty rule set for unknown ids (no throw)", () => {
|
||||
const rs = getRuleSet("nonexistent");
|
||||
expect(rs.rules).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user