diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d5ae4f0..71a7a14 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,6 +36,9 @@ jobs: - name: Tests run: pnpm test + - name: Verify Assay documentation examples against the public release + run: node scripts/verify-assay-examples.mjs + - name: Build run: pnpm build diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 26ffc69..93972f8 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -94,6 +94,9 @@ jobs: - name: Tests run: pnpm test + - name: Verify Assay documentation examples against the public release + run: node scripts/verify-assay-examples.mjs + - name: Build selected Cloudflare environment env: TARGET: ${{ inputs.target }} diff --git a/README.md b/README.md index 4193db0..0daea3f 100644 --- a/README.md +++ b/README.md @@ -99,3 +99,13 @@ Fumadocs MDX uses `async: true`, so individual documents are compiled into page- ## Design system The shared tokens, fonts and base styles in `src/app.css` are synchronized from [the platform design system](https://github.com/0xbuffdev/platform/blob/16241087830ddd0c96ae7dd7ba81023cd8892365/packages/ui/src/styles/app.css). Keep the Fumadocs adapter, local source detection and documentation-specific rules when updating that snapshot. The documentation application does not import the platform's private workspace packages. + +## Assay documentation + +The Assay collection documents the public release [v0.0.1](https://github.com/0xbuffdev/assay/tree/v0.0.1). Use its package exports, contract types, tests and versioned guides as the technical source of truth. Do not document unreleased behavior as available. + +Keep the Assay sidebar compact: installation is the index, evaluation covers criteria and composition, observations covers execution and reviews, integrity covers protected references and disclosure, and two reference pages cover the API and contracts. Use headings within those pages for related topics; add a page only for a distinct reader need. Use sentence-case titles, direct language, explicit prerequisites and expected results. Keep code fragments distinct from complete examples. Use Mermaid for data flows and trust boundaries, not decorative diagrams. + +The editorial approach draws on [Vercel's writing guidelines](https://github.com/vercel-labs/writing-guidelines), [Cloudflare's style guide](https://developers.cloudflare.com/style-guide/), [Mintlify's developer documentation checklist](https://www.mintlify.com/library/developer-documentation-best-practices) and [Diátaxis](https://diataxis.fr/). Apply the Content repository's humanizer skill when editing prose. + +Run `pnpm test` for the documentation structure and internal-link checks. Run `node scripts/verify-assay-examples.mjs` to install the pinned public release in a temporary directory, execute the marked examples, and compare the documented API and limits with the installed package. This requires registry access and Node 24; it does not add Assay to the documentation application's dependency graph. CI and the release workflow run both checks. Update the example verification and all affected version references when adopting a new Assay release. diff --git a/content/docs/assay/api.mdx b/content/docs/assay/api.mdx new file mode 100644 index 0000000..17d9444 --- /dev/null +++ b/content/docs/assay/api.mdx @@ -0,0 +1,94 @@ +--- +title: "API reference" +description: "Look up the public functions, constants and return contracts exported by Assay." +--- + +Import from `@0xbuff/assay`. The package root is the supported import path. All functions except `collectObservations` are synchronous. Inputs to validation and integrity functions are accepted as unknown and checked at runtime. + +## Evaluation + +| Function | Return | Behavior | +| --- | --- | --- | +| `evaluate(definition, evidence, references?)` | EvaluationResponse | Verify inputs, compare criteria and compose required outcomes. | +| `inspectEvidenceCoverage(definition, evidence)` | ValidationResult of EvidenceCoverage | List missing and incomplete required criteria without evaluating them. | +| `projectPublicResult(definition, result)` | PublicProjectionResponse | Validate a full result and create its public projection. | + +`EvaluationResponse` is either a complete result or an invalid-input failure. Inspect `outcome` before accessing findings. See [outcomes](/docs/assay/contracts#outcomes-and-errors). + +## Definition integrity + +| Function | Return | Behavior | +| --- | --- | --- | +| `computeDefinitionDigest(draft)` | ValidationResult of string | Validate an unsigned draft and compute its digest. | +| `createAssessmentDefinition(draft)` | ValidationResult of AssessmentDefinition | Validate, derive the digest and seal the definition. | +| `verifyAssessmentDefinition(definition)` | ValidationResult of AssessmentDefinition | Verify structure and content digest. | + +## Evidence and reference integrity + +| Function | Return | Behavior | +| --- | --- | --- | +| `createEvidenceBundle(definition, draft)` | ValidationResult of EvidenceBundle | Verify the definition, bind observations and derive the evidence digest. | +| `verifyEvidenceBundle(definition, evidence)` | ValidationResult of EvidenceBundle | Verify evidence digest, coverage and definition lineage. | +| `createReferenceRecord(draft)` | ValidationResult of ReferenceRecord | Validate and seal a typed reference value. | +| `verifyReferenceBundle(definition, bundle)` | ValidationResult of ReferenceBundle | Verify every supplied record against its authorized definition. | + +## Structural parsing + +These functions check closed record shapes and resource limits. Structural parsing does not recompute the record's digest or authenticate its source. + +| Function | Successful value | +| --- | --- | +| `parseAssessmentDefinitionDraft(input)` | AssessmentDefinitionDraft | +| `parseAssessmentDefinition(input)` | AssessmentDefinition | +| `parseEvidenceBundle(input)` | EvidenceBundle | +| `parseObservationPortReport(input)` | ObservationPortReport | +| `parseEvaluationResult(input)` | EvaluationResult | +| `decodeSerializedRecord(input)` | Bounded immutable JSON object; duplicate keys rejected | + +The first five return ValidationResult of their corresponding type. The decoder returns SerializedRecordResult. + +## Observation collection + +`collectObservations(definition, evidence, port, options?)` returns a Promise of ObservationCollectionResult. Supply an optional signal in `options.signal`. The host implements the port. See [collection guide](/docs/assay/observations#observation-ports). + +## Constants + +| Export | Value or purpose | +| --- | --- | +| ASSAY_SCHEMA_VERSION | 4 | +| ASSAY_EVALUATOR_VERSION | v0.0.5 | +| CONTRACT_LIMITS | Frozen object containing the bounds listed in [limits](/docs/assay/contracts#resource-limits). | + +## Return wrappers + + +```ts +type ValidationResult = + | Readonly<{ ok: true; value: T }> + | Readonly<{ + ok: false; + domain: ValidationDomain; + diagnostics: readonly ValidationDiagnostic[]; + }>; +``` + +The serialized decoder uses the same success shape but its failure has diagnostics without a domain. Projection returns an opaque failure with `reasonCode` instead of diagnostics. Collection returns evidence and receipt directly on success and has distinct failure variants. + +Always check `ok` before reading `value` or `evidence`. + +## Public types + +The installed declarations are the exact type reference. The following groups cover the package's public type exports. + +| Area | Types | +| --- | --- | +| Common | Completeness, ExecutionFact, ExecutionTermination, JsonValue, NumericRange, SetItemType, SetScalar | +| Definition | AssessmentDefinition, AssessmentDefinitionDraft, CompositionChild, Criterion, CriterionBase, CriterionComposition, CriterionGroup, CriterionMode, DefinitionReference, Expected, PolicyVersion, ReferenceVisibility, TextNormalization | +| Evidence | EvidenceBundle, EvidenceBundleDraft, Observation, ObservationBase, ObservationFact, ObservationOrigin, ObservationPortProvenance, QualitativeObservation, QualitativeReviewer, ReviewCitation | +| References | ReferenceBundle, ReferenceRecord, ReferenceRecordDraft | +| Collection | ObservationAbortSignal, ObservationCollectionOptions, ObservationCollectionResult, ObservationPort, ObservationPortCriterion, ObservationPortKind, ObservationPortReceipt, ObservationPortReport, ObservationPortRequest | +| Evaluation | CriterionFinding, EvaluationFailure, EvaluationResponse, EvaluationResult, FindingOutcome, ReasonCode, TechnicalOutcome, WarningCode | +| Projection | PublicCriterionFinding, PublicProjectionResponse, PublicReason, PublicTechnicalOutcome, PublicTechnicalResult | +| Validation | DiagnosticCode, EvidenceCoverage, SerializedRecordResult, ValidationDiagnostic, ValidationDomain, ValidationResult | + +See the [public entry point](https://github.com/0xbuffdev/assay/blob/v0.0.1/src/index.ts) and [record reference](/docs/assay/contracts) for exact shapes. diff --git a/content/docs/assay/contracts.mdx b/content/docs/assay/contracts.mdx new file mode 100644 index 0000000..10e945f --- /dev/null +++ b/content/docs/assay/contracts.mdx @@ -0,0 +1,221 @@ +--- +title: "Contracts and errors" +description: "Record shapes, outcomes, diagnostics and resource limits." +--- + +All versioned public records use schema version 4. Record fields are closed: unknown fields, unsupported versions and invalid values are rejected. The TypeScript declarations in the released package define the exact unions. + +## AssessmentDefinition + +| Field | Type | Required | +| --- | --- | --- | +| schemaVersion | 4 | Yes | +| assessmentId | string | Yes | +| revision | string | Yes | +| revisionDigest | SHA-256 digest | Sealed record only | +| policyVersion | composed-required-v1 | Yes | +| criteria | Criterion array | Yes | +| composition | CriterionComposition | Yes | + +A draft omits revisionDigest. Criterion IDs are unique. Revision must identify a stable revision, not latest. + +### Criterion + +All criteria have `id: string`, `kind`, `mode: "required" | "advisory"`, `visibility: "public" | "restricted"` and `parameters`. Only supported objective kinds accept a top-level executionFact. + +| Kind | Parameter fields | +| --- | --- | +| exact_text | expected | +| normalized_text | expected, normalization | +| number_with_tolerance | expected, tolerance, optional unit | +| number_range | expected, optional unit | +| set_equivalence | expected, itemType, order, duplicates | +| boolean_equality | expected | +| json_equality | expected | +| observed_execution | assertions (array of id/referenceId pairs) | +| manual_evidence | review: required | +| qualitative_review | reviewPolicyId, reviewPolicyVersion | + +An expected value is either a literal with type and value, or a reference with type, referenceId and referenceDigest. Restricted objective criteria require the reference form. See [criteria](/docs/assay/evaluation#criteria) for value types and rules. + +Composition contains rootGroupId and groups. A group has id, operator (all or any), and children, each with kind (criterion or group) and id. See [composition](/docs/assay/evaluation#composition). + +## EvidenceBundle + +| Field | Type | Required | +| --- | --- | --- | +| schemaVersion | 4 | Yes | +| definition | DefinitionReference | Sealed record only | +| evidenceDigest | SHA-256 digest | Sealed record only | +| artifactDigest | SHA-256 digest | No | +| observations | Observation array | Yes | + +DefinitionReference contains assessmentId, revision and revisionDigest. The draft omits definition and evidenceDigest. + +### Observation + +Common fields are criterionId, evidenceRef, kind and completeness (complete or truncated). Criterion IDs must refer to declared criteria and observation/evidence reference IDs cannot repeat. + +| Kind | Additional fields | +| --- | --- | +| text | value: string | +| number | value: finite number; optional unit | +| set | items: scalar array; itemType | +| boolean | value: boolean | +| json | value: JSON | +| execution | runRef; assertions with assertionId and state (confirmed, refuted, unknown) | +| manual | artifactRefs: string array | +| qualitative_review | origin, reviewPolicyId, reviewPolicyVersion, reviewer, uncertainty, feedback, citations | + +Objective selected facts also carry executionFact and an origin with runRef and termination. Other observations may have an origin as permitted by the scope rules. See [evidence](/docs/assay/evaluation#evidence), [execution facts](/docs/assay/observations#execution-facts) and [qualitative reviews](/docs/assay/observations#qualitative-reviews). + +## ReferenceRecord and ReferenceBundle + +A reference draft has schemaVersion, referenceId, kind and value. Numeric/range records accept an optional unit; set records require itemType. A sealed reference adds referenceDigest. + +Reference kinds are text, number, range, set, boolean and json. The bundle has schemaVersion, definition and references, an array of sealed records. It does not have its own digest. + +## EvaluationResponse + +A complete result has schemaVersion, definition, evidenceDigest, optional artifactDigest, outcome, policyVersion, findings, evaluator and warnings. The evaluator has id and version. Each finding has criterionId, outcome, reasonCode, evidenceRefs, evaluatorId and evaluatorVersion. + +An invalid-input failure has outcome and diagnostics only. Do not assume that definition or findings exist on a failure. + +## Observation port + +Request fields: schemaVersion, definition, optional artifactDigest, criteria and limits.maxCapturedBytes. Each requested criterion includes criterionId, kind and applicable unit, itemType, assertionIds or executionFact. + +Report fields: schemaVersion, definition, optional artifactDigest, provenance, observations and termination where required. A receipt contains definition, evidenceDigest, evidenceRefs, optional termination/artifactDigest and provenance. See [report requirements](/docs/assay/observations#observation-ports). + +## PublicTechnicalResult + +| Field | Type | +| --- | --- | +| schemaVersion | 4 | +| outcome | pass, fail, inconclusive, evaluation_error or withheld | +| findings | Array of criterionId, outcome and reason | + +No evidence references or private warnings are included. See [projection](/docs/assay/integrity#public-projection). + +The [contract source](https://github.com/0xbuffdev/assay/tree/v0.0.1/src/contracts) defines the complete field unions and types. + +## Outcomes and errors + +### Evaluation outcomes + +| Outcome | Meaning | +| --- | --- | +| pass | The required composition is satisfied. | +| fail | The required composition has a decisive mismatch. | +| inconclusive | The required composition cannot be resolved. | +| evaluation_error | A comparison error determines the required composition. | +| invalid_definition | The definition is malformed or fails integrity checks. | +| invalid_reference | Supplied reference material is invalid or does not match. | +| invalid_evidence | Evidence is malformed, incompatible or fails integrity checks. | + +The first four return complete findings; the last three return only diagnostics. The required aggregate uses the precedence in [composition](/docs/assay/evaluation#composition). + +### Criterion findings + +| Finding outcome | Reason code | Meaning | +| --- | --- | --- | +| pass | MATCH | Observed value matches. | +| fail | VALUE_MISMATCH | Observed value does not match. | +| inconclusive | REFERENCE_UNAVAILABLE | Required reference value unavailable. | +| inconclusive | EVIDENCE_MISSING | Observation absent. | +| inconclusive | EVIDENCE_TRUNCATED | Observation incomplete. | +| inconclusive | ASSERTION_INCOMPLETE | Execution assertion incomplete. | +| inconclusive | EXECUTION_UNVERIFIED | Assertion claim cannot establish correctness. | +| inconclusive | EXECUTION_INCOMPLETE | Selected run did not complete. | +| inconclusive | ARTIFACT_MISSING | Required manual artifact absent. | +| inconclusive | REVIEW_REQUIRED | Manual or qualitative review needed. | +| error | COMPARATOR_ERROR | Comparison could not complete. | +| error | NUMERIC_OVERFLOW | Relative tolerance bound overflowed. | + +`ADVISORY_UNRESOLVED` is the sole warning code; unresolved advisory findings do not determine the binding outcome. + +### Public reasons + +| Public reason | Technical codes | +| --- | --- | +| match | MATCH | +| mismatch | VALUE_MISMATCH | +| missing_evidence | EVIDENCE_MISSING, ARTIFACT_MISSING | +| incomplete_evidence | EVIDENCE_TRUNCATED, ASSERTION_INCOMPLETE, EXECUTION_INCOMPLETE | +| review_needed | REVIEW_REQUIRED | +| unavailable | REFERENCE_UNAVAILABLE, EXECUTION_UNVERIFIED | +| evaluation_error | COMPARATOR_ERROR, NUMERIC_OVERFLOW | + +Public aggregate `withheld` means the definition contains restricted criteria. It does not indicate their outcomes. + +### Validation diagnostics + +Diagnostics contain a safe schema path and a closed code, without submitted values. ValidationResult domains are invalid_definition, invalid_evidence, invalid_reference and invalid_result. + +| Category | Codes | +| --- | --- | +| Serialized input | INVALID_JSON, DUPLICATE_KEY | +| Resource bounds | INPUT_TOO_DEEP, INPUT_TOO_LARGE, TOO_MANY_ITEMS, TOO_MANY_DIAGNOSTICS | +| Unsafe input | UNSUPPORTED_INPUT, UNSAFE_OBJECT, UNSAFE_KEY, UNSAFE_NUMBER | +| Shape | UNEXPECTED_FIELD, MISSING_FIELD, INVALID_TYPE, INVALID_VALUE, UNSUPPORTED_VERSION | +| Definition | DUPLICATE_ID, EMPTY_REQUIRED_CRITERIA, RESTRICTED_LITERAL | +| Integrity | DEFINITION_DIGEST_MISMATCH, REFERENCE_DIGEST_MISMATCH, EVIDENCE_DIGEST_MISMATCH | +| Correspondence | MISMATCHED_DEFINITION, MISMATCHED_ORIGIN, UNKNOWN_REFERENCE, MISMATCHED_REFERENCE, UNKNOWN_CRITERION, MISMATCHED_OBSERVATION | + +Collection errors use OBSERVATION_PORT_ERROR or OBSERVATION_CANCELLED. Projection failures return PUBLIC_PROJECTION_REJECTED without diagnostic details. + + + +## Resource limits + +The exported `CONTRACT_LIMITS` object defines these bounds. Limits apply to the complete validated record, including nested values. + +| Constant | Maximum | +| --- | ---: | +| maxDepth | 12 | +| maxNodes | 4,096 | +| maxInputBytes | 262,144 | +| maxSerializedBytes | 262,144 | +| maxCombinedSerializedBytes | 786,432 | +| maxStringLength | 16,384 | +| maxIdentifierLength | 96 | +| maxObjectKeys | 32 | +| maxArrayLength | 128 | +| maxCriteria | 64 | +| maxGroups | 64 | +| maxGroupChildren | 64 | +| maxGroupDepth | 8 | +| maxCompositionEdges | 127 | +| maxReviewFeedbackBytes | 4,096 | +| maxReviewFeedbackLength | 4,096 | +| maxReviewCitations | 8 | +| maxObservations | 128 | +| maxSetItems | 128 | +| maxEvidenceRefs | 32 | +| maxDiagnostics | 32 | +| maxCapturedBytes | 65,536 | + +Byte counts are UTF-8. Length limits on individual strings and review feedback are UTF-16 code units. The combined serialized budget applies to the complete multi-record input. A record that fits a particular field limit can still exceed a total budget. + +### Input restrictions + +The bounded snapshot rejects unknown keys, functions, accessors, unsupported prototypes, cycles, unsafe numbers and unsupported values. Numeric values must be finite; counts and offsets that require integers must be safe integers. Serialized input must be a JSON object and cannot contain duplicate keys. + +The decoder does not replace transport limits. Cap bytes before buffering and reject adversarial live Proxy objects. See [security and trust](/docs/assay/integrity#host-responsibilities). + +The [release constants](https://github.com/0xbuffdev/assay/blob/v0.0.1/src/contracts/common.ts) are the source for this table. + +## Troubleshooting + +| Symptom | Check | +| --- | --- | +| invalid_definition | Schema, revision, criterion IDs, composition and definition digest | +| invalid_evidence | Definition lineage, observation kinds, exact units, origin and evidence digest | +| invalid_reference | Reference ID, digest, kind, unit or item type and bundle lineage | +| inconclusive | Missing or truncated facts, unavailable references, interrupted runs or pending review | +| evaluation_error | Comparator errors or numeric overflow; inspect private finding reasons | +| Collection error | Adapter logs, request/report scope and cancellation signal | +| withheld | Expected when any criterion is restricted | +| PUBLIC_PROJECTION_REJECTED | Use the exact authorized definition and an unmodified complete evaluation result | + +Keep diagnostics private. Report reproducible problems with synthetic data to the [issue tracker](https://github.com/0xbuffdev/assay/issues). diff --git a/content/docs/assay/evaluation.mdx b/content/docs/assay/evaluation.mdx new file mode 100644 index 0000000..c7e83ad --- /dev/null +++ b/content/docs/assay/evaluation.mdx @@ -0,0 +1,188 @@ +--- +title: "Evaluation" +description: "Define criteria, seal observations and evaluate technical results." +--- + +An assessment definition contains criteria and a composition tree. An evidence bundle binds observed values to that definition. The evaluator returns a private technical result. It does not execute programs or award grades. + +```mermaid +flowchart LR + D[Definition] --> V[Verify inputs] + R[Optional references] --> V + E[Evidence] --> V + V --> C[Compare criteria] + C --> A[Compose findings] + A --> F[Technical result] +``` + +## Quick start + +After [installation](/docs/assay), save this example as `calibration.mjs`. It checks a caller-supplied measurement against an inclusive voltage range. + +```js +// assay-docs: runnable +import { + createAssessmentDefinition, + createEvidenceBundle, + evaluate, + projectPublicResult, +} from "@0xbuff/assay"; + +const definition = createAssessmentDefinition({ + schemaVersion: 4, + assessmentId: "calibration", + revision: "rev1", + policyVersion: "composed-required-v1", + criteria: [ + { + id: "voltage", + kind: "number_range", + mode: "required", + visibility: "public", + parameters: { + expected: { + type: "literal", + value: { min: 98, max: 102, minInclusive: true, maxInclusive: true }, + }, + unit: "mV", + }, + }, + ], + composition: { + rootGroupId: "root", + groups: [ + { + id: "root", + operator: "all", + children: [{ kind: "criterion", id: "voltage" }], + }, + ], + }, +}); +if (!definition.ok) throw new Error("Invalid definition"); + +const evidence = createEvidenceBundle(definition.value, { + schemaVersion: 4, + observations: [ + { + criterionId: "voltage", + evidenceRef: "measurement", + kind: "number", + completeness: "complete", + value: 101, + unit: "mV", + }, + ], +}); +if (!evidence.ok) throw new Error("Invalid evidence"); + +const result = evaluate(definition.value, evidence.value); +const view = projectPublicResult(definition.value, result); +if (!view.ok) throw new Error("Projection rejected"); +if (view.value.outcome !== "pass") throw new Error("Expected pass"); +console.log(view.value.outcome); +``` + +Run `node calibration.mjs`. The output is `pass`. Change the observation to 103 and remove the assertion requiring a pass to see `fail`. With no observations, the outcome is `inconclusive`. Changing the unit to V instead of mV rejects the evidence. + +## Criteria + +Every criterion declares an ID, kind, mode, visibility and parameters. Required criteria participate in composition; advisory findings do not. Public criteria may appear in public projections. Restricted objective criteria must use [protected references](/docs/assay/integrity#protected-references). + +| Kind | Observation | Parameters | +| --- | --- | --- | +| exact_text | text | expected | +| normalized_text | text | expected, normalization | +| number_with_tolerance | number | expected, tolerance, optional unit | +| number_range | number | expected, optional unit | +| set_equivalence | set | expected, itemType, order, duplicates | +| boolean_equality | boolean | expected | +| json_equality | json | expected | +| observed_execution | execution | assertions | +| manual_evidence | manual | review: required | +| qualitative_review | qualitative_review | reviewPolicyId, reviewPolicyVersion | + +The first seven kinds compare a literal or content-bound reference expectation. The remaining kinds produce unresolved findings. + +### Text + +Exact comparison uses UTF-16 code-unit equality. Normalized text applies the declared transformations to both values, in this order: line endings (`preserve` or `lf`), case (`sensitive` or `fold`), Unicode (`none`, `NFC` or `NFKC`), whitespace (`preserve` or `collapse`) and trim (`none` or `both`). Case folding uses JavaScript lowercase conversion, not full Unicode case folding. + +### Numbers + +Tolerance is inclusive: the absolute difference must not exceed the greater of the absolute tolerance and the relative tolerance multiplied by the magnitude of the expected value. + +```ts +parameters: { + expected: { type: "literal", value: 100 }, + tolerance: { absolute: 2, relative: 0.05 }, + unit: "mV", +} +``` + +A value of 105 passes; 106 fails. Both tolerances are finite and nonnegative. Numeric ranges specify finite min/max and both inclusion flags; equal endpoints require both flags to be true. Observations must use exactly the declared unit, including its absence. No string coercion or unit conversion occurs. A nonfinite relative bound produces `NUMERIC_OVERFLOW`. + +### Sets, booleans and JSON + +Sets use `itemType` of string, number or boolean. The observation field is `items`. With order ignored and duplicates ignored, compare membership; respecting duplicates compares counts. With order preserved, compare sequences, removing repeated items only when duplicates are ignored. + +Boolean equality is strict. JSON equality ignores object key order but preserves array order; strings and keys are exact. Negative zero equals zero. False and null are legitimate values. + +## Composition + +Every required criterion belongs exactly once to a nonempty tree under the policy `composed-required-v1`. Use an `all` group for conjunction and an `any` group for alternatives. + +```ts +composition: { + rootGroupId: "root", + groups: [ + { + id: "root", + operator: "all", + children: [ + { kind: "criterion", id: "status" }, + { kind: "group", id: "format" }, + ], + }, + { + id: "format", + operator: "any", + children: [ + { kind: "criterion", id: "json-result" }, + { kind: "criterion", id: "text-result" }, + ], + }, + ], +} +``` + +```mermaid +flowchart TD + A[all: root] --> S[status] + A --> B[any: format] + B --> J[json-result] + B --> T[text-result] +``` + +IDs are unique across groups and criteria. Groups must be reachable from the root without cycles or shared subtrees. Advisory criteria cannot appear in composition. + +| Operator | First condition | Otherwise | Otherwise | Otherwise | +| --- | --- | --- | --- | --- | +| all | Any fail: fail | Any error: evaluation_error | Any unresolved: inconclusive | All pass: pass | +| any | Any pass: pass | Any error: evaluation_error | Any unresolved: inconclusive | All fail: fail | + +Every criterion is validated and compared in authored order, even when an alternative is decisive. Invalid input rejects evaluation before comparison. + +## Evidence + +Use `createEvidenceBundle(definition, draft)` to seal observations. The draft has schemaVersion, observations and optional artifactDigest; Assay derives the definition lineage and evidence digest. + +Each observation has a criterion ID, unique evidence reference, kind and completeness. Omit unavailable facts and mark partial captures `truncated`. Do not fabricate placeholder values. `inspectEvidenceCoverage` lists missing and incomplete required leaves without determining the aggregate. + +An artifact-scoped bundle requires an origin on each observation. Artifact origins carry the exact bundle artifact digest and source reference. Independent origins carry no artifact digest. Unscoped observations may omit origin but cannot claim artifact scope. Selected execution facts additionally require run reference and termination. Correcting an observation requires sealing a new bundle. + +## Outcomes + +Complete results return pass, fail, inconclusive or evaluation_error, with one finding per criterion. Invalid inputs return only diagnostics, as invalid_definition, invalid_reference or invalid_evidence. Advisory warnings do not change the aggregate. + +Keep full results private and use [public projection](/docs/assay/integrity#public-projection) for authorized disclosure. See [contracts and errors](/docs/assay/contracts) for exact records, codes and resource limits. diff --git a/content/docs/assay/index.mdx b/content/docs/assay/index.mdx index e0deb46..e47dcc6 100644 --- a/content/docs/assay/index.mdx +++ b/content/docs/assay/index.mdx @@ -1,10 +1,51 @@ --- -title: Assay -description: Compare technical evidence against explicit, versioned criteria. +title: "Installation" +description: "Install Assay and start evaluating technical evidence." --- -Assay is a library for checking technical evidence against explicit criteria and producing reproducible findings. It runs offline and has no runtime dependencies. +Assay evaluates technical evidence against versioned criteria. It runs offline, has no runtime dependencies, and leaves execution, authorization and decisions to your application. -The host supplies evidence and authorizes the criteria. Assay does not execute submitted programs, authenticate observations, assign grades, or issue credentials. +## Requirements -For the source, license, and release information, see the [Assay repository](https://github.com/0xbuffdev/assay). +Node.js 24 or later and ECMAScript modules (ESM). Use an `.mjs` file or set `"type": "module"` in your package.json. TypeScript declarations are included. + +## Install + +```sh +npm install @0xbuff/assay@0.0.1 +``` + +```sh +pnpm add @0xbuff/assay@0.0.1 +``` + +```sh +yarn add @0xbuff/assay@0.0.1 +``` + +## Verify the installation + +Save this as `check.mjs`. + +```js +// assay-docs: runnable +import { ASSAY_SCHEMA_VERSION, ASSAY_EVALUATOR_VERSION } from "@0xbuff/assay"; + +console.log(ASSAY_SCHEMA_VERSION, ASSAY_EVALUATOR_VERSION); +``` + +Run `node check.mjs`. Expected output: + +```text +4 v0.0.5 +``` + +## Next steps + +- [Evaluation](/docs/assay/evaluation): define criteria, supply evidence and evaluate your first result. +- [Observations](/docs/assay/observations): integrate captured execution facts, optional adapters and reviews. +- [Integrity and security](/docs/assay/integrity): protect expectations and control disclosure. + +These pages describe release `0.0.1`, schema 4, evaluator semantics `v0.0.5` and policy `composed-required-v1`. Older schemas are unsupported. Pin the package and keep your lockfile for reproducibility. + +[Source](https://github.com/0xbuffdev/assay) · [Changelog](https://github.com/0xbuffdev/assay/blob/v0.0.1/CHANGELOG.md) · [Apache-2.0 license](https://github.com/0xbuffdev/assay/blob/v0.0.1/LICENSE) diff --git a/content/docs/assay/integrity.mdx b/content/docs/assay/integrity.mdx new file mode 100644 index 0000000..e9cfa33 --- /dev/null +++ b/content/docs/assay/integrity.mdx @@ -0,0 +1,144 @@ +--- +title: "Integrity and security" +description: "Verify record identity, use protected expectations and control disclosure." +--- + +Assay validates and hashes content. Your application authenticates publishers and producers, authorizes inputs, isolates execution and decides who can receive findings. A valid digest cannot establish identity or authority. + +## Content integrity + +Definitions, references and evidence use separate schema-4 canonical domains. + +| Record | Domain | Digest field | Create / verify | +| --- | --- | --- | --- | +| Definition | assay:definition:v4 | revisionDigest | createAssessmentDefinition / verifyAssessmentDefinition | +| Reference | assay:reference:v4 | referenceDigest | createReferenceRecord / verifyReferenceBundle | +| Evidence | assay:evidence:v4 | evidenceDigest | createEvidenceBundle / verifyEvidenceBundle | + +The creators validate unsigned drafts and derive digests; `computeDefinitionDigest` computes a definition digest separately. Canonical JSON sorts object keys by UTF-16 code-unit order, preserves array order and absent optional fields, omits only the record's own digest and serializes negative zero as zero. Hash the UTF-8 bytes of the domain, one LF and compact JSON (no trailing LF) with SHA-256. The digest is lowercase hexadecimal prefixed by `sha256:`. + +```mermaid +flowchart TD + R[Sealed reference] --> D[Sealed definition] + D --> E[Sealed evidence] + A[Optional artifact digest] --> E + E --> F[Technical result] + D --> F + F --> P[Public projection] +``` + +The definition binds authored criteria and composition. Evidence binds lineage, observations and origin claims. A changed definition requires a new revision; corrected evidence requires a new bundle. Older schemas are rejected. See the [canonical vectors](https://github.com/0xbuffdev/assay/blob/v0.0.1/docs/integrity.md). + +## Protected references + +Restricted objective criteria cannot embed literal expectations. Seal the reference separately and bind its ID and digest into the definition. + +```js +// assay-docs: runnable +import { + createReferenceRecord, + createAssessmentDefinition, + createEvidenceBundle, + evaluate, + projectPublicResult, +} from "@0xbuff/assay"; + +const reference = createReferenceRecord({ + schemaVersion: 4, + referenceId: "expected-output", + kind: "text", + value: "ok", +}); +if (!reference.ok) throw new Error("Invalid reference"); + +const created = createAssessmentDefinition({ + schemaVersion: 4, + assessmentId: "protected-check", + revision: "rev1", + policyVersion: "composed-required-v1", + criteria: [{ + id: "output", + kind: "exact_text", + mode: "required", + visibility: "restricted", + parameters: { + expected: { + type: "reference", + referenceId: reference.value.referenceId, + referenceDigest: reference.value.referenceDigest, + }, + }, + }], + composition: { + rootGroupId: "root", + groups: [{ + id: "root", + operator: "all", + children: [{ kind: "criterion", id: "output" }], + }], + }, +}); +if (!created.ok) throw new Error("Invalid definition"); + +const definition = created.value; +const references = { + schemaVersion: 4, + definition: { + assessmentId: definition.assessmentId, + revision: definition.revision, + revisionDigest: definition.revisionDigest, + }, + references: [reference.value], +}; + +const prepared = createEvidenceBundle(definition, { + schemaVersion: 4, + observations: [{ + criterionId: "output", + evidenceRef: "capture-1", + kind: "text", + completeness: "complete", + value: "ok", + }], +}); +if (!prepared.ok) throw new Error("Invalid evidence"); + +const result = evaluate(definition, prepared.value, references); +const projected = projectPublicResult(definition, result); +if (result.outcome !== "pass" || !projected.ok || + projected.value.outcome !== "withheld") { + throw new Error("Unexpected outcome"); +} +console.log(result.outcome, projected.value.outcome); +``` + +Expected output in the trusted development terminal: `pass withheld`. Never expose the private outcome or protected reference to a submitting user. + +A supplied reference bundle must match the exact assessment ID, revision and revision digest. Each record must match its declared ID, kind, digest, numeric unit or set item type. Unknown, duplicate, malformed or substituted supplied references return invalid_reference before evidence comparison. A missing reference is inconclusive when needed. A hash of a low-entropy secret can be guessed; a digest is not encryption. + +## Public projection + +`projectPublicResult(definition, result)` checks definition integrity, exact lineage, finding correspondence and order, reason compatibility, aggregate and warning consistency. The projected record contains schemaVersion, outcome and public findings with only criterionId, outcome and reason. + +If any criterion is restricted, even an advisory one, the aggregate is always `withheld` and restricted findings are omitted. Rejection uses the opaque code `PUBLIC_PROJECTION_REJECTED`. The function does not receive evidence and cannot authenticate a purported result; use results produced in your trusted host and independently authorize the recipient. + +## Host responsibilities + +```mermaid +flowchart TD + U[Untrusted submission] --> H[Host transport limits] + H --> I[Isolated runner or producer] + I --> E[Host verifies evidence] + D[Authorized criteria and private references] --> A[Assay in trusted host] + E --> A + A --> F[Private result] + F --> P[Public projection] + P --> G[Host access policy] + G --> U +``` + +Keep private expectations, definitions, evidence and full results away from submitted programs, public endpoints, prompts and user-accessible logs. Verify the actual artifact, runner and reviewer provenance. Assay does not assign grades or issue credentials. + +Cap transport bytes before buffering; use `decodeSerializedRecord` before contract validation to reject duplicate keys and malformed JSON. Do not accept adversarial live Proxy objects as inert data. Escape captured text and review feedback before rendering. Rate-limit repeated submissions and avoid timing or secondary feedback channels that expose protected outcomes. If the existence of restricted checks is itself sensitive, use a host-defined fixed response envelope. + +Report vulnerabilities through the [security policy](https://github.com/0xbuffdev/assay/blob/v0.0.1/SECURITY.md). diff --git a/content/docs/assay/meta.json b/content/docs/assay/meta.json index bd08fb3..9798eb5 100644 --- a/content/docs/assay/meta.json +++ b/content/docs/assay/meta.json @@ -1,8 +1,14 @@ { "title": "Assay", - "description": "Compare technical evidence against explicit, versioned criteria.", + "description": "Evaluate technical evidence against explicit, versioned criteria.", "root": true, "pages": [ - "index" + "index", + "evaluation", + "observations", + "integrity", + "---Reference---", + "api", + "contracts" ] } diff --git a/content/docs/assay/observations.mdx b/content/docs/assay/observations.mdx new file mode 100644 index 0000000..01e8701 --- /dev/null +++ b/content/docs/assay/observations.mdx @@ -0,0 +1,246 @@ +--- +title: "Observations" +description: "Supply execution facts, collect missing observations and record qualitative reviews." +--- + +Assay consumes observations supplied by your application. It does not install a runner, connect to an AI provider or verify the authenticity of a capture. + +## Execution facts + +Declare `executionFact` on both the objective criterion and its observation. + +| Selector | Criterion kinds | Observation kind | +| --- | --- | --- | +| stdout, stderr | exact_text, normalized_text | text | +| exit_status | number_with_tolerance, number_range | number | +| boolean_property | boolean_equality | boolean | +| structured_stdout, structured_stderr | json_equality | json | + +Exit status is a signed safe integer without a unit. Boolean properties are identified by criterion ID. Structured stream values are host-supplied JSON. + +This example uses a fixture in place of an isolated runner. + +```js +// assay-docs: runnable +import { createAssessmentDefinition, createEvidenceBundle, evaluate } from "@0xbuff/assay"; + +const created = createAssessmentDefinition({ + schemaVersion: 4, + assessmentId: "command-output", + revision: "rev1", + policyVersion: "composed-required-v1", + criteria: [{ + id: "output", + kind: "exact_text", + executionFact: "stdout", + mode: "required", + visibility: "public", + parameters: { expected: { type: "literal", value: "ok" } }, + }], + composition: { + rootGroupId: "root", + groups: [{ + id: "root", + operator: "all", + children: [{ kind: "criterion", id: "output" }], + }], + }, +}); +if (!created.ok) throw new Error("Invalid definition"); + +const prepared = createEvidenceBundle(created.value, { + schemaVersion: 4, + observations: [{ + criterionId: "output", + evidenceRef: "stdout-1", + kind: "text", + executionFact: "stdout", + completeness: "complete", + value: "ok", + origin: { + kind: "independent", + sourceRef: "fixture", + runRef: "run-1", + termination: "exited", + }, + }], +}); +if (!prepared.ok) throw new Error("Invalid evidence"); + +const result = evaluate(created.value, prepared.value); +if (result.outcome !== "pass") throw new Error("Expected pass"); +console.log(result.outcome); +``` + +A timeout or crash makes selected facts inconclusive. Truncation takes precedence with `EVIDENCE_TRUNCATED`. Complete observations of the same selected stream or exit status must agree for the same source and run. Known truncation invalidates contradictory complete claims; stdout and stderr are tracked separately. Exit status is independent of capture truncation. The assertion-only `observed_execution` kind cannot establish correctness even when reported as confirmed. + +## Observation ports + +Use `collectObservations` to request missing public objective or execution facts through a host-owned async port. Evaluation itself remains synchronous. + +```mermaid +sequenceDiagram + participant H as Host + participant A as Assay + participant P as Host port + H->>A: Definition and existing evidence + A->>A: Verify and select missing public facts + alt Eligible facts exist + A->>P: Bounded request + P-->>A: Observations and provenance + A->>A: Validate and seal evidence + end + A-->>H: Evidence and optional receipt +``` + +Implement `observe(request, signal?)`. The following mock returns a local fixture and requires no external service. + +```js +// assay-docs: runnable +import { + collectObservations, + createAssessmentDefinition, + createEvidenceBundle, + evaluate, +} from "@0xbuff/assay"; + +const created = createAssessmentDefinition({ + schemaVersion: 4, + assessmentId: "public-demo", + revision: "rev1", + policyVersion: "composed-required-v1", + composition: { + rootGroupId: "root", + groups: [{ id: "root", operator: "all", children: [{ kind: "criterion", id: "stdout" }] }], + }, + criteria: [ + { + id: "stdout", + kind: "exact_text", + mode: "required", + visibility: "public", + parameters: { expected: { type: "literal", value: "ok" } }, + }, + ], +}); +if (!created.ok) throw new Error("Invalid authored definition"); +const definition = created.value; + +const prepared = createEvidenceBundle(definition, { + schemaVersion: 4, + observations: [], +}); +if (!prepared.ok) throw new Error("Invalid evidence"); +const startingEvidence = prepared.value; + +const mockPort = { + async observe(request) { + // request lists only public IDs, expected fact kinds and resource limits. + return { + schemaVersion: 4, + definition: request.definition, + provenance: { + adapterId: "fixture", + adapterVersion: "v1", + runRef: "local-run", + toolchainId: "node", + toolchainVersion: "v24", + capturedStdoutBytes: 2, + capturedStderrBytes: 0, + stdoutTruncated: false, + stderrTruncated: false, + }, + observations: [ + { + criterionId: "stdout", + evidenceRef: "stdout1", + kind: "text", + completeness: "complete", + value: "ok", + }, + ], + }; + }, +}; + +const collected = await collectObservations(definition, startingEvidence, mockPort); + +if (!collected.ok) throw new Error("Collection failed"); +const result = evaluate(definition, collected.evidence); +if (result.outcome !== "pass") throw new Error("Expected pass"); +console.log(result.outcome); +``` + +The request includes definition lineage, optional artifact scope, eligible public criterion IDs, kinds, applicable units/item types/selectors/assertion IDs, and capture limits. It excludes expected values, protected reference IDs, restricted criteria and commands. + +The report echoes the definition and scope and supplies provenance: adapter and toolchain IDs and versions, run reference, captured byte counts and truncation flags. Combined stdout/stderr capture is limited to 65,536 bytes. Report observations must not carry their own origin. Selected facts require top-level termination. The collector adds the report's origin to new observations and seals the combined evidence. Existing observations remain unchanged. + +| Response | Meaning | +| --- | --- | +| ok: true | Sealed evidence and receipt; null receipt if no port ran | +| invalid_definition | Invalid definition | +| invalid_evidence | Invalid evidence, report or merged lineage | +| OBSERVATION_PORT_ERROR | Port threw or rejected | +| OBSERVATION_CANCELLED | Host cancelled acquisition | + +Pass an optional `{ signal: controller.signal }` as the fourth argument. A valid pre-aborted call does not invoke the port; cancellation ignores late completion. The host must stop any actual running process. No default timeout or retry is applied. + +## Qualitative reviews + +Use an advisory-only criterion outside the composition tree to record human or model feedback. Required manual evidence remains pending authorized review. + +```ts +{ + id: "readability", + kind: "qualitative_review", + mode: "advisory", + visibility: "public", + parameters: { + reviewPolicyId: "code-review", + reviewPolicyVersion: "v1", + }, +} +``` + +The review observation must bind to the bundle's artifact digest and match the policy. + +```ts +{ + criterionId: "readability", + evidenceRef: "review-1", + kind: "qualitative_review", + completeness: "complete", + origin: { + kind: "artifact", + artifactDigest, + sourceRef: "review-service", + }, + reviewPolicyId: "code-review", + reviewPolicyVersion: "v1", + reviewer: { + kind: "human", + reviewerId: "reviewer-1", + reviewerVersion: "v1", + }, + uncertainty: "low", + feedback: "Name the intermediate result before returning it.", + citations: [{ artifactRef: "solution", startByte: 0, endByte: 10 }], +} +``` + +For model attribution, use: + +```ts +reviewer: { + kind: "model", + providerId: "provider", + modelId: "review-model", + modelVersion: "v1", + promptId: "code-review", + promptVersion: "v1", +} +``` + +The host computes the artifact digest, obtains feedback and verifies attribution and citation locations. Citations use nonnegative safe integer byte offsets with exclusive ends. Feedback is nonempty inert text, limited to 4,096 UTF-8 bytes and UTF-16 code units; supply one to eight distinct citations. Uncertainty is low, medium, high or unknown. Version IDs cannot be latest. + +Missing, truncated and complete reviews remain inconclusive, using EVIDENCE_MISSING, EVIDENCE_TRUNCATED and REVIEW_REQUIRED respectively. The collector does not request or accept qualitative reviews. Review text, attribution, uncertainty and citations stay in privileged evidence; public projection omits them. diff --git a/scripts/assay-docs.test.mjs b/scripts/assay-docs.test.mjs new file mode 100644 index 0000000..e7058f7 --- /dev/null +++ b/scripts/assay-docs.test.mjs @@ -0,0 +1,29 @@ +import assert from "node:assert/strict"; +import { readFile, readdir } from "node:fs/promises"; +import { join } from "node:path"; +import test from "node:test"; + +const directory = "content/docs/assay"; +const files = (await readdir(directory)).filter((name) => name.endsWith(".mdx")); +const pages = new Set(files.map((name) => name.slice(0, -4))); + +test("Assay has distinct entry, task, explanation and reference pages", async () => { + const meta = JSON.parse(await readFile(join(directory, "meta.json"), "utf8")); + const listed = meta.pages.filter((entry) => !entry.startsWith("---")); + assert.deepEqual([...listed].sort(), [...pages].sort()); + assert.deepEqual(listed, ["index", "evaluation", "observations", "integrity", "api", "contracts"]); +}); + +test("Assay internal links resolve and complete examples are marked", async () => { + let runnable = 0; + for (const file of files) { + const source = await readFile(join(directory, file), "utf8"); + runnable += [...source.matchAll(/^\x60\x60\x60js\r?\n\/\/ assay-docs: runnable\r?\n/gm)].length; + const prose = source.replace(/^\x60\x60\x60[^\n]*\n[\s\S]*?^\x60\x60\x60\s*$/gm, ""); + for (const match of prose.matchAll(/\]\(\/docs\/assay(?:\/([a-z0-9-]+))?(?:#[^)]*)?\)/g)) { + assert.ok(pages.has(match[1] ?? "index"), file + ": " + match[0]); + } + assert.doesNotMatch(prose, /\b(?:AY-I|PAQO-I)\d+\b/, file); + } + assert.ok(runnable >= 5, "Expected complete executable examples"); +}); diff --git a/scripts/verify-assay-examples.mjs b/scripts/verify-assay-examples.mjs new file mode 100644 index 0000000..6561b67 --- /dev/null +++ b/scripts/verify-assay-examples.mjs @@ -0,0 +1,59 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; + +const version = "0.0.1"; +const directory = "content/docs/assay"; +const temporary = await mkdtemp(join(tmpdir(), "assay-docs-")); +const expected = new Map([ + ["index.mdx", ["4 v0.0.5"]], + ["evaluation.mdx", ["pass"]], + ["observations.mdx", ["pass", "pass"]], + ["integrity.mdx", ["pass withheld"]], +]); +try { + const npm = process.platform === "win32" ? "npm.cmd" : "npm"; + execFileSync(npm, ["install", "--prefix", temporary, "--ignore-scripts", + "--no-audit", "--no-fund", "--package-lock=false", + "--registry=https://registry.npmjs.org", "@0xbuff/assay@" + version], + { stdio: "inherit", timeout: 120_000, shell: process.platform === "win32" }); + + const packageDir = join(temporary, "node_modules", "@0xbuff", "assay"); + const manifest = JSON.parse(await readFile(join(packageDir, "package.json"), "utf8")); + assert.equal(manifest.version, version); + const assay = await import(pathToFileURL(join(packageDir, manifest.exports["."].import)).href); + assert.equal(assay.ASSAY_SCHEMA_VERSION, 4); + assert.equal(assay.ASSAY_EVALUATOR_VERSION, "v0.0.5"); + + const api = await readFile(join(directory, "api.mdx"), "utf8"); + for (const name of Object.keys(assay)) { + assert.match(api, new RegExp("\\b" + name + "\\b"), "Undocumented export: " + name); + } + const limits = await readFile(join(directory, "contracts.mdx"), "utf8"); + for (const [name, value] of Object.entries(assay.CONTRACT_LIMITS)) { + assert.ok(limits.includes("| " + name + " | " + value.toLocaleString("en-US") + " |"), + "Incorrect or missing limit: " + name); + } + + const seen = new Set(); + for (const file of (await readdir(directory)).filter((name) => name.endsWith(".mdx"))) { + const source = await readFile(join(directory, file), "utf8"); + const examples = [...source.matchAll(/^\x60\x60\x60js\r?\n\/\/ assay-docs: runnable\r?\n([\s\S]*?)^\x60\x60\x60\s*$/gm)]; + assert.equal(examples.length, expected.get(file)?.length ?? 0, file + " example count"); + for (const [index, match] of examples.entries()) { + const path = join(temporary, file.replace(".mdx", "-" + index + ".mjs")); + await writeFile(path, match[1]); + const output = execFileSync(process.execPath, [path], { encoding: "utf8", timeout: 10_000 }).trim(); + assert.equal(output, expected.get(file)?.[index], file + " example " + index); + seen.add(file); + console.log("Verified " + file + ": " + output); + } + } + assert.deepEqual([...seen].sort(), [...expected.keys()].sort()); + console.log("Verified documented runtime exports and contract limits."); +} finally { + await rm(temporary, { recursive: true, force: true }); +}