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
+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;