Skip to content

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Traigent Schema Library

Agent Certificate v0 offline verification

traigent_schema.certification contains the distributable relying-party verifier for the Agent Certificate v0 envelope. A relying party supplies the certificate JSON, the issuer P-256 or Ed25519 public key, a fresh VerificationContext (nonce, build-session reference, issuer key/trust-ring references, and—when claims are present—the client public key), and an explicit pinned RelyingPartyPolicy containing the compiler-register digests and verifier bindings it accepts. Verification performs JSON-Schema validation, fp2/JCS role-separated digest checks, projection/audit bindings, and low-S P-256 or Ed25519 signature checks without network, Backend, database, issuer callbacks, or private evidence.

The B-v0 build-ledger profile is identified by the exact seal chain_schema_version traigent.cert_build_ledger.v0. Its public projection contains only the opaque seal reference, build-session reference, fixed stream family/status/root entries, and a role-separated seal-statement digest. The fixed mapping is transition=sealed, receipt_event=sealed, and decision=empty_sealed; all-zero synthetic roots and unsupported profiles are rejected. The verifier authenticates the exact signed projection, but cannot independently recompute Backend HMAC history or prove ledger completeness or omission resistance from public roots.

from traigent_schema.certification import (
    RelyingPartyPolicy, VerificationContext, verify_certificate,
)

result = verify_certificate(
    certificate,
    issuer_public_key=issuer_public_key,
    context=context,
    policy=pinned_policy,
)

For a discovery bundle returned by the verification-materials endpoint, use verify_certificate_with_materials. The relying party must provide both the explicit certificate_ref and an independently pinned expected_materials_digest. Status-aware verification is the safe default: pass the complete retrieval response (all fields from CertificateRetrievalResponseV0), and verification requires certificate_status.status == "active" with both revocation fields set to null. A bare signed certificate is rejected with CERTIFICATE_STATUS_UNKNOWN; it can be used only for explicitly declared, offline signature-only verification with require_status=False:

from traigent_schema.certification import verify_certificate_with_materials

result = verify_certificate_with_materials(
    certificate_or_retrieval_wrapper,
    verification_materials,
    certificate_ref=certificate_ref,
    expected_materials_digest=expected_materials_digest,
    context=context,
)

Do not set require_status=False when revocation status is relevant. A supplied retrieval wrapper is always checked for the exact status shape and active/null status, even when that opt-out is set.

Successful results distinguish cryptographic verification from status evidence: all currently available verification paths, including retrieval wrappers, return code="VERIFIED_SIGNATURE_ONLY" with status_evidence="not_checked". Retrieval wrappers are shape-checked for an active/null status, but their unsigned status metadata is not authenticated and cannot establish current validity or non-revocation. The VERIFIED / issuer_status_snapshot pair is reserved for a future issuer-asserted status snapshot backed by an authenticated, freshness-bounded status-proof contract; the current v0 retrieval schema provides no such proof.

The cryptography dependency is installed with the base package because the public verifier imports it unconditionally. The historical certification extra remains available as a no-op compatibility alias, so both pip install traigent-schema and pip install "traigent-schema[certification]" install the verifier. Current v0 emits B1 and G1; REG1, C1, D2, F1, and G3 are the five fixed abstentions.

The certification API has two explicit issuance branches. B1-only issuance neither produces nor consumes PrepareResponseV0; it finalizes with issuer material alone. The G1 branch uses an issuer-first signing flow: prepare returns one content-free, issuer-signed certificate projection in its final canonical wire shape, with the outer signatures.co_attestation member absent. The issuer projection excludes that client co-attestation; the client canonicalizes the exact issuer-signed projection, which includes issuer_signature and excludes only its own outer co_attestation, and signs it; it must not rebuild or pair it with a separate unsigned-manifest response. finalize validates the persisted prepared projection and requires the co-attestation because that projection has G1/tier 1. Finalization preserves the exact prepared issuer projection and adds only the client's outer co-attestation block.

For clients implementing the co-attestation step, Schema exposes prepare_client_co_attestation(prepare_response, context=...) together with the frozen ClientCoAttestationContext. Pass the exact issuer-signed G1 projection returned by prepare, not a final certificate. The context states all 19 required projection pins: project, build session, session commitment, nonce, privacy mode, SDK ref/version, disclosure profile, issuer key/trust-ring/algorithm, the immutable ordered compiler/register tuple, G1 verifier identity/version, evidence-manifest root, commitment scheme, attestor version, client signature algorithm, and client public key. CLIENT_CO_ATTESTATION_CONTEXT_FIELDS is the authoritative ordered projection-pin manifest for SDK bindings. In addition, the context requires issuer_public_key, a public-only issuer trust key that is not a projection field and is therefore not included in that 19-field manifest. The helper derives the project-scoped client key reference, compares every projection pin, the G1 declaration, the audit root, and the compiler-register-to-semantics relation, then authenticates the issuer signature over the canonical unsigned manifest before returning signing material. Its ClientCertificateProjection result contains a defensive projection, immutable projection_bytes, frozen signing_bytes, and the role-domain signed_manifest_digest.

The helper is deterministic and offline. Its first call reads the installed package's Schema resources to build cached validators; later calls reuse those validators. It never accepts a private key, signs, performs network access or writes, or receives customer examples, agent/evaluator code, or response content. It validates the prepare projection's structure and authenticates its issuer signature with the pinned public issuer key; the caller remains responsible for selecting and pinning that trust key.

Untrusted preparation input has a fail-closed 512 KiB structural resource cap, sized with conservative headroom for projections that can pass the current B1/G1 semantic restrictions. It is not an upper bound for every generic schema branch: the generic ClaimV0.evidence_refs property has structural maxItems: 64, while the complete conditional contract admits only B1/G1 and fixes each printable claim to exactly two refs; production admits at most one B1 plus one G1. Larger invalid projections may fail earlier with the same bounded CO_PROJECTION code. The final verifier does not apply this transport preflight cap after the certificate has passed its canonical schema validation.

The seal, claims, tiers, evidence references, non-claims, and audit rows are issuer/compiler evidence, not client assertions of truth; the helper checks their schema and deterministic cross-projections, then co-signs their exact bytes. Fixed envelope scope text and the G1 verifier result PASS are schema-owned constants. G1 verifier identity/version select trust semantics and are required client pins. Backend lifecycle freshness bounds such as expires_at, created_at, and finalized_at are issuer/server evidence outside PrepareResponseV0; the client pins the signed manifest nonce, not those transport-state fields. The required issuer pins prevent a prepare response from silently selecting a different issuer identity or algorithm, while the pinned issuer public key authenticates the signed manifest before co-signing.

Failures raise RelyingPartyVerificationError; its .code and string form are bounded, content-free values intended for safe logging. Public preparation codes are enumerated by CLIENT_CO_ATTESTATION_ERROR_CODES. A successful result proves the supplied envelope, signatures, projections, and declared bindings are internally consistent and match the relying party's pins. It does not prove that a G1 commitment is truthful or complete, recover the committed client artifacts, establish deployment identity/runtime behavior, or interpret opaque issuer ledger roots. The Backend endpoint/distribution integration remains a separate concern.

The official contract package for the Traigent AI optimization platform. This repository is the shared source of truth for JSON Schema definitions, endpoint mappings, and validation utilities used across the backend, SDK, and frontend.

Certificate-route error contract

The declared contract for Agent Certificate v0 HTTP error responses permits only the fixed success: false, message, error, and status-selected error_code fields. Request content, exception text, diagnostic maps, and nested values are not representable. The contract deliberately does not reuse the generic error envelope, whose message/error/details fields can carry customer response content, agent/evaluator code, or evaluation-dataset examples. This contract declaration does not establish Backend runtime conformance.

Before you push: run make install-hooks once per clone, then make local-gate before every push. The local gate runs the checks CI enforces (ruff check, mypy, the pytest/parity structural gates, the spine-trail reminder, and — for main-bound branches — a local scan that approximates the SonarCloud Code Analysis required check), so avoidable reds are caught before the push rather than after it. Budget 5-15 minutes: the pytest step is the full suite, not a smoke test. See docs/LOCAL_CI_GATE.md.

Installation

For published package consumers, including users of the offline Agent Certificate verifier:

pip install traigent-schema

The base package includes the verifier's cryptography runtime dependency. The historical certification extra remains a supported no-op compatibility alias; requesting it is not required. CI clean-installs and functionally probes the plain wheel and checks that the compatibility extra is declared. The separate clean installation of traigent-schema[certification] is release evidence run manually; it is not currently a second CI installation job.

For coordinated workspace development or release validation from GitHub (requires repository access):

pip install git+https://github.com/Traigent/TraigentSchema.git

For development:

pip install -e ".[dev]"
# Python >= 3.12, to run the TVL reactive trace tests too (they fail, not skip, without it):
pip install -e ".[dev,tvl]"

Quick Start

from traigent_schema import SchemaValidator, load_schema

# Validate current backend requests
backend_validator = SchemaValidator()
errors = backend_validator.validate_request('/api/v1/agents', 'POST', request_data)

# Validate SDK direct-tuning requests
tuning_validator = SchemaValidator(contract="sdk_tuning")
errors = tuning_validator.validate_request('/api/v1/sessions', 'POST', session_request)

# Validate planned project-scoped beta routes
planned_validator = SchemaValidator(contract="planned_projects")
errors = planned_validator.validate_request(
    '/api/v1beta/projects/proj_123/analytics/summary',
    'GET',
    {},
)

if errors:
    print(f"Validation errors: {errors}")
else:
    print("Request is valid!")

# Load a specific schema
agent_schema = load_schema('agent_schema')

Available Schemas

The library includes schemas organized by domain:

Agents (schemas/agents/)

  • agent_schema.json - Core agent configuration
  • agent_types_schema.json - Agent type definitions
  • agent_deployment_schema.json - Deployment configurations
  • agent_response_schema.json - Response format specs
  • model_schema.json - Model definitions
  • model_parameters_schema.json - Model parameter specs
  • retriever_schema.json - Retrieval configurations

Datasets (schemas/datasets/)

  • dataset_schema.json - Canonical public dataset resource
  • evaluation_set_schema.json - Legacy-compatible evaluation dataset schema
  • example_set_schema.json - Example set definitions
  • generator_config_schema.json - Data generator configs
  • evaluator_config_schema.json - Evaluator configurations

Evaluation (schemas/evaluation/)

  • experiment_schema.json - Experiment definitions
  • experiment_run_schema.json - Experiment run records
  • configuration_run_schema.json - Configuration run data
  • evaluation_schema.json - Evaluation specifications
  • evaluation_request_schema.json - Evaluation requests
  • evaluation_results_schema.json - Evaluation results

Execution (schemas/execution/)

  • hybrid_session_schema.json - Hybrid session configs
  • saas_execution_schema.json - SaaS execution specs
  • dataset_storage_schema.json - Dataset storage configs
  • metric_submission_schema.json - Metric submission format

Measures (schemas/measures/)

  • measure_schema.json - Measure definitions
  • score_schema.json - Score specifications

Results (schemas/results/)

  • report_schema.json - Report definitions
  • report_request_schema.json - Report request format
  • comparison_schema.json - Comparison specs
  • visualization_schema.json - Visualization configs
  • visualization_request_schema.json - Visualization requests

API Reference

Contract Catalogs

traigent-schema now ships three endpoint catalogs:

  • backend: current TraigentBackend truth, loaded by default through SchemaValidator()
  • sdk_tuning: direct-tuning session and hybrid routes used by SDK clients
  • planned_projects: planned and beta project-scoped /api/v1beta/projects/... routes

Use get_openapi_path() when you want the canonical backend contract root, or get_contract_path(...) when you need one of the non-default catalogs.

Contract Stability

The backend and sdk_tuning catalogs are the supported contract roots for released Traigent surfaces. The planned_projects catalog documents planned and beta project-scoped routes for coordinated development. It is not a stable public API contract, may change without a major-version bump, and may break between minor releases until those routes graduate. Pin a specific traigent-schema version if you build directly against this pre-release surface.

Schema Governance

TraigentSchema is the canonical source of truth for Traigent data contracts across the Python SDK, backend, frontend, and JavaScript SDK parity checks. When changing schemas, update the JSON Schema first, then update downstream DTOs, backend models, generated frontend types, tests, and the changelog as needed.

The shared MeasuresDict contract is enforced across projects:

  • max 50 keys
  • keys match the Python identifier pattern ^[a-zA-Z_][a-zA-Z0-9_]*$
  • values are numeric or null

Field-level privacy classification (x-privacy-classification)

Schemas may tag fields (or object groupings) with a machine-readable privacy class so redaction, retention, and export tooling can reason by contract instead of hard-coding field names.

The vocabulary is closed: the twelve allowed values below are exactly the enum in x_extensions_meta_schema.json, which is the source of truth, and a test keeps this table equal to it. A consumer that builds redaction rules should handle all twelve, since any of them may appear; pii and restricted are declared but currently carry no shipped field. This table listed six until #573, omitting secret, which five shipped fields use.

Value Meaning
user_content Raw user-supplied content / model output (prompts, inputs, outputs). The hybrid-path content fields use this — paired with x-content: true so a consumer can enumerate content-bearing leaves directly from the contract.
pii Personally identifiable information.
auth_sensitive Authentication and authorization payloads such as device-flow tokens, API keys, and SSO auth responses.
billing_sensitive Billing / pricing data (e.g. wallet, checkout).
secret One-time secrets, never re-readable after issue.
restricted Tightly access-controlled values.
aggregate_safe Aggregated / derived values safe to surface broadly.
manifest_safe Safe to include in exported manifests.
tenant_admin_safe Visible to tenant admins only.
sdk_runtime_metadata SDK execution metadata. Carried both by whole run-context schemas and, on the session-create request, by run-provenance fields such as artifact versions and code revision.
internal_confidential Service-only policy, certificate, or short-lived execution metadata.
system Internal system data.

Content-bearing fields on the hybrid DTOs carry x-content: true + x-privacy-classification: user_content: trace/observation input_data/output_data, Example.input/output, EvaluationSetExample.input_text/expected_output, and the metric-submission ConfigurationParameters. Adding these x- keywords is additive and ignored by standard JSON-Schema validators.

Canonical x-* extension list and descriptions: traigent_schema/schemas/x_extensions_meta_schema.json.

SchemaValidator

from traigent_schema import SchemaValidator

validator = SchemaValidator()
sdk_validator = SchemaValidator(contract="sdk_tuning")
planned_validator = SchemaValidator(contract="planned_projects")

# Validate by endpoint
errors = validator.validate_request(endpoint, method, data)

# Validate by schema name
errors = validator.validate_json(data, 'agent_schema')

# List available schemas
print(validator.available_schemas)

Utility Functions

from traigent_schema import (
    get_schemas_dir,      # Get path to schemas directory
    get_schema_path,      # Get path to specific schema
    get_all_schema_files, # List all schema files
    get_openapi_path,     # Get path to canonical backend contract root
    get_contract_path,    # Get path to backend/sdk_tuning/planned_projects root
    load_schema,          # Load and parse a schema
)

Development

Use the make targets: each one mirrors a check CI runs, so a green target here means a green check there. (make lint and make typecheck run CI's command verbatim, pinned by a test; make test runs the same suite with quieter reporting flags.) The bare ruff check . and mypy traigent_schema forms lint and type-check paths CI does not gate, and report errors on a clean tree.

# Install with dev dependencies (add the tvl extra on Python >= 3.12 for the TVL trace tests)
pip install -e ".[dev]"   # or: make install
pip install -e ".[dev,tvl]"

# mirrors CI / test
make test        # pytest tests/ -q -p no:cacheprovider

# mirrors CI / lint-type
make lint        # ruff check traigent_schema/
make typecheck   # mypy traigent_schema/ --ignore-missing-imports

make local-gate  # everything CI enforces — run this before you push

make test runs the full suite (7.2k tests; roughly 5-15 minutes, depending on what else the machine is doing); make lint and make typecheck take seconds. make help lists every target.

Version

Current release line: 8.0.0 (from traigent_schema/version.py; release notes in CHANGELOG.md).

That is the repository version, not the published one. PyPI's newest traigent_schema release is 5.8.0 (uploaded 2026-09-05), so pip install traigent_schema installs 5.8.0. 6.0.0, 6.1.0 and 7.0.0 are dated in CHANGELOG.md and live on main, but none of them was ever tagged or published, so a package consumer is missing two breaking changes: the 6.0.0 legacy execution-selector removals and the 7.0.0 ExperimentStatus rebind. Check what is actually published with pip index versions traigent-schema (the distribution name in pyproject.toml; traigent_schema normalizes to it); publishing is a manual dispatch of .github/workflows/publish.yml from an exact main commit. Tracked in TraigentSchema#576.

The 5.4 register additions are documentation-only annotations: invite_token and the portal's unified registration_code wire field remain unconstrained by validating keywords so every request accepted by the 5.3 schema remains accepted. Runtime constraints and the closed register property set are deferred to the next major contract release.

Package metadata is derived from traigent_schema/version.py to keep runtime and published versions aligned.

License

traigent-schema is dual-licensed: AGPL-3.0-only (see LICENSE) OR a Traigent commercial license for use without AGPL copyleft (see COMMERCIAL-LICENSE.md). SPDX: AGPL-3.0-only OR LicenseRef-Traigent-Commercial.

Use it free under AGPL-3.0, or contact legal@traigent.ai for a commercial license. See LICENSING.md for a short FAQ, NOTICE for third-party attributions, and CONTRIBUTING.md (contributions require a CLA).

TVL 1.4 reactive contracts

traigent_schema/data/tvl/ vendors the TVL runtime contract and runtime-local schemas (/1 and /2) byte for byte, and the tvl_reactive_* documents under traigent_schema/schemas/optimization/ and execution/best_config_deploy_* define the closed wire contracts of the reactive layer (facts, grants, reservations, notifications, deploy publish-result). They are a reviewed closed-contract expansion (GNFR-PRIV-002(f)); see docs/tvl-reactive-contracts.md for the field classification, principals and the vendoring record.

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages