From b6beb07aeeba42cfe52eed360bf6a062a184edf0 Mon Sep 17 00:00:00 2001 From: "Christopher S. Aondona" Date: Sat, 28 Nov 2026 16:26:16 +0100 Subject: [PATCH 1/2] Document Assay v0.0.1 with guides and complete public API reference --- .github/workflows/ci.yml | 3 + .github/workflows/deploy.yml | 3 + README.md | 10 ++ content/docs/assay/api.mdx | 94 +++++++++++++++ content/docs/assay/architecture.mdx | 61 ++++++++++ content/docs/assay/compatibility.mdx | 25 ++++ content/docs/assay/composition.mdx | 77 ++++++++++++ content/docs/assay/concepts.mdx | 42 +++++++ content/docs/assay/contracts.mdx | 100 ++++++++++++++++ content/docs/assay/criteria.mdx | 94 +++++++++++++++ content/docs/assay/evidence.mdx | 43 +++++++ content/docs/assay/execution-facts.mdx | 85 +++++++++++++ content/docs/assay/index.mdx | 32 ++++- content/docs/assay/installation.mdx | 60 ++++++++++ content/docs/assay/integrity.mdx | 51 ++++++++ content/docs/assay/limits.mdx | 41 +++++++ content/docs/assay/meta.json | 27 ++++- content/docs/assay/observation-ports.mdx | 125 ++++++++++++++++++++ content/docs/assay/outcomes.mdx | 69 +++++++++++ content/docs/assay/protected-references.mdx | 107 +++++++++++++++++ content/docs/assay/public-results.mdx | 56 +++++++++ content/docs/assay/qualitative-review.mdx | 77 ++++++++++++ content/docs/assay/quickstart.mdx | 107 +++++++++++++++++ content/docs/assay/security.mdx | 48 ++++++++ content/docs/assay/troubleshooting.mdx | 42 +++++++ scripts/assay-docs.test.mjs | 33 ++++++ scripts/verify-assay-examples.mjs | 59 +++++++++ 27 files changed, 1564 insertions(+), 7 deletions(-) create mode 100644 content/docs/assay/api.mdx create mode 100644 content/docs/assay/architecture.mdx create mode 100644 content/docs/assay/compatibility.mdx create mode 100644 content/docs/assay/composition.mdx create mode 100644 content/docs/assay/concepts.mdx create mode 100644 content/docs/assay/contracts.mdx create mode 100644 content/docs/assay/criteria.mdx create mode 100644 content/docs/assay/evidence.mdx create mode 100644 content/docs/assay/execution-facts.mdx create mode 100644 content/docs/assay/installation.mdx create mode 100644 content/docs/assay/integrity.mdx create mode 100644 content/docs/assay/limits.mdx create mode 100644 content/docs/assay/observation-ports.mdx create mode 100644 content/docs/assay/outcomes.mdx create mode 100644 content/docs/assay/protected-references.mdx create mode 100644 content/docs/assay/public-results.mdx create mode 100644 content/docs/assay/qualitative-review.mdx create mode 100644 content/docs/assay/quickstart.mdx create mode 100644 content/docs/assay/security.mdx create mode 100644 content/docs/assay/troubleshooting.mdx create mode 100644 scripts/assay-docs.test.mjs create mode 100644 scripts/verify-assay-examples.mjs 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..0b7b089 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. + +Organize pages by reader task. Start with installation and a complete tutorial, keep procedural guides separate from conceptual explanations, and maintain a reference for records, exported APIs, outcomes and limits. 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..4ebf4f7 --- /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/outcomes). + +## 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/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/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/architecture.mdx b/content/docs/assay/architecture.mdx new file mode 100644 index 0000000..951ea9b --- /dev/null +++ b/content/docs/assay/architecture.mdx @@ -0,0 +1,61 @@ +--- +title: "Architecture" +description: "Follow the validation, comparison, aggregation and projection pipeline." +--- + +Assay has a synchronous evaluation core and an optional asynchronous collector. The host decides when to call each operation. + +## Evaluation + +```mermaid +flowchart TD + D[Authorized definition] --> V[Verify definition] + V --> R[Verify supplied references] + X[Optional reference bundle] --> R + R --> B[Verify evidence and coverage] + I[Evidence bundle] --> B + B --> C[Compare all criteria] + C --> A[Compose required outcomes] + A --> F[Technical result] + V -. invalid .-> G[Diagnostic failure] + R -. invalid .-> G + B -. invalid .-> G + F --> P[Optional public projection] +``` + +Definition verification happens first, followed by verification of the entire supplied reference bundle and then the evidence. Invalid inputs return diagnostic failures without findings. Valid inputs reach comparators and the required composition engine. + +The public projection validates the definition and result correspondence, recomputes the aggregate and emits only permitted fields. It does not receive the evidence, so it cannot authenticate the evaluation. + +## Observation acquisition + +```mermaid +sequenceDiagram + participant H as Host + participant A as Assay collector + participant P as Host port + H->>A: Definition and existing evidence + A->>A: Verify inputs and select missing public facts + alt Eligible facts exist + A->>P: Bounded request + P-->>A: Report and claimed provenance + A->>A: Validate and seal combined evidence + end + A-->>H: Evidence and optional receipt + H->>H: Authorize use and call evaluate +``` + +No port is invoked when no eligible facts are missing. The collector never receives authority to run code by itself; the injected port is host-owned. + +## Source modules + +| Module | Responsibility | +| --- | --- | +| contracts | Versioned records and public types | +| validation | Bounded snapshots, structural checks and coverage | +| integrity | Canonical JSON and SHA-256 verification | +| evaluation | Comparison and group aggregation | +| observation | Optional fact acquisition | +| projection | Result correspondence and public field selection | + +The [release source](https://github.com/0xbuffdev/assay/tree/v0.0.1/src) contains the implementation. See [security and trust](/docs/assay/security) for responsibilities outside the library. diff --git a/content/docs/assay/compatibility.mdx b/content/docs/assay/compatibility.mdx new file mode 100644 index 0000000..fdc765d --- /dev/null +++ b/content/docs/assay/compatibility.mdx @@ -0,0 +1,25 @@ +--- +title: "Versions and compatibility" +description: "Distinguish the released package version from schema, policy and evaluator identities." +--- + +| Identity | Current documented value | +| --- | --- | +| npm package | 0.0.1 | +| Schema | 4 | +| Evaluation semantics | v0.0.5 | +| Binding policy | composed-required-v1 | +| Runtime | Node.js 24 or later, ESM | +| License | Apache-2.0 | + +These pages describe the public release [v0.0.1](https://github.com/0xbuffdev/assay/releases/tag/v0.0.1), not unreleased work on main. The package ships TypeScript declarations and has no runtime dependencies. + +## Reproducibility + +Pin the package version and preserve your lockfile. Persist the authorized definition and evidence records with their digests, protected references when used, and evaluator identity. The package version identifies the distribution; the evaluator version identifies the supported finding semantics. + +## Unsupported records + +Older development schemas and policy identifiers are rejected. There is no runtime migration or automatic upgrade. Do not relabel or rehash an older record as schema 4. Preserve historical records and use the version that originally produced them, or create a newly authorized definition and evidence under the current contract. + +See the [changelog](https://github.com/0xbuffdev/assay/blob/v0.0.1/CHANGELOG.md) and [release policy](https://github.com/0xbuffdev/assay/blob/v0.0.1/docs/releasing.md) for changes and release procedures. diff --git a/content/docs/assay/composition.mdx b/content/docs/assay/composition.mdx new file mode 100644 index 0000000..bef0a21 --- /dev/null +++ b/content/docs/assay/composition.mdx @@ -0,0 +1,77 @@ +--- +title: "Compose required checks" +description: "Build explicit all and any groups to determine the required outcome." +--- + +A definition must contain at least one required criterion. The `composed-required-v1` policy combines required findings through a tree of groups. Advisory findings stay outside the tree. + +## Require all checks + +Use one `all` group for a definition whose required criteria are `output` and `status`. + +```ts +composition: { + rootGroupId: "root", + groups: [{ + id: "root", + operator: "all", + children: [ + { kind: "criterion", id: "output" }, + { kind: "criterion", id: "status" }, + ], + }], +} +``` + +## Allow alternatives + +Suppose an engineering exercise accepts either a JSON result or a text result, but also requires a status check. + + +```mermaid +flowchart TD + A[all: root] --> S[status] + A --> B[any: format] + B --> J[json-result] + B --> T[text-result] +``` + + +```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" }, + ], + }, + ], +} +``` + +Each ID names a declared required criterion or group. Groups must be reachable from the root, with no cycles or shared subtrees. Each required leaf appears once; advisory leaves cannot appear. + +## How groups resolve + +Read each row from left to right. The first applicable condition determines the group outcome. + +| Operator | First | Then | Then | 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 | + +All criteria are validated and evaluated in authored order, even if an alternative already determines the aggregate. Invalid input anywhere rejects the evaluation before comparison. Missing leaves may be acceptable in an alternative whose other leaf passes, but missing evidence never passes on its own. + +Group limits are listed in [limits](/docs/assay/limits). Changing composition or authored order changes the definition digest. diff --git a/content/docs/assay/concepts.mdx b/content/docs/assay/concepts.mdx new file mode 100644 index 0000000..a10ca16 --- /dev/null +++ b/content/docs/assay/concepts.mdx @@ -0,0 +1,42 @@ +--- +title: "Core concepts" +description: "Understand the records, identities and outcomes that make up an Assay evaluation." +--- + +## Records + +| Record | Purpose | +| --- | --- | +| Assessment definition | Versioned criteria and the required composition tree. | +| Criterion | One comparison or review requirement, with an ID, mode and visibility. | +| Observation | A typed fact supplied by the host for a criterion. | +| Evidence bundle | Observations sealed to a particular definition, optionally scoped to an artifact. | +| Reference record | A separately stored expected value identified by a digest. | +| Evaluation result | Private technical findings and the composed outcome. | +| Public result | A restricted view derived from a valid definition and result. | + +A definition describes what should hold; evidence describes what was observed. Keep these inputs separate. A reference value is an expectation, never an observation. + +## Criterion mode and visibility + +Required criteria participate in the composition tree. Advisory criteria produce findings without determining the root outcome. + +Public criteria may appear in a projected result. Restricted criteria never appear there, and even a restricted advisory criterion causes the public aggregate to be withheld. Restricted objective criteria must refer to protected expected values instead of embedding literals. + +## Evidence states + +An observation is either `complete` or `truncated`. Missing observations are represented by their absence, not placeholder values. A measured zero, empty string, false or JSON null can be a valid complete observation. + +## Evaluation lifecycle + +```mermaid +flowchart LR + D[Definition] --> E[Evaluate] + B[Evidence bundle] --> E + R[Optional references] --> E + E --> F[Technical result] + F --> P[Public projection] + F --> H[Host decision] +``` + +The evaluator returns pass, fail, inconclusive or evaluation error for complete results. Invalid inputs return a separate diagnostic envelope. See [outcomes and reasons](/docs/assay/outcomes) for the distinction. diff --git a/content/docs/assay/contracts.mdx b/content/docs/assay/contracts.mdx new file mode 100644 index 0000000..6a35da2 --- /dev/null +++ b/content/docs/assay/contracts.mdx @@ -0,0 +1,100 @@ +--- +title: "Record reference" +description: "Look up the fields of definitions, evidence, references and evaluation records." +--- + +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/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/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/evidence), [execution facts](/docs/assay/execution-facts) and [qualitative reviews](/docs/assay/qualitative-review). + +## 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/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/public-results). + +The [contract source](https://github.com/0xbuffdev/assay/tree/v0.0.1/src/contracts) defines the complete field unions and types. diff --git a/content/docs/assay/criteria.mdx b/content/docs/assay/criteria.mdx new file mode 100644 index 0000000..79856fc --- /dev/null +++ b/content/docs/assay/criteria.mdx @@ -0,0 +1,94 @@ +--- +title: "Define criteria" +description: "Choose a comparison kind and declare the exact comparison parameters." +--- + +Every criterion requires `id`, `kind`, `mode`, `visibility` and `parameters`. Include each required criterion exactly once in the [composition tree](/docs/assay/composition). + +## Choose a comparator + +| Kind | Observation | Expected value and parameters | +| --- | --- | --- | +| `exact_text` | text | String; exact equality | +| `normalized_text` | text | String; explicit normalization | +| `number_with_tolerance` | number | Number; absolute and relative tolerance; optional unit | +| `number_range` | number | Range; both endpoint flags; optional unit | +| `set_equivalence` | set | Scalar array; item type, order and duplicate policies | +| `boolean_equality` | boolean | Boolean | +| `json_equality` | json | JSON value | +| `observed_execution` | execution | Assertion IDs and reference IDs | +| `manual_evidence` | manual | Review required | +| `qualitative_review` | qualitative review | Review policy ID and version; advisory only | + +The first seven are objective comparisons. They accept a literal or a content-bound reference as `parameters.expected`. The remaining kinds report unresolved evidence rather than asserting correctness. + +## Text + +Exact text compares JavaScript UTF-16 code units, including whitespace and line endings. Choose normalized text when differences in formatting are irrelevant. + +Example criterion (a fragment of a definition): + +```ts +{ + id: "message", + kind: "normalized_text", + mode: "required", + visibility: "public", + parameters: { + expected: { type: "literal", value: "hello world" }, + normalization: { + lineEndings: "lf", + case: "fold", + unicode: "NFC", + whitespace: "collapse", + trim: "both", + }, + }, +} +``` + +Both values undergo the same transformations in this order: line endings, case, Unicode normalization, whitespace, trim. Each choice is explicit. Case folding uses JavaScript lowercase conversion; it does not equate German sharp S with two s characters. + +## Numbers + +For tolerance comparisons, the allowed difference is the greater of the absolute tolerance and the relative tolerance multiplied by the magnitude of the expected value. The boundary is inclusive. + +For example, with expected value 100, absolute tolerance 2 and relative tolerance 0.05, the bound is 5. An observation of 105 passes; 106 fails. + + +```ts +parameters: { + expected: { type: "literal", value: 100 }, + tolerance: { absolute: 2, relative: 0.05 }, + unit: "mV", +} +``` + +For ranges, supply finite `min`, `max`, `minInclusive` and `maxInclusive`. Equal endpoints are valid only when both are inclusive. A numeric observation must use the exact declared unit, or omit it if the criterion has no unit. Assay uses JavaScript numbers and does not coerce strings or convert units. + +## Sets + +Declare `itemType` as string, number or boolean. The observation uses `items`, not `value`. + + +```ts +parameters: { + expected: { type: "literal", value: ["read", "write"] }, + itemType: "string", + order: "ignore", + duplicates: "ignore", +} +``` + +| Order | Duplicates | Comparison | +| --- | --- | --- | +| ignore | ignore | Membership | +| ignore | respect | Multiset counts | +| preserve | ignore | Sequence of first occurrences | +| preserve | respect | Exact sequence | + +## Booleans and JSON + +Boolean comparisons accept only true or false. JSON equality ignores object key order but preserves array order. Strings and object keys remain exact. Negative zero equals zero. JSON null is a valid expected value. + +For the complete parameter and observation contracts, see [record reference](/docs/assay/contracts). diff --git a/content/docs/assay/evidence.mdx b/content/docs/assay/evidence.mdx new file mode 100644 index 0000000..edea7b6 --- /dev/null +++ b/content/docs/assay/evidence.mdx @@ -0,0 +1,43 @@ +--- +title: "Supply evidence" +description: "Create immutable evidence bundles and handle missing, truncated and artifact-scoped observations." +--- + +Use `createEvidenceBundle(definition, draft)` to bind observations to the exact definition. The draft accepts `schemaVersion`, `observations` and optional `artifactDigest`. Assay derives the definition lineage and evidence digest. + +## Observation fields + +Every observation has a criterion ID, unique evidence reference, kind and completeness. The value fields depend on the kind. See [record reference](/docs/assay/contracts). + +For a text criterion named output: + +```ts +const prepared = createEvidenceBundle(definition, { + schemaVersion: 4, + observations: [{ + criterionId: "output", + evidenceRef: "capture-1", + kind: "text", + completeness: "complete", + value: "ok", + }], +}); +``` + +This fragment assumes you imported the creator and sealed a matching definition. A successful result exposes `prepared.value`. Handle failure before using it. + +## Missing and incomplete evidence + +Omit observations for unavailable facts. Mark partial captures as truncated. Do not substitute a fabricated empty string or zero. Use `inspectEvidenceCoverage(definition, evidence)` to list missing and incomplete required criteria; it performs no comparison and does not account for alternative group outcomes. + +## Bind evidence to an artifact + +Set an explicit bundle artifact digest when associating evidence with an artifact. Every observation in a scoped bundle must declare an origin. An artifact origin carries the exact bundle digest and a source reference; an independent origin has a source reference but no artifact digest. Unscoped observations may omit origin, but cannot claim artifact scope. + +Selected execution observations also require run reference and termination. See [execution facts](/docs/assay/execution-facts). + +## Verify and correct + +Use `verifyEvidenceBundle(definition, evidence)` to recompute the digest and check lineage. Create a new sealed bundle for corrections rather than editing existing records. Keep the original bundle if you need an audit history. + +Assay validates consistency of the claims; your application must verify the actual source and artifact. diff --git a/content/docs/assay/execution-facts.mdx b/content/docs/assay/execution-facts.mdx new file mode 100644 index 0000000..47502c0 --- /dev/null +++ b/content/docs/assay/execution-facts.mdx @@ -0,0 +1,85 @@ +--- +title: "Evaluate execution facts" +description: "Compare captured output, exit status and other typed facts supplied by a runner." +--- + +Your application runs the program, captures its output and supplies the observations. Assay compares these facts using the same objective comparators as other evidence. + +## Select a fact + +Set `executionFact` on the criterion and the corresponding 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 | + +An exit status must be a signed safe integer without a unit. A Boolean property is identified by its criterion ID. Structured stream values are JSON supplied by your application; Assay does not parse captured stdout for you. + +## Evaluate captured output + +The following example uses a fixture for stdout. In production, obtain the value and termination state from your 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); +``` + +## Interrupted or incomplete runs + +A timeout or crash produces an inconclusive finding for selected facts. Truncated captures use `EVIDENCE_TRUNCATED` first. The evaluator does not invent an exit status or output value when one is unavailable. + +For the same source and run, complete observations of the same selected stream or exit status must agree. Known stream truncation invalidates contradictory complete claims, even if an observation omits provenance. Stdout and stderr truncation are tracked separately. Exit status does not depend on stream capture. + +The older assertion-shaped `observed_execution` criterion remains inconclusive even when an assertion claims confirmation. Use selected objective facts to compare actual values. + +See [observation ports](/docs/assay/observation-ports) for optional acquisition and [host security responsibilities](/docs/assay/security) for execution isolation. diff --git a/content/docs/assay/index.mdx b/content/docs/assay/index.mdx index e0deb46..ee467e8 100644 --- a/content/docs/assay/index.mdx +++ b/content/docs/assay/index.mdx @@ -1,10 +1,32 @@ --- -title: Assay -description: Compare technical evidence against explicit, versioned criteria. +title: "Assay" +description: "Evaluate technical evidence against versioned criteria and return reproducible findings." --- -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 criteria defined by your application. Use it to check engineering exercises, measurement results, structured outputs and other technical work. -The host supplies evidence and authorizes the criteria. Assay does not execute submitted programs, authenticate observations, assign grades, or issue credentials. +You supply the criteria and observations. Assay validates the records, compares the observed values and combines required checks into an outcome. It runs offline without runtime dependencies. -For the source, license, and release information, see the [Assay repository](https://github.com/0xbuffdev/assay). +## Get started + +- [Install Assay](/docs/assay/installation) in a Node.js application. +- [Evaluate your first result](/docs/assay/quickstart) with a complete example. +- [Understand definitions, evidence and findings](/docs/assay/concepts) before integrating the evaluator. + +## What you can do + +| Task | Guide | +| --- | --- | +| Compare text, measurements, sets and JSON | [Define criteria](/docs/assay/criteria) | +| Require several checks or allow alternatives | [Compose required checks](/docs/assay/composition) | +| Evaluate results from an external runner | [Evaluate execution facts](/docs/assay/execution-facts) | +| Collect missing public observations through an adapter | [Collect observations](/docs/assay/observation-ports) | +| Use private expected values | [Use protected references](/docs/assay/protected-references) | +| Attach human or model feedback | [Record qualitative reviews](/docs/assay/qualitative-review) | +| Return a limited result to a user | [Project public results](/docs/assay/public-results) | + +## Scope + +Assay does not run submitted code, authenticate observations, assign grades or issue credentials. Your application owns execution, authorization and any decision based on the findings. Read the [security and trust model](/docs/assay/security) before accepting untrusted evidence or returning results to users. + +These pages describe package version `0.0.1`. See the [source repository](https://github.com/0xbuffdev/assay), [release notes](https://github.com/0xbuffdev/assay/releases/tag/v0.0.1) and [Apache-2.0 license](https://github.com/0xbuffdev/assay/blob/v0.0.1/LICENSE). diff --git a/content/docs/assay/installation.mdx b/content/docs/assay/installation.mdx new file mode 100644 index 0000000..886726c --- /dev/null +++ b/content/docs/assay/installation.mdx @@ -0,0 +1,60 @@ +--- +title: "Installation" +description: "Install the released Assay package and configure an ESM application." +--- + +## Requirements + +- Node.js 24 or later. +- An ECMAScript module (ESM) application. Use a file ending in `.mjs`, or set `"type": "module"` in your package.json. +- A package manager with access to the public npm registry. + +Assay has no runtime dependencies. TypeScript declarations ship with the package; you do not need a separate types package. + +## Install + +Use one of these commands: + +```sh +npm install @0xbuff/assay@0.0.1 +``` + + +```sh +pnpm add @0xbuff/assay@0.0.1 +``` + + +```sh +yarn add @0xbuff/assay@0.0.1 +``` + +Pin the release and commit your lockfile when reproducibility matters. + +## Verify the installation + +Create `check.mjs`: + +```js +// assay-docs: runnable +import { ASSAY_SCHEMA_VERSION, ASSAY_EVALUATOR_VERSION } from "@0xbuff/assay"; + +console.log(ASSAY_SCHEMA_VERSION, ASSAY_EVALUATOR_VERSION); +``` + + +```sh +node check.mjs +``` + +Expected output: + +```text +4 v0.0.5 +``` + +The package, schema and evaluator versions identify different things. See [versions and compatibility](/docs/assay/compatibility). + +## Next step + +[Evaluate a measurement](/docs/assay/quickstart) using the installed package. diff --git a/content/docs/assay/integrity.mdx b/content/docs/assay/integrity.mdx new file mode 100644 index 0000000..56fa02a --- /dev/null +++ b/content/docs/assay/integrity.mdx @@ -0,0 +1,51 @@ +--- +title: "Content integrity" +description: "Understand canonical digests, immutable revisions and evidence lineage." +--- + +Assay seals definitions, references and evidence using SHA-256 over canonical JSON. Digests identify content; they do not identify or authenticate its publisher. + +## Seal and verify records + +| Record | Create | Verify | +| --- | --- | --- | +| Definition | createAssessmentDefinition | verifyAssessmentDefinition | +| Reference | createReferenceRecord | verifyReferenceBundle | +| Evidence | createEvidenceBundle | verifyEvidenceBundle | + +`computeDefinitionDigest(draft)` computes the definition digest without creating a sealed record. The creation helpers validate unsigned drafts and derive digests. Do not supply digest fields in drafts. + +## Canonical profile + +Schema 4 uses separate domains: + +| Record | Domain | Omitted field | +| --- | --- | --- | +| Definition | assay:definition:v4 | revisionDigest | +| Reference | assay:reference:v4 | referenceDigest | +| Evidence | assay:evidence:v4 | evidenceDigest | + +After closed-contract validation, Assay sorts object keys by ECMAScript UTF-16 code-unit order and serializes compact JSON. Array order is retained, strings are not normalized, optional absent fields remain absent and negative zero serializes as zero. The UTF-8 bytes are the domain, one LF, then canonical JSON with no trailing LF. Hash the bytes using SHA-256 and prefix lowercase hexadecimal with `sha256:`. + +The [release integrity vectors](https://github.com/0xbuffdev/assay/blob/v0.0.1/docs/integrity.md) provide independent test inputs and expected digests. + +## Preserve lineage + + +```mermaid +flowchart TD + R[Sealed reference] --> D[Sealed definition] + D --> B[Sealed evidence] + A[Optional artifact digest] --> B + B --> F[Evaluation result] + D --> F + F --> P[Public projection] +``` + +A definition binds its criteria and composition, including authored order. Evidence binds the exact definition identity, optional artifact digest, observations and origin claims. The result carries definition and evidence lineage, policy and evaluator identity. + +A changed definition requires a new immutable revision. Corrected observations require a new evidence bundle. Older schemas are rejected; do not rehash old records as schema 4. + +## Trust boundary + +A caller can compute a valid digest for fabricated data. Authenticate the publisher and evidence producer independently, and authorize the exact definition and protected reference bundle before evaluation. Never treat a digest as a signature or as encryption. diff --git a/content/docs/assay/limits.mdx b/content/docs/assay/limits.mdx new file mode 100644 index 0000000..ad50fc3 --- /dev/null +++ b/content/docs/assay/limits.mdx @@ -0,0 +1,41 @@ +--- +title: "Limits" +description: "Find the exact bounded-input limits enforced by Assay schema 4." +--- + +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/security). + +The [release constants](https://github.com/0xbuffdev/assay/blob/v0.0.1/src/contracts/common.ts) are the source for this table. diff --git a/content/docs/assay/meta.json b/content/docs/assay/meta.json index bd08fb3..178fd95 100644 --- a/content/docs/assay/meta.json +++ b/content/docs/assay/meta.json @@ -1,8 +1,31 @@ { "title": "Assay", - "description": "Compare technical evidence against explicit, versioned criteria.", + "description": "Evaluate technical evidence against explicit, versioned criteria.", "root": true, "pages": [ - "index" + "index", + "installation", + "quickstart", + "concepts", + "---Evaluate---", + "criteria", + "composition", + "evidence", + "execution-facts", + "protected-references", + "observation-ports", + "qualitative-review", + "public-results", + "---Understand---", + "architecture", + "integrity", + "security", + "---Reference---", + "api", + "contracts", + "outcomes", + "limits", + "compatibility", + "troubleshooting" ] } diff --git a/content/docs/assay/observation-ports.mdx b/content/docs/assay/observation-ports.mdx new file mode 100644 index 0000000..0196705 --- /dev/null +++ b/content/docs/assay/observation-ports.mdx @@ -0,0 +1,125 @@ +--- +title: "Collect observations" +description: "Inject an optional host-owned adapter to collect eligible missing public facts." +--- + +Use `collectObservations` when your application can obtain observations through an adapter. The collector is asynchronous; the evaluator remains synchronous and does not require a port. + +## Implement a port + +The adapter implements `observe(request, signal?)` and returns a report. This example uses a fixture to show the contract without installing a runner or connecting a 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); +``` + +Expected output: `pass`. + +## Request and report + +The request contains schema version, definition lineage, optional artifact digest, capture limits and eligible missing public criterion IDs with their observation kinds. Units, item types, execution selectors or public assertion IDs are included when applicable. Expected values, reference IDs, restricted criteria and commands are never sent. + +The report echoes the definition identity and artifact scope, includes provenance and returns only requested observations. The provenance includes adapter and toolchain IDs and versions, run reference, captured stdout/stderr byte counts and both truncation flags. Their combined byte count is limited to 65,536. + +Report observations cannot include their own origins. For selected execution facts, echo the selector and provide a top-level termination state. The collector attaches the report scope to new observations and seals the combined bundle. + +## Handle the response + +| Response | Meaning | +| --- | --- | +| ok: true | Sealed evidence and receipt; receipt is null if no port was invoked. | +| invalid_definition | Definition failed validation or integrity verification. | +| invalid_evidence | Evidence, report or combined lineage was invalid. | +| OBSERVATION_PORT_ERROR | Adapter rejected or threw. | +| OBSERVATION_CANCELLED | Host cancellation occurred. | + +Existing observations retain their content and origin. The receipt identifies newly returned evidence references and the new digest. An empty report is legal but cannot satisfy a missing requirement. + +## Cancel acquisition + + +```ts +const controller = new AbortController(); +const pending = collectObservations(definition, evidence, port, { + signal: controller.signal, +}); +// Your application decides when to cancel: +controller.abort(); +const collected = await pending; +``` + +This fragment assumes valid records and a port. The signal is passed to the adapter. Valid pre-aborted input does not invoke it; cancellation during acquisition ignores late completion. No default timeout or retries are applied. Your application must terminate any actual running process. + +See the [record reference](/docs/assay/contracts) and [trust model](/docs/assay/security). The adapter is a source of claims, not a trusted execution service by virtue of its interface. diff --git a/content/docs/assay/outcomes.mdx b/content/docs/assay/outcomes.mdx new file mode 100644 index 0000000..0a406e2 --- /dev/null +++ b/content/docs/assay/outcomes.mdx @@ -0,0 +1,69 @@ +--- +title: "Outcomes and errors" +description: "Interpret technical outcomes, criterion reasons, warnings and validation failures." +--- + +## 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/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. + +See [troubleshooting](/docs/assay/troubleshooting) for recovery steps. diff --git a/content/docs/assay/protected-references.mdx b/content/docs/assay/protected-references.mdx new file mode 100644 index 0000000..1dff3ef --- /dev/null +++ b/content/docs/assay/protected-references.mdx @@ -0,0 +1,107 @@ +--- +title: "Use protected references" +description: "Store expected values separately and evaluate them through content-bound references." +--- + +Restricted objective criteria cannot contain literal expected values. Create a sealed reference record, bind its ID and digest into the criterion, and pass the record to the evaluator from an authorized environment. + +## Create a restricted comparison + +This complete example uses a fixture as the private expected value. Real protected answers belong in a store that the submitting user cannot access. + +```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: + +```text +pass withheld +``` + +Do not log the private outcome in a user-accessible environment. + +## Reference verification + +The bundle identifies the exact assessment, revision and revision digest. Each record must match its declared kind, ID and digest; numeric units and set item types must also agree. References may be absent. An absent required reference yields an inconclusive finding when its comparison is needed. + +A malformed, unknown, duplicate or substituted supplied record returns `invalid_reference` before evidence comparison. Verify separately with `verifyReferenceBundle(definition, references)` when storing or loading records. + +## Disclosure + +Keep the definition, references, evidence and full result in the trusted host. A digest of a low-entropy secret can be guessed; it is not encryption. See [content integrity](/docs/assay/integrity) and [public results](/docs/assay/public-results). diff --git a/content/docs/assay/public-results.mdx b/content/docs/assay/public-results.mdx new file mode 100644 index 0000000..53d3cde --- /dev/null +++ b/content/docs/assay/public-results.mdx @@ -0,0 +1,56 @@ +--- +title: "Project public results" +description: "Return a limited view of a technical result without exposing restricted findings." +--- + +Treat full evaluation results as private records. They contain criterion IDs, evidence references, reasons and an aggregate that can depend on protected checks. + +## Project a result + +After creating a verified definition and evaluating authorized evidence, call: + +```ts +const projected = projectPublicResult(definition, result); +if (!projected.ok) { + throw new Error("Public projection rejected"); +} +// Authorize the requesting user before returning projected.value. +``` + +This fragment assumes the API was imported and the records were created by the trusted host. + +A public result contains `schemaVersion`, `outcome` and `findings`. Each finding contains only the public criterion ID, its outcome and a finite public reason. + + +```json +{ + "schemaVersion": 4, + "outcome": "pass", + "findings": [ + { "criterionId": "voltage", "outcome": "pass", "reason": "match" } + ] +} +``` + +## Restricted criteria + +If any criterion is restricted, including an advisory criterion, the aggregate is always `withheld`. Restricted findings are omitted entirely. The projection does not disclose their count, values, evidence references or outcomes. + + +```mermaid +flowchart LR + F[Private full result] --> V[Verify correspondence] + D[Verified definition] --> V + V --> A[Select public findings] + A --> R[Public result] + A --> W[Withhold aggregate if restricted] + W --> R +``` + +## Rejection and authorization + +Projection rejects invalid definitions, invalid-input envelopes and inconsistent results with one opaque reason: `PUBLIC_PROJECTION_REJECTED`. It checks lineage, finding order, reason compatibility and recomputed composition and warning coherence. + +The function does not receive evidence, so it cannot authenticate the origin of a purported result. Only project results produced or verified in your trusted environment, and independently authorize the recipient. Repeated submissions, timing and other host feedback can leak information; keep those channels under host control. + +See [public reason codes](/docs/assay/outcomes) and [security and trust](/docs/assay/security). diff --git a/content/docs/assay/qualitative-review.mdx b/content/docs/assay/qualitative-review.mdx new file mode 100644 index 0000000..ad05dd2 --- /dev/null +++ b/content/docs/assay/qualitative-review.mdx @@ -0,0 +1,77 @@ +--- +title: "Record qualitative reviews" +description: "Attach artifact-bound advisory feedback from a human or model without changing binding outcomes." +--- + +Qualitative reviews record attributed feedback about an artifact. They can support a host-owned review workflow, but cannot establish a required pass or fail. Use manual evidence for work that requires a separate authorized decision. + +## Declare a review criterion + + +```ts +{ + id: "readability", + kind: "qualitative_review", + mode: "advisory", + visibility: "public", + parameters: { + reviewPolicyId: "code-review", + reviewPolicyVersion: "v1", + }, +} +``` + +Keep this criterion outside the required composition tree. + +## Supply a review + +The bundle must have an explicit artifact digest. The review's artifact origin must use that same digest and the policy fields must match the criterion. + +```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 }], +} +``` + +This fragment assumes `artifactDigest` is the host-computed digest of the reviewed artifact. Citation ranges are byte offsets with an exclusive end; verify them against the actual artifact. + +For a model reviewer, use this reviewer object: + +```ts +reviewer: { + kind: "model", + providerId: "provider", + modelId: "review-model", + modelVersion: "v1", + promptId: "code-review", + promptVersion: "v1", +} +``` + +Assay does not connect to a model provider. Your application obtains feedback, verifies provenance and supplies the observation. The optional observation port neither requests nor accepts qualitative review records. + +## Limits and outcomes + +Feedback must be nonempty inert text, at most 4,096 UTF-16 code units and UTF-8 bytes. Supply one to eight distinct citations with safe nonnegative byte offsets and start less than end. Uncertainty must be low, medium, high or unknown. Version identifiers cannot be the moving label latest. + +Absent, truncated and complete reviews all remain inconclusive, with reasons `EVIDENCE_MISSING`, `EVIDENCE_TRUNCATED` and `REVIEW_REQUIRED` respectively. Advisory unresolved findings do not affect the binding outcome. + +Review text, citations, attribution and uncertainty remain privileged evidence. [Public projection](/docs/assay/public-results) never copies them. Your application authorizes any separate disclosure. diff --git a/content/docs/assay/quickstart.mdx b/content/docs/assay/quickstart.mdx new file mode 100644 index 0000000..c5cf5bd --- /dev/null +++ b/content/docs/assay/quickstart.mdx @@ -0,0 +1,107 @@ +--- +title: "Evaluate your first result" +description: "Create a definition, seal a measurement and evaluate it with Assay." +--- + +This tutorial checks whether a measurement falls within an inclusive voltage range. You will create a criterion, provide the observed value and read the result. + +## Prerequisites + +Complete [installation](/docs/assay/installation). Use a file named `calibration.mjs` in your project. + +## Create and evaluate an assessment + +Copy the following example into the file. The measurement is a local fixture supplied by the caller; no hardware, runner or network service is needed. + +```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: + +```sh +node calibration.mjs +``` + +Expected output: + +```text +pass +``` + + +## Change the measurement + +Change the observation's `value` from 101 to 103 and remove the assertion that requires a pass. The output becomes `fail`. + +Restore the value and replace the observation array with an empty array. The outcome becomes `inconclusive`: there is no measurement to compare. + +If you change the unit from `mV` to `V`, evidence creation fails. Assay does not convert units. + +## What happened + +`createAssessmentDefinition` validates and seals the criteria. `createEvidenceBundle` binds the observation to that definition. `evaluate` verifies both records and compares the measurement. `projectPublicResult` constructs the limited result used in the example. + +The full evaluation record is for your application's private use. See [public results](/docs/assay/public-results) before returning findings from a service. + +Continue with [criteria](/docs/assay/criteria) and [composition](/docs/assay/composition) to evaluate other kinds of results. diff --git a/content/docs/assay/security.mdx b/content/docs/assay/security.mdx new file mode 100644 index 0000000..9592baa --- /dev/null +++ b/content/docs/assay/security.mdx @@ -0,0 +1,48 @@ +--- +title: "Security and trust" +description: "Identify the application responsibilities that remain outside Assay." +--- + +Assay performs bounded validation and technical comparison. Your application establishes authority over inputs, execution and disclosure. + +## Responsibilities + +| Assay | Host application | +| --- | --- | +| Validate closed record shapes and recompute content digests | Authenticate publishers, authorize definitions and verify artifact identity | +| Compare values and compose required outcomes | Run submitted code in an isolated environment and capture facts accurately | +| Validate adapter reports and provenance claims | Verify actual runner identity and provenance | +| Map findings to public fields | Authenticate recipients, enforce access policy and control repeated feedback | +| Record attributed qualitative review | Verify attribution, citations and any formal review decision | + +A technical pass does not award academic credit or a credential. + +## Place the trust boundary + + +```mermaid +flowchart TD + U[Untrusted submission] --> H[Host transport and authorization] + H --> I[Isolated runner or evidence producer] + I --> E[Host verifies evidence] + D[Authorized definition and private references] --> A[Assay in trusted host] + E --> A + A --> F[Private results and audit records] + F --> P[Public projection] + P --> G[Host access policy] + G --> U +``` + +Keep private expectations, full definitions and results away from the submitted program, public endpoints, prompts and user-accessible logs. Do not send protected references to a port. A valid digest proves content identity, not authenticity. + +## Accept untrusted input + +Enforce transport byte limits before buffering. Decode serialized JSON with `decodeSerializedRecord` before contract validation; it rejects duplicate keys and bounded-input violations. Prefer serialized records at trust boundaries. Do not pass adversarial live JavaScript Proxy objects: JavaScript cannot reliably inspect them without invoking traps. + +Validate and verify records in the trusted host. Treat diagnostics as private operational data even though they avoid raw values. Escape any captured text or feedback when rendering it. + +## Return findings + +Use [public projection](/docs/assay/public-results), then authorize disclosure. If even the existence of restricted checks must remain secret, design a fixed host response envelope rather than revealing the projection's withheld state. Limit repeated submissions and avoid timing or secondary-feedback channels that reveal private outcomes. + +Report security issues using the [security policy](https://github.com/0xbuffdev/assay/blob/v0.0.1/SECURITY.md). Do not publish private evidence or credentials in issue reports. diff --git a/content/docs/assay/troubleshooting.mdx b/content/docs/assay/troubleshooting.mdx new file mode 100644 index 0000000..30f6e50 --- /dev/null +++ b/content/docs/assay/troubleshooting.mdx @@ -0,0 +1,42 @@ +--- +title: "Troubleshooting" +description: "Diagnose invalid records, unresolved comparisons and rejected public projections." +--- + +Start with the returned outcome. Invalid input and a technical mismatch require different fixes. + +## Definition or evidence creation fails + +Inspect the diagnostic code and safe schema path in a trusted log. Check the schema version, required fields, criterion IDs, required composition and record limits. + +If evidence creation reports MISMATCHED_OBSERVATION, check the observation kind, numeric unit, selected execution fact and policy correspondence. Ensure the supplied definition is the one used to create the evidence. + +## Evaluation returns invalid_reference + +Verify that the bundle's definition matches the current assessment ID, revision and revision digest. Check each reference's ID, kind, digest, unit and item type. Unknown or duplicate records reject the entire supplied bundle. An omitted reference yields an inconclusive finding when needed. + +## Evaluation returns inconclusive + +Read the required leaf findings. Missing observations, truncated captures, missing references, interrupted executions and pending review can all cause an unresolved result. Use `inspectEvidenceCoverage` to find missing or incomplete required evidence; it does not calculate group outcomes. + +## Numeric comparison fails unexpectedly + +Check the declared expected value, absolute and relative tolerance, inclusive endpoints and exact unit. Convert units in your application before creating evidence. A nonfinite relative tolerance bound returns a numeric overflow error, not a mismatch. + +## Collection fails or does not call the port + +Confirm eligible public criteria are missing. Existing facts, restricted criteria and manual or qualitative reviews are not collection candidates. Verify that the returned report matches request lineage and scope, uses only requested IDs, and supplies the required provenance fields. + +For OBSERVATION_PORT_ERROR, inspect your adapter's private logs. For OBSERVATION_CANCELLED, check the host signal and termination handling. See [collection](/docs/assay/observation-ports). + +## Public outcome is withheld + +At least one criterion is restricted. This is expected even if all required public criteria pass. Do not reveal the private aggregate to work around withholding. + +## Public projection rejects a result + +Verify the exact authorized definition and use a complete result produced by `evaluate`. Do not modify finding order, reason codes, lineage, warnings or the aggregate. Projection rejects invalid-input failures and inconsistent records. + +## Report a reproducible problem + +Use the [issue tracker](https://github.com/0xbuffdev/assay/issues) with the package version, runtime version, a minimal synthetic reproduction and the outcome or diagnostic code. Remove private references, secrets and real learner evidence. Report security issues through the [security policy](https://github.com/0xbuffdev/assay/blob/v0.0.1/SECURITY.md). diff --git a/scripts/assay-docs.test.mjs b/scripts/assay-docs.test.mjs new file mode 100644 index 0000000..36cfd23 --- /dev/null +++ b/scripts/assay-docs.test.mjs @@ -0,0 +1,33 @@ +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.slice(0, 4), ["index", "installation", "quickstart", "concepts"]); + for (const slug of ["criteria", "composition", "evidence", "execution-facts", + "protected-references", "observation-ports", "qualitative-review", "public-results", + "architecture", "integrity", "security", "api", "contracts", "outcomes", + "limits", "compatibility", "troubleshooting"]) assert.ok(pages.has(slug), slug); +}); + +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..abe9d82 --- /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([ + ["installation.mdx", "4 v0.0.5"], + ["quickstart.mdx", "pass"], + ["execution-facts.mdx", "pass"], + ["protected-references.mdx", "pass withheld"], + ["observation-ports.mdx", "pass"], +]); +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, "limits.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)]; + 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), 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 }); +} From d1d8223e24be12f611e685edeed2d95fbad350b3 Mon Sep 17 00:00:00 2001 From: "Christopher S. Aondona" Date: Sat, 28 Nov 2026 16:32:15 +0100 Subject: [PATCH 2/2] Consolidate Assay documentation into six focused pages --- README.md | 2 +- content/docs/assay/api.mdx | 6 +- content/docs/assay/architecture.mdx | 61 ----- content/docs/assay/compatibility.mdx | 25 -- content/docs/assay/composition.mdx | 77 ------ content/docs/assay/concepts.mdx | 42 ---- content/docs/assay/contracts.mdx | 135 ++++++++++- content/docs/assay/criteria.mdx | 94 -------- content/docs/assay/evaluation.mdx | 188 +++++++++++++++ content/docs/assay/evidence.mdx | 43 ---- content/docs/assay/execution-facts.mdx | 85 ------- content/docs/assay/index.mdx | 61 +++-- content/docs/assay/installation.mdx | 60 ----- content/docs/assay/integrity.mdx | 153 +++++++++--- content/docs/assay/limits.mdx | 41 ---- content/docs/assay/meta.json | 23 +- content/docs/assay/observation-ports.mdx | 125 ---------- content/docs/assay/observations.mdx | 246 ++++++++++++++++++++ content/docs/assay/outcomes.mdx | 69 ------ content/docs/assay/protected-references.mdx | 107 --------- content/docs/assay/public-results.mdx | 56 ----- content/docs/assay/qualitative-review.mdx | 77 ------ content/docs/assay/quickstart.mdx | 107 --------- content/docs/assay/security.mdx | 48 ---- content/docs/assay/troubleshooting.mdx | 42 ---- scripts/assay-docs.test.mjs | 6 +- scripts/verify-assay-examples.mjs | 14 +- 27 files changed, 740 insertions(+), 1253 deletions(-) delete mode 100644 content/docs/assay/architecture.mdx delete mode 100644 content/docs/assay/compatibility.mdx delete mode 100644 content/docs/assay/composition.mdx delete mode 100644 content/docs/assay/concepts.mdx delete mode 100644 content/docs/assay/criteria.mdx create mode 100644 content/docs/assay/evaluation.mdx delete mode 100644 content/docs/assay/evidence.mdx delete mode 100644 content/docs/assay/execution-facts.mdx delete mode 100644 content/docs/assay/installation.mdx delete mode 100644 content/docs/assay/limits.mdx delete mode 100644 content/docs/assay/observation-ports.mdx create mode 100644 content/docs/assay/observations.mdx delete mode 100644 content/docs/assay/outcomes.mdx delete mode 100644 content/docs/assay/protected-references.mdx delete mode 100644 content/docs/assay/public-results.mdx delete mode 100644 content/docs/assay/qualitative-review.mdx delete mode 100644 content/docs/assay/quickstart.mdx delete mode 100644 content/docs/assay/security.mdx delete mode 100644 content/docs/assay/troubleshooting.mdx diff --git a/README.md b/README.md index 0b7b089..0daea3f 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ The shared tokens, fonts and base styles in `src/app.css` are synchronized from 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. -Organize pages by reader task. Start with installation and a complete tutorial, keep procedural guides separate from conceptual explanations, and maintain a reference for records, exported APIs, outcomes and limits. 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. +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. diff --git a/content/docs/assay/api.mdx b/content/docs/assay/api.mdx index 4ebf4f7..17d9444 100644 --- a/content/docs/assay/api.mdx +++ b/content/docs/assay/api.mdx @@ -13,7 +13,7 @@ Import from `@0xbuff/assay`. The package root is the supported import path. All | `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/outcomes). +`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 @@ -49,7 +49,7 @@ The first five return ValidationResult of their corresponding type. The decoder ## 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/observation-ports). +`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 @@ -57,7 +57,7 @@ The first five return ValidationResult of their corresponding type. The decoder | --- | --- | | ASSAY_SCHEMA_VERSION | 4 | | ASSAY_EVALUATOR_VERSION | v0.0.5 | -| CONTRACT_LIMITS | Frozen object containing the bounds listed in [limits](/docs/assay/limits). | +| CONTRACT_LIMITS | Frozen object containing the bounds listed in [limits](/docs/assay/contracts#resource-limits). | ## Return wrappers diff --git a/content/docs/assay/architecture.mdx b/content/docs/assay/architecture.mdx deleted file mode 100644 index 951ea9b..0000000 --- a/content/docs/assay/architecture.mdx +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "Architecture" -description: "Follow the validation, comparison, aggregation and projection pipeline." ---- - -Assay has a synchronous evaluation core and an optional asynchronous collector. The host decides when to call each operation. - -## Evaluation - -```mermaid -flowchart TD - D[Authorized definition] --> V[Verify definition] - V --> R[Verify supplied references] - X[Optional reference bundle] --> R - R --> B[Verify evidence and coverage] - I[Evidence bundle] --> B - B --> C[Compare all criteria] - C --> A[Compose required outcomes] - A --> F[Technical result] - V -. invalid .-> G[Diagnostic failure] - R -. invalid .-> G - B -. invalid .-> G - F --> P[Optional public projection] -``` - -Definition verification happens first, followed by verification of the entire supplied reference bundle and then the evidence. Invalid inputs return diagnostic failures without findings. Valid inputs reach comparators and the required composition engine. - -The public projection validates the definition and result correspondence, recomputes the aggregate and emits only permitted fields. It does not receive the evidence, so it cannot authenticate the evaluation. - -## Observation acquisition - -```mermaid -sequenceDiagram - participant H as Host - participant A as Assay collector - participant P as Host port - H->>A: Definition and existing evidence - A->>A: Verify inputs and select missing public facts - alt Eligible facts exist - A->>P: Bounded request - P-->>A: Report and claimed provenance - A->>A: Validate and seal combined evidence - end - A-->>H: Evidence and optional receipt - H->>H: Authorize use and call evaluate -``` - -No port is invoked when no eligible facts are missing. The collector never receives authority to run code by itself; the injected port is host-owned. - -## Source modules - -| Module | Responsibility | -| --- | --- | -| contracts | Versioned records and public types | -| validation | Bounded snapshots, structural checks and coverage | -| integrity | Canonical JSON and SHA-256 verification | -| evaluation | Comparison and group aggregation | -| observation | Optional fact acquisition | -| projection | Result correspondence and public field selection | - -The [release source](https://github.com/0xbuffdev/assay/tree/v0.0.1/src) contains the implementation. See [security and trust](/docs/assay/security) for responsibilities outside the library. diff --git a/content/docs/assay/compatibility.mdx b/content/docs/assay/compatibility.mdx deleted file mode 100644 index fdc765d..0000000 --- a/content/docs/assay/compatibility.mdx +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: "Versions and compatibility" -description: "Distinguish the released package version from schema, policy and evaluator identities." ---- - -| Identity | Current documented value | -| --- | --- | -| npm package | 0.0.1 | -| Schema | 4 | -| Evaluation semantics | v0.0.5 | -| Binding policy | composed-required-v1 | -| Runtime | Node.js 24 or later, ESM | -| License | Apache-2.0 | - -These pages describe the public release [v0.0.1](https://github.com/0xbuffdev/assay/releases/tag/v0.0.1), not unreleased work on main. The package ships TypeScript declarations and has no runtime dependencies. - -## Reproducibility - -Pin the package version and preserve your lockfile. Persist the authorized definition and evidence records with their digests, protected references when used, and evaluator identity. The package version identifies the distribution; the evaluator version identifies the supported finding semantics. - -## Unsupported records - -Older development schemas and policy identifiers are rejected. There is no runtime migration or automatic upgrade. Do not relabel or rehash an older record as schema 4. Preserve historical records and use the version that originally produced them, or create a newly authorized definition and evidence under the current contract. - -See the [changelog](https://github.com/0xbuffdev/assay/blob/v0.0.1/CHANGELOG.md) and [release policy](https://github.com/0xbuffdev/assay/blob/v0.0.1/docs/releasing.md) for changes and release procedures. diff --git a/content/docs/assay/composition.mdx b/content/docs/assay/composition.mdx deleted file mode 100644 index bef0a21..0000000 --- a/content/docs/assay/composition.mdx +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: "Compose required checks" -description: "Build explicit all and any groups to determine the required outcome." ---- - -A definition must contain at least one required criterion. The `composed-required-v1` policy combines required findings through a tree of groups. Advisory findings stay outside the tree. - -## Require all checks - -Use one `all` group for a definition whose required criteria are `output` and `status`. - -```ts -composition: { - rootGroupId: "root", - groups: [{ - id: "root", - operator: "all", - children: [ - { kind: "criterion", id: "output" }, - { kind: "criterion", id: "status" }, - ], - }], -} -``` - -## Allow alternatives - -Suppose an engineering exercise accepts either a JSON result or a text result, but also requires a status check. - - -```mermaid -flowchart TD - A[all: root] --> S[status] - A --> B[any: format] - B --> J[json-result] - B --> T[text-result] -``` - - -```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" }, - ], - }, - ], -} -``` - -Each ID names a declared required criterion or group. Groups must be reachable from the root, with no cycles or shared subtrees. Each required leaf appears once; advisory leaves cannot appear. - -## How groups resolve - -Read each row from left to right. The first applicable condition determines the group outcome. - -| Operator | First | Then | Then | 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 | - -All criteria are validated and evaluated in authored order, even if an alternative already determines the aggregate. Invalid input anywhere rejects the evaluation before comparison. Missing leaves may be acceptable in an alternative whose other leaf passes, but missing evidence never passes on its own. - -Group limits are listed in [limits](/docs/assay/limits). Changing composition or authored order changes the definition digest. diff --git a/content/docs/assay/concepts.mdx b/content/docs/assay/concepts.mdx deleted file mode 100644 index a10ca16..0000000 --- a/content/docs/assay/concepts.mdx +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: "Core concepts" -description: "Understand the records, identities and outcomes that make up an Assay evaluation." ---- - -## Records - -| Record | Purpose | -| --- | --- | -| Assessment definition | Versioned criteria and the required composition tree. | -| Criterion | One comparison or review requirement, with an ID, mode and visibility. | -| Observation | A typed fact supplied by the host for a criterion. | -| Evidence bundle | Observations sealed to a particular definition, optionally scoped to an artifact. | -| Reference record | A separately stored expected value identified by a digest. | -| Evaluation result | Private technical findings and the composed outcome. | -| Public result | A restricted view derived from a valid definition and result. | - -A definition describes what should hold; evidence describes what was observed. Keep these inputs separate. A reference value is an expectation, never an observation. - -## Criterion mode and visibility - -Required criteria participate in the composition tree. Advisory criteria produce findings without determining the root outcome. - -Public criteria may appear in a projected result. Restricted criteria never appear there, and even a restricted advisory criterion causes the public aggregate to be withheld. Restricted objective criteria must refer to protected expected values instead of embedding literals. - -## Evidence states - -An observation is either `complete` or `truncated`. Missing observations are represented by their absence, not placeholder values. A measured zero, empty string, false or JSON null can be a valid complete observation. - -## Evaluation lifecycle - -```mermaid -flowchart LR - D[Definition] --> E[Evaluate] - B[Evidence bundle] --> E - R[Optional references] --> E - E --> F[Technical result] - F --> P[Public projection] - F --> H[Host decision] -``` - -The evaluator returns pass, fail, inconclusive or evaluation error for complete results. Invalid inputs return a separate diagnostic envelope. See [outcomes and reasons](/docs/assay/outcomes) for the distinction. diff --git a/content/docs/assay/contracts.mdx b/content/docs/assay/contracts.mdx index 6a35da2..10e945f 100644 --- a/content/docs/assay/contracts.mdx +++ b/content/docs/assay/contracts.mdx @@ -1,6 +1,6 @@ --- -title: "Record reference" -description: "Look up the fields of definitions, evidence, references and evaluation records." +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. @@ -36,9 +36,9 @@ All criteria have `id: string`, `kind`, `mode: "required" | "advisory"`, `visibi | 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/criteria) for value types and rules. +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/composition). +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 @@ -67,7 +67,7 @@ Common fields are criterionId, evidenceRef, kind and completeness (complete or t | 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/evidence), [execution facts](/docs/assay/execution-facts) and [qualitative reviews](/docs/assay/qualitative-review). +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 @@ -85,7 +85,7 @@ An invalid-input failure has outcome and diagnostics only. Do not assume that de 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/observation-ports). +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 @@ -95,6 +95,127 @@ Report fields: schemaVersion, definition, optional artifactDigest, provenance, o | 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/public-results). +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/criteria.mdx b/content/docs/assay/criteria.mdx deleted file mode 100644 index 79856fc..0000000 --- a/content/docs/assay/criteria.mdx +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: "Define criteria" -description: "Choose a comparison kind and declare the exact comparison parameters." ---- - -Every criterion requires `id`, `kind`, `mode`, `visibility` and `parameters`. Include each required criterion exactly once in the [composition tree](/docs/assay/composition). - -## Choose a comparator - -| Kind | Observation | Expected value and parameters | -| --- | --- | --- | -| `exact_text` | text | String; exact equality | -| `normalized_text` | text | String; explicit normalization | -| `number_with_tolerance` | number | Number; absolute and relative tolerance; optional unit | -| `number_range` | number | Range; both endpoint flags; optional unit | -| `set_equivalence` | set | Scalar array; item type, order and duplicate policies | -| `boolean_equality` | boolean | Boolean | -| `json_equality` | json | JSON value | -| `observed_execution` | execution | Assertion IDs and reference IDs | -| `manual_evidence` | manual | Review required | -| `qualitative_review` | qualitative review | Review policy ID and version; advisory only | - -The first seven are objective comparisons. They accept a literal or a content-bound reference as `parameters.expected`. The remaining kinds report unresolved evidence rather than asserting correctness. - -## Text - -Exact text compares JavaScript UTF-16 code units, including whitespace and line endings. Choose normalized text when differences in formatting are irrelevant. - -Example criterion (a fragment of a definition): - -```ts -{ - id: "message", - kind: "normalized_text", - mode: "required", - visibility: "public", - parameters: { - expected: { type: "literal", value: "hello world" }, - normalization: { - lineEndings: "lf", - case: "fold", - unicode: "NFC", - whitespace: "collapse", - trim: "both", - }, - }, -} -``` - -Both values undergo the same transformations in this order: line endings, case, Unicode normalization, whitespace, trim. Each choice is explicit. Case folding uses JavaScript lowercase conversion; it does not equate German sharp S with two s characters. - -## Numbers - -For tolerance comparisons, the allowed difference is the greater of the absolute tolerance and the relative tolerance multiplied by the magnitude of the expected value. The boundary is inclusive. - -For example, with expected value 100, absolute tolerance 2 and relative tolerance 0.05, the bound is 5. An observation of 105 passes; 106 fails. - - -```ts -parameters: { - expected: { type: "literal", value: 100 }, - tolerance: { absolute: 2, relative: 0.05 }, - unit: "mV", -} -``` - -For ranges, supply finite `min`, `max`, `minInclusive` and `maxInclusive`. Equal endpoints are valid only when both are inclusive. A numeric observation must use the exact declared unit, or omit it if the criterion has no unit. Assay uses JavaScript numbers and does not coerce strings or convert units. - -## Sets - -Declare `itemType` as string, number or boolean. The observation uses `items`, not `value`. - - -```ts -parameters: { - expected: { type: "literal", value: ["read", "write"] }, - itemType: "string", - order: "ignore", - duplicates: "ignore", -} -``` - -| Order | Duplicates | Comparison | -| --- | --- | --- | -| ignore | ignore | Membership | -| ignore | respect | Multiset counts | -| preserve | ignore | Sequence of first occurrences | -| preserve | respect | Exact sequence | - -## Booleans and JSON - -Boolean comparisons accept only true or false. JSON equality ignores object key order but preserves array order. Strings and object keys remain exact. Negative zero equals zero. JSON null is a valid expected value. - -For the complete parameter and observation contracts, see [record reference](/docs/assay/contracts). 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/evidence.mdx b/content/docs/assay/evidence.mdx deleted file mode 100644 index edea7b6..0000000 --- a/content/docs/assay/evidence.mdx +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: "Supply evidence" -description: "Create immutable evidence bundles and handle missing, truncated and artifact-scoped observations." ---- - -Use `createEvidenceBundle(definition, draft)` to bind observations to the exact definition. The draft accepts `schemaVersion`, `observations` and optional `artifactDigest`. Assay derives the definition lineage and evidence digest. - -## Observation fields - -Every observation has a criterion ID, unique evidence reference, kind and completeness. The value fields depend on the kind. See [record reference](/docs/assay/contracts). - -For a text criterion named output: - -```ts -const prepared = createEvidenceBundle(definition, { - schemaVersion: 4, - observations: [{ - criterionId: "output", - evidenceRef: "capture-1", - kind: "text", - completeness: "complete", - value: "ok", - }], -}); -``` - -This fragment assumes you imported the creator and sealed a matching definition. A successful result exposes `prepared.value`. Handle failure before using it. - -## Missing and incomplete evidence - -Omit observations for unavailable facts. Mark partial captures as truncated. Do not substitute a fabricated empty string or zero. Use `inspectEvidenceCoverage(definition, evidence)` to list missing and incomplete required criteria; it performs no comparison and does not account for alternative group outcomes. - -## Bind evidence to an artifact - -Set an explicit bundle artifact digest when associating evidence with an artifact. Every observation in a scoped bundle must declare an origin. An artifact origin carries the exact bundle digest and a source reference; an independent origin has a source reference but no artifact digest. Unscoped observations may omit origin, but cannot claim artifact scope. - -Selected execution observations also require run reference and termination. See [execution facts](/docs/assay/execution-facts). - -## Verify and correct - -Use `verifyEvidenceBundle(definition, evidence)` to recompute the digest and check lineage. Create a new sealed bundle for corrections rather than editing existing records. Keep the original bundle if you need an audit history. - -Assay validates consistency of the claims; your application must verify the actual source and artifact. diff --git a/content/docs/assay/execution-facts.mdx b/content/docs/assay/execution-facts.mdx deleted file mode 100644 index 47502c0..0000000 --- a/content/docs/assay/execution-facts.mdx +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: "Evaluate execution facts" -description: "Compare captured output, exit status and other typed facts supplied by a runner." ---- - -Your application runs the program, captures its output and supplies the observations. Assay compares these facts using the same objective comparators as other evidence. - -## Select a fact - -Set `executionFact` on the criterion and the corresponding 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 | - -An exit status must be a signed safe integer without a unit. A Boolean property is identified by its criterion ID. Structured stream values are JSON supplied by your application; Assay does not parse captured stdout for you. - -## Evaluate captured output - -The following example uses a fixture for stdout. In production, obtain the value and termination state from your 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); -``` - -## Interrupted or incomplete runs - -A timeout or crash produces an inconclusive finding for selected facts. Truncated captures use `EVIDENCE_TRUNCATED` first. The evaluator does not invent an exit status or output value when one is unavailable. - -For the same source and run, complete observations of the same selected stream or exit status must agree. Known stream truncation invalidates contradictory complete claims, even if an observation omits provenance. Stdout and stderr truncation are tracked separately. Exit status does not depend on stream capture. - -The older assertion-shaped `observed_execution` criterion remains inconclusive even when an assertion claims confirmation. Use selected objective facts to compare actual values. - -See [observation ports](/docs/assay/observation-ports) for optional acquisition and [host security responsibilities](/docs/assay/security) for execution isolation. diff --git a/content/docs/assay/index.mdx b/content/docs/assay/index.mdx index ee467e8..e47dcc6 100644 --- a/content/docs/assay/index.mdx +++ b/content/docs/assay/index.mdx @@ -1,32 +1,51 @@ --- -title: "Assay" -description: "Evaluate technical evidence against versioned criteria and return reproducible findings." +title: "Installation" +description: "Install Assay and start evaluating technical evidence." --- -Assay evaluates technical evidence against criteria defined by your application. Use it to check engineering exercises, measurement results, structured outputs and other technical work. +Assay evaluates technical evidence against versioned criteria. It runs offline, has no runtime dependencies, and leaves execution, authorization and decisions to your application. -You supply the criteria and observations. Assay validates the records, compares the observed values and combines required checks into an outcome. It runs offline without runtime dependencies. +## Requirements -## Get started +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 Assay](/docs/assay/installation) in a Node.js application. -- [Evaluate your first result](/docs/assay/quickstart) with a complete example. -- [Understand definitions, evidence and findings](/docs/assay/concepts) before integrating the evaluator. +## Install -## What you can do +```sh +npm install @0xbuff/assay@0.0.1 +``` -| Task | Guide | -| --- | --- | -| Compare text, measurements, sets and JSON | [Define criteria](/docs/assay/criteria) | -| Require several checks or allow alternatives | [Compose required checks](/docs/assay/composition) | -| Evaluate results from an external runner | [Evaluate execution facts](/docs/assay/execution-facts) | -| Collect missing public observations through an adapter | [Collect observations](/docs/assay/observation-ports) | -| Use private expected values | [Use protected references](/docs/assay/protected-references) | -| Attach human or model feedback | [Record qualitative reviews](/docs/assay/qualitative-review) | -| Return a limited result to a user | [Project public results](/docs/assay/public-results) | +```sh +pnpm add @0xbuff/assay@0.0.1 +``` -## Scope +```sh +yarn add @0xbuff/assay@0.0.1 +``` -Assay does not run submitted code, authenticate observations, assign grades or issue credentials. Your application owns execution, authorization and any decision based on the findings. Read the [security and trust model](/docs/assay/security) before accepting untrusted evidence or returning results to users. +## Verify the installation -These pages describe package version `0.0.1`. See the [source repository](https://github.com/0xbuffdev/assay), [release notes](https://github.com/0xbuffdev/assay/releases/tag/v0.0.1) and [Apache-2.0 license](https://github.com/0xbuffdev/assay/blob/v0.0.1/LICENSE). +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/installation.mdx b/content/docs/assay/installation.mdx deleted file mode 100644 index 886726c..0000000 --- a/content/docs/assay/installation.mdx +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Installation" -description: "Install the released Assay package and configure an ESM application." ---- - -## Requirements - -- Node.js 24 or later. -- An ECMAScript module (ESM) application. Use a file ending in `.mjs`, or set `"type": "module"` in your package.json. -- A package manager with access to the public npm registry. - -Assay has no runtime dependencies. TypeScript declarations ship with the package; you do not need a separate types package. - -## Install - -Use one of these commands: - -```sh -npm install @0xbuff/assay@0.0.1 -``` - - -```sh -pnpm add @0xbuff/assay@0.0.1 -``` - - -```sh -yarn add @0xbuff/assay@0.0.1 -``` - -Pin the release and commit your lockfile when reproducibility matters. - -## Verify the installation - -Create `check.mjs`: - -```js -// assay-docs: runnable -import { ASSAY_SCHEMA_VERSION, ASSAY_EVALUATOR_VERSION } from "@0xbuff/assay"; - -console.log(ASSAY_SCHEMA_VERSION, ASSAY_EVALUATOR_VERSION); -``` - - -```sh -node check.mjs -``` - -Expected output: - -```text -4 v0.0.5 -``` - -The package, schema and evaluator versions identify different things. See [versions and compatibility](/docs/assay/compatibility). - -## Next step - -[Evaluate a measurement](/docs/assay/quickstart) using the installed package. diff --git a/content/docs/assay/integrity.mdx b/content/docs/assay/integrity.mdx index 56fa02a..e9cfa33 100644 --- a/content/docs/assay/integrity.mdx +++ b/content/docs/assay/integrity.mdx @@ -1,51 +1,144 @@ --- -title: "Content integrity" -description: "Understand canonical digests, immutable revisions and evidence lineage." +title: "Integrity and security" +description: "Verify record identity, use protected expectations and control disclosure." --- -Assay seals definitions, references and evidence using SHA-256 over canonical JSON. Digests identify content; they do not identify or authenticate its publisher. +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. -## Seal and verify records +## Content integrity -| Record | Create | Verify | -| --- | --- | --- | -| Definition | createAssessmentDefinition | verifyAssessmentDefinition | -| Reference | createReferenceRecord | verifyReferenceBundle | -| Evidence | createEvidenceBundle | verifyEvidenceBundle | +Definitions, references and evidence use separate schema-4 canonical domains. -`computeDefinitionDigest(draft)` computes the definition digest without creating a sealed record. The creation helpers validate unsigned drafts and derive digests. Do not supply digest fields in drafts. +| 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 | -## Canonical profile +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:`. -Schema 4 uses separate domains: +```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] +``` -| Record | Domain | Omitted field | -| --- | --- | --- | -| Definition | assay:definition:v4 | revisionDigest | -| Reference | assay:reference:v4 | referenceDigest | -| Evidence | assay:evidence:v4 | evidenceDigest | +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. -After closed-contract validation, Assay sorts object keys by ECMAScript UTF-16 code-unit order and serializes compact JSON. Array order is retained, strings are not normalized, optional absent fields remain absent and negative zero serializes as zero. The UTF-8 bytes are the domain, one LF, then canonical JSON with no trailing LF. Hash the bytes using SHA-256 and prefix lowercase hexadecimal with `sha256:`. +## Public projection -The [release integrity vectors](https://github.com/0xbuffdev/assay/blob/v0.0.1/docs/integrity.md) provide independent test inputs and expected digests. +`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. -## Preserve lineage +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 - R[Sealed reference] --> D[Sealed definition] - D --> B[Sealed evidence] - A[Optional artifact digest] --> B - B --> F[Evaluation result] - D --> F + 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 ``` -A definition binds its criteria and composition, including authored order. Evidence binds the exact definition identity, optional artifact digest, observations and origin claims. The result carries definition and evidence lineage, policy and evaluator identity. - -A changed definition requires a new immutable revision. Corrected observations require a new evidence bundle. Older schemas are rejected; do not rehash old records as schema 4. +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. -## Trust boundary +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. -A caller can compute a valid digest for fabricated data. Authenticate the publisher and evidence producer independently, and authorize the exact definition and protected reference bundle before evaluation. Never treat a digest as a signature or as encryption. +Report vulnerabilities through the [security policy](https://github.com/0xbuffdev/assay/blob/v0.0.1/SECURITY.md). diff --git a/content/docs/assay/limits.mdx b/content/docs/assay/limits.mdx deleted file mode 100644 index ad50fc3..0000000 --- a/content/docs/assay/limits.mdx +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: "Limits" -description: "Find the exact bounded-input limits enforced by Assay schema 4." ---- - -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/security). - -The [release constants](https://github.com/0xbuffdev/assay/blob/v0.0.1/src/contracts/common.ts) are the source for this table. diff --git a/content/docs/assay/meta.json b/content/docs/assay/meta.json index 178fd95..9798eb5 100644 --- a/content/docs/assay/meta.json +++ b/content/docs/assay/meta.json @@ -4,28 +4,11 @@ "root": true, "pages": [ "index", - "installation", - "quickstart", - "concepts", - "---Evaluate---", - "criteria", - "composition", - "evidence", - "execution-facts", - "protected-references", - "observation-ports", - "qualitative-review", - "public-results", - "---Understand---", - "architecture", + "evaluation", + "observations", "integrity", - "security", "---Reference---", "api", - "contracts", - "outcomes", - "limits", - "compatibility", - "troubleshooting" + "contracts" ] } diff --git a/content/docs/assay/observation-ports.mdx b/content/docs/assay/observation-ports.mdx deleted file mode 100644 index 0196705..0000000 --- a/content/docs/assay/observation-ports.mdx +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: "Collect observations" -description: "Inject an optional host-owned adapter to collect eligible missing public facts." ---- - -Use `collectObservations` when your application can obtain observations through an adapter. The collector is asynchronous; the evaluator remains synchronous and does not require a port. - -## Implement a port - -The adapter implements `observe(request, signal?)` and returns a report. This example uses a fixture to show the contract without installing a runner or connecting a 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); -``` - -Expected output: `pass`. - -## Request and report - -The request contains schema version, definition lineage, optional artifact digest, capture limits and eligible missing public criterion IDs with their observation kinds. Units, item types, execution selectors or public assertion IDs are included when applicable. Expected values, reference IDs, restricted criteria and commands are never sent. - -The report echoes the definition identity and artifact scope, includes provenance and returns only requested observations. The provenance includes adapter and toolchain IDs and versions, run reference, captured stdout/stderr byte counts and both truncation flags. Their combined byte count is limited to 65,536. - -Report observations cannot include their own origins. For selected execution facts, echo the selector and provide a top-level termination state. The collector attaches the report scope to new observations and seals the combined bundle. - -## Handle the response - -| Response | Meaning | -| --- | --- | -| ok: true | Sealed evidence and receipt; receipt is null if no port was invoked. | -| invalid_definition | Definition failed validation or integrity verification. | -| invalid_evidence | Evidence, report or combined lineage was invalid. | -| OBSERVATION_PORT_ERROR | Adapter rejected or threw. | -| OBSERVATION_CANCELLED | Host cancellation occurred. | - -Existing observations retain their content and origin. The receipt identifies newly returned evidence references and the new digest. An empty report is legal but cannot satisfy a missing requirement. - -## Cancel acquisition - - -```ts -const controller = new AbortController(); -const pending = collectObservations(definition, evidence, port, { - signal: controller.signal, -}); -// Your application decides when to cancel: -controller.abort(); -const collected = await pending; -``` - -This fragment assumes valid records and a port. The signal is passed to the adapter. Valid pre-aborted input does not invoke it; cancellation during acquisition ignores late completion. No default timeout or retries are applied. Your application must terminate any actual running process. - -See the [record reference](/docs/assay/contracts) and [trust model](/docs/assay/security). The adapter is a source of claims, not a trusted execution service by virtue of its interface. 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/content/docs/assay/outcomes.mdx b/content/docs/assay/outcomes.mdx deleted file mode 100644 index 0a406e2..0000000 --- a/content/docs/assay/outcomes.mdx +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: "Outcomes and errors" -description: "Interpret technical outcomes, criterion reasons, warnings and validation failures." ---- - -## 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/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. - -See [troubleshooting](/docs/assay/troubleshooting) for recovery steps. diff --git a/content/docs/assay/protected-references.mdx b/content/docs/assay/protected-references.mdx deleted file mode 100644 index 1dff3ef..0000000 --- a/content/docs/assay/protected-references.mdx +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: "Use protected references" -description: "Store expected values separately and evaluate them through content-bound references." ---- - -Restricted objective criteria cannot contain literal expected values. Create a sealed reference record, bind its ID and digest into the criterion, and pass the record to the evaluator from an authorized environment. - -## Create a restricted comparison - -This complete example uses a fixture as the private expected value. Real protected answers belong in a store that the submitting user cannot access. - -```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: - -```text -pass withheld -``` - -Do not log the private outcome in a user-accessible environment. - -## Reference verification - -The bundle identifies the exact assessment, revision and revision digest. Each record must match its declared kind, ID and digest; numeric units and set item types must also agree. References may be absent. An absent required reference yields an inconclusive finding when its comparison is needed. - -A malformed, unknown, duplicate or substituted supplied record returns `invalid_reference` before evidence comparison. Verify separately with `verifyReferenceBundle(definition, references)` when storing or loading records. - -## Disclosure - -Keep the definition, references, evidence and full result in the trusted host. A digest of a low-entropy secret can be guessed; it is not encryption. See [content integrity](/docs/assay/integrity) and [public results](/docs/assay/public-results). diff --git a/content/docs/assay/public-results.mdx b/content/docs/assay/public-results.mdx deleted file mode 100644 index 53d3cde..0000000 --- a/content/docs/assay/public-results.mdx +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: "Project public results" -description: "Return a limited view of a technical result without exposing restricted findings." ---- - -Treat full evaluation results as private records. They contain criterion IDs, evidence references, reasons and an aggregate that can depend on protected checks. - -## Project a result - -After creating a verified definition and evaluating authorized evidence, call: - -```ts -const projected = projectPublicResult(definition, result); -if (!projected.ok) { - throw new Error("Public projection rejected"); -} -// Authorize the requesting user before returning projected.value. -``` - -This fragment assumes the API was imported and the records were created by the trusted host. - -A public result contains `schemaVersion`, `outcome` and `findings`. Each finding contains only the public criterion ID, its outcome and a finite public reason. - - -```json -{ - "schemaVersion": 4, - "outcome": "pass", - "findings": [ - { "criterionId": "voltage", "outcome": "pass", "reason": "match" } - ] -} -``` - -## Restricted criteria - -If any criterion is restricted, including an advisory criterion, the aggregate is always `withheld`. Restricted findings are omitted entirely. The projection does not disclose their count, values, evidence references or outcomes. - - -```mermaid -flowchart LR - F[Private full result] --> V[Verify correspondence] - D[Verified definition] --> V - V --> A[Select public findings] - A --> R[Public result] - A --> W[Withhold aggregate if restricted] - W --> R -``` - -## Rejection and authorization - -Projection rejects invalid definitions, invalid-input envelopes and inconsistent results with one opaque reason: `PUBLIC_PROJECTION_REJECTED`. It checks lineage, finding order, reason compatibility and recomputed composition and warning coherence. - -The function does not receive evidence, so it cannot authenticate the origin of a purported result. Only project results produced or verified in your trusted environment, and independently authorize the recipient. Repeated submissions, timing and other host feedback can leak information; keep those channels under host control. - -See [public reason codes](/docs/assay/outcomes) and [security and trust](/docs/assay/security). diff --git a/content/docs/assay/qualitative-review.mdx b/content/docs/assay/qualitative-review.mdx deleted file mode 100644 index ad05dd2..0000000 --- a/content/docs/assay/qualitative-review.mdx +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: "Record qualitative reviews" -description: "Attach artifact-bound advisory feedback from a human or model without changing binding outcomes." ---- - -Qualitative reviews record attributed feedback about an artifact. They can support a host-owned review workflow, but cannot establish a required pass or fail. Use manual evidence for work that requires a separate authorized decision. - -## Declare a review criterion - - -```ts -{ - id: "readability", - kind: "qualitative_review", - mode: "advisory", - visibility: "public", - parameters: { - reviewPolicyId: "code-review", - reviewPolicyVersion: "v1", - }, -} -``` - -Keep this criterion outside the required composition tree. - -## Supply a review - -The bundle must have an explicit artifact digest. The review's artifact origin must use that same digest and the policy fields must match the criterion. - -```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 }], -} -``` - -This fragment assumes `artifactDigest` is the host-computed digest of the reviewed artifact. Citation ranges are byte offsets with an exclusive end; verify them against the actual artifact. - -For a model reviewer, use this reviewer object: - -```ts -reviewer: { - kind: "model", - providerId: "provider", - modelId: "review-model", - modelVersion: "v1", - promptId: "code-review", - promptVersion: "v1", -} -``` - -Assay does not connect to a model provider. Your application obtains feedback, verifies provenance and supplies the observation. The optional observation port neither requests nor accepts qualitative review records. - -## Limits and outcomes - -Feedback must be nonempty inert text, at most 4,096 UTF-16 code units and UTF-8 bytes. Supply one to eight distinct citations with safe nonnegative byte offsets and start less than end. Uncertainty must be low, medium, high or unknown. Version identifiers cannot be the moving label latest. - -Absent, truncated and complete reviews all remain inconclusive, with reasons `EVIDENCE_MISSING`, `EVIDENCE_TRUNCATED` and `REVIEW_REQUIRED` respectively. Advisory unresolved findings do not affect the binding outcome. - -Review text, citations, attribution and uncertainty remain privileged evidence. [Public projection](/docs/assay/public-results) never copies them. Your application authorizes any separate disclosure. diff --git a/content/docs/assay/quickstart.mdx b/content/docs/assay/quickstart.mdx deleted file mode 100644 index c5cf5bd..0000000 --- a/content/docs/assay/quickstart.mdx +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: "Evaluate your first result" -description: "Create a definition, seal a measurement and evaluate it with Assay." ---- - -This tutorial checks whether a measurement falls within an inclusive voltage range. You will create a criterion, provide the observed value and read the result. - -## Prerequisites - -Complete [installation](/docs/assay/installation). Use a file named `calibration.mjs` in your project. - -## Create and evaluate an assessment - -Copy the following example into the file. The measurement is a local fixture supplied by the caller; no hardware, runner or network service is needed. - -```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: - -```sh -node calibration.mjs -``` - -Expected output: - -```text -pass -``` - - -## Change the measurement - -Change the observation's `value` from 101 to 103 and remove the assertion that requires a pass. The output becomes `fail`. - -Restore the value and replace the observation array with an empty array. The outcome becomes `inconclusive`: there is no measurement to compare. - -If you change the unit from `mV` to `V`, evidence creation fails. Assay does not convert units. - -## What happened - -`createAssessmentDefinition` validates and seals the criteria. `createEvidenceBundle` binds the observation to that definition. `evaluate` verifies both records and compares the measurement. `projectPublicResult` constructs the limited result used in the example. - -The full evaluation record is for your application's private use. See [public results](/docs/assay/public-results) before returning findings from a service. - -Continue with [criteria](/docs/assay/criteria) and [composition](/docs/assay/composition) to evaluate other kinds of results. diff --git a/content/docs/assay/security.mdx b/content/docs/assay/security.mdx deleted file mode 100644 index 9592baa..0000000 --- a/content/docs/assay/security.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: "Security and trust" -description: "Identify the application responsibilities that remain outside Assay." ---- - -Assay performs bounded validation and technical comparison. Your application establishes authority over inputs, execution and disclosure. - -## Responsibilities - -| Assay | Host application | -| --- | --- | -| Validate closed record shapes and recompute content digests | Authenticate publishers, authorize definitions and verify artifact identity | -| Compare values and compose required outcomes | Run submitted code in an isolated environment and capture facts accurately | -| Validate adapter reports and provenance claims | Verify actual runner identity and provenance | -| Map findings to public fields | Authenticate recipients, enforce access policy and control repeated feedback | -| Record attributed qualitative review | Verify attribution, citations and any formal review decision | - -A technical pass does not award academic credit or a credential. - -## Place the trust boundary - - -```mermaid -flowchart TD - U[Untrusted submission] --> H[Host transport and authorization] - H --> I[Isolated runner or evidence producer] - I --> E[Host verifies evidence] - D[Authorized definition and private references] --> A[Assay in trusted host] - E --> A - A --> F[Private results and audit records] - F --> P[Public projection] - P --> G[Host access policy] - G --> U -``` - -Keep private expectations, full definitions and results away from the submitted program, public endpoints, prompts and user-accessible logs. Do not send protected references to a port. A valid digest proves content identity, not authenticity. - -## Accept untrusted input - -Enforce transport byte limits before buffering. Decode serialized JSON with `decodeSerializedRecord` before contract validation; it rejects duplicate keys and bounded-input violations. Prefer serialized records at trust boundaries. Do not pass adversarial live JavaScript Proxy objects: JavaScript cannot reliably inspect them without invoking traps. - -Validate and verify records in the trusted host. Treat diagnostics as private operational data even though they avoid raw values. Escape any captured text or feedback when rendering it. - -## Return findings - -Use [public projection](/docs/assay/public-results), then authorize disclosure. If even the existence of restricted checks must remain secret, design a fixed host response envelope rather than revealing the projection's withheld state. Limit repeated submissions and avoid timing or secondary-feedback channels that reveal private outcomes. - -Report security issues using the [security policy](https://github.com/0xbuffdev/assay/blob/v0.0.1/SECURITY.md). Do not publish private evidence or credentials in issue reports. diff --git a/content/docs/assay/troubleshooting.mdx b/content/docs/assay/troubleshooting.mdx deleted file mode 100644 index 30f6e50..0000000 --- a/content/docs/assay/troubleshooting.mdx +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: "Troubleshooting" -description: "Diagnose invalid records, unresolved comparisons and rejected public projections." ---- - -Start with the returned outcome. Invalid input and a technical mismatch require different fixes. - -## Definition or evidence creation fails - -Inspect the diagnostic code and safe schema path in a trusted log. Check the schema version, required fields, criterion IDs, required composition and record limits. - -If evidence creation reports MISMATCHED_OBSERVATION, check the observation kind, numeric unit, selected execution fact and policy correspondence. Ensure the supplied definition is the one used to create the evidence. - -## Evaluation returns invalid_reference - -Verify that the bundle's definition matches the current assessment ID, revision and revision digest. Check each reference's ID, kind, digest, unit and item type. Unknown or duplicate records reject the entire supplied bundle. An omitted reference yields an inconclusive finding when needed. - -## Evaluation returns inconclusive - -Read the required leaf findings. Missing observations, truncated captures, missing references, interrupted executions and pending review can all cause an unresolved result. Use `inspectEvidenceCoverage` to find missing or incomplete required evidence; it does not calculate group outcomes. - -## Numeric comparison fails unexpectedly - -Check the declared expected value, absolute and relative tolerance, inclusive endpoints and exact unit. Convert units in your application before creating evidence. A nonfinite relative tolerance bound returns a numeric overflow error, not a mismatch. - -## Collection fails or does not call the port - -Confirm eligible public criteria are missing. Existing facts, restricted criteria and manual or qualitative reviews are not collection candidates. Verify that the returned report matches request lineage and scope, uses only requested IDs, and supplies the required provenance fields. - -For OBSERVATION_PORT_ERROR, inspect your adapter's private logs. For OBSERVATION_CANCELLED, check the host signal and termination handling. See [collection](/docs/assay/observation-ports). - -## Public outcome is withheld - -At least one criterion is restricted. This is expected even if all required public criteria pass. Do not reveal the private aggregate to work around withholding. - -## Public projection rejects a result - -Verify the exact authorized definition and use a complete result produced by `evaluate`. Do not modify finding order, reason codes, lineage, warnings or the aggregate. Projection rejects invalid-input failures and inconsistent records. - -## Report a reproducible problem - -Use the [issue tracker](https://github.com/0xbuffdev/assay/issues) with the package version, runtime version, a minimal synthetic reproduction and the outcome or diagnostic code. Remove private references, secrets and real learner evidence. Report security issues through the [security policy](https://github.com/0xbuffdev/assay/blob/v0.0.1/SECURITY.md). diff --git a/scripts/assay-docs.test.mjs b/scripts/assay-docs.test.mjs index 36cfd23..e7058f7 100644 --- a/scripts/assay-docs.test.mjs +++ b/scripts/assay-docs.test.mjs @@ -11,11 +11,7 @@ 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.slice(0, 4), ["index", "installation", "quickstart", "concepts"]); - for (const slug of ["criteria", "composition", "evidence", "execution-facts", - "protected-references", "observation-ports", "qualitative-review", "public-results", - "architecture", "integrity", "security", "api", "contracts", "outcomes", - "limits", "compatibility", "troubleshooting"]) assert.ok(pages.has(slug), slug); + assert.deepEqual(listed, ["index", "evaluation", "observations", "integrity", "api", "contracts"]); }); test("Assay internal links resolve and complete examples are marked", async () => { diff --git a/scripts/verify-assay-examples.mjs b/scripts/verify-assay-examples.mjs index abe9d82..6561b67 100644 --- a/scripts/verify-assay-examples.mjs +++ b/scripts/verify-assay-examples.mjs @@ -9,11 +9,10 @@ const version = "0.0.1"; const directory = "content/docs/assay"; const temporary = await mkdtemp(join(tmpdir(), "assay-docs-")); const expected = new Map([ - ["installation.mdx", "4 v0.0.5"], - ["quickstart.mdx", "pass"], - ["execution-facts.mdx", "pass"], - ["protected-references.mdx", "pass withheld"], - ["observation-ports.mdx", "pass"], + ["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"; @@ -33,7 +32,7 @@ try { for (const name of Object.keys(assay)) { assert.match(api, new RegExp("\\b" + name + "\\b"), "Undocumented export: " + name); } - const limits = await readFile(join(directory, "limits.mdx"), "utf8"); + 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); @@ -43,11 +42,12 @@ try { 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), file + " example " + index); + assert.equal(output, expected.get(file)?.[index], file + " example " + index); seen.add(file); console.log("Verified " + file + ": " + output); }