Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ad365a65a9 | |||
| 6214780244 | |||
| 3ace783a59 | |||
| fe162251fc | |||
| 351551af0f | |||
| 2dc478f5a3 | |||
| 88f10f9db4 |
Generated
+6
-6
@@ -1,15 +1,15 @@
|
||||
{
|
||||
"name": "@arbiter/evidence-dsl",
|
||||
"version": "1.1.0",
|
||||
"version": "1.6.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@arbiter/evidence-dsl",
|
||||
"version": "1.1.0",
|
||||
"version": "1.6.0",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@arbiter/core": "^1.0.2"
|
||||
"@arbiter/core": "^1.0.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rigor/core": "^3.1.0",
|
||||
@@ -17,9 +17,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@arbiter/core": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://hub.kl1.tenere.ai/api/packages/Arbiter/npm/%40arbiter%2Fcore/-/1.0.2/core-1.0.2.tgz",
|
||||
"integrity": "sha512-N1duiHy1Rlsxqpvu8uPf4tMaLOQ2tNXvGs53jLkRcIAYqafIAMvcf0BPS2iE2xVKNsqY92+F05bZZEAO5jnbyQ==",
|
||||
"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==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@tenere/pltc-core": "^0.6.3",
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@arbiter/evidence-dsl",
|
||||
"version": "1.1.0",
|
||||
"version": "1.8.0",
|
||||
"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.2"
|
||||
"@arbiter/core": "^1.0.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rigor/core": "^3.1.0",
|
||||
|
||||
+204
-46
@@ -10,6 +10,7 @@ export class RuleGenerator {
|
||||
this.generatedRules = new Map();
|
||||
this.errors = [];
|
||||
this.dependencyIndex = new Map();
|
||||
this.evidenceNames = new Set();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -38,6 +39,14 @@ export class RuleGenerator {
|
||||
this.generateFactConfig(fact);
|
||||
});
|
||||
|
||||
// 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
|
||||
// (a linker pass), so the engine evaluates a fully-resolved config tree
|
||||
// and never needs a sub-query traversal mechanism. Forward references are
|
||||
// handled because every evidence config is built before this pass runs.
|
||||
this.resolveEvidenceReferences();
|
||||
|
||||
// Apply generated rules to arbiter
|
||||
this.applyRulesToArbiter();
|
||||
|
||||
@@ -62,6 +71,7 @@ export class RuleGenerator {
|
||||
*/
|
||||
generateEvidenceRules(evidence) {
|
||||
const relationName = evidence.name;
|
||||
this.evidenceNames.add(relationName);
|
||||
const ruleConfig = this.buildRuleConfig(evidence);
|
||||
|
||||
if (ruleConfig) {
|
||||
@@ -145,6 +155,7 @@ export class RuleGenerator {
|
||||
for (const step of rule.steps) {
|
||||
if (typeof step === 'string') targetSet.add(step);
|
||||
else if (step && typeof step.relation === 'string') targetSet.add(step.relation);
|
||||
else if (step && step.rule) collect(step.rule, targetSet);
|
||||
}
|
||||
}
|
||||
if (rule.type === 'relational_comparator') {
|
||||
@@ -162,6 +173,7 @@ export class RuleGenerator {
|
||||
for (const child of ruleList) collect(child, targetSet);
|
||||
}
|
||||
if (node?.rule) collect(node.rule, targetSet);
|
||||
if (node?.direct) collect(node.direct, targetSet);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -274,7 +286,7 @@ export class RuleGenerator {
|
||||
buildSingleStatementRule(statement, evidence) {
|
||||
switch (statement.type) {
|
||||
case 'DirectEvidence':
|
||||
return this.buildDirectRule(statement);
|
||||
return this.buildDirectRule(statement, evidence);
|
||||
case 'PatternMatch':
|
||||
return this.buildPatternMatchRule(statement, evidence);
|
||||
case 'DefeasibleLogic':
|
||||
@@ -282,7 +294,7 @@ export class RuleGenerator {
|
||||
case 'Fusion':
|
||||
return this.buildFusionRule(statement);
|
||||
case 'PredicateCall':
|
||||
return this.buildPredicateRule(statement);
|
||||
return this.buildPredicateRule(statement, evidence);
|
||||
case 'UnaryExpression':
|
||||
return this.buildUnaryRule(statement);
|
||||
case 'BinaryExpression':
|
||||
@@ -291,7 +303,7 @@ export class RuleGenerator {
|
||||
case 'Expression':
|
||||
// Handle expressions that might be predicate calls
|
||||
if (statement.type === 'PredicateCall') {
|
||||
return this.buildPredicateRule(statement);
|
||||
return this.buildPredicateRule(statement, evidence);
|
||||
}
|
||||
return this.buildRuleFromExpressionNode(statement, evidence);
|
||||
default:
|
||||
@@ -459,7 +471,7 @@ export class RuleGenerator {
|
||||
* @param {DirectEvidenceNode} directEvidence - Direct evidence statement
|
||||
* @returns {Object|null} Rule configuration or null
|
||||
*/
|
||||
buildDirectRule(directEvidence) {
|
||||
buildDirectRule(directEvidence, evidence) {
|
||||
if (!directEvidence.predicate) {
|
||||
this.errors.push('Direct evidence must have a predicate');
|
||||
return null;
|
||||
@@ -467,12 +479,31 @@ export class RuleGenerator {
|
||||
|
||||
const predicate = directEvidence.predicate;
|
||||
const relation = predicate.name;
|
||||
|
||||
return {
|
||||
|
||||
const rule = {
|
||||
type: 'direct',
|
||||
relation: relation,
|
||||
reverse: false
|
||||
};
|
||||
|
||||
// Unary predicate calls check the relation as a self-edge on the call's
|
||||
// subject entity (the graph stores unary facts as self-edges). The subject
|
||||
// entity may be the evidence's SUBJECT or its OBJECT parameter — mark the
|
||||
// matching rewrite flag.
|
||||
const evidenceParams = (evidence && evidence.params) || [];
|
||||
const objectVar = evidenceParams[1] && evidenceParams[1].name;
|
||||
const argName = a => a && (a.name !== undefined ? a.name : a.value);
|
||||
const args = predicate.arguments || [];
|
||||
if (objectVar !== undefined) {
|
||||
const hasObjectArg = args.some(a => argName(a) === objectVar);
|
||||
if (args.length === 1 && argName(args[0]) === objectVar) {
|
||||
rule._subjectIsObject = true;
|
||||
} else if (!hasObjectArg) {
|
||||
rule._subjectAsObject = true;
|
||||
}
|
||||
}
|
||||
|
||||
return rule;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -925,9 +956,6 @@ export class RuleGenerator {
|
||||
* @returns {Object|null} Rule configuration or null
|
||||
*/
|
||||
buildDirectRuleFromPredicate(predicate, evidence) {
|
||||
const expanded = this._expandPredicate(predicate.name);
|
||||
if (expanded) return expanded;
|
||||
|
||||
const rule = {
|
||||
type: 'direct',
|
||||
relation: predicate.name,
|
||||
@@ -944,36 +972,164 @@ export class RuleGenerator {
|
||||
return rule;
|
||||
}
|
||||
|
||||
_expandPredicate(predicateName) {
|
||||
const existingConfig = this.generatedRules.get(predicateName) || this.arbiter?.relationConfigs?.get(predicateName);
|
||||
if (!existingConfig) return null;
|
||||
if (!existingConfig.union && !existingConfig.intersection && !existingConfig.exclusion) return null;
|
||||
_expandPredicate() {
|
||||
// Replaced by resolveEvidenceReferences() (the compile-time evidence
|
||||
// composition pass). Predicate references are now emitted as direct rules
|
||||
// and inlined during resolution, which also handles forward references and
|
||||
// preserves the correct _subjectAsObject scoping.
|
||||
}
|
||||
|
||||
const logicalKey = existingConfig.union ? 'union' : existingConfig.intersection ? 'intersection' : 'exclusion';
|
||||
const subRules = Array.isArray(existingConfig[logicalKey]?.rules)
|
||||
? existingConfig[logicalKey].rules
|
||||
: Array.isArray(existingConfig[logicalKey]) ? existingConfig[logicalKey] : [];
|
||||
/**
|
||||
* Evidence composition pass. Every rule that references a DERIVED evidence
|
||||
* (e.g. `WHEN can_read(user, doc)` where can_read is itself an evidence) is
|
||||
* rewritten to inline that evidence's own config. This runs after all
|
||||
* evidence configs are generated, so forward references resolve; cycles are
|
||||
* detected and reported. The engine therefore evaluates a fully-resolved,
|
||||
* acyclic config tree — no runtime sub-query traversal is needed.
|
||||
*/
|
||||
resolveEvidenceReferences() {
|
||||
for (const name of this.evidenceNames) {
|
||||
if (!this.generatedRules.has(name)) continue;
|
||||
const stack = new Set([name]);
|
||||
const resolved = this._resolveRule(this.generatedRules.get(name), stack);
|
||||
this.generatedRules.set(name, resolved);
|
||||
this._annotateDependencies(name, resolved);
|
||||
}
|
||||
}
|
||||
|
||||
if (subRules.length === 0) return null;
|
||||
/**
|
||||
* Recursively rewrite a rule tree, inlining references to derived evidence
|
||||
* configs. `stack` holds the evidence names currently being expanded so a
|
||||
* cyclic reference (A → B → A) is detected and reported.
|
||||
*/
|
||||
_resolveRule(rule, stack) {
|
||||
if (!rule || typeof rule !== 'object') return rule;
|
||||
if (Array.isArray(rule)) return rule.map(r => this._resolveRule(r, stack));
|
||||
|
||||
const expandedRules = subRules.map(r => {
|
||||
if (r && r.type === 'direct') return { type: 'direct', relation: r.relation, reverse: !!r.reverse };
|
||||
if (typeof r === 'string') return { type: 'direct', relation: r, reverse: false };
|
||||
return null;
|
||||
}).filter(Boolean);
|
||||
// Direct rule referencing a derived evidence → inline its resolved config.
|
||||
if (rule.type === 'direct' && rule.relation) {
|
||||
const ref = rule.relation;
|
||||
if (this.evidenceNames.has(ref)) {
|
||||
const referencedConfig = this.generatedRules.get(ref);
|
||||
if (referencedConfig) {
|
||||
if (stack.has(ref)) {
|
||||
this.errors.push(`Cyclic evidence reference involving '${ref}'. Evidence composition must be acyclic.`);
|
||||
return rule;
|
||||
}
|
||||
const refStack = new Set(stack);
|
||||
refStack.add(ref);
|
||||
const resolvedRef = this._resolveRule(referencedConfig, refStack);
|
||||
if (resolvedRef) {
|
||||
const clone = this._deepCloneRule(resolvedRef);
|
||||
if (rule._subjectAsObject) clone._subjectAsObject = true;
|
||||
return clone;
|
||||
}
|
||||
}
|
||||
}
|
||||
return rule;
|
||||
}
|
||||
|
||||
if (expandedRules.length === 0) return null;
|
||||
// Recurse into logical / defeasible / nested containers: rule-lists
|
||||
// (union/intersection/exclusion/never/requires/when/unless .rules) and
|
||||
// single nested rules (always.direct, comparator operands).
|
||||
const out = { ...rule };
|
||||
for (const key of ['union', 'intersection', 'exclusion', 'never', 'always', 'requires', 'when', 'unless', 'direct', 'rule']) {
|
||||
const node = out[key];
|
||||
if (!node || typeof node !== 'object') continue;
|
||||
if (Array.isArray(node)) {
|
||||
out[key] = node.map(r => this._resolveRule(r, stack));
|
||||
continue;
|
||||
}
|
||||
const next = { ...node };
|
||||
if (Array.isArray(next.rules)) {
|
||||
next.rules = next.rules.map(r => this._resolveRule(r, stack));
|
||||
}
|
||||
if (next.union && Array.isArray(next.union.rules)) {
|
||||
next.union = { ...next.union, rules: next.union.rules.map(r => this._resolveRule(r, stack)) };
|
||||
}
|
||||
if (next.intersection && Array.isArray(next.intersection.rules)) {
|
||||
next.intersection = { ...next.intersection, rules: next.intersection.rules.map(r => this._resolveRule(r, stack)) };
|
||||
}
|
||||
if (next.direct && typeof next.direct === 'object') {
|
||||
next.direct = this._resolveRule(next.direct, stack);
|
||||
}
|
||||
if (next.rule && typeof next.rule === 'object') {
|
||||
next.rule = this._resolveRule(next.rule, stack);
|
||||
}
|
||||
out[key] = next;
|
||||
}
|
||||
if (out.type === 'relational_comparator') {
|
||||
if (out.left?.rule) out.left = { ...out.left, rule: this._resolveRule(out.left.rule, stack) };
|
||||
if (out.right?.rule) out.right = { ...out.right, rule: this._resolveRule(out.right.rule, stack) };
|
||||
}
|
||||
// Chain steps may reference a derived evidence; expand those steps
|
||||
// (direct evidence → underlying relation, chain evidence → spliced steps).
|
||||
if (rule.type === 'chain' && Array.isArray(out.steps)) {
|
||||
out.steps = this._expandChainSteps(out.steps, stack);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'logical',
|
||||
[logicalKey]: {
|
||||
rules: expandedRules,
|
||||
aggregator: existingConfig[logicalKey]?.aggregator || 'min'
|
||||
},
|
||||
// Flag to tell the evaluator: this expanded sub-predicate is unary —
|
||||
// use the subject as the object instead of inheriting the parent's object.
|
||||
_subjectAsObject: true
|
||||
};
|
||||
/**
|
||||
* Expand chain steps that reference a derived evidence:
|
||||
* - direct evidence → rename the step to the underlying relation
|
||||
* (member_of(user,*g){ group_read(g,doc) } where group_read = can_view
|
||||
* becomes step 'can_view');
|
||||
* - chain evidence → splice its steps into this chain (flattening)
|
||||
* (a step that is itself a sub-path becomes its steps, preserving the
|
||||
* linear source→…→object traversal);
|
||||
* - logical / defeasible / comparator evidence → only expressible as a
|
||||
* FINAL condition-gated step (the object is known, so the engine can
|
||||
* verify the condition at (intermediate, object) instead of traversing
|
||||
* an edge). Emitted as a `{ rule: <config> }` step the ChainRule
|
||||
* evaluates as a condition hop. Non-final such steps are a compile
|
||||
* error: a condition cannot discover intermediate nodes.
|
||||
*/
|
||||
_expandChainSteps(steps, stack) {
|
||||
const out = [];
|
||||
for (let idx = 0; idx < steps.length; idx++) {
|
||||
const step = steps[idx];
|
||||
const stepName = typeof step === 'string' ? step : step.relation;
|
||||
if (stepName && this.evidenceNames.has(stepName)) {
|
||||
if (stack.has(stepName)) {
|
||||
this.errors.push(`Cyclic evidence reference involving '${stepName}'. Evidence composition must be acyclic.`);
|
||||
out.push(step);
|
||||
continue;
|
||||
}
|
||||
const referencedConfig = this.generatedRules.get(stepName);
|
||||
if (referencedConfig) {
|
||||
const refStack = new Set(stack);
|
||||
refStack.add(stepName);
|
||||
const resolved = this._resolveRule(referencedConfig, refStack);
|
||||
if (resolved.type === 'direct' && resolved.relation && resolved.relation !== stepName) {
|
||||
out.push(typeof step === 'string'
|
||||
? resolved.relation
|
||||
: { ...step, relation: resolved.relation });
|
||||
continue;
|
||||
}
|
||||
if (resolved.type === 'chain' && Array.isArray(resolved.steps)) {
|
||||
out.push(...this._expandChainSteps(resolved.steps, refStack));
|
||||
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
|
||||
// (rule-based reachability) and continues from each discovered node.
|
||||
out.push({ rule: this._deepCloneRule(resolved), conditionStep: true });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(step);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
_deepCloneRule(rule) {
|
||||
try {
|
||||
return structuredClone(rule);
|
||||
} catch {
|
||||
return JSON.parse(JSON.stringify(rule));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1120,27 +1276,29 @@ export class RuleGenerator {
|
||||
return this.buildChallengeRule(expression, null);
|
||||
}
|
||||
|
||||
// Expand composite (logical) predicate references into their direct
|
||||
// leaf components so the optimizer can flatten to a correct direct_list.
|
||||
const expanded = this._expandPredicate(predicateName);
|
||||
if (expanded) return expanded;
|
||||
|
||||
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).
|
||||
// Unary predicate calls check the relation as a self-edge on the call's
|
||||
// subject entity (the graph stores unary facts as self-edges). The subject
|
||||
// entity may be the evidence's SUBJECT or its OBJECT parameter:
|
||||
// banned(user) in can_open(user, doc) -> self-edge on the user
|
||||
// trusted(other) in peer_trusted(user, other) -> self-edge on the other
|
||||
// Mark _subjectAsObject (subject-as-object on the subject entity) or
|
||||
// _subjectIsObject (the subject entity IS the object parameter) so the
|
||||
// engine rewrites the pair accordingly.
|
||||
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 = (expression.args || []).some(a =>
|
||||
a && a.type === 'Variable' && a.name === objectVar);
|
||||
if (!hasObjectArg) {
|
||||
const args = expression.args || [];
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,6 +248,13 @@ BehaviorAnnotation
|
||||
= "BEHAVES" __ "AS" __ behavior:("edge" / "transitive" / "hierarchical" / "symmetrical_graph") {
|
||||
return { type: "BehaviorAnnotation", behavior };
|
||||
}
|
||||
/ "BEHAVES" __ "{" _ behavior:(TTLBehavior) _ "}" {
|
||||
// Fact-level freshness: `fact balance(user, amount) BEHAVES { ttl 1h }`
|
||||
// declares the relation's value-freshness window, which the runtime uses
|
||||
// as the provider-result cache TTL. The behavior is wrapped like the
|
||||
// `BEHAVES AS` form so consumers read `behavior.behaviorType`.
|
||||
return { type: "BehaviorAnnotation", behavior };
|
||||
}
|
||||
|
||||
FactProperty
|
||||
= "transitive" { return "transitive"; }
|
||||
|
||||
+124
-62
@@ -490,39 +490,46 @@ function peg$parse(input, options) {
|
||||
function peg$f29(behavior) {
|
||||
return { type: "BehaviorAnnotation", behavior };
|
||||
}
|
||||
function peg$f30() { return "transitive"; }
|
||||
function peg$f31() { return "symmetrical"; }
|
||||
function peg$f32(value) { return value; }
|
||||
function peg$f33(b) { return b; }
|
||||
function peg$f34(direction, period) {
|
||||
function peg$f30(behavior) {
|
||||
// Fact-level freshness: `fact balance(user, amount) BEHAVES { ttl 1h }`
|
||||
// declares the relation's value-freshness window, which the runtime uses
|
||||
// as the provider-result cache TTL. The behavior is wrapped like the
|
||||
// `BEHAVES AS` form so consumers read `behavior.behaviorType`.
|
||||
return { type: "BehaviorAnnotation", behavior };
|
||||
}
|
||||
function peg$f31() { return "transitive"; }
|
||||
function peg$f32() { return "symmetrical"; }
|
||||
function peg$f33(value) { return value; }
|
||||
function peg$f34(b) { return b; }
|
||||
function peg$f35(direction, period) {
|
||||
return { type: "Behavior", behaviorType: "decay", direction, period };
|
||||
}
|
||||
function peg$f35(mode, confidence) {
|
||||
function peg$f36(mode, confidence) {
|
||||
return { type: "Behavior", behaviorType: "blur", mode, confidence: confidence ? confidence[1] : null };
|
||||
}
|
||||
function peg$f36(duration) {
|
||||
function peg$f37(duration) {
|
||||
return { type: "Behavior", behaviorType: "ttl", duration };
|
||||
}
|
||||
function peg$f37(directive) { return directive; }
|
||||
function peg$f38(head, tail) { return buildLeftAssoc(head, tail); }
|
||||
function peg$f38(directive) { return directive; }
|
||||
function peg$f39(head, tail) { return buildLeftAssoc(head, tail); }
|
||||
function peg$f40(head, typeName) {
|
||||
function peg$f40(head, tail) { return buildLeftAssoc(head, tail); }
|
||||
function peg$f41(head, typeName) {
|
||||
return { type: "BinaryExpression", operator: "is", left: head, right: typeName };
|
||||
}
|
||||
function peg$f41(head, tail) { return buildLeftAssoc(head, tail); }
|
||||
function peg$f42(head, right) {
|
||||
function peg$f42(head, tail) { return buildLeftAssoc(head, tail); }
|
||||
function peg$f43(head, right) {
|
||||
return { type: "BinaryExpression", operator: "within", left: head, right };
|
||||
}
|
||||
function peg$f43(head, tail) { return buildLeftAssoc(head, tail); }
|
||||
function peg$f44(head, tail) { return buildLeftAssoc(head, tail); }
|
||||
function peg$f45(operator, operand) { return { type: "UnaryExpression", operator: "NOT", operand }; }
|
||||
function peg$f46(primary, binding) {
|
||||
function peg$f45(head, tail) { return buildLeftAssoc(head, tail); }
|
||||
function peg$f46(operator, operand) { return { type: "UnaryExpression", operator: "NOT", operand }; }
|
||||
function peg$f47(primary, binding) {
|
||||
if (binding) {
|
||||
return { type: "BindingAccess", expression: primary, binding };
|
||||
}
|
||||
return primary;
|
||||
}
|
||||
function peg$f47(head, tail) {
|
||||
function peg$f48(head, tail) {
|
||||
return tail.reduce((obj, part) => {
|
||||
return {
|
||||
type: "AttributeAccess",
|
||||
@@ -532,31 +539,31 @@ function peg$parse(input, options) {
|
||||
};
|
||||
}, head);
|
||||
}
|
||||
function peg$f48(expr) { return expr; }
|
||||
function peg$f49(name, args) {
|
||||
function peg$f49(expr) { return expr; }
|
||||
function peg$f50(name, args) {
|
||||
return { type: "PredicateCall", name, args: args || [], challenge: true };
|
||||
}
|
||||
function peg$f50(name, args) {
|
||||
function peg$f51(name, args) {
|
||||
return { type: "PredicateCall", name, args: args || [] };
|
||||
}
|
||||
function peg$f51(name) { return { type: "Variable", name }; }
|
||||
function peg$f52(head, tail) {
|
||||
return [head, ...tail.map(t => t[3])];
|
||||
}
|
||||
function peg$f52(name) { return { type: "Variable", name }; }
|
||||
function peg$f53(head, tail) {
|
||||
return [head, ...tail.map(t => t[3])];
|
||||
}
|
||||
function peg$f54(chars) {
|
||||
return { type: "Literal", value: JSON.parse(text()) };
|
||||
function peg$f54(head, tail) {
|
||||
return [head, ...tail.map(t => t[3])];
|
||||
}
|
||||
function peg$f55(chars) {
|
||||
return { type: "Literal", value: JSON.parse(text()) };
|
||||
}
|
||||
function peg$f56(chars) {
|
||||
return { type: "Literal", value: JSON.parse("\"" + chars.map(c => c[0] === '\\' ? c[1] : c[1]).join('') + "\"") };
|
||||
}
|
||||
function peg$f56(value) { return { type: "Literal", value: parseFloat(text()) }; }
|
||||
function peg$f57(value) { return { type: "Literal", value: parseInt(text(), 10) }; }
|
||||
function peg$f58(value) { return { type: "Literal", value: value === "true" }; }
|
||||
function peg$f59(value) { return { type: "Literal", value: text(), unit: text().slice(-1) }; }
|
||||
function peg$f60(name) { return name; }
|
||||
function peg$f57(value) { return { type: "Literal", value: parseFloat(text()) }; }
|
||||
function peg$f58(value) { return { type: "Literal", value: parseInt(text(), 10) }; }
|
||||
function peg$f59(value) { return { type: "Literal", value: value === "true" }; }
|
||||
function peg$f60(value) { return { type: "Literal", value: text(), unit: text().slice(-1) }; }
|
||||
function peg$f61(name) { return name; }
|
||||
let peg$currPos = options.peg$currPos | 0;
|
||||
let peg$savedPos = peg$currPos;
|
||||
const peg$posDetailsCache = [{ line: 1, column: 1 }];
|
||||
@@ -2456,7 +2463,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
|
||||
function peg$parseBehaviorAnnotation() {
|
||||
let s0, s1, s2, s3, s4, s5;
|
||||
let s0, s1, s2, s3, s4, s5, s6, s7;
|
||||
|
||||
s0 = peg$currPos;
|
||||
if (input.substr(peg$currPos, 7) === peg$c28) {
|
||||
@@ -2536,6 +2543,61 @@ function peg$parse(input, options) {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
}
|
||||
if (s0 === peg$FAILED) {
|
||||
s0 = peg$currPos;
|
||||
if (input.substr(peg$currPos, 7) === peg$c28) {
|
||||
s1 = peg$c28;
|
||||
peg$currPos += 7;
|
||||
} else {
|
||||
s1 = peg$FAILED;
|
||||
if (peg$silentFails === 0) { peg$fail(peg$e34); }
|
||||
}
|
||||
if (s1 !== peg$FAILED) {
|
||||
s2 = peg$parse__();
|
||||
if (s2 !== peg$FAILED) {
|
||||
if (input.charCodeAt(peg$currPos) === 123) {
|
||||
s3 = peg$c2;
|
||||
peg$currPos++;
|
||||
} else {
|
||||
s3 = peg$FAILED;
|
||||
if (peg$silentFails === 0) { peg$fail(peg$e3); }
|
||||
}
|
||||
if (s3 !== peg$FAILED) {
|
||||
s4 = peg$parse_();
|
||||
s5 = peg$parseTTLBehavior();
|
||||
if (s5 !== peg$FAILED) {
|
||||
s6 = peg$parse_();
|
||||
if (input.charCodeAt(peg$currPos) === 125) {
|
||||
s7 = peg$c3;
|
||||
peg$currPos++;
|
||||
} else {
|
||||
s7 = peg$FAILED;
|
||||
if (peg$silentFails === 0) { peg$fail(peg$e4); }
|
||||
}
|
||||
if (s7 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f30(s5);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
}
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
}
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
}
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
}
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
return s0;
|
||||
}
|
||||
@@ -2553,7 +2615,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s1 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s1 = peg$f30();
|
||||
s1 = peg$f31();
|
||||
}
|
||||
s0 = s1;
|
||||
if (s0 === peg$FAILED) {
|
||||
@@ -2567,7 +2629,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s1 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s1 = peg$f31();
|
||||
s1 = peg$f32();
|
||||
}
|
||||
s0 = s1;
|
||||
}
|
||||
@@ -2592,7 +2654,7 @@ function peg$parse(input, options) {
|
||||
s3 = peg$parseInteger();
|
||||
if (s3 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f32(s3);
|
||||
s0 = peg$f33(s3);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -2650,7 +2712,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s7 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f33(s5);
|
||||
s0 = peg$f34(s5);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -2762,7 +2824,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s5 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f34(s3, s5);
|
||||
s0 = peg$f35(s3, s5);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -2870,7 +2932,7 @@ function peg$parse(input, options) {
|
||||
s4 = null;
|
||||
}
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f35(s3, s4);
|
||||
s0 = peg$f36(s3, s4);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -2904,7 +2966,7 @@ function peg$parse(input, options) {
|
||||
s3 = peg$parseDuration();
|
||||
if (s3 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f36(s3);
|
||||
s0 = peg$f37(s3);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -2953,7 +3015,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s3 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f37(s3);
|
||||
s0 = peg$f38(s3);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3027,7 +3089,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
}
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f38(s1, s2);
|
||||
s0 = peg$f39(s1, s2);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3093,7 +3155,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
}
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f39(s1, s2);
|
||||
s0 = peg$f40(s1, s2);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3122,7 +3184,7 @@ function peg$parse(input, options) {
|
||||
s5 = peg$parseTypeName();
|
||||
if (s5 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f40(s1, s5);
|
||||
s0 = peg$f41(s1, s5);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3266,7 +3328,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
}
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f41(s1, s2);
|
||||
s0 = peg$f42(s1, s2);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3296,7 +3358,7 @@ function peg$parse(input, options) {
|
||||
s5 = peg$parseDuration();
|
||||
if (s5 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f42(s1, s5);
|
||||
s0 = peg$f43(s1, s5);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3377,7 +3439,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
}
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f43(s1, s2);
|
||||
s0 = peg$f44(s1, s2);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3443,7 +3505,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
}
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f44(s1, s2);
|
||||
s0 = peg$f45(s1, s2);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3478,7 +3540,7 @@ function peg$parse(input, options) {
|
||||
s3 = peg$parseUnary();
|
||||
if (s3 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f45(s1, s3);
|
||||
s0 = peg$f46(s1, s3);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3512,7 +3574,7 @@ function peg$parse(input, options) {
|
||||
s2 = null;
|
||||
}
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f46(s1, s2);
|
||||
s0 = peg$f47(s1, s2);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3583,7 +3645,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s2 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f47(s1, s2);
|
||||
s0 = peg$f48(s1, s2);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3630,7 +3692,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s5 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f48(s3);
|
||||
s0 = peg$f49(s3);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3694,7 +3756,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s8 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f49(s2, s6);
|
||||
s0 = peg$f50(s2, s6);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3744,7 +3806,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s6 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f50(s1, s4);
|
||||
s0 = peg$f51(s1, s4);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3768,7 +3830,7 @@ function peg$parse(input, options) {
|
||||
s1 = peg$parseIdentifier();
|
||||
if (s1 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s1 = peg$f51(s1);
|
||||
s1 = peg$f52(s1);
|
||||
}
|
||||
s0 = s1;
|
||||
|
||||
@@ -3832,7 +3894,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
}
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f52(s1, s2);
|
||||
s0 = peg$f53(s1, s2);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -3898,7 +3960,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
}
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f53(s1, s2);
|
||||
s0 = peg$f54(s1, s2);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -4083,7 +4145,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s3 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f54(s2);
|
||||
s0 = peg$f55(s2);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -4245,7 +4307,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s3 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f55(s2);
|
||||
s0 = peg$f56(s2);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
@@ -4340,7 +4402,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s1 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s1 = peg$f56(s1);
|
||||
s1 = peg$f57(s1);
|
||||
}
|
||||
s0 = s1;
|
||||
peg$silentFails--;
|
||||
@@ -4381,7 +4443,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s1 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s1 = peg$f57(s1);
|
||||
s1 = peg$f58(s1);
|
||||
}
|
||||
s0 = s1;
|
||||
peg$silentFails--;
|
||||
@@ -4416,7 +4478,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s1 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s1 = peg$f58(s1);
|
||||
s1 = peg$f59(s1);
|
||||
}
|
||||
s0 = s1;
|
||||
peg$silentFails--;
|
||||
@@ -4477,7 +4539,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s1 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s1 = peg$f59(s1);
|
||||
s1 = peg$f60(s1);
|
||||
}
|
||||
s0 = s1;
|
||||
peg$silentFails--;
|
||||
@@ -4545,7 +4607,7 @@ function peg$parse(input, options) {
|
||||
}
|
||||
if (s2 !== peg$FAILED) {
|
||||
peg$savedPos = s0;
|
||||
s0 = peg$f60(s2);
|
||||
s0 = peg$f61(s2);
|
||||
} else {
|
||||
peg$currPos = s0;
|
||||
s0 = peg$FAILED;
|
||||
|
||||
+347
-68
@@ -1,6 +1,6 @@
|
||||
import { DSLCompiler } from '../DSLCompiler.js';
|
||||
|
||||
const PRIMITIVE_TYPES = new Set(['string', 'number', 'boolean']);
|
||||
const VALUE_TYPES = new Set(['string', 'number', 'boolean', 'timestamp', 'duration', 'object', 'any']);
|
||||
|
||||
/**
|
||||
* DSLRuntime — higher-order wrapper combining the Evidence DSL with an
|
||||
@@ -12,13 +12,19 @@ const PRIMITIVE_TYPES = new Set(['string', 'number', 'boolean']);
|
||||
* check). A raw Arbiter accepts untyped inserts; this wrapper adds the
|
||||
* DSL-informed layer:
|
||||
*
|
||||
* - addNode / updateNodeData / addRelation / updateRelation validate their
|
||||
* arguments against the compiled schema — known types, known relations,
|
||||
* matching param types, typed field values — before mutating the arbiter.
|
||||
* - check() validates the request, derives the injectable facts the
|
||||
* evidence requires (its partial-graph requirements), retrieves the
|
||||
* missing facts through caller-provided data callbacks, injects them into
|
||||
* a partial graph, then delegates to the arbiter.
|
||||
* - schema introspection: getSchema() exposes the compiled type system
|
||||
* (entity types/fields, facts, evidence, dependencies, providers);
|
||||
* - typed mutations: addNode / updateNodeData / addRelation / updateRelation
|
||||
* validate their arguments against the compiled schema — known types,
|
||||
* known relations, matching param types, typed field values — before
|
||||
* mutating the arbiter; removeNode / removeRelation pass through;
|
||||
* - per-relation data retrieval: registerFact(relation, asyncFn) registers a
|
||||
* provider that retrieves the missing partial-graph edges for a fact; a
|
||||
* bounded retrieval loop runs providers to a fixed point so a provider's
|
||||
* edges can satisfy another required fact;
|
||||
* - DSL-informed check: derives the evidence's injectable facts, retrieves
|
||||
* them via providers, injects them into a partial graph, and delegates to
|
||||
* the arbiter; require() throws on denial for middleware use.
|
||||
*
|
||||
* Trust boundary follows the core: caller-supplied evidence (partial graph /
|
||||
* provider results) is trusted, never policed; only structure is validated.
|
||||
@@ -41,8 +47,21 @@ export class DSLRuntime {
|
||||
this.strictTypes = options.policy?.strictTypes !== false;
|
||||
this.program = null;
|
||||
this.types = new Map(); // typeName -> { fields: Map(field -> {type,isArray}) }
|
||||
this.relations = new Map(); // relation -> { kind: 'fact'|'evidence', params, injectable }
|
||||
this.relations = new Map(); // relation -> { kind: 'fact'|'evidence', params, injectable, ttlMs }
|
||||
this.dependsOn = new Map(); // evidence relation -> Set(fact relations)
|
||||
|
||||
// Provider-result cache: relation|subject|object -> { edges, fetchedAt }.
|
||||
// Provider retrieval is a data-store read (balance lookups, session
|
||||
// checks, etc.) — caching results with a time expiry avoids hammering the
|
||||
// underlying store on every check. The clock is injectable (default wall
|
||||
// clock) and drives cache freshness, mirroring the core's unpinned-clock
|
||||
// contract.
|
||||
this.providerCache = new Map();
|
||||
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;
|
||||
// Per-fact overrides (ms). DSL-declared ttl behaviors are indexed here too.
|
||||
this.factTTLs = new Map(Object.entries(options.factTTLs || {}));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -62,6 +81,43 @@ export class DSLRuntime {
|
||||
return this;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Schema introspection
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A serializable snapshot of the compiled type system: entity types with
|
||||
* typed fields, facts, evidence (with their dependencies), and registered
|
||||
* providers. Callers can use this to render forms, build clients, or audit
|
||||
* a compiled program without reaching into the internal Maps.
|
||||
*/
|
||||
getSchema() {
|
||||
const types = [...this.types.entries()].map(([name, { fields }]) => ({
|
||||
name,
|
||||
fields: [...fields.entries()].map(([fieldName, f]) => ({
|
||||
name: fieldName,
|
||||
type: f.type,
|
||||
isArray: f.isArray
|
||||
}))
|
||||
}));
|
||||
const facts = [...this.relations.entries()]
|
||||
.filter(([, r]) => r.kind === 'fact')
|
||||
.map(([name, r]) => ({ name, params: r.params, injectable: r.injectable }));
|
||||
const evidence = [...this.relations.entries()]
|
||||
.filter(([, r]) => r.kind === 'evidence')
|
||||
.map(([name, r]) => ({
|
||||
name,
|
||||
params: r.params,
|
||||
dependsOn: [...(this.dependsOn.get(name) || [])]
|
||||
}));
|
||||
return { types, facts, evidence, providers: this.registeredFacts() };
|
||||
}
|
||||
|
||||
/** All relation names declared by the program (facts + evidence). */
|
||||
relationNames() {
|
||||
return [...this.relations.keys()];
|
||||
}
|
||||
|
||||
_indexSchema() {
|
||||
this.types.clear();
|
||||
this.relations.clear();
|
||||
@@ -76,10 +132,12 @@ export class DSLRuntime {
|
||||
}
|
||||
|
||||
for (const fact of this.program.facts || []) {
|
||||
const ttlMs = this._ttlFromBehavior(fact.behavior);
|
||||
this.relations.set(fact.name, {
|
||||
kind: 'fact',
|
||||
params: (fact.params || []).map(p => ({ name: p.name, type: p.paramType, isArray: !!p.isArray })),
|
||||
injectable: !!fact.injectable
|
||||
injectable: !!fact.injectable,
|
||||
ttlMs
|
||||
});
|
||||
}
|
||||
|
||||
@@ -103,7 +161,11 @@ export class DSLRuntime {
|
||||
if (rule.computedRelation) deps.add(rule.computedRelation);
|
||||
}
|
||||
if (rule.type === 'chain' && Array.isArray(rule.steps)) {
|
||||
for (const s of rule.steps) deps.add(typeof s === 'string' ? s : s.relation);
|
||||
for (const s of rule.steps) {
|
||||
if (typeof s === 'string') deps.add(s);
|
||||
else if (s && s.relation) deps.add(s.relation);
|
||||
else if (s && s.rule) collect(s.rule);
|
||||
}
|
||||
}
|
||||
if (rule.type === 'parent' && rule.parentRelation) deps.add(rule.parentRelation);
|
||||
if (rule.type === 'multi_hop' && rule.relation) deps.add(rule.relation);
|
||||
@@ -132,12 +194,149 @@ export class DSLRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Provider registration (per-relation data retrieval)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Register (or replace) an async provider for a relation name. When a check
|
||||
* needs that relation's facts and they are not in the graph, the provider is
|
||||
* invoked to retrieve the missing partial-graph edges.
|
||||
*
|
||||
* @param {string} relation - fact relation name
|
||||
* @param {Function} provider - async (subject, object, ctx) => edges
|
||||
*/
|
||||
registerFact(relation, provider) {
|
||||
if (typeof provider !== 'function') {
|
||||
throw new Error(`DSLRuntime: provider for '${relation}' must be a function`);
|
||||
}
|
||||
this.factProviders[relation] = provider;
|
||||
// A new provider supersedes any cached retrieval for this fact.
|
||||
this.invalidateProviderCache(relation);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Remove a registered provider. */
|
||||
unregisterFact(relation) {
|
||||
delete this.factProviders[relation];
|
||||
this.invalidateProviderCache(relation);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Relation names that currently have a registered provider. */
|
||||
registeredFacts() {
|
||||
return Object.keys(this.factProviders);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Provider-result caching
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Set a per-fact provider-result TTL (ms). Overrides the policy default and
|
||||
* the DSL-declared ttl behavior for that fact.
|
||||
*/
|
||||
setFactTTL(relation, ms) {
|
||||
this.factTTLs.set(relation, ms);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** The effective provider-result TTL (ms) for a fact: DSL > per-fact > policy default. */
|
||||
_ttlFor(relation) {
|
||||
if (this.factTTLs.has(relation)) return this.factTTLs.get(relation);
|
||||
const meta = this.relations.get(relation);
|
||||
if (meta && meta.ttlMs != null) return meta.ttlMs;
|
||||
return this.defaultProviderCacheTTL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate cached provider results — all, or for a single relation.
|
||||
* Callers use this when the underlying data store changes out-of-band.
|
||||
*/
|
||||
invalidateProviderCache(relation) {
|
||||
if (relation === undefined) {
|
||||
this.providerCache.clear();
|
||||
return this;
|
||||
}
|
||||
const prefix = `${relation}\u0000`;
|
||||
for (const key of [...this.providerCache.keys()]) {
|
||||
if (key.startsWith(prefix)) this.providerCache.delete(key);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
_providerCacheKey(relation, subject, object) {
|
||||
return `${relation}\u0000${subject}\u0000${object}`;
|
||||
}
|
||||
|
||||
_providerCacheGet(relation, subject, object) {
|
||||
const ttl = this._ttlFor(relation);
|
||||
if (ttl <= 0) return null;
|
||||
const entry = this.providerCache.get(this._providerCacheKey(relation, subject, object));
|
||||
if (!entry) return null;
|
||||
if (this.clock() - entry.fetchedAt >= ttl) {
|
||||
this.providerCache.delete(this._providerCacheKey(relation, subject, object));
|
||||
return null;
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
_providerCacheSet(relation, subject, object, edges) {
|
||||
const ttl = this._ttlFor(relation);
|
||||
if (ttl <= 0) return;
|
||||
this.providerCache.set(this._providerCacheKey(relation, subject, object), {
|
||||
edges,
|
||||
fetchedAt: this.clock()
|
||||
});
|
||||
}
|
||||
|
||||
/** Convert a DSL `BEHAVES { ttl <duration> }` behavior (or `BEHAVES AS`) into ms. */
|
||||
_ttlFromBehavior(behavior) {
|
||||
if (!behavior || typeof behavior !== 'object') return null;
|
||||
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];
|
||||
if (!Number.isNaN(n) && mult) return n * mult;
|
||||
}
|
||||
return 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.
|
||||
*/
|
||||
_normalizeProviderEdges(result, factMeta, 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 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 } : {})
|
||||
};
|
||||
out.push(normalized);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Schema validation helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
_isPrimitive(typeName) {
|
||||
return PRIMITIVE_TYPES.has(typeName);
|
||||
_isValueType(typeName) {
|
||||
return VALUE_TYPES.has(typeName);
|
||||
}
|
||||
|
||||
_nodeType(key) {
|
||||
@@ -154,7 +353,7 @@ export class DSLRuntime {
|
||||
}
|
||||
|
||||
_checkNodeType(key, expectedType, position) {
|
||||
if (this._isPrimitive(expectedType)) return; // value positions are validated separately
|
||||
if (this._isValueType(expectedType)) return; // value positions are validated separately
|
||||
const actual = this._nodeType(key);
|
||||
if (actual === null) {
|
||||
this._checkNodeExists(key, position);
|
||||
@@ -180,7 +379,9 @@ export class DSLRuntime {
|
||||
const ok = type === 'string' ? typeof value === 'string'
|
||||
: type === 'number' ? typeof value === 'number'
|
||||
: type === 'boolean' ? typeof value === 'boolean'
|
||||
: true; // entity-typed fields accept any key
|
||||
: (type === 'timestamp' || type === 'duration')
|
||||
? (typeof value === 'number' || typeof value === 'string')
|
||||
: true; // object / any / entity-typed fields accept any value
|
||||
if (!ok) {
|
||||
throw new Error(`DSLRuntime: field '${path}' must be ${type}, got ${typeof value}`);
|
||||
}
|
||||
@@ -203,6 +404,8 @@ export class DSLRuntime {
|
||||
} else if (this.strictTypes) {
|
||||
throw new Error(`DSLRuntime: unknown type '${typeName}'`);
|
||||
}
|
||||
// A graph mutation can make previously-retrieved facts stale.
|
||||
this.invalidateProviderCache();
|
||||
return this.arbiter.addNode(key, typeName, data);
|
||||
}
|
||||
|
||||
@@ -217,9 +420,19 @@ export class DSLRuntime {
|
||||
if (data[name] !== undefined) this._checkFieldValue(field, data[name], `${typeName}.${name}`);
|
||||
}
|
||||
}
|
||||
this.invalidateProviderCache();
|
||||
return this.arbiter.updateNodeData(key, data);
|
||||
}
|
||||
|
||||
/** Remove a node (passthrough to the arbiter's node manager). */
|
||||
removeNode(key) {
|
||||
this.invalidateProviderCache();
|
||||
if (this.arbiter.nodeManager && typeof this.arbiter.nodeManager.removeNode === 'function') {
|
||||
return this.arbiter.nodeManager.removeNode(key);
|
||||
}
|
||||
return this.arbiter.removeNode?.(key);
|
||||
}
|
||||
|
||||
_relationOrThrow(relation) {
|
||||
const meta = this.relations.get(relation);
|
||||
if (!meta) {
|
||||
@@ -239,6 +452,7 @@ export class DSLRuntime {
|
||||
if (meta) {
|
||||
this._validateRelationEndpoints(relation, meta, src, dst, attrs);
|
||||
}
|
||||
this.invalidateProviderCache();
|
||||
return this.arbiter.addRelation(src, relation, dst, attrs);
|
||||
}
|
||||
|
||||
@@ -250,10 +464,17 @@ export class DSLRuntime {
|
||||
if (meta) {
|
||||
this._validateRelationEndpoints(relation, meta, src, dst, attrs);
|
||||
}
|
||||
this.invalidateProviderCache();
|
||||
this.arbiter.removeRelation(src, relation, dst);
|
||||
return this.arbiter.addRelation(src, relation, dst, attrs);
|
||||
}
|
||||
|
||||
/** Remove a relation edge (passthrough to the arbiter). */
|
||||
removeRelation(src, relation, dst) {
|
||||
this.invalidateProviderCache();
|
||||
return this.arbiter.removeRelation(src, relation, dst);
|
||||
}
|
||||
|
||||
_validateRelationEndpoints(relation, meta, src, dst, attrs) {
|
||||
const params = meta.params;
|
||||
if (params.length === 0) {
|
||||
@@ -261,14 +482,14 @@ export class DSLRuntime {
|
||||
}
|
||||
// First param is always the subject (entity).
|
||||
const subjectType = params[0].type;
|
||||
if (this._isPrimitive(subjectType)) {
|
||||
if (this._isValueType(subjectType)) {
|
||||
throw new Error(`DSLRuntime: relation '${relation}' subject param must be an entity type, got '${subjectType}'`);
|
||||
}
|
||||
this._checkNodeType(src, subjectType, 'subject');
|
||||
|
||||
if (params.length >= 2) {
|
||||
const secondType = params[1].type;
|
||||
if (this._isPrimitive(secondType)) {
|
||||
if (this._isValueType(secondType)) {
|
||||
// Value-carrying fact (e.g. session(user, token: string)): the value
|
||||
// lives on the edge's `value` field; the graph edge is a self-edge on
|
||||
// the subject so the value is discoverable by value extraction.
|
||||
@@ -309,6 +530,13 @@ export class DSLRuntime {
|
||||
* evidence's injectable facts, inject them into a partial graph, and delegate
|
||||
* to the arbiter.
|
||||
*
|
||||
* Providers run in a bounded fixed-point loop: each round invokes the
|
||||
* provider for every required fact whose edges are not yet in the partial
|
||||
* graph. Because a provider may return edges for relations other than its
|
||||
* own name, an edge injected in one round can satisfy another required fact
|
||||
* (or unblock another provider) in a later round. The loop stops when a
|
||||
* round injects no new relation or the round budget is exhausted.
|
||||
*
|
||||
* @param {string} user - subject key
|
||||
* @param {string} relation - evidence (or fact) relation name
|
||||
* @param {string} object - object key
|
||||
@@ -316,71 +544,107 @@ export class DSLRuntime {
|
||||
* @param {object} options.partialGraph - caller-supplied partial graph edges
|
||||
* ({ relations: [{ src, relation, dst, possibility, value }], nodes, challenges })
|
||||
* @param {object} options.factProviders - per-call provider overrides
|
||||
* (merged over registered providers)
|
||||
* @param {number} options.maxProviderRounds - fixed-point loop budget (default 3)
|
||||
* @returns {object} core check result extended with { requiredFacts, providedFacts, missingFacts }
|
||||
*/
|
||||
async check(user, relation, object, options = {}) {
|
||||
const meta = this.relations.get(relation);
|
||||
if (!meta) {
|
||||
if (this.strictTypes) throw new Error(`DSLRuntime: unknown relation '${relation}'`);
|
||||
} else if (meta.kind === 'evidence') {
|
||||
if (meta.params.length === 2) {
|
||||
this._checkNodeType(user, meta.params[0].type, 'subject');
|
||||
this._checkNodeType(object, meta.params[1].type, 'object');
|
||||
}
|
||||
} else if (meta.params.length === 2) {
|
||||
this._checkNodeType(user, meta.params[0].type, 'subject');
|
||||
this._checkNodeType(object, meta.params[1].type, 'object');
|
||||
} else if (meta.params.length === 1) {
|
||||
this._checkNodeType(user, meta.params[0].type, 'subject');
|
||||
}
|
||||
|
||||
const required = this.requiredFacts(relation);
|
||||
const providers = options.factProviders || this.factProviders;
|
||||
const injectedRelations = [];
|
||||
const missingFacts = [];
|
||||
// Retrieval set: for an evidence, the injectable facts it depends on; for
|
||||
// a direct FACT check, the fact itself is the retrieval target (its
|
||||
// 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);
|
||||
const requiredList = [...required];
|
||||
const providers = { ...this.factProviders, ...(options.factProviders || {}) };
|
||||
const maxRounds = options.maxProviderRounds ?? 3;
|
||||
const partialRelations = [];
|
||||
const injectedRelations = []; // { relation, edges, round }
|
||||
const missingFacts = [];
|
||||
const satisfied = new Set(); // facts whose edges are in the partial graph
|
||||
|
||||
if (options.partialGraph && Array.isArray(options.partialGraph.relations)) {
|
||||
partialRelations.push(...options.partialGraph.relations);
|
||||
for (const rel of options.partialGraph.relations) {
|
||||
partialRelations.push(rel);
|
||||
if (rel && rel.relation) satisfied.add(rel.relation);
|
||||
}
|
||||
}
|
||||
|
||||
for (const fact of required) {
|
||||
const factMeta = this.relations.get(fact);
|
||||
const provider = providers[fact];
|
||||
let result = null;
|
||||
let error = null;
|
||||
if (typeof provider === 'function') {
|
||||
try {
|
||||
result = await provider(user, object, { relation: fact, params: factMeta.params, runtime: this, options });
|
||||
} catch (err) {
|
||||
error = err;
|
||||
// Fixed-point provider retrieval loop.
|
||||
for (let round = 1; round <= maxRounds; round++) {
|
||||
let newRelationsThisRound = 0;
|
||||
for (const fact of requiredList) {
|
||||
if (satisfied.has(fact)) continue;
|
||||
const factMeta = this.relations.get(fact);
|
||||
const provider = providers[fact];
|
||||
|
||||
// Provider-result cache: reuse fresh edges without re-invoking the
|
||||
// data store. A cached entry stores the NORMALIZED edges. Per-check
|
||||
// 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.
|
||||
const isPerCheckOverride = !!(options.factProviders && fact in options.factProviders);
|
||||
const cacheHit = isPerCheckOverride ? null : this._providerCacheGet(fact, user, object);
|
||||
let edges = null;
|
||||
let fromCache = false;
|
||||
if (cacheHit) {
|
||||
edges = cacheHit.edges;
|
||||
fromCache = true;
|
||||
} else if (typeof provider === 'function') {
|
||||
let result = null;
|
||||
let error = null;
|
||||
try {
|
||||
result = await provider(user, object, {
|
||||
relation: fact,
|
||||
params: factMeta.params,
|
||||
runtime: this,
|
||||
options,
|
||||
round,
|
||||
alreadyInjected: [...satisfied]
|
||||
});
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
if (error) {
|
||||
missingFacts.push({ relation: fact, reason: error.message });
|
||||
satisfied.add(fact);
|
||||
continue;
|
||||
}
|
||||
if (result === false || result === null || result === undefined) {
|
||||
missingFacts.push({ relation: fact, reason: 'not_provided' });
|
||||
satisfied.add(fact);
|
||||
continue;
|
||||
}
|
||||
edges = this._normalizeProviderEdges(result, factMeta, user, object);
|
||||
if (!isPerCheckOverride) this._providerCacheSet(fact, user, object, edges);
|
||||
} else {
|
||||
missingFacts.push({ relation: fact, reason: 'no_provider' });
|
||||
satisfied.add(fact);
|
||||
continue;
|
||||
}
|
||||
|
||||
// A provider may return edges for relations other than its own; the
|
||||
// injected relation names satisfy those facts too (fixed point).
|
||||
for (const normalized of edges) {
|
||||
const injectedRelation = normalized.relation ?? fact;
|
||||
partialRelations.push({ relation: injectedRelation, ...normalized });
|
||||
satisfied.add(injectedRelation);
|
||||
}
|
||||
injectedRelations.push({ relation: fact, edges: edges.length, round, cacheHit: fromCache });
|
||||
newRelationsThisRound += edges.length;
|
||||
satisfied.add(fact);
|
||||
}
|
||||
if (error) {
|
||||
missingFacts.push({ relation: fact, reason: error.message });
|
||||
continue;
|
||||
}
|
||||
if (result === false || result === null || result === undefined) {
|
||||
missingFacts.push({ relation: fact, reason: 'not_provided' });
|
||||
continue;
|
||||
}
|
||||
const edges = Array.isArray(result) ? result : [result];
|
||||
// Resolve the edge destination the same way the DSL declares the fact:
|
||||
// - unary fact (1 param) -> self-edge on the subject
|
||||
// - value fact (2nd param value) -> self-edge on the subject carrying the value
|
||||
// - binary entity fact -> subject → object
|
||||
const secondParamType = factMeta.params[1] && factMeta.params[1].type;
|
||||
const defaultDst = factMeta.params.length >= 2 && this._isPrimitive(secondParamType)
|
||||
? user
|
||||
: (factMeta.params.length >= 2 ? object : user);
|
||||
for (const edge of edges) {
|
||||
const normalized = typeof edge === 'boolean' || typeof edge === 'number'
|
||||
? { src: user, dst: defaultDst, possibility: edge === true ? 1 : edge }
|
||||
: {
|
||||
src: edge.src ?? user,
|
||||
dst: edge.dst ?? defaultDst,
|
||||
possibility: edge.possibility ?? 1,
|
||||
...(edge.value !== undefined ? { value: edge.value } : {}),
|
||||
...(edge.reliability !== undefined ? { reliability: edge.reliability } : {})
|
||||
};
|
||||
partialRelations.push({ relation: fact, ...normalized });
|
||||
}
|
||||
injectedRelations.push({ relation: fact, edges: edges.length });
|
||||
if (newRelationsThisRound === 0) break;
|
||||
}
|
||||
|
||||
const checkOptions = { ...options };
|
||||
@@ -395,9 +659,24 @@ export class DSLRuntime {
|
||||
|
||||
return {
|
||||
...result,
|
||||
requiredFacts: required,
|
||||
requiredFacts: requiredList,
|
||||
providedFacts: injectedRelations.map(r => r.relation),
|
||||
missingFacts
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check and throw on denial — convenience for middleware / guards.
|
||||
* @returns {object} the check result on success.
|
||||
* @throws {Error} with `.result` attached when the decision denies.
|
||||
*/
|
||||
async require(user, relation, object, options = {}) {
|
||||
const result = await this.check(user, relation, object, options);
|
||||
if (result.possibility <= 0) {
|
||||
const error = new Error(`DSLRuntime: authorization denied for '${relation}' (${result.reason || 'denied'})`);
|
||||
error.result = result;
|
||||
throw error;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ export function validateDslText(dslText, options = {}) {
|
||||
validateSources(program, tables, errors, warnings, dslText);
|
||||
validateMeasures(program, tables, errors, warnings, dslText);
|
||||
validateEvidence(program, tables, errors, warnings, dslText);
|
||||
validateCrossKindRelationNames(program, errors, warnings, dslText);
|
||||
|
||||
return {
|
||||
success: errors.length === 0,
|
||||
@@ -335,6 +336,37 @@ function validateEvidence(program, tables, errors, warnings, source) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Relation names must be unique across facts, sources, evidence, and measures.
|
||||
* A fact and an evidence sharing a name would silently overwrite each other's
|
||||
* relation config during generation (and read as a false cyclic reference).
|
||||
*/
|
||||
function validateCrossKindRelationNames(program, errors, warnings, source) {
|
||||
const seen = new Map();
|
||||
const kinds = [
|
||||
['fact', program.facts],
|
||||
['source', program.sources],
|
||||
['evidence', program.evidence],
|
||||
['measure', program.measures]
|
||||
];
|
||||
for (const [kind, items] of kinds) {
|
||||
for (const item of items || []) {
|
||||
const prev = seen.get(item.name);
|
||||
if (prev) {
|
||||
errors.push(createError({
|
||||
message: `Name '${item.name}' is already used by a ${prev} declaration.`,
|
||||
rule: 'Relation names must be unique across facts, sources, evidence, and measures.',
|
||||
fix: `Rename the ${kind} or the ${prev} to a unique name.`,
|
||||
location: findLocation(source, `${kind} ${item.name}`),
|
||||
context: formatContext(source, findLocation(source, item.name))
|
||||
}));
|
||||
} else {
|
||||
seen.set(item.name, kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function validateEvidenceBody(body, scope, tables, errors, warnings, source, parent) {
|
||||
for (const stmt of body.statements || []) {
|
||||
switch (stmt.type) {
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* tests/ChainConditionStep.test.js — a chain whose FINAL (object-side) hop
|
||||
* references a defeasible/logical evidence. The compiler lowers it to a
|
||||
* condition step: `{ rule: <config>, conditionStep: true }`, which the engine
|
||||
* verifies at (intermediate, object) rather than traversing an edge.
|
||||
*
|
||||
* Only the final step may be a condition (the object is known); an
|
||||
* intermediate condition cannot discover nodes and is a compile 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 DEFS = `
|
||||
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)
|
||||
fact can_edit(group: Group, doc: Doc)
|
||||
`;
|
||||
|
||||
function compile(dsl, name = 'chain-cond') {
|
||||
const arb = new Arbiter();
|
||||
const compiler = new DSLCompiler(arb);
|
||||
const result = compiler.compile(dsl, name);
|
||||
return { arb, result };
|
||||
}
|
||||
|
||||
describe('Chain condition step (logical evidence as final hop)', () => {
|
||||
it('lowers a defeasible final step to a condition step and grants', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence gated(group: Group, doc: Doc) { WHEN can_view(group, doc) UNLESS banned(group) }
|
||||
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
const steps = arb.relationConfigs.get('can_via').steps;
|
||||
assert.equal(steps[0], 'member_of');
|
||||
assert.equal(steps[1].conditionStep, true);
|
||||
assert.equal(steps[1].rule.type, 'logical');
|
||||
// transitive dependency collection through the condition step
|
||||
assert.deepEqual(arb.relationConfigs.get('can_via').dependsOn, ['member_of', 'can_view', 'banned']);
|
||||
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
|
||||
arb.addRelation('g:1', 'can_view', 'doc:9', { possibility: 0.7 });
|
||||
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.7);
|
||||
|
||||
// banning the intermediate defeats the condition hop
|
||||
arb.addRelation('g:1', 'banned', 'g:1', { possibility: 1.0 });
|
||||
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0);
|
||||
});
|
||||
|
||||
it('supports ALWAYS/NEVER evidence as a condition step', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence gated(group: Group, doc: Doc) { ALWAYS can_edit(group, doc) }
|
||||
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
const steps = arb.relationConfigs.get('can_via').steps;
|
||||
assert.equal(steps[1].conditionStep, true);
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
|
||||
arb.addRelation('g:1', 'can_edit', 'doc:9', { possibility: 0.6 });
|
||||
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.6);
|
||||
arb.removeRelation('g:1', 'can_edit', 'doc:9');
|
||||
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0);
|
||||
});
|
||||
|
||||
it('keeps the condition evidence checkable in its own right', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence gated(group: Group, doc: Doc) { WHEN can_view(group, doc) UNLESS banned(group) }
|
||||
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
arb.addNode('g:1', 'Group'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('g:1', 'can_view', 'doc:9', { possibility: 0.8 });
|
||||
assert.equal(arb.check('g:1', 'gated', 'doc:9').possibility, 0.8);
|
||||
});
|
||||
|
||||
it('parallel intermediates aggregate through the condition step', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence gated(group: Group, doc: Doc) { can_view(group, doc) }
|
||||
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('g2:2', 'Group'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 0.5 });
|
||||
arb.addRelation('g:1', 'can_view', 'doc:9', { possibility: 0.7 });
|
||||
arb.addRelation('u:1', 'member_of', 'g2:2', { possibility: 1.0 });
|
||||
arb.addRelation('g2:2', 'can_view', 'doc:9', { possibility: 0.8 });
|
||||
// max over paths: min(0.5,0.7)=0.5, min(1.0,0.8)=0.8 -> 0.8
|
||||
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.8);
|
||||
});
|
||||
|
||||
it('expands an INTERMEDIATE condition step via rule-based reachability', () => {
|
||||
const { arb, result } = compile(`
|
||||
definition Employee { id: string }
|
||||
definition Doc { id: string }
|
||||
fact peer(user: Employee, other: Employee)
|
||||
fact trusted(other: Employee)
|
||||
fact can_read(user: Employee, doc: Doc)
|
||||
evidence peer_trusted(user: Employee, other: Employee) { WHEN peer(user, other) UNLESS trusted(other) }
|
||||
evidence can_access(user: Employee, doc: Doc) { peer_trusted(user, *p) { can_read(p, doc) } }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
const steps = arb.relationConfigs.get('can_access').steps;
|
||||
assert.equal(steps[0].conditionStep, true);
|
||||
assert.equal(steps[0].rule.type, 'logical');
|
||||
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('p:1', 'Employee'); arb.addNode('p:2', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'peer', 'p:1', { possibility: 1.0 });
|
||||
arb.addRelation('u:1', 'peer', 'p:2', { possibility: 1.0 });
|
||||
arb.addRelation('p:1', 'trusted', 'p:1', { possibility: 1.0 }); // p:1 filtered
|
||||
arb.addRelation('p:1', 'can_read', 'doc:9', { possibility: 0.9 });
|
||||
arb.addRelation('p:2', 'can_read', 'doc:9', { possibility: 0.7 });
|
||||
// only untrusted peer p:2 survives the intermediate condition -> 0.7
|
||||
assert.equal(arb.check('u:1', 'can_access', 'doc:9').possibility, 0.7);
|
||||
// trusting p:2 too removes all intermediates -> 0
|
||||
arb.addRelation('p:2', 'trusted', 'p:2', { possibility: 1.0 });
|
||||
assert.equal(arb.check('u:1', 'can_access', 'doc:9').possibility, 0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* tests/ChainStepComposition.test.js — evidence composition inside CHAIN
|
||||
* steps. A chain step that references a derived evidence is expanded at
|
||||
* compile time:
|
||||
* - a DIRECT evidence step → renamed to its underlying relation
|
||||
* (member_of(user,*g){ group_read(g,doc) } where group_read = can_view
|
||||
* becomes step 'can_view');
|
||||
* - a CHAIN evidence step → its steps are spliced into the parent chain
|
||||
* (a sub-path flattens into the linear source→…→object traversal);
|
||||
* - a DEFEASIBLE / LOGICAL / COMPARATOR evidence step is not an edge
|
||||
* traversal and is rejected at compile time;
|
||||
* - cycles and self-references through chain steps are compile errors.
|
||||
*/
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Arbiter } from '@arbiter/core';
|
||||
import { DSLCompiler } from '../src/DSLCompiler.js';
|
||||
|
||||
const DEFS = `
|
||||
definition Employee { id: string }
|
||||
definition Group { id: string }
|
||||
definition Doc { id: string }
|
||||
fact member_of(user: Employee, group: Group)
|
||||
fact group_has(group: Group, sub: Group)
|
||||
fact can_view(group: Group, doc: Doc)
|
||||
fact can_access(group: Group, doc: Doc)
|
||||
fact banned(group: Group)
|
||||
`;
|
||||
|
||||
function compile(dsl, name = 'chain-compose') {
|
||||
const arb = new Arbiter();
|
||||
const compiler = new DSLCompiler(arb);
|
||||
const result = compiler.compile(dsl, name);
|
||||
return { arb, result };
|
||||
}
|
||||
|
||||
describe('Chain step composition', () => {
|
||||
it('renames a direct-evidence chain step to its underlying relation', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence group_read(group: Group, doc: Doc) { can_view(group, doc) }
|
||||
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { group_read(g, doc) } }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
// step 'group_read' → 'can_view'
|
||||
assert.deepEqual(arb.relationConfigs.get('can_via').steps, ['member_of', 'can_view']);
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
|
||||
arb.addRelation('g:1', 'can_view', 'doc:9', { possibility: 0.7 });
|
||||
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.7);
|
||||
});
|
||||
|
||||
it('splices a chain-evidence step into the parent chain', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence group_enter(group: Group, doc: Doc) { group_has(group, *s) { can_access(s, doc) } }
|
||||
evidence can_deep(user: Employee, doc: Doc) { member_of(user, *g) { group_enter(g, doc) } }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
// step 'group_enter' → its steps [group_has, can_access]
|
||||
assert.deepEqual(arb.relationConfigs.get('can_deep').steps, ['member_of', 'group_has', 'can_access']);
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('g2:2', 'Group'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
|
||||
arb.addRelation('g:1', 'group_has', 'g2:2', { possibility: 0.9 });
|
||||
arb.addRelation('g2:2', 'can_access', 'doc:9', { possibility: 0.8 });
|
||||
assert.equal(arb.check('u:1', 'can_deep', 'doc:9').possibility, 0.8);
|
||||
});
|
||||
|
||||
it('expands a chain step whose direct evidence is itself composed', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence group_view(group: Group, doc: Doc) { can_view(group, doc) }
|
||||
evidence group_read(group: Group, doc: Doc) { group_view(group, doc) }
|
||||
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { group_read(g, doc) } }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
assert.deepEqual(arb.relationConfigs.get('can_via').steps, ['member_of', 'can_view']);
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
|
||||
arb.addRelation('g:1', 'can_view', 'doc:9', { possibility: 0.6 });
|
||||
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.6);
|
||||
});
|
||||
|
||||
it('lowers a logical evidence FINAL step to a condition step', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence gated(group: Group, doc: Doc) { WHEN can_view(group, doc) UNLESS banned(group) }
|
||||
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
// final-step logical evidence → condition step (verified at the object)
|
||||
const steps = arb.relationConfigs.get('can_via').steps;
|
||||
assert.equal(steps[0], 'member_of');
|
||||
assert.equal(steps[1].conditionStep, true);
|
||||
assert.equal(steps[1].rule.type, 'logical');
|
||||
});
|
||||
|
||||
it('rejects a mutual cycle through chain steps', () => {
|
||||
const { result } = compile(`
|
||||
${DEFS}
|
||||
evidence cyc_a(group: Group, doc: Doc) { group_has(group, *g) { cyc_b(g, doc) } }
|
||||
evidence cyc_b(group: Group, doc: Doc) { cyc_a(group, doc) }
|
||||
`);
|
||||
assert.equal(result.success, false);
|
||||
assert.ok(result.errors.some(e => /[Cc]yclic/.test(e)), JSON.stringify(result.errors));
|
||||
});
|
||||
|
||||
it('rejects a self-reference through its own chain step', () => {
|
||||
const { result } = compile(`
|
||||
${DEFS}
|
||||
evidence cyc_c(group: Group, doc: Doc) { group_has(group, *g) { cyc_c(g, doc) } }
|
||||
`);
|
||||
assert.equal(result.success, false);
|
||||
assert.ok(result.errors.some(e => /[Cc]yclic/.test(e)), JSON.stringify(result.errors));
|
||||
});
|
||||
|
||||
it('re-derives transitive dependencies through expanded chain steps', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence group_read(group: Group, doc: Doc) { can_view(group, doc) }
|
||||
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { group_read(g, doc) } }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
// dependsOn reflects the expanded step, not the evidence reference
|
||||
assert.deepEqual(arb.relationConfigs.get('can_via').dependsOn, ['member_of', 'can_view']);
|
||||
});
|
||||
});
|
||||
@@ -161,4 +161,48 @@ describe('DSLRuntime', () => {
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
await assert.rejects(() => rt.check('u:1', 'does_not_exist', 'doc:9'), /unknown relation/);
|
||||
});
|
||||
|
||||
it('derives transitive required facts through evidence composition', async () => {
|
||||
const dsl = `
|
||||
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) }
|
||||
evidence can_open(user: Employee, doc: Doc) { WHEN can_read(user, doc) UNLESS banned(user) }
|
||||
`;
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-comp');
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
// can_open composes can_read, so its requirements reach through to owns.
|
||||
assert.deepEqual(rt.requiredFacts('can_open'), ['owns', 'banned']);
|
||||
const granted = await rt.check('u:1', 'can_open', 'doc:9', {
|
||||
factProviders: { owns: async () => 0.9, banned: async () => 0 }
|
||||
});
|
||||
assert.equal(granted.possibility, 0.9);
|
||||
assert.equal(granted.reason, 'allow_rule_matched');
|
||||
assert.deepEqual(granted.providedFacts, ['owns', 'banned']);
|
||||
const denied = await rt.check('u:1', 'can_open', 'doc:9', {
|
||||
factProviders: { owns: async () => 0.9, banned: async () => 1 }
|
||||
});
|
||||
assert.equal(denied.possibility, 0);
|
||||
assert.equal(denied.reason, 'defeated_by_unless');
|
||||
});
|
||||
|
||||
it('derives transitive required facts through a condition-step chain', () => {
|
||||
const dsl = `
|
||||
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)
|
||||
evidence gated(group: Group, doc: Doc) { WHEN can_view(group, doc) UNLESS banned(group) }
|
||||
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
|
||||
`;
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-cond');
|
||||
// The condition step's facts (can_view, banned) reach through to the
|
||||
// evidence's requirements, alongside the edge-traversal fact.
|
||||
assert.deepEqual(rt.requiredFacts('can_via'), ['member_of', 'can_view', 'banned']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* tests/DSLRuntimeCache.test.js — provider-result caching with time expiry.
|
||||
*
|
||||
* Registered providers retrieve missing facts from a data store; caching the
|
||||
* retrieval avoids hammering the store on repeated checks. TTL resolution:
|
||||
* DSL-declared `BEHAVES { ttl <duration> }` on a fact > per-fact setFactTTL >
|
||||
* policy default (30s). Per-check factProviders are cache-transparent (one-off
|
||||
* observations: no cache read, no cache write). Registering a provider or
|
||||
* mutating the graph invalidates the cache.
|
||||
*/
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Arbiter } from '@arbiter/core';
|
||||
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
|
||||
|
||||
const BASE_DSL = `
|
||||
definition Employee { id: string }
|
||||
definition Doc { id: string }
|
||||
fact *owns(user: Employee, doc: Doc)
|
||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
`;
|
||||
|
||||
function makeRuntime(options = {}) {
|
||||
let t = 0;
|
||||
const clock = () => t;
|
||||
const rt = new DSLRuntime(new Arbiter(), { clock, ...options }).compile(BASE_DSL, 'rt-cache');
|
||||
rt._test_advance = (ms) => { t += ms; };
|
||||
return rt;
|
||||
}
|
||||
|
||||
describe('DSLRuntime provider-result caching', () => {
|
||||
it('reuses a registered provider result within the TTL', 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');
|
||||
await rt.check('u:1', 'can_read', 'doc:9');
|
||||
assert.equal(calls, 1, 'provider should be invoked once within TTL');
|
||||
});
|
||||
|
||||
it('re-invokes the provider after the TTL expires', async () => {
|
||||
const rt = makeRuntime();
|
||||
rt.setFactTTL('owns', 100);
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
let calls = 0;
|
||||
let value = 0.9;
|
||||
rt.registerFact('owns', async () => { calls++; return value; });
|
||||
const first = await rt.check('u:1', 'can_read', 'doc:9');
|
||||
assert.equal(first.possibility, 0.9);
|
||||
rt._test_advance(50);
|
||||
await rt.check('u:1', 'can_read', 'doc:9'); // within TTL -> cached
|
||||
assert.equal(calls, 1);
|
||||
rt._test_advance(60); // past TTL (110 total)
|
||||
value = 0.4;
|
||||
const after = await rt.check('u:1', 'can_read', 'doc:9');
|
||||
assert.equal(calls, 2);
|
||||
assert.equal(after.possibility, 0.4);
|
||||
});
|
||||
|
||||
it('per-check factProviders override the cache (fresh observation)', async () => {
|
||||
const rt = makeRuntime();
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
rt.registerFact('owns', async () => 0.9);
|
||||
await rt.check('u:1', 'can_read', 'doc:9');
|
||||
// Per-check override is cache-transparent: it must NOT be masked by the
|
||||
// cached 0.9, and it must NOT overwrite the cached value.
|
||||
const over = await rt.check('u:1', 'can_read', 'doc:9', {
|
||||
factProviders: { owns: async () => 0.2 }
|
||||
});
|
||||
assert.equal(over.possibility, 0.2);
|
||||
const next = await rt.check('u:1', 'can_read', 'doc:9');
|
||||
assert.equal(next.possibility, 0.9, 'registered provider cache untouched by per-check override');
|
||||
});
|
||||
|
||||
it('registerFact invalidates the cached result for that relation', async () => {
|
||||
const rt = makeRuntime();
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
rt.registerFact('owns', async () => 0.9);
|
||||
await rt.check('u:1', 'can_read', 'doc:9');
|
||||
rt.registerFact('owns', async () => 0.3); // re-register -> cache invalidated
|
||||
const res = await rt.check('u:1', 'can_read', 'doc:9');
|
||||
assert.equal(res.possibility, 0.3);
|
||||
});
|
||||
|
||||
it('invalidates cached results on graph mutations', 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);
|
||||
rt.addRelation('u:1', 'owns', 'doc:9', { possibility: 1.0 }); // mutation clears cache
|
||||
const res = await rt.check('u:1', 'can_read', 'doc:9');
|
||||
assert.equal(calls, 2, 'graph mutation should invalidate the provider cache');
|
||||
});
|
||||
|
||||
it('invalidateProviderCache() clears all or per relation', async () => {
|
||||
const dsl = `
|
||||
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) }
|
||||
evidence can_open(user: Employee, doc: Doc) { WHEN can_read(user, doc) UNLESS banned(user) }
|
||||
`;
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-cache2');
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
let ownsCalls = 0, bannedCalls = 0;
|
||||
rt.registerFact('owns', async () => { ownsCalls++; return 0.9; });
|
||||
rt.registerFact('banned', async () => { bannedCalls++; return 0; });
|
||||
await rt.check('u:1', 'can_open', 'doc:9');
|
||||
assert.equal(ownsCalls, 1);
|
||||
assert.equal(bannedCalls, 1);
|
||||
// Invalidate a non-dependency relation: can_open's cache (owns+banned) survives.
|
||||
rt.invalidateProviderCache('does_not_exist');
|
||||
await rt.check('u:1', 'can_open', 'doc:9');
|
||||
assert.equal(ownsCalls, 1);
|
||||
assert.equal(bannedCalls, 1);
|
||||
// Invalidate owns only: banned survives, owns re-fetched.
|
||||
rt.invalidateProviderCache('owns');
|
||||
await rt.check('u:1', 'can_open', 'doc:9');
|
||||
assert.equal(ownsCalls, 2, 'owns cache cleared by per-relation invalidation');
|
||||
assert.equal(bannedCalls, 1, 'banned cache survives per-relation invalidation');
|
||||
// Clear all.
|
||||
rt.invalidateProviderCache();
|
||||
await rt.check('u:1', 'can_open', 'doc:9');
|
||||
assert.equal(bannedCalls, 2, 'full invalidation clears every relation');
|
||||
});
|
||||
|
||||
it('policy default TTL applies when no per-fact TTL is set', async () => {
|
||||
const rt = makeRuntime({ policy: { providerCacheTTL: 50 } });
|
||||
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');
|
||||
rt._test_advance(40);
|
||||
await rt.check('u:1', 'can_read', 'doc:9');
|
||||
assert.equal(calls, 1, 'within 50ms policy TTL -> cached');
|
||||
rt._test_advance(20);
|
||||
await rt.check('u:1', 'can_read', 'doc:9');
|
||||
assert.equal(calls, 2, 'past 50ms policy TTL -> re-invoked');
|
||||
});
|
||||
|
||||
it('uses the DSL-declared fact TTL (BEHAVES { ttl X })', async () => {
|
||||
const dsl = `
|
||||
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) }
|
||||
`;
|
||||
let t = 0;
|
||||
const rt = new DSLRuntime(new Arbiter(), { clock: () => t }).compile(dsl, 'rt-dsl-ttl');
|
||||
// The DSL declares a 1h TTL for the balance fact.
|
||||
assert.equal(rt.relations.get('balance').ttlMs, 3600_000);
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
let calls = 0;
|
||||
rt.registerFact('balance', async () => { calls++; return { possibility: 1.0, value: 50 }; });
|
||||
await rt.check('u:1', 'can_spend', 'doc:9');
|
||||
assert.equal(calls, 1);
|
||||
t += 60 * 60 * 1000 - 1; // just under 1h
|
||||
await rt.check('u:1', 'can_spend', 'doc:9');
|
||||
assert.equal(calls, 1, 'cached within DSL-declared 1h TTL');
|
||||
t += 2;
|
||||
await rt.check('u:1', 'can_spend', 'doc:9');
|
||||
assert.equal(calls, 2, 're-invoked past the DSL-declared 1h TTL');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* tests/DSLRuntimeExt.test.js — extended DSLRuntime capabilities:
|
||||
* - schema introspection (getSchema)
|
||||
* - per-relation provider registration (registerFact/unregisterFact)
|
||||
* - provider merging (registered + per-check overrides)
|
||||
* - bounded fixed-point provider retrieval loop (edges satisfy other facts)
|
||||
* - require() throw-on-deny
|
||||
* - removal passthroughs and fact-relation check validation
|
||||
* - timestamp/duration field typing
|
||||
*/
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
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 }
|
||||
fact *owns(user: Employee, doc: Doc)
|
||||
fact *banned(user: Employee)
|
||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
evidence can_open(user: Employee, doc: Doc) { WHEN can_read(user, doc) UNLESS banned(user) }
|
||||
`;
|
||||
|
||||
function makeRuntime() {
|
||||
return new DSLRuntime(new Arbiter()).compile(BASE_DSL, 'rt-ext');
|
||||
}
|
||||
|
||||
describe('DSLRuntime extended', () => {
|
||||
it('exposes a serializable schema snapshot', () => {
|
||||
const rt = makeRuntime();
|
||||
const schema = rt.getSchema();
|
||||
assert.ok(Array.isArray(schema.types));
|
||||
const employee = schema.types.find(t => t.name === 'Employee');
|
||||
assert.ok(employee);
|
||||
assert.ok(employee.fields.some(f => f.name === 'level' && f.type === 'number'));
|
||||
const owns = schema.facts.find(f => f.name === 'owns');
|
||||
assert.equal(owns.injectable, true);
|
||||
assert.equal(owns.params[1].type, 'Doc');
|
||||
const can_open = schema.evidence.find(e => e.name === 'can_open');
|
||||
assert.ok(can_open.dependsOn.includes('owns'));
|
||||
assert.deepEqual(schema.providers, []);
|
||||
assert.ok(rt.relationNames().includes('owns') && rt.relationNames().includes('can_read'));
|
||||
});
|
||||
|
||||
it('registers, lists, and unregisters per-relation providers', () => {
|
||||
const rt = makeRuntime();
|
||||
rt.registerFact('owns', async () => 0.8);
|
||||
assert.deepEqual(rt.registeredFacts(), ['owns']);
|
||||
rt.registerFact('banned', async () => 0);
|
||||
assert.deepEqual(rt.registeredFacts().sort(), ['banned', 'owns']);
|
||||
rt.unregisterFact('banned');
|
||||
assert.deepEqual(rt.registeredFacts(), ['owns']);
|
||||
assert.throws(() => rt.registerFact('owns', 'not a function'), /must be a function/);
|
||||
});
|
||||
|
||||
it('merges registered providers with per-check overrides', async () => {
|
||||
const rt = makeRuntime();
|
||||
rt.registerFact('owns', async () => 0.5);
|
||||
rt.registerFact('banned', async () => 0);
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
// registered owns (0.5) wins over nothing; per-check banned overrides
|
||||
const res = await rt.check('u:1', 'can_open', 'doc:9', {
|
||||
factProviders: { banned: async () => 0 }
|
||||
});
|
||||
assert.equal(res.possibility, 0.5);
|
||||
assert.deepEqual(res.providedFacts.sort(), ['banned', 'owns']);
|
||||
});
|
||||
|
||||
it('runs providers to a fixed point when edges satisfy other required facts', async () => {
|
||||
// can_open needs owns (injectable). A registered owns provider returns an
|
||||
// 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 }
|
||||
fact *owns(user: Employee, doc: Doc)
|
||||
fact *granted(user: Employee, doc: Doc)
|
||||
evidence base_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
evidence can_open(user: Employee, doc: Doc) { WHEN base_read(user, doc) UNLESS granted(user, doc) }
|
||||
`;
|
||||
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-loop');
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
let ownsCalls = 0;
|
||||
let grantedCalls = 0;
|
||||
rt.registerFact('owns', async () => {
|
||||
ownsCalls++;
|
||||
// First round the owns provider also supplies the granted edge (a
|
||||
// fixed-point dependency: granted needs owns to have been retrieved).
|
||||
return [
|
||||
{ src: 'u:1', relation: 'owns', dst: 'doc:9', possibility: 0.9 },
|
||||
{ src: 'u:1', relation: 'granted', dst: 'doc:9', possibility: 0 }
|
||||
];
|
||||
});
|
||||
rt.registerFact('granted', async () => { grantedCalls++; return 0; });
|
||||
const res = await rt.check('u:1', 'can_open', 'doc:9', { maxProviderRounds: 3 });
|
||||
assert.equal(res.possibility, 0.9);
|
||||
// granted was satisfied by the owns provider's extra edge, so its own
|
||||
// provider was never needed in a later round.
|
||||
assert.equal(grantedCalls, 0);
|
||||
assert.ok(ownsCalls >= 1);
|
||||
assert.deepEqual(res.providedFacts, ['owns']);
|
||||
assert.deepEqual(res.missingFacts, []);
|
||||
});
|
||||
|
||||
it('require() throws on denial and returns the result on grant', async () => {
|
||||
const rt = makeRuntime();
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
rt.registerFact('owns', async () => 0.9);
|
||||
const ok = await rt.require('u:1', 'can_read', 'doc:9');
|
||||
assert.equal(ok.possibility, 0.9);
|
||||
rt.registerFact('owns', async () => 0);
|
||||
await assert.rejects(
|
||||
() => rt.require('u:1', 'can_read', 'doc:9'),
|
||||
(err) => err.result && err.result.possibility === 0 && /denied/.test(err.message)
|
||||
);
|
||||
});
|
||||
|
||||
it('passes through node/relation removal', () => {
|
||||
const rt = makeRuntime();
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
rt.addRelation('u:1', 'owns', 'doc:9', { possibility: 1.0 });
|
||||
rt.removeRelation('u:1', 'owns', 'doc:9');
|
||||
assert.equal(rt.arbiter.check('u:1', 'owns', 'doc:9').possibility, 0);
|
||||
rt.removeNode('u:1');
|
||||
assert.equal(rt.arbiter.nodeIdByKey.has('u:1'), false);
|
||||
});
|
||||
|
||||
it('validates fact-relation check endpoints like evidence', async () => {
|
||||
const rt = makeRuntime();
|
||||
rt.addNode('u:1', 'Employee', {});
|
||||
rt.addNode('doc:9', 'Doc', {});
|
||||
// can_read is evidence; owns is a fact — checking a fact still validates.
|
||||
await assert.rejects(() => rt.check('u:1', 'owns', 'u:1', {}), /expected 'Doc'/);
|
||||
});
|
||||
|
||||
it('accepts timestamp field values and rejects mistyped ones', () => {
|
||||
const rt = makeRuntime();
|
||||
rt.addNode('doc:9', 'Doc', { created: 1720000000000 });
|
||||
rt.updateNodeData('doc:9', { created: '2026-08-03T00:00:00Z' });
|
||||
assert.throws(() => rt.addNode('doc:8', 'Doc', { created: {} }), /must be timestamp/);
|
||||
});
|
||||
|
||||
it('direct FACT checks consult the registered provider', 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; });
|
||||
// Checking the fact directly (not via an evidence) must retrieve it.
|
||||
const res = await rt.check('u:1', 'owns', 'doc:9');
|
||||
assert.equal(res.possibility, 0.9);
|
||||
assert.equal(calls, 1);
|
||||
assert.deepEqual(res.requiredFacts, ['owns']);
|
||||
assert.deepEqual(res.providedFacts, ['owns']);
|
||||
// Without a provider and without an edge, it reports the missing fact.
|
||||
const rt2 = new DSLRuntime(new Arbiter()).compile(BASE_DSL, 'rt-fact-miss');
|
||||
rt2.addNode('u:1', 'Employee', {});
|
||||
rt2.addNode('doc:9', 'Doc', {});
|
||||
const missed = await rt2.check('u:1', 'owns', 'doc:9');
|
||||
assert.equal(missed.possibility, 0);
|
||||
assert.deepEqual(missed.missingFacts, [{ relation: 'owns', reason: 'no_provider' }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* tests/EvidenceComposition.test.js — referencing a derived evidence as a
|
||||
* sub-rule of another evidence (WHEN can_read(user, doc) where can_read is
|
||||
* itself an evidence).
|
||||
*
|
||||
* Composition is resolved at COMPILE time: the generator inlines each
|
||||
* evidence reference with the referenced evidence's own config (a linker
|
||||
* pass that handles forward references and rejects cycles), so the engine
|
||||
* evaluates a fully-resolved, acyclic config tree.
|
||||
*/
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Arbiter } from '@arbiter/core';
|
||||
import { DSLCompiler } from '../src/DSLCompiler.js';
|
||||
|
||||
const DEFS = `
|
||||
definition Employee { id: string }
|
||||
definition Group { id: string }
|
||||
definition Doc { id: string }
|
||||
fact owns(user: Employee, doc: Doc)
|
||||
fact *trusted(user: Employee)
|
||||
fact member_of(user: Employee, group: Group)
|
||||
fact can_access(group: Group, doc: Doc)
|
||||
`;
|
||||
|
||||
function compile(dsl, name = 'compose') {
|
||||
const arb = new Arbiter();
|
||||
const compiler = new DSLCompiler(arb);
|
||||
const result = compiler.compile(dsl, name);
|
||||
return { arb, result };
|
||||
}
|
||||
|
||||
describe('Evidence composition', () => {
|
||||
it('composes a direct evidence into another evidence', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
evidence can_browse(user: Employee, doc: Doc) { can_read(user, doc) }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'owns', 'doc:9', { possibility: 0.8 });
|
||||
const res = arb.check('u:1', 'can_browse', 'doc:9');
|
||||
assert.equal(res.possibility, 0.8);
|
||||
// The reference is inlined to the underlying fact config.
|
||||
assert.equal(arb.relationConfigs.get('can_browse').type, 'direct');
|
||||
assert.equal(arb.relationConfigs.get('can_browse').relation, 'owns');
|
||||
});
|
||||
|
||||
it('composes an evidence inside a defeasible WHEN/UNLESS', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
evidence can_open(user: Employee, doc: Doc) { WHEN can_read(user, doc) UNLESS trusted(user) }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'owns', 'doc:9', { possibility: 0.9 });
|
||||
assert.equal(arb.check('u:1', 'can_open', 'doc:9').possibility, 0.9);
|
||||
arb.addRelation('u:1', 'trusted', 'u:1', { possibility: 1.0 });
|
||||
const denied = arb.check('u:1', 'can_open', 'doc:9');
|
||||
assert.equal(denied.possibility, 0);
|
||||
assert.equal(denied.reason, 'defeated_by_unless');
|
||||
});
|
||||
|
||||
it('composes a chain evidence into another evidence', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence can_enter(user: Employee, doc: Doc) { member_of(user, *g) { can_access(g, doc) } }
|
||||
evidence can_work(user: Employee, doc: Doc) { can_enter(user, doc) }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
|
||||
arb.addRelation('g:1', 'can_access', 'doc:9', { possibility: 0.7 });
|
||||
const res = arb.check('u:1', 'can_work', 'doc:9');
|
||||
assert.equal(res.possibility, 0.7);
|
||||
assert.equal(arb.relationConfigs.get('can_work').type, 'chain');
|
||||
});
|
||||
|
||||
it('composes transitively (A → B → fact) and re-derives dependencies', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
evidence can_browse(user: Employee, doc: Doc) { can_read(user, doc) }
|
||||
evidence can_open(user: Employee, doc: Doc) { can_browse(user, doc) }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'owns', 'doc:9', { possibility: 0.6 });
|
||||
assert.equal(arb.check('u:1', 'can_open', 'doc:9').possibility, 0.6);
|
||||
assert.deepEqual(arb.relationConfigs.get('can_open').dependsOn, ['owns']);
|
||||
});
|
||||
|
||||
it('composes a value-carrying evidence and preserves subject-as-object scope', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
fact *user_risk(user: Employee, value: number)
|
||||
evidence risk_ok(user: Employee, doc: Doc) { user_risk(user, 1) }
|
||||
evidence can_proceed(user: Employee, doc: Doc) { risk_ok(user, doc) }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'user_risk', 'u:1', { possibility: 1.0, value: 1 });
|
||||
const res = arb.check('u:1', 'can_proceed', 'doc:9');
|
||||
assert.equal(res.possibility, 1);
|
||||
});
|
||||
|
||||
it('composes evidence inside a comparator operand', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
fact *user_risk(user: Employee, value: number)
|
||||
fact *risk_limit(doc: Doc, value: number)
|
||||
evidence user_risk_ok(user: Employee, doc: Doc) { user_risk(user, 1) }
|
||||
evidence can_proceed(user: Employee, doc: Doc) { user_risk_ok(user, doc) }
|
||||
`);
|
||||
assert.ok(result.success, JSON.stringify(result.errors));
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'user_risk', 'u:1', { possibility: 1.0, value: 1 });
|
||||
assert.equal(arb.check('u:1', 'can_proceed', 'doc:9').possibility, 1);
|
||||
});
|
||||
|
||||
it('rejects cyclic evidence references at compile time', () => {
|
||||
const { result } = compile(`
|
||||
${DEFS}
|
||||
evidence a(user: Employee, doc: Doc) { b(user, doc) }
|
||||
evidence b(user: Employee, doc: Doc) { a(user, doc) }
|
||||
`);
|
||||
assert.equal(result.success, false);
|
||||
assert.ok(result.errors.some(e => /[Cc]yclic/.test(e)), JSON.stringify(result.errors));
|
||||
});
|
||||
|
||||
it('rejects self-referencing evidence at compile time', () => {
|
||||
const { result } = compile(`
|
||||
${DEFS}
|
||||
evidence a(user: Employee, doc: Doc) { a(user, doc) }
|
||||
`);
|
||||
assert.equal(result.success, false);
|
||||
assert.ok(result.errors.some(e => /[Cc]yclic/.test(e)), JSON.stringify(result.errors));
|
||||
});
|
||||
|
||||
it('keeps the referenced evidence checkable in its own right', () => {
|
||||
const { arb, result } = compile(`
|
||||
${DEFS}
|
||||
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
evidence can_browse(user: Employee, doc: Doc) { can_read(user, doc) }
|
||||
`);
|
||||
assert.ok(result.success);
|
||||
arb.addNode('u:1', 'Employee'); arb.addNode('doc:9', 'Doc');
|
||||
arb.addRelation('u:1', 'owns', 'doc:9', { possibility: 0.5 });
|
||||
assert.equal(arb.check('u:1', 'can_read', 'doc:9').possibility, 0.5);
|
||||
assert.equal(arb.check('u:1', 'can_browse', 'doc:9').possibility, 0.5);
|
||||
});
|
||||
});
|
||||
+14
-13
@@ -45,6 +45,7 @@ const DSL_SUPPORT = `
|
||||
fact isMember(user: any, group: any)
|
||||
fact isFriend(user: any, friend: any)
|
||||
fact similar(a: any, b: any)
|
||||
fact reachable(user: any, doc: any)
|
||||
fact parentOf(user: any, parent: any)
|
||||
fact isEditable(doc: any)
|
||||
fact isPublic(doc: any)
|
||||
@@ -159,7 +160,7 @@ describe('Evidence Rules', () => {
|
||||
{
|
||||
input: `evidence canRead(user: Employee, doc: Document) {
|
||||
isMember(user, *group) {
|
||||
canRead(group, doc)
|
||||
reachable(group, doc)
|
||||
}
|
||||
}`,
|
||||
description: 'Basic pattern matching with wildcard'
|
||||
@@ -167,7 +168,7 @@ describe('Evidence Rules', () => {
|
||||
{
|
||||
input: `evidence canRead(user: Employee, doc: Document) {
|
||||
isMember(user, *group) {
|
||||
canRead(group, doc)
|
||||
reachable(group, doc)
|
||||
} limit 5
|
||||
}`,
|
||||
description: 'Pattern matching with limit'
|
||||
@@ -175,7 +176,7 @@ describe('Evidence Rules', () => {
|
||||
{
|
||||
input: `evidence canRead(user: Employee, doc: Document) {
|
||||
similar(doc, *similar) |similarity| {
|
||||
canRead(user, similar)
|
||||
reachable(user, similar)
|
||||
} with similarity > 0.7
|
||||
}`,
|
||||
description: 'Pattern matching with binding and condition'
|
||||
@@ -183,7 +184,7 @@ describe('Evidence Rules', () => {
|
||||
{
|
||||
input: `evidence canRead(user: Employee, doc: Document) {
|
||||
similar(doc, *similar) |similarity| {
|
||||
canRead(user, similar)
|
||||
reachable(user, similar)
|
||||
} limit 5 with similarity > 0.7
|
||||
}`,
|
||||
description: 'Pattern matching with binding, condition, and limit'
|
||||
@@ -192,7 +193,7 @@ describe('Evidence Rules', () => {
|
||||
input: `evidence canRead(user: Employee, doc: Document) {
|
||||
isMember(user, *group) {
|
||||
isMember(group, *parentGroup) {
|
||||
canRead(parentGroup, doc)
|
||||
reachable(parentGroup, doc)
|
||||
} limit 2
|
||||
} limit 3
|
||||
}`,
|
||||
@@ -202,7 +203,7 @@ describe('Evidence Rules', () => {
|
||||
input: `evidence canRead(user: Employee, doc: Document) {
|
||||
isFriend(user, *friend) {
|
||||
isMember(friend, *group) {
|
||||
canRead(group, doc)
|
||||
reachable(group, doc)
|
||||
} limit 1
|
||||
} limit 5
|
||||
}`,
|
||||
@@ -291,15 +292,15 @@ describe('Evidence Rules', () => {
|
||||
owns(user, doc)
|
||||
|
||||
isMember(user, *group) {
|
||||
canRead(group, doc)
|
||||
reachable(group, doc)
|
||||
} limit 5
|
||||
|
||||
parentOf(user, *parent) {
|
||||
canRead(parent, doc)
|
||||
reachable(parent, doc)
|
||||
} limit 3
|
||||
|
||||
similar(doc, *similar) |similarity| {
|
||||
canRead(user, similar)
|
||||
reachable(user, similar)
|
||||
} limit 5 with similarity > 0.7
|
||||
|
||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||
@@ -337,11 +338,11 @@ describe('Evidence Rules', () => {
|
||||
owns(user, doc)
|
||||
|
||||
isMember(user, *group) {
|
||||
canModify(group, doc)
|
||||
reachable(group, doc)
|
||||
} limit 3
|
||||
|
||||
similar(doc, *similar) |similarity| {
|
||||
canModify(user, similar)
|
||||
reachable(user, similar)
|
||||
isEditable(similar)
|
||||
} limit 2 with similarity > 0.8
|
||||
|
||||
@@ -385,7 +386,7 @@ describe('Evidence Rules', () => {
|
||||
{
|
||||
input: `evidence canRead(user: Employee, doc: Document) {
|
||||
isMember(user, *group) {
|
||||
canRead(group, doc)
|
||||
reachable(group, doc)
|
||||
} with
|
||||
}`,
|
||||
description: 'Incomplete with clause should fail'
|
||||
@@ -393,7 +394,7 @@ describe('Evidence Rules', () => {
|
||||
{
|
||||
input: `evidence canRead(user: Employee, doc: Document) {
|
||||
isMember(user, *group) {
|
||||
canRead(group, doc)
|
||||
reachable(group, doc)
|
||||
} limit
|
||||
}`,
|
||||
description: 'Incomplete limit should fail'
|
||||
|
||||
+16
-12
@@ -105,6 +105,7 @@ describe('Integration Tests', () => {
|
||||
fact hasAccess(user: Employee, resource: Resource, level: string) CACHE lazy
|
||||
fact isColleague(user: any, colleague: any) symmetrical CACHE lazy limit 50
|
||||
fact isParentOf(parent: Employee, child: Employee) transitive CACHE eager limit 3
|
||||
fact reachable(user: any, doc: any) CACHE lazy
|
||||
fact hasClearance(user: Employee, level: string) CACHE eager
|
||||
fact parentOf(user: any, parent: any) CACHE eager
|
||||
fact similar(a: any, b: any) CACHE lazy
|
||||
@@ -119,15 +120,15 @@ describe('Integration Tests', () => {
|
||||
owns(user, doc)
|
||||
|
||||
isMember(user, *group) {
|
||||
canRead(group, doc)
|
||||
reachable(group, doc)
|
||||
} limit 5
|
||||
|
||||
parentOf(user, *parent) {
|
||||
canRead(parent, doc)
|
||||
reachable(parent, doc)
|
||||
} limit 3
|
||||
|
||||
similar(doc, *similar) |similarity| {
|
||||
canRead(user, similar)
|
||||
reachable(user, similar)
|
||||
} limit 5 with similarity > 0.7
|
||||
|
||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||
@@ -137,7 +138,7 @@ describe('Integration Tests', () => {
|
||||
owns(user, doc)
|
||||
|
||||
isMember(user, *group) {
|
||||
canWrite(group, doc)
|
||||
reachable(group, doc)
|
||||
} limit 3
|
||||
|
||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||
@@ -330,6 +331,7 @@ describe('Integration Tests', () => {
|
||||
|
||||
fact isMember(user: any, org: any) transitive CACHE lazy limit 5
|
||||
fact isParentOf(parent: Organization, child: Organization) transitive CACHE eager limit 3
|
||||
fact reachable(user: any, doc: any) CACHE lazy
|
||||
fact hasRole(user: Employee, role: string) CACHE eager
|
||||
fact hasClearance(user: Employee, level: string) CACHE eager
|
||||
fact isSuspended(user: any) CACHE lazy
|
||||
@@ -339,7 +341,7 @@ describe('Integration Tests', () => {
|
||||
isMember(user, org)
|
||||
|
||||
isParentOf(org, *parentOrg) {
|
||||
canAccessOrg(user, parentOrg)
|
||||
reachable(user, parentOrg)
|
||||
} limit 3
|
||||
|
||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||
@@ -347,11 +349,11 @@ describe('Integration Tests', () => {
|
||||
|
||||
evidence canAccessResource(user: Employee, resource: Resource) {
|
||||
isMember(user, *org) {
|
||||
canAccessResource(org, resource)
|
||||
reachable(org, resource)
|
||||
} limit 5
|
||||
|
||||
parentOf(user, *parent) {
|
||||
canAccessResource(parent, resource)
|
||||
reachable(parent, resource)
|
||||
} limit 2
|
||||
}
|
||||
`;
|
||||
@@ -379,6 +381,7 @@ describe('Integration Tests', () => {
|
||||
fact hasInterest(user: any, interest: string) CACHE lazy
|
||||
fact hasTag(doc: any, tag: string) CACHE lazy
|
||||
fact owns(user: any, doc: any) CACHE eager
|
||||
fact reachable(user: any, doc: any) CACHE lazy
|
||||
fact similar(a: any, b: any) CACHE lazy
|
||||
fact isPublic(doc: any) CACHE eager
|
||||
fact hasInterests(user: any) CACHE lazy
|
||||
@@ -390,12 +393,12 @@ describe('Integration Tests', () => {
|
||||
owns(user, doc)
|
||||
|
||||
similar(doc, *similar) |similarity| {
|
||||
canRead(user, similar)
|
||||
reachable(user, similar)
|
||||
isPublic(similar)
|
||||
} limit 10 with similarity > 0.7
|
||||
|
||||
isFriend(user, *friend) {
|
||||
canRead(friend, doc)
|
||||
reachable(friend, doc)
|
||||
} limit 5
|
||||
|
||||
fusion majority {
|
||||
@@ -406,7 +409,7 @@ describe('Integration Tests', () => {
|
||||
|
||||
evidence canRecommend(user: Employee, doc: Document) {
|
||||
similar(user, *similarUser) |similarity| {
|
||||
canRead(similarUser, doc)
|
||||
reachable(similarUser, doc)
|
||||
} limit 20 with similarity > 0.8
|
||||
|
||||
fusion average {
|
||||
@@ -556,13 +559,14 @@ describe('Integration Tests', () => {
|
||||
fact isFriend(user: any, friend: any) symmetrical CACHE eager limit 50
|
||||
fact hasPermission(user: Employee, resource: Resource, action: string) CACHE eager
|
||||
fact owns(user: Employee, resource: Resource) CACHE eager
|
||||
fact reachable(user: any, doc: any) CACHE lazy
|
||||
|
||||
// Optimized evidence rules
|
||||
evidence canAccess(user: Employee, resource: Resource) {
|
||||
owns(user, resource)
|
||||
|
||||
isMember(user, *group) {
|
||||
canAccess(group, resource)
|
||||
reachable(group, resource)
|
||||
} limit 3
|
||||
|
||||
WHEN hasPermission(user, resource, 'read')
|
||||
@@ -572,7 +576,7 @@ describe('Integration Tests', () => {
|
||||
owns(user, resource)
|
||||
|
||||
isMember(user, *group) {
|
||||
canModify(group, resource)
|
||||
reachable(group, resource)
|
||||
} limit 2
|
||||
|
||||
WHEN hasPermission(user, resource, 'write')
|
||||
|
||||
@@ -32,7 +32,12 @@ const FACTS = `
|
||||
fact can_access(group: Group, doc: Doc)
|
||||
fact owner(group: Group, doc: Doc)
|
||||
fact granted(user: Employee, doc: Doc)
|
||||
fact group_perm(group: Group, doc: Doc)
|
||||
fact group_banned(group: Group)
|
||||
fact banned(user: Employee)
|
||||
fact peer(user: Employee, other: Employee)
|
||||
fact trusted(other: Employee)
|
||||
fact doc_read(user: Employee, doc: Doc)
|
||||
fact mfa(user: Employee)
|
||||
`;
|
||||
|
||||
@@ -106,11 +111,66 @@ function buildProgram(kind, ps) {
|
||||
oracle = pG * pM;
|
||||
break;
|
||||
}
|
||||
case 'composition': {
|
||||
// can_via composes the direct evidence can_read, which reads the owns
|
||||
// edge — an evidence-in-evidence reference resolved at compile time.
|
||||
const [pOwn] = ps;
|
||||
evidence = `evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||
evidence can_via(user: Employee, doc: Doc) { can_read(user, doc) }`;
|
||||
edges.push({ src: 'u:1', relation: 'owns', dst: 'doc:9', possibility: pOwn });
|
||||
oracle = pOwn;
|
||||
break;
|
||||
}
|
||||
case 'chain_step_composition': {
|
||||
// group_read (a direct evidence) used as a CHAIN STEP inside can_via:
|
||||
// the step is expanded at compile time to the underlying can_view edge.
|
||||
const [pm, pv] = ps;
|
||||
evidence = `evidence group_read(group: Group, doc: Doc) { group_perm(group, doc) }
|
||||
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { group_read(g, doc) } }`;
|
||||
edges.push({ src: 'u:1', relation: 'member_of', dst: 'g:1', possibility: pm });
|
||||
edges.push({ src: 'g:1', relation: 'group_perm', dst: 'doc:9', possibility: pv });
|
||||
oracle = Math.min(pm, pv);
|
||||
break;
|
||||
}
|
||||
case 'chain_condition_step': {
|
||||
// gated (a defeasible evidence) as the FINAL chain step → a condition
|
||||
// step: the engine verifies gated at (intermediate, object). The oracle
|
||||
// is the chain's min combined with the condition's base*(1-defeat).
|
||||
const [pm, pv, pb] = ps;
|
||||
evidence = `evidence gated(group: Group, doc: Doc) { WHEN group_perm(group, doc) UNLESS group_banned(group) }
|
||||
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }`;
|
||||
edges.push({ src: 'u:1', relation: 'member_of', dst: 'g:1', possibility: pm });
|
||||
edges.push({ src: 'g:1', relation: 'group_perm', dst: 'doc:9', possibility: pv });
|
||||
edges.push({ src: 'g:1', relation: 'group_banned', dst: 'g:1', possibility: pb });
|
||||
oracle = Math.min(pm, pv * (1 - pb));
|
||||
break;
|
||||
}
|
||||
case 'chain_intermediate_condition': {
|
||||
// peer_trusted (a defeasible evidence) as an INTERMEDIATE chain step:
|
||||
// the engine expands it from the source (peer edges filtered by the
|
||||
// trusted defeater) then continues to can_read. Oracle = min of the
|
||||
// surviving peer leg and the read leg.
|
||||
const [pp, pt, pr] = ps;
|
||||
evidence = `evidence peer_trusted(user: Employee, other: Employee) { WHEN peer(user, other) UNLESS trusted(other) }
|
||||
evidence can_via(user: Employee, doc: Doc) { peer_trusted(user, *p) { doc_read(p, doc) } }`;
|
||||
edges.push({ src: 'u:1', relation: 'peer', dst: 'p:1', possibility: pp });
|
||||
edges.push({ src: 'p:1', relation: 'trusted', dst: 'p:1', possibility: pt });
|
||||
edges.push({ src: 'p:1', relation: 'doc_read', dst: 'doc:9', possibility: pr });
|
||||
oracle = Math.min(pp * (1 - pt), pr);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new Error(`unknown construct: ${kind}`);
|
||||
}
|
||||
|
||||
return { dsl: FACTS + evidence, edges, oracle, relation: evidence.match(/evidence (\w+)/)[1] };
|
||||
return {
|
||||
dsl: FACTS + evidence,
|
||||
edges,
|
||||
oracle,
|
||||
// Check the LAST evidence declaration: the composition construct declares
|
||||
// two evidences (can_read + can_via), and the composed one is the target.
|
||||
relation: [...evidence.matchAll(/evidence\s+(\w+)/g)].at(-1)[1]
|
||||
};
|
||||
}
|
||||
|
||||
function runCheck({ kind, ps }) {
|
||||
@@ -119,6 +179,10 @@ function runCheck({ kind, ps }) {
|
||||
arbiter.addNode('u:1', 'Employee');
|
||||
arbiter.addNode('g:1', 'Group');
|
||||
arbiter.addNode('doc:9', 'Doc');
|
||||
for (const e of edges) {
|
||||
arbiter.addNode(e.src, e.dst === 'doc:9' ? 'Doc' : 'Employee');
|
||||
arbiter.addNode(e.dst, e.dst === 'doc:9' ? 'Doc' : 'Employee');
|
||||
}
|
||||
const compiler = new DSLCompiler(arbiter);
|
||||
const compiled = compiler.compile(dsl, 'oracle');
|
||||
if (!compiled.success) {
|
||||
@@ -134,7 +198,8 @@ function runCheck({ kind, ps }) {
|
||||
}
|
||||
|
||||
const CONSTRUCTS = ['direct', 'chain', 'tuple_to_userset', 'fusion_min', 'fusion_max',
|
||||
'when_unless', 'never_always', 'requires_when'];
|
||||
'when_unless', 'never_always', 'requires_when', 'composition', 'chain_step_composition',
|
||||
'chain_condition_step', 'chain_intermediate_condition'];
|
||||
|
||||
describe('DSL generative oracle parity (rigor)', () => {
|
||||
it('generated legal DSL compiles and every check matches the oracle', async () => {
|
||||
@@ -145,7 +210,7 @@ describe('DSL generative oracle parity (rigor)', () => {
|
||||
kind: rigor.gen.oneOf(CONSTRUCTS),
|
||||
// exactly two edge possibilities (direct uses only the first);
|
||||
// a shorter array would leave pB undefined and produce a NaN oracle
|
||||
ps: rigor.gen.tuple(rigor.gen.oneOf(P), rigor.gen.oneOf(P))
|
||||
ps: rigor.gen.tuple(rigor.gen.oneOf(P), rigor.gen.oneOf(P), rigor.gen.oneOf(P))
|
||||
})
|
||||
))
|
||||
],
|
||||
@@ -163,18 +228,23 @@ describe('DSL generative oracle parity (rigor)', () => {
|
||||
});
|
||||
|
||||
it('exhaustive deterministic sweep: every construct x every possibility value', () => {
|
||||
// Anti-vacuity complement to the campaign: sweep the full P × P grid per
|
||||
// construct without any RNG, so a construct the campaign skipped would
|
||||
// Anti-vacuity complement to the campaign: sweep the full P × P × P grid
|
||||
// per construct without any RNG, so a construct the campaign skipped would
|
||||
// still be caught here.
|
||||
for (const kind of CONSTRUCTS) {
|
||||
for (const a of P) {
|
||||
for (const b of P) {
|
||||
const ps = kind === 'direct' ? [a] : [a, b];
|
||||
for (const c of P) {
|
||||
const ps = kind === 'direct' ? [a] : [a, b, c];
|
||||
const { dsl, edges, oracle, relation } = buildProgram(kind, ps);
|
||||
const arbiter = new Arbiter();
|
||||
arbiter.addNode('u:1', 'Employee');
|
||||
arbiter.addNode('g:1', 'Group');
|
||||
arbiter.addNode('doc:9', 'Doc');
|
||||
for (const e of edges) {
|
||||
arbiter.addNode(e.src, e.dst === 'doc:9' ? 'Doc' : 'Employee');
|
||||
arbiter.addNode(e.dst, e.dst === 'doc:9' ? 'Doc' : 'Employee');
|
||||
}
|
||||
const compiled = new DSLCompiler(arbiter).compile(dsl, 'sweep');
|
||||
assert.ok(compiled.success, `${kind} compile failed: ${(compiled.errors || []).join('; ')}`);
|
||||
for (const e of edges) arbiter.addRelation(e.src, e.relation, e.dst, { possibility: e.possibility });
|
||||
@@ -183,6 +253,7 @@ describe('DSL generative oracle parity (rigor)', () => {
|
||||
Math.abs(result.possibility - oracle) <= EPS,
|
||||
`${kind} ps=[${ps}] check=${result.possibility}(${result.reason}) vs oracle=${oracle}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +81,21 @@ const MUTATIONS = {
|
||||
desc: 'evidence declared with mismatched parameter arity',
|
||||
mustFail: true,
|
||||
apply: () => VALID_DSL.replace('evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }', 'evidence can_read(user: Employee) { owns(user, doc) }')
|
||||
},
|
||||
cyclic_evidence_ref: {
|
||||
desc: 'two evidences referencing each other (cycle)',
|
||||
mustFail: true,
|
||||
apply: () => VALID_DSL + `
|
||||
evidence can_cyc_a(user: Employee, doc: Doc) { can_cyc_b(user, doc) }
|
||||
evidence can_cyc_b(user: Employee, doc: Doc) { can_cyc_a(user, doc) }`
|
||||
},
|
||||
cross_kind_collision: {
|
||||
desc: 'fact and evidence sharing a relation name',
|
||||
mustFail: true,
|
||||
apply: () => VALID_DSL.replace(
|
||||
'evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }',
|
||||
'fact can_read(user: Employee, doc: Doc)\n evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }'
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user