feat: fix lowering, DSLRuntime wrapper, rigor oracle + rejection campaigns
CI / publish (push) Successful in 10s
CI / test (push) Successful in 13s

Lowering fixes (validate/lower/compile into known-correct core structures):
- tuple_to_userset: structural classification by object-side predicate
  (owner(*g, doc) { member_of(user, g) } -> tuple_to_userset with direction
  'in'/'out'); the old heuristic routed every outer-wildcard to chain.
- relational_comparator: operands now lower to real direct-rule configs
  (evaluateFrom derived from evidence param positions; expectedValue for
  literal args) instead of raw AST nodes the engine could not evaluate.
- defeasible: multi-level bodies (NEVER/REQUIRES/ALWAYS/WHEN/UNLESS) merge
  into one five-level rule instead of ANDed level-only rules that always
  resolved 0; nested PatternMatches flatten to N-step chains; unary predicate
  calls mark _subjectAsObject (subject-as-object semantics).
- validation: reject duplicate fact/evidence definitions.

DSLRuntime (higher-order DSL+Core wrapper):
- typed addNode/updateNodeData/addRelation/updateRelation against the DSL
  schema (known types, relation params, field types, value-carrying facts);
- check() derives the evidence's injectable partial-graph requirements,
  retrieves missing facts through caller data callbacks, injects them, and
  delegates, returning requiredFacts/providedFacts/missingFacts.

js-rigor campaigns:
- generative oracle: generate legal DSL per construct and compare every
  verdict against an independent hand-computed oracle (8 constructs x P grid)
  plus an exhaustive deterministic sweep;
- illegal mutations: one-flaw perturbations of a valid program must be
  reliably rejected (duplicate evidence/fact, arity/type mismatches, reserved
  built-ins, malformed syntax), with a control that must compile.

Depends on @arbiter/core@^1.0.2 (reason codes + _subjectAsObject).
This commit is contained in:
John Dvorak
2026-08-03 10:58:29 -07:00
parent 0c2ddc282b
commit 0a744329e6
11 changed files with 1530 additions and 89 deletions
+331 -81
View File
@@ -258,26 +258,27 @@ export class RuleGenerator {
// Handle single statement evidence
if (statements.length === 1) {
return this.buildSingleStatementRule(statements[0]);
return this.buildSingleStatementRule(statements[0], evidence);
}
// Handle multiple statements with logical operators
return this.buildLogicalRule(statements);
return this.buildLogicalRule(statements, evidence);
}
/**
* Build rule configuration for a single statement
* @param {BaseNode} statement - Statement to build rule for
* @param {Object} evidence - Evidence definition (params inform pattern/operand lowering)
* @returns {Object|null} Rule configuration or null
*/
buildSingleStatementRule(statement) {
buildSingleStatementRule(statement, evidence) {
switch (statement.type) {
case 'DirectEvidence':
return this.buildDirectRule(statement);
case 'PatternMatch':
return this.buildPatternMatchRule(statement);
return this.buildPatternMatchRule(statement, evidence);
case 'DefeasibleLogic':
return this.buildDefeasibleRule(statement);
return this.buildDefeasibleRule(statement, evidence);
case 'Fusion':
return this.buildFusionRule(statement);
case 'PredicateCall':
@@ -286,13 +287,13 @@ export class RuleGenerator {
return this.buildUnaryRule(statement);
case 'BinaryExpression':
// Top-level comparator — emit a relational_comparator rule. RF-24 closure.
return this.buildRuleFromExpressionNode(statement);
return this.buildRuleFromExpressionNode(statement, evidence);
case 'Expression':
// Handle expressions that might be predicate calls
if (statement.type === 'PredicateCall') {
return this.buildPredicateRule(statement);
}
return this.buildRuleFromExpressionNode(statement);
return this.buildRuleFromExpressionNode(statement, evidence);
default:
this.errors.push(`Unsupported statement type: ${statement.type}`);
return null;
@@ -331,11 +332,24 @@ export class RuleGenerator {
* @param {BaseNode[]} statements - Statements to combine
* @returns {Object|null} Rule configuration or null
*/
buildLogicalRule(statements) {
buildLogicalRule(statements, evidence) {
const defeasible = statements.filter(s => s && s.type === 'DefeasibleLogic');
const others = statements.filter(s => s && s.type !== 'DefeasibleLogic');
// Defeasible levels (NEVER / REQUIRES / ALWAYS / WHEN / UNLESS) form ONE
// five-level hierarchy (ADR-000), not separate ANDed rules. A standalone
// NEVER-only rule contributes 0 whether or not it fires, so ANDing the
// levels separately would always yield 0. Merge all defeasible statements
// into a single config; any non-defeasible statements become the base
// grant (when) that the defeaters and requirements gate.
if (defeasible.length > 0) {
return this.buildMergedDefeasibleRule(defeasible, others, evidence);
}
const rules = [];
statements.forEach(statement => {
const rule = this.buildSingleStatementRule(statement);
others.forEach(statement => {
const rule = this.buildSingleStatementRule(statement, evidence);
if (rule) {
rules.push(rule);
}
@@ -361,6 +375,85 @@ export class RuleGenerator {
};
}
/**
* Merge defeasible-level statements into a single five-level rule config.
* The ADR-000 hierarchy is never > requires > strict (always) > when > unless;
* each level accumulates its conditions and the whole thing evaluates as one
* defeasible rule rather than a conjunction of level-only rules.
*/
buildMergedDefeasibleRule(defeasibleStatements, otherStatements, evidence) {
const neverRules = [];
const alwaysRules = [];
const requiresRules = [];
const whenRules = [];
const unlessRules = [];
for (const st of defeasibleStatements) {
const condition = this.buildRuleFromExpression(st.condition, evidence);
const defeater = st.defeater ? this.buildRuleFromExpression(st.defeater, evidence) : null;
switch (st.logicType) {
case 'NEVER':
if (condition) neverRules.push(condition);
break;
case 'ALWAYS':
if (condition) alwaysRules.push(condition);
break;
case 'REQUIRES':
if (condition) requiresRules.push(condition);
break;
case 'WHEN':
if (condition) whenRules.push(condition);
if (defeater) unlessRules.push(defeater);
break;
case 'UNLESS':
if (condition) unlessRules.push(condition);
break;
default:
this.errors.push(`Unsupported defeasible logic type: ${st.logicType}`);
}
}
// Non-defeasible statements in the same body act as the base grant
// (when) that NEVER/REQUIRES/UNLESS gate.
if (otherStatements.length > 0) {
const baseRules = otherStatements
.map(s => this.buildSingleStatementRule(s, evidence))
.filter(Boolean);
if (baseRules.length === 1) {
whenRules.push(baseRules[0]);
} else if (baseRules.length > 1) {
whenRules.push({
type: 'logical',
intersection: { rules: baseRules, aggregator: 'min' }
});
}
}
const rule = { type: 'logical' };
if (neverRules.length > 0) {
rule.never = { union: { rules: neverRules, aggregator: 'max' } };
}
if (requiresRules.length > 0) {
rule.requires = { union: { rules: requiresRules, aggregator: 'min' } };
}
if (alwaysRules.length > 0) {
rule.always = {
direct: alwaysRules.length === 1
? alwaysRules[0]
: { type: 'logical', intersection: { rules: alwaysRules, aggregator: 'min' } },
aggregator: 'min'
};
}
if (whenRules.length > 0) {
rule.when = { intersection: { rules: whenRules, aggregator: 'min' } };
}
if (unlessRules.length > 0) {
rule.unless = { union: { rules: unlessRules, aggregator: 'max' } };
}
return rule;
}
/**
* Build direct rule configuration
* @param {DirectEvidenceNode} directEvidence - Direct evidence statement
@@ -387,7 +480,7 @@ export class RuleGenerator {
* @param {PatternMatchNode} patternMatch - Pattern match statement
* @returns {Object|null} Rule configuration or null
*/
buildPatternMatchRule(patternMatch) {
buildPatternMatchRule(patternMatch, evidence) {
if (!patternMatch.predicate) {
this.errors.push('Pattern match must have a predicate');
return null;
@@ -396,27 +489,119 @@ export class RuleGenerator {
const predicate = patternMatch.predicate;
const relation = predicate.name;
// Membership/hierarchy predicates map to TupleToUsersetRule / ParentRule
// regardless of body shape — those have priority over chain detection.
// Structural classification (ADR-000 §Mapping to Engine Rule Types): the
// two-hop pattern "P(args) { Q(args) }" binds an intermediate via a Wildcard.
// The predicate whose args include the OBJECT parameter is the object-side
// hop. Object-side = outer → tuple_to_userset (user → computed → intermediate
// → tupleset → object). Object-side = inner → chain (user → outer →
// intermediate → inner → object). This mirrors Zanzibar's tuple-to-userset
// vs. two-hop path semantics and fixes the previous heuristic that routed
// every outer-wildcard pattern to chain (owner(*g, doc) { member_of(user, g) }
// was emitted as a chain and could never match).
const inner = this._singleInnerPredicate(patternMatch);
const evidenceParams = (evidence && evidence.params) || [];
const userVar = evidenceParams[0] && evidenceParams[0].name;
const objectVar = evidenceParams[1] && evidenceParams[1].name;
// Nested PatternMatch bodies ("P(user, *a) { Q(a, *b) { R(b, doc) } }") are
// fixed-length multi-hop PATHS — a chain whose steps are the flattened
// predicate sequence [P, Q, R], not transitive-closure multi_hop over one
// relation. Chain handles N steps; multi_hop only walks a single relation.
if (this._isNestedPattern(patternMatch)) {
return this.buildNestedChainRule(patternMatch, inner);
}
if (inner) {
const argName = a => a && (a.name !== undefined ? a.name : a.value);
const outerHasObject = objectVar !== undefined &&
(predicate.args || []).some(a => argName(a) === objectVar);
const innerHasObject = objectVar !== undefined &&
(inner.args || []).some(a => argName(a) === objectVar);
if (outerHasObject && !innerHasObject) {
return this.buildTupleToUsersetRule(patternMatch, inner);
}
if (innerHasObject && !outerHasObject) {
return this.buildChainRule(patternMatch, inner);
}
}
// Fallback: membership/hierarchy naming hints (evidence params unavailable
// or both predicates reference the object — keep legacy behavior).
if (this.isMembershipPredicate(predicate)) {
return this.buildTupleToUsersetRule(patternMatch);
return this.buildTupleToUsersetRule(patternMatch, inner);
}
if (this.isHierarchyPredicate(predicate)) {
return this.buildParentRule(patternMatch);
}
// Chain detection: ADR-000 ChainRule shape is "works_in(p, *d) { has_access(d, r) }".
// The outer PatternMatch has a Wildcard binding, and its body contains a single
// PredicateCall (no DefeasibleLogic wrapping, no nested PatternMatch). Treat that
// as a chain: two-hop traversal through the wildcard intermediate. RF-24 closure
// (parallel to RF-22/RF-23 — DSL→engine mapping gap surfaced by rigor coverage).
if (this._isChainPattern(patternMatch)) {
return this.buildChainRule(patternMatch);
return this.buildChainRule(patternMatch, inner);
}
return this.buildMultiHopRule(patternMatch);
}
/**
* Extract the single inner PredicateCall of a PatternMatch body (null if the
* body has multiple statements, is nested, or is wrapped in logic operators).
*/
_singleInnerPredicate(patternMatch) {
if (!patternMatch.body || !Array.isArray(patternMatch.body.statements)) return null;
const stmts = patternMatch.body.statements;
if (stmts.length !== 1) return null;
if (stmts[0].type === 'PredicateCall') return stmts[0];
return null;
}
/**
* True when the PatternMatch body is itself a nested PatternMatch
* ("P(user, *a) { Q(a, *b) { R(b, doc) } }") — a multi-hop path.
*/
_isNestedPattern(patternMatch) {
if (!patternMatch.body || !Array.isArray(patternMatch.body.statements)) return false;
const stmts = patternMatch.body.statements;
return stmts.length === 1 && stmts[0].type === 'PatternMatch';
}
/**
* Flatten a nested PatternMatch into its linear predicate sequence
* [P, Q, ..., R] where R is the object-side hop.
*/
_flattenPatternSteps(patternMatch, acc = []) {
const predicate = patternMatch.predicate;
if (!predicate || !predicate.name) return acc;
acc.push(predicate.name);
if (patternMatch.body && Array.isArray(patternMatch.body.statements) &&
patternMatch.body.statements.length === 1) {
const child = patternMatch.body.statements[0];
if (child && child.type === 'PredicateCall' && child.name) {
acc.push(child.name);
} else if (child && child.type === 'PatternMatch') {
this._flattenPatternSteps(child, acc);
}
}
return acc;
}
/**
* Build a chain rule from a nested (multi-hop path) PatternMatch.
* "P(user, *a) { Q(a, *b) { R(b, doc) } }" → { type: 'chain', steps: [P, Q, R] }.
*/
buildNestedChainRule(patternMatch) {
const steps = this._flattenPatternSteps(patternMatch);
if (steps.length < 2) {
this.errors.push('Nested pattern match must yield at least two steps');
return null;
}
return {
type: 'chain',
steps,
aggregator: 'max',
collectValues: true
};
}
/**
* Detect the ChainRule shape: a PatternMatch whose body contains exactly one
* PredicateCall and uses a Wildcard arg to bind the intermediate. The predicate
@@ -435,17 +620,19 @@ export class RuleGenerator {
/**
* Build chain rule configuration (ADR-000 ChainRule).
* Compiles "works_in(p, *d) { has_access(d, doc) }" into
* Compiles "works_in(user, *d) { has_access(d, doc) }" into
* { type: 'chain', steps: ['works_in', 'has_access'] }
* The intermediate wildcard binds the two predicates' arguments.
* The intermediate wildcard binds the two predicates' arguments. Step order is
* [userSide, objectSide]: the outer predicate connects user → intermediate,
* the inner predicate connects intermediate → object.
*/
buildChainRule(patternMatch) {
buildChainRule(patternMatch, inner) {
const steps = [];
steps.push(patternMatch.predicate.name);
const inner = patternMatch.body.statements[0];
if (inner && inner.type === 'PredicateCall' && inner.name) {
steps.push(inner.name);
const innerPredicate = inner || (patternMatch.body.statements[0]);
if (innerPredicate && innerPredicate.type === 'PredicateCall' && innerPredicate.name) {
steps.push(innerPredicate.name);
}
return {
@@ -457,18 +644,31 @@ export class RuleGenerator {
}
/**
* Build tuple-to-userset rule configuration
* @param {PatternMatchNode} patternMatch - Pattern match statement
* @returns {Object|null} Rule configuration or null
* Build tuple-to-userset rule configuration (ADR-000 TupleToUsersetRule).
* Compiles "owner(*g, doc) { member_of(user, g) }" into
* {
* type: 'tuple_to_userset',
* tuplesetRelation: 'owner', // object-side hop: intermediate → object
* computedRelation: 'member_of', // user-side hop: user → intermediate
* tuplesetDirection: 'in', // intermediates hold the tupleset edge TO the object
* reverse: false
* }
* The tupleset edge direction follows the wildcard position in the outer
* predicate: wildcard as first arg (owner(*g, doc)) means the intermediate is
* the edge source ('in' — fetch edges with dst = object); wildcard as second
* arg (owner(doc, *g)) means the object is the source ('out').
*/
buildTupleToUsersetRule(patternMatch) {
buildTupleToUsersetRule(patternMatch, inner) {
const predicate = patternMatch.predicate;
const relation = predicate.name;
const computedRelation = inner && inner.name ? inner.name : relation;
const wildcardIndex = (predicate.args || []).findIndex(a => a && a.type === 'Wildcard');
return {
type: 'tuple_to_userset',
tuplesetRelation: 'owner', // Default, could be inferred from context
computedRelation: relation,
tuplesetRelation: relation,
computedRelation,
tuplesetDirection: wildcardIndex === 0 ? 'in' : 'out',
reverse: false,
earlyExitThreshold: 0.95,
maxIntermediates: patternMatch.limit || 10
@@ -518,19 +718,19 @@ export class RuleGenerator {
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
* @returns {Object|null} Rule configuration or null
*/
buildDefeasibleRule(defeasibleLogic) {
buildDefeasibleRule(defeasibleLogic, evidence) {
const logicType = defeasibleLogic.logicType;
if (logicType === 'NEVER') {
return this.buildNeverRule(defeasibleLogic);
return this.buildNeverRule(defeasibleLogic, evidence);
} else if (logicType === 'ALWAYS') {
return this.buildStrictRule(defeasibleLogic);
return this.buildStrictRule(defeasibleLogic, evidence);
} else if (logicType === 'WHEN') {
return this.buildDefeasibleRuleWithDefeater(defeasibleLogic);
return this.buildDefeasibleRuleWithDefeater(defeasibleLogic, evidence);
} else if (logicType === 'UNLESS') {
return this.buildDefeaterRule(defeasibleLogic);
return this.buildDefeaterRule(defeasibleLogic, evidence);
} else if (logicType === 'REQUIRES') {
return this.buildRequirementRule(defeasibleLogic);
return this.buildRequirementRule(defeasibleLogic, evidence);
}
this.errors.push(`Unsupported defeasible logic type: ${logicType}`);
@@ -542,8 +742,8 @@ export class RuleGenerator {
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
* @returns {Object|null} Rule configuration or null
*/
buildNeverRule(defeasibleLogic) {
const condition = this.buildRuleFromExpression(defeasibleLogic.condition);
buildNeverRule(defeasibleLogic, evidence) {
const condition = this.buildRuleFromExpression(defeasibleLogic.condition, evidence);
return {
type: 'logical',
@@ -561,8 +761,8 @@ export class RuleGenerator {
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
* @returns {Object|null} Rule configuration or null
*/
buildStrictRule(defeasibleLogic) {
const condition = this.buildRuleFromExpression(defeasibleLogic.condition);
buildStrictRule(defeasibleLogic, evidence) {
const condition = this.buildRuleFromExpression(defeasibleLogic.condition, evidence);
return {
type: 'logical',
@@ -578,9 +778,9 @@ export class RuleGenerator {
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
* @returns {Object|null} Rule configuration or null
*/
buildDefeasibleRuleWithDefeater(defeasibleLogic) {
const condition = this.buildRuleFromExpression(defeasibleLogic.condition);
const defeater = this.buildRuleFromExpression(defeasibleLogic.defeater);
buildDefeasibleRuleWithDefeater(defeasibleLogic, evidence) {
const condition = this.buildRuleFromExpression(defeasibleLogic.condition, evidence);
const defeater = this.buildRuleFromExpression(defeasibleLogic.defeater, evidence);
const rule = {
type: 'logical',
@@ -609,8 +809,8 @@ export class RuleGenerator {
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
* @returns {Object|null} Rule configuration or null
*/
buildDefeaterRule(defeasibleLogic) {
const condition = this.buildRuleFromExpression(defeasibleLogic.condition);
buildDefeaterRule(defeasibleLogic, evidence) {
const condition = this.buildRuleFromExpression(defeasibleLogic.condition, evidence);
return {
type: 'logical',
@@ -628,8 +828,8 @@ export class RuleGenerator {
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
* @returns {Object|null} Rule configuration or null
*/
buildRequirementRule(defeasibleLogic) {
const condition = this.buildRuleFromExpression(defeasibleLogic.condition);
buildRequirementRule(defeasibleLogic, evidence) {
const condition = this.buildRuleFromExpression(defeasibleLogic.condition, evidence);
return {
type: 'logical',
@@ -698,19 +898,21 @@ export class RuleGenerator {
* @param {BaseNode} expression - Expression to build rule from
* @returns {Object|null} Rule configuration or null
*/
buildRuleFromExpression(expression) {
buildRuleFromExpression(expression, evidence) {
if (!expression) {
return null;
}
if (expression.type === 'Predicate') {
return this.buildDirectRuleFromPredicate(expression);
return this.buildDirectRuleFromPredicate(expression, evidence);
} else if (expression.type === 'Expression') {
return this.buildRuleFromExpressionNode(expression);
return this.buildRuleFromExpressionNode(expression, evidence);
} else if (expression.type === 'PredicateCall') {
return this.buildPredicateRule(expression);
return this.buildPredicateRule(expression, evidence);
} else if (expression.type === 'UnaryExpression') {
return this.buildUnaryRule(expression);
} else if (expression.type === 'BinaryExpression') {
return this.buildRuleFromExpressionNode(expression, evidence);
}
this.errors.push(`Unsupported expression type: ${expression.type}`);
@@ -722,15 +924,24 @@ export class RuleGenerator {
* @param {PredicateNode} predicate - Predicate to build rule from
* @returns {Object|null} Rule configuration or null
*/
buildDirectRuleFromPredicate(predicate) {
buildDirectRuleFromPredicate(predicate, evidence) {
const expanded = this._expandPredicate(predicate.name);
if (expanded) return expanded;
return {
const rule = {
type: 'direct',
relation: predicate.name,
reverse: false
};
const evidenceParams = (evidence && evidence.params) || [];
const objectVar = evidenceParams[1] && evidenceParams[1].name;
if (objectVar !== undefined && !(predicate.args || []).some(a =>
a && a.type === 'Variable' && a.name === objectVar)) {
rule._subjectAsObject = true;
}
return rule;
}
_expandPredicate(predicateName) {
@@ -770,7 +981,7 @@ export class RuleGenerator {
* @param {ExpressionNode} expression - Expression to build rule from
* @returns {Object|null} Rule configuration or null
*/
buildRuleFromExpressionNode(expression) {
buildRuleFromExpressionNode(expression, evidence) {
if (expression.type === 'AttributeAccess') {
return this.buildAttributeRule(expression);
} else if (expression.type === 'PredicateCall') {
@@ -782,7 +993,7 @@ export class RuleGenerator {
// Route BinaryExpression with comparator operators here so the
// evaluator can run a fuzzy interval comparison instead of treating
// them as logical truth values. RF-24 closure.
return this.buildRelationalComparatorRule(expression);
return this.buildRelationalComparatorRule(expression, evidence);
}
this.errors.push(`Unsupported expression type: ${expression.type}`);
@@ -812,10 +1023,10 @@ export class RuleGenerator {
* minRulePossibility: 0
* }
*/
buildRelationalComparatorRule(binaryExpression) {
buildRelationalComparatorRule(binaryExpression, evidence) {
const comparator = binaryExpression.operator;
const left = this._buildComparatorOperand(binaryExpression.left);
const right = this._buildComparatorOperand(binaryExpression.right);
const left = this._buildComparatorOperand(binaryExpression.left, evidence);
const right = this._buildComparatorOperand(binaryExpression.right, evidence);
if (!left || !right) {
this.errors.push(`Comparator operands must resolve to predicate calls (operator=${comparator})`);
return null;
@@ -833,29 +1044,52 @@ export class RuleGenerator {
}
/**
* Wrap a BinaryExpression side into a relational_comparator operand. The
* operand's `rule` field is the original predicate call (preserving reference
* semantics so the inner rule's evaluator can resolve its values). `extractValue`
* tells the evaluator to read the relation's `value` field rather than its
* `possibility`, which is what `personAge(p)` / `docMinAge(d)` semantics require.
* Lower a comparator operand to a core-evaluable config. The operand's `rule`
* MUST be a real rule configuration (the engine's RuleEvaluator only accepts
* configs — raw AST nodes evaluate to 0). Per the core's operand contract:
*
* userRisk(user) → { rule: { type: 'direct', relation: 'userRisk' }, extractValue: true } (user perspective, auto)
* riskLimit(doc) → { rule: { type: 'direct', relation: 'riskLimit' }, extractValue: true, evaluateFrom: 'object' }
*
* The evaluateFrom side is derived from the evidence parameter positions:
* params[0] is the subject (user), params[1] is the object. A predicate call
* whose first arg is the object variable reads its value from the object
* perspective; anything else defaults to the user perspective.
*
* Literal value args (userRisk(user, 5)) annotate the operand with
* `expectedValue` — the declared value the caller expects the relation to
* carry. The engine compares resolved relation values; the DSLRuntime wrapper
* may enforce expectedValue as an additional gate.
*/
_buildComparatorOperand(side) {
_buildComparatorOperand(side, evidence) {
if (!side) return null;
if (side.type === 'PredicateCall') {
return {
rule: side,
extractValue: true,
evaluatorFrom: 'auto'
};
}
if (side.type === 'AttributeAccess') {
// user.age — treat the attribute path as a "measure" reference
return {
rule: side,
const operand = {
rule: { type: 'direct', relation: side.name, reverse: false },
extractValue: true,
evaluatorFrom: 'auto',
attributePath: side.getAttributePath ? side.getAttributePath() : null
valueRelation: side.name
};
const evidenceParams = (evidence && evidence.params) || [];
const userVar = evidenceParams[0] && evidenceParams[0].name;
const objectVar = evidenceParams[1] && evidenceParams[1].name;
const firstArg = (side.args || [])[0];
const firstArgName = firstArg && (firstArg.name !== undefined ? firstArg.name : firstArg.value);
if (objectVar !== undefined && firstArgName === objectVar) {
operand.evaluateFrom = 'object';
}
const literalArg = (side.args || []).find(a => a && a.type === 'Literal');
if (literalArg) {
operand.expectedValue = literalArg.value;
}
return operand;
}
if (side.type === 'AttributeAccess') {
// Attribute paths cannot lower to a relation config — the engine's
// operand machinery reads relation `value` fields, not node attributes.
// Reject loudly instead of emitting an unevaluable rule.
this.errors.push('Comparator operands cannot be attribute accesses (use a value-carrying relation instead)');
return null;
}
return null;
}
@@ -880,7 +1114,7 @@ export class RuleGenerator {
* @param {ExpressionNode} expression - Function expression
* @returns {Object|null} Rule configuration or null
*/
buildPredicateRule(expression) {
buildPredicateRule(expression, evidence) {
const predicateName = expression.name;
if (expression.challenge) {
return this.buildChallengeRule(expression, null);
@@ -891,11 +1125,27 @@ export class RuleGenerator {
const expanded = this._expandPredicate(predicateName);
if (expanded) return expanded;
return {
const rule = {
type: 'direct',
relation: predicateName,
reverse: false
};
// Subject-scoped (unary) predicate call: the call's variable args omit the
// evidence's object parameter (banned(user) inside can_open(user, doc)).
// Mark _subjectAsObject so the engine checks the relation on the subject
// itself — the unary fact's self-edge — instead of (subject, object).
const evidenceParams = (evidence && evidence.params) || [];
const objectVar = evidenceParams[1] && evidenceParams[1].name;
if (objectVar !== undefined) {
const hasObjectArg = (expression.args || []).some(a =>
a && a.type === 'Variable' && a.name === objectVar);
if (!hasObjectArg) {
rule._subjectAsObject = true;
}
}
return rule;
}
buildWithinRule(expression) {
+3
View File
@@ -15,6 +15,9 @@ export { RuleGenerator } from './generator/RuleGenerator.js';
// Validation
export { validateDslText } from './validation/DSLValidation.js';
// Runtime
export { DSLRuntime } from './runtime/DSLRuntime.js';
// All AST nodes
export * from './nodes/index.js';
+403
View File
@@ -0,0 +1,403 @@
import { DSLCompiler } from '../DSLCompiler.js';
const PRIMITIVE_TYPES = new Set(['string', 'number', 'boolean']);
/**
* DSLRuntime — higher-order wrapper combining the Evidence DSL with an
* @arbiter/core Arbiter.
*
* The DSL declares a typed schema: `definition` blocks (entity types with
* typed fields), `fact` declarations (relations with typed params, optional
* `*` injectable marker), and `evidence` rules (relations the runtime can
* check). A raw Arbiter accepts untyped inserts; this wrapper adds the
* DSL-informed layer:
*
* - addNode / updateNodeData / addRelation / updateRelation validate their
* arguments against the compiled schema — known types, known relations,
* matching param types, typed field values — before mutating the arbiter.
* - check() validates the request, derives the injectable facts the
* evidence requires (its partial-graph requirements), retrieves the
* missing facts through caller-provided data callbacks, injects them into
* a partial graph, then delegates to the arbiter.
*
* Trust boundary follows the core: caller-supplied evidence (partial graph /
* provider results) is trusted, never policed; only structure is validated.
*/
export class DSLRuntime {
/**
* @param {object} arbiter - An @arbiter/core Arbiter instance.
* @param {object} options
* @param {object} options.factProviders - relation → async fn(subject, object, ctx)
* returning a boolean, possibility number, { possibility, value }, or an
* array of { src, relation, dst, possibility, value } partial-graph edges.
* @param {object} options.policy
* @param {boolean} options.policy.strictTypes - throw on unknown types/relations
* (default true; false degrades to arbiter behavior for undeclared names).
*/
constructor(arbiter, options = {}) {
this.arbiter = arbiter;
this.compiler = new DSLCompiler(this.arbiter);
this.factProviders = options.factProviders || {};
this.strictTypes = options.policy?.strictTypes !== false;
this.program = null;
this.types = new Map(); // typeName -> { fields: Map(field -> {type,isArray}) }
this.relations = new Map(); // relation -> { kind: 'fact'|'evidence', params, injectable }
this.dependsOn = new Map(); // evidence relation -> Set(fact relations)
}
/**
* Compile a DSL program and index its schema. Returns this for chaining.
* @param {string} dsl
* @param {string} name
*/
compile(dsl, name) {
const result = this.compiler.compile(dsl, name);
if (!result.success) {
const error = new Error(`DSLRuntime compile failed: ${(result.errors || []).join('; ')}`);
error.errors = result.errors || [];
throw error;
}
this.program = result.program;
this._indexSchema();
return this;
}
_indexSchema() {
this.types.clear();
this.relations.clear();
this.dependsOn.clear();
for (const def of this.program.definitions || []) {
const fields = new Map();
for (const field of def.fields || []) {
fields.set(field.name, { type: field.fieldType, isArray: !!field.isArray });
}
this.types.set(def.name, { fields });
}
for (const fact of this.program.facts || []) {
this.relations.set(fact.name, {
kind: 'fact',
params: (fact.params || []).map(p => ({ name: p.name, type: p.paramType, isArray: !!p.isArray })),
injectable: !!fact.injectable
});
}
for (const ev of this.program.evidence || []) {
this.relations.set(ev.name, {
kind: 'evidence',
params: (ev.params || []).map(p => ({ name: p.name, type: p.paramType, isArray: !!p.isArray })),
injectable: false
});
}
// Index each evidence's fact dependencies from the compiled arbiter configs.
for (const ev of this.program.evidence || []) {
const config = this.arbiter.relationConfigs.get(ev.name);
const deps = new Set();
const collect = (rule) => {
if (!rule || typeof rule !== 'object') return;
if (rule.type === 'direct' && rule.relation) deps.add(rule.relation);
if (rule.type === 'tuple_to_userset') {
if (rule.tuplesetRelation) deps.add(rule.tuplesetRelation);
if (rule.computedRelation) deps.add(rule.computedRelation);
}
if (rule.type === 'chain' && Array.isArray(rule.steps)) {
for (const s of rule.steps) deps.add(typeof s === 'string' ? s : s.relation);
}
if (rule.type === 'parent' && rule.parentRelation) deps.add(rule.parentRelation);
if (rule.type === 'multi_hop' && rule.relation) deps.add(rule.relation);
if (rule.type === 'relational_comparator') {
collect(rule.left?.rule);
collect(rule.right?.rule);
if (rule.left?.valueRelation) deps.add(rule.left.valueRelation);
if (rule.right?.valueRelation) deps.add(rule.right.valueRelation);
}
for (const key of ['union', 'intersection', 'exclusion', 'never', 'always', 'requires', 'when', 'unless']) {
const node = rule[key];
if (!node) continue;
if (Array.isArray(node.rules)) for (const c of node.rules) collect(c);
if (Array.isArray(node.union?.rules)) for (const c of node.union.rules) collect(c);
if (Array.isArray(node.intersection?.rules)) for (const c of node.intersection.rules) collect(c);
if (node.direct) collect(node.direct);
if (node.rule) collect(node.rule);
}
};
if (config && Array.isArray(config.dependsOn)) {
for (const d of config.dependsOn) deps.add(d);
} else {
collect(config);
}
this.dependsOn.set(ev.name, deps);
}
}
// ---------------------------------------------------------------------------
// Schema validation helpers
// ---------------------------------------------------------------------------
_isPrimitive(typeName) {
return PRIMITIVE_TYPES.has(typeName);
}
_nodeType(key) {
const nodeId = this.arbiter.resolveNodeId(key);
if (nodeId === undefined) return null;
const node = this.arbiter.nodes.get(nodeId);
return node ? node.type : null;
}
_checkNodeExists(key, position) {
if (!this.arbiter.nodeIdByKey.has(key)) {
throw new Error(`DSLRuntime: ${position} node '${key}' does not exist`);
}
}
_checkNodeType(key, expectedType, position) {
if (this._isPrimitive(expectedType)) return; // value positions are validated separately
const actual = this._nodeType(key);
if (actual === null) {
this._checkNodeExists(key, position);
return;
}
if (actual !== expectedType) {
throw new Error(`DSLRuntime: ${position} node '${key}' has type '${actual}', expected '${expectedType}'`);
}
}
_checkFieldValue(field, value, path) {
if (field.isArray) {
if (!Array.isArray(value)) {
throw new Error(`DSLRuntime: field '${path}' must be an array of ${field.type}`);
}
for (const item of value) this._checkScalarValue(field.type, item, path);
return;
}
this._checkScalarValue(field.type, value, path);
}
_checkScalarValue(type, value, path) {
const ok = type === 'string' ? typeof value === 'string'
: type === 'number' ? typeof value === 'number'
: type === 'boolean' ? typeof value === 'boolean'
: true; // entity-typed fields accept any key
if (!ok) {
throw new Error(`DSLRuntime: field '${path}' must be ${type}, got ${typeof value}`);
}
}
// ---------------------------------------------------------------------------
// Typed mutations
// ---------------------------------------------------------------------------
/**
* Insert a node, validating the type exists (when declared) and that `data`
* conforms to the definition's typed fields.
*/
addNode(key, typeName, data = {}) {
if (this.types.has(typeName)) {
const { fields } = this.types.get(typeName);
for (const [name, field] of fields) {
if (data[name] !== undefined) this._checkFieldValue(field, data[name], `${typeName}.${name}`);
}
} else if (this.strictTypes) {
throw new Error(`DSLRuntime: unknown type '${typeName}'`);
}
return this.arbiter.addNode(key, typeName, data);
}
/**
* Update node data, validating fields against the node's declared type.
*/
updateNodeData(key, data) {
const typeName = this._nodeType(key);
if (typeName && this.types.has(typeName)) {
const { fields } = this.types.get(typeName);
for (const [name, field] of fields) {
if (data[name] !== undefined) this._checkFieldValue(field, data[name], `${typeName}.${name}`);
}
}
return this.arbiter.updateNodeData(key, data);
}
_relationOrThrow(relation) {
const meta = this.relations.get(relation);
if (!meta) {
if (this.strictTypes) throw new Error(`DSLRuntime: unknown relation '${relation}'`);
return null;
}
return meta;
}
/**
* Insert a relation edge. Validates the relation is declared, that the
* subject/object nodes match the declared entity param types, and that any
* primitive value param is supplied in attrs.value of the correct type.
*/
addRelation(src, relation, dst, attrs = {}) {
const meta = this._relationOrThrow(relation);
if (meta) {
this._validateRelationEndpoints(relation, meta, src, dst, attrs);
}
return this.arbiter.addRelation(src, relation, dst, attrs);
}
/**
* Update a relation edge (idempotent replace). Validates like addRelation.
*/
updateRelation(src, relation, dst, attrs = {}) {
const meta = this._relationOrThrow(relation);
if (meta) {
this._validateRelationEndpoints(relation, meta, src, dst, attrs);
}
this.arbiter.removeRelation(src, relation, dst);
return this.arbiter.addRelation(src, relation, dst, attrs);
}
_validateRelationEndpoints(relation, meta, src, dst, attrs) {
const params = meta.params;
if (params.length === 0) {
throw new Error(`DSLRuntime: relation '${relation}' declares no parameters`);
}
// First param is always the subject (entity).
const subjectType = params[0].type;
if (this._isPrimitive(subjectType)) {
throw new Error(`DSLRuntime: relation '${relation}' subject param must be an entity type, got '${subjectType}'`);
}
this._checkNodeType(src, subjectType, 'subject');
if (params.length >= 2) {
const secondType = params[1].type;
if (this._isPrimitive(secondType)) {
// Value-carrying fact (e.g. session(user, token: string)): the value
// lives on the edge's `value` field; the graph edge is a self-edge on
// the subject so the value is discoverable by value extraction.
if (attrs.value === undefined) {
attrs.value = dst;
}
this._checkScalarValue(secondType, attrs.value, `${relation}.${params[1].name}`);
if (dst !== src) {
throw new Error(`DSLRuntime: value param '${params[1].name}' must be supplied as attrs.value with dst = src (self-edge), got dst '${dst}'`);
}
} else {
this._checkNodeType(dst, secondType, 'object');
}
}
}
/**
* The partial-graph requirements of an evidence relation: the declared
* injectable facts it depends on.
*/
requiredFacts(relation) {
const deps = this.dependsOn.get(relation);
if (!deps) return [];
const required = [];
for (const dep of deps) {
const meta = this.relations.get(dep);
if (meta && meta.kind === 'fact' && meta.injectable) required.push(dep);
}
return required;
}
// ---------------------------------------------------------------------------
// DSL-informed check
// ---------------------------------------------------------------------------
/**
* Validate a check request against the DSL schema, derive and retrieve the
* evidence's injectable facts, inject them into a partial graph, and delegate
* to the arbiter.
*
* @param {string} user - subject key
* @param {string} relation - evidence (or fact) relation name
* @param {string} object - object key
* @param {object} options
* @param {object} options.partialGraph - caller-supplied partial graph edges
* ({ relations: [{ src, relation, dst, possibility, value }], nodes, challenges })
* @param {object} options.factProviders - per-call provider overrides
* @returns {object} core check result extended with { requiredFacts, providedFacts, missingFacts }
*/
async check(user, relation, object, options = {}) {
const meta = this.relations.get(relation);
if (!meta) {
if (this.strictTypes) throw new Error(`DSLRuntime: unknown relation '${relation}'`);
} else if (meta.kind === 'evidence') {
if (meta.params.length === 2) {
this._checkNodeType(user, meta.params[0].type, 'subject');
this._checkNodeType(object, meta.params[1].type, 'object');
}
}
const required = this.requiredFacts(relation);
const providers = options.factProviders || this.factProviders;
const injectedRelations = [];
const missingFacts = [];
const partialRelations = [];
if (options.partialGraph && Array.isArray(options.partialGraph.relations)) {
partialRelations.push(...options.partialGraph.relations);
}
for (const fact of required) {
const factMeta = this.relations.get(fact);
const provider = providers[fact];
let result = null;
let error = null;
if (typeof provider === 'function') {
try {
result = await provider(user, object, { relation: fact, params: factMeta.params, runtime: this, options });
} catch (err) {
error = err;
}
}
if (error) {
missingFacts.push({ relation: fact, reason: error.message });
continue;
}
if (result === false || result === null || result === undefined) {
missingFacts.push({ relation: fact, reason: 'not_provided' });
continue;
}
const edges = Array.isArray(result) ? result : [result];
// Resolve the edge destination the same way the DSL declares the fact:
// - unary fact (1 param) -> self-edge on the subject
// - value fact (2nd param value) -> self-edge on the subject carrying the value
// - binary entity fact -> subject → object
const secondParamType = factMeta.params[1] && factMeta.params[1].type;
const defaultDst = factMeta.params.length >= 2 && this._isPrimitive(secondParamType)
? user
: (factMeta.params.length >= 2 ? object : user);
for (const edge of edges) {
const normalized = typeof edge === 'boolean' || typeof edge === 'number'
? { src: user, dst: defaultDst, possibility: edge === true ? 1 : edge }
: {
src: edge.src ?? user,
dst: edge.dst ?? defaultDst,
possibility: edge.possibility ?? 1,
...(edge.value !== undefined ? { value: edge.value } : {}),
...(edge.reliability !== undefined ? { reliability: edge.reliability } : {})
};
partialRelations.push({ relation: fact, ...normalized });
}
injectedRelations.push({ relation: fact, edges: edges.length });
}
const checkOptions = { ...options };
if (partialRelations.length > 0) {
checkOptions.partialGraph = {
...(options.partialGraph || {}),
relations: partialRelations
};
}
const result = this.arbiter.check(user, relation, object, checkOptions);
return {
...result,
requiredFacts: required,
providedFacts: injectedRelations.map(r => r.relation),
missingFacts
};
}
}
+22
View File
@@ -144,6 +144,7 @@ function validateDefinitions(program, tables, errors, warnings, source) {
}
function validateFacts(program, tables, errors, warnings, source) {
const seen = new Map();
for (const fact of program.facts || []) {
if (tables.builtins?.facts?.has(fact.name)) {
errors.push(createError({
@@ -154,6 +155,16 @@ function validateFacts(program, tables, errors, warnings, source) {
context: formatContext(source, findLocation(source, fact.name))
}));
}
if (seen.has(fact.name)) {
errors.push(createError({
message: `Duplicate fact definition '${fact.name}'.`,
rule: 'Each fact name must be unique within a program.',
fix: 'Rename one of the fact definitions to a unique name.',
location: findLocation(source, `fact ${fact.name}`),
context: formatContext(source, findLocation(source, fact.name))
}));
}
seen.set(fact.name, fact);
const arity = fact.params ? fact.params.length : 0;
if (!fact.params || arity === 0) {
warnings.push(createError({
@@ -285,6 +296,7 @@ function validateMeasures(program, tables, errors, warnings, source) {
}
function validateEvidence(program, tables, errors, warnings, source) {
const seen = new Map();
for (const ev of program.evidence || []) {
if (tables.builtins?.evidence?.has(ev.name)) {
errors.push(createError({
@@ -295,6 +307,16 @@ function validateEvidence(program, tables, errors, warnings, source) {
context: formatContext(source, findLocation(source, ev.name))
}));
}
if (seen.has(ev.name)) {
errors.push(createError({
message: `Duplicate evidence definition '${ev.name}'.`,
rule: 'Each evidence name must be unique within a program.',
fix: 'Rename one of the evidence definitions to a unique name.',
location: findLocation(source, `evidence ${ev.name}`),
context: formatContext(source, findLocation(source, ev.name))
}));
}
seen.set(ev.name, ev);
const returnType = ev.provides || DEFAULT_EVIDENCE_RETURN;
if (returnType !== DEFAULT_EVIDENCE_RETURN && !isTypeKnown(returnType, tables)) {
errors.push(createError({