12 Commits

Author SHA1 Message Date
Dvorak 7898a7990a 1.13.0: measure + evidence compose; value-graph now a registry dep
CI / test (push) Successful in 24s
CI / publish (push) Failing after 10s
- DSLValueGraph integrates the evidence DSL with @arbiter/value-graph: measures
  become typed value-graph nodes; attach() wires runtime.measure through the graph.
- DSLRuntime.check() now retrieves required MEASURE values and injects them as
  value-carrying self-edges, so an evidence comparator over a measure (e.g.
  budget_used(user) <= budget_limit(user)) evaluates — measure and evidence
  compose (provider-sourced AND value-graph-sourced), with 3 new composition tests.
- BUILTIN_TYPES: bigint → buffer (the value-graph wire is JSON-free/bigint-free).
- @arbiter/value-graph: file:../value-graph → ^0.1.0 (registry); CI auth adds
  @push-stream-std registry for the transitive dep.
- rigor core ^3.1.2 / probe ^0.0.8.
2026-08-04 17:51:13 -07:00
John Dvorak b145c979ab chore: sync lockfile to core ^1.0.8 for CI publish
CI / test (push) Successful in 20s
CI / publish (push) Successful in 9s
2026-08-03 20:47:08 -07:00
John Dvorak 512831a8fc chore: bump version to 1.12.1, core dep ^1.0.8 for CI publish
CI / test (push) Failing after 7s
CI / publish (push) Has been skipped
2026-08-03 20:46:25 -07:00
John Dvorak 2a7f4c315b feat: sources wired as recency-gated injectables; transitive closure, NOT scoping, recompile-scope uninstall; targeted parse errors
CI / test (push) Successful in 20s
CI / publish (push) Has been skipped
BEHAVES AS transitive now emits bounded multi_hop configs (direct checks and
evidence references), fixing a silent no-op. NOT builds keep _subjectAsObject
scoping so unary predicates negate the right node, and value-typed evidence
objects gate by exact edge value. Recompiling a scope uninstalls its stale
relation configs (compileMultiple coexistence preserved). Sources become
injectable relations honored by requiredFacts with a within-X recency gate.
Duplicate definition fields and three common declaration mistakes (within on a
fact, two BEHAVES clauses, limit on a non-pattern body) now produce targeted
errors. Provider edges referencing unknown nodes are warned and dropped.
2026-08-03 20:27:13 -07:00
John Dvorak 4d498b07e8 feat: bounded self-recursion (transitive closure) for evidence
CI / publish (push) Successful in 9s
CI / test (push) Successful in 18s
An evidence whose config contains a chain step referencing ITSELF is now
unrolled at compile time into a bounded transitive closure: a union of paths
— base, hop+base, hop²+base, …, hop^N+base — where `hop` is the recursive
chain's steps before the self-reference and the depth N comes from the
pattern's `limit N` (or the compiler's maxRecursionDepth default, 3). The
base (the evidence's non-recursive statements) is verified as a condition
step at each path's terminal node, so the engine needs no new machinery.

- Chain configs carry the pattern's `limit` as maxDepth.
- resolveEvidenceReferences detects a self-reference (_findSelfReference),
  extracts the base (_extractBase), and unrolls (_unrollRecursiveEvidence).
- Pure recursion with no base case is a compile-time error; mutual cycles
  between distinct evidence remain a compile-time error.

Example: can_access_via = can_access OR (reports_to + can_access_via) up to
the declared limit grants access inherited up a reporting chain.

Tests: Recursion (unroll shape, base + multi-hop grants, depth-limit
enforcement, default depth, pure-recursion error, mutual-cycle guard).
2026-08-03 16:35:19 -07:00
John Dvorak 9111c4b20d feat: duration seconds; required fields; type-validated insertions/updates/retrievals
CI / publish (push) Successful in 9s
CI / test (push) Successful in 19s
- Duration literals now accept s/m/h/d/w (was m/h/d/w): 'BEHAVES { ttl 30s }'
  is 30s, and 'within 30s' temporal expressions parse.
- Definition fields are REQUIRED by default ('field: type'); 'field: type?'
  marks a field optional. addNode enforces presence on insert, getSchema
  exposes per-field requiredness, and updateNodeData still validates the
  provided fields' types.
- Provider-returned edges are validated against the fact's declared typing:
  a value-carrying fact must return { value, possibility } with a value of the
  declared type (bare-number shorthand is rejected); a non-value fact must not
  carry a value; and every possibility must lie in [0, 1]. Violations throw a
  clear provider-authoring error instead of silently injecting malformed edges.

Tests: DSLRuntimeTyping (duration units, required-field enforcement, schema
requiredness, value-type + shape + possibility validation).
2026-08-03 16:00:49 -07:00
John Dvorak aa38fbfd8c feat: provider-cache bypass knob; reject non-final comparator chain steps
CI / publish (push) Successful in 9s
CI / test (push) Successful in 18s
- check() gains cacheProviderResults (per-check option + policy default): the
  provider cache is a STORE-RETRIEVAL cache (wall-clock), independent of the
  caller's decision { now }; callers who pin time or want fresh retrieval can
  opt out per-check or globally.
- The generator now rejects a comparator evidence referenced at a NON-final
  chain position (a comparator compares values at (src, candidate) but
  provides no candidate set, so it cannot enumerate intermediate nodes).
  Final-position comparators still lower to condition steps.

Tests: cache bypass (per-check + policy), comparator final OK / intermediate
error.
2026-08-03 15:43:59 -07:00
John Dvorak ad365a65a9 feat: direct fact checks consult registered providers
CI / test (push) Successful in 19s
CI / publish (push) Successful in 9s
Checking a FACT relation directly (rt.check('u:1', 'owns', 'doc:9')) now
runs the provider-retrieval pipeline instead of returning 0 without ever
consulting the registered provider. The retrieval set for a direct fact
check is the fact itself (plus, for evidence checks, the injectable deps as
before). The result reports requiredFacts/providedFacts/missingFacts for the
fact, and missingFacts surfaces 'no_provider' when neither a provider nor an
edge can satisfy the check.
2026-08-03 15:25:33 -07:00
John Dvorak 6214780244 feat: provider-result caching with time expiry + DSL fact-level TTL
CI / publish (push) Successful in 9s
CI / test (push) Successful in 18s
Automatically-retrieved facts (balances, sessions, etc.) are now cached with
a time expiry so repeated checks don't re-invoke the underlying data store.

- check(): registered providers cache their normalized edges per
  (relation, subject, object) with a TTL; a fresh entry is reused without
  re-invoking the provider. Per-check factProviders are one-off observations
  and stay cache-transparent (no read, no write).
- TTL resolution: DSL-declared 'BEHAVES { ttl <duration> }' on a fact >
  setFactTTL(relation, ms) > policy.providerCacheTTL (default 30s; 0 disables).
- Grammar: facts may now declare a freshness window via
  'fact balance(user, amount) BEHAVES { ttl 1h }' (previously BEHAVES only
  accepted 'AS edge|transitive|hierarchical|symmetrical_graph'). The runtime
  indexes it as the fact's ttlMs.
- registerFact/unregisterFact, graph mutations (add/update/remove node or
  relation), and invalidateProviderCache(relation?) keep the cache consistent.
- Injectable clock (default wall clock) drives cache freshness, mirroring the
  core's unpinned-clock contract.

Tests: DSLRuntimeCache (reuse within TTL, expiry re-invoke, per-check
override transparency, registerFact invalidation, mutation invalidation,
per-relation/all invalidation, policy default, DSL-declared 1h TTL).
2026-08-03 14:32:15 -07:00
John Dvorak 3ace783a59 feat: intermediate chain condition steps + _subjectIsObject unary scoping
CI / publish (push) Successful in 10s
CI / test (push) Successful in 19s
- _expandChainSteps: a logical/defeasible evidence referenced by a chain step
  is now a condition step ({ rule, conditionStep }) at ANY position. As the
  FINAL step the engine verifies it at (intermediate, object); as an
  INTERMEDIATE step the engine expands it from the current node (rule-based
  reachability: base edges' destinations filtered by the rule's
  defeaters/requirements) and continues traversal from each discovered node.
- buildPredicateRule / buildDirectRule: unary predicate calls whose subject
  entity IS the evidence's object parameter (trusted(other) inside
  peer_trusted(user, other)) are marked _subjectIsObject (was: only subject-var
  calls got _subjectAsObject). Requires @arbiter/core@^1.0.4.

Tests: ChainConditionStep intermediate expansion; oracle campaign gains a
chain_intermediate_condition construct (oracle = min(peer*(1-trusted), read)).
2026-08-03 13:36:16 -07:00
John Dvorak fe162251fc feat: DSLRuntime schema introspection, per-relation providers, retrieval loop
CI / publish (push) Successful in 10s
CI / test (push) Successful in 20s
The higher-order DSL+Core wrapper now covers the full contract the DSL
informs, beyond the typed mutations already present:

- getSchema(): serializable introspection of the compiled type system —
  entity types/fields, facts (params + injectable flag), evidence (with
  transitive dependsOn), and registered providers. relationNames() lists all
  declared relations. (The DSL's type system was always present; this exposes
  it programmatically.)
- registerFact(relation, fn) / unregisterFact / registeredFacts: per-relation
  async providers that retrieve missing partial-graph edges; per-check
  factProviders merge OVER registered ones.
- Bounded fixed-point provider retrieval loop (maxProviderRounds): each round
  invokes providers for required facts whose edges are not yet injected. A
  provider may return edges for relations other than its own — those satisfy
  the other required facts and can unblock later rounds.
- check() now type-validates FACT relations too (not just evidence); edge
  normalization preserves a provider edge's own relation name.
- removeNode / removeRelation passthroughs; require() throws on denial for
  middleware.
- Field typing extended to the DSL's full value-type universe
  (timestamp/duration accept number or string; object/any accept anything).

Tests: DSLRuntimeExt (schema, registration, merge, fixed-point, require,
removal, fact-check validation, timestamp typing).
2026-08-03 12:45:16 -07:00
John Dvorak 351551af0f feat: chain condition steps — defeasible/logical evidence as final chain hop
CI / publish (push) Successful in 9s
CI / test (push) Successful in 18s
A chain's FINAL (object-side) step may now reference a defeasible/logical
evidence. The compiler lowers it to a condition step
({ rule: <config>, conditionStep: true }) that the engine verifies at
(intermediate, object) instead of traversing an edge. Requires
@arbiter/core@^1.0.3 (ChainRule condition-step support).

- _expandChainSteps: a logical/defeasible/comparator evidence is expressible
  as a final condition step; non-final such steps remain a compile error
  (a condition cannot discover intermediate nodes).
- Dependency collection (generator + DSLRuntime) descends into condition-step
  rule configs, so partial-graph requirements reach through them.

Tests: ChainConditionStep (defeasible + ALWAYS steps, independent checkability,
parallel aggregation), oracle campaign chain_condition_step construct
(oracle = min(pm, pv*(1-pb))), DSLRuntime transitive required facts through a
condition step.
2026-08-03 12:08:54 -07:00
27 changed files with 4279 additions and 1084 deletions
+4
View File
@@ -26,6 +26,8 @@ jobs:
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 "//hub.kl1.tenere.ai/api/packages/Tenere/npm/:_authToken=${{ secrets.PACKAGE_TOKEN }}" >> .npmrc
echo "@push-stream-std:registry=https://hub.kl1.tenere.ai/api/packages/push-stream-std/npm/" >> .npmrc
echo "//hub.kl1.tenere.ai/api/packages/push-stream-std/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
@@ -52,6 +54,8 @@ jobs:
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 "//hub.kl1.tenere.ai/api/packages/Tenere/npm/:_authToken=${{ secrets.PACKAGE_TOKEN }}" >> .npmrc
echo "@push-stream-std:registry=https://hub.kl1.tenere.ai/api/packages/push-stream-std/npm/" >> .npmrc
echo "//hub.kl1.tenere.ai/api/packages/push-stream-std/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
+2
View File
@@ -4,3 +4,5 @@
//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}
@push-stream-std:registry=https://hub.kl1.tenere.ai/api/packages/push-stream-std/npm/
//hub.kl1.tenere.ai/api/packages/push-stream-std/npm/:_authToken=${PACKAGE_TOKEN}
+26
View File
@@ -0,0 +1,26 @@
// DSLValueGraph measure hotpath (async retrieval for authorization checks).
import { performance } from 'node:perf_hooks';
import { DSLRuntime, DSLValueGraph } from '../src/index.js';
import { Arbiter } from '@arbiter/core';
const rt = new DSLRuntime(new Arbiter()).compile('measure budget(user: string) { } PROVIDES number', 'bench');
const dvg = new DSLValueGraph(rt);
dvg.attach();
dvg.setValue('budget', { __subject: 'u:1', user: 'u:1' }, 1250);
async function measureCached() { return dvg.measure('budget', { __subject: 'u:1', user: 'u:1' }); }
await measureCached(); // warm
let t0 = performance.now();
let N = 20_000;
for (let i = 0; i < N; i++) await measureCached();
console.log(`dvg.measure cached (async) ${(((performance.now() - t0) / N) * 1e6).toFixed(0).padStart(8)} ns/op ${Math.round(N / ((performance.now() - t0) / 1000)).toLocaleString()} ops/sec`);
// cold: a fresh measure with an external resolver computing on the fly
const cold = new DSLValueGraph(new DSLRuntime(new Arbiter()).compile('measure b(user: string) { } PROVIDES number', 'b'));
cold.resolve('b', (s) => 99);
async function measureCold() { return cold.measure('b', { __subject: 'u:1', user: 'u:1' }); }
await measureCold();
t0 = performance.now();
N = 20_000;
for (let i = 0; i < N; i++) await measureCold();
console.log(`dvg.measure cold (resolver) ${(((performance.now() - t0) / N) * 1e6).toFixed(0).padStart(8)} ns/op`);
+112 -82
View File
@@ -1,25 +1,25 @@
{
"name": "@arbiter/evidence-dsl",
"version": "1.1.0",
"version": "1.13.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@arbiter/evidence-dsl",
"version": "1.1.0",
"version": "1.13.0",
"license": "ISC",
"dependencies": {
"@arbiter/core": "^1.0.2"
"@arbiter/core": "^1.0.8",
"@arbiter/value-graph": "^0.1.0",
"@rigor/probe": "^0.0.8"
},
"devDependencies": {
"@rigor/core": "^3.1.0",
"@rigor/core": "^3.1.2",
"peggy": "^5.0.6"
}
},
"node_modules/@arbiter/core": {
"version": "1.0.2",
"resolved": "https://hub.kl1.tenere.ai/api/packages/Arbiter/npm/%40arbiter%2Fcore/-/1.0.2/core-1.0.2.tgz",
"integrity": "sha512-N1duiHy1Rlsxqpvu8uPf4tMaLOQ2tNXvGs53jLkRcIAYqafIAMvcf0BPS2iE2xVKNsqY92+F05bZZEAO5jnbyQ==",
"version": "1.0.8",
"license": "ISC",
"dependencies": {
"@tenere/pltc-core": "^0.6.3",
@@ -27,10 +27,19 @@
"uuidv7": "^1.0.2"
}
},
"node_modules/@arbiter/value-graph": {
"version": "0.1.0",
"resolved": "https://hub.kl1.tenere.ai/api/packages/Arbiter/npm/%40arbiter%2Fvalue-graph/-/0.1.0/value-graph-0.1.0.tgz",
"integrity": "sha512-sofmF6O/o3bUf2Vzg24MxSB6NLQR8s2xjaBqL+k2LbGhlmt4/lHD9J6l/CjgObn+4UsXjb/QEccZ8rX0BFOUKg==",
"license": "ISC",
"dependencies": {
"@push-stream-std/push-pushable": "*",
"@push-stream-std/push-stream-base": "*",
"@rigor/probe": "^0.0.8"
}
},
"node_modules/@peggyjs/from-mem": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/@peggyjs/from-mem/-/from-mem-3.1.3.tgz",
"integrity": "sha512-LLlgtfXIaeYXoOYovOI0spLM8ZXaqkAlmcRRrLzHJzLMqkU6Sw0R4KMoCoHx1PjaP815pSCBlS+BN6aD8t1Jgg==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -40,53 +49,70 @@
"node": ">=20.8"
}
},
"node_modules/@push-stream-std/push-pushable": {
"version": "0.0.10",
"resolved": "https://hub.kl1.tenere.ai/api/packages/push-stream-std/npm/%40push-stream-std%2Fpush-pushable/-/0.0.10/push-pushable-0.0.10.tgz",
"integrity": "sha512-xf8nt50zckM8G+WRKV5RTNl4EEe6rhzuplNfqpdZ/b8kx0HnuTawDHlL0R449PKqG9X4DOQ5RzBrX2jYAnfY2A==",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@push-stream-std/push-stream-base": "*"
}
},
"node_modules/@push-stream-std/push-stream-base": {
"version": "0.0.9",
"resolved": "https://hub.kl1.tenere.ai/api/packages/push-stream-std/npm/%40push-stream-std%2Fpush-stream-base/-/0.0.9/push-stream-base-0.0.9.tgz",
"integrity": "sha512-RCbTwQz88XR0j0f/0NWIWgQ3NBQUUICu+CRHzOAvYfG2YQ8j+aTczYWTEedJJhGA+svcFrAQ8Oai/UnjtQ0l3Q==",
"license": "SEE LICENSE IN LICENSE"
},
"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": "*"
},
"engines": {
"node": ">=22.0.0"
}
},
"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": "*"
},
"engines": {
"node": ">=22.0.0"
}
},
"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": "*"
},
"engines": {
"node": ">=18.0.0"
}
},
"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": "*"
},
"engines": {
"node": ">=18.0.0"
}
},
"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==",
"version": "3.1.2",
"dev": true,
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
@@ -110,24 +136,25 @@
"@rigor/spec": "*",
"@rigor/storage": "*",
"@rigor/trace": "*"
},
"engines": {
"node": ">=22.0.0"
}
},
"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": "*"
},
"engines": {
"node": ">=18.0.0"
}
},
"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": {
@@ -135,40 +162,43 @@
"@rigor/rng": "*",
"@rigor/shrink": "*",
"@rigor/trace": "*"
},
"engines": {
"node": ">=18.0.0"
}
},
"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": "*"
},
"engines": {
"node": ">=22.0.0"
}
},
"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": "*"
},
"engines": {
"node": ">=18.0.0"
}
},
"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"
"license": "SEE LICENSE IN LICENSE",
"engines": {
"node": ">=22.0.0"
}
},
"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": {
@@ -180,12 +210,13 @@
"@rigor/rng": "*",
"@rigor/shrink": "*",
"@rigor/trace": "*"
},
"engines": {
"node": ">=18.0.0"
}
},
"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": {
@@ -193,24 +224,25 @@
"@rigor/rng": "*",
"@rigor/scheduler": "*",
"@rigor/trace": "*"
},
"engines": {
"node": ">=18.0.0"
}
},
"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,
"version": "0.0.8",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@rigor/fault": "*",
"@rigor/gen": "*",
"@rigor/trace": "*"
},
"engines": {
"node": ">=22.0.0"
}
},
"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": {
@@ -221,30 +253,32 @@
"@rigor/rng": "*",
"@rigor/shrink": "*",
"@rigor/trace": "*"
},
"engines": {
"node": ">=18.0.0"
}
},
"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": "*"
},
"engines": {
"node": ">=18.0.0"
}
},
"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"
"license": "SEE LICENSE IN LICENSE",
"engines": {
"node": ">=18.0.0"
}
},
"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": {
@@ -252,40 +286,43 @@
"@rigor/rng": "*",
"@rigor/shrink": "*",
"@rigor/trace": "*"
},
"engines": {
"node": ">=18.0.0"
}
},
"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": "*"
},
"engines": {
"node": ">=22.0.0"
}
},
"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"
"license": "SEE LICENSE IN LICENSE",
"engines": {
"node": ">=18.0.0"
}
},
"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": "*"
},
"engines": {
"node": ">=18.0.0"
}
},
"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": {
@@ -293,34 +330,37 @@
"@rigor/rng": "*",
"@rigor/scheduler": "*",
"@rigor/trace": "*"
},
"engines": {
"node": ">=18.0.0"
}
},
"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"
"license": "SEE LICENSE IN LICENSE",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@tenere/graph-core": {
"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",
"integrity": "sha512-29EzF1yBVLuaaapmrL+xNGRaWsM2Ln0G+WHVJURNzwQnDUC2ZSgaeVRMGj3aHFOj2K4mfSh9JqBP5Az2ZHU4pw==",
"license": "MIT"
"license": "MIT",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@tenere/pltc-core": {
"version": "0.6.3",
"resolved": "https://hub.kl1.tenere.ai/api/packages/Tenere/npm/%40tenere%2Fpltc-core/-/0.6.3/pltc-core-0.6.3.tgz",
"integrity": "sha512-+XsxNw35fyX8ku19FfyFsb6DgYoaKb6wkAbo1VF+moeyZ0D3AqDTofsBnd2sv5o2y8RpB3XftBxt0Hv1sBcQtg==",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@tenere/graph-core": "^1.0.1"
},
"engines": {
"node": ">=22.0.0"
}
},
"node_modules/commander": {
"version": "14.0.3",
"resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz",
"integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -329,14 +369,10 @@
},
"node_modules/heapify": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/heapify/-/heapify-1.0.2.tgz",
"integrity": "sha512-h/b3y12Orh2VsISvDsF/vulkoKH38P7yr223hfWJILo3imy7dX8f9ZrBgkkfLsJG11g8GI1/y6+8POSxgR7YcQ==",
"license": "MIT"
},
"node_modules/peggy": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/peggy/-/peggy-5.1.0.tgz",
"integrity": "sha512-IEo5aYRZ2kXH4Qby06cjtL114PZnwLoTiA41vUmg2vPZgANn+c87m5BUurhuDr5/cu758ZlpgsAfBVx+hhO5+w==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -353,8 +389,6 @@
},
"node_modules/semver": {
"version": "7.7.4",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
"dev": true,
"license": "ISC",
"bin": {
@@ -366,8 +400,6 @@
},
"node_modules/source-map-generator": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/source-map-generator/-/source-map-generator-2.0.6.tgz",
"integrity": "sha512-IlassDs1Ve8nV6uyQZXF9kdkJpVKnMte2JZQXu13M0A5zwc+vu6+LNHfmxsHBMDtoZE21RHiKI0/xvpecZRCNg==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
@@ -376,8 +408,6 @@
},
"node_modules/uuidv7": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/uuidv7/-/uuidv7-1.2.1.tgz",
"integrity": "sha512-4kPkK3/XTQW9Hbm4CaqfICn+kY9LJtDVEOfgsRRra/+n2Ofg4NqzRFceAkxvQ/Ud/6BpHOPzj8cirqM7TzTN5Q==",
"license": "Apache-2.0",
"bin": {
"uuidv7": "cli.js"
+7 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@arbiter/evidence-dsl",
"version": "1.3.0",
"version": "1.13.0",
"description": "Evidence DSL v2 compiler: translates the natural Evidence DSL (ADR-000) into @arbiter/core relation configurations.",
"license": "ISC",
"type": "module",
@@ -21,13 +21,16 @@
],
"scripts": {
"test": "node --test --test-force-exit \"tests/**/*.test.js\"",
"generate:parser": "node scripts/generate-parser.js"
"generate:parser": "node scripts/generate-parser.js",
"bench": "node bench/measure-hotpath.mjs"
},
"dependencies": {
"@arbiter/core": "^1.0.2"
"@arbiter/core": "^1.0.8",
"@arbiter/value-graph": "^0.1.0",
"@rigor/probe": "^0.0.8"
},
"devDependencies": {
"@rigor/core": "^3.1.0",
"@rigor/core": "^3.1.2",
"peggy": "^5.0.6"
}
}
+6 -4
View File
@@ -7,10 +7,10 @@ import { validateDslText } from './validation/DSLValidation.js';
* Compiles DSL text into rule configurations for the zanzibar-graph system
*/
export class DSLCompiler {
constructor(arbiter) {
constructor(arbiter, options = {}) {
this.arbiter = arbiter;
this.parser = parse;
this.generator = new RuleGenerator(arbiter);
this.generator = new RuleGenerator(arbiter, options);
this.compiledPrograms = new Map();
}
@@ -39,13 +39,15 @@ export class DSLCompiler {
const programNode = {
definitions: program.body.filter(s => s.type === 'Definition'),
facts: program.body.filter(s => s.type === 'Fact'),
sources: program.body.filter(s => s.type === 'Source'),
evidence: program.body.filter(s => s.type === 'Evidence'),
measures: program.body.filter(s => s.type === 'Measure'),
validate: () => ({ isValid: true, errors: [], warnings: [] })
};
// Generate rules from AST
const generationResult = this.generator.generateRules(programNode);
// Generate rules from AST (scoped to the program name so recompiling a
// scope revokes its stale relations without touching other scopes).
const generationResult = this.generator.generateRules(programNode, programName);
if (!generationResult.success) {
return {
+359 -29
View File
@@ -5,12 +5,22 @@ import { ProgramNode, DefinitionNode, FactNode, EvidenceNode, MeasureNode, Direc
* Generates rule configurations that interface with the existing rule system
*/
export class RuleGenerator {
constructor(arbiter) {
constructor(arbiter, options = {}) {
this.arbiter = arbiter;
this.generatedRules = new Map();
this.errors = [];
this.dependencyIndex = new Map();
this.evidenceNames = new Set();
// Relation names this generator has installed on the arbiter, tracked PER
// PROGRAM SCOPE (the compile() program name). Recompiling the same scope
// uninstalls relations that scope previously declared but no longer does —
// otherwise a revoked evidence/fact keeps its config and still grants
// (stale-permission leak). Relations from OTHER scopes (compileMultiple
// coexistence) are never touched.
this._installedByScope = new Map();
this._currentScope = 'default';
// Default depth for bounded self-recursion when the DSL `limit N` is absent.
this.maxRecursionDepth = options.maxRecursionDepth ?? 3;
}
/**
@@ -18,10 +28,25 @@ export class RuleGenerator {
* @param {ProgramNode} program - AST program to generate rules from
* @returns {Object} Generation result with success status and errors
*/
generateRules(program) {
generateRules(program, scopeName = 'default') {
this.errors = [];
this._currentScope = scopeName;
this.program = program;
this.generatedRules.clear();
this.dependencyIndex.clear();
// Facts declared `BEHAVES AS transitive` are resolved as bounded transitive
// closure (multi_hop) everywhere they are referenced — both the fact's own
// config and any direct rule that references the fact. Without this the
// declaration parses but grants only direct edges (silent no-op). Value is
// the closure depth (the fact's `limit N`, or the recursion default).
this.transitiveFacts = new Map();
for (const fact of program.facts || []) {
const behavior = fact && fact.behavior;
if (behavior && (behavior.behavior === 'transitive' || behavior === 'transitive')) {
const depth = (fact.limit && typeof fact.limit === 'object' ? fact.limit.value : fact.limit) ?? this.maxRecursionDepth;
this.transitiveFacts.set(fact.name, depth);
}
}
try {
// Generate rules for each evidence definition
@@ -39,6 +64,14 @@ export class RuleGenerator {
this.generateFactConfig(fact);
});
// Generate source relation configs (injectable, recency-gated proofs).
// Without a config a source referenced by an evidence would never
// resolve — the reference would lower to a config-less direct rule that
// grants nothing.
(program.sources || []).forEach(source => {
this.generateSourceConfig(source);
});
// Resolve evidence composition: a rule that references another derived
// evidence (WHEN can_read(user, doc) where can_read is an evidence) is
// lowered in place to that evidence's own config — compile-time inlining
@@ -107,9 +140,13 @@ export class RuleGenerator {
const paramNames = params.map(p => p.name);
const paramTypes = params.map(p => p.type);
this.generatedRules.set(name, {
type: 'direct',
relation: name,
// BEHAVES AS transitive: the fact resolves to bounded transitive closure.
// A multi_hop config walks the relation's edges up to maxDepth (the fact's
// `limit N`, or the recursion default), so a direct check on the fact —
// and any evidence that references it — follows multi-hop paths instead of
// only direct edges.
const transitiveDepth = this.transitiveFacts.get(name);
const base = {
isFactRelation: true,
requiresInjection: true,
arity: paramTypes.length,
@@ -121,6 +158,39 @@ export class RuleGenerator {
typeof p === 'string' ? [p, true] : Array.isArray(p) ? p : [p, true]
)
)
};
this.generatedRules.set(name, transitiveDepth !== undefined
? {
type: 'multi_hop',
relation: name,
maxDepth: transitiveDepth,
pathAggregation: 'max',
reverse: false,
fallbackToBasicPaths: true,
collectValues: false,
...base
}
: {
type: 'direct',
relation: name,
...base
});
}
generateSourceConfig(source) {
const name = source.name;
const params = source.params || [];
const withinMs = source.within ? this._durationToMs(source.within) : null;
this.generatedRules.set(name, {
type: 'direct',
relation: name,
isSourceRelation: true,
requiresInjection: true,
arity: params.length,
paramTypes: params.map(p => p.paramType),
paramNames: params.map(p => p.name),
...(withinMs !== null ? { withinMs } : {})
});
}
@@ -155,6 +225,7 @@ export class RuleGenerator {
for (const step of rule.steps) {
if (typeof step === 'string') targetSet.add(step);
else if (step && typeof step.relation === 'string') targetSet.add(step.relation);
else if (step && step.rule) collect(step.rule, targetSet);
}
}
if (rule.type === 'relational_comparator') {
@@ -295,7 +366,7 @@ export class RuleGenerator {
case 'PredicateCall':
return this.buildPredicateRule(statement, evidence);
case 'UnaryExpression':
return this.buildUnaryRule(statement);
return this.buildUnaryRule(statement, evidence);
case 'BinaryExpression':
// Top-level comparator — emit a relational_comparator rule. RF-24 closure.
return this.buildRuleFromExpressionNode(statement, evidence);
@@ -314,15 +385,19 @@ export class RuleGenerator {
/**
* Build rule for unary expression (NOT)
* @param {Object} expression - Unary expression
* @param {Object} evidence - Evidence definition (threaded through so a
* unary inner predicate like NOT banned(user) keeps its _subjectAsObject
* rewrite; without it the unary fact would be checked on the evidence's
* OBJECT node instead of the subject, silently negating the wrong fact).
* @returns {Object|null} Rule configuration or null
*/
buildUnaryRule(expression) {
buildUnaryRule(expression, evidence) {
if (expression.operator !== 'NOT') {
this.errors.push(`Unsupported unary operator: ${expression.operator}`);
return null;
}
const innerRule = this.buildRuleFromExpression(expression.operand);
const innerRule = this.buildRuleFromExpression(expression.operand, evidence);
if (!innerRule) {
return null;
}
@@ -479,21 +554,40 @@ export class RuleGenerator {
const predicate = directEvidence.predicate;
const relation = predicate.name;
// A reference to a `BEHAVES AS transitive` fact resolves to closure.
const transitiveDepth = this.transitiveFacts.get(relation);
if (transitiveDepth !== undefined) {
return this._buildTransitiveRule(relation, transitiveDepth, predicate.arguments || [], evidence);
}
const rule = {
type: 'direct',
relation: relation,
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.
// Unary predicate calls check the relation as a self-edge on the call's
// subject entity (the graph stores unary facts as self-edges). The subject
// entity may be the evidence's SUBJECT or its OBJECT parameter — mark the
// matching rewrite flag.
const evidenceParams = (evidence && evidence.params) || [];
const objectVar = evidenceParams[1] && evidenceParams[1].name;
const argName = a => a && (a.name !== undefined ? a.name : a.value);
if (objectVar !== undefined && !(predicate.arguments || []).some(a => argName(a) === objectVar)) {
const args = predicate.arguments || [];
if (objectVar !== undefined) {
const hasObjectArg = args.some(a => argName(a) === objectVar);
if (args.length === 1 && argName(args[0]) === objectVar) {
rule._subjectIsObject = true;
} else if (!hasObjectArg) {
rule._subjectAsObject = true;
}
}
// A literal value in the object position (balance(user, 5)) is a VALUE
// constraint, not a node key: the rule only grants when the matched edge
// carries exactly that value. Without this gate a value-carrying fact
// would match ANY edge regardless of its amount (silent over-grant).
this._applyExpectedValue(rule, args);
return rule;
}
@@ -621,7 +715,8 @@ export class RuleGenerator {
type: 'chain',
steps,
aggregator: 'max',
collectValues: true
collectValues: true,
maxDepth: patternMatch.limit || null
};
}
@@ -662,7 +757,10 @@ export class RuleGenerator {
type: 'chain',
steps,
aggregator: 'max',
collectValues: true
collectValues: true,
// Carry the pattern's `limit N` as a max depth so a self-referential
// chain step can be unrolled into bounded transitive closure.
maxDepth: patternMatch.limit || null
};
}
@@ -933,7 +1031,7 @@ export class RuleGenerator {
} else if (expression.type === 'PredicateCall') {
return this.buildPredicateRule(expression, evidence);
} else if (expression.type === 'UnaryExpression') {
return this.buildUnaryRule(expression);
return this.buildUnaryRule(expression, evidence);
} else if (expression.type === 'BinaryExpression') {
return this.buildRuleFromExpressionNode(expression, evidence);
}
@@ -948,6 +1046,12 @@ export class RuleGenerator {
* @returns {Object|null} Rule configuration or null
*/
buildDirectRuleFromPredicate(predicate, evidence) {
// A reference to a `BEHAVES AS transitive` fact resolves to closure.
const transitiveDepth = this.transitiveFacts.get(predicate.name);
if (transitiveDepth !== undefined) {
return this._buildTransitiveRule(predicate.name, transitiveDepth, predicate.args || [], evidence);
}
const rule = {
type: 'direct',
relation: predicate.name,
@@ -961,6 +1065,58 @@ export class RuleGenerator {
rule._subjectAsObject = true;
}
// Value constraint: a literal in the object position (balance(user, 5)).
this._applyExpectedValue(rule, predicate.args || []);
return rule;
}
/**
* Annotate a direct rule with `expectedValue` when its object-position
* argument is a literal. The engine only grants the rule if the matched
* edge's `value` field equals this literal — without the gate a
* value-carrying fact would match any edge of the same relation, silently
* over-granting (e.g. balance(user, 5) matching a value-3 edge).
*/
_applyExpectedValue(rule, args) {
if (rule && args && args.length >= 2) {
const objectArg = args[1];
if (objectArg && objectArg.type === 'Literal' && objectArg.value !== undefined) {
rule.expectedValue = objectArg.value;
}
}
return rule;
}
/**
* Build a bounded transitive-closure rule for a `BEHAVES AS transitive`
* fact reference. Applies the same subject/object rewrite flags as the
* direct-rule builders so a unary or object-var reference still targets the
* correct nodes.
*/
_buildTransitiveRule(relation, maxDepth, args, evidence) {
const rule = {
type: 'multi_hop',
relation: relation,
maxDepth: maxDepth,
pathAggregation: 'max',
reverse: false,
fallbackToBasicPaths: true,
collectValues: false
};
const evidenceParams = (evidence && evidence.params) || [];
const objectVar = evidenceParams[1] && evidenceParams[1].name;
const argName = a => a && (a.name !== undefined ? a.name : a.value);
if (objectVar !== undefined) {
const hasObjectArg = args.some(a => a && a.type === 'Variable' && a.name === objectVar);
if (args.length === 1 && argName(args[0]) === objectVar) {
rule._subjectIsObject = true;
} else if (!hasObjectArg) {
rule._subjectAsObject = true;
}
}
return rule;
}
@@ -982,13 +1138,113 @@ export class RuleGenerator {
resolveEvidenceReferences() {
for (const name of this.evidenceNames) {
if (!this.generatedRules.has(name)) continue;
let config = this.generatedRules.get(name);
// Bounded self-recursion (transitive closure): an evidence whose config
// contains a chain step referencing ITSELF is unrolled into a union of
// bounded paths — base, hop+base, hop²+base, …, hop^N+base — where `hop`
// is the recursive chain's steps before the self-reference and the depth
// N comes from the pattern's `limit N` (or the compiler default).
const selfRef = this._findSelfReference(config, name);
if (selfRef) {
const depth = selfRef.limit ?? this.maxRecursionDepth;
const unrolled = this._unrollRecursiveEvidence(name, config, selfRef.hop, depth);
if (unrolled) {
config = unrolled;
this.generatedRules.set(name, config);
}
}
const stack = new Set([name]);
const resolved = this._resolveRule(this.generatedRules.get(name), stack);
const resolved = this._resolveRule(config, stack);
this.generatedRules.set(name, resolved);
this._annotateDependencies(name, resolved);
}
}
/**
* Find the first chain step within `config` that references `name` (a
* self-reference). Returns { hop, limit } where hop is the chain's steps
* before the self-reference and limit is the chain's declared max depth.
* Returns null when there is no self-reference.
*/
_findSelfReference(config, name) {
let found = null;
const walk = (rule) => {
if (!rule || typeof rule !== 'object' || found) return;
if (rule.type === 'chain' && Array.isArray(rule.steps)) {
const idx = rule.steps.findIndex(s => (typeof s === 'string' ? s : s && s.relation) === name);
if (idx >= 0) {
const lim = rule.maxDepth;
const limit = lim && typeof lim === 'object' ? lim.value : lim;
found = { hop: rule.steps.slice(0, idx), limit: Number.isFinite(limit) ? limit : null };
return;
}
}
for (const key of ['union', 'intersection', 'exclusion', 'never', 'always', 'requires', 'when', 'unless']) {
const node = rule[key];
if (!node) continue;
if (Array.isArray(node.rules)) for (const c of node.rules) walk(c);
if (Array.isArray(node.union?.rules)) for (const c of node.union.rules) walk(c);
if (Array.isArray(node.intersection?.rules)) for (const c of node.intersection.rules) walk(c);
if (node.direct) walk(node.direct);
if (node.rule) walk(node.rule);
}
};
walk(config);
return found;
}
/**
* Unroll a self-recursive evidence into a bounded transitive closure.
* The recursive chain is removed from the config; the remainder is the base.
* Result: union([base, hop+base, hop²+base, …, hop^depth+base]) where the
* base is verified as a condition step at each path's terminal node.
*/
_unrollRecursiveEvidence(name, config, hop, depth) {
if (hop.length === 0) {
this.errors.push(`Recursive evidence '${name}' has an empty recursion hop (no steps before the self-reference).`);
return null;
}
const base = this._extractBase(config, name);
if (!base) {
this.errors.push(`Recursive evidence '${name}' has no base case — pure recursion cannot grant. Add a non-recursive statement.`);
return null;
}
const rules = [this._deepCloneRule(base)];
for (let d = 1; d <= depth; d++) {
const steps = [];
for (let h = 0; h < d; h++) steps.push(...hop.map(s => this._deepCloneRule(s)));
steps.push({ rule: this._deepCloneRule(base), conditionStep: true });
rules.push({ type: 'chain', steps, aggregator: 'max', collectValues: true });
}
return { type: 'logical', union: { rules, aggregator: 'max' } };
}
/**
* Remove the recursive chain (the chain containing a self-reference) from an
* evidence config and return the remainder as the base case. Returns null if
* there is no base (pure recursion).
*/
_extractBase(config, name) {
if (config.type === 'chain') {
const hasSelf = (config.steps || []).some(s => (typeof s === 'string' ? s : s && s.relation) === name);
return hasSelf ? null : this._deepCloneRule(config);
}
if (config.type === 'logical' && config.intersection) {
const remaining = (config.intersection.rules || []).filter(r => {
// keep rules that are not (or do not contain) the recursive chain
return !this._containsSelfReference(r, name);
});
if (remaining.length === 0) return null;
if (remaining.length === 1) return this._deepCloneRule(remaining[0]);
return { type: 'logical', intersection: { rules: remaining.map(r => this._deepCloneRule(r)), aggregator: config.intersection.aggregator || 'min' } };
}
return this._containsSelfReference(config, name) ? null : this._deepCloneRule(config);
}
_containsSelfReference(rule, name) {
return this._findSelfReference(rule, name) !== null;
}
/**
* Recursively rewrite a rule tree, inlining references to derived evidence
* configs. `stack` holds the evidence names currently being expanded so a
@@ -1070,13 +1326,17 @@ export class RuleGenerator {
* - 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.
* - logical / defeasible / comparator evidence → only expressible as a
* FINAL condition-gated step (the object is known, so the engine can
* verify the condition at (intermediate, object) instead of traversing
* an edge). Emitted as a `{ rule: <config> }` step the ChainRule
* evaluates as a condition hop. Non-final such steps are a compile
* error: a condition cannot discover intermediate nodes.
*/
_expandChainSteps(steps, stack) {
const out = [];
for (const step of steps) {
for (let idx = 0; idx < steps.length; idx++) {
const step = steps[idx];
const stepName = typeof step === 'string' ? step : step.relation;
if (stepName && this.evidenceNames.has(stepName)) {
if (stack.has(stepName)) {
@@ -1099,11 +1359,22 @@ export class RuleGenerator {
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.');
if (resolved.type === 'relational_comparator' && idx !== steps.length - 1) {
// A comparator compares values at (src, candidate) but provides no
// candidate set — it cannot enumerate intermediate nodes, so only
// a FINAL comparator step (verified at the known object) lowers.
this.errors.push(`Chain step '${stepName}' references a comparator evidence at a non-final position. ` +
'Comparators can only be the final chain step (the object is known); intermediate positions are not enumerable.');
out.push(step);
continue;
}
// Condition step: inline the evidence's config as a rule step. As the
// FINAL step the engine verifies it at (intermediate, object); as an
// INTERMEDIATE step the engine EXPANDS it from the current node
// (rule-based reachability) and continues from each discovered node.
out.push({ rule: this._deepCloneRule(resolved), conditionStep: true });
continue;
}
}
out.push(step);
}
@@ -1262,26 +1533,45 @@ export class RuleGenerator {
return this.buildChallengeRule(expression, null);
}
// A reference to a `BEHAVES AS transitive` fact resolves to bounded
// transitive closure, not a direct edge lookup.
const transitiveDepth = this.transitiveFacts.get(predicateName);
if (transitiveDepth !== undefined) {
return this._buildTransitiveRule(predicateName, transitiveDepth, expression.args || [], evidence);
}
const rule = {
type: 'direct',
relation: predicateName,
reverse: false
};
// Subject-scoped (unary) predicate call: the call's variable args omit the
// evidence's object parameter (banned(user) inside can_open(user, doc)).
// Mark _subjectAsObject so the engine checks the relation on the subject
// itself — the unary fact's self-edge — instead of (subject, object).
// Unary predicate calls check the relation as a self-edge on the call's
// subject entity (the graph stores unary facts as self-edges). The subject
// entity may be the evidence's SUBJECT or its OBJECT parameter:
// banned(user) in can_open(user, doc) -> self-edge on the user
// trusted(other) in peer_trusted(user, other) -> self-edge on the other
// Mark _subjectAsObject (subject-as-object on the subject entity) or
// _subjectIsObject (the subject entity IS the object parameter) so the
// engine rewrites the pair accordingly.
const evidenceParams = (evidence && evidence.params) || [];
const objectVar = evidenceParams[1] && evidenceParams[1].name;
const argName = a => a && (a.name !== undefined ? a.name : a.value);
if (objectVar !== undefined) {
const hasObjectArg = (expression.args || []).some(a =>
a && a.type === 'Variable' && a.name === objectVar);
if (!hasObjectArg) {
const args = expression.args || [];
const hasObjectArg = args.some(a => a && a.type === 'Variable' && a.name === objectVar);
if (args.length === 1 && argName(args[0]) === objectVar) {
rule._subjectIsObject = true;
} else if (!hasObjectArg) {
rule._subjectAsObject = true;
}
}
// Value constraint: a literal in the object position (balance(user, 5))
// is a VALUE gate, not a node key — the rule only grants when the matched
// edge carries exactly that value.
this._applyExpectedValue(rule, expression.args || []);
return rule;
}
@@ -1395,6 +1685,19 @@ export class RuleGenerator {
return;
}
// Recompile hygiene (per program scope): relations installed by a previous
// compile of THIS scope but absent from the current program are stale —
// remove their configs from every cache and index so a revoked relation
// stops granting immediately. Relations belonging to other scopes
// (compileMultiple coexistence) are left intact.
const scope = this._currentScope || 'default';
const previously = this._installedByScope.get(scope) || new Set();
for (const name of previously) {
if (!this.generatedRules.has(name)) {
this._uninstallRelation(name);
}
}
this.generatedRules.forEach((config, relation) => {
try {
this.arbiter.setRelationConfig(relation, config);
@@ -1406,6 +1709,33 @@ export class RuleGenerator {
if (typeof this.arbiter.registerDependencyIndex === 'function') {
this.arbiter.registerDependencyIndex(this.dependencyIndex);
}
this._installedByScope.set(scope, new Set(this.generatedRules.keys()));
}
/**
* Remove a relation's config and cached state from the arbiter. Mirrors the
* invalidation that setRelationConfig performs, applied to deletion.
*/
_uninstallRelation(name) {
const arb = this.arbiter;
if (!arb) return;
if (arb.relationConfigs && typeof arb.relationConfigs.delete === 'function') {
arb.relationConfigs.delete(name);
}
const analysis = arb.graphManager && arb.graphManager.analysis;
if (analysis && analysis.relationConfigs && typeof analysis.relationConfigs.delete === 'function') {
analysis.relationConfigs.delete(name);
}
if (typeof arb._invalidateDirectCheckCache === 'function') {
arb._invalidateDirectCheckCache(null, name, null);
}
if (typeof arb.invalidateRuleResultCacheByRelation === 'function') {
arb.invalidateRuleResultCacheByRelation(name);
}
if (arb.authChecker && typeof arb.authChecker.invalidateRuleCaches === 'function') {
arb.authChecker.invalidateRuleCaches(name);
}
}
/**
+12 -2
View File
@@ -54,11 +54,14 @@ Definition "A type definition"
}
Field
= name:Identifier _ ":" _ fieldType:Type _ isArray:("[]")? _ behavior:Behavior? _ cache:CacheDirective? {
= name:Identifier _ ":" _ fieldType:Type optional:("?")? _ isArray:("[]")? _ behavior:Behavior? _ cache:CacheDirective? {
return {
type: "Field",
name,
fieldType,
// `field: type` is REQUIRED on node insert; `field: type?` is optional.
// Presence is enforced by the DSLRuntime when a node is created.
required: !optional,
isArray: !!isArray,
behavior: behavior || null,
cache: cache || null
@@ -248,6 +251,13 @@ BehaviorAnnotation
= "BEHAVES" __ "AS" __ behavior:("edge" / "transitive" / "hierarchical" / "symmetrical_graph") {
return { type: "BehaviorAnnotation", behavior };
}
/ "BEHAVES" __ "{" _ behavior:(TTLBehavior) _ "}" {
// Fact-level freshness: `fact balance(user, amount) BEHAVES { ttl 1h }`
// declares the relation's value-freshness window, which the runtime uses
// as the provider-result cache TTL. The behavior is wrapped like the
// `BEHAVES AS` form so consumers read `behavior.behaviorType`.
return { type: "BehaviorAnnotation", behavior };
}
FactProperty
= "transitive" { return "transitive"; }
@@ -385,7 +395,7 @@ Boolean "A boolean literal"
= value:("true" / "false") { return { type: "Literal", value: value === "true" }; }
Duration "A time duration literal"
= value:([0-9]+ ("h" / "d" / "w" / "m")) { return { type: "Literal", value: text(), unit: text().slice(-1) }; }
= value:([0-9]+ ("s" / "m" / "h" / "d" / "w")) { return { type: "Literal", value: text(), unit: text().slice(-1) }; }
// -- Core Tokens & Whitespace --
+3
View File
@@ -18,6 +18,9 @@ export { validateDslText } from './validation/DSLValidation.js';
// Runtime
export { DSLRuntime } from './runtime/DSLRuntime.js';
// Value-graph integration — DSL-declared measures as value-graph nodes
export { DSLValueGraph } from './value-graph/DSLValueGraph.js';
// All AST nodes
export * from './nodes/index.js';
File diff suppressed because it is too large Load Diff
+595 -54
View File
@@ -1,6 +1,6 @@
import { DSLCompiler } from '../DSLCompiler.js';
const PRIMITIVE_TYPES = new Set(['string', 'number', 'boolean']);
const VALUE_TYPES = new Set(['string', 'number', 'boolean', 'timestamp', 'duration', 'object', 'any']);
/**
* DSLRuntime — higher-order wrapper combining the Evidence DSL with an
@@ -12,13 +12,19 @@ const PRIMITIVE_TYPES = new Set(['string', 'number', 'boolean']);
* check). A raw Arbiter accepts untyped inserts; this wrapper adds the
* DSL-informed layer:
*
* - addNode / updateNodeData / addRelation / updateRelation validate their
* arguments against the compiled schema — known types, known relations,
* matching param types, typed field values — before mutating the arbiter.
* - check() validates the request, derives the injectable facts the
* evidence requires (its partial-graph requirements), retrieves the
* missing facts through caller-provided data callbacks, injects them into
* a partial graph, then delegates to the arbiter.
* - schema introspection: getSchema() exposes the compiled type system
* (entity types/fields, facts, evidence, dependencies, providers);
* - typed mutations: addNode / updateNodeData / addRelation / updateRelation
* validate their arguments against the compiled schema — known types,
* known relations, matching param types, typed field values — before
* mutating the arbiter; removeNode / removeRelation pass through;
* - per-relation data retrieval: registerFact(relation, asyncFn) registers a
* provider that retrieves the missing partial-graph edges for a fact; a
* bounded retrieval loop runs providers to a fixed point so a provider's
* edges can satisfy another required fact;
* - DSL-informed check: derives the evidence's injectable facts, retrieves
* them via providers, injects them into a partial graph, and delegates to
* the arbiter; require() throws on denial for middleware use.
*
* Trust boundary follows the core: caller-supplied evidence (partial graph /
* provider results) is trusted, never policed; only structure is validated.
@@ -38,11 +44,31 @@ export class DSLRuntime {
this.arbiter = arbiter;
this.compiler = new DSLCompiler(this.arbiter);
this.factProviders = options.factProviders || {};
this.measureProviders = new Map(); // measure name -> async (args, ctx) => { value, unit? }
this.strictTypes = options.policy?.strictTypes !== false;
this.program = null;
this.types = new Map(); // typeName -> { fields: Map(field -> {type,isArray}) }
this.relations = new Map(); // relation -> { kind: 'fact'|'evidence', params, injectable }
this.relations = new Map(); // relation -> { kind: 'fact'|'evidence', params, injectable, ttlMs }
this.dependsOn = new Map(); // evidence relation -> Set(fact relations)
// Provider-result cache: relation|subject|object -> { edges, fetchedAt }.
// Provider retrieval is a data-store read (balance lookups, session
// checks, etc.) — caching results with a time expiry avoids hammering the
// underlying store on every check. The clock is injectable (default wall
// clock) and drives cache freshness, mirroring the core's unpinned-clock
// contract.
this.providerCache = new Map();
this.clock = typeof options.clock === 'function' ? options.clock : (() => Date.now());
// Default provider-result TTL in ms (0 disables caching).
this.defaultProviderCacheTTL = options.policy?.providerCacheTTL ?? options.providerCacheTTL ?? 30_000;
// Provider caching is a STORE-RETRIEVAL cache (wall-clock), deliberately
// independent of the caller's decision `{ now }` — a provider returns the
// store's current data, not a time-travel snapshot. Callers who pin time
// or otherwise want fresh retrieval can disable it per-check
// (options.cacheProviderResults: false) or globally (policy).
this.cacheProviderResults = options.policy?.cacheProviderResults ?? options.cacheProviderResults ?? true;
// Per-fact overrides (ms). DSL-declared ttl behaviors are indexed here too.
this.factTTLs = new Map(Object.entries(options.factTTLs || {}));
}
/**
@@ -62,6 +88,50 @@ export class DSLRuntime {
return this;
}
// ---------------------------------------------------------------------------
// Schema introspection
// ---------------------------------------------------------------------------
/**
* A serializable snapshot of the compiled type system: entity types with
* typed fields, facts, evidence (with their dependencies), and registered
* providers. Callers can use this to render forms, build clients, or audit
* a compiled program without reaching into the internal Maps.
*/
getSchema() {
const types = [...this.types.entries()].map(([name, { fields }]) => ({
name,
fields: [...fields.entries()].map(([fieldName, f]) => ({
name: fieldName,
type: f.type,
isArray: f.isArray,
required: f.required !== false
}))
}));
const facts = [...this.relations.entries()]
.filter(([, r]) => r.kind === 'fact')
.map(([name, r]) => ({ name, params: r.params, injectable: r.injectable }));
const sources = [...this.relations.entries()]
.filter(([, r]) => r.kind === 'source')
.map(([name, r]) => ({ name, params: r.params, injectable: true, withinMs: r.withinMs }));
const evidence = [...this.relations.entries()]
.filter(([, r]) => r.kind === 'evidence')
.map(([name, r]) => ({
name,
params: r.params,
dependsOn: [...(this.dependsOn.get(name) || [])]
}));
const measures = [...this.relations.entries()]
.filter(([, r]) => r.kind === 'measure')
.map(([name, r]) => ({ name, params: r.params, returnType: r.returnType }));
return { types, facts, sources, evidence, measures, providers: this.registeredFacts() };
}
/** All relation names declared by the program (facts + evidence). */
relationNames() {
return [...this.relations.keys()];
}
_indexSchema() {
this.types.clear();
this.relations.clear();
@@ -70,16 +140,30 @@ export class DSLRuntime {
for (const def of this.program.definitions || []) {
const fields = new Map();
for (const field of def.fields || []) {
fields.set(field.name, { type: field.fieldType, isArray: !!field.isArray });
fields.set(field.name, { type: field.fieldType, isArray: !!field.isArray, required: field.required !== false });
}
this.types.set(def.name, { fields });
}
for (const fact of this.program.facts || []) {
const ttlMs = this._ttlFromBehavior(fact.behavior);
this.relations.set(fact.name, {
kind: 'fact',
params: (fact.params || []).map(p => ({ name: p.name, type: p.paramType, isArray: !!p.isArray })),
injectable: !!fact.injectable
injectable: !!fact.injectable,
ttlMs
});
}
// Sources are injectable, recency-gated proofs: registered as retrievable
// relations so a provider can supply them and `within X` gates freshness.
for (const src of this.program.sources || []) {
this.relations.set(src.name, {
kind: 'source',
params: (src.params || []).map(p => ({ name: p.name, type: p.paramType, isArray: !!p.isArray })),
injectable: true,
ttlMs: 0,
withinMs: src.within ? this._durationToMs(src.within) : null
});
}
@@ -91,6 +175,19 @@ export class DSLRuntime {
});
}
// Measures are derived-value lookups (kind: 'measure'). Their VALUES come
// from a registered provider (the ARRA adapter / value-graph), not the
// graph. `provides` declares the return type.
for (const m of this.program.measures || []) {
const provides = m.provides?.type || m.provides || 'number';
this.relations.set(m.name, {
kind: 'measure',
params: (m.params || []).map(p => ({ name: p.name, type: p.paramType, isArray: !!p.isArray })),
returnType: provides,
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);
@@ -103,7 +200,11 @@ export class DSLRuntime {
if (rule.computedRelation) deps.add(rule.computedRelation);
}
if (rule.type === 'chain' && Array.isArray(rule.steps)) {
for (const s of rule.steps) deps.add(typeof s === 'string' ? s : s.relation);
for (const s of rule.steps) {
if (typeof s === 'string') deps.add(s);
else if (s && s.relation) deps.add(s.relation);
else if (s && s.rule) collect(s.rule);
}
}
if (rule.type === 'parent' && rule.parentRelation) deps.add(rule.parentRelation);
if (rule.type === 'multi_hop' && rule.relation) deps.add(rule.relation);
@@ -132,12 +233,255 @@ export class DSLRuntime {
}
}
// ---------------------------------------------------------------------------
// Provider registration (per-relation data retrieval)
// ---------------------------------------------------------------------------
/**
* Register (or replace) an async provider for a relation name. When a check
* needs that relation's facts and they are not in the graph, the provider is
* invoked to retrieve the missing partial-graph edges.
*
* @param {string} relation - fact relation name
* @param {Function} provider - async (subject, object, ctx) => edges
*/
registerFact(relation, provider) {
if (typeof provider !== 'function') {
throw new Error(`DSLRuntime: provider for '${relation}' must be a function`);
}
this.factProviders[relation] = provider;
// A new provider supersedes any cached retrieval for this fact.
this.invalidateProviderCache(relation);
return this;
}
/** Remove a registered provider. */
unregisterFact(relation) {
delete this.factProviders[relation];
this.invalidateProviderCache(relation);
return this;
}
/** Relation names that currently have a registered provider. */
registeredFacts() {
return Object.keys(this.factProviders);
}
/**
* Register a measure provider. A measure is a derived-value lookup declared
* in the DSL (`measure name(...) { ... } provides <type>`); its VALUE comes
* from a registered provider (e.g. the ARRA adapter bridging the value-graph),
* not from the graph.
*
* @param {string} name - declared measure name
* @param {Function} provider - async (args, ctx) => { value, unit? } | number
*/
registerMeasure(name, provider) {
const meta = this.relations.get(name);
if (!meta || meta.kind !== 'measure') {
throw new Error(`DSLRuntime: '${name}' is not a declared measure`);
}
if (typeof provider !== 'function') {
throw new Error(`DSLRuntime: provider for measure '${name}' must be a function`);
}
this.measureProviders.set(name, provider);
return this;
}
/** Unregister a measure provider. */
unregisterMeasure(name) {
this.measureProviders.delete(name);
return this;
}
/**
* Resolve a measure value by its parameter bindings.
* @param {string} name - declared measure name
* @param {Object} args - positional or named args (positional for unary/arity-1)
* @returns {Promise<{value: *, unit?: string|null, source?: string}>}
*/
async measure(name, args = {}) {
const meta = this.relations.get(name);
if (!meta || meta.kind !== 'measure') {
if (this.strictTypes) throw new Error(`DSLRuntime: unknown measure '${name}'`);
return null;
}
const provider = this.measureProviders.get(name);
if (!provider) {
throw new Error(`DSLRuntime: no provider registered for measure '${name}'`);
}
const params = meta.params || [];
// Normalize positional args (e.g. measure(userKey)) to named bindings.
let bindings = args;
if (Array.isArray(args)) {
bindings = {};
for (let i = 0; i < params.length; i++) bindings[params[i].name] = args[i];
}
const result = await provider(bindings, { runtime: this });
if (typeof result === 'number' || typeof result === 'string' || typeof result === 'boolean') {
return { value: result, unit: null };
}
if (result && typeof result === 'object' && 'value' in result) {
return { value: result.value, unit: result.unit ?? null, source: result.source };
}
throw new Error(`DSLRuntime: provider for measure '${name}' must return a value or { value, unit }`);
}
// ---------------------------------------------------------------------------
// Provider-result caching
// ---------------------------------------------------------------------------
/**
* Set a per-fact provider-result TTL (ms). Overrides the policy default and
* the DSL-declared ttl behavior for that fact.
*/
setFactTTL(relation, ms) {
this.factTTLs.set(relation, ms);
return this;
}
/** The effective provider-result TTL (ms) for a fact: DSL > per-fact > policy default. */
_ttlFor(relation) {
if (this.factTTLs.has(relation)) return this.factTTLs.get(relation);
const meta = this.relations.get(relation);
if (meta && meta.ttlMs != null) return meta.ttlMs;
return this.defaultProviderCacheTTL;
}
/**
* Invalidate cached provider results — all, or for a single relation.
* Callers use this when the underlying data store changes out-of-band.
*/
invalidateProviderCache(relation) {
if (relation === undefined) {
this.providerCache.clear();
return this;
}
const prefix = `${relation}\u0000`;
for (const key of [...this.providerCache.keys()]) {
if (key.startsWith(prefix)) this.providerCache.delete(key);
}
return this;
}
_providerCacheKey(relation, subject, object) {
return `${relation}\u0000${subject}\u0000${object}`;
}
_providerCacheGet(relation, subject, object) {
const ttl = this._ttlFor(relation);
if (ttl <= 0) return null;
const entry = this.providerCache.get(this._providerCacheKey(relation, subject, object));
if (!entry) return null;
if (this.clock() - entry.fetchedAt >= ttl) {
this.providerCache.delete(this._providerCacheKey(relation, subject, object));
return null;
}
return entry;
}
_providerCacheSet(relation, subject, object, edges) {
const ttl = this._ttlFor(relation);
if (ttl <= 0) return;
this.providerCache.set(this._providerCacheKey(relation, subject, object), {
edges,
fetchedAt: this.clock()
});
}
/** Convert a DSL `BEHAVES { ttl <duration> }` behavior (or `BEHAVES AS`) into ms. */
_ttlFromBehavior(behavior) {
if (!behavior || typeof behavior !== 'object') return null;
const b = behavior.behavior || behavior;
if (b && b.behaviorType === 'ttl' && b.duration) {
const n = parseInt(String(b.duration.value), 10);
const mult = { s: 1000, m: 60_000, h: 3600_000, d: 86_400_000, w: 604_800_000 }[b.duration.unit];
if (!Number.isNaN(n) && mult) return n * mult;
}
return null;
}
/** Convert a Duration AST ({ value, unit }) to milliseconds. */
_durationToMs(duration) {
if (!duration || duration.value === undefined) return null;
const raw = typeof duration.value === 'string' ? duration.value : String(duration.value);
const unit = duration.unit || raw.slice(-1);
const numeric = parseFloat(raw);
if (!Number.isFinite(numeric)) return null;
const mult = { s: 1000, m: 60_000, h: 3600_000, d: 86_400_000, w: 604_800_000 }[unit];
return mult ? numeric * mult : null;
}
/**
* Normalize a provider result (boolean / number / { possibility, value } /
* array of edge objects) into an array of partial-graph edge objects. The
* destination follows the DSL fact's declared shape: unary and value-carrying
* facts are self-edges on the subject; binary entity facts go subject → object.
* Provider-returned edges are validated against the fact's declared typing:
* a value-carrying fact must return an object with a value of the declared
* type, and possibilities must be in [0, 1]. A violation throws — it is a
* provider-authoring error, not a denial.
*/
_normalizeProviderEdges(result, factMeta, fact, user, object) {
const edges = Array.isArray(result) ? result : [result];
const secondParamType = factMeta.params[1] && factMeta.params[1].type;
const isValueFact = factMeta.params.length >= 2 && this._isValueType(secondParamType);
// Sources carry a timestamp in `value` for their recency (`within X`) gate.
const isSource = factMeta.kind === 'source';
const defaultDst = isValueFact ? user : (factMeta.params.length >= 2 ? object : user);
const label = `provider for '${fact}'`;
const out = [];
for (const edge of edges) {
const normalized = typeof edge === 'boolean' || typeof edge === 'number'
? (() => {
if (isValueFact) {
throw new Error(`DSLRuntime: ${label} is a value-carrying fact — return { value, possibility } (got a bare ${typeof edge === 'number' ? 'number' : 'boolean'})`);
}
const possibility = edge === true ? 1 : edge;
this._checkPossibility(possibility, label);
return { src: user, dst: defaultDst, possibility };
})()
: (() => {
const possibility = edge.possibility ?? 1;
this._checkPossibility(possibility, label);
if (edge.value !== undefined) {
if (!isValueFact && !isSource) {
throw new Error(`DSLRuntime: ${label} returned a value for a non-value fact '${fact}'`);
}
if (isValueFact) {
this._checkScalarValue(secondParamType, edge.value, `${label}.value`);
} else if (isSource && (typeof edge.value !== 'number' || Number.isNaN(edge.value))) {
throw new Error(`DSLRuntime: ${label} (a source) must return a numeric timestamp in value`);
}
} else if (isValueFact) {
throw new Error(`DSLRuntime: ${label} must supply a 'value' of type ${secondParamType}`);
}
return {
...(edge.relation ? { relation: edge.relation } : {}),
src: edge.src ?? user,
dst: edge.dst ?? defaultDst,
possibility,
...(edge.value !== undefined ? { value: edge.value } : {}),
...(edge.reliability !== undefined ? { reliability: edge.reliability } : {})
};
})();
out.push(normalized);
}
return out;
}
_checkPossibility(possibility, label) {
if (typeof possibility !== 'number' || !Number.isFinite(possibility) || possibility < 0 || possibility > 1) {
throw new Error(`DSLRuntime: ${label} returned invalid possibility ${possibility} (expected a number in [0, 1])`);
}
}
// ---------------------------------------------------------------------------
// Schema validation helpers
// ---------------------------------------------------------------------------
_isPrimitive(typeName) {
return PRIMITIVE_TYPES.has(typeName);
_isValueType(typeName) {
return VALUE_TYPES.has(typeName);
}
_nodeType(key) {
@@ -154,7 +498,7 @@ export class DSLRuntime {
}
_checkNodeType(key, expectedType, position) {
if (this._isPrimitive(expectedType)) return; // value positions are validated separately
if (this._isValueType(expectedType)) return; // value positions are validated separately
const actual = this._nodeType(key);
if (actual === null) {
this._checkNodeExists(key, position);
@@ -180,7 +524,9 @@ export class DSLRuntime {
const ok = type === 'string' ? typeof value === 'string'
: type === 'number' ? typeof value === 'number'
: type === 'boolean' ? typeof value === 'boolean'
: true; // entity-typed fields accept any key
: (type === 'timestamp' || type === 'duration')
? (typeof value === 'number' || typeof value === 'string')
: true; // object / any / entity-typed fields accept any value
if (!ok) {
throw new Error(`DSLRuntime: field '${path}' must be ${type}, got ${typeof value}`);
}
@@ -198,11 +544,18 @@ export class DSLRuntime {
if (this.types.has(typeName)) {
const { fields } = this.types.get(typeName);
for (const [name, field] of fields) {
// Required fields must be present on insert (`field: type` in the DSL;
// `field?: type` marks a field optional).
if (field.required && data[name] === undefined) {
throw new Error(`DSLRuntime: missing required field '${typeName}.${name}' on node insert`);
}
if (data[name] !== undefined) this._checkFieldValue(field, data[name], `${typeName}.${name}`);
}
} else if (this.strictTypes) {
throw new Error(`DSLRuntime: unknown type '${typeName}'`);
}
// A graph mutation can make previously-retrieved facts stale.
this.invalidateProviderCache();
return this.arbiter.addNode(key, typeName, data);
}
@@ -217,9 +570,19 @@ export class DSLRuntime {
if (data[name] !== undefined) this._checkFieldValue(field, data[name], `${typeName}.${name}`);
}
}
this.invalidateProviderCache();
return this.arbiter.updateNodeData(key, data);
}
/** Remove a node (passthrough to the arbiter's node manager). */
removeNode(key) {
this.invalidateProviderCache();
if (this.arbiter.nodeManager && typeof this.arbiter.nodeManager.removeNode === 'function') {
return this.arbiter.nodeManager.removeNode(key);
}
return this.arbiter.removeNode?.(key);
}
_relationOrThrow(relation) {
const meta = this.relations.get(relation);
if (!meta) {
@@ -239,6 +602,7 @@ export class DSLRuntime {
if (meta) {
this._validateRelationEndpoints(relation, meta, src, dst, attrs);
}
this.invalidateProviderCache();
return this.arbiter.addRelation(src, relation, dst, attrs);
}
@@ -250,10 +614,17 @@ export class DSLRuntime {
if (meta) {
this._validateRelationEndpoints(relation, meta, src, dst, attrs);
}
this.invalidateProviderCache();
this.arbiter.removeRelation(src, relation, dst);
return this.arbiter.addRelation(src, relation, dst, attrs);
}
/** Remove a relation edge (passthrough to the arbiter). */
removeRelation(src, relation, dst) {
this.invalidateProviderCache();
return this.arbiter.removeRelation(src, relation, dst);
}
_validateRelationEndpoints(relation, meta, src, dst, attrs) {
const params = meta.params;
if (params.length === 0) {
@@ -261,14 +632,14 @@ export class DSLRuntime {
}
// First param is always the subject (entity).
const subjectType = params[0].type;
if (this._isPrimitive(subjectType)) {
if (this._isValueType(subjectType)) {
throw new Error(`DSLRuntime: relation '${relation}' subject param must be an entity type, got '${subjectType}'`);
}
this._checkNodeType(src, subjectType, 'subject');
if (params.length >= 2) {
const secondType = params[1].type;
if (this._isPrimitive(secondType)) {
if (this._isValueType(secondType)) {
// Value-carrying fact (e.g. session(user, token: string)): the value
// lives on the edge's `value` field; the graph edge is a self-edge on
// the subject so the value is discoverable by value extraction.
@@ -287,7 +658,7 @@ export class DSLRuntime {
/**
* The partial-graph requirements of an evidence relation: the declared
* injectable facts it depends on.
* injectable facts and sources it depends on.
*/
requiredFacts(relation) {
const deps = this.dependsOn.get(relation);
@@ -296,6 +667,24 @@ export class DSLRuntime {
for (const dep of deps) {
const meta = this.relations.get(dep);
if (meta && meta.kind === 'fact' && meta.injectable) required.push(dep);
if (meta && meta.kind === 'source') required.push(dep);
}
return required;
}
/**
* The MEASURE requirements of an evidence relation: the derived measures its
* comparator operands reference (valueRelation deps that are `kind: measure`).
* These compose the measure system into the evidence system — the evidence's
* truth depends on a measure VALUE, which `check()` resolves and injects.
*/
requiredMeasures(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 === 'measure') required.push(dep);
}
return required;
}
@@ -309,6 +698,13 @@ export class DSLRuntime {
* evidence's injectable facts, inject them into a partial graph, and delegate
* to the arbiter.
*
* Providers run in a bounded fixed-point loop: each round invokes the
* provider for every required fact whose edges are not yet in the partial
* graph. Because a provider may return edges for relations other than its
* own name, an edge injected in one round can satisfy another required fact
* (or unblock another provider) in a later round. The loop stops when a
* round injects no new relation or the round budget is exhausted.
*
* @param {string} user - subject key
* @param {string} relation - evidence (or fact) relation name
* @param {string} object - object key
@@ -316,71 +712,139 @@ export class DSLRuntime {
* @param {object} options.partialGraph - caller-supplied partial graph edges
* ({ relations: [{ src, relation, dst, possibility, value }], nodes, challenges })
* @param {object} options.factProviders - per-call provider overrides
* (merged over registered providers)
* @param {number} options.maxProviderRounds - fixed-point loop budget (default 3)
* @returns {object} core check result extended with { requiredFacts, providedFacts, missingFacts }
*/
async check(user, relation, object, options = {}) {
const meta = this.relations.get(relation);
if (!meta) {
if (this.strictTypes) throw new Error(`DSLRuntime: unknown relation '${relation}'`);
} else if (meta.kind === 'evidence') {
if (meta.params.length === 2) {
} else if (meta.params.length === 2) {
this._checkNodeType(user, meta.params[0].type, 'subject');
this._checkNodeType(object, meta.params[1].type, 'object');
// A value-typed object parameter (can_withdraw(user, amount: number))
// carries the expected EDGE VALUE, not a node key — validate the scalar.
if (this._isValueType(meta.params[1].type)) {
this._checkScalarValue(meta.params[1].type, object, `object of '${relation}'`);
}
} else if (meta.params.length === 1) {
this._checkNodeType(user, meta.params[0].type, 'subject');
}
const required = this.requiredFacts(relation);
const providers = options.factProviders || this.factProviders;
const injectedRelations = [];
const missingFacts = [];
// Retrieval set: for an evidence, the injectable facts it depends on; for
// a direct FACT check, the fact itself is the retrieval target (its
// provider, if registered, supplies the edge — checking `owns` directly
// must consult the `owns` provider, not only evidence-mediated checks).
const required = new Set(this.requiredFacts(relation));
if (meta && (meta.kind === 'fact' || meta.kind === 'source')) required.add(relation);
const requiredList = [...required];
const providers = { ...this.factProviders, ...(options.factProviders || {}) };
const maxRounds = options.maxProviderRounds ?? 3;
const partialRelations = [];
const injectedRelations = []; // { relation, edges, round }
const missingFacts = [];
const warnings = [];
const satisfied = new Set(); // facts whose edges are in the partial graph
const now = this.clock ? this.clock() : Date.now();
if (options.partialGraph && Array.isArray(options.partialGraph.relations)) {
partialRelations.push(...options.partialGraph.relations);
for (const rel of options.partialGraph.relations) {
partialRelations.push(rel);
if (rel && rel.relation) satisfied.add(rel.relation);
}
}
for (const fact of required) {
// Fixed-point provider retrieval loop.
for (let round = 1; round <= maxRounds; round++) {
let newRelationsThisRound = 0;
for (const fact of requiredList) {
if (satisfied.has(fact)) continue;
const factMeta = this.relations.get(fact);
const provider = providers[fact];
// Provider-result cache: reuse fresh edges without re-invoking the
// data store. A cached entry stores the NORMALIZED edges. Per-check
// provider overrides are one-off observations — they bypass the cache
// entirely (no read, no write) so a fresh override is never masked by
// a cached registered-provider result, nor does it pollute the cache.
// options.cacheProviderResults:false (or the policy default) disables
// the cache for this check.
const cachingEnabled = options.cacheProviderResults ?? this.cacheProviderResults;
const isPerCheckOverride = !!(options.factProviders && fact in options.factProviders);
const cacheHit = (cachingEnabled && !isPerCheckOverride) ? this._providerCacheGet(fact, user, object) : null;
let edges = null;
let fromCache = false;
if (cacheHit) {
edges = cacheHit.edges;
fromCache = true;
} else if (typeof provider === 'function') {
let result = null;
let error = null;
if (typeof provider === 'function') {
try {
result = await provider(user, object, { relation: fact, params: factMeta.params, runtime: this, options });
result = await provider(user, object, {
relation: fact,
params: factMeta.params,
runtime: this,
options,
round,
alreadyInjected: [...satisfied]
});
} catch (err) {
error = err;
}
}
if (error) {
missingFacts.push({ relation: fact, reason: error.message });
satisfied.add(fact);
continue;
}
if (result === false || result === null || result === undefined) {
missingFacts.push({ relation: fact, reason: 'not_provided' });
satisfied.add(fact);
continue;
}
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 });
edges = this._normalizeProviderEdges(result, factMeta, fact, user, object);
if (cachingEnabled && !isPerCheckOverride) this._providerCacheSet(fact, user, object, edges);
} else {
missingFacts.push({ relation: fact, reason: 'no_provider' });
satisfied.add(fact);
continue;
}
injectedRelations.push({ relation: fact, edges: edges.length });
// A provider may return edges for relations other than its own; the
// injected relation names satisfy those facts too (fixed point). Apply
// the source recency gate (within X) and drop ghost-node edges.
const accepted = [];
for (const normalized of edges) {
const injectedRelation = normalized.relation ?? fact;
if (factMeta.kind === 'source' && factMeta.withinMs !== null && factMeta.withinMs !== undefined) {
if (normalized.value === undefined) {
throw new Error(`DSLRuntime: provider for recency-gated source '${fact}' must return a timestamp in value (within ${factMeta.withinMs}ms)`);
}
if (now - normalized.value > factMeta.withinMs) {
missingFacts.push({ relation: fact, reason: 'stale' });
continue;
}
}
if (normalized.src !== undefined && !this.arbiter.nodeIdByKey.has(normalized.src)) {
warnings.push(`provider for '${fact}' returned an edge with unknown source node '${normalized.src}' — dropped`);
continue;
}
if (normalized.dst !== undefined && !this.arbiter.nodeIdByKey.has(normalized.dst)) {
warnings.push(`provider for '${fact}' returned an edge with unknown target node '${normalized.dst}' — dropped`);
continue;
}
accepted.push({ relation: injectedRelation, ...normalized });
}
for (const normalized of accepted) {
partialRelations.push(normalized);
satisfied.add(normalized.relation);
}
injectedRelations.push({ relation: fact, edges: edges.length, round, cacheHit: fromCache });
newRelationsThisRound += edges.length;
satisfied.add(fact);
}
if (newRelationsThisRound === 0) break;
}
const checkOptions = { ...options };
@@ -391,13 +855,90 @@ export class DSLRuntime {
};
}
const result = this.arbiter.check(user, relation, object, checkOptions);
// --- Measure + evidence composition ---
// An evidence whose comparator references a measure (a valueRelation with
// `_needsValues`) needs the measure VALUE in the partial graph before the
// core evaluator runs. Measures inject as value-carrying self-edges on the
// subject, resolved through `this.measure()` — which is the attached
// value-graph when DSLValueGraph is wired, so both systems compose.
const measureRequirements = this.requiredMeasures(relation);
if (measureRequirements.length > 0) {
const bound = {};
for (let i = 0; i < (meta?.params || []).length; i++) {
if (i === 0) bound[meta.params[i].name] = user;
else if (i === 1 && !this._isValueType(meta.params[i].type)) bound[meta.params[i].name] = object;
}
for (const measure of measureRequirements) {
if (satisfied.has(measure)) continue;
const measureMeta = this.relations.get(measure);
// `__subject` aligns with the value-graph's subjectOf default so the
// attached DSLValueGraph resolves the same key setValue() wrote.
const args = { __subject: user };
for (const p of (measureMeta?.params || [])) args[p.name] = (p.name in bound ? bound[p.name] : user);
let resolved = null;
let err = null;
try {
resolved = await this.measure(measure, args);
} catch (e) {
err = e;
}
if (err || resolved === null || resolved === undefined) {
missingFacts.push({ relation: measure, reason: err ? err.message : 'not_provided' });
satisfied.add(measure);
continue;
}
partialRelations.push({
relation: measure,
src: user,
dst: user,
value: resolved.value,
possibility: 1,
...(resolved.unit != null ? { unit: resolved.unit } : {})
});
satisfied.add(measure);
injectedRelations.push({ relation: measure, edges: 1, round: 'measure', cacheHit: false });
}
if (partialRelations.length > 0) {
checkOptions.partialGraph = {
...(checkOptions.partialGraph || {}),
relations: partialRelations
};
}
}
// A value-typed object parameter means the check object IS the expected
// edge value, not a node key. Value-carrying facts store edges as
// self-edges on the subject, so the underlying check runs on the subject
// with the value carried as a per-check gate (options.expectedValue).
const isValueObject = meta && meta.params.length === 2 && this._isValueType(meta.params[1].type);
const checkObject = isValueObject ? user : object;
if (isValueObject) {
checkOptions.expectedValue = object;
}
const result = this.arbiter.check(user, relation, checkObject, checkOptions);
return {
...result,
requiredFacts: required,
requiredFacts: requiredList,
providedFacts: injectedRelations.map(r => r.relation),
missingFacts
missingFacts,
warnings
};
}
/**
* Check and throw on denial — convenience for middleware / guards.
* @returns {object} the check result on success.
* @throws {Error} with `.result` attached when the decision denies.
*/
async require(user, relation, object, options = {}) {
const result = await this.check(user, relation, object, options);
if (result.possibility <= 0) {
const error = new Error(`DSLRuntime: authorization denied for '${relation}' (${result.reason || 'denied'})`);
error.result = result;
throw error;
}
return result;
}
}
+44 -1
View File
@@ -1,7 +1,9 @@
import { parse } from '../parser/GeneratedParser.js';
import { DSL_PRELUDE } from './DSLPrelude.js';
const BUILTIN_TYPES = new Set(['string', 'number', 'boolean', 'timestamp', 'duration', 'object', 'any']);
// NO JS bigint in the value model — large integers are `buffer` (Uint8Array),
// matching the value-graph's JSON-free/bigint-free wire format.
const BUILTIN_TYPES = new Set(['string', 'number', 'boolean', 'timestamp', 'duration', 'object', 'any', 'buffer', 'array', 'interval']);
const BUILTIN_CHALLENGES = new Set([
'mfa',
'webauthn',
@@ -141,6 +143,22 @@ function validateDefinitions(program, tables, errors, warnings, source) {
}));
}
}
// Duplicate field names within a definition silently keep the last
// declaration (e.g. `{ id: string id: string }`) — reject loudly instead.
const fieldSeen = new Set();
for (const field of def.fields || []) {
if (fieldSeen.has(field.name)) {
errors.push(createError({
message: `Duplicate field '${def.name}.${field.name}'.`,
rule: 'Each field name must be unique within a definition.',
fix: `Remove the duplicate declaration of '${def.name}.${field.name}'.`,
location: findLocation(source, field.name),
context: formatContext(source, findLocation(source, def.name))
}));
}
fieldSeen.add(field.name);
}
}
}
@@ -1006,6 +1024,31 @@ function formatPegError(error, sourceText, sourceName) {
message = 'Missing colon after identifier.';
fix = 'Add ":" between a name and its type.';
rule = 'Types must be declared using name: Type syntax.';
} else {
// Targeted hints for common declaration mistakes. The peggy error only
// reports "unexpected X"; these heuristics read the source around the
// failure to point at the real constraint.
const offset = error.location?.start?.offset ?? -1;
const before = offset >= 0 ? sourceText.slice(0, offset) : '';
const tail = before.split(/\n/).pop() || '';
const lastKeyword = (() => {
const matches = [...before.matchAll(/\b(fact|relation|source|evidence|measure)\b/g)];
return matches.length ? matches[matches.length - 1][1] : null;
})();
if (found === 'w' && lastKeyword === 'fact' || (found === 'w' && lastKeyword === 'relation')) {
message = '`within` is only valid on `source` declarations.';
fix = 'Move the recency constraint to a `source` declaration, or drop `within` here.';
rule = 'Only sources accept a `within` freshness constraint.';
} else if (/\bBEHAVES\b/.test(before) && tail.includes('BEHAVES')) {
message = 'A declaration can carry only one `BEHAVES` clause.';
fix = 'Choose either a behavior (`BEHAVES AS transitive`) or a TTL (`BEHAVES { ttl 1h }`), not both.';
rule = '`BEHAVES` may appear at most once per declaration.';
} else if (found === 'l' && lastKeyword === 'evidence' && sourceText.slice(offset, offset + 5) === 'limit') {
message = '`limit` is only valid on pattern/recursive bodies.';
fix = 'Move `limit N` onto the pattern itself, e.g. reports_to(user, *m) { ... } limit N.';
rule = 'Only pattern bodies take a recursion depth limit.';
}
}
return createError({
+256
View File
@@ -0,0 +1,256 @@
/**
* DSLValueGraph — wires a DSLRuntime's declared MEASURES to a @arbiter/value-graph.
*
* The DSL is the schema authority: each `measure name(params) { ... } PROVIDES type`
* becomes a value-graph relation whose spec carries the declared return type and
* parameter types. The value-graph is then:
*
* - the STORAGE substrate for values/attributes that are supplied directly
* (not cached or computed) — `setValue(name, args, value)` writes them;
* - the RETRIEVAL substrate for measure lookups — `measure(name, args)` (and,
* after `attach()`, `runtime.measure(...)`) read through `valueGraph.get(...)`,
* so authorization evaluation pulls values "for partial graph purposes";
* - the COMPUTE substrate for external value resolvers — `resolve(name, fn)`
* registers a callback/sync resolver that becomes the node's operator fn
* (ARRA/Overlay adapters plug here).
*
* Typing / validation: values written or resolved must match the DSL-declared
* PROVIDES type (enforced both here and by the value-graph itself), and bindings
* are validated against the declared parameter types. Unknown measure names and
* type mismatches fail loudly.
*/
import { ValueGraph, validateValueType } from '@arbiter/value-graph';
const CONTROL_KEYS = new Set(['__subject', '__actor', '__source', '__meta']);
function isControlKey(key) {
return CONTROL_KEYS.has(key) || (typeof key === 'string' && key.startsWith('_'));
}
export class DSLValueGraph {
/**
* @param {DSLRuntime} runtime - an already-compiled DSLRuntime
* @param {Object} [options]
* @param {ValueGraph} [options.valueGraph] - shared graph (default: a fresh one)
* @param {number} [options.defaultTTL] - per-node TTL for declared measures (default 0 = persist until set/invalidate)
* @param {Function} [options.subjectOf] - (name, args) => subject key (default: args.__subject ?? 'global')
* @param {boolean} [options.strict] - throw on unknown measures (default true)
*/
constructor(runtime, options = {}) {
this.runtime = runtime;
this.vg = options.valueGraph || new ValueGraph({ defaultTTL: options.defaultTTL ?? 0 });
this.subjectOf = options.subjectOf || ((name, args) => (args && args.__subject) || 'global');
this.strict = options.strict !== false;
this.resolvers = new Map(); // measure name -> callback/sync resolver
this.measures = new Map(); // measure name -> { params, returnType }
this._attached = new Set(); // measure names attach() registered on the runtime
this._registerFromSchema();
}
// ---------------------------------------------------------------------------
// Schema registration — DSL declares the value-graph's typing / structure.
// ---------------------------------------------------------------------------
_registerFromSchema() {
return this.sync();
}
/**
* Re-read the runtime schema and re-register measure nodes. Call after the
* runtime recompiles a new program: new measures get value-graph nodes, removed
* ones are dropped, and changed return types/params are updated in place.
*/
sync() {
const schema = this.runtime.getSchema();
const seen = new Set();
for (const m of schema.measures || []) {
const name = m.name;
seen.add(name);
const params = (m.params || []).map((p) => ({ name: p.name, type: p.type, isArray: !!p.isArray }));
const returnType = m.returnType || 'number';
const existing = this.measures.get(name);
if (existing) {
existing.params = params;
existing.returnType = returnType;
} else {
this.measures.set(name, { params, returnType });
this.vg.define(name, {
operator: 'source',
returnType,
params,
fn: (subject, bindings, ctx, cb) => this._resolve(name, subject, bindings, ctx, cb)
});
}
}
for (const name of [...this.measures.keys()]) {
if (!seen.has(name)) this.measures.delete(name);
}
return this;
}
/** The value-graph node schema derived from the DSL (name → spec). */
schema() {
const out = {};
for (const [name] of this.measures) out[name] = this.vg.relationSpec(name);
return out;
}
// ---------------------------------------------------------------------------
// Measure metadata + binding normalization + validation
// ---------------------------------------------------------------------------
_measure(name) {
const meta = this.measures.get(name);
if (!meta) {
if (this.strict) throw new Error(`DSLValueGraph: '${name}' is not a declared measure`);
return null;
}
return meta;
}
/**
* Normalize positional (array) args to named bindings, strip control keys
* (`_subject` etc.), and validate the bound values against declared params.
* Positional args must match the declared arity exactly — otherwise the cache
* key would silently diverge from the caller's intent.
*/
_bindings(name, args) {
const meta = this._measure(name);
if (!meta) return {};
let raw = args;
if (Array.isArray(args)) {
if (args.length !== meta.params.length) {
throw new Error(
`DSLValueGraph: measure '${name}' expects ${meta.params.length} positional argument(s), got ${args.length}`
);
}
raw = {};
for (let i = 0; i < meta.params.length; i++) raw[meta.params[i].name] = args[i];
}
const bindings = {};
for (const [key, value] of Object.entries(raw || {})) {
if (isControlKey(key)) continue;
bindings[key] = value;
}
for (const p of meta.params) {
if (!(p.name in bindings)) continue;
const v = bindings[p.name];
if (p.isArray) {
if (!Array.isArray(v)) throw new Error(`DSLValueGraph: parameter '${p.name}' of '${name}' must be an array`);
} else if (!validateValueType(v, p.type)) {
throw new Error(`DSLValueGraph: parameter '${p.name}' of '${name}' must match declared type '${p.type}'`);
}
}
return bindings;
}
// ---------------------------------------------------------------------------
// Resolvers (the compute substrate)
// ---------------------------------------------------------------------------
_resolve(name, subject, bindings, ctx, cb) {
const resolver = this.resolvers.get(name);
if (resolver) return resolver(subject, bindings, ctx, cb);
cb(null, null); // stored-only measure with nothing stored → null
}
/**
* Register an external value resolver for a declared measure. The resolver is
* a value-graph callback/sync resolver: `(subject, params, ctx, cb)` → calls
* `cb(err, value)` (or `{ value, unit, source }`) or returns a value synchronously.
* Unknown measures are a no-op in non-strict mode, an error in strict mode.
*/
resolve(name, fn) {
if (!this._measure(name)) return this;
if (typeof fn !== 'function') throw new Error(`DSLValueGraph: resolver for '${name}' must be a function`);
this.resolvers.set(name, fn);
return this;
}
// ---------------------------------------------------------------------------
// Storage — values/attributes that are NOT cached or computed.
// ---------------------------------------------------------------------------
/**
* Store a value/attribute directly into the value-graph. The value is validated
* against the measure's declared PROVIDES type and readable back via getValue /
* measure / runtime.measure until overwritten or invalidated.
* Unknown measures are a no-op in non-strict mode, an error in strict mode.
*/
setValue(name, args, value, { unit = null, source = 'dsl' } = {}) {
const meta = this._measure(name);
if (!meta) return this;
if (!validateValueType(value, meta.returnType)) {
throw new Error(`DSLValueGraph: value for '${name}' must match declared type '${meta.returnType}'`);
}
const bindings = this._bindings(name, args);
const subject = this.subjectOf(name, args);
this.vg.set(subject, name, bindings, { value, unit, source });
return this;
}
// ---------------------------------------------------------------------------
// Retrieval — partial-graph purposes.
// ---------------------------------------------------------------------------
/**
* Synchronously retrieve a value from the value-graph (stored or resolved).
* Returns the entry `{ value, unit, at, source, fresh }` or `null`.
* Unknown measures are null in non-strict mode, an error in strict mode.
*/
getValue(name, args) {
const meta = this._measure(name);
if (!meta) return null;
const bindings = this._bindings(name, args);
const subject = this.subjectOf(name, args);
let out = null;
let errOut = null;
this.vg.get(subject, name, bindings, (err, entry) => { errOut = err; out = entry; });
if (errOut) throw errOut;
return out;
}
/**
* Async measure retrieval matching `DSLRuntime.measure`'s shape:
* `{ value, unit, source }`. Missing → `{ value: null, unit: null, source: null }`.
* Unknown measures are `{ value: null, ... }` in non-strict mode, an error in strict mode.
*/
async measure(name, args = {}) {
const meta = this._measure(name);
if (!meta) return { value: null, unit: null, source: null };
const bindings = this._bindings(name, args);
const subject = this.subjectOf(name, args);
return new Promise((resolve, reject) => {
this.vg.get(subject, name, bindings, (err, entry) => {
if (err) return reject(err);
resolve(entry
? { value: entry.value, unit: entry.unit, source: entry.source }
: { value: null, unit: null, source: null });
});
});
}
/**
* Wire `runtime.measure(name, args)` through the value-graph by registering a
* value-graph-backed provider for every DECLARED measure. Re-syncs first, so a
* recompiled runtime picks up new measures and drops attach-registered
* providers for removed ones. A later manual `registerMeasure` overrides it
* until the next attach.
*/
attach() {
this.sync();
const declared = new Set(this.measures.keys());
for (const name of this._attached) {
if (!declared.has(name) && this.runtime.measureProviders.has(name)) {
this.runtime.unregisterMeasure(name);
}
}
for (const name of declared) {
this.runtime.registerMeasure(name, async (bindings) => this.measure(name, bindings));
this._attached.add(name);
}
return this;
}
}
export default DSLValueGraph;
+129
View File
@@ -0,0 +1,129 @@
/**
* tests/ChainConditionStep.test.js — a chain whose FINAL (object-side) hop
* references a defeasible/logical evidence. The compiler lowers it to a
* condition step: `{ rule: <config>, conditionStep: true }`, which the engine
* verifies at (intermediate, object) rather than traversing an edge.
*
* Only the final step may be a condition (the object is known); an
* intermediate condition cannot discover nodes and is a compile error.
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { Arbiter } from '@arbiter/core';
import { DSLCompiler } from '../src/DSLCompiler.js';
const DEFS = `
definition Employee { id: string }
definition Group { id: string }
definition Doc { id: string }
fact member_of(user: Employee, group: Group)
fact can_view(group: Group, doc: Doc)
fact banned(group: Group)
fact can_edit(group: Group, doc: Doc)
`;
function compile(dsl, name = 'chain-cond') {
const arb = new Arbiter();
const compiler = new DSLCompiler(arb);
const result = compiler.compile(dsl, name);
return { arb, result };
}
describe('Chain condition step (logical evidence as final hop)', () => {
it('lowers a defeasible final step to a condition step and grants', () => {
const { arb, result } = compile(`
${DEFS}
evidence gated(group: Group, doc: Doc) { WHEN can_view(group, doc) UNLESS banned(group) }
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
`);
assert.ok(result.success, JSON.stringify(result.errors));
const steps = arb.relationConfigs.get('can_via').steps;
assert.equal(steps[0], 'member_of');
assert.equal(steps[1].conditionStep, true);
assert.equal(steps[1].rule.type, 'logical');
// transitive dependency collection through the condition step
assert.deepEqual(arb.relationConfigs.get('can_via').dependsOn, ['member_of', 'can_view', 'banned']);
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('doc:9', 'Doc');
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
arb.addRelation('g:1', 'can_view', 'doc:9', { possibility: 0.7 });
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.7);
// banning the intermediate defeats the condition hop
arb.addRelation('g:1', 'banned', 'g:1', { possibility: 1.0 });
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0);
});
it('supports ALWAYS/NEVER evidence as a condition step', () => {
const { arb, result } = compile(`
${DEFS}
evidence gated(group: Group, doc: Doc) { ALWAYS can_edit(group, doc) }
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
`);
assert.ok(result.success, JSON.stringify(result.errors));
const steps = arb.relationConfigs.get('can_via').steps;
assert.equal(steps[1].conditionStep, true);
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('doc:9', 'Doc');
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 1.0 });
arb.addRelation('g:1', 'can_edit', 'doc:9', { possibility: 0.6 });
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.6);
arb.removeRelation('g:1', 'can_edit', 'doc:9');
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0);
});
it('keeps the condition evidence checkable in its own right', () => {
const { arb, result } = compile(`
${DEFS}
evidence gated(group: Group, doc: Doc) { WHEN can_view(group, doc) UNLESS banned(group) }
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
`);
assert.ok(result.success, JSON.stringify(result.errors));
arb.addNode('g:1', 'Group'); arb.addNode('doc:9', 'Doc');
arb.addRelation('g:1', 'can_view', 'doc:9', { possibility: 0.8 });
assert.equal(arb.check('g:1', 'gated', 'doc:9').possibility, 0.8);
});
it('parallel intermediates aggregate through the condition step', () => {
const { arb, result } = compile(`
${DEFS}
evidence gated(group: Group, doc: Doc) { can_view(group, doc) }
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
`);
assert.ok(result.success, JSON.stringify(result.errors));
arb.addNode('u:1', 'Employee'); arb.addNode('g:1', 'Group'); arb.addNode('g2:2', 'Group'); arb.addNode('doc:9', 'Doc');
arb.addRelation('u:1', 'member_of', 'g:1', { possibility: 0.5 });
arb.addRelation('g:1', 'can_view', 'doc:9', { possibility: 0.7 });
arb.addRelation('u:1', 'member_of', 'g2:2', { possibility: 1.0 });
arb.addRelation('g2:2', 'can_view', 'doc:9', { possibility: 0.8 });
// max over paths: min(0.5,0.7)=0.5, min(1.0,0.8)=0.8 -> 0.8
assert.equal(arb.check('u:1', 'can_via', 'doc:9').possibility, 0.8);
});
it('expands an INTERMEDIATE condition step via rule-based reachability', () => {
const { arb, result } = compile(`
definition Employee { id: string }
definition Doc { id: string }
fact peer(user: Employee, other: Employee)
fact trusted(other: Employee)
fact can_read(user: Employee, doc: Doc)
evidence peer_trusted(user: Employee, other: Employee) { WHEN peer(user, other) UNLESS trusted(other) }
evidence can_access(user: Employee, doc: Doc) { peer_trusted(user, *p) { can_read(p, doc) } }
`);
assert.ok(result.success, JSON.stringify(result.errors));
const steps = arb.relationConfigs.get('can_access').steps;
assert.equal(steps[0].conditionStep, true);
assert.equal(steps[0].rule.type, 'logical');
arb.addNode('u:1', 'Employee'); arb.addNode('p:1', 'Employee'); arb.addNode('p:2', 'Employee'); arb.addNode('doc:9', 'Doc');
arb.addRelation('u:1', 'peer', 'p:1', { possibility: 1.0 });
arb.addRelation('u:1', 'peer', 'p:2', { possibility: 1.0 });
arb.addRelation('p:1', 'trusted', 'p:1', { possibility: 1.0 }); // p:1 filtered
arb.addRelation('p:1', 'can_read', 'doc:9', { possibility: 0.9 });
arb.addRelation('p:2', 'can_read', 'doc:9', { possibility: 0.7 });
// only untrusted peer p:2 survives the intermediate condition -> 0.7
assert.equal(arb.check('u:1', 'can_access', 'doc:9').possibility, 0.7);
// trusting p:2 too removes all intermediates -> 0
arb.addRelation('p:2', 'trusted', 'p:2', { possibility: 1.0 });
assert.equal(arb.check('u:1', 'can_access', 'doc:9').possibility, 0);
});
});
+8 -4
View File
@@ -81,14 +81,18 @@ describe('Chain step composition', () => {
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(`
it('lowers a logical evidence FINAL step to a condition step', () => {
const { arb, result } = compile(`
${DEFS}
evidence gated(group: Group, doc: Doc) { WHEN can_view(group, doc) UNLESS banned(group) }
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
`);
assert.equal(result.success, false);
assert.ok(result.errors.some(e => /Chain step 'gated'/.test(e)), JSON.stringify(result.errors));
assert.ok(result.success, JSON.stringify(result.errors));
// final-step logical evidence → condition step (verified at the object)
const steps = arb.relationConfigs.get('can_via').steps;
assert.equal(steps[0], 'member_of');
assert.equal(steps[1].conditionStep, true);
assert.equal(steps[1].rule.type, 'logical');
});
it('rejects a mutual cycle through chain steps', () => {
+30
View File
@@ -196,6 +196,36 @@ describe('DSL Compiler', () => {
assert.ok(invalidResult.errors.length > 0, 'Should have validation errors');
});
test('Rejects duplicate fields within a definition', () => {
const dupFieldDSL = `
definition Employee { id: string id: string }
`;
const result = compiler.validate(dupFieldDSL);
assert.ok(!result.success, 'Duplicate field should fail validation');
assert.match(result.errors[0], /Duplicate field 'Employee.id'/);
});
test('Hints at the real constraint for common declaration mistakes', () => {
const withinOnFact = compiler.compile(`
definition Employee { id: string? }
fact owns(user: Employee, doc: Employee) within 1h
`, 'err-within');
assert.match(withinOnFact.errors[0], /within.*only valid on `source`/);
const doubleBehaves = compiler.compile(`
definition Employee { id: string? }
fact rel(user: Employee, doc: Employee) BEHAVES AS transitive BEHAVES { ttl 1h }
`, 'err-behaves');
assert.match(doubleBehaves.errors[0], /only one `BEHAVES` clause/);
const limitAfterBody = compiler.compile(`
definition Employee { id: string? }
fact owns(user: Employee, doc: Employee)
evidence can_read(user: Employee, doc: Employee) { owns(user, doc) } limit 5
`, 'err-limit');
assert.match(limitAfterBody.errors[0], /`limit` is only valid on pattern/);
});
test('Rule generation', () => {
const dsl = `
definition Employee {
+141 -5
View File
@@ -20,9 +20,9 @@ import { Arbiter } from '@arbiter/core';
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
const BASE_DSL = `
definition Employee { id: string level: number active: boolean }
definition Group { id: string }
definition Doc { id: string }
definition Employee { id: string? level: number? active: boolean? }
definition Group { id: string? }
definition Doc { id: string? }
fact member_of(user: Employee, group: Group)
fact *owns(user: Employee, doc: Doc)
fact *user_score(user: Employee, value: number)
@@ -164,8 +164,8 @@ describe('DSLRuntime', () => {
it('derives transitive required facts through evidence composition', async () => {
const dsl = `
definition Employee { id: string }
definition Doc { id: string }
definition Employee { id: string? }
definition Doc { id: string? }
fact *owns(user: Employee, doc: Doc)
fact *banned(user: Employee)
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
@@ -188,4 +188,140 @@ describe('DSLRuntime', () => {
assert.equal(denied.possibility, 0);
assert.equal(denied.reason, 'defeated_by_unless');
});
it('derives transitive required facts through a condition-step chain', () => {
const dsl = `
definition Employee { id: string? }
definition Group { id: string? }
definition Doc { id: string? }
fact *member_of(user: Employee, group: Group)
fact *can_view(group: Group, doc: Doc)
fact *banned(group: Group)
evidence gated(group: Group, doc: Doc) { WHEN can_view(group, doc) UNLESS banned(group) }
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }
`;
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-cond');
// The condition step's facts (can_view, banned) reach through to the
// evidence's requirements, alongside the edge-traversal fact.
assert.deepEqual(rt.requiredFacts('can_via'), ['member_of', 'can_view', 'banned']);
});
it('negates a NOT predicate (1 - possibility)', async () => {
const dsl = `
definition Employee { id: string? }
fact banned(user: Employee)
evidence can_enter(user: Employee) { NOT banned(user) }
`;
// Absent predicate negates to allow.
const absent = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-not-absent');
absent.addNode('u:1', 'Employee', {});
assert.equal((await absent.check('u:1', 'can_enter', 'u:1')).possibility, 1);
// Present predicate negates to its complement.
const present = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-not-present');
present.addNode('u:1', 'Employee', {});
present.addRelation('u:1', 'banned', 'u:1', { possibility: 0.9 });
const denied = await present.check('u:1', 'can_enter', 'u:1');
assert.ok(Math.abs(denied.possibility - 0.1) < 1e-9, `expected 0.1, got ${denied.possibility}`);
// Nested inside an AND: the negated child still scopes to the subject.
const nested = new DSLRuntime(new Arbiter()).compile(`
definition Employee { id: string? }
definition Doc { id: string? }
fact owns(user: Employee, doc: Doc)
fact banned(user: Employee)
evidence can_open(user: Employee, doc: Doc) { owns(user, doc) NOT banned(user) }
`, 'rt-not-nested');
nested.addNode('u:1', 'Employee', {});
nested.addNode('doc:9', 'Doc', {});
nested.addRelation('u:1', 'owns', 'doc:9', { possibility: 0.8 });
nested.addRelation('u:1', 'banned', 'u:1', { possibility: 0.6 });
assert.equal((await nested.check('u:1', 'can_open', 'doc:9')).possibility, 0.4);
});
it('resolves BEHAVES AS transitive facts as bounded transitive closure', async () => {
const dsl = `
definition Employee { id: string? }
fact reports_to(user: Employee, boss: Employee) BEHAVES AS transitive
evidence can_see(user: Employee, doc: Employee) { reports_to(user, doc) }
`;
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-transitive');
['e:1', 'e:2', 'e:3', 'e:4'].forEach(k => rt.addNode(k, 'Employee', {}));
rt.addRelation('e:1', 'reports_to', 'e:2', { possibility: 1.0 });
rt.addRelation('e:2', 'reports_to', 'e:3', { possibility: 0.9 });
rt.addRelation('e:3', 'reports_to', 'e:4', { possibility: 0.8 });
// Direct checks on the transitive fact follow multi-hop paths.
assert.equal((await rt.check('e:1', 'reports_to', 'e:3')).possibility, 0.9);
assert.equal((await rt.check('e:1', 'reports_to', 'e:4')).possibility, 0.8);
// Reverse direction does not grant.
assert.equal((await rt.check('e:2', 'reports_to', 'e:1')).possibility, 0);
// Evidence references inherit the closure.
assert.equal((await rt.check('e:1', 'can_see', 'e:4')).possibility, 0.8);
// Non-transitive facts stay direct-only.
const direct = new DSLRuntime(new Arbiter()).compile(`
definition Employee { id: string? }
fact knows(user: Employee, peer: Employee)
evidence can_ping(user: Employee, doc: Employee) { knows(user, doc) }
`, 'rt-nontransitive');
['a:1', 'a:2', 'a:3'].forEach(k => direct.addNode(k, 'Employee', {}));
direct.addRelation('a:1', 'knows', 'a:2', { possibility: 1.0 });
direct.addRelation('a:2', 'knows', 'a:3', { possibility: 1.0 });
assert.equal((await direct.check('a:1', 'can_ping', 'a:3')).possibility, 0);
});
it('bounds transitive closure depth by the fact limit', async () => {
const rt = new DSLRuntime(new Arbiter()).compile(`
definition Employee { id: string? }
fact reports_to(user: Employee, boss: Employee) BEHAVES AS transitive limit 2
evidence can_see(user: Employee, doc: Employee) { reports_to(user, doc) }
`, 'rt-transitive-limit');
['e:1', 'e:2', 'e:3', 'e:4'].forEach(k => rt.addNode(k, 'Employee', {}));
rt.addRelation('e:1', 'reports_to', 'e:2', { possibility: 1.0 });
rt.addRelation('e:2', 'reports_to', 'e:3', { possibility: 1.0 });
rt.addRelation('e:3', 'reports_to', 'e:4', { possibility: 1.0 });
assert.equal((await rt.check('e:1', 'can_see', 'e:3')).possibility, 1.0);
assert.equal((await rt.check('e:1', 'can_see', 'e:4')).possibility, 0);
});
it('retrieves sources through providers and gates them by within recency', async () => {
const rt = new DSLRuntime(new Arbiter()).compile(`
definition Employee { id: string? }
definition Doc { id: string? }
source *session(user: Employee) within 1h
fact *owns(user: Employee, doc: Doc)
evidence can_read(user: Employee, doc: Doc) { session(user) owns(user, doc) }
`, 'rt-source');
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
assert.ok(rt.relations.has('session'));
assert.equal(rt.relations.get('session').kind, 'source');
assert.equal(rt.relations.get('session').withinMs, 3_600_000);
// A fresh session proof grants.
const fresh = await rt.check('u:1', 'can_read', 'doc:9', {
factProviders: { session: async () => ({ possibility: 1.0, value: Date.now() }), owns: async () => 0.9 }
});
assert.equal(fresh.possibility, 0.9);
assert.deepEqual(fresh.providedFacts, ['session', 'owns']);
// A stale proof (2h old, beyond the 1h window) denies as stale.
const stale = await rt.check('u:1', 'can_read', 'doc:9', {
factProviders: { session: async () => ({ possibility: 1.0, value: Date.now() - 2 * 3600_000 }), owns: async () => 0.9 }
});
assert.equal(stale.possibility, 0);
assert.deepEqual(stale.missingFacts, [{ relation: 'session', reason: 'stale' }]);
});
it('warns about and drops provider edges referencing unknown nodes', async () => {
const rt = new DSLRuntime(new Arbiter()).compile(`
definition Employee { id: string? }
definition Doc { id: string? }
fact *owns(user: Employee, doc: Doc)
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
`, 'rt-ghost');
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
const res = await rt.check('u:1', 'can_read', 'doc:9', {
factProviders: { owns: async () => [{ src: 'ghost:1', dst: 'doc:9', possibility: 0.9 }] }
});
assert.equal(res.possibility, 0);
assert.equal(res.warnings.length, 1);
assert.match(res.warnings[0], /unknown source node 'ghost:1'/);
});
});
+203
View File
@@ -0,0 +1,203 @@
/**
* tests/DSLRuntimeCache.test.js — provider-result caching with time expiry.
*
* Registered providers retrieve missing facts from a data store; caching the
* retrieval avoids hammering the store on repeated checks. TTL resolution:
* DSL-declared `BEHAVES { ttl <duration> }` on a fact > per-fact setFactTTL >
* policy default (30s). Per-check factProviders are cache-transparent (one-off
* observations: no cache read, no cache write). Registering a provider or
* mutating the graph invalidates the cache.
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { Arbiter } from '@arbiter/core';
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
const BASE_DSL = `
definition Employee { id: string? }
definition Doc { id: string? }
fact *owns(user: Employee, doc: Doc)
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
`;
function makeRuntime(options = {}) {
let t = 0;
const clock = () => t;
const rt = new DSLRuntime(new Arbiter(), { clock, ...options }).compile(BASE_DSL, 'rt-cache');
rt._test_advance = (ms) => { t += ms; };
return rt;
}
describe('DSLRuntime provider-result caching', () => {
it('reuses a registered provider result within the TTL', async () => {
const rt = makeRuntime();
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
let calls = 0;
rt.registerFact('owns', async () => { calls++; return 0.9; });
await rt.check('u:1', 'can_read', 'doc:9');
await rt.check('u:1', 'can_read', 'doc:9');
assert.equal(calls, 1, 'provider should be invoked once within TTL');
});
it('re-invokes the provider after the TTL expires', async () => {
const rt = makeRuntime();
rt.setFactTTL('owns', 100);
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
let calls = 0;
let value = 0.9;
rt.registerFact('owns', async () => { calls++; return value; });
const first = await rt.check('u:1', 'can_read', 'doc:9');
assert.equal(first.possibility, 0.9);
rt._test_advance(50);
await rt.check('u:1', 'can_read', 'doc:9'); // within TTL -> cached
assert.equal(calls, 1);
rt._test_advance(60); // past TTL (110 total)
value = 0.4;
const after = await rt.check('u:1', 'can_read', 'doc:9');
assert.equal(calls, 2);
assert.equal(after.possibility, 0.4);
});
it('per-check factProviders override the cache (fresh observation)', async () => {
const rt = makeRuntime();
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
rt.registerFact('owns', async () => 0.9);
await rt.check('u:1', 'can_read', 'doc:9');
// Per-check override is cache-transparent: it must NOT be masked by the
// cached 0.9, and it must NOT overwrite the cached value.
const over = await rt.check('u:1', 'can_read', 'doc:9', {
factProviders: { owns: async () => 0.2 }
});
assert.equal(over.possibility, 0.2);
const next = await rt.check('u:1', 'can_read', 'doc:9');
assert.equal(next.possibility, 0.9, 'registered provider cache untouched by per-check override');
});
it('registerFact invalidates the cached result for that relation', async () => {
const rt = makeRuntime();
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
rt.registerFact('owns', async () => 0.9);
await rt.check('u:1', 'can_read', 'doc:9');
rt.registerFact('owns', async () => 0.3); // re-register -> cache invalidated
const res = await rt.check('u:1', 'can_read', 'doc:9');
assert.equal(res.possibility, 0.3);
});
it('invalidates cached results on graph mutations', async () => {
const rt = makeRuntime();
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
let calls = 0;
rt.registerFact('owns', async () => { calls++; return 0.9; });
await rt.check('u:1', 'can_read', 'doc:9');
assert.equal(calls, 1);
rt.addRelation('u:1', 'owns', 'doc:9', { possibility: 1.0 }); // mutation clears cache
const res = await rt.check('u:1', 'can_read', 'doc:9');
assert.equal(calls, 2, 'graph mutation should invalidate the provider cache');
});
it('invalidateProviderCache() clears all or per relation', async () => {
const dsl = `
definition Employee { id: string? }
definition Doc { id: string? }
fact *owns(user: Employee, doc: Doc)
fact *banned(user: Employee)
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
evidence can_open(user: Employee, doc: Doc) { WHEN can_read(user, doc) UNLESS banned(user) }
`;
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-cache2');
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
let ownsCalls = 0, bannedCalls = 0;
rt.registerFact('owns', async () => { ownsCalls++; return 0.9; });
rt.registerFact('banned', async () => { bannedCalls++; return 0; });
await rt.check('u:1', 'can_open', 'doc:9');
assert.equal(ownsCalls, 1);
assert.equal(bannedCalls, 1);
// Invalidate a non-dependency relation: can_open's cache (owns+banned) survives.
rt.invalidateProviderCache('does_not_exist');
await rt.check('u:1', 'can_open', 'doc:9');
assert.equal(ownsCalls, 1);
assert.equal(bannedCalls, 1);
// Invalidate owns only: banned survives, owns re-fetched.
rt.invalidateProviderCache('owns');
await rt.check('u:1', 'can_open', 'doc:9');
assert.equal(ownsCalls, 2, 'owns cache cleared by per-relation invalidation');
assert.equal(bannedCalls, 1, 'banned cache survives per-relation invalidation');
// Clear all.
rt.invalidateProviderCache();
await rt.check('u:1', 'can_open', 'doc:9');
assert.equal(bannedCalls, 2, 'full invalidation clears every relation');
});
it('policy default TTL applies when no per-fact TTL is set', async () => {
const rt = makeRuntime({ policy: { providerCacheTTL: 50 } });
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
let calls = 0;
rt.registerFact('owns', async () => { calls++; return 0.9; });
await rt.check('u:1', 'can_read', 'doc:9');
rt._test_advance(40);
await rt.check('u:1', 'can_read', 'doc:9');
assert.equal(calls, 1, 'within 50ms policy TTL -> cached');
rt._test_advance(20);
await rt.check('u:1', 'can_read', 'doc:9');
assert.equal(calls, 2, 'past 50ms policy TTL -> re-invoked');
});
it('uses the DSL-declared fact TTL (BEHAVES { ttl X })', async () => {
const dsl = `
definition Employee { id: string? }
definition Doc { id: string? }
fact *balance(user: Employee, amount: number) BEHAVES { ttl 1h }
evidence can_spend(user: Employee, doc: Doc) { balance(user, 1) }
`;
let t = 0;
const rt = new DSLRuntime(new Arbiter(), { clock: () => t }).compile(dsl, 'rt-dsl-ttl');
// The DSL declares a 1h TTL for the balance fact.
assert.equal(rt.relations.get('balance').ttlMs, 3600_000);
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
let calls = 0;
rt.registerFact('balance', async () => { calls++; return { possibility: 1.0, value: 50 }; });
await rt.check('u:1', 'can_spend', 'doc:9');
assert.equal(calls, 1);
t += 60 * 60 * 1000 - 1; // just under 1h
await rt.check('u:1', 'can_spend', 'doc:9');
assert.equal(calls, 1, 'cached within DSL-declared 1h TTL');
t += 2;
await rt.check('u:1', 'can_spend', 'doc:9');
assert.equal(calls, 2, 're-invoked past the DSL-declared 1h TTL');
});
it('cacheProviderResults:false bypasses the cache per check', async () => {
const rt = makeRuntime();
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
let calls = 0;
rt.registerFact('owns', async () => { calls++; return 0.9; });
await rt.check('u:1', 'can_read', 'doc:9');
assert.equal(calls, 1);
// Bypass forces a fresh retrieval without clearing the cache.
await rt.check('u:1', 'can_read', 'doc:9', { cacheProviderResults: false });
assert.equal(calls, 2);
// Cache still intact for the next default check.
await rt.check('u:1', 'can_read', 'doc:9');
assert.equal(calls, 2);
});
it('policy.cacheProviderResults:false disables caching globally', async () => {
const rt = makeRuntime({ policy: { cacheProviderResults: false } });
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
let calls = 0;
rt.registerFact('owns', async () => { calls++; return 0.9; });
await rt.check('u:1', 'can_read', 'doc:9');
await rt.check('u:1', 'can_read', 'doc:9');
assert.equal(calls, 2, 'no caching when disabled globally');
});
});
+233
View File
@@ -0,0 +1,233 @@
/**
* tests/DSLRuntimeExt.test.js — extended DSLRuntime capabilities:
* - schema introspection (getSchema)
* - per-relation provider registration (registerFact/unregisterFact)
* - provider merging (registered + per-check overrides)
* - bounded fixed-point provider retrieval loop (edges satisfy other facts)
* - require() throw-on-deny
* - removal passthroughs and fact-relation check validation
* - timestamp/duration field typing
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { Arbiter } from '@arbiter/core';
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
const BASE_DSL = `
definition Employee { id: string? level: number? active: boolean? }
definition Doc { id: string? created: timestamp? }
fact *owns(user: Employee, doc: Doc)
fact *banned(user: Employee)
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
evidence can_open(user: Employee, doc: Doc) { WHEN can_read(user, doc) UNLESS banned(user) }
`;
function makeRuntime() {
return new DSLRuntime(new Arbiter()).compile(BASE_DSL, 'rt-ext');
}
describe('DSLRuntime extended', () => {
it('exposes a serializable schema snapshot', () => {
const rt = makeRuntime();
const schema = rt.getSchema();
assert.ok(Array.isArray(schema.types));
const employee = schema.types.find(t => t.name === 'Employee');
assert.ok(employee);
assert.ok(employee.fields.some(f => f.name === 'level' && f.type === 'number'));
const owns = schema.facts.find(f => f.name === 'owns');
assert.equal(owns.injectable, true);
assert.equal(owns.params[1].type, 'Doc');
const can_open = schema.evidence.find(e => e.name === 'can_open');
assert.ok(can_open.dependsOn.includes('owns'));
assert.deepEqual(schema.providers, []);
assert.ok(rt.relationNames().includes('owns') && rt.relationNames().includes('can_read'));
});
it('registers, lists, and unregisters per-relation providers', () => {
const rt = makeRuntime();
rt.registerFact('owns', async () => 0.8);
assert.deepEqual(rt.registeredFacts(), ['owns']);
rt.registerFact('banned', async () => 0);
assert.deepEqual(rt.registeredFacts().sort(), ['banned', 'owns']);
rt.unregisterFact('banned');
assert.deepEqual(rt.registeredFacts(), ['owns']);
assert.throws(() => rt.registerFact('owns', 'not a function'), /must be a function/);
});
it('merges registered providers with per-check overrides', async () => {
const rt = makeRuntime();
rt.registerFact('owns', async () => 0.5);
rt.registerFact('banned', async () => 0);
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
// registered owns (0.5) wins over nothing; per-check banned overrides
const res = await rt.check('u:1', 'can_open', 'doc:9', {
factProviders: { banned: async () => 0 }
});
assert.equal(res.possibility, 0.5);
assert.deepEqual(res.providedFacts.sort(), ['banned', 'owns']);
});
it('runs providers to a fixed point when edges satisfy other required facts', async () => {
// can_open needs owns (injectable). A registered owns provider returns an
// edge for a DIFFERENT injectable fact that can_open also requires via
// composition — here we add a transitive requirement to prove the loop.
const dsl = `
definition Employee { id: string? }
definition Doc { id: string? }
fact *owns(user: Employee, doc: Doc)
fact *granted(user: Employee, doc: Doc)
evidence base_read(user: Employee, doc: Doc) { owns(user, doc) }
evidence can_open(user: Employee, doc: Doc) { WHEN base_read(user, doc) UNLESS granted(user, doc) }
`;
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-loop');
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
let ownsCalls = 0;
let grantedCalls = 0;
rt.registerFact('owns', async () => {
ownsCalls++;
// First round the owns provider also supplies the granted edge (a
// fixed-point dependency: granted needs owns to have been retrieved).
return [
{ src: 'u:1', relation: 'owns', dst: 'doc:9', possibility: 0.9 },
{ src: 'u:1', relation: 'granted', dst: 'doc:9', possibility: 0 }
];
});
rt.registerFact('granted', async () => { grantedCalls++; return 0; });
const res = await rt.check('u:1', 'can_open', 'doc:9', { maxProviderRounds: 3 });
assert.equal(res.possibility, 0.9);
// granted was satisfied by the owns provider's extra edge, so its own
// provider was never needed in a later round.
assert.equal(grantedCalls, 0);
assert.ok(ownsCalls >= 1);
assert.deepEqual(res.providedFacts, ['owns']);
assert.deepEqual(res.missingFacts, []);
});
it('require() throws on denial and returns the result on grant', async () => {
const rt = makeRuntime();
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
rt.registerFact('owns', async () => 0.9);
const ok = await rt.require('u:1', 'can_read', 'doc:9');
assert.equal(ok.possibility, 0.9);
rt.registerFact('owns', async () => 0);
await assert.rejects(
() => rt.require('u:1', 'can_read', 'doc:9'),
(err) => err.result && err.result.possibility === 0 && /denied/.test(err.message)
);
});
it('passes through node/relation removal', () => {
const rt = makeRuntime();
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
rt.addRelation('u:1', 'owns', 'doc:9', { possibility: 1.0 });
rt.removeRelation('u:1', 'owns', 'doc:9');
assert.equal(rt.arbiter.check('u:1', 'owns', 'doc:9').possibility, 0);
rt.removeNode('u:1');
assert.equal(rt.arbiter.nodeIdByKey.has('u:1'), false);
});
it('validates fact-relation check endpoints like evidence', async () => {
const rt = makeRuntime();
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
// can_read is evidence; owns is a fact — checking a fact still validates.
await assert.rejects(() => rt.check('u:1', 'owns', 'u:1', {}), /expected 'Doc'/);
});
it('accepts timestamp field values and rejects mistyped ones', () => {
const rt = makeRuntime();
rt.addNode('doc:9', 'Doc', { created: 1720000000000 });
rt.updateNodeData('doc:9', { created: '2026-08-03T00:00:00Z' });
assert.throws(() => rt.addNode('doc:8', 'Doc', { created: {} }), /must be timestamp/);
});
it('direct FACT checks consult the registered provider', async () => {
const rt = makeRuntime();
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
let calls = 0;
rt.registerFact('owns', async () => { calls++; return 0.9; });
// Checking the fact directly (not via an evidence) must retrieve it.
const res = await rt.check('u:1', 'owns', 'doc:9');
assert.equal(res.possibility, 0.9);
assert.equal(calls, 1);
assert.deepEqual(res.requiredFacts, ['owns']);
assert.deepEqual(res.providedFacts, ['owns']);
// Without a provider and without an edge, it reports the missing fact.
const rt2 = new DSLRuntime(new Arbiter()).compile(BASE_DSL, 'rt-fact-miss');
rt2.addNode('u:1', 'Employee', {});
rt2.addNode('doc:9', 'Doc', {});
const missed = await rt2.check('u:1', 'owns', 'doc:9');
assert.equal(missed.possibility, 0);
assert.deepEqual(missed.missingFacts, [{ relation: 'owns', reason: 'no_provider' }]);
});
it('recompiling a scope uninstalls its stale relation configs', async () => {
const rt = new DSLRuntime(new Arbiter());
rt.compile(`
definition Employee { id: string? }
definition Doc { id: string? }
fact owns(user: Employee, doc: Doc)
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
`, 'rt-stale');
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
rt.addRelation('u:1', 'owns', 'doc:9', { possibility: 1.0 });
assert.equal(rt.arbiter.check('u:1', 'can_read', 'doc:9').possibility, 1.0);
// Recompile the SAME scope with a different program: can_read/owns are no
// longer declared and must not keep granting. A second scope's relations
// would be unaffected (compileMultiple coexistence).
rt.compile(`
definition Employee { id: string? }
definition Doc { id: string? }
fact shares(user: Employee, doc: Doc)
evidence can_share(user: Employee, doc: Doc) { shares(user, doc) }
`, 'rt-stale');
const stale = rt.arbiter.check('u:1', 'can_read', 'doc:9');
assert.equal(stale.possibility, 0, 'revoked can_read must not keep granting');
assert.ok(!rt.arbiter.relationConfigs.has('can_read'));
assert.ok(!rt.arbiter.relationConfigs.has('owns'));
assert.ok(rt.arbiter.relationConfigs.has('can_share'));
});
it('indexes measures and resolves them via a registered provider', async () => {
const rt = new DSLRuntime(new Arbiter()).compile(`
definition Employee { id: string? }
definition Project { id: string? }
measure budget_available(tenant: Employee, feature: string) { } PROVIDES number
measure clearance(user: Employee) { } PROVIDES string
`, 'rt-measures');
// Schema exposes measures with their return type.
const schema = rt.getSchema();
const budget = schema.measures.find(m => m.name === 'budget_available');
assert.ok(budget);
assert.equal(budget.returnType, 'number');
assert.deepEqual(budget.params.map(p => p.name), ['tenant', 'feature']);
assert.ok(rt.relationNames().includes('clearance'));
// No provider yet → resolution fails loudly.
await assert.rejects(() => rt.measure('budget_available', { tenant: 'tenant:acme', feature: 'tokens_in:gpt-4' }), /no provider registered/);
// Register a provider (the ARRA adapter would bridge the value-graph).
rt.registerMeasure('budget_available', async ({ tenant, feature }) => {
assert.equal(tenant, 'tenant:acme');
assert.equal(feature, 'tokens_in:gpt-4');
return { value: 1250, unit: 'tokens' };
});
const resolved = await rt.measure('budget_available', { tenant: 'tenant:acme', feature: 'tokens_in:gpt-4' });
assert.equal(resolved.value, 1250);
assert.equal(resolved.unit, 'tokens');
// Positional args bind by param order for unary measures.
rt.registerMeasure('clearance', async () => ({ value: 'secret' }));
assert.equal((await rt.measure('clearance', ['user:alice'])).value, 'secret');
// registerMeasure rejects undeclared names.
assert.throws(() => rt.registerMeasure('nope', async () => 1), /not a declared measure/);
});
});
+136
View File
@@ -0,0 +1,136 @@
/**
* tests/DSLRuntimeTyping.test.js duration seconds, required fields, and
* type validation of insertions / updates / provider retrievals.
*
* - Duration literals now accept s/m/h/d/w: `BEHAVES { ttl 30s }` is 30s.
* - Definition fields are REQUIRED by default (`field: type`); `field: type?`
* marks a field optional. addNode enforces presence on insert.
* - Provider-returned edges are validated against the fact's declared typing:
* a value-carrying fact must return { value, possibility } with a value of
* the declared type, and possibilities must lie in [0, 1].
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { Arbiter } from '@arbiter/core';
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
describe('DSLRuntime typing', () => {
it('accepts seconds/minutes/hours/days/weeks in duration literals', async () => {
const dsl = `
definition Employee { id: string? }
definition Doc { id: string? }
fact *a(user: Employee, amount: number) BEHAVES { ttl 30s }
fact *b(user: Employee, amount: number) BEHAVES { ttl 2m }
fact *c(user: Employee, amount: number) BEHAVES { ttl 1h }
fact *d(user: Employee, amount: number) BEHAVES { ttl 3d }
fact *e(user: Employee, amount: number) BEHAVES { ttl 1w }
`;
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'rt-units');
assert.equal(rt.relations.get('a').ttlMs, 30_000);
assert.equal(rt.relations.get('b').ttlMs, 120_000);
assert.equal(rt.relations.get('c').ttlMs, 3_600_000);
assert.equal(rt.relations.get('d').ttlMs, 259_200_000);
assert.equal(rt.relations.get('e').ttlMs, 604_800_000);
});
it('enforces required definition fields on node insert', () => {
const rt = new DSLRuntime(new Arbiter()).compile(`
definition Employee { id: string level: number active: boolean? }
`, 'rt-req');
// id and level are required (no `?`); active is optional.
assert.throws(() => rt.addNode('u:1', 'Employee', { level: 3 }), /missing required field 'Employee.id'/);
assert.throws(() => rt.addNode('u:2', 'Employee', { id: 'u:2' }), /missing required field 'Employee.level'/);
rt.addNode('u:3', 'Employee', { id: 'u:3', level: 5 }); // both required, no active -> ok
rt.addNode('u:4', 'Employee', { id: 'u:4', level: 5, active: true });
});
it('exposes requiredness in the schema snapshot', () => {
const rt = new DSLRuntime(new Arbiter()).compile(`
definition Employee { id: string level: number? }
`, 'rt-schema-req');
const employee = rt.getSchema().types.find(t => t.name === 'Employee');
assert.equal(employee.fields.find(f => f.name === 'id').required, true);
assert.equal(employee.fields.find(f => f.name === 'level').required, false);
});
it('validates a provider-returned value against the declared value type', async () => {
const rt = new DSLRuntime(new Arbiter()).compile(`
definition Employee { id: string? }
definition Doc { id: string? }
fact *balance(user: Employee, amount: number)
evidence can_spend(user: Employee, doc: Doc) { balance(user, 1) }
`, 'rt-valuetype');
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
rt.registerFact('balance', async () => ({ possibility: 1.0, value: 'high' }));
await assert.rejects(() => rt.check('u:1', 'can_spend', 'doc:9'), /must be number/);
});
it('requires a value for a value-carrying fact (no bare-number shorthand)', async () => {
const rt = new DSLRuntime(new Arbiter()).compile(`
definition Employee { id: string? }
definition Doc { id: string? }
fact *balance(user: Employee, amount: number)
evidence can_spend(user: Employee, doc: Doc) { balance(user, 1) }
`, 'rt-valshape');
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
rt.registerFact('balance', async () => 0.9);
await assert.rejects(() => rt.check('u:1', 'can_spend', 'doc:9'), /value-carrying fact/);
rt.registerFact('balance', async () => ({ possibility: 1.0 })); // missing value
await assert.rejects(() => rt.check('u:1', 'can_spend', 'doc:9'), /must supply a 'value'/);
});
it('rejects a provider-returned possibility outside [0, 1]', async () => {
const rt = new DSLRuntime(new Arbiter()).compile(`
definition Employee { id: string? }
definition Doc { id: string? }
fact *owns(user: Employee, doc: Doc)
evidence can_read(user: Employee, doc: Doc) { owns(user, doc) }
`, 'rt-poss');
rt.addNode('u:1', 'Employee', {});
rt.addNode('doc:9', 'Doc', {});
rt.registerFact('owns', async () => ({ possibility: 2.0 }));
await assert.rejects(() => rt.check('u:1', 'can_read', 'doc:9'), /invalid possibility/);
});
it('enforces a literal value in evidence as an exact edge-value gate', async () => {
const rt = new DSLRuntime(new Arbiter()).compile(`
definition Employee { id: string? }
fact balance(user: Employee, amount: number)
evidence can_afford(user: Employee) { balance(user, 5) }
`, 'rt-expected-value');
rt.addNode('u:1', 'Employee', {});
// An edge carrying amount 3 must NOT satisfy balance(user, 5) — without the
// gate every balance edge matched regardless of amount (silent over-grant).
rt.addRelation('u:1', 'balance', 'u:1', { possibility: 1.0, value: 3 });
const denied = await rt.check('u:1', 'can_afford', 'u:1');
assert.equal(denied.possibility, 0, 'value-3 edge must not satisfy balance(user, 5)');
rt.addRelation('u:1', 'balance', 'u:1', { possibility: 0.8, value: 5 });
const granted = await rt.check('u:1', 'can_afford', 'u:1');
assert.equal(granted.possibility, 0.8, 'value-5 edge must satisfy balance(user, 5)');
});
it('treats a value-typed evidence OBJECT param as the expected edge value', async () => {
const rt = new DSLRuntime(new Arbiter()).compile(`
definition Employee { id: string? }
fact balance(user: Employee, amount: number)
evidence can_withdraw(user: Employee, amount: number) { balance(user, amount) }
`, 'rt-value-object');
rt.addNode('u:1', 'Employee', {});
rt.addRelation('u:1', 'balance', 'u:1', { possibility: 0.9, value: 5 });
// The check object is the VALUE, not a node key: grant only on exact match.
const granted = await rt.check('u:1', 'can_withdraw', 5);
assert.equal(granted.possibility, 0.9, 'value-5 check must match the value-5 edge');
const denied = await rt.check('u:1', 'can_withdraw', 3);
assert.equal(denied.possibility, 0, 'value-3 check must not match the value-5 edge');
// Re-checking the granted value must not hit a value-3 cache entry.
const again = await rt.check('u:1', 'can_withdraw', 5);
assert.equal(again.possibility, 0.9, 'value-5 re-check must not be served the value-3 result');
// Direct fact check with a value object works the same way.
const direct = await rt.check('u:1', 'balance', 5);
assert.equal(direct.possibility, 0.9, 'direct balance(user, 5) must match the value-5 edge');
// A non-scalar object for a value-typed param is rejected loudly.
await assert.rejects(() => rt.check('u:1', 'can_withdraw', 'u:1'), /must be number/);
});
});
+201
View File
@@ -0,0 +1,201 @@
/**
* DSLValueGraph evidence DSL declares the value-graph's typing/structures;
* measures retrieve through the graph (partial-graph purposes), and attributes
* that are neither cached nor computed are stored directly via setValue.
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { Arbiter } from '@arbiter/core';
import { ValueGraph } from '@arbiter/value-graph';
import { DSLRuntime, DSLValueGraph } from '../src/index.js';
function makeRuntime(dsl) {
return new DSLRuntime(new Arbiter()).compile(dsl, 'vg-test');
}
const DSL = `
definition Employee { id: string? }
definition Project { id: string? }
measure budget_available(tenant: Employee, feature: string) { } PROVIDES number
measure clearance(user: Employee) { } PROVIDES string
measure is_active(user: Employee) { } PROVIDES boolean
`;
describe('DSLValueGraph integration', () => {
it('derives the value-graph node schema from the DSL measures', () => {
const dvg = new DSLValueGraph(makeRuntime(DSL));
const schema = dvg.schema();
assert.equal(schema.budget_available.returnType, 'number');
assert.deepEqual(schema.budget_available.params.map((p) => p.name), ['tenant', 'feature']);
assert.equal(schema.clearance.returnType, 'string');
assert.equal(schema.is_active.returnType, 'boolean');
});
it('stores attributes that are neither cached nor computed, and reads them back', () => {
const dvg = new DSLValueGraph(makeRuntime(DSL));
dvg.setValue('budget_available', { __subject: 'tenant:acme', tenant: 'tenant:acme', feature: 'tokens_in:gpt-4' }, 1250, { unit: 'tokens' });
const entry = dvg.getValue('budget_available', { __subject: 'tenant:acme', tenant: 'tenant:acme', feature: 'tokens_in:gpt-4' });
assert.equal(entry.value, 1250);
assert.equal(entry.unit, 'tokens');
assert.equal(entry.source, 'dsl');
assert.equal(entry.fresh, true);
});
it('measure() retrieves through the value-graph (partial-graph purposes)', async () => {
const dvg = new DSLValueGraph(makeRuntime(DSL));
dvg.setValue('clearance', { __subject: 'user:alice', user: 'user:alice' }, 'secret');
const resolved = await dvg.measure('clearance', { __subject: 'user:alice', user: 'user:alice' });
assert.equal(resolved.value, 'secret');
});
it('attach() wires runtime.measure() through the value-graph', async () => {
const rt = makeRuntime(DSL);
const dvg = new DSLValueGraph(rt);
dvg.setValue('is_active', { __subject: 'user:alice', user: 'user:alice' }, true);
dvg.attach();
const resolved = await rt.measure('is_active', { __subject: 'user:alice', user: 'user:alice' });
assert.equal(resolved.value, true);
// A measure with nothing stored resolves to null — no provider explosion.
const missing = await rt.measure('clearance', { __subject: 'user:bob', user: 'user:bob' });
assert.equal(missing.value, null);
});
it('resolves a value via an external callback resolver (the compute substrate)', async () => {
const dvg = new DSLValueGraph(makeRuntime(DSL));
dvg.resolve('budget_available', (subject, params, ctx, cb) => {
cb(null, { value: 999, unit: 'tokens', source: 'overlay:balances' });
});
const entry = await dvg.measure('budget_available', { __subject: 'tenant:acme', tenant: 'tenant:acme', feature: 'x' });
assert.equal(entry.value, 999);
assert.equal(entry.unit, 'tokens');
assert.equal(entry.source, 'overlay:balances');
});
it('validates stored values against the declared PROVIDES type', () => {
const dvg = new DSLValueGraph(makeRuntime(DSL));
assert.throws(() => dvg.setValue('budget_available', { feature: 'x' }, 'not-a-number'), /must match declared type 'number'/);
assert.throws(() => dvg.setValue('clearance', { user: 'u' }, 42), /must match declared type 'string'/);
});
it('validates parameter bindings against the declared parameter types', () => {
const dvg = new DSLValueGraph(makeRuntime(DSL));
assert.throws(() => dvg.setValue('budget_available', { tenant: 't', feature: 42 }, 5),
/parameter 'feature' of 'budget_available' must match declared type 'string'/);
});
it('rejects unknown measure names', async () => {
const dvg = new DSLValueGraph(makeRuntime(DSL));
assert.throws(() => dvg.setValue('nope', {}, 1), /not a declared measure/);
assert.throws(() => dvg.getValue('nope', {}), /not a declared measure/);
assert.throws(() => dvg.resolve('nope', () => 1), /not a declared measure/);
await assert.rejects(() => dvg.measure('nope', {}), /not a declared measure/);
});
it('binds positional args by declared parameter order', () => {
const dvg = new DSLValueGraph(makeRuntime(DSL));
dvg.setValue('budget_available', ['tenant:acme', 'tokens_in:gpt-4'], 50);
const entry = dvg.getValue('budget_available', ['tenant:acme', 'tokens_in:gpt-4']);
assert.equal(entry.value, 50);
});
it('the value-graph itself enforces declared return types on resolver results', async () => {
const dvg = new DSLValueGraph(makeRuntime(DSL));
dvg.resolve('clearance', (s, p, ctx, cb) => cb(null, 12345)); // number, but PROVIDES string
const err = await dvg.measure('clearance', { __subject: 'user:alice', user: 'user:alice' }).then(() => null, (e) => e);
assert.ok(err, 'a wrong-typed resolver result must be rejected');
assert.match(err.message, /must match declared type 'string'/);
});
it('shares a caller-supplied value graph and supports subjectOf', () => {
const vg = new ValueGraph();
const dvg = new DSLValueGraph(makeRuntime(DSL), {
valueGraph: vg,
subjectOf: (name, args) => args.tenant || args.user || 'global'
});
assert.equal(dvg.vg, vg);
dvg.setValue('clearance', { user: 'user:alice' }, 'top-secret');
assert.equal(dvg.getValue('clearance', { user: 'user:alice' }).value, 'top-secret');
});
it('rigor: setValue/getValue round-trips always return the stored value', async () => {
const { rigor } = await import('@rigor/core');
const report = await rigor.campaign(
[rigor.fn('roundtrip', (value) => {
const dvg = new DSLValueGraph(makeRuntime(DSL));
dvg.setValue('budget_available', { __subject: 'tenant:acme', tenant: 'tenant:acme', feature: 'f' }, value);
const e = dvg.getValue('budget_available', { __subject: 'tenant:acme', tenant: 'tenant:acme', feature: 'f' });
return e ? e.value : 'MISSING';
}, rigor.args(rigor.gen.int(-100000, 100000)))],
rigor.crucible([rigor.invariant('roundtrip', (ctx) => ctx.actual === ctx.args[0])])
).run({ effort: 150, seed: 'dsl-vg-roundtrip' });
if (report.status !== 'passed') {
throw new Error(`DSLValueGraph rigor roundtrip failed: ${JSON.stringify((report.failures || []).slice(0, 3))}`);
}
});
it('rigor: setValue rejects wrong-typed values for every generated value', async () => {
const { rigor } = await import('@rigor/core');
const report = await rigor.campaign(
[rigor.fn('typed-reject', (value) => {
const dvg = new DSLValueGraph(makeRuntime(DSL));
try {
dvg.setValue('clearance', { user: 'u' }, value); // PROVIDES string
return { ok: true };
} catch (e) {
return { ok: false, error: e.message };
}
}, rigor.args(rigor.gen.int(0, 100)))],
rigor.crucible([rigor.invariant('rejects', (ctx) => ctx.actual.ok === false && /must match declared type 'string'/.test(ctx.actual.error))])
).run({ effort: 150, seed: 'dsl-vg-typecheck' });
if (report.status !== 'passed') {
throw new Error(`DSLValueGraph rigor typecheck failed: ${JSON.stringify((report.failures || []).slice(0, 3))}`);
}
});
it('the aligned type vocabulary round-trips buffer/interval/any/duration', () => {
const dvg = new DSLValueGraph(makeRuntime(`
definition T { id: string }
measure quota(user: string) { } PROVIDES buffer
measure span(user: string) { } PROVIDES interval
measure whatever(user: string) { } PROVIDES any
measure window(user: string) { } PROVIDES duration
`));
const bytes = new Uint8Array([1, 2, 3, 254, 255]);
dvg.setValue('quota', { __subject: 'u', user: 'u' }, bytes);
assert.deepEqual([...dvg.getValue('quota', { __subject: 'u', user: 'u' }).value], [...bytes]);
dvg.setValue('span', { __subject: 'u', user: 'u' }, { lower: 100, upper: 200 });
assert.deepEqual(dvg.getValue('span', { __subject: 'u', user: 'u' }).value, { lower: 100, upper: 200 });
dvg.setValue('whatever', { __subject: 'u', user: 'u' }, 42); // any → accepted
assert.equal(dvg.getValue('whatever', { __subject: 'u', user: 'u' }).value, 42);
dvg.setValue('window', { __subject: 'u', user: 'u' }, '1h');
assert.equal(dvg.getValue('window', { __subject: 'u', user: 'u' }).value, '1h');
});
it('sync() re-registers measures after the runtime recompiles', () => {
const rt = new DSLRuntime(new Arbiter()).compile('measure a() { } PROVIDES number', 'v1');
const dvg = new DSLValueGraph(rt);
rt.compile('measure b() { } PROVIDES string', 'v2'); // a removed, b added
// Before sync: stale schema.
assert.throws(() => dvg.setValue('b', {}, 'x'), /not a declared measure/);
// After sync: b is usable, a is gone.
dvg.sync();
dvg.setValue('b', {}, 'x');
assert.equal(dvg.getValue('b', {}).value, 'x');
assert.throws(() => dvg.setValue('a', {}, 1), /not a declared measure/);
// schema() reflects the current measure set
assert.ok(dvg.schema().b);
assert.ok(!dvg.schema().a);
});
it('attach() re-syncs and unregisters providers for removed measures after recompile', async () => {
const rt = new DSLRuntime(new Arbiter()).compile('measure a() { } PROVIDES number', 'v1');
const dvg = new DSLValueGraph(rt);
dvg.attach();
rt.compile('measure b() { } PROVIDES string', 'v2');
dvg.attach(); // re-sync + re-wire
dvg.setValue('b', { __subject: 't' }, 'hello');
assert.equal((await rt.measure('b', { __subject: 't' })).value, 'hello');
// a is no longer declared after the recompile → the runtime rejects it
await assert.rejects(() => rt.measure('a', { __subject: 't' }), /unknown measure/);
});
});
+62
View File
@@ -12,6 +12,8 @@ import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { Arbiter } from '@arbiter/core';
import { DSLCompiler } from '../src/DSLCompiler.js';
import { DSLRuntime } from '../src/runtime/DSLRuntime.js';
import { DSLValueGraph } from '../src/value-graph/DSLValueGraph.js';
const DEFS = `
definition Employee { id: string }
@@ -151,4 +153,64 @@ describe('Evidence composition', () => {
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);
});
describe('measure + evidence composition', () => {
const M_DEFS = `
definition Employee { id: string }
measure budget_used(user: Employee) { } PROVIDES number
measure budget_limit(user: Employee) { } PROVIDES number
evidence can_use(user: Employee, doc: string) { budget_used(user) <= budget_limit(user) }
`;
it('compiles an evidence comparator over measure valueRelations', () => {
const { arb, result } = compile(M_DEFS, 'm+e-compile');
assert.ok(result.success, JSON.stringify(result.errors));
const cfg = arb.relationConfigs.get('can_use');
assert.equal(cfg.type, 'relational_comparator');
assert.equal(cfg.left.valueRelation, 'budget_used');
assert.equal(cfg.right.valueRelation, 'budget_limit');
assert.deepEqual(cfg.dependsOn, ['budget_used', 'budget_limit']);
assert.equal(cfg._needsValues, true);
});
it('evaluates with measure values from registered providers (measure → evidence)', async () => {
const rt = new DSLRuntime(new Arbiter()).compile(M_DEFS, 'm+e-provider');
const dvg = new DSLValueGraph(rt);
dvg.attach(); // wires runtime.measure through the value-graph
rt.registerMeasure('budget_used', async () => ({ value: 900 }));
rt.registerMeasure('budget_limit', async () => ({ value: 1000 }));
rt.arbiter.addNode('u:1', 'Employee');
// Both systems live: the measure resolves standalone...
assert.equal((await rt.measure('budget_used', { user: 'u:1' })).value, 900);
// ...and composes into the evidence comparator.
const allow = await rt.check('u:1', 'can_use', 'doc:9');
assert.equal(allow.possibility, 1);
assert.equal(allow.reason, 'allow_rule_matched');
assert.ok(allow.providedFacts.includes('budget_used'), 'measure injected as a partial-graph edge');
});
it('evaluates with measure values stored in the value-graph (setValue)', async () => {
const rt = new DSLRuntime(new Arbiter()).compile(M_DEFS, 'm+e-vg');
const dvg = new DSLValueGraph(rt);
dvg.attach();
dvg.setValue('budget_used', { __subject: 'u:1', user: 'u:1' }, 900);
dvg.setValue('budget_limit', { __subject: 'u:1', user: 'u:1' }, 1000);
rt.arbiter.addNode('u:1', 'Employee');
const allow = await rt.check('u:1', 'can_use', 'doc:9');
assert.equal(allow.possibility, 1, 'in-budget evidence allowed from graph-sourced measures');
// Over budget → the comparator denies.
const rt2 = new DSLRuntime(new Arbiter()).compile(M_DEFS, 'm+e-vg2');
const dvg2 = new DSLValueGraph(rt2);
dvg2.attach();
dvg2.setValue('budget_used', { __subject: 'u:1', user: 'u:1' }, 1200);
dvg2.setValue('budget_limit', { __subject: 'u:1', user: 'u:1' }, 1000);
rt2.arbiter.addNode('u:1', 'Employee');
const deny = await rt2.check('u:1', 'can_use', 'doc:9');
assert.equal(deny.possibility, 0);
assert.equal(deny.reason, 'values_compared_comparison_false');
});
});
});
+136
View File
@@ -0,0 +1,136 @@
/**
* tests/Recursion.test.js bounded self-recursion (transitive closure).
*
* An evidence whose config contains a chain step referencing ITSELF is
* unrolled at compile time into a bounded transitive closure: a union of
* paths base, hop+base, hop²+base, where `hop` is the recursive chain's
* steps before the self-reference and the depth N comes from the pattern's
* `limit N` (or the compiler's maxRecursionDepth default). The base (the
* evidence's non-recursive statements) is verified as a condition step at each
* path's terminal node.
*
* A pure recursion (no base case) cannot grant and is a compile-time error.
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { Arbiter } from '@arbiter/core';
import { DSLCompiler } from '../src/DSLCompiler.js';
const BASE = `
definition Employee { id: string }
definition Doc { id: string }
fact can_access(user: Employee, doc: Doc)
fact reports_to(user: Employee, manager: Employee)
`;
const RECURSIVE = `
evidence can_access_via(user: Employee, doc: Doc) {
can_access(user, doc)
reports_to(user, *m) { can_access_via(m, doc) } limit 3
}
`;
function compile(dsl, name = 'rec') {
const arb = new Arbiter();
const result = new DSLCompiler(arb).compile(dsl, name);
return { arb, result };
}
describe('Bounded self-recursion', () => {
it('unrolls into a union of base + bounded hop chains', () => {
const { arb, result } = compile(BASE + RECURSIVE);
assert.ok(result.success, JSON.stringify(result.errors));
const cfg = arb.relationConfigs.get('can_access_via');
assert.equal(cfg.type, 'logical');
assert.ok(cfg.union, 'recursion should compile to a union of paths');
// base + 3 hops (limit 3)
assert.equal(cfg.union.rules.length, 4);
});
it('grants through the base case and through multi-hop chains', () => {
const { arb, result } = compile(BASE + RECURSIVE);
assert.ok(result.success);
arb.addNode('u:1', 'Employee'); arb.addNode('m:1', 'Employee'); arb.addNode('m2:1', 'Employee'); arb.addNode('doc:9', 'Doc');
// base
arb.addRelation('u:1', 'can_access', 'doc:9', { possibility: 1.0 });
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 1.0);
// 1-hop: u -> m -> doc
arb.removeRelation('u:1', 'can_access', 'doc:9');
arb.addRelation('u:1', 'reports_to', 'm:1', { possibility: 1.0 });
arb.addRelation('m:1', 'can_access', 'doc:9', { possibility: 0.7 });
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0.7);
// 2-hop: u -> m -> m2 -> doc
arb.addRelation('m:1', 'reports_to', 'm2:1', { possibility: 1.0 });
arb.addRelation('m2:1', 'can_access', 'doc:9', { possibility: 0.5 });
// union takes the best path: max(0.7, 0.5) = 0.7
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0.7);
// 2-hop alone (remove the 1-hop can_access)
arb.removeRelation('m:1', 'can_access', 'doc:9');
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0.5);
});
it('enforces the recursion depth limit', () => {
const { arb, result } = compile(`
${BASE}
evidence can_access_via(user: Employee, doc: Doc) {
can_access(user, doc)
reports_to(user, *m) { can_access_via(m, doc) } limit 2
}
`);
assert.ok(result.success);
arb.addNode('u:1', 'Employee'); arb.addNode('m:1', 'Employee'); arb.addNode('m2:1', 'Employee'); arb.addNode('m3:1', 'Employee'); arb.addNode('doc:9', 'Doc');
arb.addRelation('u:1', 'reports_to', 'm:1', { possibility: 1.0 });
arb.addRelation('m:1', 'reports_to', 'm2:1', { possibility: 1.0 });
arb.addRelation('m2:1', 'reports_to', 'm3:1', { possibility: 1.0 });
arb.addRelation('m2:1', 'can_access', 'doc:9', { possibility: 0.5 }); // 2 hops
arb.addRelation('m3:1', 'can_access', 'doc:9', { possibility: 0.9 }); // 3 hops
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0.5);
arb.removeRelation('m2:1', 'can_access', 'doc:9');
// only the 3-hop path remains — beyond the limit -> denied
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0);
});
it('uses the compiler maxRecursionDepth default when no limit is given', () => {
const dsl = `
${BASE}
evidence can_access_via(user: Employee, doc: Doc) {
can_access(user, doc)
reports_to(user, *m) { can_access_via(m, doc) }
}
`;
const { arb, result } = compile(dsl);
assert.ok(result.success, JSON.stringify(result.errors));
// default depth 3 -> base + 3 hops
assert.equal(arb.relationConfigs.get('can_access_via').union.rules.length, 4);
// a deeper path (4 hops) is not granted
arb.addNode('u:1', 'Employee'); arb.addNode('m:1', 'Employee'); arb.addNode('m2:1', 'Employee'); arb.addNode('m3:1', 'Employee'); arb.addNode('m4:1', 'Employee'); arb.addNode('doc:9', 'Doc');
arb.addRelation('u:1', 'reports_to', 'm:1', { possibility: 1.0 });
arb.addRelation('m:1', 'reports_to', 'm2:1', { possibility: 1.0 });
arb.addRelation('m2:1', 'reports_to', 'm3:1', { possibility: 1.0 });
arb.addRelation('m3:1', 'reports_to', 'm4:1', { possibility: 1.0 });
arb.addRelation('m4:1', 'can_access', 'doc:9', { possibility: 1.0 });
assert.equal(arb.check('u:1', 'can_access_via', 'doc:9').possibility, 0, '4-hop path exceeds default depth');
});
it('rejects a pure recursion with no base case', () => {
const { result } = compile(`
${BASE}
evidence can_access_via(user: Employee, doc: Doc) {
reports_to(user, *m) { can_access_via(m, doc) } limit 3
}
`);
assert.equal(result.success, false);
assert.ok(result.errors.some(e => /no base case/.test(e)), JSON.stringify(result.errors));
});
it('keeps mutual (non-self) cycles a compile error', () => {
const { result } = compile(`
${BASE}
fact peer(user: Employee, other: Employee)
evidence a(user: Employee, doc: Doc) { peer(user, *p) { b(p, doc) } }
evidence b(user: Employee, doc: Doc) { peer(user, *p) { a(p, doc) } }
`);
assert.equal(result.success, false);
assert.ok(result.errors.some(e => /[Cc]yclic/.test(e)), JSON.stringify(result.errors));
});
});
+47 -5
View File
@@ -33,7 +33,11 @@ const FACTS = `
fact owner(group: Group, doc: Doc)
fact granted(user: Employee, doc: Doc)
fact group_perm(group: Group, doc: Doc)
fact group_banned(group: Group)
fact banned(user: Employee)
fact peer(user: Employee, other: Employee)
fact trusted(other: Employee)
fact doc_read(user: Employee, doc: Doc)
fact mfa(user: Employee)
`;
@@ -128,6 +132,33 @@ function buildProgram(kind, ps) {
oracle = Math.min(pm, pv);
break;
}
case 'chain_condition_step': {
// gated (a defeasible evidence) as the FINAL chain step → a condition
// step: the engine verifies gated at (intermediate, object). The oracle
// is the chain's min combined with the condition's base*(1-defeat).
const [pm, pv, pb] = ps;
evidence = `evidence gated(group: Group, doc: Doc) { WHEN group_perm(group, doc) UNLESS group_banned(group) }
evidence can_via(user: Employee, doc: Doc) { member_of(user, *g) { gated(g, doc) } }`;
edges.push({ src: 'u:1', relation: 'member_of', dst: 'g:1', possibility: pm });
edges.push({ src: 'g:1', relation: 'group_perm', dst: 'doc:9', possibility: pv });
edges.push({ src: 'g:1', relation: 'group_banned', dst: 'g:1', possibility: pb });
oracle = Math.min(pm, pv * (1 - pb));
break;
}
case 'chain_intermediate_condition': {
// peer_trusted (a defeasible evidence) as an INTERMEDIATE chain step:
// the engine expands it from the source (peer edges filtered by the
// trusted defeater) then continues to can_read. Oracle = min of the
// surviving peer leg and the read leg.
const [pp, pt, pr] = ps;
evidence = `evidence peer_trusted(user: Employee, other: Employee) { WHEN peer(user, other) UNLESS trusted(other) }
evidence can_via(user: Employee, doc: Doc) { peer_trusted(user, *p) { doc_read(p, doc) } }`;
edges.push({ src: 'u:1', relation: 'peer', dst: 'p:1', possibility: pp });
edges.push({ src: 'p:1', relation: 'trusted', dst: 'p:1', possibility: pt });
edges.push({ src: 'p:1', relation: 'doc_read', dst: 'doc:9', possibility: pr });
oracle = Math.min(pp * (1 - pt), pr);
break;
}
default:
throw new Error(`unknown construct: ${kind}`);
}
@@ -148,6 +179,10 @@ function runCheck({ kind, ps }) {
arbiter.addNode('u:1', 'Employee');
arbiter.addNode('g:1', 'Group');
arbiter.addNode('doc:9', 'Doc');
for (const e of edges) {
arbiter.addNode(e.src, e.dst === 'doc:9' ? 'Doc' : 'Employee');
arbiter.addNode(e.dst, e.dst === 'doc:9' ? 'Doc' : 'Employee');
}
const compiler = new DSLCompiler(arbiter);
const compiled = compiler.compile(dsl, 'oracle');
if (!compiled.success) {
@@ -163,7 +198,8 @@ function runCheck({ kind, ps }) {
}
const CONSTRUCTS = ['direct', 'chain', 'tuple_to_userset', 'fusion_min', 'fusion_max',
'when_unless', 'never_always', 'requires_when', 'composition', 'chain_step_composition'];
'when_unless', 'never_always', 'requires_when', 'composition', 'chain_step_composition',
'chain_condition_step', 'chain_intermediate_condition'];
describe('DSL generative oracle parity (rigor)', () => {
it('generated legal DSL compiles and every check matches the oracle', async () => {
@@ -174,7 +210,7 @@ describe('DSL generative oracle parity (rigor)', () => {
kind: rigor.gen.oneOf(CONSTRUCTS),
// exactly two edge possibilities (direct uses only the first);
// a shorter array would leave pB undefined and produce a NaN oracle
ps: rigor.gen.tuple(rigor.gen.oneOf(P), rigor.gen.oneOf(P))
ps: rigor.gen.tuple(rigor.gen.oneOf(P), rigor.gen.oneOf(P), rigor.gen.oneOf(P))
})
))
],
@@ -192,18 +228,23 @@ describe('DSL generative oracle parity (rigor)', () => {
});
it('exhaustive deterministic sweep: every construct x every possibility value', () => {
// Anti-vacuity complement to the campaign: sweep the full P × P grid per
// construct without any RNG, so a construct the campaign skipped would
// Anti-vacuity complement to the campaign: sweep the full P × P × P grid
// per construct without any RNG, so a construct the campaign skipped would
// still be caught here.
for (const kind of CONSTRUCTS) {
for (const a of P) {
for (const b of P) {
const ps = kind === 'direct' ? [a] : [a, b];
for (const c of P) {
const ps = kind === 'direct' ? [a] : [a, b, c];
const { dsl, edges, oracle, relation } = buildProgram(kind, ps);
const arbiter = new Arbiter();
arbiter.addNode('u:1', 'Employee');
arbiter.addNode('g:1', 'Group');
arbiter.addNode('doc:9', 'Doc');
for (const e of edges) {
arbiter.addNode(e.src, e.dst === 'doc:9' ? 'Doc' : 'Employee');
arbiter.addNode(e.dst, e.dst === 'doc:9' ? 'Doc' : 'Employee');
}
const compiled = new DSLCompiler(arbiter).compile(dsl, 'sweep');
assert.ok(compiled.success, `${kind} compile failed: ${(compiled.errors || []).join('; ')}`);
for (const e of edges) arbiter.addRelation(e.src, e.relation, e.dst, { possibility: e.possibility });
@@ -215,5 +256,6 @@ describe('DSL generative oracle parity (rigor)', () => {
}
}
}
}
});
});
@@ -96,14 +96,6 @@ const MUTATIONS = {
'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)')
}
};
@@ -0,0 +1,338 @@
/**
* tests/rigor/dsl-value-graph-robustness.test.js js-rigor invariants for the
* DSLValueGraph wrapper's robustness: attach() semantics, resolver failure modes,
* stored-value lifecycle (overwrite / invalidation isolation / TTL), binding
* edge cases, strict-mode behavior, and concurrent retrieval.
*/
import { describe, it } from 'node:test';
import { rigor, reducers } from '@rigor/core';
import { Arbiter } from '@arbiter/core';
import { ValueGraph } from '@arbiter/value-graph';
import { DSLRuntime, DSLValueGraph } from '../../src/index.js';
const DSL = `
definition Tenant { id: string }
measure budget(tenant: Tenant, feature: string) { } PROVIDES number
measure label(user: string) { } PROVIDES string
`;
function makeDvg() {
const rt = new DSLRuntime(new Arbiter()).compile(DSL, 'vg-robust');
return new DSLValueGraph(rt);
}
async function expectPass(name, actions, checks, config = {}) {
const report = await rigor.campaign(actions, rigor.crucible(checks))
.run({ seed: `dsl-vg-robust-${name}`, effort: 100, artifacts: { dir: '', persist: 'never' }, ...config });
if (report.status !== 'passed') {
const detail = (report.failures || []).slice(0, 5)
.map((f) => JSON.stringify({ action: f.actionName || f.action, inv: f.name, args: f.args, msg: f.message }));
throw new Error(`campaign '${name}' failed.\n${detail.join('\n')}`);
}
return report;
}
describe('DSLValueGraph robustness (rigor)', () => {
it('attach() is idempotent and a manual registerMeasure overrides it', async () => {
const actions = [
rigor.fn('attach_idempotent', (value, cb) => {
const rt = new DSLRuntime(new Arbiter()).compile(DSL, 'r');
const dvg = new DSLValueGraph(rt);
dvg.attach();
dvg.attach(); // idempotent
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, value);
rt.measure('budget', { __subject: 't', tenant: 't', feature: 'x' }).then(
(r) => cb(null, r.value), (e) => cb(e)
);
}, rigor.args(rigor.gen.int(0, 100), rigor.handler(reducers.first()))),
rigor.fn('attach_override', (cb) => {
const rt = new DSLRuntime(new Arbiter()).compile(DSL, 'r');
const dvg = new DSLValueGraph(rt);
dvg.attach();
rt.registerMeasure('budget', async () => ({ value: 12345, unit: 'manual' }));
rt.measure('budget', { __subject: 't', tenant: 't', feature: 'x' }).then(
(r) => cb(null, r.value), (e) => cb(e)
);
}, rigor.args(rigor.handler(reducers.first()))),
];
const checks = [
rigor.after('attach_idempotent', (ctx) => ctx.error == null && ctx.actual === ctx.args[0]),
rigor.after('attach_override', (ctx) => ctx.error == null && ctx.actual === 12345),
];
await expectPass('attach', actions, checks);
});
it('resolver failure modes: sync-return, error propagation, wrong-typed result', async () => {
const actions = [
rigor.fn('resolver_sync', (value, cb) => {
const dvg = makeDvg();
dvg.resolve('budget', (s, p) => value * 2); // sync return
dvg.measure('budget', { __subject: 't', tenant: 't', feature: 'x' }).then(
(r) => cb(null, r.value), (e) => cb(e)
);
}, rigor.args(rigor.gen.int(0, 50), rigor.handler(reducers.first()))),
rigor.fn('resolver_error', (cb) => {
const dvg = makeDvg();
dvg.resolve('budget', (s, p, ctx, done) => { done(new Error('provider down')); });
dvg.measure('budget', { __subject: 't', tenant: 't', feature: 'x' }).then(
(r) => cb(null, { ok: true, v: r.value }),
(e) => cb(null, { ok: false, msg: e.message })
);
}, rigor.args(rigor.handler(reducers.first()))),
rigor.fn('resolver_wrong_type', (cb) => {
const dvg = makeDvg();
dvg.resolve('budget', (s, p, ctx, done) => { done(null, 'not-a-number'); });
dvg.measure('budget', { __subject: 't', tenant: 't', feature: 'x' }).then(
(r) => cb(null, { ok: true, v: r.value }),
(e) => cb(null, { ok: false, msg: e.message })
);
}, rigor.args(rigor.handler(reducers.first()))),
];
const checks = [
rigor.after('resolver_sync', (ctx) => ctx.error == null && ctx.actual === ctx.args[0] * 2),
rigor.after('resolver_error', (ctx) => ctx.actual.ok === false && /provider down/.test(ctx.actual.msg)),
rigor.after('resolver_wrong_type', (ctx) => ctx.actual.ok === false && /must match declared type 'number'/.test(ctx.actual.msg)),
];
await expectPass('resolvers', actions, checks);
});
it('stored-value lifecycle: overwrite wins, cross-measure invalidation is isolated, TTL expires', async () => {
const actions = [
rigor.fn('overwrite', (a, b) => {
const dvg = makeDvg();
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, a);
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, b); // last-write-wins
return dvg.getValue('budget', { __subject: 't', tenant: 't', feature: 'x' }).value;
}, rigor.args(rigor.gen.int(0, 100), rigor.gen.int(0, 100))),
rigor.fn('cross_measure_invalidate', (a, b) => {
const dvg = makeDvg();
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, a);
dvg.setValue('label', { __subject: 't', user: 'u' }, String(b));
dvg.vg.invalidate('t', 'budget', { tenant: 't', feature: 'x' });
const budget = dvg.getValue('budget', { __subject: 't', tenant: 't', feature: 'x' });
const label = dvg.getValue('label', { __subject: 't', user: 'u' });
return { budget: budget === null ? 'null' : budget.value, label: label.value };
}, rigor.args(rigor.gen.int(0, 100), rigor.gen.int(0, 100))),
rigor.fn('ttl_expiry', (value, cb) => {
let t = 0;
const rt = new DSLRuntime(new Arbiter()).compile(DSL, 'r');
const dvg = new DSLValueGraph(rt, {
valueGraph: new ValueGraph({ clock: () => t, defaultTTL: 100 })
});
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, value);
const before = dvg.getValue('budget', { __subject: 't', tenant: 't', feature: 'x' }).value;
t = 200;
const after = dvg.getValue('budget', { __subject: 't', tenant: 't', feature: 'x' });
cb(null, { before, after: after === null ? 'null' : after.value });
}, rigor.args(rigor.gen.int(0, 100), rigor.handler(reducers.first()))),
];
const checks = [
rigor.after('overwrite', (ctx) => ctx.actual === ctx.args[1]),
rigor.after('cross_measure_invalidate', (ctx) => ctx.actual.budget === 'null' && ctx.actual.label === String(ctx.args[1])),
rigor.after('ttl_expiry', (ctx) => ctx.actual.before === ctx.args[0] && ctx.actual.after === 'null'),
];
await expectPass('lifecycle', actions, checks);
});
it('binding edge cases: array params, extra keys preserved, positional arity, unit/source', async () => {
const actions = [
rigor.fn('array_param', (arr, cb) => {
const rt = new DSLRuntime(new Arbiter()).compile(`measure tags(user: string, xs: array) { } PROVIDES number`, 'r');
const dvg = new DSLValueGraph(rt);
dvg.setValue('tags', { __subject: 't', user: 'u', xs: arr }, 7);
const e = dvg.getValue('tags', { __subject: 't', user: 'u', xs: arr });
cb(null, e ? e.value : 'MISSING');
}, rigor.args(rigor.gen.array(rigor.gen.int(0, 9), 0, 4), rigor.handler(reducers.first()))),
rigor.fn('extra_keys', (v) => {
const dvg = makeDvg();
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x', extra: 'zzz' }, v);
return dvg.getValue('budget', { __subject: 't', tenant: 't', feature: 'x', extra: 'zzz' }).value;
}, rigor.args(rigor.gen.int(0, 100))),
rigor.fn('positional_arity', (v) => {
const dvg = makeDvg();
dvg.setValue('budget', ['t', 'x'], v);
return dvg.getValue('budget', ['t', 'x']).value;
}, rigor.args(rigor.gen.int(0, 100))),
rigor.fn('unit_preserved', (v) => {
const dvg = makeDvg();
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, v, { unit: 'tokens', source: 'ledger' });
const e = dvg.getValue('budget', { __subject: 't', tenant: 't', feature: 'x' });
return { value: e.value, unit: e.unit, source: e.source };
}, rigor.args(rigor.gen.int(0, 100))),
];
const checks = [
rigor.after('array_param', (ctx) => ctx.error == null && ctx.actual === 7),
rigor.after('extra_keys', (ctx) => ctx.actual === ctx.args[0]),
rigor.after('positional_arity', (ctx) => ctx.actual === ctx.args[0]),
rigor.after('unit_preserved', (ctx) => ctx.actual.value === ctx.args[0] && ctx.actual.unit === 'tokens' && ctx.actual.source === 'ledger'),
];
await expectPass('bindings', actions, checks);
});
it('strict:false degrades gracefully for unknown measures; strict mode throws', async () => {
const actions = [
rigor.fn('strict_false', (cb) => {
const rt = new DSLRuntime(new Arbiter()).compile(DSL, 'r');
const dvg = new DSLValueGraph(rt, { strict: false });
dvg.setValue('nope', {}, 1); // no-op
dvg.resolve('nope', () => 1); // no-op
const g = dvg.getValue('nope', {}); // null
dvg.measure('nope', {}).then(
(r) => cb(null, { get: g, measure: r.value }),
() => cb(null, { get: g, measure: 'rejected' })
);
}, rigor.args(rigor.handler(reducers.first()))),
rigor.fn('no_value_null', () => {
const dvg = makeDvg();
return dvg.getValue('budget', { __subject: 't', tenant: 't', feature: 'x' }) === null ? 'null' : 'value';
}, rigor.args()),
];
const checks = [
rigor.after('strict_false', (ctx) => ctx.actual.get === null && ctx.actual.measure === null),
rigor.after('no_value_null', (ctx) => ctx.actual === 'null'),
];
await expectPass('strict', actions, checks);
});
it('concurrent measure retrievals all resolve to the same stored value', async () => {
const actions = [
rigor.fn('concurrent_measure', (value, cb) => {
const dvg = makeDvg();
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, value);
const N = 5;
const calls = [];
for (let i = 0; i < N; i++) {
calls.push(dvg.measure('budget', { __subject: 't', tenant: 't', feature: 'x' }).then((r) => r.value));
}
Promise.all(calls).then((values) => cb(null, values), (e) => cb(e));
}, rigor.args(rigor.gen.int(0, 100), rigor.handler(reducers.first()))),
];
const checks = [
rigor.after('concurrent_measure', (ctx) =>
ctx.error == null && Array.isArray(ctx.actual) && ctx.actual.length === 5 && ctx.actual.every((v) => v === ctx.args[0])),
];
await expectPass('concurrent', actions, checks);
});
it('stored values and resolvers coexist per subject (stored wins on its own subject)', async () => {
const actions = [
rigor.fn('subject_resolver_mix', (a, b, cb) => {
const dvg = makeDvg();
dvg.setValue('budget', { __subject: 'A', tenant: 'A', feature: 'x' }, a);
dvg.resolve('budget', (s) => b);
dvg.measure('budget', { __subject: 'A', tenant: 'A', feature: 'x' }).then(
(r1) => dvg.measure('budget', { __subject: 'B', tenant: 'B', feature: 'x' }).then(
(r2) => cb(null, { a: r1.value, b: r2.value }),
(e) => cb(e)
),
(e) => cb(e)
);
}, rigor.args(rigor.gen.int(0, 100), rigor.gen.int(0, 100), rigor.handler(reducers.first()))),
];
const checks = [
rigor.after('subject_resolver_mix', (ctx) =>
ctx.error == null && ctx.actual.a === ctx.args[0] && ctx.actual.b === ctx.args[1]),
];
await expectPass('subject-resolver-mix', actions, checks);
});
it('final confirmation: positional arity enforced, zero-param measures, control keys stripped', async () => {
const actions = [
rigor.fn('arity_too_many', (v) => {
const dvg = makeDvg();
try { dvg.setValue('budget', ['t', 'x', 'extra'], v); return { ok: true }; }
catch (e) { return { ok: false, msg: e.message }; }
}, rigor.args(rigor.gen.int(0, 100))),
rigor.fn('arity_too_few', (v) => {
const dvg = makeDvg();
try { dvg.setValue('budget', ['t'], v); return { ok: true }; }
catch (e) { return { ok: false, msg: e.message }; }
}, rigor.args(rigor.gen.int(0, 100))),
rigor.fn('arity_exact', (v) => {
const dvg = makeDvg();
dvg.setValue('budget', ['t', 'x'], v);
return dvg.getValue('budget', ['t', 'x']).value;
}, rigor.args(rigor.gen.int(0, 100))),
rigor.fn('zero_param_measure', (v) => {
const rt = new DSLRuntime(new Arbiter()).compile(`measure heartbeat() { } PROVIDES number`, 'r');
const dvg = new DSLValueGraph(rt);
dvg.setValue('heartbeat', {}, v);
const e = dvg.getValue('heartbeat', {});
return e ? e.value : 'MISSING';
}, rigor.args(rigor.gen.int(0, 100))),
rigor.fn('actor_stripped', (v) => {
const dvg = makeDvg();
// __actor is a control key → stripped from the cache key, so differing
// actors hit the SAME stored entry.
dvg.setValue('budget', { __actor: 'actor:1', __subject: 't', tenant: 't', feature: 'x' }, v);
return dvg.getValue('budget', { __actor: 'actor:2', __subject: 't', tenant: 't', feature: 'x' }).value;
}, rigor.args(rigor.gen.int(0, 100))),
];
const checks = [
rigor.after('arity_too_many', (ctx) => ctx.actual.ok === false && /expects 2 positional argument\(s\), got 3/.test(ctx.actual.msg)),
rigor.after('arity_too_few', (ctx) => ctx.actual.ok === false && /expects 2 positional argument\(s\), got 1/.test(ctx.actual.msg)),
rigor.after('arity_exact', (ctx) => ctx.actual === ctx.args[0]),
rigor.after('zero_param_measure', (ctx) => ctx.actual === ctx.args[0]),
rigor.after('actor_stripped', (ctx) => ctx.actual === ctx.args[0]),
];
await expectPass('final-confirm', actions, checks);
});
it('hardening: retrieval paths, sync-throw resolvers, unregister, param-driven resolvers, NaN', async () => {
const actions = [
rigor.fn('get_sync_vs_measure_async', (value, cb) => {
const dvg = makeDvg();
dvg.resolve('budget', (s, p, ctx, done) => { setTimeout(() => done(null, value), 1); });
const syncPath = dvg.getValue('budget', { __subject: 't', tenant: 't', feature: 'x' });
dvg.measure('budget', { __subject: 't', tenant: 't', feature: 'x' }).then(
(r) => cb(null, { sync: syncPath === null ? 'null' : syncPath.value, async: r.value }),
(e) => cb(e)
);
}, rigor.args(rigor.gen.int(0, 100), rigor.handler(reducers.first()))),
rigor.fn('resolver_throws_sync', (cb) => {
const dvg = makeDvg();
dvg.resolve('budget', () => { throw new Error('boom'); });
dvg.measure('budget', { __subject: 't', tenant: 't', feature: 'x' }).then(
(r) => cb(null, { ok: true, v: r.value }),
(e) => cb(null, { ok: false, msg: e.message })
);
}, rigor.args(rigor.handler(reducers.first()))),
rigor.fn('unregister_after_attach', (cb) => {
const rt = new DSLRuntime(new Arbiter()).compile(DSL, 'r');
const dvg = new DSLValueGraph(rt);
dvg.attach();
rt.unregisterMeasure('budget');
rt.measure('budget', { __subject: 't', tenant: 't', feature: 'x' }).then(
(r) => cb(null, { ok: true, v: r.value }),
(e) => cb(null, { ok: false, msg: e.message })
);
}, rigor.args(rigor.handler(reducers.first()))),
rigor.fn('resolver_from_params', (x, y, cb) => {
const dvg = makeDvg();
dvg.resolve('budget', (s, p, ctx, done) => done(null, p.feature === 'a' ? x : y));
dvg.measure('budget', { __subject: 't', tenant: 't', feature: 'a' }).then(
(r1) => dvg.measure('budget', { __subject: 't', tenant: 't', feature: 'b' }).then(
(r2) => cb(null, { a: r1.value, b: r2.value }),
(e) => cb(e)
),
(e) => cb(e)
);
}, rigor.args(rigor.gen.int(0, 100), rigor.gen.int(0, 100), rigor.handler(reducers.first()))),
rigor.fn('nan_rejected', () => {
const dvg = makeDvg();
try { dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, Number.NaN); return { ok: true }; }
catch (e) { return { ok: false, msg: e.message }; }
}, rigor.args()),
];
const checks = [
rigor.after('get_sync_vs_measure_async', (ctx) =>
ctx.error == null && ctx.actual.sync === 'null' && ctx.actual.async === ctx.args[0]),
rigor.after('resolver_throws_sync', (ctx) => ctx.actual.ok === false && /boom/.test(ctx.actual.msg)),
rigor.after('unregister_after_attach', (ctx) => ctx.actual.ok === false && /no provider registered/.test(ctx.actual.msg)),
rigor.after('resolver_from_params', (ctx) =>
ctx.error == null && ctx.actual.a === ctx.args[0] && ctx.actual.b === ctx.args[1]),
rigor.after('nan_rejected', (ctx) => ctx.actual.ok === false && /must match declared type 'number'/.test(ctx.actual.msg)),
];
await expectPass('hardening', actions, checks);
});
});
+226
View File
@@ -0,0 +1,226 @@
/**
* tests/rigor/dsl-value-graph.test.js js-rigor deep tests for the
* DSLValueGraph integration (evidence DSL declares the value-graph's typing;
* measures retrieve through the graph; attributes are stored directly).
*
* Covers, as property campaigns:
* - setValue/getValue round-trips across every declared value type
* - type enforcement (wrong-typed writes always reject)
* - parameter-binding validation (wrong-typed params always reject)
* - subject scoping (different subjects never share entries)
* - attach() parity (runtime.measure === value-graph retrieval)
* - external resolvers compute, and a stored value wins over the resolver
* - invalidation clears a stored value (next retrieval null)
* - schema derivation from generated measure declarations
* - multi-measure independence
*/
import { describe, it } from 'node:test';
import { rigor, reducers } from '@rigor/core';
import { Arbiter } from '@arbiter/core';
import { DSLRuntime, DSLValueGraph } from '../../src/index.js';
const DSL = `
definition Tenant { id: string }
measure budget(tenant: Tenant, feature: string) { } PROVIDES number
measure label(user: string) { } PROVIDES string
measure active(user: string) { } PROVIDES boolean
measure tags(user: string) { } PROVIDES array
`;
function makeDvg() {
const rt = new DSLRuntime(new Arbiter()).compile(DSL, 'vg-rigor');
return new DSLValueGraph(rt);
}
async function expectPass(name, actions, checks, config = {}) {
const report = await rigor.campaign(actions, rigor.crucible(checks))
.run({ seed: `dsl-vg-${name}`, effort: 120, artifacts: { dir: '', persist: 'never' }, ...config });
if (report.status !== 'passed') {
const detail = (report.failures || []).slice(0, 5)
.map((f) => JSON.stringify({ action: f.actionName || f.action, inv: f.name, args: f.args, msg: f.message }));
throw new Error(`campaign '${name}' failed.\n${detail.join('\n')}`);
}
return report;
}
describe('DSLValueGraph integration (rigor)', () => {
it('setValue/getValue round-trips every declared value type', async () => {
const actions = [
rigor.fn('rt_number', (v) => {
const dvg = makeDvg();
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, v);
const e = dvg.getValue('budget', { __subject: 't', tenant: 't', feature: 'x' });
return e ? e.value : 'MISSING';
}, rigor.args(rigor.gen.int(-100000, 100000))),
rigor.fn('rt_string', (v) => {
const dvg = makeDvg();
dvg.setValue('label', { __subject: 't', user: 'u' }, v);
const e = dvg.getValue('label', { __subject: 't', user: 'u' });
return e ? e.value : 'MISSING';
}, rigor.args(rigor.gen.asciiString())),
rigor.fn('rt_bool', (v) => {
const dvg = makeDvg();
dvg.setValue('active', { __subject: 't', user: 'u' }, v);
const e = dvg.getValue('active', { __subject: 't', user: 'u' });
return e ? e.value : 'MISSING';
}, rigor.args(rigor.gen.boolean())),
rigor.fn('rt_array', (v) => {
const dvg = makeDvg();
dvg.setValue('tags', { __subject: 't', user: 'u' }, v);
const e = dvg.getValue('tags', { __subject: 't', user: 'u' });
return e ? e.value : null;
}, rigor.args(rigor.gen.array(rigor.gen.string(), 0, 5))),
];
const checks = [
rigor.after('rt_number', (ctx) => ctx.actual === ctx.args[0]),
rigor.after('rt_string', (ctx) => ctx.actual === ctx.args[0]),
rigor.after('rt_bool', (ctx) => ctx.actual === ctx.args[0]),
rigor.after('rt_array', (ctx) => JSON.stringify(ctx.actual) === JSON.stringify(ctx.args[0])),
];
await expectPass('roundtrip', actions, checks, { effort: 200 });
});
it('type enforcement: wrong-typed writes always reject, right-typed always pass', async () => {
const actions = [
rigor.fn('type_ok', (v) => {
const dvg = makeDvg();
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, v);
return dvg.getValue('budget', { __subject: 't', tenant: 't', feature: 'x' }).value;
}, rigor.args(rigor.gen.int(-100, 100))),
rigor.fn('type_reject', (v) => {
const dvg = makeDvg();
try { dvg.setValue('label', { user: 'u' }, v); return { ok: true }; }
catch (e) { return { ok: false, msg: e.message }; }
}, rigor.args(rigor.gen.oneOf([rigor.gen.int(0, 100), rigor.gen.boolean(), rigor.gen.array(rigor.gen.int(0, 9), 1, 3)]))),
rigor.fn('param_reject', (v) => {
const dvg = makeDvg();
try { dvg.setValue('budget', { tenant: 't', feature: v }, 1); return { ok: true }; }
catch (e) { return { ok: false, msg: e.message }; }
}, rigor.args(rigor.gen.oneOf([rigor.gen.constant(42), rigor.gen.boolean(), rigor.gen.array(rigor.gen.int(0, 9), 1, 2)]))),
];
const checks = [
rigor.after('type_ok', (ctx) => ctx.actual === ctx.args[0]),
rigor.after('type_reject', (ctx) => ctx.actual.ok === false && /must match declared type 'string'/.test(ctx.actual.msg)),
rigor.after('param_reject', (ctx) => ctx.actual.ok === false && /parameter 'feature'/.test(ctx.actual.msg)),
];
await expectPass('typecheck', actions, checks, { effort: 200 });
});
it('subjects never share entries', async () => {
const actions = [
rigor.fn('subject_isolation', (a, b) => {
const dvg = makeDvg();
dvg.setValue('budget', { __subject: 'A', tenant: 'A', feature: 'x' }, a);
dvg.setValue('budget', { __subject: 'B', tenant: 'B', feature: 'x' }, b);
const ea = dvg.getValue('budget', { __subject: 'A', tenant: 'A', feature: 'x' });
const eb = dvg.getValue('budget', { __subject: 'B', tenant: 'B', feature: 'x' });
return { a: ea ? ea.value : null, b: eb ? eb.value : null };
}, rigor.args(rigor.gen.int(-50, 50), rigor.gen.int(-50, 50))),
];
const checks = [
rigor.after('subject_isolation', (ctx) => ctx.actual.a === ctx.args[0] && ctx.actual.b === ctx.args[1]),
];
await expectPass('subjects', actions, checks, { effort: 120 });
});
it('attach() makes runtime.measure retrieve through the value-graph', async () => {
const actions = [
rigor.fn('attach_parity', (value, cb) => {
const rt = new DSLRuntime(new Arbiter()).compile(DSL, 'vg-rigor');
const dvg = new DSLValueGraph(rt);
dvg.attach();
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, value);
rt.measure('budget', { __subject: 't', tenant: 't', feature: 'x' }).then(
(r) => cb(null, r.value),
(e) => cb(e)
);
}, rigor.args(rigor.gen.int(0, 100), rigor.handler(reducers.first()))),
];
const checks = [
rigor.after('attach_parity', (ctx) => ctx.error == null && ctx.actual === ctx.args[0]),
];
await expectPass('attach', actions, checks, { effort: 120 });
});
it('external resolvers compute; a stored value wins over the resolver', async () => {
const actions = [
rigor.fn('resolver_compute', (value, cb) => {
const dvg = makeDvg();
dvg.resolve('budget', (s, p, ctx, done) => done(null, { value, unit: 'tokens', source: 'resolver' }));
dvg.measure('budget', { __subject: 't', tenant: 't', feature: 'x' }).then(
(r) => cb(null, { value: r.value, source: r.source }),
(e) => cb(e)
);
}, rigor.args(rigor.gen.int(0, 100), rigor.handler(reducers.first()))),
rigor.fn('stored_wins', (value, cb) => {
const dvg = makeDvg();
dvg.resolve('budget', (s, p, ctx, done) => done(null, 999));
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, value);
dvg.measure('budget', { __subject: 't', tenant: 't', feature: 'x' }).then(
(r) => cb(null, r.value),
(e) => cb(e)
);
}, rigor.args(rigor.gen.int(0, 100), rigor.handler(reducers.first()))),
];
const checks = [
rigor.after('resolver_compute', (ctx) => ctx.error == null && ctx.actual.value === ctx.args[0] && ctx.actual.source === 'resolver'),
rigor.after('stored_wins', (ctx) => ctx.error == null && ctx.actual === ctx.args[0]),
];
await expectPass('resolvers', actions, checks, { effort: 120 });
});
it('invalidation clears a stored value; the next retrieval is null', async () => {
const actions = [
rigor.fn('invalidate_clears', (value, cb) => {
const dvg = makeDvg();
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, value);
dvg.vg.invalidate('t', 'budget', { tenant: 't', feature: 'x' });
dvg.measure('budget', { __subject: 't', tenant: 't', feature: 'x' }).then(
(r) => cb(null, r.value),
(e) => cb(e)
);
}, rigor.args(rigor.gen.int(0, 100), rigor.handler(reducers.first()))),
];
const checks = [
rigor.after('invalidate_clears', (ctx) => ctx.error == null && ctx.actual === null),
];
await expectPass('invalidate', actions, checks, { effort: 120 });
});
it('schema derivation: every generated measure gets its declared returnType and params', async () => {
const actions = [
rigor.fn('schema_ok', (name, type) => {
const dsl = `definition T { id: string } measure ${name}(p: T) { } PROVIDES ${type}`;
const rt = new DSLRuntime(new Arbiter()).compile(dsl, 'gen');
const dvg = new DSLValueGraph(rt);
const spec = dvg.schema()[name];
return { returnType: spec && spec.returnType, params: spec ? spec.params.map((x) => x.name) : null };
}, rigor.args(
rigor.gen.oneOf(['balance', 'rate', 'quota', 'volume', 'meter']),
rigor.gen.oneOf(['number', 'string', 'boolean', 'array'])
)),
];
const checks = [
rigor.after('schema_ok', (ctx) => ctx.actual.returnType === ctx.args[1] && JSON.stringify(ctx.actual.params) === JSON.stringify(['p'])),
];
await expectPass('schema', actions, checks, { effort: 120 });
});
it('measures are independent (no cross-measure cache sharing)', async () => {
const actions = [
rigor.fn('multi_measure', (a, b) => {
const dvg = makeDvg();
dvg.setValue('budget', { __subject: 't', tenant: 't', feature: 'x' }, a);
dvg.setValue('label', { __subject: 't', user: 'u' }, String(b));
return {
budget: dvg.getValue('budget', { __subject: 't', tenant: 't', feature: 'x' }).value,
label: dvg.getValue('label', { __subject: 't', user: 'u' }).value
};
}, rigor.args(rigor.gen.int(0, 100), rigor.gen.int(0, 100))),
];
const checks = [
rigor.after('multi_measure', (ctx) => ctx.actual.budget === ctx.args[0] && ctx.actual.label === String(ctx.args[1])),
];
await expectPass('independence', actions, checks, { effort: 120 });
});
});