Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions tools/verify-decision/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,26 @@

Changes to `brainchain-verify`, the npm package built from this directory. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Dates are npm publish dates, in UTC.

## [0.12.0] - unreleased

### Added

- The weighted rule. A panel record under `weighted` carries `panel.weights`: one weight per member in panel order, Jev first, each from 0 to 1, summing to 1 to four decimals. `confidence-recomputed` takes the probability of paying as each member's weight times its own probability, added up and rounded to four decimals as `median` is, and holds the answer to 0.5, or to 90% when the panel decided without a member. A panel short of a member divides each answering weight by the sum of the answering weights, as the brain does, and pays only from 90%. Answering weights that sum to 0 give the rule no value, so `panel` fails a record that decides by it.
- `panel` fails a record that decides by `weighted` without weights, values `weighted` in `rules` without weights, or carries weights that are not one per member, lie outside 0 to 1 or do not sum to 1. Each failure names its reason.
- `evidence` rebuilds evidence version 2 with `panel.weights` beside the rule when the rule is `weighted`. Records under any other rule hash as before.
- `--json` carries `weights` in `panel` when the record has them.
- `shape` checks a grade or ruling on a brief that fences a JSON schema (a block marked `json schema`). The tool checks the record's result against the schema exactly as BrainChain does before any grader is asked. The outcome and the problems must be the ones in the request, the record's `shape` field must agree, and the question must show the graders the check in BrainChain's own wording. A result that does not match must be a reject, or a refund on a ruling, at 10,000 bps. Records decided under prompt version 2 or later owe the check. Older ones skip it.
- `--json` carries `shape` on a decision whose brief has a schema.
- `evidence` rebuilds evidence version 2 with the record's `shape`, which the brain hashes beside `checks`, so a copy served without the work cannot change it.

### Changed

- A rule the tool does not know now fails `panel` with `weighted` among the rules it lists.
- `confidence-recomputed` puts the probability of paying at 0 when the result does not match the brief's schema, as it does when the brief's checks failed.
- `checks` accepts a question that shows the graders the shape after the run of the checks.

0.11.0 and earlier do not know the weighted rule. On a weighted record they fail `panel`, naming `weighted` as no candidate rule, skip `confidence-recomputed` and fail `evidence`, so the verdict is `MISMATCH` until you upgrade. They also leave `shape` out of the evidence hash, so a grade or ruling on a brief that fences a JSON schema fails `evidence` there. Records under the other rules verify exactly as in 0.11.0.

## [0.11.0] - unreleased

### Added
Expand Down
20 changes: 13 additions & 7 deletions tools/verify-decision/README.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions tools/verify-decision/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion tools/verify-decision/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "brainchain-verify",
"version": "0.11.0",
"version": "0.12.0",
"description": "Check a BrainChain decision against the chain: the published record, its hashes, its confidence and the thresholds the contracts applied.",
"license": "MIT",
"author": "BrainChain",
Expand Down
1 change: 1 addition & 0 deletions tools/verify-decision/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ async function main(): Promise<void> {
...(r.outside ? { outside: true } : {}),
...(r.withheld ? { withheld: true } : {}),
...(r.run ? { run: r.run } : {}),
...(r.shape ? { shape: r.shape } : {}),
...(r.panel ? { panel: r.panel } : {}),
...(r.evidence ? { evidence: r.evidence } : {}),
...(r.receipt ? { receipt: r.receipt } : {}),
Expand Down
105 changes: 105 additions & 0 deletions tools/verify-decision/src/shape.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// The brain's schema check (schema-check.ts), so a result is checked here exactly as BrainChain checked it before
// any grader was asked. A brief carries the schema in a fenced block whose info string is "json schema".

export type Schema = Record<string, unknown>;

export interface Shape {
outcome: "passed" | "failed";
/** What does not match, each line naming the path. */
problems?: string[];
}

const MAX_SCHEMA = 8_000;
const MAX_PROBLEMS = 20;
const MAX_DEPTH = 8;
const TYPES = new Set(["object", "array", "string", "integer", "number", "boolean", "null"]);
const KEYWORDS = new Set(["type", "properties", "required", "additionalProperties", "items", "enum", "minimum", "maximum", "minLength", "maxLength", "description", "title"]);
const FENCE = /```json[^\S\n]+schema[^\S\n]*\n([\s\S]*?)```/i;
const RESULT_FENCE = /^```(?:json)?[^\S\n]*\n([\s\S]*?)\n?```$/i;

const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);

function unsupported(schema: unknown, path = "schema", depth = 0): string | undefined {
if (!isRecord(schema)) return `${path} must be an object`;
if (depth > MAX_DEPTH) return `${path} nests deeper than ${MAX_DEPTH} levels`;
for (const key of Object.keys(schema)) if (!KEYWORDS.has(key)) return `${path} uses "${key}"; BrainChain checks ${[...KEYWORDS].filter((k) => k !== "description" && k !== "title").join(", ")}`;
const { type, properties, required, additionalProperties, items, enum: allowed } = schema;
const types = Array.isArray(type) ? type : type === undefined ? [] : [type];
if (!types.every((t) => typeof t === "string" && TYPES.has(t))) return `${path}.type names a type outside ${[...TYPES].join(", ")}`;
if (properties !== undefined) {
if (!isRecord(properties)) return `${path}.properties must be an object`;
for (const [name, sub] of Object.entries(properties)) {
const problem = unsupported(sub, `${path}.properties.${name}`, depth + 1);
if (problem) return problem;
}
}
if (required !== undefined && !(Array.isArray(required) && required.every((r) => typeof r === "string"))) return `${path}.required must list property names`;
if (additionalProperties !== undefined && typeof additionalProperties !== "boolean") return `${path}.additionalProperties must be true or false`;
if (items !== undefined) return unsupported(items, `${path}.items`, depth + 1);
if (allowed !== undefined && !(Array.isArray(allowed) && allowed.length > 0)) return `${path}.enum must list at least one value`;
for (const bound of ["minimum", "maximum", "minLength", "maxLength"] as const) {
if (schema[bound] !== undefined && typeof schema[bound] !== "number") return `${path}.${bound} must be a number`;
}
return undefined;
}

/** The schema fenced in a brief; a string says why the fence holds none BrainChain checks, and BrainChain then checks nothing. */
export function schemaIn(brief: string): Schema | string | undefined {
const fenced = FENCE.exec(brief)?.[1];
if (fenced === undefined) return undefined;
if (fenced.length > MAX_SCHEMA) return `the json schema is over ${MAX_SCHEMA.toLocaleString("en-US")} characters`;
let schema: unknown;
try {
schema = JSON.parse(fenced);
} catch {
return "the json schema is not valid JSON";
}
return unsupported(schema) ?? (schema as Schema);
}

const typeOf = (value: unknown): string =>
value === null ? "null" : Array.isArray(value) ? "array" : typeof value === "number" && Number.isInteger(value) ? "integer" : typeof value;

function matches(value: unknown, schema: Schema, path: string, problems: string[]): void {
if (problems.length >= MAX_PROBLEMS) return;
const types = Array.isArray(schema.type) ? (schema.type as string[]) : schema.type === undefined ? [] : [schema.type as string];
const actual = typeOf(value);
if (types.length > 0 && !types.includes(actual) && !(actual === "integer" && types.includes("number"))) {
problems.push(`${path} is ${actual}, the schema asks for ${types.join(" or ")}`);
return;
}
if (Array.isArray(schema.enum) && !schema.enum.some((option) => JSON.stringify(option) === JSON.stringify(value))) problems.push(`${path} is not one of the allowed values`);
if (typeof value === "string") {
if (typeof schema.minLength === "number" && value.length < schema.minLength) problems.push(`${path} is shorter than ${schema.minLength} characters`);
if (typeof schema.maxLength === "number" && value.length > schema.maxLength) problems.push(`${path} is longer than ${schema.maxLength} characters`);
}
if (typeof value === "number") {
if (typeof schema.minimum === "number" && value < schema.minimum) problems.push(`${path} is below ${schema.minimum}`);
if (typeof schema.maximum === "number" && value > schema.maximum) problems.push(`${path} is above ${schema.maximum}`);
}
if (actual === "object") {
const object = value as Record<string, unknown>;
const properties = (schema.properties ?? {}) as Record<string, Schema>;
for (const name of (schema.required ?? []) as string[]) if (!Object.hasOwn(object, name)) problems.push(`${path}.${name} is missing`);
for (const [name, field] of Object.entries(object)) {
if (Object.hasOwn(properties, name)) matches(field, properties[name]!, `${path}.${name}`, problems);
else if (schema.additionalProperties === false) problems.push(`${path}.${name} is not in the schema`);
}
}
if (actual === "array" && isRecord(schema.items)) (value as unknown[]).forEach((item, i) => matches(item, schema.items as Schema, `${path}[${i}]`, problems));
}

/** The result checked against the schema: the result must be one JSON value, bare or in a single fenced block. */
export function checkShape(result: string, schema: Schema): Shape {
const text = result.trim();
const body = RESULT_FENCE.exec(text)?.[1] ?? text;
let value: unknown;
try {
value = JSON.parse(body);
} catch {
return { outcome: "failed", problems: ["the result is not one JSON value"] };
}
const problems: string[] = [];
matches(value, schema, "result", problems);
return problems.length === 0 ? { outcome: "passed" } : { outcome: "failed", problems: problems.slice(0, MAX_PROBLEMS) };
}
Loading
Loading