feat: fix lowering, DSLRuntime wrapper, rigor oracle + rejection campaigns
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:
+331
-81
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user