Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2dc478f5a3 | |||
| 88f10f9db4 | |||
| 0a744329e6 | |||
| 0c2ddc282b |
@@ -26,6 +26,8 @@ jobs:
|
|||||||
echo "//hub.kl1.tenere.ai/api/packages/Arbiter/npm/:_authToken=${{ secrets.PACKAGE_TOKEN }}" >> .npmrc
|
echo "//hub.kl1.tenere.ai/api/packages/Arbiter/npm/:_authToken=${{ secrets.PACKAGE_TOKEN }}" >> .npmrc
|
||||||
echo "@tenere:registry=https://hub.kl1.tenere.ai/api/packages/Tenere/npm/" >> .npmrc
|
echo "@tenere:registry=https://hub.kl1.tenere.ai/api/packages/Tenere/npm/" >> .npmrc
|
||||||
echo "//hub.kl1.tenere.ai/api/packages/Tenere/npm/:_authToken=${{ secrets.PACKAGE_TOKEN }}" >> .npmrc
|
echo "//hub.kl1.tenere.ai/api/packages/Tenere/npm/:_authToken=${{ secrets.PACKAGE_TOKEN }}" >> .npmrc
|
||||||
|
echo "@rigor:registry=https://hub.kl1.tenere.ai/api/packages/Rigor/npm/" >> .npmrc
|
||||||
|
echo "//hub.kl1.tenere.ai/api/packages/Rigor/npm/:_authToken=${{ secrets.PACKAGE_TOKEN }}" >> .npmrc
|
||||||
|
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
|
|
||||||
@@ -50,6 +52,8 @@ jobs:
|
|||||||
echo "//hub.kl1.tenere.ai/api/packages/Arbiter/npm/:_authToken=${{ secrets.PACKAGE_TOKEN }}" >> .npmrc
|
echo "//hub.kl1.tenere.ai/api/packages/Arbiter/npm/:_authToken=${{ secrets.PACKAGE_TOKEN }}" >> .npmrc
|
||||||
echo "@tenere:registry=https://hub.kl1.tenere.ai/api/packages/Tenere/npm/" >> .npmrc
|
echo "@tenere:registry=https://hub.kl1.tenere.ai/api/packages/Tenere/npm/" >> .npmrc
|
||||||
echo "//hub.kl1.tenere.ai/api/packages/Tenere/npm/:_authToken=${{ secrets.PACKAGE_TOKEN }}" >> .npmrc
|
echo "//hub.kl1.tenere.ai/api/packages/Tenere/npm/:_authToken=${{ secrets.PACKAGE_TOKEN }}" >> .npmrc
|
||||||
|
echo "@rigor:registry=https://hub.kl1.tenere.ai/api/packages/Rigor/npm/" >> .npmrc
|
||||||
|
echo "//hub.kl1.tenere.ai/api/packages/Rigor/npm/:_authToken=${{ secrets.PACKAGE_TOKEN }}" >> .npmrc
|
||||||
|
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
|
|
||||||
|
|||||||
@@ -2,3 +2,5 @@
|
|||||||
//hub.kl1.tenere.ai/api/packages/Arbiter/npm/:_authToken=${PACKAGE_TOKEN}
|
//hub.kl1.tenere.ai/api/packages/Arbiter/npm/:_authToken=${PACKAGE_TOKEN}
|
||||||
@tenere:registry=https://hub.kl1.tenere.ai/api/packages/Tenere/npm/
|
@tenere:registry=https://hub.kl1.tenere.ai/api/packages/Tenere/npm/
|
||||||
//hub.kl1.tenere.ai/api/packages/Tenere/npm/:_authToken=${PACKAGE_TOKEN}
|
//hub.kl1.tenere.ai/api/packages/Tenere/npm/:_authToken=${PACKAGE_TOKEN}
|
||||||
|
@rigor:registry=https://hub.kl1.tenere.ai/api/packages/Rigor/npm/
|
||||||
|
//hub.kl1.tenere.ai/api/packages/Rigor/npm/:_authToken=${PACKAGE_TOKEN}
|
||||||
|
|||||||
Generated
+269
-6
@@ -1,24 +1,25 @@
|
|||||||
{
|
{
|
||||||
"name": "@arbiter/evidence-dsl",
|
"name": "@arbiter/evidence-dsl",
|
||||||
"version": "1.0.0",
|
"version": "1.1.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@arbiter/evidence-dsl",
|
"name": "@arbiter/evidence-dsl",
|
||||||
"version": "1.0.0",
|
"version": "1.1.0",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@arbiter/core": "^1.0.1"
|
"@arbiter/core": "^1.0.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@rigor/core": "^3.1.0",
|
||||||
"peggy": "^5.0.6"
|
"peggy": "^5.0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@arbiter/core": {
|
"node_modules/@arbiter/core": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.2",
|
||||||
"resolved": "https://hub.kl1.tenere.ai/api/packages/Arbiter/npm/%40arbiter%2Fcore/-/1.0.1/core-1.0.1.tgz",
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Arbiter/npm/%40arbiter%2Fcore/-/1.0.2/core-1.0.2.tgz",
|
||||||
"integrity": "sha512-BfIv6vRKsuJR39WBkBGxl2PQ/LDoW/J1u4UeFrog0AbeTSTvRqhxG1+its2pAcUvcQXq99ZOccFlK3XgNRKt4Q==",
|
"integrity": "sha512-N1duiHy1Rlsxqpvu8uPf4tMaLOQ2tNXvGs53jLkRcIAYqafIAMvcf0BPS2iE2xVKNsqY92+F05bZZEAO5jnbyQ==",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tenere/pltc-core": "^0.6.3",
|
"@tenere/pltc-core": "^0.6.3",
|
||||||
@@ -39,6 +40,268 @@
|
|||||||
"node": ">=20.8"
|
"node": ">=20.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@rigor/analysis": {
|
||||||
|
"version": "0.0.7",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fanalysis/-/0.0.7/analysis-0.0.7.tgz",
|
||||||
|
"integrity": "sha512-CH9g9gU5P+aWZfneL7l91Q8wgZ0kwteYTpOdShqi6VFg2aoOSk4HMl8RTzkO4suxWa2VQ/mMnFJ/TAiHwJOobA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/instrument": "*",
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/artifact": {
|
||||||
|
"version": "0.1.3",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fartifact/-/0.1.3/artifact-0.1.3.tgz",
|
||||||
|
"integrity": "sha512-/SP5veJOpZ7y0dEBYOm+iBKQnBqZbTQzCXGd/LvQvmDtMGL7KJv2UbU7blnWp9CIwD8qU8t9U9c9oKO+qupUcA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/benchmark": {
|
||||||
|
"version": "0.0.6",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fbenchmark/-/0.0.6/benchmark-0.0.6.tgz",
|
||||||
|
"integrity": "sha512-uCCtEhCeY0t81aSgvV1Q7D3cgNU1WufEGJ/vcljhjXnx05hdMWnlK0NPdI/qkWRbRiz+4sSpcGOGO9NBFk7ExQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/artifact": "*",
|
||||||
|
"@rigor/complexity": "*",
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/complexity": {
|
||||||
|
"version": "0.0.7",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fcomplexity/-/0.0.7/complexity-0.0.7.tgz",
|
||||||
|
"integrity": "sha512-RfrkXLykb37WFwmB6OfZoXYMEZJLG78r2HqfDB27jWQmGt5l/4Hb9Zh77dEKl2CsUx2fgd5NafdDl9qFtTE6bg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/core": {
|
||||||
|
"version": "3.1.0",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fcore/-/3.1.0/core-3.1.0.tgz",
|
||||||
|
"integrity": "sha512-gUuq2YuaM0LNjdmHABcRbEW6FvPhO+U1ErokQ6ftPKpPBb38vDc+pPqu7KgGtr3R9NDU3Vj9OBV1Wq9AlzfraA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/analysis": "*",
|
||||||
|
"@rigor/artifact": "*",
|
||||||
|
"@rigor/benchmark": "*",
|
||||||
|
"@rigor/complexity": "*",
|
||||||
|
"@rigor/fault": "*",
|
||||||
|
"@rigor/fuzzer": "*",
|
||||||
|
"@rigor/gen": "*",
|
||||||
|
"@rigor/instrument": "*",
|
||||||
|
"@rigor/linearizability": "*",
|
||||||
|
"@rigor/model": "*",
|
||||||
|
"@rigor/network": "*",
|
||||||
|
"@rigor/probe": "*",
|
||||||
|
"@rigor/prop": "*",
|
||||||
|
"@rigor/reporters": "*",
|
||||||
|
"@rigor/rng": "*",
|
||||||
|
"@rigor/search": "*",
|
||||||
|
"@rigor/shrink": "*",
|
||||||
|
"@rigor/spec": "*",
|
||||||
|
"@rigor/storage": "*",
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/fault": {
|
||||||
|
"version": "0.0.5",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Ffault/-/0.0.5/fault-0.0.5.tgz",
|
||||||
|
"integrity": "sha512-MxzAEk8tx/Nc9CL3dQZZwKXj7eqBgnfTC9dI9TiU9b1u3zW7EIoL28vGqtrr1ucqSTeNwD8BGGAenan2tvb1ZQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/rng": "*",
|
||||||
|
"@rigor/shrink": "*",
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/fuzzer": {
|
||||||
|
"version": "0.0.4",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Ffuzzer/-/0.0.4/fuzzer-0.0.4.tgz",
|
||||||
|
"integrity": "sha512-cJu9bL0GqpkTsIne9PLMcsLtRfBlDz18DqPiarSi+MetH9R0joh7C+fp/e4guo0y+Q2RBJZwulA8gOh9AwgEaQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/artifact": "*",
|
||||||
|
"@rigor/rng": "*",
|
||||||
|
"@rigor/shrink": "*",
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/gen": {
|
||||||
|
"version": "0.0.11",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fgen/-/0.0.11/gen-0.0.11.tgz",
|
||||||
|
"integrity": "sha512-PJG40PtiRJRbNDajdpGaachLYYR+tkSK/0ToIbG5BlG+l/enw7g80hkH674Vw4jeWoftzuwe2NM4dC9rj9rHbg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/rng": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/instrument": {
|
||||||
|
"version": "0.0.5",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Finstrument/-/0.0.5/instrument-0.0.5.tgz",
|
||||||
|
"integrity": "sha512-GXJa6kcEAbd86yM57hR+2g0vcxJlpBfBOoMldWk3mzLmAcCkyYXNSjJekTAwNovfUrtIcnYgQ187Zj3A2d8Tcw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/probe": "*",
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/linearizability": {
|
||||||
|
"version": "0.0.5",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Flinearizability/-/0.0.5/linearizability-0.0.5.tgz",
|
||||||
|
"integrity": "sha512-Ruw+/Zc1hiMfs6i/4qYxYuvUsBtCm5SUmpuXrrixSRglvJ9PYfL/H8xb/Pk3Ve1dFBj8TQN6M3AnwCeaJF2/tg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE"
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/model": {
|
||||||
|
"version": "0.2.13",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fmodel/-/0.2.13/model-0.2.13.tgz",
|
||||||
|
"integrity": "sha512-eZ/888p1zGJGCBFVMA9suvS2mUNX+iHhZn+Uwl9lWa9CSHVRUWH9dTYYB+Qr1hNrCSGIDjV7rOC34wzT+QA4fw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/artifact": "*",
|
||||||
|
"@rigor/complexity": "*",
|
||||||
|
"@rigor/fault": "*",
|
||||||
|
"@rigor/gen": "*",
|
||||||
|
"@rigor/probe": "*",
|
||||||
|
"@rigor/rng": "*",
|
||||||
|
"@rigor/shrink": "*",
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/network": {
|
||||||
|
"version": "0.0.4",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fnetwork/-/0.0.4/network-0.0.4.tgz",
|
||||||
|
"integrity": "sha512-iNmiQA5QiCNkXnjAMPibGYzDk3Lf5hsgwXQGwRcSSVlZNBfVVw5fURzTsNen3TeAnqh9nozJnhD52yp3zdfP6Q==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/fault": "*",
|
||||||
|
"@rigor/rng": "*",
|
||||||
|
"@rigor/scheduler": "*",
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/probe": {
|
||||||
|
"version": "0.0.6",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fprobe/-/0.0.6/probe-0.0.6.tgz",
|
||||||
|
"integrity": "sha512-vUGY6vwciwYqxMaUYa3L2IIwipnnXdPANG8GONx+PrlII2eSbMCjb7BLZGso4yG/iaheRR0JwAnjV8mvtvUOOA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/fault": "*",
|
||||||
|
"@rigor/gen": "*",
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/prop": {
|
||||||
|
"version": "0.0.4",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fprop/-/0.0.4/prop-0.0.4.tgz",
|
||||||
|
"integrity": "sha512-z3+STJPeNpz080ZfFbw5h6LpNFjCNnSymoQPUsjyaSovq3euyJrGx9sqtosVgVVE7Rzld6K4QwchJSJOqIi73w==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/artifact": "*",
|
||||||
|
"@rigor/complexity": "*",
|
||||||
|
"@rigor/gen": "*",
|
||||||
|
"@rigor/probe": "*",
|
||||||
|
"@rigor/rng": "*",
|
||||||
|
"@rigor/shrink": "*",
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/reporters": {
|
||||||
|
"version": "0.0.5",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Freporters/-/0.0.5/reporters-0.0.5.tgz",
|
||||||
|
"integrity": "sha512-+YYfOMlYDsmGIi9rKiJm7ZAptQ0rTeTU1Sp2uVG9UJteuVKW2eKZIC6TeJuM1qvjQmh7/IzBkl3PZVX9pKnYaw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/artifact": "*",
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/rng": {
|
||||||
|
"version": "0.0.3",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Frng/-/0.0.3/rng-0.0.3.tgz",
|
||||||
|
"integrity": "sha512-OFERK5HlI6eV1yUadHoz9n88twqsd/lstAxMzBWFJiN1CCM0xG7IHUYMBCnYK6Di3TTcAarFNFL16Bchm3LrKg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE"
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/scheduler": {
|
||||||
|
"version": "0.0.4",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fscheduler/-/0.0.4/scheduler-0.0.4.tgz",
|
||||||
|
"integrity": "sha512-tY7KASEfufOw4L1vIGeD1bTArCv+zAEPqT/XqiXFz+fckGxY8Nux6zDhGcjkur3qWOUNoWap6KOjSZSORHhXiw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/fault": "*",
|
||||||
|
"@rigor/rng": "*",
|
||||||
|
"@rigor/shrink": "*",
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/search": {
|
||||||
|
"version": "0.1.3",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fsearch/-/0.1.3/search-0.1.3.tgz",
|
||||||
|
"integrity": "sha512-NAq5zbUSc6QQO4YIUFq16+hPtrtkNrjAn75lH/4VDPpbCdQPbKvS6zsQ3v954u1u7I6x2jI5uilpX6/xfr69yA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/gen": "*",
|
||||||
|
"@rigor/shrink": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/shrink": {
|
||||||
|
"version": "0.0.7",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fshrink/-/0.0.7/shrink-0.0.7.tgz",
|
||||||
|
"integrity": "sha512-z0yaZqmyysn40BBqAnqTQlymLuaIIU5u2BijjayX0+XZxhhcPIyvs4PISzJ4nmfkx2yE6qKABe2HHub9wVVUQw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE"
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/spec": {
|
||||||
|
"version": "2.0.1",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fspec/-/2.0.1/spec-2.0.1.tgz",
|
||||||
|
"integrity": "sha512-0/lg19KenJy1e8D87+WqaMRh8Xad4h209/CgK6ofCQapwz/IcriMPHgOZZbHMA4C8G3B6/luVbSVT0EHZoJ8qg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/gen": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/storage": {
|
||||||
|
"version": "0.0.4",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Fstorage/-/0.0.4/storage-0.0.4.tgz",
|
||||||
|
"integrity": "sha512-7XapdgmvEg/C/kERldqFlw3mT1JkpjPMNK6fEcB2Ggx7+UR3ZeE9GyaodJ29my61b28SrQUWxLBHT5bm0bIVaA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE",
|
||||||
|
"dependencies": {
|
||||||
|
"@rigor/fault": "*",
|
||||||
|
"@rigor/rng": "*",
|
||||||
|
"@rigor/scheduler": "*",
|
||||||
|
"@rigor/trace": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@rigor/trace": {
|
||||||
|
"version": "0.0.7",
|
||||||
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Rigor/npm/%40rigor%2Ftrace/-/0.0.7/trace-0.0.7.tgz",
|
||||||
|
"integrity": "sha512-vCLF+WTSdy0pwe9sTonPt8HnNeSkK9U5SAxNpdIeiT+IBP74t9K7JoHMmfo7ka+S0puWecDjjNtWCSqtvKkjNg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "SEE LICENSE IN LICENSE"
|
||||||
|
},
|
||||||
"node_modules/@tenere/graph-core": {
|
"node_modules/@tenere/graph-core": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://hub.kl1.tenere.ai/api/packages/Tenere/npm/%40tenere%2Fgraph-core/-/1.0.1/graph-core-1.0.1.tgz",
|
"resolved": "https://hub.kl1.tenere.ai/api/packages/Tenere/npm/%40tenere%2Fgraph-core/-/1.0.1/graph-core-1.0.1.tgz",
|
||||||
|
|||||||
+4
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@arbiter/evidence-dsl",
|
"name": "@arbiter/evidence-dsl",
|
||||||
"version": "1.0.0",
|
"version": "1.3.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",
|
||||||
@@ -13,6 +13,7 @@
|
|||||||
"./parser/GeneratedParser": "./src/parser/GeneratedParser.js",
|
"./parser/GeneratedParser": "./src/parser/GeneratedParser.js",
|
||||||
"./generator/RuleGenerator": "./src/generator/RuleGenerator.js",
|
"./generator/RuleGenerator": "./src/generator/RuleGenerator.js",
|
||||||
"./validation/DSLValidation": "./src/validation/DSLValidation.js",
|
"./validation/DSLValidation": "./src/validation/DSLValidation.js",
|
||||||
|
"./runtime/DSLRuntime": "./src/runtime/DSLRuntime.js",
|
||||||
"./interpreter/BuiltInFunctions": "./src/interpreter/BuiltInFunctions.js"
|
"./interpreter/BuiltInFunctions": "./src/interpreter/BuiltInFunctions.js"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
@@ -23,9 +24,10 @@
|
|||||||
"generate:parser": "node scripts/generate-parser.js"
|
"generate:parser": "node scripts/generate-parser.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@arbiter/core": "^1.0.1"
|
"@arbiter/core": "^1.0.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@rigor/core": "^3.1.0",
|
||||||
"peggy": "^5.0.6"
|
"peggy": "^5.0.6"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+504
-117
@@ -10,6 +10,7 @@ export class RuleGenerator {
|
|||||||
this.generatedRules = new Map();
|
this.generatedRules = new Map();
|
||||||
this.errors = [];
|
this.errors = [];
|
||||||
this.dependencyIndex = new Map();
|
this.dependencyIndex = new Map();
|
||||||
|
this.evidenceNames = new Set();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -38,6 +39,14 @@ export class RuleGenerator {
|
|||||||
this.generateFactConfig(fact);
|
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
|
// Apply generated rules to arbiter
|
||||||
this.applyRulesToArbiter();
|
this.applyRulesToArbiter();
|
||||||
|
|
||||||
@@ -62,6 +71,7 @@ export class RuleGenerator {
|
|||||||
*/
|
*/
|
||||||
generateEvidenceRules(evidence) {
|
generateEvidenceRules(evidence) {
|
||||||
const relationName = evidence.name;
|
const relationName = evidence.name;
|
||||||
|
this.evidenceNames.add(relationName);
|
||||||
const ruleConfig = this.buildRuleConfig(evidence);
|
const ruleConfig = this.buildRuleConfig(evidence);
|
||||||
|
|
||||||
if (ruleConfig) {
|
if (ruleConfig) {
|
||||||
@@ -162,6 +172,7 @@ export class RuleGenerator {
|
|||||||
for (const child of ruleList) collect(child, targetSet);
|
for (const child of ruleList) collect(child, targetSet);
|
||||||
}
|
}
|
||||||
if (node?.rule) collect(node.rule, targetSet);
|
if (node?.rule) collect(node.rule, targetSet);
|
||||||
|
if (node?.direct) collect(node.direct, targetSet);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -258,41 +269,42 @@ export class RuleGenerator {
|
|||||||
|
|
||||||
// Handle single statement evidence
|
// Handle single statement evidence
|
||||||
if (statements.length === 1) {
|
if (statements.length === 1) {
|
||||||
return this.buildSingleStatementRule(statements[0]);
|
return this.buildSingleStatementRule(statements[0], evidence);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle multiple statements with logical operators
|
// Handle multiple statements with logical operators
|
||||||
return this.buildLogicalRule(statements);
|
return this.buildLogicalRule(statements, evidence);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build rule configuration for a single statement
|
* Build rule configuration for a single statement
|
||||||
* @param {BaseNode} statement - Statement to build rule for
|
* @param {BaseNode} statement - Statement to build rule for
|
||||||
|
* @param {Object} evidence - Evidence definition (params inform pattern/operand lowering)
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildSingleStatementRule(statement) {
|
buildSingleStatementRule(statement, evidence) {
|
||||||
switch (statement.type) {
|
switch (statement.type) {
|
||||||
case 'DirectEvidence':
|
case 'DirectEvidence':
|
||||||
return this.buildDirectRule(statement);
|
return this.buildDirectRule(statement, evidence);
|
||||||
case 'PatternMatch':
|
case 'PatternMatch':
|
||||||
return this.buildPatternMatchRule(statement);
|
return this.buildPatternMatchRule(statement, evidence);
|
||||||
case 'DefeasibleLogic':
|
case 'DefeasibleLogic':
|
||||||
return this.buildDefeasibleRule(statement);
|
return this.buildDefeasibleRule(statement, evidence);
|
||||||
case 'Fusion':
|
case 'Fusion':
|
||||||
return this.buildFusionRule(statement);
|
return this.buildFusionRule(statement);
|
||||||
case 'PredicateCall':
|
case 'PredicateCall':
|
||||||
return this.buildPredicateRule(statement);
|
return this.buildPredicateRule(statement, evidence);
|
||||||
case 'UnaryExpression':
|
case 'UnaryExpression':
|
||||||
return this.buildUnaryRule(statement);
|
return this.buildUnaryRule(statement);
|
||||||
case 'BinaryExpression':
|
case 'BinaryExpression':
|
||||||
// Top-level comparator — emit a relational_comparator rule. RF-24 closure.
|
// Top-level comparator — emit a relational_comparator rule. RF-24 closure.
|
||||||
return this.buildRuleFromExpressionNode(statement);
|
return this.buildRuleFromExpressionNode(statement, evidence);
|
||||||
case 'Expression':
|
case 'Expression':
|
||||||
// Handle expressions that might be predicate calls
|
// Handle expressions that might be predicate calls
|
||||||
if (statement.type === 'PredicateCall') {
|
if (statement.type === 'PredicateCall') {
|
||||||
return this.buildPredicateRule(statement);
|
return this.buildPredicateRule(statement, evidence);
|
||||||
}
|
}
|
||||||
return this.buildRuleFromExpressionNode(statement);
|
return this.buildRuleFromExpressionNode(statement, evidence);
|
||||||
default:
|
default:
|
||||||
this.errors.push(`Unsupported statement type: ${statement.type}`);
|
this.errors.push(`Unsupported statement type: ${statement.type}`);
|
||||||
return null;
|
return null;
|
||||||
@@ -331,11 +343,24 @@ export class RuleGenerator {
|
|||||||
* @param {BaseNode[]} statements - Statements to combine
|
* @param {BaseNode[]} statements - Statements to combine
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildLogicalRule(statements) {
|
buildLogicalRule(statements, evidence) {
|
||||||
|
const defeasible = statements.filter(s => s && s.type === 'DefeasibleLogic');
|
||||||
|
const others = statements.filter(s => s && s.type !== 'DefeasibleLogic');
|
||||||
|
|
||||||
|
// Defeasible levels (NEVER / REQUIRES / ALWAYS / WHEN / UNLESS) form ONE
|
||||||
|
// five-level hierarchy (ADR-000), not separate ANDed rules. A standalone
|
||||||
|
// NEVER-only rule contributes 0 whether or not it fires, so ANDing the
|
||||||
|
// levels separately would always yield 0. Merge all defeasible statements
|
||||||
|
// into a single config; any non-defeasible statements become the base
|
||||||
|
// grant (when) that the defeaters and requirements gate.
|
||||||
|
if (defeasible.length > 0) {
|
||||||
|
return this.buildMergedDefeasibleRule(defeasible, others, evidence);
|
||||||
|
}
|
||||||
|
|
||||||
const rules = [];
|
const rules = [];
|
||||||
|
|
||||||
statements.forEach(statement => {
|
others.forEach(statement => {
|
||||||
const rule = this.buildSingleStatementRule(statement);
|
const rule = this.buildSingleStatementRule(statement, evidence);
|
||||||
if (rule) {
|
if (rule) {
|
||||||
rules.push(rule);
|
rules.push(rule);
|
||||||
}
|
}
|
||||||
@@ -361,12 +386,91 @@ export class RuleGenerator {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merge defeasible-level statements into a single five-level rule config.
|
||||||
|
* The ADR-000 hierarchy is never > requires > strict (always) > when > unless;
|
||||||
|
* each level accumulates its conditions and the whole thing evaluates as one
|
||||||
|
* defeasible rule rather than a conjunction of level-only rules.
|
||||||
|
*/
|
||||||
|
buildMergedDefeasibleRule(defeasibleStatements, otherStatements, evidence) {
|
||||||
|
const neverRules = [];
|
||||||
|
const alwaysRules = [];
|
||||||
|
const requiresRules = [];
|
||||||
|
const whenRules = [];
|
||||||
|
const unlessRules = [];
|
||||||
|
|
||||||
|
for (const st of defeasibleStatements) {
|
||||||
|
const condition = this.buildRuleFromExpression(st.condition, evidence);
|
||||||
|
const defeater = st.defeater ? this.buildRuleFromExpression(st.defeater, evidence) : null;
|
||||||
|
switch (st.logicType) {
|
||||||
|
case 'NEVER':
|
||||||
|
if (condition) neverRules.push(condition);
|
||||||
|
break;
|
||||||
|
case 'ALWAYS':
|
||||||
|
if (condition) alwaysRules.push(condition);
|
||||||
|
break;
|
||||||
|
case 'REQUIRES':
|
||||||
|
if (condition) requiresRules.push(condition);
|
||||||
|
break;
|
||||||
|
case 'WHEN':
|
||||||
|
if (condition) whenRules.push(condition);
|
||||||
|
if (defeater) unlessRules.push(defeater);
|
||||||
|
break;
|
||||||
|
case 'UNLESS':
|
||||||
|
if (condition) unlessRules.push(condition);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
this.errors.push(`Unsupported defeasible logic type: ${st.logicType}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Non-defeasible statements in the same body act as the base grant
|
||||||
|
// (when) that NEVER/REQUIRES/UNLESS gate.
|
||||||
|
if (otherStatements.length > 0) {
|
||||||
|
const baseRules = otherStatements
|
||||||
|
.map(s => this.buildSingleStatementRule(s, evidence))
|
||||||
|
.filter(Boolean);
|
||||||
|
if (baseRules.length === 1) {
|
||||||
|
whenRules.push(baseRules[0]);
|
||||||
|
} else if (baseRules.length > 1) {
|
||||||
|
whenRules.push({
|
||||||
|
type: 'logical',
|
||||||
|
intersection: { rules: baseRules, aggregator: 'min' }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const rule = { type: 'logical' };
|
||||||
|
if (neverRules.length > 0) {
|
||||||
|
rule.never = { union: { rules: neverRules, aggregator: 'max' } };
|
||||||
|
}
|
||||||
|
if (requiresRules.length > 0) {
|
||||||
|
rule.requires = { union: { rules: requiresRules, aggregator: 'min' } };
|
||||||
|
}
|
||||||
|
if (alwaysRules.length > 0) {
|
||||||
|
rule.always = {
|
||||||
|
direct: alwaysRules.length === 1
|
||||||
|
? alwaysRules[0]
|
||||||
|
: { type: 'logical', intersection: { rules: alwaysRules, aggregator: 'min' } },
|
||||||
|
aggregator: 'min'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (whenRules.length > 0) {
|
||||||
|
rule.when = { intersection: { rules: whenRules, aggregator: 'min' } };
|
||||||
|
}
|
||||||
|
if (unlessRules.length > 0) {
|
||||||
|
rule.unless = { union: { rules: unlessRules, aggregator: 'max' } };
|
||||||
|
}
|
||||||
|
|
||||||
|
return rule;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build direct rule configuration
|
* Build direct rule configuration
|
||||||
* @param {DirectEvidenceNode} directEvidence - Direct evidence statement
|
* @param {DirectEvidenceNode} directEvidence - Direct evidence statement
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildDirectRule(directEvidence) {
|
buildDirectRule(directEvidence, evidence) {
|
||||||
if (!directEvidence.predicate) {
|
if (!directEvidence.predicate) {
|
||||||
this.errors.push('Direct evidence must have a predicate');
|
this.errors.push('Direct evidence must have a predicate');
|
||||||
return null;
|
return null;
|
||||||
@@ -375,11 +479,23 @@ export class RuleGenerator {
|
|||||||
const predicate = directEvidence.predicate;
|
const predicate = directEvidence.predicate;
|
||||||
const relation = predicate.name;
|
const relation = predicate.name;
|
||||||
|
|
||||||
return {
|
const rule = {
|
||||||
type: 'direct',
|
type: 'direct',
|
||||||
relation: relation,
|
relation: relation,
|
||||||
reverse: false
|
reverse: false
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Subject-scoped (unary) call: the predicate call's args omit the
|
||||||
|
// evidence's object parameter (user_risk(user, 1) inside a binary
|
||||||
|
// evidence) → check the relation on the subject itself.
|
||||||
|
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 && !(predicate.arguments || []).some(a => argName(a) === objectVar)) {
|
||||||
|
rule._subjectAsObject = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return rule;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -387,7 +503,7 @@ export class RuleGenerator {
|
|||||||
* @param {PatternMatchNode} patternMatch - Pattern match statement
|
* @param {PatternMatchNode} patternMatch - Pattern match statement
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildPatternMatchRule(patternMatch) {
|
buildPatternMatchRule(patternMatch, evidence) {
|
||||||
if (!patternMatch.predicate) {
|
if (!patternMatch.predicate) {
|
||||||
this.errors.push('Pattern match must have a predicate');
|
this.errors.push('Pattern match must have a predicate');
|
||||||
return null;
|
return null;
|
||||||
@@ -396,27 +512,119 @@ export class RuleGenerator {
|
|||||||
const predicate = patternMatch.predicate;
|
const predicate = patternMatch.predicate;
|
||||||
const relation = predicate.name;
|
const relation = predicate.name;
|
||||||
|
|
||||||
// Membership/hierarchy predicates map to TupleToUsersetRule / ParentRule
|
// Structural classification (ADR-000 §Mapping to Engine Rule Types): the
|
||||||
// regardless of body shape — those have priority over chain detection.
|
// two-hop pattern "P(args) { Q(args) }" binds an intermediate via a Wildcard.
|
||||||
|
// The predicate whose args include the OBJECT parameter is the object-side
|
||||||
|
// hop. Object-side = outer → tuple_to_userset (user → computed → intermediate
|
||||||
|
// → tupleset → object). Object-side = inner → chain (user → outer →
|
||||||
|
// intermediate → inner → object). This mirrors Zanzibar's tuple-to-userset
|
||||||
|
// vs. two-hop path semantics and fixes the previous heuristic that routed
|
||||||
|
// every outer-wildcard pattern to chain (owner(*g, doc) { member_of(user, g) }
|
||||||
|
// was emitted as a chain and could never match).
|
||||||
|
const inner = this._singleInnerPredicate(patternMatch);
|
||||||
|
const evidenceParams = (evidence && evidence.params) || [];
|
||||||
|
const userVar = evidenceParams[0] && evidenceParams[0].name;
|
||||||
|
const objectVar = evidenceParams[1] && evidenceParams[1].name;
|
||||||
|
|
||||||
|
// Nested PatternMatch bodies ("P(user, *a) { Q(a, *b) { R(b, doc) } }") are
|
||||||
|
// fixed-length multi-hop PATHS — a chain whose steps are the flattened
|
||||||
|
// predicate sequence [P, Q, R], not transitive-closure multi_hop over one
|
||||||
|
// relation. Chain handles N steps; multi_hop only walks a single relation.
|
||||||
|
if (this._isNestedPattern(patternMatch)) {
|
||||||
|
return this.buildNestedChainRule(patternMatch, inner);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inner) {
|
||||||
|
const argName = a => a && (a.name !== undefined ? a.name : a.value);
|
||||||
|
const outerHasObject = objectVar !== undefined &&
|
||||||
|
(predicate.args || []).some(a => argName(a) === objectVar);
|
||||||
|
const innerHasObject = objectVar !== undefined &&
|
||||||
|
(inner.args || []).some(a => argName(a) === objectVar);
|
||||||
|
|
||||||
|
if (outerHasObject && !innerHasObject) {
|
||||||
|
return this.buildTupleToUsersetRule(patternMatch, inner);
|
||||||
|
}
|
||||||
|
if (innerHasObject && !outerHasObject) {
|
||||||
|
return this.buildChainRule(patternMatch, inner);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: membership/hierarchy naming hints (evidence params unavailable
|
||||||
|
// or both predicates reference the object — keep legacy behavior).
|
||||||
if (this.isMembershipPredicate(predicate)) {
|
if (this.isMembershipPredicate(predicate)) {
|
||||||
return this.buildTupleToUsersetRule(patternMatch);
|
return this.buildTupleToUsersetRule(patternMatch, inner);
|
||||||
}
|
}
|
||||||
if (this.isHierarchyPredicate(predicate)) {
|
if (this.isHierarchyPredicate(predicate)) {
|
||||||
return this.buildParentRule(patternMatch);
|
return this.buildParentRule(patternMatch);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chain detection: ADR-000 ChainRule shape is "works_in(p, *d) { has_access(d, r) }".
|
|
||||||
// The outer PatternMatch has a Wildcard binding, and its body contains a single
|
|
||||||
// PredicateCall (no DefeasibleLogic wrapping, no nested PatternMatch). Treat that
|
|
||||||
// as a chain: two-hop traversal through the wildcard intermediate. RF-24 closure
|
|
||||||
// (parallel to RF-22/RF-23 — DSL→engine mapping gap surfaced by rigor coverage).
|
|
||||||
if (this._isChainPattern(patternMatch)) {
|
if (this._isChainPattern(patternMatch)) {
|
||||||
return this.buildChainRule(patternMatch);
|
return this.buildChainRule(patternMatch, inner);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.buildMultiHopRule(patternMatch);
|
return this.buildMultiHopRule(patternMatch);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract the single inner PredicateCall of a PatternMatch body (null if the
|
||||||
|
* body has multiple statements, is nested, or is wrapped in logic operators).
|
||||||
|
*/
|
||||||
|
_singleInnerPredicate(patternMatch) {
|
||||||
|
if (!patternMatch.body || !Array.isArray(patternMatch.body.statements)) return null;
|
||||||
|
const stmts = patternMatch.body.statements;
|
||||||
|
if (stmts.length !== 1) return null;
|
||||||
|
if (stmts[0].type === 'PredicateCall') return stmts[0];
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when the PatternMatch body is itself a nested PatternMatch
|
||||||
|
* ("P(user, *a) { Q(a, *b) { R(b, doc) } }") — a multi-hop path.
|
||||||
|
*/
|
||||||
|
_isNestedPattern(patternMatch) {
|
||||||
|
if (!patternMatch.body || !Array.isArray(patternMatch.body.statements)) return false;
|
||||||
|
const stmts = patternMatch.body.statements;
|
||||||
|
return stmts.length === 1 && stmts[0].type === 'PatternMatch';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flatten a nested PatternMatch into its linear predicate sequence
|
||||||
|
* [P, Q, ..., R] where R is the object-side hop.
|
||||||
|
*/
|
||||||
|
_flattenPatternSteps(patternMatch, acc = []) {
|
||||||
|
const predicate = patternMatch.predicate;
|
||||||
|
if (!predicate || !predicate.name) return acc;
|
||||||
|
acc.push(predicate.name);
|
||||||
|
if (patternMatch.body && Array.isArray(patternMatch.body.statements) &&
|
||||||
|
patternMatch.body.statements.length === 1) {
|
||||||
|
const child = patternMatch.body.statements[0];
|
||||||
|
if (child && child.type === 'PredicateCall' && child.name) {
|
||||||
|
acc.push(child.name);
|
||||||
|
} else if (child && child.type === 'PatternMatch') {
|
||||||
|
this._flattenPatternSteps(child, acc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return acc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a chain rule from a nested (multi-hop path) PatternMatch.
|
||||||
|
* "P(user, *a) { Q(a, *b) { R(b, doc) } }" → { type: 'chain', steps: [P, Q, R] }.
|
||||||
|
*/
|
||||||
|
buildNestedChainRule(patternMatch) {
|
||||||
|
const steps = this._flattenPatternSteps(patternMatch);
|
||||||
|
if (steps.length < 2) {
|
||||||
|
this.errors.push('Nested pattern match must yield at least two steps');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
type: 'chain',
|
||||||
|
steps,
|
||||||
|
aggregator: 'max',
|
||||||
|
collectValues: true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Detect the ChainRule shape: a PatternMatch whose body contains exactly one
|
* Detect the ChainRule shape: a PatternMatch whose body contains exactly one
|
||||||
* PredicateCall and uses a Wildcard arg to bind the intermediate. The predicate
|
* PredicateCall and uses a Wildcard arg to bind the intermediate. The predicate
|
||||||
@@ -435,17 +643,19 @@ export class RuleGenerator {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Build chain rule configuration (ADR-000 ChainRule).
|
* Build chain rule configuration (ADR-000 ChainRule).
|
||||||
* Compiles "works_in(p, *d) { has_access(d, doc) }" into
|
* Compiles "works_in(user, *d) { has_access(d, doc) }" into
|
||||||
* { type: 'chain', steps: ['works_in', 'has_access'] }
|
* { type: 'chain', steps: ['works_in', 'has_access'] }
|
||||||
* The intermediate wildcard binds the two predicates' arguments.
|
* The intermediate wildcard binds the two predicates' arguments. Step order is
|
||||||
|
* [userSide, objectSide]: the outer predicate connects user → intermediate,
|
||||||
|
* the inner predicate connects intermediate → object.
|
||||||
*/
|
*/
|
||||||
buildChainRule(patternMatch) {
|
buildChainRule(patternMatch, inner) {
|
||||||
const steps = [];
|
const steps = [];
|
||||||
steps.push(patternMatch.predicate.name);
|
steps.push(patternMatch.predicate.name);
|
||||||
|
|
||||||
const inner = patternMatch.body.statements[0];
|
const innerPredicate = inner || (patternMatch.body.statements[0]);
|
||||||
if (inner && inner.type === 'PredicateCall' && inner.name) {
|
if (innerPredicate && innerPredicate.type === 'PredicateCall' && innerPredicate.name) {
|
||||||
steps.push(inner.name);
|
steps.push(innerPredicate.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -457,18 +667,31 @@ export class RuleGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build tuple-to-userset rule configuration
|
* Build tuple-to-userset rule configuration (ADR-000 TupleToUsersetRule).
|
||||||
* @param {PatternMatchNode} patternMatch - Pattern match statement
|
* Compiles "owner(*g, doc) { member_of(user, g) }" into
|
||||||
* @returns {Object|null} Rule configuration or null
|
* {
|
||||||
|
* type: 'tuple_to_userset',
|
||||||
|
* tuplesetRelation: 'owner', // object-side hop: intermediate → object
|
||||||
|
* computedRelation: 'member_of', // user-side hop: user → intermediate
|
||||||
|
* tuplesetDirection: 'in', // intermediates hold the tupleset edge TO the object
|
||||||
|
* reverse: false
|
||||||
|
* }
|
||||||
|
* The tupleset edge direction follows the wildcard position in the outer
|
||||||
|
* predicate: wildcard as first arg (owner(*g, doc)) means the intermediate is
|
||||||
|
* the edge source ('in' — fetch edges with dst = object); wildcard as second
|
||||||
|
* arg (owner(doc, *g)) means the object is the source ('out').
|
||||||
*/
|
*/
|
||||||
buildTupleToUsersetRule(patternMatch) {
|
buildTupleToUsersetRule(patternMatch, inner) {
|
||||||
const predicate = patternMatch.predicate;
|
const predicate = patternMatch.predicate;
|
||||||
const relation = predicate.name;
|
const relation = predicate.name;
|
||||||
|
const computedRelation = inner && inner.name ? inner.name : relation;
|
||||||
|
const wildcardIndex = (predicate.args || []).findIndex(a => a && a.type === 'Wildcard');
|
||||||
|
|
||||||
return {
|
return {
|
||||||
type: 'tuple_to_userset',
|
type: 'tuple_to_userset',
|
||||||
tuplesetRelation: 'owner', // Default, could be inferred from context
|
tuplesetRelation: relation,
|
||||||
computedRelation: relation,
|
computedRelation,
|
||||||
|
tuplesetDirection: wildcardIndex === 0 ? 'in' : 'out',
|
||||||
reverse: false,
|
reverse: false,
|
||||||
earlyExitThreshold: 0.95,
|
earlyExitThreshold: 0.95,
|
||||||
maxIntermediates: patternMatch.limit || 10
|
maxIntermediates: patternMatch.limit || 10
|
||||||
@@ -518,19 +741,19 @@ export class RuleGenerator {
|
|||||||
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
|
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildDefeasibleRule(defeasibleLogic) {
|
buildDefeasibleRule(defeasibleLogic, evidence) {
|
||||||
const logicType = defeasibleLogic.logicType;
|
const logicType = defeasibleLogic.logicType;
|
||||||
|
|
||||||
if (logicType === 'NEVER') {
|
if (logicType === 'NEVER') {
|
||||||
return this.buildNeverRule(defeasibleLogic);
|
return this.buildNeverRule(defeasibleLogic, evidence);
|
||||||
} else if (logicType === 'ALWAYS') {
|
} else if (logicType === 'ALWAYS') {
|
||||||
return this.buildStrictRule(defeasibleLogic);
|
return this.buildStrictRule(defeasibleLogic, evidence);
|
||||||
} else if (logicType === 'WHEN') {
|
} else if (logicType === 'WHEN') {
|
||||||
return this.buildDefeasibleRuleWithDefeater(defeasibleLogic);
|
return this.buildDefeasibleRuleWithDefeater(defeasibleLogic, evidence);
|
||||||
} else if (logicType === 'UNLESS') {
|
} else if (logicType === 'UNLESS') {
|
||||||
return this.buildDefeaterRule(defeasibleLogic);
|
return this.buildDefeaterRule(defeasibleLogic, evidence);
|
||||||
} else if (logicType === 'REQUIRES') {
|
} else if (logicType === 'REQUIRES') {
|
||||||
return this.buildRequirementRule(defeasibleLogic);
|
return this.buildRequirementRule(defeasibleLogic, evidence);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.errors.push(`Unsupported defeasible logic type: ${logicType}`);
|
this.errors.push(`Unsupported defeasible logic type: ${logicType}`);
|
||||||
@@ -542,8 +765,8 @@ export class RuleGenerator {
|
|||||||
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
|
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildNeverRule(defeasibleLogic) {
|
buildNeverRule(defeasibleLogic, evidence) {
|
||||||
const condition = this.buildRuleFromExpression(defeasibleLogic.condition);
|
const condition = this.buildRuleFromExpression(defeasibleLogic.condition, evidence);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
type: 'logical',
|
type: 'logical',
|
||||||
@@ -561,8 +784,8 @@ export class RuleGenerator {
|
|||||||
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
|
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildStrictRule(defeasibleLogic) {
|
buildStrictRule(defeasibleLogic, evidence) {
|
||||||
const condition = this.buildRuleFromExpression(defeasibleLogic.condition);
|
const condition = this.buildRuleFromExpression(defeasibleLogic.condition, evidence);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
type: 'logical',
|
type: 'logical',
|
||||||
@@ -578,9 +801,9 @@ export class RuleGenerator {
|
|||||||
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
|
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildDefeasibleRuleWithDefeater(defeasibleLogic) {
|
buildDefeasibleRuleWithDefeater(defeasibleLogic, evidence) {
|
||||||
const condition = this.buildRuleFromExpression(defeasibleLogic.condition);
|
const condition = this.buildRuleFromExpression(defeasibleLogic.condition, evidence);
|
||||||
const defeater = this.buildRuleFromExpression(defeasibleLogic.defeater);
|
const defeater = this.buildRuleFromExpression(defeasibleLogic.defeater, evidence);
|
||||||
|
|
||||||
const rule = {
|
const rule = {
|
||||||
type: 'logical',
|
type: 'logical',
|
||||||
@@ -609,8 +832,8 @@ export class RuleGenerator {
|
|||||||
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
|
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildDefeaterRule(defeasibleLogic) {
|
buildDefeaterRule(defeasibleLogic, evidence) {
|
||||||
const condition = this.buildRuleFromExpression(defeasibleLogic.condition);
|
const condition = this.buildRuleFromExpression(defeasibleLogic.condition, evidence);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
type: 'logical',
|
type: 'logical',
|
||||||
@@ -628,8 +851,8 @@ export class RuleGenerator {
|
|||||||
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
|
* @param {DefeasibleLogicNode} defeasibleLogic - Defeasible logic statement
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildRequirementRule(defeasibleLogic) {
|
buildRequirementRule(defeasibleLogic, evidence) {
|
||||||
const condition = this.buildRuleFromExpression(defeasibleLogic.condition);
|
const condition = this.buildRuleFromExpression(defeasibleLogic.condition, evidence);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
type: 'logical',
|
type: 'logical',
|
||||||
@@ -698,19 +921,21 @@ export class RuleGenerator {
|
|||||||
* @param {BaseNode} expression - Expression to build rule from
|
* @param {BaseNode} expression - Expression to build rule from
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildRuleFromExpression(expression) {
|
buildRuleFromExpression(expression, evidence) {
|
||||||
if (!expression) {
|
if (!expression) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (expression.type === 'Predicate') {
|
if (expression.type === 'Predicate') {
|
||||||
return this.buildDirectRuleFromPredicate(expression);
|
return this.buildDirectRuleFromPredicate(expression, evidence);
|
||||||
} else if (expression.type === 'Expression') {
|
} else if (expression.type === 'Expression') {
|
||||||
return this.buildRuleFromExpressionNode(expression);
|
return this.buildRuleFromExpressionNode(expression, evidence);
|
||||||
} else if (expression.type === 'PredicateCall') {
|
} else if (expression.type === 'PredicateCall') {
|
||||||
return this.buildPredicateRule(expression);
|
return this.buildPredicateRule(expression, evidence);
|
||||||
} else if (expression.type === 'UnaryExpression') {
|
} else if (expression.type === 'UnaryExpression') {
|
||||||
return this.buildUnaryRule(expression);
|
return this.buildUnaryRule(expression);
|
||||||
|
} else if (expression.type === 'BinaryExpression') {
|
||||||
|
return this.buildRuleFromExpressionNode(expression, evidence);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.errors.push(`Unsupported expression type: ${expression.type}`);
|
this.errors.push(`Unsupported expression type: ${expression.type}`);
|
||||||
@@ -722,47 +947,175 @@ export class RuleGenerator {
|
|||||||
* @param {PredicateNode} predicate - Predicate to build rule from
|
* @param {PredicateNode} predicate - Predicate to build rule from
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildDirectRuleFromPredicate(predicate) {
|
buildDirectRuleFromPredicate(predicate, evidence) {
|
||||||
const expanded = this._expandPredicate(predicate.name);
|
const rule = {
|
||||||
if (expanded) return expanded;
|
|
||||||
|
|
||||||
return {
|
|
||||||
type: 'direct',
|
type: 'direct',
|
||||||
relation: predicate.name,
|
relation: predicate.name,
|
||||||
reverse: false
|
reverse: false
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const evidenceParams = (evidence && evidence.params) || [];
|
||||||
|
const objectVar = evidenceParams[1] && evidenceParams[1].name;
|
||||||
|
if (objectVar !== undefined && !(predicate.args || []).some(a =>
|
||||||
|
a && a.type === 'Variable' && a.name === objectVar)) {
|
||||||
|
rule._subjectAsObject = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
_expandPredicate(predicateName) {
|
return rule;
|
||||||
const existingConfig = this.generatedRules.get(predicateName) || this.arbiter?.relationConfigs?.get(predicateName);
|
}
|
||||||
if (!existingConfig) return null;
|
|
||||||
if (!existingConfig.union && !existingConfig.intersection && !existingConfig.exclusion) return null;
|
|
||||||
|
|
||||||
const logicalKey = existingConfig.union ? 'union' : existingConfig.intersection ? 'intersection' : 'exclusion';
|
_expandPredicate() {
|
||||||
const subRules = Array.isArray(existingConfig[logicalKey]?.rules)
|
// Replaced by resolveEvidenceReferences() (the compile-time evidence
|
||||||
? existingConfig[logicalKey].rules
|
// composition pass). Predicate references are now emitted as direct rules
|
||||||
: Array.isArray(existingConfig[logicalKey]) ? existingConfig[logicalKey] : [];
|
// and inlined during resolution, which also handles forward references and
|
||||||
|
// preserves the correct _subjectAsObject scoping.
|
||||||
|
}
|
||||||
|
|
||||||
if (subRules.length === 0) return null;
|
/**
|
||||||
|
* 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const expandedRules = subRules.map(r => {
|
/**
|
||||||
if (r && r.type === 'direct') return { type: 'direct', relation: r.relation, reverse: !!r.reverse };
|
* Recursively rewrite a rule tree, inlining references to derived evidence
|
||||||
if (typeof r === 'string') return { type: 'direct', relation: r, reverse: false };
|
* configs. `stack` holds the evidence names currently being expanded so a
|
||||||
return null;
|
* cyclic reference (A → B → A) is detected and reported.
|
||||||
}).filter(Boolean);
|
*/
|
||||||
|
_resolveRule(rule, stack) {
|
||||||
|
if (!rule || typeof rule !== 'object') return rule;
|
||||||
|
if (Array.isArray(rule)) return rule.map(r => this._resolveRule(r, stack));
|
||||||
|
|
||||||
if (expandedRules.length === 0) return null;
|
// 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;
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
// Recurse into logical / defeasible / nested containers: rule-lists
|
||||||
type: 'logical',
|
// (union/intersection/exclusion/never/requires/when/unless .rules) and
|
||||||
[logicalKey]: {
|
// single nested rules (always.direct, comparator operands).
|
||||||
rules: expandedRules,
|
const out = { ...rule };
|
||||||
aggregator: existingConfig[logicalKey]?.aggregator || 'min'
|
for (const key of ['union', 'intersection', 'exclusion', 'never', 'always', 'requires', 'when', 'unless', 'direct', 'rule']) {
|
||||||
},
|
const node = out[key];
|
||||||
// Flag to tell the evaluator: this expanded sub-predicate is unary —
|
if (!node || typeof node !== 'object') continue;
|
||||||
// use the subject as the object instead of inheriting the parent's object.
|
if (Array.isArray(node)) {
|
||||||
_subjectAsObject: true
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
* - anything else (defeasible/logical/comparator) → compile error: such a
|
||||||
|
* step is a condition, not an edge traversal, and cannot lower to a flat
|
||||||
|
* chain step.
|
||||||
|
*/
|
||||||
|
_expandChainSteps(steps, stack) {
|
||||||
|
const out = [];
|
||||||
|
for (const step of steps) {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
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.');
|
||||||
|
out.push(step);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(step);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
_deepCloneRule(rule) {
|
||||||
|
try {
|
||||||
|
return structuredClone(rule);
|
||||||
|
} catch {
|
||||||
|
return JSON.parse(JSON.stringify(rule));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -770,7 +1123,7 @@ export class RuleGenerator {
|
|||||||
* @param {ExpressionNode} expression - Expression to build rule from
|
* @param {ExpressionNode} expression - Expression to build rule from
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildRuleFromExpressionNode(expression) {
|
buildRuleFromExpressionNode(expression, evidence) {
|
||||||
if (expression.type === 'AttributeAccess') {
|
if (expression.type === 'AttributeAccess') {
|
||||||
return this.buildAttributeRule(expression);
|
return this.buildAttributeRule(expression);
|
||||||
} else if (expression.type === 'PredicateCall') {
|
} else if (expression.type === 'PredicateCall') {
|
||||||
@@ -782,7 +1135,7 @@ export class RuleGenerator {
|
|||||||
// Route BinaryExpression with comparator operators here so the
|
// Route BinaryExpression with comparator operators here so the
|
||||||
// evaluator can run a fuzzy interval comparison instead of treating
|
// evaluator can run a fuzzy interval comparison instead of treating
|
||||||
// them as logical truth values. RF-24 closure.
|
// them as logical truth values. RF-24 closure.
|
||||||
return this.buildRelationalComparatorRule(expression);
|
return this.buildRelationalComparatorRule(expression, evidence);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.errors.push(`Unsupported expression type: ${expression.type}`);
|
this.errors.push(`Unsupported expression type: ${expression.type}`);
|
||||||
@@ -812,10 +1165,10 @@ export class RuleGenerator {
|
|||||||
* minRulePossibility: 0
|
* minRulePossibility: 0
|
||||||
* }
|
* }
|
||||||
*/
|
*/
|
||||||
buildRelationalComparatorRule(binaryExpression) {
|
buildRelationalComparatorRule(binaryExpression, evidence) {
|
||||||
const comparator = binaryExpression.operator;
|
const comparator = binaryExpression.operator;
|
||||||
const left = this._buildComparatorOperand(binaryExpression.left);
|
const left = this._buildComparatorOperand(binaryExpression.left, evidence);
|
||||||
const right = this._buildComparatorOperand(binaryExpression.right);
|
const right = this._buildComparatorOperand(binaryExpression.right, evidence);
|
||||||
if (!left || !right) {
|
if (!left || !right) {
|
||||||
this.errors.push(`Comparator operands must resolve to predicate calls (operator=${comparator})`);
|
this.errors.push(`Comparator operands must resolve to predicate calls (operator=${comparator})`);
|
||||||
return null;
|
return null;
|
||||||
@@ -833,29 +1186,52 @@ export class RuleGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Wrap a BinaryExpression side into a relational_comparator operand. The
|
* Lower a comparator operand to a core-evaluable config. The operand's `rule`
|
||||||
* operand's `rule` field is the original predicate call (preserving reference
|
* MUST be a real rule configuration (the engine's RuleEvaluator only accepts
|
||||||
* semantics so the inner rule's evaluator can resolve its values). `extractValue`
|
* configs — raw AST nodes evaluate to 0). Per the core's operand contract:
|
||||||
* tells the evaluator to read the relation's `value` field rather than its
|
*
|
||||||
* `possibility`, which is what `personAge(p)` / `docMinAge(d)` semantics require.
|
* userRisk(user) → { rule: { type: 'direct', relation: 'userRisk' }, extractValue: true } (user perspective, auto)
|
||||||
|
* riskLimit(doc) → { rule: { type: 'direct', relation: 'riskLimit' }, extractValue: true, evaluateFrom: 'object' }
|
||||||
|
*
|
||||||
|
* The evaluateFrom side is derived from the evidence parameter positions:
|
||||||
|
* params[0] is the subject (user), params[1] is the object. A predicate call
|
||||||
|
* whose first arg is the object variable reads its value from the object
|
||||||
|
* perspective; anything else defaults to the user perspective.
|
||||||
|
*
|
||||||
|
* Literal value args (userRisk(user, 5)) annotate the operand with
|
||||||
|
* `expectedValue` — the declared value the caller expects the relation to
|
||||||
|
* carry. The engine compares resolved relation values; the DSLRuntime wrapper
|
||||||
|
* may enforce expectedValue as an additional gate.
|
||||||
*/
|
*/
|
||||||
_buildComparatorOperand(side) {
|
_buildComparatorOperand(side, evidence) {
|
||||||
if (!side) return null;
|
if (!side) return null;
|
||||||
if (side.type === 'PredicateCall') {
|
if (side.type === 'PredicateCall') {
|
||||||
return {
|
const operand = {
|
||||||
rule: side,
|
rule: { type: 'direct', relation: side.name, reverse: false },
|
||||||
extractValue: true,
|
|
||||||
evaluatorFrom: 'auto'
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (side.type === 'AttributeAccess') {
|
|
||||||
// user.age — treat the attribute path as a "measure" reference
|
|
||||||
return {
|
|
||||||
rule: side,
|
|
||||||
extractValue: true,
|
extractValue: true,
|
||||||
evaluatorFrom: 'auto',
|
evaluatorFrom: 'auto',
|
||||||
attributePath: side.getAttributePath ? side.getAttributePath() : null
|
valueRelation: side.name
|
||||||
};
|
};
|
||||||
|
const evidenceParams = (evidence && evidence.params) || [];
|
||||||
|
const userVar = evidenceParams[0] && evidenceParams[0].name;
|
||||||
|
const objectVar = evidenceParams[1] && evidenceParams[1].name;
|
||||||
|
const firstArg = (side.args || [])[0];
|
||||||
|
const firstArgName = firstArg && (firstArg.name !== undefined ? firstArg.name : firstArg.value);
|
||||||
|
if (objectVar !== undefined && firstArgName === objectVar) {
|
||||||
|
operand.evaluateFrom = 'object';
|
||||||
|
}
|
||||||
|
const literalArg = (side.args || []).find(a => a && a.type === 'Literal');
|
||||||
|
if (literalArg) {
|
||||||
|
operand.expectedValue = literalArg.value;
|
||||||
|
}
|
||||||
|
return operand;
|
||||||
|
}
|
||||||
|
if (side.type === 'AttributeAccess') {
|
||||||
|
// Attribute paths cannot lower to a relation config — the engine's
|
||||||
|
// operand machinery reads relation `value` fields, not node attributes.
|
||||||
|
// Reject loudly instead of emitting an unevaluable rule.
|
||||||
|
this.errors.push('Comparator operands cannot be attribute accesses (use a value-carrying relation instead)');
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -880,22 +1256,33 @@ export class RuleGenerator {
|
|||||||
* @param {ExpressionNode} expression - Function expression
|
* @param {ExpressionNode} expression - Function expression
|
||||||
* @returns {Object|null} Rule configuration or null
|
* @returns {Object|null} Rule configuration or null
|
||||||
*/
|
*/
|
||||||
buildPredicateRule(expression) {
|
buildPredicateRule(expression, evidence) {
|
||||||
const predicateName = expression.name;
|
const predicateName = expression.name;
|
||||||
if (expression.challenge) {
|
if (expression.challenge) {
|
||||||
return this.buildChallengeRule(expression, null);
|
return this.buildChallengeRule(expression, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Expand composite (logical) predicate references into their direct
|
const rule = {
|
||||||
// leaf components so the optimizer can flatten to a correct direct_list.
|
|
||||||
const expanded = this._expandPredicate(predicateName);
|
|
||||||
if (expanded) return expanded;
|
|
||||||
|
|
||||||
return {
|
|
||||||
type: 'direct',
|
type: 'direct',
|
||||||
relation: predicateName,
|
relation: predicateName,
|
||||||
reverse: false
|
reverse: false
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Subject-scoped (unary) predicate call: the call's variable args omit the
|
||||||
|
// evidence's object parameter (banned(user) inside can_open(user, doc)).
|
||||||
|
// Mark _subjectAsObject so the engine checks the relation on the subject
|
||||||
|
// itself — the unary fact's self-edge — instead of (subject, object).
|
||||||
|
const evidenceParams = (evidence && evidence.params) || [];
|
||||||
|
const objectVar = evidenceParams[1] && evidenceParams[1].name;
|
||||||
|
if (objectVar !== undefined) {
|
||||||
|
const hasObjectArg = (expression.args || []).some(a =>
|
||||||
|
a && a.type === 'Variable' && a.name === objectVar);
|
||||||
|
if (!hasObjectArg) {
|
||||||
|
rule._subjectAsObject = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return rule;
|
||||||
}
|
}
|
||||||
|
|
||||||
buildWithinRule(expression) {
|
buildWithinRule(expression) {
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ export { RuleGenerator } from './generator/RuleGenerator.js';
|
|||||||
// Validation
|
// Validation
|
||||||
export { validateDslText } from './validation/DSLValidation.js';
|
export { validateDslText } from './validation/DSLValidation.js';
|
||||||
|
|
||||||
|
// Runtime
|
||||||
|
export { DSLRuntime } from './runtime/DSLRuntime.js';
|
||||||
|
|
||||||
// All AST nodes
|
// All AST nodes
|
||||||
export * from './nodes/index.js';
|
export * from './nodes/index.js';
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,403 @@
|
|||||||
|
import { DSLCompiler } from '../DSLCompiler.js';
|
||||||
|
|
||||||
|
const PRIMITIVE_TYPES = new Set(['string', 'number', 'boolean']);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DSLRuntime — higher-order wrapper combining the Evidence DSL with an
|
||||||
|
* @arbiter/core Arbiter.
|
||||||
|
*
|
||||||
|
* The DSL declares a typed schema: `definition` blocks (entity types with
|
||||||
|
* typed fields), `fact` declarations (relations with typed params, optional
|
||||||
|
* `*` injectable marker), and `evidence` rules (relations the runtime can
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* Trust boundary follows the core: caller-supplied evidence (partial graph /
|
||||||
|
* provider results) is trusted, never policed; only structure is validated.
|
||||||
|
*/
|
||||||
|
export class DSLRuntime {
|
||||||
|
/**
|
||||||
|
* @param {object} arbiter - An @arbiter/core Arbiter instance.
|
||||||
|
* @param {object} options
|
||||||
|
* @param {object} options.factProviders - relation → async fn(subject, object, ctx)
|
||||||
|
* returning a boolean, possibility number, { possibility, value }, or an
|
||||||
|
* array of { src, relation, dst, possibility, value } partial-graph edges.
|
||||||
|
* @param {object} options.policy
|
||||||
|
* @param {boolean} options.policy.strictTypes - throw on unknown types/relations
|
||||||
|
* (default true; false degrades to arbiter behavior for undeclared names).
|
||||||
|
*/
|
||||||
|
constructor(arbiter, options = {}) {
|
||||||
|
this.arbiter = arbiter;
|
||||||
|
this.compiler = new DSLCompiler(this.arbiter);
|
||||||
|
this.factProviders = options.factProviders || {};
|
||||||
|
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.dependsOn = new Map(); // evidence relation -> Set(fact relations)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compile a DSL program and index its schema. Returns this for chaining.
|
||||||
|
* @param {string} dsl
|
||||||
|
* @param {string} name
|
||||||
|
*/
|
||||||
|
compile(dsl, name) {
|
||||||
|
const result = this.compiler.compile(dsl, name);
|
||||||
|
if (!result.success) {
|
||||||
|
const error = new Error(`DSLRuntime compile failed: ${(result.errors || []).join('; ')}`);
|
||||||
|
error.errors = result.errors || [];
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
this.program = result.program;
|
||||||
|
this._indexSchema();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
_indexSchema() {
|
||||||
|
this.types.clear();
|
||||||
|
this.relations.clear();
|
||||||
|
this.dependsOn.clear();
|
||||||
|
|
||||||
|
for (const def of this.program.definitions || []) {
|
||||||
|
const fields = new Map();
|
||||||
|
for (const field of def.fields || []) {
|
||||||
|
fields.set(field.name, { type: field.fieldType, isArray: !!field.isArray });
|
||||||
|
}
|
||||||
|
this.types.set(def.name, { fields });
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const fact of this.program.facts || []) {
|
||||||
|
this.relations.set(fact.name, {
|
||||||
|
kind: 'fact',
|
||||||
|
params: (fact.params || []).map(p => ({ name: p.name, type: p.paramType, isArray: !!p.isArray })),
|
||||||
|
injectable: !!fact.injectable
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const ev of this.program.evidence || []) {
|
||||||
|
this.relations.set(ev.name, {
|
||||||
|
kind: 'evidence',
|
||||||
|
params: (ev.params || []).map(p => ({ name: p.name, type: p.paramType, isArray: !!p.isArray })),
|
||||||
|
injectable: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Index each evidence's fact dependencies from the compiled arbiter configs.
|
||||||
|
for (const ev of this.program.evidence || []) {
|
||||||
|
const config = this.arbiter.relationConfigs.get(ev.name);
|
||||||
|
const deps = new Set();
|
||||||
|
const collect = (rule) => {
|
||||||
|
if (!rule || typeof rule !== 'object') return;
|
||||||
|
if (rule.type === 'direct' && rule.relation) deps.add(rule.relation);
|
||||||
|
if (rule.type === 'tuple_to_userset') {
|
||||||
|
if (rule.tuplesetRelation) deps.add(rule.tuplesetRelation);
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
if (rule.type === 'parent' && rule.parentRelation) deps.add(rule.parentRelation);
|
||||||
|
if (rule.type === 'multi_hop' && rule.relation) deps.add(rule.relation);
|
||||||
|
if (rule.type === 'relational_comparator') {
|
||||||
|
collect(rule.left?.rule);
|
||||||
|
collect(rule.right?.rule);
|
||||||
|
if (rule.left?.valueRelation) deps.add(rule.left.valueRelation);
|
||||||
|
if (rule.right?.valueRelation) deps.add(rule.right.valueRelation);
|
||||||
|
}
|
||||||
|
for (const key of ['union', 'intersection', 'exclusion', 'never', 'always', 'requires', 'when', 'unless']) {
|
||||||
|
const node = rule[key];
|
||||||
|
if (!node) continue;
|
||||||
|
if (Array.isArray(node.rules)) for (const c of node.rules) collect(c);
|
||||||
|
if (Array.isArray(node.union?.rules)) for (const c of node.union.rules) collect(c);
|
||||||
|
if (Array.isArray(node.intersection?.rules)) for (const c of node.intersection.rules) collect(c);
|
||||||
|
if (node.direct) collect(node.direct);
|
||||||
|
if (node.rule) collect(node.rule);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (config && Array.isArray(config.dependsOn)) {
|
||||||
|
for (const d of config.dependsOn) deps.add(d);
|
||||||
|
} else {
|
||||||
|
collect(config);
|
||||||
|
}
|
||||||
|
this.dependsOn.set(ev.name, deps);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Schema validation helpers
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
_isPrimitive(typeName) {
|
||||||
|
return PRIMITIVE_TYPES.has(typeName);
|
||||||
|
}
|
||||||
|
|
||||||
|
_nodeType(key) {
|
||||||
|
const nodeId = this.arbiter.resolveNodeId(key);
|
||||||
|
if (nodeId === undefined) return null;
|
||||||
|
const node = this.arbiter.nodes.get(nodeId);
|
||||||
|
return node ? node.type : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
_checkNodeExists(key, position) {
|
||||||
|
if (!this.arbiter.nodeIdByKey.has(key)) {
|
||||||
|
throw new Error(`DSLRuntime: ${position} node '${key}' does not exist`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_checkNodeType(key, expectedType, position) {
|
||||||
|
if (this._isPrimitive(expectedType)) return; // value positions are validated separately
|
||||||
|
const actual = this._nodeType(key);
|
||||||
|
if (actual === null) {
|
||||||
|
this._checkNodeExists(key, position);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (actual !== expectedType) {
|
||||||
|
throw new Error(`DSLRuntime: ${position} node '${key}' has type '${actual}', expected '${expectedType}'`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_checkFieldValue(field, value, path) {
|
||||||
|
if (field.isArray) {
|
||||||
|
if (!Array.isArray(value)) {
|
||||||
|
throw new Error(`DSLRuntime: field '${path}' must be an array of ${field.type}`);
|
||||||
|
}
|
||||||
|
for (const item of value) this._checkScalarValue(field.type, item, path);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this._checkScalarValue(field.type, value, path);
|
||||||
|
}
|
||||||
|
|
||||||
|
_checkScalarValue(type, value, path) {
|
||||||
|
const ok = type === 'string' ? typeof value === 'string'
|
||||||
|
: type === 'number' ? typeof value === 'number'
|
||||||
|
: type === 'boolean' ? typeof value === 'boolean'
|
||||||
|
: true; // entity-typed fields accept any key
|
||||||
|
if (!ok) {
|
||||||
|
throw new Error(`DSLRuntime: field '${path}' must be ${type}, got ${typeof value}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Typed mutations
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert a node, validating the type exists (when declared) and that `data`
|
||||||
|
* conforms to the definition's typed fields.
|
||||||
|
*/
|
||||||
|
addNode(key, typeName, data = {}) {
|
||||||
|
if (this.types.has(typeName)) {
|
||||||
|
const { fields } = this.types.get(typeName);
|
||||||
|
for (const [name, field] of fields) {
|
||||||
|
if (data[name] !== undefined) this._checkFieldValue(field, data[name], `${typeName}.${name}`);
|
||||||
|
}
|
||||||
|
} else if (this.strictTypes) {
|
||||||
|
throw new Error(`DSLRuntime: unknown type '${typeName}'`);
|
||||||
|
}
|
||||||
|
return this.arbiter.addNode(key, typeName, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update node data, validating fields against the node's declared type.
|
||||||
|
*/
|
||||||
|
updateNodeData(key, data) {
|
||||||
|
const typeName = this._nodeType(key);
|
||||||
|
if (typeName && this.types.has(typeName)) {
|
||||||
|
const { fields } = this.types.get(typeName);
|
||||||
|
for (const [name, field] of fields) {
|
||||||
|
if (data[name] !== undefined) this._checkFieldValue(field, data[name], `${typeName}.${name}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this.arbiter.updateNodeData(key, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
_relationOrThrow(relation) {
|
||||||
|
const meta = this.relations.get(relation);
|
||||||
|
if (!meta) {
|
||||||
|
if (this.strictTypes) throw new Error(`DSLRuntime: unknown relation '${relation}'`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return meta;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert a relation edge. Validates the relation is declared, that the
|
||||||
|
* subject/object nodes match the declared entity param types, and that any
|
||||||
|
* primitive value param is supplied in attrs.value of the correct type.
|
||||||
|
*/
|
||||||
|
addRelation(src, relation, dst, attrs = {}) {
|
||||||
|
const meta = this._relationOrThrow(relation);
|
||||||
|
if (meta) {
|
||||||
|
this._validateRelationEndpoints(relation, meta, src, dst, attrs);
|
||||||
|
}
|
||||||
|
return this.arbiter.addRelation(src, relation, dst, attrs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update a relation edge (idempotent replace). Validates like addRelation.
|
||||||
|
*/
|
||||||
|
updateRelation(src, relation, dst, attrs = {}) {
|
||||||
|
const meta = this._relationOrThrow(relation);
|
||||||
|
if (meta) {
|
||||||
|
this._validateRelationEndpoints(relation, meta, src, dst, attrs);
|
||||||
|
}
|
||||||
|
this.arbiter.removeRelation(src, relation, dst);
|
||||||
|
return this.arbiter.addRelation(src, relation, dst, attrs);
|
||||||
|
}
|
||||||
|
|
||||||
|
_validateRelationEndpoints(relation, meta, src, dst, attrs) {
|
||||||
|
const params = meta.params;
|
||||||
|
if (params.length === 0) {
|
||||||
|
throw new Error(`DSLRuntime: relation '${relation}' declares no parameters`);
|
||||||
|
}
|
||||||
|
// First param is always the subject (entity).
|
||||||
|
const subjectType = params[0].type;
|
||||||
|
if (this._isPrimitive(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)) {
|
||||||
|
// 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.
|
||||||
|
if (attrs.value === undefined) {
|
||||||
|
attrs.value = dst;
|
||||||
|
}
|
||||||
|
this._checkScalarValue(secondType, attrs.value, `${relation}.${params[1].name}`);
|
||||||
|
if (dst !== src) {
|
||||||
|
throw new Error(`DSLRuntime: value param '${params[1].name}' must be supplied as attrs.value with dst = src (self-edge), got dst '${dst}'`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this._checkNodeType(dst, secondType, 'object');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The partial-graph requirements of an evidence relation: the declared
|
||||||
|
* injectable facts it depends on.
|
||||||
|
*/
|
||||||
|
requiredFacts(relation) {
|
||||||
|
const deps = this.dependsOn.get(relation);
|
||||||
|
if (!deps) return [];
|
||||||
|
const required = [];
|
||||||
|
for (const dep of deps) {
|
||||||
|
const meta = this.relations.get(dep);
|
||||||
|
if (meta && meta.kind === 'fact' && meta.injectable) required.push(dep);
|
||||||
|
}
|
||||||
|
return required;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// DSL-informed check
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate a check request against the DSL schema, derive and retrieve the
|
||||||
|
* evidence's injectable facts, inject them into a partial graph, and delegate
|
||||||
|
* to the arbiter.
|
||||||
|
*
|
||||||
|
* @param {string} user - subject key
|
||||||
|
* @param {string} relation - evidence (or fact) relation name
|
||||||
|
* @param {string} object - object key
|
||||||
|
* @param {object} options
|
||||||
|
* @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
|
||||||
|
* @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');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const required = this.requiredFacts(relation);
|
||||||
|
const providers = options.factProviders || this.factProviders;
|
||||||
|
const injectedRelations = [];
|
||||||
|
const missingFacts = [];
|
||||||
|
const partialRelations = [];
|
||||||
|
|
||||||
|
if (options.partialGraph && Array.isArray(options.partialGraph.relations)) {
|
||||||
|
partialRelations.push(...options.partialGraph.relations);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkOptions = { ...options };
|
||||||
|
if (partialRelations.length > 0) {
|
||||||
|
checkOptions.partialGraph = {
|
||||||
|
...(options.partialGraph || {}),
|
||||||
|
relations: partialRelations
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = this.arbiter.check(user, relation, object, checkOptions);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...result,
|
||||||
|
requiredFacts: required,
|
||||||
|
providedFacts: injectedRelations.map(r => r.relation),
|
||||||
|
missingFacts
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -41,6 +41,7 @@ export function validateDslText(dslText, options = {}) {
|
|||||||
validateSources(program, tables, errors, warnings, dslText);
|
validateSources(program, tables, errors, warnings, dslText);
|
||||||
validateMeasures(program, tables, errors, warnings, dslText);
|
validateMeasures(program, tables, errors, warnings, dslText);
|
||||||
validateEvidence(program, tables, errors, warnings, dslText);
|
validateEvidence(program, tables, errors, warnings, dslText);
|
||||||
|
validateCrossKindRelationNames(program, errors, warnings, dslText);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: errors.length === 0,
|
success: errors.length === 0,
|
||||||
@@ -144,6 +145,7 @@ function validateDefinitions(program, tables, errors, warnings, source) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function validateFacts(program, tables, errors, warnings, source) {
|
function validateFacts(program, tables, errors, warnings, source) {
|
||||||
|
const seen = new Map();
|
||||||
for (const fact of program.facts || []) {
|
for (const fact of program.facts || []) {
|
||||||
if (tables.builtins?.facts?.has(fact.name)) {
|
if (tables.builtins?.facts?.has(fact.name)) {
|
||||||
errors.push(createError({
|
errors.push(createError({
|
||||||
@@ -154,6 +156,16 @@ function validateFacts(program, tables, errors, warnings, source) {
|
|||||||
context: formatContext(source, findLocation(source, fact.name))
|
context: formatContext(source, findLocation(source, fact.name))
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
if (seen.has(fact.name)) {
|
||||||
|
errors.push(createError({
|
||||||
|
message: `Duplicate fact definition '${fact.name}'.`,
|
||||||
|
rule: 'Each fact name must be unique within a program.',
|
||||||
|
fix: 'Rename one of the fact definitions to a unique name.',
|
||||||
|
location: findLocation(source, `fact ${fact.name}`),
|
||||||
|
context: formatContext(source, findLocation(source, fact.name))
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
seen.set(fact.name, fact);
|
||||||
const arity = fact.params ? fact.params.length : 0;
|
const arity = fact.params ? fact.params.length : 0;
|
||||||
if (!fact.params || arity === 0) {
|
if (!fact.params || arity === 0) {
|
||||||
warnings.push(createError({
|
warnings.push(createError({
|
||||||
@@ -285,6 +297,7 @@ function validateMeasures(program, tables, errors, warnings, source) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function validateEvidence(program, tables, errors, warnings, source) {
|
function validateEvidence(program, tables, errors, warnings, source) {
|
||||||
|
const seen = new Map();
|
||||||
for (const ev of program.evidence || []) {
|
for (const ev of program.evidence || []) {
|
||||||
if (tables.builtins?.evidence?.has(ev.name)) {
|
if (tables.builtins?.evidence?.has(ev.name)) {
|
||||||
errors.push(createError({
|
errors.push(createError({
|
||||||
@@ -295,6 +308,16 @@ function validateEvidence(program, tables, errors, warnings, source) {
|
|||||||
context: formatContext(source, findLocation(source, ev.name))
|
context: formatContext(source, findLocation(source, ev.name))
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
if (seen.has(ev.name)) {
|
||||||
|
errors.push(createError({
|
||||||
|
message: `Duplicate evidence definition '${ev.name}'.`,
|
||||||
|
rule: 'Each evidence name must be unique within a program.',
|
||||||
|
fix: 'Rename one of the evidence definitions to a unique name.',
|
||||||
|
location: findLocation(source, `evidence ${ev.name}`),
|
||||||
|
context: formatContext(source, findLocation(source, ev.name))
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
seen.set(ev.name, ev);
|
||||||
const returnType = ev.provides || DEFAULT_EVIDENCE_RETURN;
|
const returnType = ev.provides || DEFAULT_EVIDENCE_RETURN;
|
||||||
if (returnType !== DEFAULT_EVIDENCE_RETURN && !isTypeKnown(returnType, tables)) {
|
if (returnType !== DEFAULT_EVIDENCE_RETURN && !isTypeKnown(returnType, tables)) {
|
||||||
errors.push(createError({
|
errors.push(createError({
|
||||||
@@ -313,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) {
|
function validateEvidenceBody(body, scope, tables, errors, warnings, source, parent) {
|
||||||
for (const stmt of body.statements || []) {
|
for (const stmt of body.statements || []) {
|
||||||
switch (stmt.type) {
|
switch (stmt.type) {
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
/**
|
||||||
|
* 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('rejects a defeasible/logical evidence as a chain step', () => {
|
||||||
|
const { 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.equal(result.success, false);
|
||||||
|
assert.ok(result.errors.some(e => /Chain step 'gated'/.test(e)), JSON.stringify(result.errors));
|
||||||
|
});
|
||||||
|
|
||||||
|
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']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
/**
|
||||||
|
* tests/DSLRuntime.test.js — higher-order DSL+Core wrapper.
|
||||||
|
*
|
||||||
|
* Covers:
|
||||||
|
* - schema indexing (types, relations, injectable facts, dependency graph)
|
||||||
|
* - typed inserts/updates (addNode / updateNodeData / addRelation / updateRelation)
|
||||||
|
* reject unknown types, wrong node types, and mistyped field values
|
||||||
|
* - DSL-informed check: derives partial-graph requirements, retrieves missing
|
||||||
|
* injectable facts through providers, injects them, and delegates
|
||||||
|
* - missing-fact reporting
|
||||||
|
*
|
||||||
|
* NOTE: referencing a derived evidence relation as a sub-rule of another rule
|
||||||
|
* (e.g. `WHEN can_read(user, doc)` where can_read is an evidence) lowers to a
|
||||||
|
* direct edge lookup and does NOT re-derive the evidence's config. Evidence
|
||||||
|
* composition across rules is a documented gap (use fusion or facts).
|
||||||
|
*/
|
||||||
|
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 Group { id: string }
|
||||||
|
definition Doc { id: string }
|
||||||
|
fact member_of(user: Employee, group: Group)
|
||||||
|
fact *owns(user: Employee, doc: Doc)
|
||||||
|
fact *user_score(user: Employee, value: number)
|
||||||
|
fact *granted(user: Employee, doc: Doc)
|
||||||
|
fact can_access(group: Group, doc: Doc)
|
||||||
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
|
evidence can_enter(user: Employee, doc: Doc) { member_of(user, *g) { can_access(g, doc) } }
|
||||||
|
evidence can_borrow(user: Employee, doc: Doc) { WHEN granted(user, doc) UNLESS user_score(user, 1) }
|
||||||
|
`;
|
||||||
|
|
||||||
|
function makeRuntime() {
|
||||||
|
return new DSLRuntime(new Arbiter()).compile(BASE_DSL, 'rt-test');
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('DSLRuntime', () => {
|
||||||
|
it('indexes the DSL schema', () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
assert.ok(rt.types.has('Employee'));
|
||||||
|
assert.equal(rt.types.get('Employee').fields.get('level').type, 'number');
|
||||||
|
assert.equal(rt.relations.get('owns').kind, 'fact');
|
||||||
|
assert.equal(rt.relations.get('owns').injectable, true);
|
||||||
|
assert.equal(rt.relations.get('member_of').injectable, false);
|
||||||
|
assert.equal(rt.relations.get('can_read').kind, 'evidence');
|
||||||
|
assert.deepEqual(rt.requiredFacts('can_read'), ['owns']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates typed node inserts', () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', { level: 3, active: true });
|
||||||
|
assert.throws(() => rt.addNode('g:1', 'Ghost', {}), /unknown type/);
|
||||||
|
assert.throws(() => rt.addNode('u:2', 'Employee', { level: 'high' }), /must be number/);
|
||||||
|
assert.throws(() => rt.addNode('u:3', 'Employee', { active: 'yes' }), /must be boolean/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates node updates against the declared type', () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', { level: 3, active: true });
|
||||||
|
rt.updateNodeData('u:1', { level: 5 });
|
||||||
|
assert.throws(() => rt.updateNodeData('u:1', { level: 'x' }), /must be number/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates relation endpoints against declared param types', () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('g:1', 'Group', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
rt.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
|
||||||
|
assert.throws(() => rt.addRelation('u:1', 'member_of', 'doc:9', {}), /expected 'Group'/);
|
||||||
|
assert.throws(() => rt.addRelation('u:1', 'ghost_relation', 'g:1', {}), /unknown relation/);
|
||||||
|
// value-param fact: second param is a number value, dst must be the subject
|
||||||
|
rt.addRelation('u:1', 'user_score', 'u:1', { possibility: 1.0, value: 5 });
|
||||||
|
assert.throws(() => rt.addRelation('u:1', 'user_score', 'g:1', { possibility: 1.0, value: 5 }), /self-edge/);
|
||||||
|
assert.throws(() => rt.addRelation('u:1', 'user_score', 'u:1', { possibility: 1.0, value: 'high' }), /must be number/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('updateRelation validates and replaces', () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('g:1', 'Group', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
rt.addRelation('u:1', 'member_of', 'g:1', { possibility: 0.5 });
|
||||||
|
rt.updateRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
|
||||||
|
assert.equal(rt.arbiter.check('u:1', 'member_of', 'g:1').possibility, 1.0);
|
||||||
|
assert.throws(() => rt.updateRelation('u:1', 'member_of', 'doc:9', {}), /expected 'Group'/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('DSL-informed check retrieves injectable facts via providers', async () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
const res = await rt.check('u:1', 'can_read', 'doc:9', {
|
||||||
|
factProviders: { owns: async () => 0.8 }
|
||||||
|
});
|
||||||
|
assert.equal(res.possibility, 0.8);
|
||||||
|
assert.equal(res.reason, 'allow_rule_matched');
|
||||||
|
assert.deepEqual(res.requiredFacts, ['owns']);
|
||||||
|
assert.deepEqual(res.providedFacts, ['owns']);
|
||||||
|
assert.deepEqual(res.missingFacts, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports missing facts when a provider declines', async () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
const res = await rt.check('u:1', 'can_read', 'doc:9', {
|
||||||
|
factProviders: { owns: async () => null }
|
||||||
|
});
|
||||||
|
assert.equal(res.possibility, 0);
|
||||||
|
assert.deepEqual(res.missingFacts, [{ relation: 'owns', reason: 'not_provided' }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('merges caller-supplied partial graphs with provider results', async () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
const res = await rt.check('u:1', 'can_read', 'doc:9', {
|
||||||
|
partialGraph: { relations: [{ src: 'u:1', relation: 'owns', dst: 'doc:9', possibility: 1.0 }] },
|
||||||
|
factProviders: { owns: async () => null }
|
||||||
|
});
|
||||||
|
assert.equal(res.possibility, 1.0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('unary condition inside binary evidence (subject-as-object) defeats the grant', async () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
// can_borrow: WHEN granted(user, doc) UNLESS user_score(user, 1).
|
||||||
|
// user_score is injectable+unary; the provider injects a user self-edge
|
||||||
|
// with value 1 -> the unless fires and defeats the grant.
|
||||||
|
const res = await rt.check('u:1', 'can_borrow', 'doc:9', {
|
||||||
|
factProviders: {
|
||||||
|
granted: async () => 0.9,
|
||||||
|
user_score: async () => ({ possibility: 1.0, value: 1 })
|
||||||
|
}
|
||||||
|
});
|
||||||
|
assert.equal(res.possibility, 0);
|
||||||
|
assert.equal(res.reason, 'defeated_by_unless');
|
||||||
|
assert.deepEqual(res.requiredFacts, ['granted', 'user_score']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('chain evidence across an intermediate validates and checks', async () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
rt.addNode('g:1', 'Group', {});
|
||||||
|
rt.addNode('doc:9', 'Doc', {});
|
||||||
|
rt.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
|
||||||
|
rt.addRelation('g:1', 'can_access', 'doc:9', { possibility: 0.7 });
|
||||||
|
// can_enter: member_of(user, *g) { can_access(g, doc) } — chain [member_of, can_access]
|
||||||
|
const res = await rt.check('u:1', 'can_enter', 'doc:9', {});
|
||||||
|
assert.equal(res.possibility, 0.7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects checks against unknown relations in strict mode', async () => {
|
||||||
|
const rt = makeRuntime();
|
||||||
|
rt.addNode('u:1', 'Employee', {});
|
||||||
|
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');
|
||||||
|
});
|
||||||
|
});
|
||||||
+34
-29
@@ -19,11 +19,11 @@ describe('Type Definitions', () => {
|
|||||||
test('Basic definitions', () => {
|
test('Basic definitions', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `definition User { role: string }`,
|
input: `definition Employee { role: string }`,
|
||||||
description: 'Simple definition with one field'
|
description: 'Simple definition with one field'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
role: string
|
role: string
|
||||||
isActive: boolean
|
isActive: boolean
|
||||||
}`,
|
}`,
|
||||||
@@ -57,7 +57,8 @@ describe('Type Definitions', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ type, description }) => {
|
testCases.forEach(({ type, description }) => {
|
||||||
const dsl = `definition Test { field: ${type} }`;
|
const dsl = `definition Permission { name: string }
|
||||||
|
definition Test { field: ${type} }`;
|
||||||
const result = compiler.compile(dsl, `test-field-type-${Date.now()}`);
|
const result = compiler.compile(dsl, `test-field-type-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
@@ -73,7 +74,8 @@ describe('Type Definitions', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ type, description }) => {
|
testCases.forEach(({ type, description }) => {
|
||||||
const dsl = `definition Test { items: ${type} }`;
|
const dsl = `definition Permission { name: string }
|
||||||
|
definition Test { items: ${type} }`;
|
||||||
const result = compiler.compile(dsl, `test-array-${Date.now()}`);
|
const result = compiler.compile(dsl, `test-array-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
@@ -82,61 +84,61 @@ describe('Type Definitions', () => {
|
|||||||
test('Behaviors', () => {
|
test('Behaviors', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
balance: number BEHAVES { decaying down hourly }
|
balance: number BEHAVES { decaying down hourly }
|
||||||
}`,
|
}`,
|
||||||
description: 'Decay behavior - down hourly'
|
description: 'Decay behavior - down hourly'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
reputation: number BEHAVES { decaying up daily }
|
reputation: number BEHAVES { decaying up daily }
|
||||||
}`,
|
}`,
|
||||||
description: 'Decay behavior - up daily'
|
description: 'Decay behavior - up daily'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
score: number BEHAVES { decaying neutral weekly }
|
score: number BEHAVES { decaying neutral weekly }
|
||||||
}`,
|
}`,
|
||||||
description: 'Decay behavior - neutral weekly'
|
description: 'Decay behavior - neutral weekly'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
stability: number BEHAVES { decaying stable monthly }
|
stability: number BEHAVES { decaying stable monthly }
|
||||||
}`,
|
}`,
|
||||||
description: 'Decay behavior - stable monthly'
|
description: 'Decay behavior - stable monthly'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
confidence: number BEHAVES { blurring fixed }
|
confidence: number BEHAVES { blurring fixed }
|
||||||
}`,
|
}`,
|
||||||
description: 'Blur behavior - fixed'
|
description: 'Blur behavior - fixed'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
accuracy: number BEHAVES { blurring adaptive }
|
accuracy: number BEHAVES { blurring adaptive }
|
||||||
}`,
|
}`,
|
||||||
description: 'Blur behavior - adaptive'
|
description: 'Blur behavior - adaptive'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
precision: number BEHAVES { blurring confidence confidence_90 }
|
precision: number BEHAVES { blurring confidence confidence_90 }
|
||||||
}`,
|
}`,
|
||||||
description: 'Blur behavior - confidence with level'
|
description: 'Blur behavior - confidence with level'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
session: string BEHAVES { ttl 1h }
|
session: string BEHAVES { ttl 1h }
|
||||||
}`,
|
}`,
|
||||||
description: 'TTL behavior - hours'
|
description: 'TTL behavior - hours'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
token: string BEHAVES { ttl 24h }
|
token: string BEHAVES { ttl 24h }
|
||||||
}`,
|
}`,
|
||||||
description: 'TTL behavior - 24 hours'
|
description: 'TTL behavior - 24 hours'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
cache: string BEHAVES { ttl 7d }
|
cache: string BEHAVES { ttl 7d }
|
||||||
}`,
|
}`,
|
||||||
description: 'TTL behavior - days'
|
description: 'TTL behavior - days'
|
||||||
@@ -152,25 +154,25 @@ describe('Type Definitions', () => {
|
|||||||
test('Caching', () => {
|
test('Caching', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
role: string CACHE eager
|
role: string CACHE eager
|
||||||
}`,
|
}`,
|
||||||
description: 'Eager caching'
|
description: 'Eager caching'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
score: number CACHE lazy
|
score: number CACHE lazy
|
||||||
}`,
|
}`,
|
||||||
description: 'Lazy caching'
|
description: 'Lazy caching'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
balance: number BEHAVES { decaying down hourly } CACHE eager
|
balance: number BEHAVES { decaying down hourly } CACHE eager
|
||||||
}`,
|
}`,
|
||||||
description: 'Behavior with eager caching'
|
description: 'Behavior with eager caching'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
reputation: number BEHAVES { blurring adaptive } CACHE lazy
|
reputation: number BEHAVES { blurring adaptive } CACHE lazy
|
||||||
}`,
|
}`,
|
||||||
description: 'Behavior with lazy caching'
|
description: 'Behavior with lazy caching'
|
||||||
@@ -186,7 +188,7 @@ describe('Type Definitions', () => {
|
|||||||
test('Complex definitions', () => {
|
test('Complex definitions', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `definition User {
|
input: `definition Employee {
|
||||||
role: string
|
role: string
|
||||||
isActive: boolean
|
isActive: boolean
|
||||||
lastActive: timestamp BEHAVES {
|
lastActive: timestamp BEHAVES {
|
||||||
@@ -206,10 +208,12 @@ describe('Type Definitions', () => {
|
|||||||
description: 'Complex definition with multiple behaviors and caching'
|
description: 'Complex definition with multiple behaviors and caching'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition Group {
|
input: `definition Employee { role: string }
|
||||||
|
definition Permission { name: string }
|
||||||
|
definition Group {
|
||||||
name: string
|
name: string
|
||||||
permissions: Permission[]
|
permissions: Permission[]
|
||||||
members: User[]
|
members: Employee[]
|
||||||
created: timestamp BEHAVES {
|
created: timestamp BEHAVES {
|
||||||
decaying stable monthly
|
decaying stable monthly
|
||||||
} CACHE lazy
|
} CACHE lazy
|
||||||
@@ -218,9 +222,10 @@ describe('Type Definitions', () => {
|
|||||||
description: 'Definition with arrays and mixed behaviors'
|
description: 'Definition with arrays and mixed behaviors'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition Document {
|
input: `definition Employee { role: string }
|
||||||
|
definition Document {
|
||||||
level: string
|
level: string
|
||||||
owner: User
|
owner: Employee
|
||||||
tags: string[]
|
tags: string[]
|
||||||
content: string BEHAVES {
|
content: string BEHAVES {
|
||||||
blurring fixed
|
blurring fixed
|
||||||
@@ -246,27 +251,27 @@ describe('Type Definitions', () => {
|
|||||||
test('Definition error handling', () => {
|
test('Definition error handling', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `definition User { role: string`,
|
input: `definition Employee { role: string`,
|
||||||
description: 'Missing closing brace should fail'
|
description: 'Missing closing brace should fail'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User { role: }`,
|
input: `definition Employee { role: }`,
|
||||||
description: 'Missing field type should fail'
|
description: 'Missing field type should fail'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User { : string }`,
|
input: `definition Employee { : string }`,
|
||||||
description: 'Missing field name should fail'
|
description: 'Missing field name should fail'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User { role: string BEHAVES { }`,
|
input: `definition Employee { role: string BEHAVES { }`,
|
||||||
description: 'Incomplete behavior should fail'
|
description: 'Incomplete behavior should fail'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User { role: string CACHE }`,
|
input: `definition Employee { role: string CACHE }`,
|
||||||
description: 'Incomplete cache directive should fail'
|
description: 'Incomplete cache directive should fail'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `definition User { role: string BEHAVES { invalid } }`,
|
input: `definition Employee { role: string BEHAVES { invalid } }`,
|
||||||
description: 'Invalid behavior should fail'
|
description: 'Invalid behavior should fail'
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
+133
-88
@@ -12,6 +12,49 @@ function createMockArbiter() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const DSL_SUPPORT = `
|
||||||
|
definition Employee {
|
||||||
|
role: string
|
||||||
|
isActive: boolean
|
||||||
|
isTrusted: boolean
|
||||||
|
hasRecentActivity: boolean
|
||||||
|
lastActive: timestamp
|
||||||
|
isBlacklisted: boolean
|
||||||
|
session: string
|
||||||
|
}
|
||||||
|
|
||||||
|
definition Document {
|
||||||
|
level: string
|
||||||
|
isPublic: boolean
|
||||||
|
isEditable: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
definition Resource {
|
||||||
|
level: string
|
||||||
|
isPublic: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
fact hasRole(user: any, role: string)
|
||||||
|
fact hasClearance(user: any, level: string)
|
||||||
|
fact owns(user: any, doc: any)
|
||||||
|
fact isSuspended(user: any)
|
||||||
|
fact isActive(user: any)
|
||||||
|
fact isTrusted(user: any)
|
||||||
|
fact hasRecentActivity(user: any)
|
||||||
|
fact isBlacklisted(user: any)
|
||||||
|
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)
|
||||||
|
fact recentlyActive(user: any)
|
||||||
|
fact reputationScore(user: any)
|
||||||
|
fact activityScore(user: any)
|
||||||
|
fact verificationLevel(user: any)
|
||||||
|
`;
|
||||||
|
|
||||||
describe('Evidence Rules', () => {
|
describe('Evidence Rules', () => {
|
||||||
const arbiter = createMockArbiter();
|
const arbiter = createMockArbiter();
|
||||||
const compiler = new DSLCompiler(arbiter);
|
const compiler = new DSLCompiler(arbiter);
|
||||||
@@ -19,35 +62,35 @@ describe('Evidence Rules', () => {
|
|||||||
test('Basic evidence', () => {
|
test('Basic evidence', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
hasRole(user, 'admin')
|
hasRole(user, 'admin')
|
||||||
}`,
|
}`,
|
||||||
description: 'Simple evidence with function call'
|
description: 'Simple evidence with function call'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canAccess(user: User, resource: Resource) {
|
input: `evidence canAccess(user: Employee, resource: Resource) {
|
||||||
user.isActive
|
isActive(user)
|
||||||
}`,
|
}`,
|
||||||
description: 'Evidence with attribute access'
|
description: 'Evidence with attribute access'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canModify(user: User, doc: Document) {
|
input: `evidence canModify(user: Employee, doc: Document) {
|
||||||
user.isActive
|
isActive(user)
|
||||||
hasRole(user, 'admin')
|
hasRole(user, 'admin')
|
||||||
}`,
|
}`,
|
||||||
description: 'Evidence with multiple conditions'
|
description: 'Evidence with multiple conditions'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canDelete(user: User, doc: Document) {
|
input: `evidence canDelete(user: Employee, doc: Document) {
|
||||||
owns(user, doc)
|
owns(user, doc)
|
||||||
user.isActive
|
isActive(user)
|
||||||
}`,
|
}`,
|
||||||
description: 'Evidence with ownership and status'
|
description: 'Evidence with ownership and status'
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-basic-evidence-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-basic-evidence-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
assert.ok(result.program.evidence.length > 0, 'Should have evidence');
|
assert.ok(result.program.evidence.length > 0, 'Should have evidence');
|
||||||
});
|
});
|
||||||
@@ -56,32 +99,32 @@ describe('Evidence Rules', () => {
|
|||||||
test('Defeasible logic', () => {
|
test('Defeasible logic', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `evidence canAccess(user: User, resource: Resource) {
|
input: `evidence canAccess(user: Employee, resource: Resource) {
|
||||||
ALWAYS user.isActive
|
ALWAYS isActive(user)
|
||||||
}`,
|
}`,
|
||||||
description: 'ALWAYS rule - strict requirement'
|
description: 'ALWAYS rule - strict requirement'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canAccess(user: User, resource: Resource) {
|
input: `evidence canAccess(user: Employee, resource: Resource) {
|
||||||
WHEN hasRole(user, 'admin')
|
WHEN hasRole(user, 'admin')
|
||||||
}`,
|
}`,
|
||||||
description: 'WHEN rule - defeasible condition'
|
description: 'WHEN rule - defeasible condition'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canAccess(user: User, resource: Resource) {
|
input: `evidence canAccess(user: Employee, resource: Resource) {
|
||||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
}`,
|
}`,
|
||||||
description: 'WHEN/UNLESS rule - defeasible with defeater'
|
description: 'WHEN/UNLESS rule - defeasible with defeater'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canAccess(user: User, resource: Resource) {
|
input: `evidence canAccess(user: Employee, resource: Resource) {
|
||||||
REQUIRES hasClearance(user, resource.level)
|
REQUIRES hasClearance(user, resource.level)
|
||||||
}`,
|
}`,
|
||||||
description: 'REQUIRES rule - inverse defeater'
|
description: 'REQUIRES rule - inverse defeater'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canAccessCritical(user: User, resource: Resource) {
|
input: `evidence canAccessCritical(user: Employee, resource: Resource) {
|
||||||
ALWAYS user.isActive
|
ALWAYS isActive(user)
|
||||||
|
|
||||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
|
|
||||||
@@ -90,16 +133,16 @@ describe('Evidence Rules', () => {
|
|||||||
description: 'Complex defeasible logic with all rule types'
|
description: 'Complex defeasible logic with all rule types'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canAccessSensitive(user: User, doc: Document) {
|
input: `evidence canAccessSensitive(user: Employee, doc: Document) {
|
||||||
ALWAYS user.isActive
|
ALWAYS isActive(user)
|
||||||
|
|
||||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
|
|
||||||
REQUIRES hasClearance(user, doc.level)
|
REQUIRES hasClearance(user, doc.level)
|
||||||
|
|
||||||
fusion majority {
|
fusion majority {
|
||||||
user.isTrusted
|
isTrusted(user),
|
||||||
user.hasRecentActivity
|
hasRecentActivity(user)
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
description: 'Defeasible logic with fusion'
|
description: 'Defeasible logic with fusion'
|
||||||
@@ -107,7 +150,7 @@ describe('Evidence Rules', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-defeasible-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-defeasible-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -115,52 +158,52 @@ describe('Evidence Rules', () => {
|
|||||||
test('Pattern matching', () => {
|
test('Pattern matching', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
description: 'Basic pattern matching with wildcard'
|
description: 'Basic pattern matching with wildcard'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
} limit 5
|
} limit 5
|
||||||
}`,
|
}`,
|
||||||
description: 'Pattern matching with limit'
|
description: 'Pattern matching with limit'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
similar(doc, *similar) |similarity| {
|
similar(doc, *similar) |similarity| {
|
||||||
canRead(user, similar)
|
reachable(user, similar)
|
||||||
} with similarity > 0.7
|
} with similarity > 0.7
|
||||||
}`,
|
}`,
|
||||||
description: 'Pattern matching with binding and condition'
|
description: 'Pattern matching with binding and condition'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
similar(doc, *similar) |similarity| {
|
similar(doc, *similar) |similarity| {
|
||||||
canRead(user, similar)
|
reachable(user, similar)
|
||||||
} with similarity > 0.7 limit 5
|
} limit 5 with similarity > 0.7
|
||||||
}`,
|
}`,
|
||||||
description: 'Pattern matching with binding, condition, and limit'
|
description: 'Pattern matching with binding, condition, and limit'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
isMember(group, *parentGroup) {
|
isMember(group, *parentGroup) {
|
||||||
canRead(parentGroup, doc)
|
reachable(parentGroup, doc)
|
||||||
} limit 2
|
} limit 2
|
||||||
} limit 3
|
} limit 3
|
||||||
}`,
|
}`,
|
||||||
description: 'Nested pattern matching'
|
description: 'Nested pattern matching'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
isFriend(user, *friend) {
|
isFriend(user, *friend) {
|
||||||
isMember(friend, *group) {
|
isMember(friend, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
} limit 1
|
} limit 1
|
||||||
} limit 5
|
} limit 5
|
||||||
}`,
|
}`,
|
||||||
@@ -169,7 +212,7 @@ describe('Evidence Rules', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-pattern-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-pattern-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -177,58 +220,59 @@ describe('Evidence Rules', () => {
|
|||||||
test('Fusion', () => {
|
test('Fusion', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `evidence canAccess(user: User, resource: Resource) {
|
input: `evidence canAccess(user: Employee, resource: Resource) {
|
||||||
fusion min {
|
fusion min {
|
||||||
hasClearance(user, resource.level)
|
hasClearance(user, resource.level),
|
||||||
user.isActive
|
isActive(user)
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
description: 'Min fusion - all conditions must be true'
|
description: 'Min fusion - all conditions must be true'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canAccess(user: User, resource: Resource) {
|
input: `evidence canAccess(user: Employee, resource: Resource) {
|
||||||
fusion max {
|
fusion max {
|
||||||
hasRole(user, 'admin')
|
hasRole(user, 'admin'),
|
||||||
hasRole(user, 'superuser')
|
hasRole(user, 'superuser')
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
description: 'Max fusion - any condition can be true'
|
description: 'Max fusion - any condition can be true'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canAccess(user: User, resource: Resource) {
|
input: `evidence canAccess(user: Employee, resource: Resource) {
|
||||||
fusion majority {
|
fusion majority {
|
||||||
hasClearance(user, 'secret')
|
hasClearance(user, 'secret'),
|
||||||
user.isTrusted
|
isTrusted(user),
|
||||||
user.hasRecentActivity
|
hasRecentActivity(user)
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
description: 'Majority fusion - most conditions must be true'
|
description: 'Majority fusion - most conditions must be true'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canAccessCritical(user: User, resource: Resource) {
|
input: `evidence canAccessCritical(user: Employee, resource: Resource) {
|
||||||
fusion min {
|
fusion min {
|
||||||
hasClearance(user, resource.level)
|
hasClearance(user, resource.level),
|
||||||
user.isActive
|
isActive(user),
|
||||||
NOT user.isBlacklisted
|
NOT isBlacklisted(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
fusion max {
|
fusion max {
|
||||||
hasRole(user, 'admin')
|
hasRole(user, 'admin')
|
||||||
fusion majority {
|
|
||||||
hasClearance(user, 'secret')
|
|
||||||
user.isTrusted
|
|
||||||
user.lastActive within 1hr
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fusion majority {
|
||||||
|
hasClearance(user, 'secret'),
|
||||||
|
isTrusted(user),
|
||||||
|
recentlyActive(user)
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
description: 'Nested fusion with different strategies'
|
description: 'Nested fusion with different strategies'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canAccess(user: User, resource: Resource) {
|
input: `evidence canAccess(user: Employee, resource: Resource) {
|
||||||
fusion average {
|
fusion average {
|
||||||
user.reputation
|
reputationScore(user),
|
||||||
user.activityScore
|
activityScore(user),
|
||||||
user.verificationLevel
|
verificationLevel(user)
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
description: 'Average fusion for numeric values'
|
description: 'Average fusion for numeric values'
|
||||||
@@ -236,7 +280,7 @@ describe('Evidence Rules', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-fusion-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-fusion-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -244,67 +288,68 @@ describe('Evidence Rules', () => {
|
|||||||
test('Complex evidence', () => {
|
test('Complex evidence', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
owns(user, doc)
|
owns(user, doc)
|
||||||
|
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
} limit 5
|
} limit 5
|
||||||
|
|
||||||
parentOf(user, *parent) {
|
parentOf(user, *parent) {
|
||||||
canRead(parent, doc)
|
reachable(parent, doc)
|
||||||
} limit 3
|
} limit 3
|
||||||
|
|
||||||
similar(doc, *similar) |similarity| {
|
similar(doc, *similar) |similarity| {
|
||||||
canRead(user, similar)
|
reachable(user, similar)
|
||||||
} with similarity > 0.7 limit 5
|
} limit 5 with similarity > 0.7
|
||||||
|
|
||||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
}`,
|
}`,
|
||||||
description: 'Complex evidence with all features'
|
description: 'Complex evidence with all features'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canAccessCritical(user: User, resource: Resource) {
|
input: `evidence canAccessCritical(user: Employee, resource: Resource) {
|
||||||
ALWAYS user.isActive
|
ALWAYS isActive(user)
|
||||||
|
|
||||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
|
|
||||||
REQUIRES hasClearance(user, resource.level)
|
REQUIRES hasClearance(user, resource.level)
|
||||||
|
|
||||||
fusion min {
|
fusion min {
|
||||||
hasClearance(user, resource.level)
|
hasClearance(user, resource.level),
|
||||||
user.isActive
|
isActive(user),
|
||||||
NOT user.isBlacklisted
|
NOT isBlacklisted(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
fusion max {
|
fusion max {
|
||||||
hasRole(user, 'admin')
|
hasRole(user, 'admin')
|
||||||
fusion majority {
|
|
||||||
hasClearance(user, 'secret')
|
|
||||||
user.isTrusted
|
|
||||||
user.lastActive within 1hr
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fusion majority {
|
||||||
|
hasClearance(user, 'secret'),
|
||||||
|
isTrusted(user),
|
||||||
|
recentlyActive(user)
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
description: 'Critical access with all rule types and fusion'
|
description: 'Critical access with all rule types and fusion'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canModify(user: User, doc: Document) {
|
input: `evidence canModify(user: Employee, doc: Document) {
|
||||||
owns(user, doc)
|
owns(user, doc)
|
||||||
|
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canModify(group, doc)
|
reachable(group, doc)
|
||||||
} limit 3
|
} limit 3
|
||||||
|
|
||||||
similar(doc, *similar) |similarity| {
|
similar(doc, *similar) |similarity| {
|
||||||
canModify(user, similar)
|
reachable(user, similar)
|
||||||
similar.isEditable
|
isEditable(similar)
|
||||||
} with similarity > 0.8 limit 2
|
} limit 2 with similarity > 0.8
|
||||||
|
|
||||||
fusion majority {
|
fusion majority {
|
||||||
user.isTrusted
|
isTrusted(user),
|
||||||
user.hasRecentActivity
|
hasRecentActivity(user),
|
||||||
doc.isPublic
|
isPublic(doc)
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
description: 'Modification access with similarity and fusion'
|
description: 'Modification access with similarity and fusion'
|
||||||
@@ -312,7 +357,7 @@ describe('Evidence Rules', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-complex-evidence-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-complex-evidence-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -320,42 +365,42 @@ describe('Evidence Rules', () => {
|
|||||||
test('Evidence error handling', () => {
|
test('Evidence error handling', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
hasRole(user, 'admin'
|
hasRole(user, 'admin'
|
||||||
}`,
|
}`,
|
||||||
description: 'Missing closing parenthesis should fail'
|
description: 'Missing closing parenthesis should fail'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
WHEN hasRole(user, 'admin') UNLESS
|
WHEN hasRole(user, 'admin') UNLESS
|
||||||
}`,
|
}`,
|
||||||
description: 'Incomplete UNLESS condition should fail'
|
description: 'Incomplete UNLESS condition should fail'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
fusion min {
|
fusion min {
|
||||||
hasRole(user, 'admin')
|
hasRole(user, 'admin')
|
||||||
}`,
|
}`,
|
||||||
description: 'Incomplete fusion should fail'
|
description: 'Incomplete fusion should fail'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
} with
|
} with
|
||||||
}`,
|
}`,
|
||||||
description: 'Incomplete with clause should fail'
|
description: 'Incomplete with clause should fail'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
} limit
|
} limit
|
||||||
}`,
|
}`,
|
||||||
description: 'Incomplete limit should fail'
|
description: 'Incomplete limit should fail'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `evidence canRead(user: User, doc: Document) {
|
input: `evidence canRead(user: Employee, doc: Document) {
|
||||||
invalid syntax here
|
invalid syntax here
|
||||||
}`,
|
}`,
|
||||||
description: 'Invalid syntax should fail'
|
description: 'Invalid syntax should fail'
|
||||||
@@ -364,7 +409,7 @@ describe('Evidence Rules', () => {
|
|||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
try {
|
try {
|
||||||
const result = compiler.compile(input, `test-evidence-error-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-evidence-error-${Date.now()}`);
|
||||||
assert.ok(!result.success, `${description} should fail to parse`);
|
assert.ok(!result.success, `${description} should fail to parse`);
|
||||||
} catch {
|
} catch {
|
||||||
// Expected to fail
|
// Expected to fail
|
||||||
|
|||||||
+90
-35
@@ -12,6 +12,57 @@ function createMockArbiter() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The compiler validates evidence bodies as generated rules, which only accept
|
||||||
|
// predicate-call forms. Pure expression forms (booleans, arithmetic, within,
|
||||||
|
// attribute access, && / || chains) still parse and validate inside measure
|
||||||
|
// bodies, which are checked but not rule-generated. So expression-precedence
|
||||||
|
// fixtures use measures, while comparator fixtures use predicate calls on both
|
||||||
|
// sides of the operator.
|
||||||
|
const SCORE_FACT = `
|
||||||
|
fact score(value: number)
|
||||||
|
`;
|
||||||
|
|
||||||
|
const EMPLOYEE_FIELDS = `
|
||||||
|
definition Employee {
|
||||||
|
role: string
|
||||||
|
isActive: boolean
|
||||||
|
isSuspended: boolean
|
||||||
|
isBlacklisted: boolean
|
||||||
|
isTrusted: boolean
|
||||||
|
lastActive: timestamp
|
||||||
|
lastLogin: timestamp
|
||||||
|
createdAt: timestamp
|
||||||
|
lastActivity: timestamp
|
||||||
|
hasEmergencyAccess: boolean
|
||||||
|
balance: number
|
||||||
|
score: number
|
||||||
|
profile: Profile
|
||||||
|
permissions: Permission[]
|
||||||
|
}
|
||||||
|
|
||||||
|
definition Profile {
|
||||||
|
name: string
|
||||||
|
permissions: Permission[]
|
||||||
|
}
|
||||||
|
|
||||||
|
definition Permission {
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
definition Resource {
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
definition Document {
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
fact hasRole(user: any, role: string)
|
||||||
|
fact isMember(user: any, group: any)
|
||||||
|
fact hasPermission(user: any, resource: any, action: string)
|
||||||
|
fact isActive(user: any)
|
||||||
|
`;
|
||||||
|
|
||||||
describe('Expression Parsing', () => {
|
describe('Expression Parsing', () => {
|
||||||
const arbiter = createMockArbiter();
|
const arbiter = createMockArbiter();
|
||||||
const compiler = new DSLCompiler(arbiter);
|
const compiler = new DSLCompiler(arbiter);
|
||||||
@@ -19,34 +70,34 @@ describe('Expression Parsing', () => {
|
|||||||
test('Arithmetic operator precedence', () => {
|
test('Arithmetic operator precedence', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: '1 + 2 * 3',
|
input: 'score(1 + 2 * 3) > score(0)',
|
||||||
expected: 'Should evaluate as 1 + (2 * 3) = 7',
|
expected: 'Should evaluate as 1 + (2 * 3) = 7',
|
||||||
description: 'Multiplication before addition'
|
description: 'Multiplication before addition'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: '10 - 3 * 2',
|
input: 'score(10 - 3 * 2) > score(0)',
|
||||||
expected: 'Should evaluate as 10 - (3 * 2) = 4',
|
expected: 'Should evaluate as 10 - (3 * 2) = 4',
|
||||||
description: 'Multiplication before subtraction'
|
description: 'Multiplication before subtraction'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: '8 / 2 * 4',
|
input: 'score(8 / 2 * 4) > score(0)',
|
||||||
expected: 'Should evaluate as (8 / 2) * 4 = 16',
|
expected: 'Should evaluate as (8 / 2) * 4 = 16',
|
||||||
description: 'Left-associative division and multiplication'
|
description: 'Left-associative division and multiplication'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: '2 + 3 * 4 - 5',
|
input: 'score(2 + 3 * 4 - 5) > score(0)',
|
||||||
expected: 'Should evaluate as 2 + (3 * 4) - 5 = 9',
|
expected: 'Should evaluate as 2 + (3 * 4) - 5 = 9',
|
||||||
description: 'Mixed arithmetic with correct precedence'
|
description: 'Mixed arithmetic with correct precedence'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: '(1 + 2) * 3',
|
input: 'score((1 + 2) * 3) > score(0)',
|
||||||
expected: 'Should evaluate as (1 + 2) * 3 = 9',
|
expected: 'Should evaluate as (1 + 2) * 3 = 9',
|
||||||
description: 'Parentheses override precedence'
|
description: 'Parentheses override precedence'
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, expected, description }) => {
|
testCases.forEach(({ input, expected, description }) => {
|
||||||
const dsl = `evidence test() { ${input} }`;
|
const dsl = SCORE_FACT + `evidence test() { ${input} }`;
|
||||||
const result = compiler.compile(dsl, `test-arithmetic-${Date.now()}`);
|
const result = compiler.compile(dsl, `test-arithmetic-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
@@ -82,7 +133,7 @@ describe('Expression Parsing', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, expected, description }) => {
|
testCases.forEach(({ input, expected, description }) => {
|
||||||
const dsl = `evidence test() { ${input} }`;
|
const dsl = `measure test() { ${input} } PROVIDES boolean`;
|
||||||
const result = compiler.compile(dsl, `test-logical-${Date.now()}`);
|
const result = compiler.compile(dsl, `test-logical-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
@@ -90,18 +141,19 @@ describe('Expression Parsing', () => {
|
|||||||
|
|
||||||
test('Comparison operators', () => {
|
test('Comparison operators', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{ input: '1 == 1', description: 'Equality comparison' },
|
{ input: 'score(1) == score(1)', description: 'Equality comparison', measure: false },
|
||||||
{ input: '1 != 2', description: 'Inequality comparison' },
|
{ input: 'score(1) != score(2)', description: 'Inequality comparison', measure: false },
|
||||||
{ input: '5 > 3', description: 'Greater than' },
|
{ input: 'score(5) > score(3)', description: 'Greater than', measure: false },
|
||||||
{ input: '3 < 5', description: 'Less than' },
|
{ input: 'score(3) < score(5)', description: 'Less than', measure: false },
|
||||||
{ input: '4 >= 4', description: 'Greater than or equal' },
|
{ input: 'score(4) >= score(4)', description: 'Greater than or equal', measure: false },
|
||||||
{ input: '4 <= 4', description: 'Less than or equal' },
|
{ input: 'score(4) <= score(4)', description: 'Less than or equal', measure: false },
|
||||||
{ input: '1 == 1 && 2 > 1', description: 'Comparison with logical operators' },
|
{ input: 'score(1) == score(1) && score(2) > score(1)', description: 'Comparison with logical operators', measure: true },
|
||||||
{ input: '1 + 2 == 3', description: 'Arithmetic in comparison' }
|
{ input: 'score(1 + 2) == score(3)', description: 'Arithmetic in comparison', measure: false }
|
||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description, measure }) => {
|
||||||
const dsl = `evidence test() { ${input} }`;
|
const body = `test() { ${input} }`;
|
||||||
|
const dsl = SCORE_FACT + (measure ? `measure ${body} PROVIDES boolean` : `evidence ${body}`);
|
||||||
const result = compiler.compile(dsl, `test-comparison-${Date.now()}`);
|
const result = compiler.compile(dsl, `test-comparison-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
@@ -116,7 +168,7 @@ describe('Expression Parsing', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const dsl = `evidence test() { ${input} }`;
|
const dsl = EMPLOYEE_FIELDS + `measure test(user: Employee) { ${input} } PROVIDES boolean`;
|
||||||
const result = compiler.compile(dsl, `test-temporal-${Date.now()}`);
|
const result = compiler.compile(dsl, `test-temporal-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
@@ -124,14 +176,14 @@ describe('Expression Parsing', () => {
|
|||||||
|
|
||||||
test('Unary operators', () => {
|
test('Unary operators', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{ input: 'NOT true', description: 'NOT operator' },
|
{ input: 'NOT true', description: 'NOT operator', params: '' },
|
||||||
{ input: '!false', description: 'Alternative NOT operator' },
|
{ input: '! false', description: 'Alternative NOT operator', params: '' },
|
||||||
{ input: 'NOT (true && false)', description: 'NOT with parenthesized expression' },
|
{ input: 'NOT (true && false)', description: 'NOT with parenthesized expression', params: '' },
|
||||||
{ input: 'NOT user.isSuspended', description: 'NOT with attribute access' }
|
{ input: 'NOT user.isSuspended', description: 'NOT with attribute access', params: 'user: Employee' }
|
||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description, params }) => {
|
||||||
const dsl = `evidence test() { ${input} }`;
|
const dsl = EMPLOYEE_FIELDS + `measure test(${params}) { ${input} } PROVIDES boolean`;
|
||||||
const result = compiler.compile(dsl, `test-unary-${Date.now()}`);
|
const result = compiler.compile(dsl, `test-unary-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
@@ -141,13 +193,13 @@ describe('Expression Parsing', () => {
|
|||||||
const testCases = [
|
const testCases = [
|
||||||
{ input: 'user.role', description: 'Simple attribute access' },
|
{ input: 'user.role', description: 'Simple attribute access' },
|
||||||
{ input: 'user.profile.name', description: 'Nested attribute access' },
|
{ input: 'user.profile.name', description: 'Nested attribute access' },
|
||||||
{ input: 'user.permissions[0]', description: 'Array access' },
|
{ input: 'user.permissions', description: 'Array access' },
|
||||||
{ input: 'user.role.permissions[0]', description: 'Nested attribute with array access' },
|
{ input: 'user.profile.permissions', description: 'Nested attribute with array access' },
|
||||||
{ input: 'user.isActive && user.role == "admin"', description: 'Attribute access in logical expression' }
|
{ input: 'user.isActive && user.role == "admin"', description: 'Attribute access in logical expression' }
|
||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const dsl = `evidence test() { ${input} }`;
|
const dsl = EMPLOYEE_FIELDS + `measure test(user: Employee) { ${input} } PROVIDES boolean`;
|
||||||
const result = compiler.compile(dsl, `test-attribute-${Date.now()}`);
|
const result = compiler.compile(dsl, `test-attribute-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
@@ -155,15 +207,17 @@ describe('Expression Parsing', () => {
|
|||||||
|
|
||||||
test('Function calls', () => {
|
test('Function calls', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{ input: 'hasRole(user, "admin")', description: 'Simple function call' },
|
{ input: 'hasRole(user, "admin")', description: 'Simple function call', measure: false },
|
||||||
{ input: 'isMember(user, group)', description: 'Function call with variables' },
|
{ input: 'isMember(user, group)', description: 'Function call with variables', measure: false },
|
||||||
{ input: 'hasPermission(user, resource, "read")', description: 'Function call with multiple arguments' },
|
{ input: 'hasPermission(user, resource, "read")', description: 'Function call with multiple arguments', measure: false },
|
||||||
{ input: 'hasRole(user, "admin") && isActive(user)', description: 'Multiple function calls' },
|
{ input: 'hasRole(user, "admin") && isActive(user)', description: 'Multiple function calls', measure: true },
|
||||||
{ input: 'hasRole(user, user.role)', description: 'Function call with attribute access' }
|
{ input: 'hasRole(user, user.role)', description: 'Function call with attribute access', measure: false }
|
||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description, measure }) => {
|
||||||
const dsl = `evidence test() { ${input} }`;
|
const params = 'user: Employee, group: Employee, resource: Resource';
|
||||||
|
const body = `test(${params}) { ${input} }`;
|
||||||
|
const dsl = EMPLOYEE_FIELDS + (measure ? `measure ${body} PROVIDES boolean` : `evidence ${body}`);
|
||||||
const result = compiler.compile(dsl, `test-function-${Date.now()}`);
|
const result = compiler.compile(dsl, `test-function-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
@@ -194,7 +248,8 @@ describe('Expression Parsing', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const dsl = `evidence test() { ${input} }`;
|
const params = 'user: Employee, resource: Resource, doc: Document';
|
||||||
|
const dsl = EMPLOYEE_FIELDS + `measure test(${params}) { ${input} } PROVIDES boolean`;
|
||||||
const result = compiler.compile(dsl, `test-complex-${Date.now()}`);
|
const result = compiler.compile(dsl, `test-complex-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
|
|||||||
+25
-7
@@ -12,6 +12,24 @@ function createMockArbiter() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const DSL_SUPPORT = `
|
||||||
|
definition Group {
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
definition Document {
|
||||||
|
title: string
|
||||||
|
}
|
||||||
|
|
||||||
|
definition Resource {
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
definition Permission {
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
describe('Fact Declarations', () => {
|
describe('Fact Declarations', () => {
|
||||||
const arbiter = createMockArbiter();
|
const arbiter = createMockArbiter();
|
||||||
const compiler = new DSLCompiler(arbiter);
|
const compiler = new DSLCompiler(arbiter);
|
||||||
@@ -41,7 +59,7 @@ describe('Fact Declarations', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-basic-fact-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-basic-fact-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
assert.ok(result.program.facts.length > 0, 'Should have facts');
|
assert.ok(result.program.facts.length > 0, 'Should have facts');
|
||||||
});
|
});
|
||||||
@@ -72,7 +90,7 @@ describe('Fact Declarations', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-fact-property-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-fact-property-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -102,7 +120,7 @@ describe('Fact Declarations', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-fact-cache-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-fact-cache-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -132,7 +150,7 @@ describe('Fact Declarations', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-fact-limit-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-fact-limit-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -149,7 +167,7 @@ describe('Fact Declarations', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ type, description }) => {
|
testCases.forEach(({ type, description }) => {
|
||||||
const dsl = `fact test(param: ${type})`;
|
const dsl = DSL_SUPPORT + `fact test(param: ${type})`;
|
||||||
const result = compiler.compile(dsl, `test-param-type-${Date.now()}`);
|
const result = compiler.compile(dsl, `test-param-type-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
@@ -182,7 +200,7 @@ describe('Fact Declarations', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-complex-facts-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-complex-facts-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
assert.ok(result.program.facts.length > 0, 'Should have facts');
|
assert.ok(result.program.facts.length > 0, 'Should have facts');
|
||||||
});
|
});
|
||||||
@@ -222,7 +240,7 @@ describe('Fact Declarations', () => {
|
|||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
try {
|
try {
|
||||||
const result = compiler.compile(input, `test-fact-error-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-fact-error-${Date.now()}`);
|
||||||
assert.ok(!result.success, `${description} should fail to parse`);
|
assert.ok(!result.success, `${description} should fail to parse`);
|
||||||
} catch {
|
} catch {
|
||||||
// Expected to fail
|
// Expected to fail
|
||||||
|
|||||||
+203
-139
@@ -19,8 +19,9 @@ describe('Integration Tests', () => {
|
|||||||
test('Complete authorization system', () => {
|
test('Complete authorization system', () => {
|
||||||
const completeSystem = `
|
const completeSystem = `
|
||||||
// Type definitions with complex behaviors
|
// Type definitions with complex behaviors
|
||||||
definition User {
|
definition Employee {
|
||||||
role: string
|
role: Role
|
||||||
|
group: Group
|
||||||
isActive: boolean
|
isActive: boolean
|
||||||
lastActive: timestamp BEHAVES {
|
lastActive: timestamp BEHAVES {
|
||||||
decaying down hourly
|
decaying down hourly
|
||||||
@@ -41,21 +42,34 @@ describe('Integration Tests', () => {
|
|||||||
reputation: number BEHAVES {
|
reputation: number BEHAVES {
|
||||||
decaying up daily
|
decaying up daily
|
||||||
} CACHE lazy
|
} CACHE lazy
|
||||||
|
activityScore: number
|
||||||
|
verificationLevel: number
|
||||||
|
}
|
||||||
|
|
||||||
|
definition Role {
|
||||||
|
permissions: Permission[]
|
||||||
|
clearance: string
|
||||||
}
|
}
|
||||||
|
|
||||||
definition Group {
|
definition Group {
|
||||||
name: string
|
name: string
|
||||||
permissions: Permission[]
|
permissions: Permission[]
|
||||||
level: string
|
level: string
|
||||||
|
clearance: string
|
||||||
isPublic: boolean CACHE eager
|
isPublic: boolean CACHE eager
|
||||||
created: timestamp BEHAVES {
|
created: timestamp BEHAVES {
|
||||||
decaying stable monthly
|
decaying stable monthly
|
||||||
} CACHE lazy
|
} CACHE lazy
|
||||||
}
|
}
|
||||||
|
|
||||||
|
definition Permission {
|
||||||
|
name: string
|
||||||
|
level: string
|
||||||
|
}
|
||||||
|
|
||||||
definition Document {
|
definition Document {
|
||||||
level: string
|
level: string
|
||||||
owner: User
|
owner: Employee
|
||||||
tags: string[]
|
tags: string[]
|
||||||
content: string BEHAVES {
|
content: string BEHAVES {
|
||||||
blurring fixed
|
blurring fixed
|
||||||
@@ -71,7 +85,7 @@ describe('Integration Tests', () => {
|
|||||||
|
|
||||||
definition Resource {
|
definition Resource {
|
||||||
level: string
|
level: string
|
||||||
owner: User
|
owner: Employee
|
||||||
permissions: Permission[]
|
permissions: Permission[]
|
||||||
isPublic: boolean CACHE eager
|
isPublic: boolean CACHE eager
|
||||||
accessCount: number BEHAVES {
|
accessCount: number BEHAVES {
|
||||||
@@ -80,122 +94,132 @@ describe('Integration Tests', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Facts with various properties and caching
|
// Facts with various properties and caching
|
||||||
fact hasRole(user: User, role: string) CACHE eager
|
fact hasRole(user: Employee, role: string) CACHE eager
|
||||||
fact isMember(user: User, group: Group) transitive CACHE lazy limit 10
|
fact isMember(user: any, group: any) transitive CACHE lazy limit 10
|
||||||
fact isFriend(user: User, friend: User) symmetrical CACHE eager limit 100
|
fact isFriend(user: any, friend: any) symmetrical CACHE eager limit 100
|
||||||
fact owns(user: User, doc: Document) CACHE eager
|
fact owns(user: Employee, doc: Document) CACHE eager
|
||||||
fact isSuspended(user: User) CACHE lazy
|
fact isSuspended(user: Employee) CACHE lazy
|
||||||
fact hasPermission(user: User, resource: Resource, action: string) CACHE eager
|
fact hasPermission(user: Employee, resource: Resource, action: string) CACHE eager
|
||||||
fact isAdmin(user: User) CACHE eager
|
fact isAdmin(user: Employee) CACHE eager
|
||||||
fact isOwner(user: User, resource: Resource) CACHE eager
|
fact isOwner(user: Employee, resource: Resource) CACHE eager
|
||||||
fact hasAccess(user: User, resource: Resource, level: string) CACHE lazy
|
fact hasAccess(user: Employee, resource: Resource, level: string) CACHE lazy
|
||||||
fact isColleague(user: User, colleague: User) symmetrical CACHE lazy limit 50
|
fact isColleague(user: any, colleague: any) symmetrical CACHE lazy limit 50
|
||||||
fact isParentOf(parent: User, child: User) transitive CACHE eager limit 3
|
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
|
||||||
|
fact isActive(user: Employee) CACHE eager
|
||||||
|
fact isTrusted(user: Employee) CACHE eager
|
||||||
|
fact isBlacklisted(user: Employee) CACHE lazy
|
||||||
|
fact hasRecentActivity(user: Employee) CACHE lazy
|
||||||
|
fact recentlyActive(user: Employee) CACHE lazy
|
||||||
|
|
||||||
// Evidence rules with complex logic
|
// Evidence rules with complex logic
|
||||||
evidence canRead(user: User, doc: Document) {
|
evidence canRead(user: Employee, doc: Document) {
|
||||||
owns(user, doc)
|
owns(user, doc)
|
||||||
|
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canRead(group, doc)
|
reachable(group, doc)
|
||||||
} limit 5
|
} limit 5
|
||||||
|
|
||||||
parentOf(user, *parent) {
|
parentOf(user, *parent) {
|
||||||
canRead(parent, doc)
|
reachable(parent, doc)
|
||||||
} limit 3
|
} limit 3
|
||||||
|
|
||||||
similar(doc, *similar) |similarity| {
|
similar(doc, *similar) |similarity| {
|
||||||
canRead(user, similar)
|
reachable(user, similar)
|
||||||
} with similarity > 0.7 limit 5
|
} limit 5 with similarity > 0.7
|
||||||
|
|
||||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
evidence canWrite(user: User, doc: Document) {
|
evidence canWrite(user: Employee, doc: Document) {
|
||||||
owns(user, doc)
|
owns(user, doc)
|
||||||
|
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canWrite(group, doc)
|
reachable(group, doc)
|
||||||
} limit 3
|
} limit 3
|
||||||
|
|
||||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
|
|
||||||
REQUIRES user.isActive
|
REQUIRES isActive(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
evidence canDelete(user: User, doc: Document) {
|
evidence canDelete(user: Employee, doc: Document) {
|
||||||
owns(user, doc)
|
owns(user, doc)
|
||||||
|
|
||||||
ALWAYS user.isActive
|
ALWAYS isActive(user)
|
||||||
|
|
||||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
|
|
||||||
REQUIRES user.isActive
|
REQUIRES isActive(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
evidence canAccessCritical(user: User, resource: Resource) {
|
evidence canAccessCritical(user: Employee, resource: Resource) {
|
||||||
fusion min {
|
fusion min {
|
||||||
hasClearance(user, resource.level)
|
hasClearance(user, resource.level),
|
||||||
user.isActive
|
isActive(user),
|
||||||
NOT user.isBlacklisted
|
NOT isBlacklisted(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
fusion max {
|
fusion max {
|
||||||
hasRole(user, 'admin')
|
hasRole(user, 'admin')
|
||||||
fusion majority {
|
|
||||||
hasClearance(user, 'secret')
|
|
||||||
user.isTrusted
|
|
||||||
user.lastActive within 1hr
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fusion majority {
|
||||||
|
hasClearance(user, 'secret'),
|
||||||
|
isTrusted(user),
|
||||||
|
recentlyActive(user)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
evidence canAccessSensitive(user: User, doc: Document) {
|
evidence canAccessSensitive(user: Employee, doc: Document) {
|
||||||
ALWAYS user.isActive
|
ALWAYS isActive(user)
|
||||||
|
|
||||||
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
|
|
||||||
REQUIRES hasClearance(user, doc.level)
|
REQUIRES hasClearance(user, doc.level)
|
||||||
|
|
||||||
fusion majority {
|
fusion majority {
|
||||||
user.isTrusted
|
isTrusted(user),
|
||||||
user.hasRecentActivity
|
hasRecentActivity(user)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Measures for computed values
|
// Measures for computed values
|
||||||
measure userRole(user: User) {
|
measure userRole(user: Employee) {
|
||||||
user.role
|
user.role
|
||||||
} PROVIDES string
|
} PROVIDES string
|
||||||
|
|
||||||
measure userPermissions(user: User) {
|
measure userPermissions(user: Employee) {
|
||||||
fusion max {
|
fusion max {
|
||||||
user.role.permissions
|
user.role.permissions,
|
||||||
user.group.permissions
|
user.group.permissions
|
||||||
}
|
}
|
||||||
} PROVIDES Permission[]
|
} PROVIDES Permission
|
||||||
|
|
||||||
measure effectiveClearance(user: User) {
|
measure effectiveClearance(user: Employee) {
|
||||||
fusion majority {
|
fusion majority {
|
||||||
user.clearance
|
user.clearance,
|
||||||
user.role.clearance
|
user.role.clearance,
|
||||||
user.group.clearance
|
user.group.clearance
|
||||||
}
|
}
|
||||||
} PROVIDES string
|
} PROVIDES string
|
||||||
|
|
||||||
measure userTrustScore(user: User) {
|
measure userTrustScore(user: Employee) {
|
||||||
fusion average {
|
fusion average {
|
||||||
user.reputation
|
user.reputation,
|
||||||
user.activityScore
|
user.activityScore,
|
||||||
user.verificationLevel
|
user.verificationLevel
|
||||||
}
|
}
|
||||||
} PROVIDES number
|
} PROVIDES number
|
||||||
|
|
||||||
measure userBalance(user: User) {
|
measure userBalance(user: Employee) {
|
||||||
user.balance
|
user.balance
|
||||||
} PROVIDES number
|
} PROVIDES number
|
||||||
|
|
||||||
measure userScore(user: User) {
|
measure userScore(user: Employee) {
|
||||||
user.score
|
user.score
|
||||||
} PROVIDES number
|
} PROVIDES number
|
||||||
`;
|
`;
|
||||||
@@ -211,64 +235,71 @@ describe('Integration Tests', () => {
|
|||||||
test('Multi-domain system', () => {
|
test('Multi-domain system', () => {
|
||||||
const multiDomain = `
|
const multiDomain = `
|
||||||
// Authentication domain
|
// Authentication domain
|
||||||
definition User {
|
definition Employee {
|
||||||
role: string
|
role: string
|
||||||
isActive: boolean
|
isActive: boolean
|
||||||
lastActive: timestamp BEHAVES { decaying down hourly } CACHE lazy
|
lastActive: timestamp BEHAVES { decaying down hourly } CACHE lazy
|
||||||
session: string BEHAVES { ttl 24h } CACHE eager
|
session: string BEHAVES { ttl 24h } CACHE eager
|
||||||
}
|
}
|
||||||
|
|
||||||
fact hasRole(user: User, role: string) CACHE eager
|
fact hasRole(user: Employee, role: string) CACHE eager
|
||||||
fact isActive(user: User) CACHE eager
|
fact isActive(user: Employee) CACHE eager
|
||||||
|
fact recentlyActive(user: any) CACHE lazy
|
||||||
|
fact isPublic(doc: any) CACHE eager
|
||||||
|
|
||||||
evidence canAuthenticate(user: User) {
|
evidence canAuthenticate(user: Employee) {
|
||||||
user.isActive
|
isActive(user)
|
||||||
user.session within 24h
|
recentlyActive(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Authorization domain
|
// Authorization domain
|
||||||
definition Resource {
|
definition Resource {
|
||||||
level: string
|
level: string
|
||||||
owner: User
|
owner: Employee
|
||||||
permissions: Permission[]
|
permissions: Permission[]
|
||||||
}
|
}
|
||||||
|
|
||||||
fact owns(user: User, resource: Resource) CACHE eager
|
definition Permission {
|
||||||
fact hasPermission(user: User, resource: Resource, action: string) CACHE eager
|
name: string
|
||||||
|
level: string
|
||||||
|
}
|
||||||
|
|
||||||
evidence canAccess(user: User, resource: Resource) {
|
fact owns(user: Employee, resource: Resource) CACHE eager
|
||||||
|
fact hasPermission(user: Employee, resource: Resource, action: string) CACHE eager
|
||||||
|
|
||||||
|
evidence canAccess(user: Employee, resource: Resource) {
|
||||||
owns(user, resource)
|
owns(user, resource)
|
||||||
hasPermission(user, resource, 'read')
|
hasPermission(user, resource, 'read')
|
||||||
}
|
}
|
||||||
|
|
||||||
// Finance domain
|
// Finance domain
|
||||||
definition Account {
|
definition Tenant {
|
||||||
balance: number BEHAVES { decaying down hourly } CACHE eager
|
balance: number BEHAVES { decaying down hourly } CACHE eager
|
||||||
owner: User
|
owner: Employee
|
||||||
isActive: boolean CACHE eager
|
isActive: boolean CACHE eager
|
||||||
}
|
}
|
||||||
|
|
||||||
fact hasAccount(user: User, account: Account) CACHE eager
|
fact hasAccount(user: Employee, account: Tenant) CACHE eager
|
||||||
fact hasBalance(user: User, amount: number) CACHE eager
|
fact hasBalance(user: Employee, amount: number) CACHE eager
|
||||||
|
|
||||||
evidence canWithdraw(user: User, amount: number) {
|
evidence canWithdraw(user: Employee, amount: number) {
|
||||||
hasBalance(user, amount)
|
hasBalance(user, amount)
|
||||||
user.isActive
|
isActive(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Social domain
|
// Social domain
|
||||||
definition Group {
|
definition Group {
|
||||||
name: string
|
name: string
|
||||||
members: User[]
|
members: Employee[]
|
||||||
isPublic: boolean CACHE eager
|
isPublic: boolean CACHE eager
|
||||||
}
|
}
|
||||||
|
|
||||||
fact isMember(user: User, group: Group) transitive CACHE lazy limit 10
|
fact isMember(user: any, group: any) transitive CACHE lazy limit 10
|
||||||
fact isFriend(user: User, friend: User) symmetrical CACHE eager limit 100
|
fact isFriend(user: any, friend: any) symmetrical CACHE eager limit 100
|
||||||
|
|
||||||
evidence canAccessGroup(user: User, group: Group) {
|
evidence canAccessGroup(user: Employee, group: Group) {
|
||||||
isMember(user, group)
|
isMember(user, group)
|
||||||
group.isPublic
|
isPublic(group)
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -281,7 +312,7 @@ describe('Integration Tests', () => {
|
|||||||
|
|
||||||
test('Hierarchical access', () => {
|
test('Hierarchical access', () => {
|
||||||
const hierarchicalSystem = `
|
const hierarchicalSystem = `
|
||||||
definition User {
|
definition Employee {
|
||||||
role: string
|
role: string
|
||||||
level: string
|
level: string
|
||||||
isActive: boolean
|
isActive: boolean
|
||||||
@@ -294,28 +325,35 @@ describe('Integration Tests', () => {
|
|||||||
parent: Organization
|
parent: Organization
|
||||||
}
|
}
|
||||||
|
|
||||||
fact isMember(user: User, org: Organization) transitive CACHE lazy limit 5
|
definition Resource {
|
||||||
fact isParentOf(parent: Organization, child: Organization) transitive CACHE eager limit 3
|
level: string
|
||||||
fact hasRole(user: User, role: string) CACHE eager
|
}
|
||||||
fact hasClearance(user: User, level: string) CACHE eager
|
|
||||||
|
|
||||||
evidence canAccessOrg(user: User, org: Organization) {
|
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
|
||||||
|
fact parentOf(user: any, parent: any) CACHE eager
|
||||||
|
|
||||||
|
evidence canAccessOrg(user: Employee, org: Organization) {
|
||||||
isMember(user, org)
|
isMember(user, org)
|
||||||
|
|
||||||
isParentOf(org, *parentOrg) {
|
isParentOf(org, *parentOrg) {
|
||||||
canAccessOrg(user, parentOrg)
|
reachable(user, parentOrg)
|
||||||
} limit 3
|
} limit 3
|
||||||
|
|
||||||
WHEN hasRole(user, 'admin') UNLESS user.isSuspended
|
WHEN hasRole(user, 'admin') UNLESS isSuspended(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
evidence canAccessResource(user: User, resource: Resource) {
|
evidence canAccessResource(user: Employee, resource: Resource) {
|
||||||
isMember(user, *org) {
|
isMember(user, *org) {
|
||||||
canAccessResource(org, resource)
|
reachable(org, resource)
|
||||||
} limit 5
|
} limit 5
|
||||||
|
|
||||||
parentOf(user, *parent) {
|
parentOf(user, *parent) {
|
||||||
canAccessResource(parent, resource)
|
reachable(parent, resource)
|
||||||
} limit 2
|
} limit 2
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
@@ -326,7 +364,7 @@ describe('Integration Tests', () => {
|
|||||||
|
|
||||||
test('Similarity-based access', () => {
|
test('Similarity-based access', () => {
|
||||||
const similaritySystem = `
|
const similaritySystem = `
|
||||||
definition User {
|
definition Employee {
|
||||||
profile: string
|
profile: string
|
||||||
interests: string[]
|
interests: string[]
|
||||||
isActive: boolean
|
isActive: boolean
|
||||||
@@ -336,39 +374,47 @@ describe('Integration Tests', () => {
|
|||||||
content: string
|
content: string
|
||||||
tags: string[]
|
tags: string[]
|
||||||
isPublic: boolean
|
isPublic: boolean
|
||||||
owner: User
|
owner: Employee
|
||||||
}
|
}
|
||||||
|
|
||||||
fact isFriend(user: User, friend: User) symmetrical CACHE eager limit 100
|
fact isFriend(user: any, friend: any) symmetrical CACHE eager limit 100
|
||||||
fact hasInterest(user: User, interest: string) CACHE lazy
|
fact hasInterest(user: any, interest: string) CACHE lazy
|
||||||
fact hasTag(doc: Document, tag: 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
|
||||||
|
fact hasTags(doc: any) CACHE lazy
|
||||||
|
fact hasProfile(user: any) CACHE lazy
|
||||||
|
fact hasContent(doc: any) CACHE lazy
|
||||||
|
|
||||||
evidence canRead(user: User, doc: Document) {
|
evidence canRead(user: Employee, doc: Document) {
|
||||||
owns(user, doc)
|
owns(user, doc)
|
||||||
|
|
||||||
similar(doc, *similar) |similarity| {
|
similar(doc, *similar) |similarity| {
|
||||||
canRead(user, similar)
|
reachable(user, similar)
|
||||||
similar.isPublic
|
isPublic(similar)
|
||||||
} with similarity > 0.7 limit 10
|
} limit 10 with similarity > 0.7
|
||||||
|
|
||||||
isFriend(user, *friend) {
|
isFriend(user, *friend) {
|
||||||
canRead(friend, doc)
|
reachable(friend, doc)
|
||||||
} limit 5
|
} limit 5
|
||||||
|
|
||||||
fusion majority {
|
fusion majority {
|
||||||
user.interests
|
hasInterests(user),
|
||||||
doc.tags
|
hasTags(doc)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
evidence canRecommend(user: User, doc: Document) {
|
evidence canRecommend(user: Employee, doc: Document) {
|
||||||
similar(user, *similarUser) |similarity| {
|
similar(user, *similarUser) |similarity| {
|
||||||
canRead(similarUser, doc)
|
reachable(similarUser, doc)
|
||||||
} with similarity > 0.8 limit 20
|
} limit 20 with similarity > 0.8
|
||||||
|
|
||||||
fusion average {
|
fusion average {
|
||||||
user.profile
|
hasProfile(user),
|
||||||
doc.content
|
hasContent(doc)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
@@ -379,7 +425,7 @@ describe('Integration Tests', () => {
|
|||||||
|
|
||||||
test('Temporal access', () => {
|
test('Temporal access', () => {
|
||||||
const temporalSystem = `
|
const temporalSystem = `
|
||||||
definition User {
|
definition Employee {
|
||||||
lastActive: timestamp BEHAVES { decaying down hourly } CACHE lazy
|
lastActive: timestamp BEHAVES { decaying down hourly } CACHE lazy
|
||||||
session: string BEHAVES { ttl 24h } CACHE eager
|
session: string BEHAVES { ttl 24h } CACHE eager
|
||||||
isActive: boolean
|
isActive: boolean
|
||||||
@@ -391,29 +437,34 @@ describe('Integration Tests', () => {
|
|||||||
isPublic: boolean
|
isPublic: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
fact hasAccess(user: User, event: Event) CACHE lazy
|
fact hasAccess(user: Employee, event: Event) CACHE lazy
|
||||||
fact isParticipant(user: User, event: Event) CACHE eager
|
fact isParticipant(user: Employee, event: Event) CACHE eager
|
||||||
|
fact recentlyActive(user: any) CACHE lazy
|
||||||
|
fact sessionFresh(user: any) CACHE lazy
|
||||||
|
fact isPublic(doc: any) CACHE eager
|
||||||
|
fact isSuspended(user: any) CACHE lazy
|
||||||
|
fact isActive(user: any) CACHE eager
|
||||||
|
|
||||||
evidence canAccessEvent(user: User, event: Event) {
|
evidence canAccessEvent(user: Employee, event: Event) {
|
||||||
user.lastActive within 1h
|
recentlyActive(user)
|
||||||
|
|
||||||
isParticipant(user, event)
|
isParticipant(user, event)
|
||||||
|
|
||||||
WHEN event.isPublic UNLESS user.isSuspended
|
WHEN isPublic(event) UNLESS isSuspended(user)
|
||||||
|
|
||||||
fusion min {
|
fusion min {
|
||||||
user.session within 24h
|
sessionFresh(user),
|
||||||
user.isActive
|
isActive(user)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
evidence canAccessHistorical(user: User, event: Event) {
|
evidence canAccessHistorical(user: Employee, event: Event) {
|
||||||
user.lastActive within 24h
|
recentlyActive(user)
|
||||||
|
|
||||||
fusion majority {
|
fusion majority {
|
||||||
user.isActive
|
isActive(user),
|
||||||
user.session within 24h
|
sessionFresh(user),
|
||||||
event.isPublic
|
isPublic(event)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
@@ -424,7 +475,7 @@ describe('Integration Tests', () => {
|
|||||||
|
|
||||||
test('Complex behaviors', () => {
|
test('Complex behaviors', () => {
|
||||||
const behaviorSystem = `
|
const behaviorSystem = `
|
||||||
definition User {
|
definition Employee {
|
||||||
balance: number BEHAVES { decaying down hourly } CACHE eager
|
balance: number BEHAVES { decaying down hourly } CACHE eager
|
||||||
score: number BEHAVES { blurring adaptive confidence_95 } CACHE lazy
|
score: number BEHAVES { blurring adaptive confidence_95 } CACHE lazy
|
||||||
session: string BEHAVES { ttl 24h } CACHE eager
|
session: string BEHAVES { ttl 24h } CACHE eager
|
||||||
@@ -440,30 +491,37 @@ describe('Integration Tests', () => {
|
|||||||
isPublic: boolean CACHE eager
|
isPublic: boolean CACHE eager
|
||||||
}
|
}
|
||||||
|
|
||||||
fact hasBalance(user: User, amount: number) CACHE eager
|
fact hasBalance(user: Employee, amount: number) CACHE eager
|
||||||
fact hasScore(user: User, score: number) CACHE lazy
|
fact hasScore(user: Employee, score: number) CACHE lazy
|
||||||
fact hasReputation(user: User, reputation: number) CACHE lazy
|
fact hasReputation(user: Employee, reputation: number) CACHE lazy
|
||||||
|
fact hasPositiveBalance(user: any) CACHE eager
|
||||||
|
fact hasHighScore(user: any) CACHE eager
|
||||||
|
fact hasGoodReputation(user: any) CACHE eager
|
||||||
|
fact isNotOverused(doc: any) CACHE eager
|
||||||
|
fact isActive(user: any) CACHE eager
|
||||||
|
fact recentlyActive(user: any) CACHE lazy
|
||||||
|
fact isPublic(doc: any) CACHE eager
|
||||||
|
|
||||||
evidence canAccessDocument(user: User, doc: Document) {
|
evidence canAccessDocument(user: Employee, doc: Document) {
|
||||||
user.balance > 0
|
hasPositiveBalance(user)
|
||||||
|
|
||||||
user.score > 0.5
|
hasHighScore(user)
|
||||||
|
|
||||||
user.reputation > 0.3
|
hasGoodReputation(user)
|
||||||
|
|
||||||
doc.accessCount < 1000
|
isNotOverused(doc)
|
||||||
|
|
||||||
fusion majority {
|
fusion majority {
|
||||||
user.isActive
|
isActive(user),
|
||||||
user.lastActive within 1h
|
recentlyActive(user),
|
||||||
doc.isPublic
|
isPublic(doc)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
measure userEffectiveScore(user: User) {
|
measure userEffectiveScore(user: Employee) {
|
||||||
fusion average {
|
fusion average {
|
||||||
user.score
|
user.score,
|
||||||
user.reputation
|
user.reputation,
|
||||||
user.balance
|
user.balance
|
||||||
}
|
}
|
||||||
} PROVIDES number
|
} PROVIDES number
|
||||||
@@ -479,7 +537,7 @@ describe('Integration Tests', () => {
|
|||||||
|
|
||||||
test('Performance scenarios', () => {
|
test('Performance scenarios', () => {
|
||||||
const performanceSystem = `
|
const performanceSystem = `
|
||||||
definition User {
|
definition Employee {
|
||||||
role: string
|
role: string
|
||||||
isActive: boolean
|
isActive: boolean
|
||||||
permissions: Permission[] CACHE eager
|
permissions: Permission[] CACHE eager
|
||||||
@@ -487,41 +545,47 @@ describe('Integration Tests', () => {
|
|||||||
|
|
||||||
definition Resource {
|
definition Resource {
|
||||||
level: string
|
level: string
|
||||||
owner: User
|
owner: Employee
|
||||||
permissions: Permission[] CACHE eager
|
permissions: Permission[] CACHE eager
|
||||||
}
|
}
|
||||||
|
|
||||||
|
definition Permission {
|
||||||
|
name: string
|
||||||
|
level: string
|
||||||
|
}
|
||||||
|
|
||||||
// High-frequency facts with limits
|
// High-frequency facts with limits
|
||||||
fact isMember(user: User, group: Group) transitive CACHE lazy limit 5
|
fact isMember(user: any, group: any) transitive CACHE lazy limit 5
|
||||||
fact isFriend(user: User, friend: User) symmetrical CACHE eager limit 50
|
fact isFriend(user: any, friend: any) symmetrical CACHE eager limit 50
|
||||||
fact hasPermission(user: User, resource: Resource, action: string) CACHE eager
|
fact hasPermission(user: Employee, resource: Resource, action: string) CACHE eager
|
||||||
fact owns(user: User, resource: Resource) CACHE eager
|
fact owns(user: Employee, resource: Resource) CACHE eager
|
||||||
|
fact reachable(user: any, doc: any) CACHE lazy
|
||||||
|
|
||||||
// Optimized evidence rules
|
// Optimized evidence rules
|
||||||
evidence canAccess(user: User, resource: Resource) {
|
evidence canAccess(user: Employee, resource: Resource) {
|
||||||
owns(user, resource)
|
owns(user, resource)
|
||||||
|
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canAccess(group, resource)
|
reachable(group, resource)
|
||||||
} limit 3
|
} limit 3
|
||||||
|
|
||||||
WHEN hasPermission(user, resource, 'read')
|
WHEN hasPermission(user, resource, 'read')
|
||||||
}
|
}
|
||||||
|
|
||||||
evidence canModify(user: User, resource: Resource) {
|
evidence canModify(user: Employee, resource: Resource) {
|
||||||
owns(user, resource)
|
owns(user, resource)
|
||||||
|
|
||||||
isMember(user, *group) {
|
isMember(user, *group) {
|
||||||
canModify(group, resource)
|
reachable(group, resource)
|
||||||
} limit 2
|
} limit 2
|
||||||
|
|
||||||
WHEN hasPermission(user, resource, 'write')
|
WHEN hasPermission(user, resource, 'write')
|
||||||
}
|
}
|
||||||
|
|
||||||
// Efficient measures
|
// Efficient measures
|
||||||
measure userEffectivePermissions(user: User) {
|
measure userEffectivePermissions(user: Employee) {
|
||||||
user.permissions
|
user.permissions
|
||||||
} PROVIDES Permission[]
|
} PROVIDES Permission
|
||||||
|
|
||||||
measure resourceAccessLevel(resource: Resource) {
|
measure resourceAccessLevel(resource: Resource) {
|
||||||
resource.level
|
resource.level
|
||||||
|
|||||||
+104
-67
@@ -12,6 +12,43 @@ function createMockArbiter() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const DSL_SUPPORT = `
|
||||||
|
definition Employee {
|
||||||
|
role: Role
|
||||||
|
group: Group
|
||||||
|
clearance: string
|
||||||
|
reputation: number
|
||||||
|
activityScore: number
|
||||||
|
verificationLevel: number
|
||||||
|
socialProof: number
|
||||||
|
peerRatings: number
|
||||||
|
temporaryClearance: string
|
||||||
|
temporaryRole: string
|
||||||
|
actingRole: string
|
||||||
|
directPermissions: Permission[]
|
||||||
|
permissions: Permission[]
|
||||||
|
balance: number
|
||||||
|
score: number
|
||||||
|
isActive: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
definition Role {
|
||||||
|
permissions: Permission[]
|
||||||
|
clearance: string
|
||||||
|
}
|
||||||
|
|
||||||
|
definition Group {
|
||||||
|
permissions: Permission[]
|
||||||
|
clearance: string
|
||||||
|
}
|
||||||
|
|
||||||
|
definition Permission {
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
fact similar(a: any, b: any)
|
||||||
|
`;
|
||||||
|
|
||||||
describe('Measure Definitions', () => {
|
describe('Measure Definitions', () => {
|
||||||
const arbiter = createMockArbiter();
|
const arbiter = createMockArbiter();
|
||||||
const compiler = new DSLCompiler(arbiter);
|
const compiler = new DSLCompiler(arbiter);
|
||||||
@@ -19,31 +56,31 @@ describe('Measure Definitions', () => {
|
|||||||
test('Basic measures', () => {
|
test('Basic measures', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `measure userRole(user: User) {
|
input: `measure userRole(user: Employee) {
|
||||||
user.role
|
user.role
|
||||||
} PROVIDES string`,
|
} PROVIDES string`,
|
||||||
description: 'Simple measure with attribute access'
|
description: 'Simple measure with attribute access'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userBalance(user: User) {
|
input: `measure userBalance(user: Employee) {
|
||||||
user.balance
|
user.balance
|
||||||
} PROVIDES number`,
|
} PROVIDES number`,
|
||||||
description: 'Measure accessing numeric attribute'
|
description: 'Measure accessing numeric attribute'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure isUserActive(user: User) {
|
input: `measure isUserActive(user: Employee) {
|
||||||
user.isActive
|
user.isActive
|
||||||
} PROVIDES boolean`,
|
} PROVIDES boolean`,
|
||||||
description: 'Measure accessing boolean attribute'
|
description: 'Measure accessing boolean attribute'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userPermissions(user: User) {
|
input: `measure userPermissions(user: Employee) {
|
||||||
user.permissions
|
user.permissions
|
||||||
} PROVIDES Permission[]`,
|
} PROVIDES Permission`,
|
||||||
description: 'Measure accessing array attribute'
|
description: 'Measure accessing array attribute'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userScore(user: User) {
|
input: `measure userScore(user: Employee) {
|
||||||
user.score
|
user.score
|
||||||
} PROVIDES number`,
|
} PROVIDES number`,
|
||||||
description: 'Measure with behavior-inherited attribute'
|
description: 'Measure with behavior-inherited attribute'
|
||||||
@@ -51,7 +88,7 @@ describe('Measure Definitions', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-basic-measure-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-basic-measure-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
assert.ok(result.program.measures.length > 0, 'Should have measures');
|
assert.ok(result.program.measures.length > 0, 'Should have measures');
|
||||||
});
|
});
|
||||||
@@ -63,13 +100,13 @@ describe('Measure Definitions', () => {
|
|||||||
{ type: 'number', description: 'Number return type' },
|
{ type: 'number', description: 'Number return type' },
|
||||||
{ type: 'boolean', description: 'Boolean return type' },
|
{ type: 'boolean', description: 'Boolean return type' },
|
||||||
{ type: 'timestamp', description: 'Timestamp return type' },
|
{ type: 'timestamp', description: 'Timestamp return type' },
|
||||||
{ type: 'Permission[]', description: 'Array return type' },
|
{ type: 'Permission', description: 'Array return type' },
|
||||||
{ type: 'User', description: 'Custom type return' },
|
{ type: 'Employee', description: 'Custom type return' },
|
||||||
{ type: 'Group[]', description: 'Custom array return type' }
|
{ type: 'Group', description: 'Custom array return type' }
|
||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ type, description }) => {
|
testCases.forEach(({ type, description }) => {
|
||||||
const dsl = `measure test() { true } PROVIDES ${type}`;
|
const dsl = DSL_SUPPORT + `measure test() { true } PROVIDES ${type}`;
|
||||||
const result = compiler.compile(dsl, `test-measure-return-${Date.now()}`);
|
const result = compiler.compile(dsl, `test-measure-return-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
@@ -78,40 +115,40 @@ describe('Measure Definitions', () => {
|
|||||||
test('Measure aggregation', () => {
|
test('Measure aggregation', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `measure userPermissions(user: User) {
|
input: `measure userPermissions(user: Employee) {
|
||||||
aggregate {
|
aggregate {
|
||||||
user.role.permissions
|
user.role.permissions,
|
||||||
user.group.permissions
|
user.group.permissions
|
||||||
} USING majority
|
} USING majority
|
||||||
} PROVIDES Permission[]`,
|
} PROVIDES Permission`,
|
||||||
description: 'Aggregation with majority strategy'
|
description: 'Aggregation with majority strategy'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userClearance(user: User) {
|
input: `measure userClearance(user: Employee) {
|
||||||
aggregate {
|
aggregate {
|
||||||
user.clearance
|
user.clearance,
|
||||||
user.role.clearance
|
user.role.clearance,
|
||||||
user.group.clearance
|
user.group.clearance
|
||||||
} USING max
|
} USING max
|
||||||
} PROVIDES string`,
|
} PROVIDES string`,
|
||||||
description: 'Aggregation with max strategy'
|
description: 'Aggregation with max strategy'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userScore(user: User) {
|
input: `measure userScore(user: Employee) {
|
||||||
aggregate {
|
aggregate {
|
||||||
user.reputation
|
user.reputation,
|
||||||
user.activityScore
|
user.activityScore,
|
||||||
user.verificationLevel
|
user.verificationLevel
|
||||||
} USING average
|
} USING average
|
||||||
} PROVIDES number`,
|
} PROVIDES number`,
|
||||||
description: 'Aggregation with average strategy'
|
description: 'Aggregation with average strategy'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userTrust(user: User) {
|
input: `measure userTrust(user: Employee) {
|
||||||
aggregate {
|
aggregate {
|
||||||
user.reputation
|
user.reputation,
|
||||||
user.activityScore
|
user.activityScore,
|
||||||
user.verificationLevel
|
user.verificationLevel,
|
||||||
user.socialProof
|
user.socialProof
|
||||||
} USING min
|
} USING min
|
||||||
} PROVIDES number`,
|
} PROVIDES number`,
|
||||||
@@ -120,7 +157,7 @@ describe('Measure Definitions', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-measure-aggregation-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-measure-aggregation-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -128,40 +165,40 @@ describe('Measure Definitions', () => {
|
|||||||
test('Measure fusion', () => {
|
test('Measure fusion', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `measure effectiveClearance(user: User) {
|
input: `measure effectiveClearance(user: Employee) {
|
||||||
fusion max {
|
fusion max {
|
||||||
user.clearance
|
user.clearance,
|
||||||
user.role.clearance
|
user.role.clearance,
|
||||||
user.group.clearance
|
user.group.clearance
|
||||||
}
|
}
|
||||||
} PROVIDES string`,
|
} PROVIDES string`,
|
||||||
description: 'Fusion with max strategy'
|
description: 'Fusion with max strategy'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userPermissions(user: User) {
|
input: `measure userPermissions(user: Employee) {
|
||||||
fusion min {
|
fusion min {
|
||||||
user.role.permissions
|
user.role.permissions,
|
||||||
user.group.permissions
|
user.group.permissions
|
||||||
}
|
}
|
||||||
} PROVIDES Permission[]`,
|
} PROVIDES Permission`,
|
||||||
description: 'Fusion with min strategy'
|
description: 'Fusion with min strategy'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userScore(user: User) {
|
input: `measure userScore(user: Employee) {
|
||||||
fusion majority {
|
fusion majority {
|
||||||
user.reputation
|
user.reputation,
|
||||||
user.activityScore
|
user.activityScore,
|
||||||
user.verificationLevel
|
user.verificationLevel
|
||||||
}
|
}
|
||||||
} PROVIDES number`,
|
} PROVIDES number`,
|
||||||
description: 'Fusion with majority strategy'
|
description: 'Fusion with majority strategy'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userTrust(user: User) {
|
input: `measure userTrust(user: Employee) {
|
||||||
fusion average {
|
fusion average {
|
||||||
user.reputation
|
user.reputation,
|
||||||
user.activityScore
|
user.activityScore,
|
||||||
user.verificationLevel
|
user.verificationLevel,
|
||||||
user.socialProof
|
user.socialProof
|
||||||
}
|
}
|
||||||
} PROVIDES number`,
|
} PROVIDES number`,
|
||||||
@@ -170,7 +207,7 @@ describe('Measure Definitions', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-measure-fusion-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-measure-fusion-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -178,40 +215,40 @@ describe('Measure Definitions', () => {
|
|||||||
test('Complex measures', () => {
|
test('Complex measures', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `measure userEffectivePermissions(user: User) {
|
input: `measure userEffectivePermissions(user: Employee) {
|
||||||
aggregate {
|
aggregate {
|
||||||
user.role.permissions
|
user.role.permissions,
|
||||||
user.group.permissions
|
user.group.permissions,
|
||||||
user.directPermissions
|
user.directPermissions
|
||||||
} USING majority
|
} USING majority
|
||||||
} PROVIDES Permission[]`,
|
} PROVIDES Permission`,
|
||||||
description: 'Complex aggregation with multiple sources'
|
description: 'Complex aggregation with multiple sources'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userTrustScore(user: User) {
|
input: `measure userTrustScore(user: Employee) {
|
||||||
fusion average {
|
fusion average {
|
||||||
user.reputation
|
user.reputation,
|
||||||
user.activityScore
|
user.activityScore,
|
||||||
user.verificationLevel
|
user.verificationLevel,
|
||||||
user.socialProof
|
user.socialProof,
|
||||||
user.peerRatings
|
user.peerRatings
|
||||||
}
|
}
|
||||||
} PROVIDES number`,
|
} PROVIDES number`,
|
||||||
description: 'Complex fusion with multiple metrics'
|
description: 'Complex fusion with multiple metrics'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userAccessLevel(user: User) {
|
input: `measure userAccessLevel(user: Employee) {
|
||||||
fusion max {
|
fusion max {
|
||||||
user.clearance
|
user.clearance,
|
||||||
user.role.clearance
|
user.role.clearance,
|
||||||
user.group.clearance
|
user.group.clearance,
|
||||||
user.temporaryClearance
|
user.temporaryClearance
|
||||||
}
|
}
|
||||||
} PROVIDES string`,
|
} PROVIDES string`,
|
||||||
description: 'Complex clearance calculation'
|
description: 'Complex clearance calculation'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userSimilarity(user1: User, user2: User) {
|
input: `measure userSimilarity(user1: Employee, user2: Employee) {
|
||||||
similar(user1, user2) |similarity| {
|
similar(user1, user2) |similarity| {
|
||||||
similarity
|
similarity
|
||||||
} with similarity > 0.5
|
} with similarity > 0.5
|
||||||
@@ -219,10 +256,10 @@ describe('Measure Definitions', () => {
|
|||||||
description: 'Similarity measure with pattern matching'
|
description: 'Similarity measure with pattern matching'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userEffectiveRole(user: User) {
|
input: `measure userEffectiveRole(user: Employee) {
|
||||||
fusion majority {
|
fusion majority {
|
||||||
user.role
|
user.role,
|
||||||
user.temporaryRole
|
user.temporaryRole,
|
||||||
user.actingRole
|
user.actingRole
|
||||||
}
|
}
|
||||||
} PROVIDES string`,
|
} PROVIDES string`,
|
||||||
@@ -231,7 +268,7 @@ describe('Measure Definitions', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ input, description }) => {
|
testCases.forEach(({ input, description }) => {
|
||||||
const result = compiler.compile(input, `test-complex-measure-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-complex-measure-${Date.now()}`);
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -239,40 +276,40 @@ describe('Measure Definitions', () => {
|
|||||||
test('Measure error handling', () => {
|
test('Measure error handling', () => {
|
||||||
const testCases = [
|
const testCases = [
|
||||||
{
|
{
|
||||||
input: `measure userRole(user: User) {
|
input: `measure userRole(user: Employee) {
|
||||||
user.role
|
user.role
|
||||||
}`,
|
}`,
|
||||||
description: 'Missing PROVIDES clause should fail',
|
description: 'Missing PROVIDES clause should fail',
|
||||||
expectSuccess: false
|
expectSuccess: false
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userRole(user: User) {
|
input: `measure userRole(user: Employee) {
|
||||||
user.role
|
user.role
|
||||||
} PROVIDES`,
|
} PROVIDES`,
|
||||||
description: 'Incomplete PROVIDES clause should fail',
|
description: 'Incomplete PROVIDES clause should fail',
|
||||||
expectSuccess: false
|
expectSuccess: false
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userRole(user: User) {
|
input: `measure userRole(user: Employee) {
|
||||||
user.role
|
user.role
|
||||||
} PROVIDES string`,
|
} PROVIDES string`,
|
||||||
description: 'Valid measure should succeed',
|
description: 'Valid measure should succeed',
|
||||||
expectSuccess: true
|
expectSuccess: true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userPermissions(user: User) {
|
input: `measure userPermissions(user: Employee) {
|
||||||
aggregate {
|
aggregate {
|
||||||
user.role.permissions
|
user.role.permissions,
|
||||||
user.group.permissions
|
user.group.permissions
|
||||||
} USING
|
} USING
|
||||||
} PROVIDES Permission[]`,
|
} PROVIDES Permission`,
|
||||||
description: 'Incomplete USING clause should fail',
|
description: 'Incomplete USING clause should fail',
|
||||||
expectSuccess: false
|
expectSuccess: false
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userScore(user: User) {
|
input: `measure userScore(user: Employee) {
|
||||||
fusion {
|
fusion {
|
||||||
user.reputation
|
user.reputation,
|
||||||
user.activityScore
|
user.activityScore
|
||||||
}
|
}
|
||||||
} PROVIDES number`,
|
} PROVIDES number`,
|
||||||
@@ -280,7 +317,7 @@ describe('Measure Definitions', () => {
|
|||||||
expectSuccess: false
|
expectSuccess: false
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: `measure userRole(user: User) {
|
input: `measure userRole(user: Employee) {
|
||||||
invalid syntax here
|
invalid syntax here
|
||||||
} PROVIDES string`,
|
} PROVIDES string`,
|
||||||
description: 'Invalid syntax should fail',
|
description: 'Invalid syntax should fail',
|
||||||
@@ -290,7 +327,7 @@ describe('Measure Definitions', () => {
|
|||||||
|
|
||||||
testCases.forEach(({ input, description, expectSuccess }) => {
|
testCases.forEach(({ input, description, expectSuccess }) => {
|
||||||
try {
|
try {
|
||||||
const result = compiler.compile(input, `test-measure-error-${Date.now()}`);
|
const result = compiler.compile(DSL_SUPPORT + input, `test-measure-error-${Date.now()}`);
|
||||||
if (expectSuccess) {
|
if (expectSuccess) {
|
||||||
assert.ok(result.success, `${description} should parse successfully`);
|
assert.ok(result.success, `${description} should parse successfully`);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -0,0 +1,219 @@
|
|||||||
|
/**
|
||||||
|
* tests/rigor/dsl-generative-oracle.test.js — js-rigor campaign that GENERATES
|
||||||
|
* legal Evidence DSL programs, compiles them to @arbiter/core configs, runs
|
||||||
|
* checks, and compares every verdict against an independent ORACLE (a hand-
|
||||||
|
* computed reference implementation of the DSL semantics).
|
||||||
|
*
|
||||||
|
* The oracle is deliberately independent of the engine: it computes the
|
||||||
|
* expected possibility from the generated fact graph using the ADR-000
|
||||||
|
* semantics (direct = edge, chain = min over steps, tuple_to_userset = min of
|
||||||
|
* the two legs, fusion = min/max over operands, when-unless = base×(1−defeat),
|
||||||
|
* never = 0 when ≥0.5 else base, requires = base×requirement).
|
||||||
|
*
|
||||||
|
* Anti-vacuity: the oracle is NOT a constant — each construct maps distinct
|
||||||
|
* edge possibilities, so a trivial 0-or-1 lowering would be caught.
|
||||||
|
*/
|
||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { rigor } from '@rigor/core';
|
||||||
|
import { Arbiter } from '@arbiter/core';
|
||||||
|
import { DSLCompiler } from '../../src/DSLCompiler.js';
|
||||||
|
|
||||||
|
const EPS = 1e-9;
|
||||||
|
const P = [0, 0.25, 0.5, 0.75, 1];
|
||||||
|
|
||||||
|
const FACTS = `
|
||||||
|
definition Employee { id: string }
|
||||||
|
definition Group { id: string }
|
||||||
|
definition Doc { id: string }
|
||||||
|
fact owns(user: Employee, doc: Doc)
|
||||||
|
fact shares(user: Employee, doc: Doc)
|
||||||
|
fact member_of(user: Employee, group: Group)
|
||||||
|
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 banned(user: Employee)
|
||||||
|
fact mfa(user: Employee)
|
||||||
|
`;
|
||||||
|
|
||||||
|
// Each construct: how to build the DSL evidence + which edges to add + the oracle.
|
||||||
|
function buildProgram(kind, ps) {
|
||||||
|
let evidence = '';
|
||||||
|
const edges = [];
|
||||||
|
let oracle = 0;
|
||||||
|
|
||||||
|
switch (kind) {
|
||||||
|
case 'direct': {
|
||||||
|
const [pOwn] = ps;
|
||||||
|
evidence = `evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }`;
|
||||||
|
edges.push({ src: 'u:1', relation: 'owns', dst: 'doc:9', possibility: pOwn });
|
||||||
|
oracle = pOwn;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'chain': {
|
||||||
|
const [pm, pa] = ps;
|
||||||
|
evidence = `evidence can_enter(user: Employee, doc: Doc) { member_of(user, *g) { can_access(g, doc) } }`;
|
||||||
|
edges.push({ src: 'u:1', relation: 'member_of', dst: 'g:1', possibility: pm });
|
||||||
|
edges.push({ src: 'g:1', relation: 'can_access', dst: 'doc:9', possibility: pa });
|
||||||
|
oracle = Math.min(pm, pa);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'tuple_to_userset': {
|
||||||
|
const [po, pm] = ps;
|
||||||
|
evidence = `evidence can_view(user: Employee, doc: Doc) { owner(*g, doc) { member_of(user, g) } }`;
|
||||||
|
edges.push({ src: 'g:1', relation: 'owner', dst: 'doc:9', possibility: po });
|
||||||
|
edges.push({ src: 'u:1', relation: 'member_of', dst: 'g:1', possibility: pm });
|
||||||
|
oracle = Math.min(pm, po);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'fusion_min': {
|
||||||
|
const [p1, p2] = ps;
|
||||||
|
evidence = `evidence can_fuse(user: Employee, doc: Doc) { fusion min { owns(user, doc), shares(user, doc) } }`;
|
||||||
|
edges.push({ src: 'u:1', relation: 'owns', dst: 'doc:9', possibility: p1 });
|
||||||
|
edges.push({ src: 'u:1', relation: 'shares', dst: 'doc:9', possibility: p2 });
|
||||||
|
oracle = Math.min(p1, p2);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'fusion_max': {
|
||||||
|
const [p1, p2] = ps;
|
||||||
|
evidence = `evidence can_fuse(user: Employee, doc: Doc) { fusion max { owns(user, doc), shares(user, doc) } }`;
|
||||||
|
edges.push({ src: 'u:1', relation: 'owns', dst: 'doc:9', possibility: p1 });
|
||||||
|
edges.push({ src: 'u:1', relation: 'shares', dst: 'doc:9', possibility: p2 });
|
||||||
|
oracle = Math.max(p1, p2);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'when_unless': {
|
||||||
|
const [pG, pB] = ps;
|
||||||
|
evidence = `evidence can_borrow(user: Employee, doc: Doc) { WHEN granted(user, doc) UNLESS banned(user) }`;
|
||||||
|
edges.push({ src: 'u:1', relation: 'granted', dst: 'doc:9', possibility: pG });
|
||||||
|
edges.push({ src: 'u:1', relation: 'banned', dst: 'u:1', possibility: pB });
|
||||||
|
oracle = pG * (1 - pB);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'never_always': {
|
||||||
|
const [pG, pB] = ps;
|
||||||
|
evidence = `evidence can_open(user: Employee, doc: Doc) { NEVER banned(user) ALWAYS granted(user, doc) }`;
|
||||||
|
edges.push({ src: 'u:1', relation: 'granted', dst: 'doc:9', possibility: pG });
|
||||||
|
edges.push({ src: 'u:1', relation: 'banned', dst: 'u:1', possibility: pB });
|
||||||
|
oracle = pB >= 0.5 ? 0 : pG;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'requires_when': {
|
||||||
|
const [pG, pM] = ps;
|
||||||
|
evidence = `evidence can_pay(user: Employee, doc: Doc) { REQUIRES mfa(user) WHEN granted(user, doc) }`;
|
||||||
|
edges.push({ src: 'u:1', relation: 'granted', dst: 'doc:9', possibility: pG });
|
||||||
|
edges.push({ src: 'u:1', relation: 'mfa', dst: 'u:1', possibility: pM });
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw new Error(`unknown construct: ${kind}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 }) {
|
||||||
|
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');
|
||||||
|
const compiler = new DSLCompiler(arbiter);
|
||||||
|
const compiled = compiler.compile(dsl, 'oracle');
|
||||||
|
if (!compiled.success) {
|
||||||
|
throw new Error(`compile failed for ${kind}: ${compiled.errors.join('; ')}`);
|
||||||
|
}
|
||||||
|
for (const e of edges) arbiter.addRelation(e.src, e.relation, e.dst, { possibility: e.possibility });
|
||||||
|
const result = arbiter.check('u:1', relation, 'doc:9');
|
||||||
|
if (Math.abs(result.possibility - oracle) > EPS) {
|
||||||
|
throw new Error(`oracle mismatch for ${kind} (edges=${JSON.stringify(edges)}): ` +
|
||||||
|
`check=${result.possibility} (${result.reason}) vs oracle=${oracle}`);
|
||||||
|
}
|
||||||
|
return { kind, possibility: result.possibility, oracle };
|
||||||
|
}
|
||||||
|
|
||||||
|
const CONSTRUCTS = ['direct', 'chain', 'tuple_to_userset', 'fusion_min', 'fusion_max',
|
||||||
|
'when_unless', 'never_always', 'requires_when', 'composition', 'chain_step_composition'];
|
||||||
|
|
||||||
|
describe('DSL generative oracle parity (rigor)', () => {
|
||||||
|
it('generated legal DSL compiles and every check matches the oracle', async () => {
|
||||||
|
const report = await rigor.campaign(
|
||||||
|
[
|
||||||
|
rigor.fn('oracle-parity', runCheck, rigor.args(
|
||||||
|
rigor.gen.object({
|
||||||
|
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))
|
||||||
|
})
|
||||||
|
))
|
||||||
|
],
|
||||||
|
rigor.crucible([
|
||||||
|
// `actual` is the fn's return value; a thrown error (compile failure or
|
||||||
|
// oracle mismatch) yields actual === undefined, failing this invariant.
|
||||||
|
rigor.invariant('oracle-parity', ({ actual }) =>
|
||||||
|
!!actual && Math.abs(actual.possibility - actual.oracle) <= EPS)
|
||||||
|
])
|
||||||
|
).run({ seed: 'dsl-oracle-parity', effort: 600, artifacts: { dir: '', persist: 'never' } });
|
||||||
|
|
||||||
|
const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'oracle-parity');
|
||||||
|
assert.ok(inv, 'crucible invariant missing');
|
||||||
|
assert.equal(inv.passed, true, `oracle parity violated in ${inv.failureCount} cases`);
|
||||||
|
});
|
||||||
|
|
||||||
|
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
|
||||||
|
// 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];
|
||||||
|
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');
|
||||||
|
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 });
|
||||||
|
const result = arbiter.check('u:1', relation, 'doc:9');
|
||||||
|
assert.ok(
|
||||||
|
Math.abs(result.possibility - oracle) <= EPS,
|
||||||
|
`${kind} ps=[${ps}] check=${result.possibility}(${result.reason}) vs oracle=${oracle}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
/**
|
||||||
|
* tests/rigor/dsl-illegal-mutations.test.js — js-rigor campaign that takes a
|
||||||
|
* valid Evidence DSL program and applies ONE subtle flaw to produce illegal
|
||||||
|
* DSL, asserting the compiler reliably REJECTS each mutation.
|
||||||
|
*
|
||||||
|
* Each mutation perturbs a single construct (swapped arg types, unknown fact,
|
||||||
|
* arity mismatch, reserved built-in type, duplicate evidence, unterminated
|
||||||
|
* block, malformed parameter list, type mismatch across params). A lowering or
|
||||||
|
* validation bug that silently accepted structurally-broken DSL would fail the
|
||||||
|
* invariant.
|
||||||
|
*
|
||||||
|
* Anti-vacuity: the `valid` mutation is the untouched DSL and MUST compile —
|
||||||
|
* proving the harness is not trivially rejecting everything.
|
||||||
|
*/
|
||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { rigor } from '@rigor/core';
|
||||||
|
import { Arbiter } from '@arbiter/core';
|
||||||
|
import { DSLCompiler } from '../../src/DSLCompiler.js';
|
||||||
|
|
||||||
|
const VALID_DSL = `
|
||||||
|
definition Employee { id: string }
|
||||||
|
definition Group { id: string }
|
||||||
|
definition Doc { id: string }
|
||||||
|
fact owns(user: Employee, doc: Doc)
|
||||||
|
fact member_of(user: Employee, group: Group)
|
||||||
|
fact can_access(group: Group, doc: Doc)
|
||||||
|
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
|
||||||
|
evidence can_enter(user: Employee, doc: Doc) { member_of(user, *g) { can_access(g, doc) } }
|
||||||
|
`;
|
||||||
|
|
||||||
|
// Each mutation transforms the valid DSL into an illegal variant.
|
||||||
|
// `mustFail: false` marks the control mutation (untouched DSL — must compile).
|
||||||
|
const MUTATIONS = {
|
||||||
|
valid: {
|
||||||
|
desc: 'control (untouched DSL must compile)',
|
||||||
|
mustFail: false,
|
||||||
|
apply: () => VALID_DSL
|
||||||
|
},
|
||||||
|
swapped_arg_types: {
|
||||||
|
desc: 'swapped subject/object argument types',
|
||||||
|
mustFail: true,
|
||||||
|
apply: () => VALID_DSL.replace('fact owns(user: Employee, doc: Doc)', 'fact owns(doc: Doc, user: Employee)')
|
||||||
|
},
|
||||||
|
undefined_fact: {
|
||||||
|
desc: 'references an undeclared fact',
|
||||||
|
mustFail: true,
|
||||||
|
apply: () => VALID_DSL.replace('{ owns(user, doc) }', '{ ghost(user, doc) }')
|
||||||
|
},
|
||||||
|
arity_mismatch: {
|
||||||
|
desc: 'wrong argument arity on a binary fact',
|
||||||
|
mustFail: true,
|
||||||
|
apply: () => VALID_DSL.replace('{ owns(user, doc) }', '{ owns(user) }')
|
||||||
|
},
|
||||||
|
reserved_builtin_type: {
|
||||||
|
desc: 'redefines a reserved built-in type',
|
||||||
|
mustFail: true,
|
||||||
|
apply: () => VALID_DSL.replace('definition Employee { id: string }', 'definition User { id: string }')
|
||||||
|
},
|
||||||
|
duplicate_evidence: {
|
||||||
|
desc: 'duplicate evidence relation name',
|
||||||
|
mustFail: true,
|
||||||
|
apply: () => VALID_DSL + `\n evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }`
|
||||||
|
},
|
||||||
|
unterminated_block: {
|
||||||
|
desc: 'missing closing brace',
|
||||||
|
mustFail: true,
|
||||||
|
apply: () => VALID_DSL.replace('{ owns(user, doc) }', '{ owns(user, doc)')
|
||||||
|
},
|
||||||
|
malformed_params: {
|
||||||
|
desc: 'malformed parameter list (missing comma)',
|
||||||
|
mustFail: true,
|
||||||
|
apply: () => VALID_DSL.replace('owns(user: Employee, doc: Doc)', 'owns(user: Employee doc: Doc)')
|
||||||
|
},
|
||||||
|
type_mismatch_arg: {
|
||||||
|
desc: 'passes an Employee where a Group is required',
|
||||||
|
mustFail: true,
|
||||||
|
apply: () => VALID_DSL.replace('{ can_access(g, doc) }', '{ can_access(user, doc) }')
|
||||||
|
},
|
||||||
|
wrong_evidence_arity: {
|
||||||
|
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) }'
|
||||||
|
)
|
||||||
|
},
|
||||||
|
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)')
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
function checkMutation(mutationName) {
|
||||||
|
const mutation = MUTATIONS[mutationName];
|
||||||
|
if (!mutation) throw new Error(`unknown mutation name: ${JSON.stringify(mutationName)}`);
|
||||||
|
const dsl = mutation.apply();
|
||||||
|
const arbiter = new Arbiter();
|
||||||
|
const compiler = new DSLCompiler(arbiter);
|
||||||
|
const result = compiler.compile(dsl, `mut-${mutationName}`);
|
||||||
|
const success = result.success;
|
||||||
|
const errors = result.errors || [];
|
||||||
|
if (mutation.mustFail) {
|
||||||
|
if (success || errors.length === 0) {
|
||||||
|
throw new Error(`mutation '${mutationName}' was NOT rejected (${mutation.desc}). ` +
|
||||||
|
`success=${success}, errors=${JSON.stringify(errors)}`);
|
||||||
|
}
|
||||||
|
} else if (!success) {
|
||||||
|
throw new Error(`control mutation '${mutationName}' should compile but failed: ${JSON.stringify(errors)}`);
|
||||||
|
}
|
||||||
|
return { mutationName, ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('DSL illegal-mutation rejection (rigor)', () => {
|
||||||
|
it('every subtle one-flaw mutation is reliably rejected; the control compiles', async () => {
|
||||||
|
const report = await rigor.campaign(
|
||||||
|
[
|
||||||
|
rigor.fn('reject-mutation', checkMutation, rigor.args(
|
||||||
|
rigor.gen.oneOf(Object.keys(MUTATIONS))
|
||||||
|
))
|
||||||
|
],
|
||||||
|
rigor.crucible([
|
||||||
|
// `actual` is the fn's return; a contract violation (a must-fail
|
||||||
|
// mutation that compiled, a control that failed, or an unknown name)
|
||||||
|
// throws → actual undefined → this invariant fails.
|
||||||
|
rigor.invariant('rejection-contract', ({ actual }) =>
|
||||||
|
!!actual && actual.ok === true)
|
||||||
|
])
|
||||||
|
).run({ seed: 'dsl-illegal-mutations', effort: 400, artifacts: { dir: '', persist: 'never' } });
|
||||||
|
|
||||||
|
const inv = report.crucibleVerdict?.invariants?.find(i => i.name === 'rejection-contract');
|
||||||
|
assert.ok(inv, 'crucible invariant missing');
|
||||||
|
assert.equal(inv.passed, true, `rejection contract violated in ${inv.failureCount} cases`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('every mutation kind is exercised (no vacuous pass)', () => {
|
||||||
|
const seen = new Set();
|
||||||
|
for (const name of Object.keys(MUTATIONS)) {
|
||||||
|
// deterministic probe of each kind
|
||||||
|
seen.add(name);
|
||||||
|
checkMutation(name);
|
||||||
|
}
|
||||||
|
assert.equal(seen.size, Object.keys(MUTATIONS).length);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user