Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fe162251fc | |||
| 351551af0f |
Generated
+6
-6
@@ -1,15 +1,15 @@
|
|||||||
{
|
{
|
||||||
"name": "@arbiter/evidence-dsl",
|
"name": "@arbiter/evidence-dsl",
|
||||||
"version": "1.1.0",
|
"version": "1.4.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@arbiter/evidence-dsl",
|
"name": "@arbiter/evidence-dsl",
|
||||||
"version": "1.1.0",
|
"version": "1.4.0",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@arbiter/core": "^1.0.2"
|
"@arbiter/core": "^1.0.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@rigor/core": "^3.1.0",
|
"@rigor/core": "^3.1.0",
|
||||||
@@ -17,9 +17,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@arbiter/core": {
|
"node_modules/@arbiter/core": {
|
||||||
"version": "1.0.2",
|
"version": "1.0.3",
|
||||||
"resolved": "https://hub.kl1.tenere.ai/api/packages/Arbiter/npm/%40arbiter%2Fcore/-/1.0.2/core-1.0.2.tgz",
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Arbiter/npm/%40arbiter%2Fcore/-/1.0.3/core-1.0.3.tgz",
|
||||||
"integrity": "sha512-N1duiHy1Rlsxqpvu8uPf4tMaLOQ2tNXvGs53jLkRcIAYqafIAMvcf0BPS2iE2xVKNsqY92+F05bZZEAO5jnbyQ==",
|
"integrity": "sha512-MCXxyeWBoYjEJMrdO8N8q9uEdX7JgDvwRH39D+8x65zFz+JCNWIQ8H4DgsP2rgF+yzv/cdVH4BX9PfFt6i0ftQ==",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tenere/pltc-core": "^0.6.3",
|
"@tenere/pltc-core": "^0.6.3",
|
||||||
|
|||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@arbiter/evidence-dsl",
|
"name": "@arbiter/evidence-dsl",
|
||||||
"version": "1.3.0",
|
"version": "1.5.0",
|
||||||
"description": "Evidence DSL v2 compiler: translates the natural Evidence DSL (ADR-000) into @arbiter/core relation configurations.",
|
"description": "Evidence DSL v2 compiler: translates the natural Evidence DSL (ADR-000) into @arbiter/core relation configurations.",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
"generate:parser": "node scripts/generate-parser.js"
|
"generate:parser": "node scripts/generate-parser.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@arbiter/core": "^1.0.2"
|
"@arbiter/core": "^1.0.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@rigor/core": "^3.1.0",
|
"@rigor/core": "^3.1.0",
|
||||||
|
|||||||
@@ -155,6 +155,7 @@ export class RuleGenerator {
|
|||||||
for (const step of rule.steps) {
|
for (const step of rule.steps) {
|
||||||
if (typeof step === 'string') targetSet.add(step);
|
if (typeof step === 'string') targetSet.add(step);
|
||||||
else if (step && typeof step.relation === 'string') targetSet.add(step.relation);
|
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') {
|
if (rule.type === 'relational_comparator') {
|
||||||
@@ -1070,13 +1071,18 @@ export class RuleGenerator {
|
|||||||
* - chain evidence → splice its steps into this chain (flattening)
|
* - chain evidence → splice its steps into this chain (flattening)
|
||||||
* (a step that is itself a sub-path becomes its steps, preserving the
|
* (a step that is itself a sub-path becomes its steps, preserving the
|
||||||
* linear source→…→object traversal);
|
* linear source→…→object traversal);
|
||||||
* - anything else (defeasible/logical/comparator) → compile error: such a
|
* - logical / defeasible / comparator evidence → only expressible as a
|
||||||
* step is a condition, not an edge traversal, and cannot lower to a flat
|
* FINAL condition-gated step (the object is known, so the engine can
|
||||||
* chain step.
|
* 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) {
|
_expandChainSteps(steps, stack) {
|
||||||
const out = [];
|
const out = [];
|
||||||
for (const step of steps) {
|
for (let idx = 0; idx < steps.length; idx++) {
|
||||||
|
const step = steps[idx];
|
||||||
|
const isLast = idx === steps.length - 1;
|
||||||
const stepName = typeof step === 'string' ? step : step.relation;
|
const stepName = typeof step === 'string' ? step : step.relation;
|
||||||
if (stepName && this.evidenceNames.has(stepName)) {
|
if (stepName && this.evidenceNames.has(stepName)) {
|
||||||
if (stack.has(stepName)) {
|
if (stack.has(stepName)) {
|
||||||
@@ -1099,8 +1105,14 @@ export class RuleGenerator {
|
|||||||
out.push(...this._expandChainSteps(resolved.steps, refStack));
|
out.push(...this._expandChainSteps(resolved.steps, refStack));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if (isLast) {
|
||||||
|
// Condition-gated final hop: inline the evidence's config as a
|
||||||
|
// rule step the engine evaluates at (intermediate, object).
|
||||||
|
out.push({ rule: this._deepCloneRule(resolved), conditionStep: true });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
this.errors.push(`Chain step '${stepName}' references an evidence with type '${resolved.type || 'logical'}'. ` +
|
this.errors.push(`Chain step '${stepName}' references an evidence with type '${resolved.type || 'logical'}'. ` +
|
||||||
'Chain steps can only reference facts, direct evidence, or chain evidence.');
|
'Only the final chain step may reference a defeasible/logical evidence (a condition-gated hop); intermediate steps must be edge traversals.');
|
||||||
out.push(step);
|
out.push(step);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
+175
-28
@@ -1,6 +1,6 @@
|
|||||||
import { DSLCompiler } from '../DSLCompiler.js';
|
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
|
* 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
|
* check). A raw Arbiter accepts untyped inserts; this wrapper adds the
|
||||||
* DSL-informed layer:
|
* DSL-informed layer:
|
||||||
*
|
*
|
||||||
* - addNode / updateNodeData / addRelation / updateRelation validate their
|
* - schema introspection: getSchema() exposes the compiled type system
|
||||||
* arguments against the compiled schema — known types, known relations,
|
* (entity types/fields, facts, evidence, dependencies, providers);
|
||||||
* matching param types, typed field values — before mutating the arbiter.
|
* - typed mutations: addNode / updateNodeData / addRelation / updateRelation
|
||||||
* - check() validates the request, derives the injectable facts the
|
* validate their arguments against the compiled schema — known types,
|
||||||
* evidence requires (its partial-graph requirements), retrieves the
|
* known relations, matching param types, typed field values — before
|
||||||
* missing facts through caller-provided data callbacks, injects them into
|
* mutating the arbiter; removeNode / removeRelation pass through;
|
||||||
* a partial graph, then delegates to the arbiter.
|
* - 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 /
|
* Trust boundary follows the core: caller-supplied evidence (partial graph /
|
||||||
* provider results) is trusted, never policed; only structure is validated.
|
* provider results) is trusted, never policed; only structure is validated.
|
||||||
@@ -62,6 +68,43 @@ export class DSLRuntime {
|
|||||||
return this;
|
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() {
|
_indexSchema() {
|
||||||
this.types.clear();
|
this.types.clear();
|
||||||
this.relations.clear();
|
this.relations.clear();
|
||||||
@@ -103,7 +146,11 @@ export class DSLRuntime {
|
|||||||
if (rule.computedRelation) deps.add(rule.computedRelation);
|
if (rule.computedRelation) deps.add(rule.computedRelation);
|
||||||
}
|
}
|
||||||
if (rule.type === 'chain' && Array.isArray(rule.steps)) {
|
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 === 'parent' && rule.parentRelation) deps.add(rule.parentRelation);
|
||||||
if (rule.type === 'multi_hop' && rule.relation) deps.add(rule.relation);
|
if (rule.type === 'multi_hop' && rule.relation) deps.add(rule.relation);
|
||||||
@@ -132,12 +179,43 @@ 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;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove a registered provider. */
|
||||||
|
unregisterFact(relation) {
|
||||||
|
delete this.factProviders[relation];
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Relation names that currently have a registered provider. */
|
||||||
|
registeredFacts() {
|
||||||
|
return Object.keys(this.factProviders);
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Schema validation helpers
|
// Schema validation helpers
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
_isPrimitive(typeName) {
|
_isValueType(typeName) {
|
||||||
return PRIMITIVE_TYPES.has(typeName);
|
return VALUE_TYPES.has(typeName);
|
||||||
}
|
}
|
||||||
|
|
||||||
_nodeType(key) {
|
_nodeType(key) {
|
||||||
@@ -154,7 +232,7 @@ export class DSLRuntime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_checkNodeType(key, expectedType, position) {
|
_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);
|
const actual = this._nodeType(key);
|
||||||
if (actual === null) {
|
if (actual === null) {
|
||||||
this._checkNodeExists(key, position);
|
this._checkNodeExists(key, position);
|
||||||
@@ -180,7 +258,9 @@ export class DSLRuntime {
|
|||||||
const ok = type === 'string' ? typeof value === 'string'
|
const ok = type === 'string' ? typeof value === 'string'
|
||||||
: type === 'number' ? typeof value === 'number'
|
: type === 'number' ? typeof value === 'number'
|
||||||
: type === 'boolean' ? typeof value === 'boolean'
|
: 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) {
|
if (!ok) {
|
||||||
throw new Error(`DSLRuntime: field '${path}' must be ${type}, got ${typeof value}`);
|
throw new Error(`DSLRuntime: field '${path}' must be ${type}, got ${typeof value}`);
|
||||||
}
|
}
|
||||||
@@ -220,6 +300,14 @@ export class DSLRuntime {
|
|||||||
return this.arbiter.updateNodeData(key, data);
|
return this.arbiter.updateNodeData(key, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Remove a node (passthrough to the arbiter's node manager). */
|
||||||
|
removeNode(key) {
|
||||||
|
if (this.arbiter.nodeManager && typeof this.arbiter.nodeManager.removeNode === 'function') {
|
||||||
|
return this.arbiter.nodeManager.removeNode(key);
|
||||||
|
}
|
||||||
|
return this.arbiter.removeNode?.(key);
|
||||||
|
}
|
||||||
|
|
||||||
_relationOrThrow(relation) {
|
_relationOrThrow(relation) {
|
||||||
const meta = this.relations.get(relation);
|
const meta = this.relations.get(relation);
|
||||||
if (!meta) {
|
if (!meta) {
|
||||||
@@ -254,6 +342,11 @@ export class DSLRuntime {
|
|||||||
return this.arbiter.addRelation(src, relation, dst, attrs);
|
return this.arbiter.addRelation(src, relation, dst, attrs);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Remove a relation edge (passthrough to the arbiter). */
|
||||||
|
removeRelation(src, relation, dst) {
|
||||||
|
return this.arbiter.removeRelation(src, relation, dst);
|
||||||
|
}
|
||||||
|
|
||||||
_validateRelationEndpoints(relation, meta, src, dst, attrs) {
|
_validateRelationEndpoints(relation, meta, src, dst, attrs) {
|
||||||
const params = meta.params;
|
const params = meta.params;
|
||||||
if (params.length === 0) {
|
if (params.length === 0) {
|
||||||
@@ -261,14 +354,14 @@ export class DSLRuntime {
|
|||||||
}
|
}
|
||||||
// First param is always the subject (entity).
|
// First param is always the subject (entity).
|
||||||
const subjectType = params[0].type;
|
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}'`);
|
throw new Error(`DSLRuntime: relation '${relation}' subject param must be an entity type, got '${subjectType}'`);
|
||||||
}
|
}
|
||||||
this._checkNodeType(src, subjectType, 'subject');
|
this._checkNodeType(src, subjectType, 'subject');
|
||||||
|
|
||||||
if (params.length >= 2) {
|
if (params.length >= 2) {
|
||||||
const secondType = params[1].type;
|
const secondType = params[1].type;
|
||||||
if (this._isPrimitive(secondType)) {
|
if (this._isValueType(secondType)) {
|
||||||
// Value-carrying fact (e.g. session(user, token: string)): the value
|
// 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
|
// 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.
|
// the subject so the value is discoverable by value extraction.
|
||||||
@@ -309,6 +402,13 @@ export class DSLRuntime {
|
|||||||
* evidence's injectable facts, inject them into a partial graph, and delegate
|
* evidence's injectable facts, inject them into a partial graph, and delegate
|
||||||
* to the arbiter.
|
* 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} user - subject key
|
||||||
* @param {string} relation - evidence (or fact) relation name
|
* @param {string} relation - evidence (or fact) relation name
|
||||||
* @param {string} object - object key
|
* @param {string} object - object key
|
||||||
@@ -316,47 +416,70 @@ export class DSLRuntime {
|
|||||||
* @param {object} options.partialGraph - caller-supplied partial graph edges
|
* @param {object} options.partialGraph - caller-supplied partial graph edges
|
||||||
* ({ relations: [{ src, relation, dst, possibility, value }], nodes, challenges })
|
* ({ relations: [{ src, relation, dst, possibility, value }], nodes, challenges })
|
||||||
* @param {object} options.factProviders - per-call provider overrides
|
* @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 }
|
* @returns {object} core check result extended with { requiredFacts, providedFacts, missingFacts }
|
||||||
*/
|
*/
|
||||||
async check(user, relation, object, options = {}) {
|
async check(user, relation, object, options = {}) {
|
||||||
const meta = this.relations.get(relation);
|
const meta = this.relations.get(relation);
|
||||||
if (!meta) {
|
if (!meta) {
|
||||||
if (this.strictTypes) throw new Error(`DSLRuntime: unknown relation '${relation}'`);
|
if (this.strictTypes) throw new Error(`DSLRuntime: unknown relation '${relation}'`);
|
||||||
} else if (meta.kind === 'evidence') {
|
} else if (meta.params.length === 2) {
|
||||||
if (meta.params.length === 2) {
|
|
||||||
this._checkNodeType(user, meta.params[0].type, 'subject');
|
this._checkNodeType(user, meta.params[0].type, 'subject');
|
||||||
this._checkNodeType(object, meta.params[1].type, 'object');
|
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 required = this.requiredFacts(relation);
|
||||||
const providers = options.factProviders || this.factProviders;
|
const providers = { ...this.factProviders, ...(options.factProviders || {}) };
|
||||||
const injectedRelations = [];
|
const maxRounds = options.maxProviderRounds ?? 3;
|
||||||
const missingFacts = [];
|
|
||||||
const partialRelations = [];
|
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)) {
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Fixed-point provider retrieval loop.
|
||||||
|
for (let round = 1; round <= maxRounds; round++) {
|
||||||
|
let newRelationsThisRound = 0;
|
||||||
for (const fact of required) {
|
for (const fact of required) {
|
||||||
|
if (satisfied.has(fact)) continue;
|
||||||
const factMeta = this.relations.get(fact);
|
const factMeta = this.relations.get(fact);
|
||||||
const provider = providers[fact];
|
const provider = providers[fact];
|
||||||
|
if (typeof provider !== 'function') {
|
||||||
|
missingFacts.push({ relation: fact, reason: 'no_provider' });
|
||||||
|
satisfied.add(fact);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let result = null;
|
let result = null;
|
||||||
let error = null;
|
let error = null;
|
||||||
if (typeof provider === 'function') {
|
|
||||||
try {
|
try {
|
||||||
result = await provider(user, object, { relation: fact, params: factMeta.params, runtime: this, options });
|
result = await provider(user, object, {
|
||||||
|
relation: fact,
|
||||||
|
params: factMeta.params,
|
||||||
|
runtime: this,
|
||||||
|
options,
|
||||||
|
round,
|
||||||
|
alreadyInjected: [...satisfied]
|
||||||
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error = err;
|
error = err;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
if (error) {
|
if (error) {
|
||||||
missingFacts.push({ relation: fact, reason: error.message });
|
missingFacts.push({ relation: fact, reason: error.message });
|
||||||
|
satisfied.add(fact);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (result === false || result === null || result === undefined) {
|
if (result === false || result === null || result === undefined) {
|
||||||
missingFacts.push({ relation: fact, reason: 'not_provided' });
|
missingFacts.push({ relation: fact, reason: 'not_provided' });
|
||||||
|
satisfied.add(fact);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const edges = Array.isArray(result) ? result : [result];
|
const edges = Array.isArray(result) ? result : [result];
|
||||||
@@ -365,22 +488,31 @@ export class DSLRuntime {
|
|||||||
// - value fact (2nd param value) -> self-edge on the subject carrying the value
|
// - value fact (2nd param value) -> self-edge on the subject carrying the value
|
||||||
// - binary entity fact -> subject → object
|
// - binary entity fact -> subject → object
|
||||||
const secondParamType = factMeta.params[1] && factMeta.params[1].type;
|
const secondParamType = factMeta.params[1] && factMeta.params[1].type;
|
||||||
const defaultDst = factMeta.params.length >= 2 && this._isPrimitive(secondParamType)
|
const defaultDst = factMeta.params.length >= 2 && this._isValueType(secondParamType)
|
||||||
? user
|
? user
|
||||||
: (factMeta.params.length >= 2 ? object : user);
|
: (factMeta.params.length >= 2 ? object : user);
|
||||||
for (const edge of edges) {
|
for (const edge of edges) {
|
||||||
const normalized = typeof edge === 'boolean' || typeof edge === 'number'
|
const normalized = typeof edge === 'boolean' || typeof edge === 'number'
|
||||||
? { src: user, dst: defaultDst, possibility: edge === true ? 1 : edge }
|
? { src: user, dst: defaultDst, possibility: edge === true ? 1 : edge }
|
||||||
: {
|
: {
|
||||||
|
...(edge.relation ? { relation: edge.relation } : {}),
|
||||||
src: edge.src ?? user,
|
src: edge.src ?? user,
|
||||||
dst: edge.dst ?? defaultDst,
|
dst: edge.dst ?? defaultDst,
|
||||||
possibility: edge.possibility ?? 1,
|
possibility: edge.possibility ?? 1,
|
||||||
...(edge.value !== undefined ? { value: edge.value } : {}),
|
...(edge.value !== undefined ? { value: edge.value } : {}),
|
||||||
...(edge.reliability !== undefined ? { reliability: edge.reliability } : {})
|
...(edge.reliability !== undefined ? { reliability: edge.reliability } : {})
|
||||||
};
|
};
|
||||||
partialRelations.push({ relation: fact, ...normalized });
|
// A provider may return edges for relations other than its own; the
|
||||||
|
// injected relation names satisfy those facts too (fixed point).
|
||||||
|
const injectedRelation = normalized.relation ?? fact;
|
||||||
|
partialRelations.push({ relation: injectedRelation, ...normalized });
|
||||||
|
satisfied.add(injectedRelation);
|
||||||
}
|
}
|
||||||
injectedRelations.push({ relation: fact, edges: edges.length });
|
injectedRelations.push({ relation: fact, edges: edges.length, round });
|
||||||
|
newRelationsThisRound += edges.length;
|
||||||
|
satisfied.add(fact);
|
||||||
|
}
|
||||||
|
if (newRelationsThisRound === 0) break;
|
||||||
}
|
}
|
||||||
|
|
||||||
const checkOptions = { ...options };
|
const checkOptions = { ...options };
|
||||||
@@ -400,4 +532,19 @@ export class DSLRuntime {
|
|||||||
missingFacts
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -81,14 +81,18 @@ describe('Chain step composition', () => {
|
|||||||
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.6);
|
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.6);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects a defeasible/logical evidence as a chain step', () => {
|
it('lowers a logical evidence FINAL step to a condition step', () => {
|
||||||
const { result } = compile(`
|
const { arb, result } = compile(`
|
||||||
${DEFS}
|
${DEFS}
|
||||||
evidence gated(group: Group, doc: Doc) { WHEN can_view(group, doc) UNLESS banned(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) } }
|
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
|
||||||
`);
|
`);
|
||||||
assert.equal(result.success, false);
|
assert.ok(result.success, JSON.stringify(result.errors));
|
||||||
assert.ok(result.errors.some(e => /Chain step 'gated'/.test(e)), 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', () => {
|
it('rejects a mutual cycle through chain steps', () => {
|
||||||
|
|||||||
@@ -188,4 +188,21 @@ describe('DSLRuntime', () => {
|
|||||||
assert.equal(denied.possibility, 0);
|
assert.equal(denied.possibility, 0);
|
||||||
assert.equal(denied.reason, 'defeated_by_unless');
|
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,147 @@
|
|||||||
|
/**
|
||||||
|
* 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/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -34,6 +34,7 @@ const FACTS = `
|
|||||||
fact granted(user: Employee, doc: Doc)
|
fact granted(user: Employee, doc: Doc)
|
||||||
fact group_perm(group: Group, doc: Doc)
|
fact group_perm(group: Group, doc: Doc)
|
||||||
fact banned(user: Employee)
|
fact banned(user: Employee)
|
||||||
|
fact group_banned(group: Group)
|
||||||
fact mfa(user: Employee)
|
fact mfa(user: Employee)
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -128,6 +129,19 @@ function buildProgram(kind, ps) {
|
|||||||
oracle = Math.min(pm, pv);
|
oracle = Math.min(pm, pv);
|
||||||
break;
|
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;
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
throw new Error(`unknown construct: ${kind}`);
|
throw new Error(`unknown construct: ${kind}`);
|
||||||
}
|
}
|
||||||
@@ -163,7 +177,8 @@ function runCheck({ kind, ps }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const CONSTRUCTS = ['direct', 'chain', 'tuple_to_userset', 'fusion_min', 'fusion_max',
|
const CONSTRUCTS = ['direct', 'chain', 'tuple_to_userset', 'fusion_min', 'fusion_max',
|
||||||
'when_unless', 'never_always', 'requires_when', 'composition', 'chain_step_composition'];
|
'when_unless', 'never_always', 'requires_when', 'composition', 'chain_step_composition',
|
||||||
|
'chain_condition_step'];
|
||||||
|
|
||||||
describe('DSL generative oracle parity (rigor)', () => {
|
describe('DSL generative oracle parity (rigor)', () => {
|
||||||
it('generated legal DSL compiles and every check matches the oracle', async () => {
|
it('generated legal DSL compiles and every check matches the oracle', async () => {
|
||||||
@@ -174,7 +189,7 @@ describe('DSL generative oracle parity (rigor)', () => {
|
|||||||
kind: rigor.gen.oneOf(CONSTRUCTS),
|
kind: rigor.gen.oneOf(CONSTRUCTS),
|
||||||
// exactly two edge possibilities (direct uses only the first);
|
// exactly two edge possibilities (direct uses only the first);
|
||||||
// a shorter array would leave pB undefined and produce a NaN oracle
|
// 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))
|
||||||
})
|
})
|
||||||
))
|
))
|
||||||
],
|
],
|
||||||
@@ -192,13 +207,14 @@ describe('DSL generative oracle parity (rigor)', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('exhaustive deterministic sweep: every construct x every possibility value', () => {
|
it('exhaustive deterministic sweep: every construct x every possibility value', () => {
|
||||||
// Anti-vacuity complement to the campaign: sweep the full P × P grid per
|
// Anti-vacuity complement to the campaign: sweep the full P × P × P grid
|
||||||
// construct without any RNG, so a construct the campaign skipped would
|
// per construct without any RNG, so a construct the campaign skipped would
|
||||||
// still be caught here.
|
// still be caught here.
|
||||||
for (const kind of CONSTRUCTS) {
|
for (const kind of CONSTRUCTS) {
|
||||||
for (const a of P) {
|
for (const a of P) {
|
||||||
for (const b 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 { dsl, edges, oracle, relation } = buildProgram(kind, ps);
|
||||||
const arbiter = new Arbiter();
|
const arbiter = new Arbiter();
|
||||||
arbiter.addNode('u:1', 'Employee');
|
arbiter.addNode('u:1', 'Employee');
|
||||||
@@ -215,5 +231,6 @@ describe('DSL generative oracle parity (rigor)', () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -96,14 +96,6 @@ const MUTATIONS = {
|
|||||||
'evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }',
|
'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) }'
|
'fact can_read(user: Employee, doc: Doc)\n evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }'
|
||||||
)
|
)
|
||||||
},
|
|
||||||
non_lowerable_chain_step: {
|
|
||||||
desc: 'a defeasible evidence used as a chain step (cannot lower to an edge)',
|
|
||||||
mustFail: true,
|
|
||||||
apply: () => VALID_DSL.replace(
|
|
||||||
'evidence can_enter(user: Employee, doc: Doc) { member_of(user, *g) { can_access(g, doc) } }',
|
|
||||||
'evidence can_gated(group: Group, doc: Doc) { WHEN can_access(group, doc) UNLESS banned(group) }\n evidence can_enter(user: Employee, doc: Doc) { member_of(user, *g) { can_gated(g, doc) } }'
|
|
||||||
).replace('fact can_access(group: Group, doc: Doc)', 'fact can_access(group: Group, doc: Doc)\n fact banned(group: Group)')
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user