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.
This commit is contained in:
2026-08-04 17:51:13 -07:00
parent b145c979ab
commit 7898a7990a
14 changed files with 1421 additions and 87 deletions
+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';
+146 -1
View File
@@ -44,6 +44,7 @@ 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}) }
@@ -120,7 +121,10 @@ export class DSLRuntime {
params: r.params,
dependsOn: [...(this.dependsOn.get(name) || [])]
}));
return { types, facts, sources, evidence, providers: this.registeredFacts() };
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). */
@@ -171,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);
@@ -250,6 +267,66 @@ export class DSLRuntime {
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
// ---------------------------------------------------------------------------
@@ -595,6 +672,23 @@ export class DSLRuntime {
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;
}
// ---------------------------------------------------------------------------
// DSL-informed check
// ---------------------------------------------------------------------------
@@ -761,6 +855,57 @@ export class DSLRuntime {
};
}
// --- 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
+3 -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',
+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;