Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b145c979ab | |||
| 512831a8fc | |||
| 2a7f4c315b | |||
| 4d498b07e8 | |||
| 9111c4b20d | |||
| aa38fbfd8c |
Generated
+6
-6
@@ -1,15 +1,15 @@
|
||||
{
|
||||
"name": "@arbiter/evidence-dsl",
|
||||
"version": "1.6.0",
|
||||
"version": "1.12.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@arbiter/evidence-dsl",
|
||||
"version": "1.6.0",
|
||||
"version": "1.12.1",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@arbiter/core": "^1.0.4"
|
||||
"@arbiter/core": "^1.0.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rigor/core": "^3.1.0",
|
||||
@@ -17,9 +17,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@arbiter/core": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://hub.kl1.tenere.ai/api/packages/Arbiter/npm/%40arbiter%2Fcore/-/1.0.4/core-1.0.4.tgz",
|
||||
"integrity": "sha512-1zXy3mZACjwELptsV8QpYvZJmMU7BhUQ4FsKNfp3/oJDwjfMqAImcAF3mJ+HNZpQnLQXScmELTwow5VduvN27g==",
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://hub.kl1.tenere.ai/api/packages/Arbiter/npm/%40arbiter%2Fcore/-/1.0.8/core-1.0.8.tgz",
|
||||
"integrity": "sha512-x/nWymJca0AHoUaLrq09ENeiPBplaCcuQbX1zHKVUk1fYoYVfW9ZmmrApoKPsK58WkcPwBWo1cB6VSrGk9//WA==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@tenere/pltc-core": "^0.6.3",
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@arbiter/evidence-dsl",
|
||||
"version": "1.8.0",
|
||||
"version": "1.12.1",
|
||||
"description": "Evidence DSL v2 compiler: translates the natural Evidence DSL (ADR-000) into @arbiter/core relation configurations.",
|
||||
"license": "ISC",
|
||||
"type": "module",
|
||||
@@ -24,7 +24,7 @@
|
||||
"generate:parser": "node scripts/generate-parser.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@arbiter/core": "^1.0.4"
|
||||
"@arbiter/core": "^1.0.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rigor/core": "^3.1.0",
|
||||
|
||||
+6
-4
@@ -7,10 +7,10 @@ import { validateDslText } from './validation/DSLValidation.js';
|
||||
* Compiles DSL text into rule configurations for the zanzibar-graph system
|
||||
*/
|
||||
export class DSLCompiler {
|
||||
constructor(arbiter) {
|
||||
constructor(arbiter, options = {}) {
|
||||
this.arbiter = arbiter;
|
||||
this.parser = parse;
|
||||
this.generator = new RuleGenerator(arbiter);
|
||||
this.generator = new RuleGenerator(arbiter, options);
|
||||
this.compiledPrograms = new Map();
|
||||
}
|
||||
|
||||
@@ -39,13 +39,15 @@ export class DSLCompiler {
|
||||
const programNode = {
|
||||
definitions: program.body.filter(s => s.type === 'Definition'),
|
||||
facts: program.body.filter(s => s.type === 'Fact'),
|
||||
sources: program.body.filter(s => s.type === 'Source'),
|
||||
evidence: program.body.filter(s => s.type === 'Evidence'),
|
||||
measures: program.body.filter(s => s.type === 'Measure'),
|
||||
validate: () => ({ isValid: true, errors: [], warnings: [] })
|
||||
};
|
||||
|
||||
// Generate rules from AST
|
||||
const generationResult = this.generator.generateRules(programNode);
|
||||
// Generate rules from AST (scoped to the program name so recompiling a
|
||||
// scope revokes its stale relations without touching other scopes).
|
||||
const generationResult = this.generator.generateRules(programNode, programName);
|
||||
|
||||
if (!generationResult.success) {
|
||||
return {
|
||||
|
||||
+321
-12
@@ -5,12 +5,22 @@ import { ProgramNode, DefinitionNode, FactNode, EvidenceNode, MeasureNode, Direc
|
||||
* Generates rule configurations that interface with the existing rule system
|
||||
*/
|
||||
export class RuleGenerator {
|
||||
constructor(arbiter) {
|
||||
constructor(arbiter, options = {}) {
|
||||
this.arbiter = arbiter;
|
||||
this.generatedRules = new Map();
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -18,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
|
||||
@@ -39,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
|
||||
@@ -107,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,
|
||||
@@ -121,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 } : {})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -296,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);
|
||||
@@ -315,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;
|
||||
}
|
||||
@@ -480,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,
|
||||
@@ -503,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;
|
||||
}
|
||||
|
||||
@@ -629,7 +715,8 @@ export class RuleGenerator {
|
||||
type: 'chain',
|
||||
steps,
|
||||
aggregator: 'max',
|
||||
collectValues: true
|
||||
collectValues: true,
|
||||
maxDepth: patternMatch.limit || null
|
||||
};
|
||||
}
|
||||
|
||||
@@ -670,7 +757,10 @@ export class RuleGenerator {
|
||||
type: 'chain',
|
||||
steps,
|
||||
aggregator: 'max',
|
||||
collectValues: true
|
||||
collectValues: true,
|
||||
// Carry the pattern's `limit N` as a max depth so a self-referential
|
||||
// chain step can be unrolled into bounded transitive closure.
|
||||
maxDepth: patternMatch.limit || null
|
||||
};
|
||||
}
|
||||
|
||||
@@ -941,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);
|
||||
}
|
||||
@@ -956,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,
|
||||
@@ -969,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;
|
||||
}
|
||||
|
||||
@@ -990,13 +1138,113 @@ export class RuleGenerator {
|
||||
resolveEvidenceReferences() {
|
||||
for (const name of this.evidenceNames) {
|
||||
if (!this.generatedRules.has(name)) continue;
|
||||
let config = this.generatedRules.get(name);
|
||||
// Bounded self-recursion (transitive closure): an evidence whose config
|
||||
// contains a chain step referencing ITSELF is unrolled into a union of
|
||||
// bounded paths — base, hop+base, hop²+base, …, hop^N+base — where `hop`
|
||||
// is the recursive chain's steps before the self-reference and the depth
|
||||
// N comes from the pattern's `limit N` (or the compiler default).
|
||||
const selfRef = this._findSelfReference(config, name);
|
||||
if (selfRef) {
|
||||
const depth = selfRef.limit ?? this.maxRecursionDepth;
|
||||
const unrolled = this._unrollRecursiveEvidence(name, config, selfRef.hop, depth);
|
||||
if (unrolled) {
|
||||
config = unrolled;
|
||||
this.generatedRules.set(name, config);
|
||||
}
|
||||
}
|
||||
const stack = new Set([name]);
|
||||
const resolved = this._resolveRule(this.generatedRules.get(name), stack);
|
||||
const resolved = this._resolveRule(config, stack);
|
||||
this.generatedRules.set(name, resolved);
|
||||
this._annotateDependencies(name, resolved);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the first chain step within `config` that references `name` (a
|
||||
* self-reference). Returns { hop, limit } where hop is the chain's steps
|
||||
* before the self-reference and limit is the chain's declared max depth.
|
||||
* Returns null when there is no self-reference.
|
||||
*/
|
||||
_findSelfReference(config, name) {
|
||||
let found = null;
|
||||
const walk = (rule) => {
|
||||
if (!rule || typeof rule !== 'object' || found) return;
|
||||
if (rule.type === 'chain' && Array.isArray(rule.steps)) {
|
||||
const idx = rule.steps.findIndex(s => (typeof s === 'string' ? s : s && s.relation) === name);
|
||||
if (idx >= 0) {
|
||||
const lim = rule.maxDepth;
|
||||
const limit = lim && typeof lim === 'object' ? lim.value : lim;
|
||||
found = { hop: rule.steps.slice(0, idx), limit: Number.isFinite(limit) ? limit : null };
|
||||
return;
|
||||
}
|
||||
}
|
||||
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) walk(c);
|
||||
if (Array.isArray(node.union?.rules)) for (const c of node.union.rules) walk(c);
|
||||
if (Array.isArray(node.intersection?.rules)) for (const c of node.intersection.rules) walk(c);
|
||||
if (node.direct) walk(node.direct);
|
||||
if (node.rule) walk(node.rule);
|
||||
}
|
||||
};
|
||||
walk(config);
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unroll a self-recursive evidence into a bounded transitive closure.
|
||||
* The recursive chain is removed from the config; the remainder is the base.
|
||||
* Result: union([base, hop+base, hop²+base, …, hop^depth+base]) where the
|
||||
* base is verified as a condition step at each path's terminal node.
|
||||
*/
|
||||
_unrollRecursiveEvidence(name, config, hop, depth) {
|
||||
if (hop.length === 0) {
|
||||
this.errors.push(`Recursive evidence '${name}' has an empty recursion hop (no steps before the self-reference).`);
|
||||
return null;
|
||||
}
|
||||
const base = this._extractBase(config, name);
|
||||
if (!base) {
|
||||
this.errors.push(`Recursive evidence '${name}' has no base case — pure recursion cannot grant. Add a non-recursive statement.`);
|
||||
return null;
|
||||
}
|
||||
const rules = [this._deepCloneRule(base)];
|
||||
for (let d = 1; d <= depth; d++) {
|
||||
const steps = [];
|
||||
for (let h = 0; h < d; h++) steps.push(...hop.map(s => this._deepCloneRule(s)));
|
||||
steps.push({ rule: this._deepCloneRule(base), conditionStep: true });
|
||||
rules.push({ type: 'chain', steps, aggregator: 'max', collectValues: true });
|
||||
}
|
||||
return { type: 'logical', union: { rules, aggregator: 'max' } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the recursive chain (the chain containing a self-reference) from an
|
||||
* evidence config and return the remainder as the base case. Returns null if
|
||||
* there is no base (pure recursion).
|
||||
*/
|
||||
_extractBase(config, name) {
|
||||
if (config.type === 'chain') {
|
||||
const hasSelf = (config.steps || []).some(s => (typeof s === 'string' ? s : s && s.relation) === name);
|
||||
return hasSelf ? null : this._deepCloneRule(config);
|
||||
}
|
||||
if (config.type === 'logical' && config.intersection) {
|
||||
const remaining = (config.intersection.rules || []).filter(r => {
|
||||
// keep rules that are not (or do not contain) the recursive chain
|
||||
return !this._containsSelfReference(r, name);
|
||||
});
|
||||
if (remaining.length === 0) return null;
|
||||
if (remaining.length === 1) return this._deepCloneRule(remaining[0]);
|
||||
return { type: 'logical', intersection: { rules: remaining.map(r => this._deepCloneRule(r)), aggregator: config.intersection.aggregator || 'min' } };
|
||||
}
|
||||
return this._containsSelfReference(config, name) ? null : this._deepCloneRule(config);
|
||||
}
|
||||
|
||||
_containsSelfReference(rule, name) {
|
||||
return this._findSelfReference(rule, name) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively rewrite a rule tree, inlining references to derived evidence
|
||||
* configs. `stack` holds the evidence names currently being expanded so a
|
||||
@@ -1111,6 +1359,15 @@ export class RuleGenerator {
|
||||
out.push(...this._expandChainSteps(resolved.steps, refStack));
|
||||
continue;
|
||||
}
|
||||
if (resolved.type === 'relational_comparator' && idx !== steps.length - 1) {
|
||||
// A comparator compares values at (src, candidate) but provides no
|
||||
// candidate set — it cannot enumerate intermediate nodes, so only
|
||||
// a FINAL comparator step (verified at the known object) lowers.
|
||||
this.errors.push(`Chain step '${stepName}' references a comparator evidence at a non-final position. ` +
|
||||
'Comparators can only be the final chain step (the object is known); intermediate positions are not enumerable.');
|
||||
out.push(step);
|
||||
continue;
|
||||
}
|
||||
// Condition step: inline the evidence's config as a rule step. As the
|
||||
// FINAL step the engine verifies it at (intermediate, object); as an
|
||||
// INTERMEDIATE step the engine EXPANDS it from the current node
|
||||
@@ -1276,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,
|
||||
@@ -1303,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;
|
||||
}
|
||||
|
||||
@@ -1416,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);
|
||||
@@ -1427,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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -54,11 +54,14 @@ Definition "A type definition"
|
||||
}
|
||||
|
||||
Field
|
||||
= name:Identifier _ ":" _ fieldType:Type _ isArray:("[]")? _ behavior:Behavior? _ cache:CacheDirective? {
|
||||
= name:Identifier _ ":" _ fieldType:Type optional:("?")? _ isArray:("[]")? _ behavior:Behavior? _ cache:CacheDirective? {
|
||||
return {
|
||||
type: "Field",
|
||||
name,
|
||||
fieldType,
|
||||
// `field: type` is REQUIRED on node insert; `field: type?` is optional.
|
||||
// Presence is enforced by the DSLRuntime when a node is created.
|
||||
required: !optional,
|
||||
isArray: !!isArray,
|
||||
behavior: behavior || null,
|
||||
cache: cache || null
|
||||
@@ -392,7 +395,7 @@ Boolean "A boolean literal"
|
||||
= value:("true" / "false") { return { type: "Literal", value: value === "true" }; }
|
||||
|
||||
Duration "A time duration literal"
|
||||
= value:([0-9]+ ("h" / "d" / "w" / "m")) { return { type: "Literal", value: text(), unit: text().slice(-1) }; }
|
||||
= value:([0-9]+ ("s" / "m" / "h" / "d" / "w")) { return { type: "Literal", value: text(), unit: text().slice(-1) }; }
|
||||
|
||||
|
||||
// -- Core Tokens & Whitespace --
|
||||
|
||||
+684
-669
File diff suppressed because it is too large
Load Diff
+144
-27
@@ -60,6 +60,12 @@ export class DSLRuntime {
|
||||
this.clock = typeof options.clock === 'function' ? options.clock : (() => Date.now());
|
||||
// Default provider-result TTL in ms (0 disables caching).
|
||||
this.defaultProviderCacheTTL = options.policy?.providerCacheTTL ?? options.providerCacheTTL ?? 30_000;
|
||||
// Provider caching is a STORE-RETRIEVAL cache (wall-clock), deliberately
|
||||
// independent of the caller's decision `{ now }` — a provider returns the
|
||||
// store's current data, not a time-travel snapshot. Callers who pin time
|
||||
// or otherwise want fresh retrieval can disable it per-check
|
||||
// (options.cacheProviderResults: false) or globally (policy).
|
||||
this.cacheProviderResults = options.policy?.cacheProviderResults ?? options.cacheProviderResults ?? true;
|
||||
// Per-fact overrides (ms). DSL-declared ttl behaviors are indexed here too.
|
||||
this.factTTLs = new Map(Object.entries(options.factTTLs || {}));
|
||||
}
|
||||
@@ -97,12 +103,16 @@ export class DSLRuntime {
|
||||
fields: [...fields.entries()].map(([fieldName, f]) => ({
|
||||
name: fieldName,
|
||||
type: f.type,
|
||||
isArray: f.isArray
|
||||
isArray: f.isArray,
|
||||
required: f.required !== false
|
||||
}))
|
||||
}));
|
||||
const facts = [...this.relations.entries()]
|
||||
.filter(([, r]) => r.kind === 'fact')
|
||||
.map(([name, r]) => ({ name, params: r.params, injectable: r.injectable }));
|
||||
const sources = [...this.relations.entries()]
|
||||
.filter(([, r]) => r.kind === 'source')
|
||||
.map(([name, r]) => ({ name, params: r.params, injectable: true, withinMs: r.withinMs }));
|
||||
const evidence = [...this.relations.entries()]
|
||||
.filter(([, r]) => r.kind === 'evidence')
|
||||
.map(([name, r]) => ({
|
||||
@@ -110,7 +120,7 @@ export class DSLRuntime {
|
||||
params: r.params,
|
||||
dependsOn: [...(this.dependsOn.get(name) || [])]
|
||||
}));
|
||||
return { types, facts, evidence, providers: this.registeredFacts() };
|
||||
return { types, facts, sources, evidence, providers: this.registeredFacts() };
|
||||
}
|
||||
|
||||
/** All relation names declared by the program (facts + evidence). */
|
||||
@@ -126,7 +136,7 @@ export class DSLRuntime {
|
||||
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 });
|
||||
fields.set(field.name, { type: field.fieldType, isArray: !!field.isArray, required: field.required !== false });
|
||||
}
|
||||
this.types.set(def.name, { fields });
|
||||
}
|
||||
@@ -141,6 +151,18 @@ export class DSLRuntime {
|
||||
});
|
||||
}
|
||||
|
||||
// Sources are injectable, recency-gated proofs: registered as retrievable
|
||||
// relations so a provider can supply them and `within X` gates freshness.
|
||||
for (const src of this.program.sources || []) {
|
||||
this.relations.set(src.name, {
|
||||
kind: 'source',
|
||||
params: (src.params || []).map(p => ({ name: p.name, type: p.paramType, isArray: !!p.isArray })),
|
||||
injectable: true,
|
||||
ttlMs: 0,
|
||||
withinMs: src.within ? this._durationToMs(src.within) : null
|
||||
});
|
||||
}
|
||||
|
||||
for (const ev of this.program.evidence || []) {
|
||||
this.relations.set(ev.name, {
|
||||
kind: 'evidence',
|
||||
@@ -296,41 +318,87 @@ export class DSLRuntime {
|
||||
const b = behavior.behavior || behavior;
|
||||
if (b && b.behaviorType === 'ttl' && b.duration) {
|
||||
const n = parseInt(String(b.duration.value), 10);
|
||||
const mult = { h: 3600_000, d: 86_400_000, w: 604_800_000, m: 60_000 }[b.duration.unit];
|
||||
const mult = { s: 1000, m: 60_000, h: 3600_000, d: 86_400_000, w: 604_800_000 }[b.duration.unit];
|
||||
if (!Number.isNaN(n) && mult) return n * mult;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Convert a Duration AST ({ value, unit }) to milliseconds. */
|
||||
_durationToMs(duration) {
|
||||
if (!duration || duration.value === undefined) return null;
|
||||
const raw = typeof duration.value === 'string' ? duration.value : String(duration.value);
|
||||
const unit = duration.unit || raw.slice(-1);
|
||||
const numeric = parseFloat(raw);
|
||||
if (!Number.isFinite(numeric)) return null;
|
||||
const mult = { s: 1000, m: 60_000, h: 3600_000, d: 86_400_000, w: 604_800_000 }[unit];
|
||||
return mult ? numeric * mult : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a provider result (boolean / number / { possibility, value } /
|
||||
* array of edge objects) into an array of partial-graph edge objects. The
|
||||
* destination follows the DSL fact's declared shape: unary and value-carrying
|
||||
* facts are self-edges on the subject; binary entity facts go subject → object.
|
||||
* Provider-returned edges are validated against the fact's declared typing:
|
||||
* a value-carrying fact must return an object with a value of the declared
|
||||
* type, and possibilities must be in [0, 1]. A violation throws — it is a
|
||||
* provider-authoring error, not a denial.
|
||||
*/
|
||||
_normalizeProviderEdges(result, factMeta, user, object) {
|
||||
_normalizeProviderEdges(result, factMeta, fact, user, object) {
|
||||
const edges = Array.isArray(result) ? result : [result];
|
||||
const secondParamType = factMeta.params[1] && factMeta.params[1].type;
|
||||
const defaultDst = factMeta.params.length >= 2 && this._isValueType(secondParamType)
|
||||
? user
|
||||
: (factMeta.params.length >= 2 ? object : user);
|
||||
const isValueFact = factMeta.params.length >= 2 && this._isValueType(secondParamType);
|
||||
// Sources carry a timestamp in `value` for their recency (`within X`) gate.
|
||||
const isSource = factMeta.kind === 'source';
|
||||
const defaultDst = isValueFact ? user : (factMeta.params.length >= 2 ? object : user);
|
||||
const label = `provider for '${fact}'`;
|
||||
const out = [];
|
||||
for (const edge of edges) {
|
||||
const normalized = typeof edge === 'boolean' || typeof edge === 'number'
|
||||
? { src: user, dst: defaultDst, possibility: edge === true ? 1 : edge }
|
||||
: {
|
||||
...(edge.relation ? { relation: edge.relation } : {}),
|
||||
src: edge.src ?? user,
|
||||
dst: edge.dst ?? defaultDst,
|
||||
possibility: edge.possibility ?? 1,
|
||||
...(edge.value !== undefined ? { value: edge.value } : {}),
|
||||
...(edge.reliability !== undefined ? { reliability: edge.reliability } : {})
|
||||
};
|
||||
? (() => {
|
||||
if (isValueFact) {
|
||||
throw new Error(`DSLRuntime: ${label} is a value-carrying fact — return { value, possibility } (got a bare ${typeof edge === 'number' ? 'number' : 'boolean'})`);
|
||||
}
|
||||
const possibility = edge === true ? 1 : edge;
|
||||
this._checkPossibility(possibility, label);
|
||||
return { src: user, dst: defaultDst, possibility };
|
||||
})()
|
||||
: (() => {
|
||||
const possibility = edge.possibility ?? 1;
|
||||
this._checkPossibility(possibility, label);
|
||||
if (edge.value !== undefined) {
|
||||
if (!isValueFact && !isSource) {
|
||||
throw new Error(`DSLRuntime: ${label} returned a value for a non-value fact '${fact}'`);
|
||||
}
|
||||
if (isValueFact) {
|
||||
this._checkScalarValue(secondParamType, edge.value, `${label}.value`);
|
||||
} else if (isSource && (typeof edge.value !== 'number' || Number.isNaN(edge.value))) {
|
||||
throw new Error(`DSLRuntime: ${label} (a source) must return a numeric timestamp in value`);
|
||||
}
|
||||
} else if (isValueFact) {
|
||||
throw new Error(`DSLRuntime: ${label} must supply a 'value' of type ${secondParamType}`);
|
||||
}
|
||||
return {
|
||||
...(edge.relation ? { relation: edge.relation } : {}),
|
||||
src: edge.src ?? user,
|
||||
dst: edge.dst ?? defaultDst,
|
||||
possibility,
|
||||
...(edge.value !== undefined ? { value: edge.value } : {}),
|
||||
...(edge.reliability !== undefined ? { reliability: edge.reliability } : {})
|
||||
};
|
||||
})();
|
||||
out.push(normalized);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
_checkPossibility(possibility, label) {
|
||||
if (typeof possibility !== 'number' || !Number.isFinite(possibility) || possibility < 0 || possibility > 1) {
|
||||
throw new Error(`DSLRuntime: ${label} returned invalid possibility ${possibility} (expected a number in [0, 1])`);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Schema validation helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -399,6 +467,11 @@ export class DSLRuntime {
|
||||
if (this.types.has(typeName)) {
|
||||
const { fields } = this.types.get(typeName);
|
||||
for (const [name, field] of fields) {
|
||||
// Required fields must be present on insert (`field: type` in the DSL;
|
||||
// `field?: type` marks a field optional).
|
||||
if (field.required && data[name] === undefined) {
|
||||
throw new Error(`DSLRuntime: missing required field '${typeName}.${name}' on node insert`);
|
||||
}
|
||||
if (data[name] !== undefined) this._checkFieldValue(field, data[name], `${typeName}.${name}`);
|
||||
}
|
||||
} else if (this.strictTypes) {
|
||||
@@ -508,7 +581,7 @@ export class DSLRuntime {
|
||||
|
||||
/**
|
||||
* The partial-graph requirements of an evidence relation: the declared
|
||||
* injectable facts it depends on.
|
||||
* injectable facts and sources it depends on.
|
||||
*/
|
||||
requiredFacts(relation) {
|
||||
const deps = this.dependsOn.get(relation);
|
||||
@@ -517,6 +590,7 @@ export class DSLRuntime {
|
||||
for (const dep of deps) {
|
||||
const meta = this.relations.get(dep);
|
||||
if (meta && meta.kind === 'fact' && meta.injectable) required.push(dep);
|
||||
if (meta && meta.kind === 'source') required.push(dep);
|
||||
}
|
||||
return required;
|
||||
}
|
||||
@@ -555,6 +629,11 @@ export class DSLRuntime {
|
||||
} else if (meta.params.length === 2) {
|
||||
this._checkNodeType(user, meta.params[0].type, 'subject');
|
||||
this._checkNodeType(object, meta.params[1].type, 'object');
|
||||
// A value-typed object parameter (can_withdraw(user, amount: number))
|
||||
// carries the expected EDGE VALUE, not a node key — validate the scalar.
|
||||
if (this._isValueType(meta.params[1].type)) {
|
||||
this._checkScalarValue(meta.params[1].type, object, `object of '${relation}'`);
|
||||
}
|
||||
} else if (meta.params.length === 1) {
|
||||
this._checkNodeType(user, meta.params[0].type, 'subject');
|
||||
}
|
||||
@@ -564,14 +643,16 @@ export class DSLRuntime {
|
||||
// provider, if registered, supplies the edge — checking `owns` directly
|
||||
// must consult the `owns` provider, not only evidence-mediated checks).
|
||||
const required = new Set(this.requiredFacts(relation));
|
||||
if (meta && meta.kind === 'fact') required.add(relation);
|
||||
if (meta && (meta.kind === 'fact' || meta.kind === 'source')) required.add(relation);
|
||||
const requiredList = [...required];
|
||||
const providers = { ...this.factProviders, ...(options.factProviders || {}) };
|
||||
const maxRounds = options.maxProviderRounds ?? 3;
|
||||
const partialRelations = [];
|
||||
const injectedRelations = []; // { relation, edges, round }
|
||||
const missingFacts = [];
|
||||
const warnings = [];
|
||||
const satisfied = new Set(); // facts whose edges are in the partial graph
|
||||
const now = this.clock ? this.clock() : Date.now();
|
||||
|
||||
if (options.partialGraph && Array.isArray(options.partialGraph.relations)) {
|
||||
for (const rel of options.partialGraph.relations) {
|
||||
@@ -593,8 +674,11 @@ export class DSLRuntime {
|
||||
// provider overrides are one-off observations — they bypass the cache
|
||||
// entirely (no read, no write) so a fresh override is never masked by
|
||||
// a cached registered-provider result, nor does it pollute the cache.
|
||||
// options.cacheProviderResults:false (or the policy default) disables
|
||||
// the cache for this check.
|
||||
const cachingEnabled = options.cacheProviderResults ?? this.cacheProviderResults;
|
||||
const isPerCheckOverride = !!(options.factProviders && fact in options.factProviders);
|
||||
const cacheHit = isPerCheckOverride ? null : this._providerCacheGet(fact, user, object);
|
||||
const cacheHit = (cachingEnabled && !isPerCheckOverride) ? this._providerCacheGet(fact, user, object) : null;
|
||||
let edges = null;
|
||||
let fromCache = false;
|
||||
if (cacheHit) {
|
||||
@@ -625,8 +709,8 @@ export class DSLRuntime {
|
||||
satisfied.add(fact);
|
||||
continue;
|
||||
}
|
||||
edges = this._normalizeProviderEdges(result, factMeta, user, object);
|
||||
if (!isPerCheckOverride) this._providerCacheSet(fact, user, object, edges);
|
||||
edges = this._normalizeProviderEdges(result, factMeta, fact, user, object);
|
||||
if (cachingEnabled && !isPerCheckOverride) this._providerCacheSet(fact, user, object, edges);
|
||||
} else {
|
||||
missingFacts.push({ relation: fact, reason: 'no_provider' });
|
||||
satisfied.add(fact);
|
||||
@@ -634,11 +718,33 @@ export class DSLRuntime {
|
||||
}
|
||||
|
||||
// A provider may return edges for relations other than its own; the
|
||||
// injected relation names satisfy those facts too (fixed point).
|
||||
// injected relation names satisfy those facts too (fixed point). Apply
|
||||
// the source recency gate (within X) and drop ghost-node edges.
|
||||
const accepted = [];
|
||||
for (const normalized of edges) {
|
||||
const injectedRelation = normalized.relation ?? fact;
|
||||
partialRelations.push({ relation: injectedRelation, ...normalized });
|
||||
satisfied.add(injectedRelation);
|
||||
if (factMeta.kind === 'source' && factMeta.withinMs !== null && factMeta.withinMs !== undefined) {
|
||||
if (normalized.value === undefined) {
|
||||
throw new Error(`DSLRuntime: provider for recency-gated source '${fact}' must return a timestamp in value (within ${factMeta.withinMs}ms)`);
|
||||
}
|
||||
if (now - normalized.value > factMeta.withinMs) {
|
||||
missingFacts.push({ relation: fact, reason: 'stale' });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (normalized.src !== undefined && !this.arbiter.nodeIdByKey.has(normalized.src)) {
|
||||
warnings.push(`provider for '${fact}' returned an edge with unknown source node '${normalized.src}' — dropped`);
|
||||
continue;
|
||||
}
|
||||
if (normalized.dst !== undefined && !this.arbiter.nodeIdByKey.has(normalized.dst)) {
|
||||
warnings.push(`provider for '${fact}' returned an edge with unknown target node '${normalized.dst}' — dropped`);
|
||||
continue;
|
||||
}
|
||||
accepted.push({ relation: injectedRelation, ...normalized });
|
||||
}
|
||||
for (const normalized of accepted) {
|
||||
partialRelations.push(normalized);
|
||||
satisfied.add(normalized.relation);
|
||||
}
|
||||
injectedRelations.push({ relation: fact, edges: edges.length, round, cacheHit: fromCache });
|
||||
newRelationsThisRound += edges.length;
|
||||
@@ -655,13 +761,24 @@ export class DSLRuntime {
|
||||
};
|
||||
}
|
||||
|
||||
const result = this.arbiter.check(user, relation, object, checkOptions);
|
||||
// A value-typed object parameter means the check object IS the expected
|
||||
// edge value, not a node key. Value-carrying facts store edges as
|
||||
// self-edges on the subject, so the underlying check runs on the subject
|
||||
// with the value carried as a per-check gate (options.expectedValue).
|
||||
const isValueObject = meta && meta.params.length === 2 && this._isValueType(meta.params[1].type);
|
||||
const checkObject = isValueObject ? user : object;
|
||||
if (isValueObject) {
|
||||
checkOptions.expectedValue = object;
|
||||
}
|
||||
|
||||
const result = this.arbiter.check(user, relation, checkObject, checkOptions);
|
||||
|
||||
return {
|
||||
...result,
|
||||
requiredFacts: requiredList,
|
||||
providedFacts: injectedRelations.map(r => r.relation),
|
||||
missingFacts
|
||||
missingFacts,
|
||||
warnings
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -141,6 +141,22 @@ function validateDefinitions(program, tables, errors, warnings, source) {
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// Duplicate field names within a definition silently keep the last
|
||||
// declaration (e.g. `{ id: string id: string }`) — reject loudly instead.
|
||||
const fieldSeen = new Set();
|
||||
for (const field of def.fields || []) {
|
||||
if (fieldSeen.has(field.name)) {
|
||||
errors.push(createError({
|
||||
message: `Duplicate field '${def.name}.${field.name}'.`,
|
||||
rule: 'Each field name must be unique within a definition.',
|
||||
fix: `Remove the duplicate declaration of '${def.name}.${field.name}'.`,
|
||||
location: findLocation(source, field.name),
|
||||
context: formatContext(source, findLocation(source, def.name))
|
||||
}));
|
||||
}
|
||||
fieldSeen.add(field.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1006,6 +1022,31 @@ function formatPegError(error, sourceText, sourceName) {
|
||||
message = 'Missing colon after identifier.';
|
||||
fix = 'Add ":" between a name and its type.';
|
||||
rule = 'Types must be declared using name: Type syntax.';
|
||||
} else {
|
||||
// Targeted hints for common declaration mistakes. The peggy error only
|
||||
// reports "unexpected X"; these heuristics read the source around the
|
||||
// failure to point at the real constraint.
|
||||
const offset = error.location?.start?.offset ?? -1;
|
||||
const before = offset >= 0 ? sourceText.slice(0, offset) : '';
|
||||
const tail = before.split(/\n/).pop() || '';
|
||||
const lastKeyword = (() => {
|
||||
const matches = [...before.matchAll(/\b(fact|relation|source|evidence|measure)\b/g)];
|
||||
return matches.length ? matches[matches.length - 1][1] : null;
|
||||
})();
|
||||
|
||||
if (found === 'w' && lastKeyword === 'fact' || (found === 'w' && lastKeyword === 'relation')) {
|
||||
message = '`within` is only valid on `source` declarations.';
|
||||
fix = 'Move the recency constraint to a `source` declaration, or drop `within` here.';
|
||||
rule = 'Only sources accept a `within` freshness constraint.';
|
||||
} else if (/\bBEHAVES\b/.test(before) && tail.includes('BEHAVES')) {
|
||||
message = 'A declaration can carry only one `BEHAVES` clause.';
|
||||
fix = 'Choose either a behavior (`BEHAVES AS transitive`) or a TTL (`BEHAVES { ttl 1h }`), not both.';
|
||||
rule = '`BEHAVES` may appear at most once per declaration.';
|
||||
} else if (found === 'l' && lastKeyword === 'evidence' && sourceText.slice(offset, offset + 5) === 'limit') {
|
||||
message = '`limit` is only valid on pattern/recursive bodies.';
|
||||
fix = 'Move `limit N` onto the pattern itself, e.g. reports_to(user, *m) { ... } limit N.';
|
||||
rule = 'Only pattern bodies take a recursion depth limit.';
|
||||
}
|
||||
}
|
||||
|
||||
return createError({
|
||||
|
||||
@@ -196,6 +196,36 @@ describe('DSL Compiler', () => {
|
||||
assert.ok(invalidResult.errors.length > 0, 'Should have validation errors');
|
||||
});
|
||||
|
||||
test('Rejects duplicate fields within a definition', () => {
|
||||
const dupFieldDSL = `
|
||||
definition Employee { id: string id: string }
|
||||
`;
|
||||
const result = compiler.validate(dupFieldDSL);
|
||||
assert.ok(!result.success, 'Duplicate field should fail validation');
|
||||
assert.match(result.errors[0], /Duplicate field 'Employee.id'/);
|
||||
});
|
||||
|
||||
test('Hints at the real constraint for common declaration mistakes', () => {
|
||||
const withinOnFact = compiler.compile(`
|
||||
definition Employee { id: string? }
|
||||
fact owns(user: Employee, doc: Employee) within 1h
|
||||
`, 'err-within');
|
||||
assert.match(withinOnFact.errors[0], /within.*only valid on `source`/);
|
||||
|
||||
const doubleBehaves = compiler.compile(`
|
||||
definition Employee { id: string? }
|
||||
fact rel(user: Employee, doc: Employee) BEHAVES AS transitive BEHAVES { ttl 1h }
|
||||
`, 'err-behaves');
|
||||
assert.match(doubleBehaves.errors[0], /only one `BEHAVES` clause/);
|
||||
|
||||
const limitAfterBody = compiler.compile(`
|
||||
definition Employee { id: string? }
|
||||
fact owns(user: Employee, doc: Employee)
|
||||
evidence can_read(user: Employee, doc: Employee) { owns(user, doc) } limit 5
|
||||
`, 'err-limit');
|
||||
assert.match(limitAfterBody.errors[0], /`limit` is only valid on pattern/);
|
||||
});
|
||||
|
||||
test('Rule generation', () => {
|
||||
const dsl = `
|
||||
definition Employee {
|
||||
|
||||
+127
-8
@@ -20,9 +20,9 @@ import { Arbiter } from '@arbiter/core';
|
||||
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
|
||||
|
||||
const BASE_DSL = `
|
||||
definition Employee { id: string level: number active: boolean }
|
||||
definition Group { id: string }
|
||||
definition Doc { id: string }
|
||||
definition Employee { id: string? level: number? active: boolean? }
|
||||
definition Group { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact member_of(user: Employee, group: Group)
|
||||
fact *owns(user: Employee, doc: Doc)
|
||||
fact *user_score(user: Employee, value: number)
|
||||
@@ -164,8 +164,8 @@ describe('DSLRuntime', () => {
|
||||
|
||||
it('derives transitive required facts through evidence composition', async () => {
|
||||
const dsl = `
|
||||
definition Employee { id: string }
|
||||
definition Doc { id: string }
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact *owns(user: Employee, doc: Doc)
|
||||
fact *banned(user: Employee)
|
||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
@@ -191,9 +191,9 @@ describe('DSLRuntime', () => {
|
||||
|
||||
it('derives transitive required facts through a condition-step chain', () => {
|
||||
const dsl = `
|
||||
definition Employee { id: string }
|
||||
definition Group { id: string }
|
||||
definition Doc { id: string }
|
||||
definition Employee { id: string? }
|
||||
definition Group { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact *member_of(user: Employee, group: Group)
|
||||
fact *can_view(group: Group, doc: Doc)
|
||||
fact *banned(group: Group)
|
||||
@@ -205,4 +205,123 @@ describe('DSLRuntime', () => {
|
||||
// evidence's requirements, alongside the edge-traversal fact.
|
||||
assert.deepEqual(rt.requiredFacts('can_via'), ['member_of', 'can_view', 'banned']);
|
||||
});
|
||||
|
||||
it('negates a NOT predicate (1 - possibility)', async () => {
|
||||
const dsl = `
|
||||
definition Employee { id: string? }
|
||||
fact banned(user: Employee)
|
||||
evidence can_enter(user: Employee) { NOT banned(user) }
|
||||
`;
|
||||
// Absent predicate negates to allow.
|
||||
const absent = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-not-absent');
|
||||
absent.addNode('u:1', 'Employee', {});
|
||||
assert.equal((await absent.check('u:1', 'can_enter', 'u:1')).possibility, 1);
|
||||
// Present predicate negates to its complement.
|
||||
const present = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-not-present');
|
||||
present.addNode('u:1', 'Employee', {});
|
||||
present.addRelation('u:1', 'banned', 'u:1', { possibility: 0.9 });
|
||||
const denied = await present.check('u:1', 'can_enter', 'u:1');
|
||||
assert.ok(Math.abs(denied.possibility - 0.1) < 1e-9, `expected 0.1, got ${denied.possibility}`);
|
||||
// Nested inside an AND: the negated child still scopes to the subject.
|
||||
const nested = new DSLRuntime(new Arbiter()).compile(`
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact owns(user: Employee, doc: Doc)
|
||||
fact banned(user: Employee)
|
||||
evidence can_open(user: Employee, doc: Doc) { owns(user, doc) NOT banned(user) }
|
||||
`, 'rt-not-nested');
|
||||
nested.addNode('u:1', 'Employee', {});
|
||||
nested.addNode('doc:9', 'Doc', {});
|
||||
nested.addRelation('u:1', 'owns', 'doc:9', { possibility: 0.8 });
|
||||
nested.addRelation('u:1', 'banned', 'u:1', { possibility: 0.6 });
|
||||
assert.equal((await nested.check('u:1', 'can_open', 'doc:9')).possibility, 0.4);
|
||||
});
|
||||
|
||||
it('resolves BEHAVES AS transitive facts as bounded transitive closure', async () => {
|
||||
const dsl = `
|
||||
definition Employee { id: string? }
|
||||
fact reports_to(user: Employee, boss: Employee) BEHAVES AS transitive
|
||||
evidence can_see(user: Employee, doc: Employee) { reports_to(user, doc) }
|
||||
`;
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-transitive');
|
||||
['e:1', 'e:2', 'e:3', 'e:4'].forEach(k => rt.addNode(k, 'Employee', {}));
|
||||
rt.addRelation('e:1', 'reports_to', 'e:2', { possibility: 1.0 });
|
||||
rt.addRelation('e:2', 'reports_to', 'e:3', { possibility: 0.9 });
|
||||
rt.addRelation('e:3', 'reports_to', 'e:4', { possibility: 0.8 });
|
||||
// Direct checks on the transitive fact follow multi-hop paths.
|
||||
assert.equal((await rt.check('e:1', 'reports_to', 'e:3')).possibility, 0.9);
|
||||
assert.equal((await rt.check('e:1', 'reports_to', 'e:4')).possibility, 0.8);
|
||||
// Reverse direction does not grant.
|
||||
assert.equal((await rt.check('e:2', 'reports_to', 'e:1')).possibility, 0);
|
||||
// Evidence references inherit the closure.
|
||||
assert.equal((await rt.check('e:1', 'can_see', 'e:4')).possibility, 0.8);
|
||||
// Non-transitive facts stay direct-only.
|
||||
const direct = new DSLRuntime(new Arbiter()).compile(`
|
||||
definition Employee { id: string? }
|
||||
fact knows(user: Employee, peer: Employee)
|
||||
evidence can_ping(user: Employee, doc: Employee) { knows(user, doc) }
|
||||
`, 'rt-nontransitive');
|
||||
['a:1', 'a:2', 'a:3'].forEach(k => direct.addNode(k, 'Employee', {}));
|
||||
direct.addRelation('a:1', 'knows', 'a:2', { possibility: 1.0 });
|
||||
direct.addRelation('a:2', 'knows', 'a:3', { possibility: 1.0 });
|
||||
assert.equal((await direct.check('a:1', 'can_ping', 'a:3')).possibility, 0);
|
||||
});
|
||||
|
||||
it('bounds transitive closure depth by the fact limit', async () => {
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||
definition Employee { id: string? }
|
||||
fact reports_to(user: Employee, boss: Employee) BEHAVES AS transitive limit 2
|
||||
evidence can_see(user: Employee, doc: Employee) { reports_to(user, doc) }
|
||||
`, 'rt-transitive-limit');
|
||||
['e:1', 'e:2', 'e:3', 'e:4'].forEach(k => rt.addNode(k, 'Employee', {}));
|
||||
rt.addRelation('e:1', 'reports_to', 'e:2', { possibility: 1.0 });
|
||||
rt.addRelation('e:2', 'reports_to', 'e:3', { possibility: 1.0 });
|
||||
rt.addRelation('e:3', 'reports_to', 'e:4', { possibility: 1.0 });
|
||||
assert.equal((await rt.check('e:1', 'can_see', 'e:3')).possibility, 1.0);
|
||||
assert.equal((await rt.check('e:1', 'can_see', 'e:4')).possibility, 0);
|
||||
});
|
||||
|
||||
it('retrieves sources through providers and gates them by within recency', async () => {
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
source *session(user: Employee) within 1h
|
||||
fact *owns(user: Employee, doc: Doc)
|
||||
evidence can_read(user: Employee, doc: Doc) { session(user) owns(user, doc) }
|
||||
`, 'rt-source');
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
assert.ok(rt.relations.has('session'));
|
||||
assert.equal(rt.relations.get('session').kind, 'source');
|
||||
assert.equal(rt.relations.get('session').withinMs, 3_600_000);
|
||||
// A fresh session proof grants.
|
||||
const fresh = await rt.check('u:1', 'can_read', 'doc:9', {
|
||||
factProviders: { session: async () => ({ possibility: 1.0, value: Date.now() }), owns: async () => 0.9 }
|
||||
});
|
||||
assert.equal(fresh.possibility, 0.9);
|
||||
assert.deepEqual(fresh.providedFacts, ['session', 'owns']);
|
||||
// A stale proof (2h old, beyond the 1h window) denies as stale.
|
||||
const stale = await rt.check('u:1', 'can_read', 'doc:9', {
|
||||
factProviders: { session: async () => ({ possibility: 1.0, value: Date.now() - 2 * 3600_000 }), owns: async () => 0.9 }
|
||||
});
|
||||
assert.equal(stale.possibility, 0);
|
||||
assert.deepEqual(stale.missingFacts, [{ relation: 'session', reason: 'stale' }]);
|
||||
});
|
||||
|
||||
it('warns about and drops provider edges referencing unknown nodes', async () => {
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact *owns(user: Employee, doc: Doc)
|
||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
`, 'rt-ghost');
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
const res = await rt.check('u:1', 'can_read', 'doc:9', {
|
||||
factProviders: { owns: async () => [{ src: 'ghost:1', dst: 'doc:9', possibility: 0.9 }] }
|
||||
});
|
||||
assert.equal(res.possibility, 0);
|
||||
assert.equal(res.warnings.length, 1);
|
||||
assert.match(res.warnings[0], /unknown source node 'ghost:1'/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,8 +14,8 @@ import { Arbiter } from '@arbiter/core';
|
||||
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
|
||||
|
||||
const BASE_DSL = `
|
||||
definition Employee { id: string }
|
||||
definition Doc { id: string }
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact *owns(user: Employee, doc: Doc)
|
||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
`;
|
||||
@@ -102,8 +102,8 @@ describe('DSLRuntime provider-result caching', () => {
|
||||
|
||||
it('invalidateProviderCache() clears all or per relation', async () => {
|
||||
const dsl = `
|
||||
definition Employee { id: string }
|
||||
definition Doc { id: string }
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact *owns(user: Employee, doc: Doc)
|
||||
fact *banned(user: Employee)
|
||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
@@ -151,8 +151,8 @@ describe('DSLRuntime provider-result caching', () => {
|
||||
|
||||
it('uses the DSL-declared fact TTL (BEHAVES { ttl X })', async () => {
|
||||
const dsl = `
|
||||
definition Employee { id: string }
|
||||
definition Doc { id: string }
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact *balance(user: Employee, amount: number) BEHAVES { ttl 1h }
|
||||
evidence can_spend(user: Employee, doc: Doc) { balance(user, 1) }
|
||||
`;
|
||||
@@ -173,4 +173,31 @@ describe('DSLRuntime provider-result caching', () => {
|
||||
await rt.check('u:1', 'can_spend', 'doc:9');
|
||||
assert.equal(calls, 2, 're-invoked past the DSL-declared 1h TTL');
|
||||
});
|
||||
|
||||
it('cacheProviderResults:false bypasses the cache per check', async () => {
|
||||
const rt = makeRuntime();
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
let calls = 0;
|
||||
rt.registerFact('owns', async () => { calls++; return 0.9; });
|
||||
await rt.check('u:1', 'can_read', 'doc:9');
|
||||
assert.equal(calls, 1);
|
||||
// Bypass forces a fresh retrieval without clearing the cache.
|
||||
await rt.check('u:1', 'can_read', 'doc:9', { cacheProviderResults: false });
|
||||
assert.equal(calls, 2);
|
||||
// Cache still intact for the next default check.
|
||||
await rt.check('u:1', 'can_read', 'doc:9');
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
it('policy.cacheProviderResults:false disables caching globally', async () => {
|
||||
const rt = makeRuntime({ policy: { cacheProviderResults: false } });
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
let calls = 0;
|
||||
rt.registerFact('owns', async () => { calls++; return 0.9; });
|
||||
await rt.check('u:1', 'can_read', 'doc:9');
|
||||
await rt.check('u:1', 'can_read', 'doc:9');
|
||||
assert.equal(calls, 2, 'no caching when disabled globally');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,8 +14,8 @@ import { Arbiter } from '@arbiter/core';
|
||||
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
|
||||
|
||||
const BASE_DSL = `
|
||||
definition Employee { id: string level: number active: boolean }
|
||||
definition Doc { id: string created: timestamp }
|
||||
definition Employee { id: string? level: number? active: boolean? }
|
||||
definition Doc { id: string? created: timestamp? }
|
||||
fact *owns(user: Employee, doc: Doc)
|
||||
fact *banned(user: Employee)
|
||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
@@ -73,8 +73,8 @@ describe('DSLRuntime extended', () => {
|
||||
// edge for a DIFFERENT injectable fact that can_open also requires via
|
||||
// composition — here we add a transitive requirement to prove the loop.
|
||||
const dsl = `
|
||||
definition Employee { id: string }
|
||||
definition Doc { id: string }
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact *owns(user: Employee, doc: Doc)
|
||||
fact *granted(user: Employee, doc: Doc)
|
||||
evidence base_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
@@ -165,4 +165,33 @@ describe('DSLRuntime extended', () => {
|
||||
assert.equal(missed.possibility, 0);
|
||||
assert.deepEqual(missed.missingFacts, [{ relation: 'owns', reason: 'no_provider' }]);
|
||||
});
|
||||
|
||||
it('recompiling a scope uninstalls its stale relation configs', async () => {
|
||||
const rt = new DSLRuntime(new Arbiter());
|
||||
rt.compile(`
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact owns(user: Employee, doc: Doc)
|
||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
`, 'rt-stale');
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
rt.addRelation('u:1', 'owns', 'doc:9', { possibility: 1.0 });
|
||||
assert.equal(rt.arbiter.check('u:1', 'can_read', 'doc:9').possibility, 1.0);
|
||||
|
||||
// Recompile the SAME scope with a different program: can_read/owns are no
|
||||
// longer declared and must not keep granting. A second scope's relations
|
||||
// would be unaffected (compileMultiple coexistence).
|
||||
rt.compile(`
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact shares(user: Employee, doc: Doc)
|
||||
evidence can_share(user: Employee, doc: Doc) { shares(user, doc) }
|
||||
`, 'rt-stale');
|
||||
const stale = rt.arbiter.check('u:1', 'can_read', 'doc:9');
|
||||
assert.equal(stale.possibility, 0, 'revoked can_read must not keep granting');
|
||||
assert.ok(!rt.arbiter.relationConfigs.has('can_read'));
|
||||
assert.ok(!rt.arbiter.relationConfigs.has('owns'));
|
||||
assert.ok(rt.arbiter.relationConfigs.has('can_share'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* tests/DSLRuntimeTyping.test.js — duration seconds, required fields, and
|
||||
* type validation of insertions / updates / provider retrievals.
|
||||
*
|
||||
* - Duration literals now accept s/m/h/d/w: `BEHAVES { ttl 30s }` is 30s.
|
||||
* - Definition fields are REQUIRED by default (`field: type`); `field: type?`
|
||||
* marks a field optional. addNode enforces presence on insert.
|
||||
* - Provider-returned edges are validated against the fact's declared typing:
|
||||
* a value-carrying fact must return { value, possibility } with a value of
|
||||
* the declared type, and possibilities must lie in [0, 1].
|
||||
*/
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Arbiter } from '@arbiter/core';
|
||||
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
|
||||
|
||||
describe('DSLRuntime typing', () => {
|
||||
it('accepts seconds/minutes/hours/days/weeks in duration literals', async () => {
|
||||
const dsl = `
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact *a(user: Employee, amount: number) BEHAVES { ttl 30s }
|
||||
fact *b(user: Employee, amount: number) BEHAVES { ttl 2m }
|
||||
fact *c(user: Employee, amount: number) BEHAVES { ttl 1h }
|
||||
fact *d(user: Employee, amount: number) BEHAVES { ttl 3d }
|
||||
fact *e(user: Employee, amount: number) BEHAVES { ttl 1w }
|
||||
`;
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-units');
|
||||
assert.equal(rt.relations.get('a').ttlMs, 30_000);
|
||||
assert.equal(rt.relations.get('b').ttlMs, 120_000);
|
||||
assert.equal(rt.relations.get('c').ttlMs, 3_600_000);
|
||||
assert.equal(rt.relations.get('d').ttlMs, 259_200_000);
|
||||
assert.equal(rt.relations.get('e').ttlMs, 604_800_000);
|
||||
});
|
||||
|
||||
it('enforces required definition fields on node insert', () => {
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||
definition Employee { id: string level: number active: boolean? }
|
||||
`, 'rt-req');
|
||||
// id and level are required (no `?`); active is optional.
|
||||
assert.throws(() => rt.addNode('u:1', 'Employee', { level: 3 }), /missing required field 'Employee.id'/);
|
||||
assert.throws(() => rt.addNode('u:2', 'Employee', { id: 'u:2' }), /missing required field 'Employee.level'/);
|
||||
rt.addNode('u:3', 'Employee', { id: 'u:3', level: 5 }); // both required, no active -> ok
|
||||
rt.addNode('u:4', 'Employee', { id: 'u:4', level: 5, active: true });
|
||||
});
|
||||
|
||||
it('exposes requiredness in the schema snapshot', () => {
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||
definition Employee { id: string level: number? }
|
||||
`, 'rt-schema-req');
|
||||
const employee = rt.getSchema().types.find(t => t.name === 'Employee');
|
||||
assert.equal(employee.fields.find(f => f.name === 'id').required, true);
|
||||
assert.equal(employee.fields.find(f => f.name === 'level').required, false);
|
||||
});
|
||||
|
||||
it('validates a provider-returned value against the declared value type', async () => {
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact *balance(user: Employee, amount: number)
|
||||
evidence can_spend(user: Employee, doc: Doc) { balance(user, 1) }
|
||||
`, 'rt-valuetype');
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
rt.registerFact('balance', async () => ({ possibility: 1.0, value: 'high' }));
|
||||
await assert.rejects(() => rt.check('u:1', 'can_spend', 'doc:9'), /must be number/);
|
||||
});
|
||||
|
||||
it('requires a value for a value-carrying fact (no bare-number shorthand)', async () => {
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact *balance(user: Employee, amount: number)
|
||||
evidence can_spend(user: Employee, doc: Doc) { balance(user, 1) }
|
||||
`, 'rt-valshape');
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
rt.registerFact('balance', async () => 0.9);
|
||||
await assert.rejects(() => rt.check('u:1', 'can_spend', 'doc:9'), /value-carrying fact/);
|
||||
rt.registerFact('balance', async () => ({ possibility: 1.0 })); // missing value
|
||||
await assert.rejects(() => rt.check('u:1', 'can_spend', 'doc:9'), /must supply a 'value'/);
|
||||
});
|
||||
|
||||
it('rejects a provider-returned possibility outside [0, 1]', async () => {
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||
definition Employee { id: string? }
|
||||
definition Doc { id: string? }
|
||||
fact *owns(user: Employee, doc: Doc)
|
||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
`, 'rt-poss');
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
rt.registerFact('owns', async () => ({ possibility: 2.0 }));
|
||||
await assert.rejects(() => rt.check('u:1', 'can_read', 'doc:9'), /invalid possibility/);
|
||||
});
|
||||
|
||||
it('enforces a literal value in evidence as an exact edge-value gate', async () => {
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||
definition Employee { id: string? }
|
||||
fact balance(user: Employee, amount: number)
|
||||
evidence can_afford(user: Employee) { balance(user, 5) }
|
||||
`, 'rt-expected-value');
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
// An edge carrying amount 3 must NOT satisfy balance(user, 5) — without the
|
||||
// gate every balance edge matched regardless of amount (silent over-grant).
|
||||
rt.addRelation('u:1', 'balance', 'u:1', { possibility: 1.0, value: 3 });
|
||||
const denied = await rt.check('u:1', 'can_afford', 'u:1');
|
||||
assert.equal(denied.possibility, 0, 'value-3 edge must not satisfy balance(user, 5)');
|
||||
rt.addRelation('u:1', 'balance', 'u:1', { possibility: 0.8, value: 5 });
|
||||
const granted = await rt.check('u:1', 'can_afford', 'u:1');
|
||||
assert.equal(granted.possibility, 0.8, 'value-5 edge must satisfy balance(user, 5)');
|
||||
});
|
||||
|
||||
it('treats a value-typed evidence OBJECT param as the expected edge value', async () => {
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(`
|
||||
definition Employee { id: string? }
|
||||
fact balance(user: Employee, amount: number)
|
||||
evidence can_withdraw(user: Employee, amount: number) { balance(user, amount) }
|
||||
`, 'rt-value-object');
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addRelation('u:1', 'balance', 'u:1', { possibility: 0.9, value: 5 });
|
||||
// The check object is the VALUE, not a node key: grant only on exact match.
|
||||
const granted = await rt.check('u:1', 'can_withdraw', 5);
|
||||
assert.equal(granted.possibility, 0.9, 'value-5 check must match the value-5 edge');
|
||||
const denied = await rt.check('u:1', 'can_withdraw', 3);
|
||||
assert.equal(denied.possibility, 0, 'value-3 check must not match the value-5 edge');
|
||||
// Re-checking the granted value must not hit a value-3 cache entry.
|
||||
const again = await rt.check('u:1', 'can_withdraw', 5);
|
||||
assert.equal(again.possibility, 0.9, 'value-5 re-check must not be served the value-3 result');
|
||||
// Direct fact check with a value object works the same way.
|
||||
const direct = await rt.check('u:1', 'balance', 5);
|
||||
assert.equal(direct.possibility, 0.9, 'direct balance(user, 5) must match the value-5 edge');
|
||||
// A non-scalar object for a value-typed param is rejected loudly.
|
||||
await assert.rejects(() => rt.check('u:1', 'can_withdraw', 'u:1'), /must be number/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* tests/Recursion.test.js — bounded self-recursion (transitive closure).
|
||||
*
|
||||
* An evidence whose config contains a chain step referencing ITSELF is
|
||||
* unrolled at compile time into a bounded transitive closure: a union of
|
||||
* paths — base, hop+base, hop²+base, … — where `hop` is the recursive chain's
|
||||
* steps before the self-reference and the depth N comes from the pattern's
|
||||
* `limit N` (or the compiler's maxRecursionDepth default). The base (the
|
||||
* evidence's non-recursive statements) is verified as a condition step at each
|
||||
* path's terminal node.
|
||||
*
|
||||
* A pure recursion (no base case) cannot grant and is a compile-time error.
|
||||
*/
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Arbiter } from '@arbiter/core';
|
||||
import { DSLCompiler } from '../src/DSLCompiler.js';
|
||||
|
||||
const BASE = `
|
||||
definition Employee { id: string }
|
||||
definition Doc { id: string }
|
||||
fact can_access(user: Employee, doc: Doc)
|
||||
fact reports_to(user: Employee, manager: Employee)
|
||||
`;
|
||||
|
||||
const RECURSIVE = `
|
||||
evidence can_access_via(user: Employee, doc: Doc) {
|
||||
can_access(user, doc)
|
||||
reports_to(user, *m) { can_access_via(m, doc) } limit 3
|
||||
}
|
||||
`;
|
||||
|
||||
function compile(dsl, name = 'rec') {
|
||||
const arb = new Arbiter();
|
||||
const result = new DSLCompiler(arb).compile(dsl, name);
|
||||
return { arb, result };
|
||||
}
|
||||
|
||||
describe('Bounded self-recursion', () => {
|
||||
it('unrolls into a union of base + bounded hop chains', () => {
|
||||
const { arb, result } = compile(BASE + RECURSIVE);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
const cfg = arb.relationConfigs.get('can_access_via');
|
||||
assert.equal(cfg.type, 'logical');
|
||||
assert.ok(cfg.union, 'recursion should compile to a union of paths');
|
||||
// base + 3 hops (limit 3)
|
||||
assert.equal(cfg.union.rules.length, 4);
|
||||
});
|
||||
|
||||
it('grants through the base case and through multi-hop chains', () => {
|
||||
const { arb, result } = compile(BASE + RECURSIVE);
|
||||
assert.ok(result.success);
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('m:1', 'Employee'); arb.addNode('m2:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||
// base
|
||||
arb.addRelation('u:1', 'can_access', 'doc:9', { possibility: 1.0 });
|
||||
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 1.0);
|
||||
// 1-hop: u -> m -> doc
|
||||
arb.removeRelation('u:1', 'can_access', 'doc:9');
|
||||
arb.addRelation('u:1', 'reports_to', 'm:1', { possibility: 1.0 });
|
||||
arb.addRelation('m:1', 'can_access', 'doc:9', { possibility: 0.7 });
|
||||
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0.7);
|
||||
// 2-hop: u -> m -> m2 -> doc
|
||||
arb.addRelation('m:1', 'reports_to', 'm2:1', { possibility: 1.0 });
|
||||
arb.addRelation('m2:1', 'can_access', 'doc:9', { possibility: 0.5 });
|
||||
// union takes the best path: max(0.7, 0.5) = 0.7
|
||||
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0.7);
|
||||
// 2-hop alone (remove the 1-hop can_access)
|
||||
arb.removeRelation('m:1', 'can_access', 'doc:9');
|
||||
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0.5);
|
||||
});
|
||||
|
||||
it('enforces the recursion depth limit', () => {
|
||||
const { arb, result } = compile(`
|
||||
${BASE}
|
||||
evidence can_access_via(user: Employee, doc: Doc) {
|
||||
can_access(user, doc)
|
||||
reports_to(user, *m) { can_access_via(m, doc) } limit 2
|
||||
}
|
||||
`);
|
||||
assert.ok(result.success);
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('m:1', 'Employee'); arb.addNode('m2:1', 'Employee'); arb.addNode('m3:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'reports_to', 'm:1', { possibility: 1.0 });
|
||||
arb.addRelation('m:1', 'reports_to', 'm2:1', { possibility: 1.0 });
|
||||
arb.addRelation('m2:1', 'reports_to', 'm3:1', { possibility: 1.0 });
|
||||
arb.addRelation('m2:1', 'can_access', 'doc:9', { possibility: 0.5 }); // 2 hops
|
||||
arb.addRelation('m3:1', 'can_access', 'doc:9', { possibility: 0.9 }); // 3 hops
|
||||
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0.5);
|
||||
arb.removeRelation('m2:1', 'can_access', 'doc:9');
|
||||
// only the 3-hop path remains — beyond the limit -> denied
|
||||
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0);
|
||||
});
|
||||
|
||||
it('uses the compiler maxRecursionDepth default when no limit is given', () => {
|
||||
const dsl = `
|
||||
${BASE}
|
||||
evidence can_access_via(user: Employee, doc: Doc) {
|
||||
can_access(user, doc)
|
||||
reports_to(user, *m) { can_access_via(m, doc) }
|
||||
}
|
||||
`;
|
||||
const { arb, result } = compile(dsl);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
// default depth 3 -> base + 3 hops
|
||||
assert.equal(arb.relationConfigs.get('can_access_via').union.rules.length, 4);
|
||||
// a deeper path (4 hops) is not granted
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('m:1', 'Employee'); arb.addNode('m2:1', 'Employee'); arb.addNode('m3:1', 'Employee'); arb.addNode('m4:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'reports_to', 'm:1', { possibility: 1.0 });
|
||||
arb.addRelation('m:1', 'reports_to', 'm2:1', { possibility: 1.0 });
|
||||
arb.addRelation('m2:1', 'reports_to', 'm3:1', { possibility: 1.0 });
|
||||
arb.addRelation('m3:1', 'reports_to', 'm4:1', { possibility: 1.0 });
|
||||
arb.addRelation('m4:1', 'can_access', 'doc:9', { possibility: 1.0 });
|
||||
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0, '4-hop path exceeds default depth');
|
||||
});
|
||||
|
||||
it('rejects a pure recursion with no base case', () => {
|
||||
const { result } = compile(`
|
||||
${BASE}
|
||||
evidence can_access_via(user: Employee, doc: Doc) {
|
||||
reports_to(user, *m) { can_access_via(m, doc) } limit 3
|
||||
}
|
||||
`);
|
||||
assert.equal(result.success, false);
|
||||
assert.ok(result.errors.some(e => /no base case/.test(e)), JSON.stringify(result.errors));
|
||||
});
|
||||
|
||||
it('keeps mutual (non-self) cycles a compile error', () => {
|
||||
const { result } = compile(`
|
||||
${BASE}
|
||||
fact peer(user: Employee, other: Employee)
|
||||
evidence a(user: Employee, doc: Doc) { peer(user, *p) { b(p, doc) } }
|
||||
evidence b(user: Employee, doc: Doc) { peer(user, *p) { a(p, doc) } }
|
||||
`);
|
||||
assert.equal(result.success, false);
|
||||
assert.ok(result.errors.some(e => /[Cc]yclic/.test(e)), JSON.stringify(result.errors));
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user