feat: sources wired as recency-gated injectables; transitive closure, NOT scoping, recompile-scope uninstall; targeted parse errors
BEHAVES AS transitive now emits bounded multi_hop configs (direct checks and evidence references), fixing a silent no-op. NOT builds keep _subjectAsObject scoping so unary predicates negate the right node, and value-typed evidence objects gate by exact edge value. Recompiling a scope uninstalls its stale relation configs (compileMultiple coexistence preserved). Sources become injectable relations honored by requiredFacts with a within-X recency gate. Duplicate definition fields and three common declaration mistakes (within on a fact, two BEHAVES clauses, limit on a non-pattern body) now produce targeted errors. Provider edges referencing unknown nodes are warned and dropped.
This commit is contained in:
@@ -11,6 +11,14 @@ export class RuleGenerator {
|
||||
this.errors = [];
|
||||
this.dependencyIndex = new Map();
|
||||
this.evidenceNames = new Set();
|
||||
// Relation names this generator has installed on the arbiter, tracked PER
|
||||
// PROGRAM SCOPE (the compile() program name). Recompiling the same scope
|
||||
// uninstalls relations that scope previously declared but no longer does —
|
||||
// otherwise a revoked evidence/fact keeps its config and still grants
|
||||
// (stale-permission leak). Relations from OTHER scopes (compileMultiple
|
||||
// coexistence) are never touched.
|
||||
this._installedByScope = new Map();
|
||||
this._currentScope = 'default';
|
||||
// Default depth for bounded self-recursion when the DSL `limit N` is absent.
|
||||
this.maxRecursionDepth = options.maxRecursionDepth ?? 3;
|
||||
}
|
||||
@@ -20,10 +28,25 @@ export class RuleGenerator {
|
||||
* @param {ProgramNode} program - AST program to generate rules from
|
||||
* @returns {Object} Generation result with success status and errors
|
||||
*/
|
||||
generateRules(program) {
|
||||
generateRules(program, scopeName = 'default') {
|
||||
this.errors = [];
|
||||
this._currentScope = scopeName;
|
||||
this.program = program;
|
||||
this.generatedRules.clear();
|
||||
this.dependencyIndex.clear();
|
||||
// Facts declared `BEHAVES AS transitive` are resolved as bounded transitive
|
||||
// closure (multi_hop) everywhere they are referenced — both the fact's own
|
||||
// config and any direct rule that references the fact. Without this the
|
||||
// declaration parses but grants only direct edges (silent no-op). Value is
|
||||
// the closure depth (the fact's `limit N`, or the recursion default).
|
||||
this.transitiveFacts = new Map();
|
||||
for (const fact of program.facts || []) {
|
||||
const behavior = fact && fact.behavior;
|
||||
if (behavior && (behavior.behavior === 'transitive' || behavior === 'transitive')) {
|
||||
const depth = (fact.limit && typeof fact.limit === 'object' ? fact.limit.value : fact.limit) ?? this.maxRecursionDepth;
|
||||
this.transitiveFacts.set(fact.name, depth);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Generate rules for each evidence definition
|
||||
@@ -41,6 +64,14 @@ export class RuleGenerator {
|
||||
this.generateFactConfig(fact);
|
||||
});
|
||||
|
||||
// Generate source relation configs (injectable, recency-gated proofs).
|
||||
// Without a config a source referenced by an evidence would never
|
||||
// resolve — the reference would lower to a config-less direct rule that
|
||||
// grants nothing.
|
||||
(program.sources || []).forEach(source => {
|
||||
this.generateSourceConfig(source);
|
||||
});
|
||||
|
||||
// Resolve evidence composition: a rule that references another derived
|
||||
// evidence (WHEN can_read(user, doc) where can_read is an evidence) is
|
||||
// lowered in place to that evidence's own config — compile-time inlining
|
||||
@@ -109,9 +140,13 @@ export class RuleGenerator {
|
||||
const paramNames = params.map(p => p.name);
|
||||
const paramTypes = params.map(p => p.type);
|
||||
|
||||
this.generatedRules.set(name, {
|
||||
type: 'direct',
|
||||
relation: name,
|
||||
// BEHAVES AS transitive: the fact resolves to bounded transitive closure.
|
||||
// A multi_hop config walks the relation's edges up to maxDepth (the fact's
|
||||
// `limit N`, or the recursion default), so a direct check on the fact —
|
||||
// and any evidence that references it — follows multi-hop paths instead of
|
||||
// only direct edges.
|
||||
const transitiveDepth = this.transitiveFacts.get(name);
|
||||
const base = {
|
||||
isFactRelation: true,
|
||||
requiresInjection: true,
|
||||
arity: paramTypes.length,
|
||||
@@ -123,6 +158,39 @@ export class RuleGenerator {
|
||||
typeof p === 'string' ? [p, true] : Array.isArray(p) ? p : [p, true]
|
||||
)
|
||||
)
|
||||
};
|
||||
|
||||
this.generatedRules.set(name, transitiveDepth !== undefined
|
||||
? {
|
||||
type: 'multi_hop',
|
||||
relation: name,
|
||||
maxDepth: transitiveDepth,
|
||||
pathAggregation: 'max',
|
||||
reverse: false,
|
||||
fallbackToBasicPaths: true,
|
||||
collectValues: false,
|
||||
...base
|
||||
}
|
||||
: {
|
||||
type: 'direct',
|
||||
relation: name,
|
||||
...base
|
||||
});
|
||||
}
|
||||
|
||||
generateSourceConfig(source) {
|
||||
const name = source.name;
|
||||
const params = source.params || [];
|
||||
const withinMs = source.within ? this._durationToMs(source.within) : null;
|
||||
this.generatedRules.set(name, {
|
||||
type: 'direct',
|
||||
relation: name,
|
||||
isSourceRelation: true,
|
||||
requiresInjection: true,
|
||||
arity: params.length,
|
||||
paramTypes: params.map(p => p.paramType),
|
||||
paramNames: params.map(p => p.name),
|
||||
...(withinMs !== null ? { withinMs } : {})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -298,7 +366,7 @@ export class RuleGenerator {
|
||||
case 'PredicateCall':
|
||||
return this.buildPredicateRule(statement, evidence);
|
||||
case 'UnaryExpression':
|
||||
return this.buildUnaryRule(statement);
|
||||
return this.buildUnaryRule(statement, evidence);
|
||||
case 'BinaryExpression':
|
||||
// Top-level comparator — emit a relational_comparator rule. RF-24 closure.
|
||||
return this.buildRuleFromExpressionNode(statement, evidence);
|
||||
@@ -317,15 +385,19 @@ export class RuleGenerator {
|
||||
/**
|
||||
* Build rule for unary expression (NOT)
|
||||
* @param {Object} expression - Unary expression
|
||||
* @param {Object} evidence - Evidence definition (threaded through so a
|
||||
* unary inner predicate like NOT banned(user) keeps its _subjectAsObject
|
||||
* rewrite; without it the unary fact would be checked on the evidence's
|
||||
* OBJECT node instead of the subject, silently negating the wrong fact).
|
||||
* @returns {Object|null} Rule configuration or null
|
||||
*/
|
||||
buildUnaryRule(expression) {
|
||||
buildUnaryRule(expression, evidence) {
|
||||
if (expression.operator !== 'NOT') {
|
||||
this.errors.push(`Unsupported unary operator: ${expression.operator}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const innerRule = this.buildRuleFromExpression(expression.operand);
|
||||
const innerRule = this.buildRuleFromExpression(expression.operand, evidence);
|
||||
if (!innerRule) {
|
||||
return null;
|
||||
}
|
||||
@@ -482,6 +554,12 @@ export class RuleGenerator {
|
||||
const predicate = directEvidence.predicate;
|
||||
const relation = predicate.name;
|
||||
|
||||
// A reference to a `BEHAVES AS transitive` fact resolves to closure.
|
||||
const transitiveDepth = this.transitiveFacts.get(relation);
|
||||
if (transitiveDepth !== undefined) {
|
||||
return this._buildTransitiveRule(relation, transitiveDepth, predicate.arguments || [], evidence);
|
||||
}
|
||||
|
||||
const rule = {
|
||||
type: 'direct',
|
||||
relation: relation,
|
||||
@@ -505,6 +583,12 @@ export class RuleGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
// A literal value in the object position (balance(user, 5)) is a VALUE
|
||||
// constraint, not a node key: the rule only grants when the matched edge
|
||||
// carries exactly that value. Without this gate a value-carrying fact
|
||||
// would match ANY edge regardless of its amount (silent over-grant).
|
||||
this._applyExpectedValue(rule, args);
|
||||
|
||||
return rule;
|
||||
}
|
||||
|
||||
@@ -947,7 +1031,7 @@ export class RuleGenerator {
|
||||
} else if (expression.type === 'PredicateCall') {
|
||||
return this.buildPredicateRule(expression, evidence);
|
||||
} else if (expression.type === 'UnaryExpression') {
|
||||
return this.buildUnaryRule(expression);
|
||||
return this.buildUnaryRule(expression, evidence);
|
||||
} else if (expression.type === 'BinaryExpression') {
|
||||
return this.buildRuleFromExpressionNode(expression, evidence);
|
||||
}
|
||||
@@ -962,6 +1046,12 @@ export class RuleGenerator {
|
||||
* @returns {Object|null} Rule configuration or null
|
||||
*/
|
||||
buildDirectRuleFromPredicate(predicate, evidence) {
|
||||
// A reference to a `BEHAVES AS transitive` fact resolves to closure.
|
||||
const transitiveDepth = this.transitiveFacts.get(predicate.name);
|
||||
if (transitiveDepth !== undefined) {
|
||||
return this._buildTransitiveRule(predicate.name, transitiveDepth, predicate.args || [], evidence);
|
||||
}
|
||||
|
||||
const rule = {
|
||||
type: 'direct',
|
||||
relation: predicate.name,
|
||||
@@ -975,6 +1065,58 @@ export class RuleGenerator {
|
||||
rule._subjectAsObject = true;
|
||||
}
|
||||
|
||||
// Value constraint: a literal in the object position (balance(user, 5)).
|
||||
this._applyExpectedValue(rule, predicate.args || []);
|
||||
|
||||
return rule;
|
||||
}
|
||||
|
||||
/**
|
||||
* Annotate a direct rule with `expectedValue` when its object-position
|
||||
* argument is a literal. The engine only grants the rule if the matched
|
||||
* edge's `value` field equals this literal — without the gate a
|
||||
* value-carrying fact would match any edge of the same relation, silently
|
||||
* over-granting (e.g. balance(user, 5) matching a value-3 edge).
|
||||
*/
|
||||
_applyExpectedValue(rule, args) {
|
||||
if (rule && args && args.length >= 2) {
|
||||
const objectArg = args[1];
|
||||
if (objectArg && objectArg.type === 'Literal' && objectArg.value !== undefined) {
|
||||
rule.expectedValue = objectArg.value;
|
||||
}
|
||||
}
|
||||
return rule;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a bounded transitive-closure rule for a `BEHAVES AS transitive`
|
||||
* fact reference. Applies the same subject/object rewrite flags as the
|
||||
* direct-rule builders so a unary or object-var reference still targets the
|
||||
* correct nodes.
|
||||
*/
|
||||
_buildTransitiveRule(relation, maxDepth, args, evidence) {
|
||||
const rule = {
|
||||
type: 'multi_hop',
|
||||
relation: relation,
|
||||
maxDepth: maxDepth,
|
||||
pathAggregation: 'max',
|
||||
reverse: false,
|
||||
fallbackToBasicPaths: true,
|
||||
collectValues: false
|
||||
};
|
||||
|
||||
const evidenceParams = (evidence && evidence.params) || [];
|
||||
const objectVar = evidenceParams[1] && evidenceParams[1].name;
|
||||
const argName = a => a && (a.name !== undefined ? a.name : a.value);
|
||||
if (objectVar !== undefined) {
|
||||
const hasObjectArg = args.some(a => a && a.type === 'Variable' && a.name === objectVar);
|
||||
if (args.length === 1 && argName(args[0]) === objectVar) {
|
||||
rule._subjectIsObject = true;
|
||||
} else if (!hasObjectArg) {
|
||||
rule._subjectAsObject = true;
|
||||
}
|
||||
}
|
||||
|
||||
return rule;
|
||||
}
|
||||
|
||||
@@ -1391,6 +1533,13 @@ export class RuleGenerator {
|
||||
return this.buildChallengeRule(expression, null);
|
||||
}
|
||||
|
||||
// A reference to a `BEHAVES AS transitive` fact resolves to bounded
|
||||
// transitive closure, not a direct edge lookup.
|
||||
const transitiveDepth = this.transitiveFacts.get(predicateName);
|
||||
if (transitiveDepth !== undefined) {
|
||||
return this._buildTransitiveRule(predicateName, transitiveDepth, expression.args || [], evidence);
|
||||
}
|
||||
|
||||
const rule = {
|
||||
type: 'direct',
|
||||
relation: predicateName,
|
||||
@@ -1418,6 +1567,11 @@ export class RuleGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
// Value constraint: a literal in the object position (balance(user, 5))
|
||||
// is a VALUE gate, not a node key — the rule only grants when the matched
|
||||
// edge carries exactly that value.
|
||||
this._applyExpectedValue(rule, expression.args || []);
|
||||
|
||||
return rule;
|
||||
}
|
||||
|
||||
@@ -1531,6 +1685,19 @@ export class RuleGenerator {
|
||||
return;
|
||||
}
|
||||
|
||||
// Recompile hygiene (per program scope): relations installed by a previous
|
||||
// compile of THIS scope but absent from the current program are stale —
|
||||
// remove their configs from every cache and index so a revoked relation
|
||||
// stops granting immediately. Relations belonging to other scopes
|
||||
// (compileMultiple coexistence) are left intact.
|
||||
const scope = this._currentScope || 'default';
|
||||
const previously = this._installedByScope.get(scope) || new Set();
|
||||
for (const name of previously) {
|
||||
if (!this.generatedRules.has(name)) {
|
||||
this._uninstallRelation(name);
|
||||
}
|
||||
}
|
||||
|
||||
this.generatedRules.forEach((config, relation) => {
|
||||
try {
|
||||
this.arbiter.setRelationConfig(relation, config);
|
||||
@@ -1542,6 +1709,33 @@ export class RuleGenerator {
|
||||
if (typeof this.arbiter.registerDependencyIndex === 'function') {
|
||||
this.arbiter.registerDependencyIndex(this.dependencyIndex);
|
||||
}
|
||||
|
||||
this._installedByScope.set(scope, new Set(this.generatedRules.keys()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a relation's config and cached state from the arbiter. Mirrors the
|
||||
* invalidation that setRelationConfig performs, applied to deletion.
|
||||
*/
|
||||
_uninstallRelation(name) {
|
||||
const arb = this.arbiter;
|
||||
if (!arb) return;
|
||||
if (arb.relationConfigs && typeof arb.relationConfigs.delete === 'function') {
|
||||
arb.relationConfigs.delete(name);
|
||||
}
|
||||
const analysis = arb.graphManager && arb.graphManager.analysis;
|
||||
if (analysis && analysis.relationConfigs && typeof analysis.relationConfigs.delete === 'function') {
|
||||
analysis.relationConfigs.delete(name);
|
||||
}
|
||||
if (typeof arb._invalidateDirectCheckCache === 'function') {
|
||||
arb._invalidateDirectCheckCache(null, name, null);
|
||||
}
|
||||
if (typeof arb.invalidateRuleResultCacheByRelation === 'function') {
|
||||
arb.invalidateRuleResultCacheByRelation(name);
|
||||
}
|
||||
if (arb.authChecker && typeof arb.authChecker.invalidateRuleCaches === 'function') {
|
||||
arb.authChecker.invalidateRuleCaches(name);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user