From 2a2e6584e524ebe90919a51363802df6d11a6aa8 Mon Sep 17 00:00:00 2001 From: Nimrod Busany Date: Thu, 26 Nov 2026 12:28:53 +0200 Subject: [PATCH 1/2] feat(agent-readiness)!: compliance document search, signing bound to the reviewed subject, required rationale - Compliance document references can be searched by link substring through a new project-scoped operation (additive; contract only). - Attestation signing requires review_context, the keyed freshness token read from the evidence response, so a signature is bound to the subject the signer reviewed; a stale token is a 409 with the closed reason stale_review_context. - A not_applicable applicability decision requires a non-empty rationale; a missing one is a 400 with the closed body RationaleRequiredError (fixed message, no client text). - The breaking changes are pre-release and acknowledged in scripts/breaking_schema_allowlist.json. Spine-Trail: st_f6fb29f7a817 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + parity/python-js-sdk.json | 2 +- scripts/breaking_schema_allowlist.json | 238 +++++++++++++++++- .../test_compliance_applicability_contract.py | 72 ++++++ tests/test_compliance_attestation_contract.py | 16 ++ .../test_compliance_document_ref_contract.py | 35 +++ tests/test_compliance_evidence_contract.py | 13 + .../compliance_applicability_endpoints.json | 7 +- .../compliance_applicability_schema.json | 22 +- .../compliance_attestation_endpoints.json | 13 + .../compliance_attestation_schema.json | 8 +- .../compliance_document_ref_endpoints.json | 102 ++++++++ .../compliance_document_ref_schema.json | 30 +++ .../compliance_evidence_response_schema.json | 17 +- 14 files changed, 560 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cbd80b86..cdffa340 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **API-key scope `fleet_imports:write` (additive; contract only; fleet observe increment 1).** New user-requestable scope in `api_key_authorization_vocabulary_schema.json` for an unattended importer that uploads fleet inventory to exactly one project. It maps to the single permission `fleet_import.write` (new `ApiKeyPermissionToken` and audit-permission value) with compatibility alias `write:fleet_import`. Unlike every other `*:write` scope it implies no read permission: no `fleet_import.read` token and no read alias exist, and the map entry is marked `x-write-only` and `x-requires-project-binding` (a key with this scope must be bound to exactly one project, and the backend must not add an implied read during scope normalization). Documented under `x-scope-convention.exceptions`. Pinned by `tests/test_api_key_authorization_vocabulary.py`. Package version unchanged until a release is cut. - **Fleet Observe endpoints, request/response envelopes, import bundle and request-digest vectors (TRAIG-179; additive, contract only).** New `fleet_observe/fleet_observe_endpoints.json` (registered in `mep_endpoints.json` as "Fleet Observe"): the six routes under `/api/v1beta/projects/{project_id}/fleet-observe` (`POST /imports`, `GET /clusters`, `/clusters/{cluster_ref}`, `/coverage`, `/diff`, `/findings`) with the API server's operation ids `project_fleet_observe.*`. New closed `import_request_schema.json` (`source_kind`, `boundary{boundary_kind, boundary_digest}`, `idempotency_key`, `observed_at`, optional `retention_class`, 1 to 5000 `members`; `parent_member_digest` may be omitted or explicit null), `fleet_observe_responses_schema.json` (the standard `{success, message, data}` envelope for each route, including `DiffResponse` and `FindingsResponse`; the import data is the nested import view `{import_event, evidence, outcome}` plus `replayed`, 201 new and 200 replay; the closed `ErrorBody`; the limiter 429 `RateLimitedBody`, the masked 5xx `RateLimitUnavailableBody` and the 401 `AuthErrorBody`) and `import_bundle_schema.json` (offline bundle and run manifest, `digest_scheme: hmac_sha256_v1`, `digest_key_id`). Both multi-definition documents have a constrained root (the responses document accepts any one response definition; the bundle document accepts a Bundle or a Manifest), so validating by document name rejects arbitrary content, including a `label_map` or a name. `ErrorBody` also publishes two PLANNED codes the API server does not emit yet: `fleet_observe_idempotency_conflict` (409) and `fleet_observe_project_quota_exceeded` (429); their message wording is a proposal. A 401 from the shared authentication layer keeps its status and is declared; only 403 and 404 are rewritten to the closed 404. New data: `data/fleet_observe/request_digest_v1.md` (canonical request digest: fixed key order, normalized `observed_at`, defaults applied, duplicate members collapsed, sorted members, parent cycles and the 5000 cap on the original array rejected, `idempotency_key` excluded and derived from the digest), `request_digest_vectors.json` (shared SDK and server vectors, valid and rejected), `identifier_canonicalization.json` (HMAC-SHA256 identifier digests with `tfl1` domain separation by role and source; full git-remote canonicalization rules with raw-remote vectors; a public test key marked never for production) and the reference implementation `traigent_schema/fleet_observe_digest.py`. `scripts/content_class_lint.py` changes: the four new documents join the lint roots, the 16-hex digest key id is an approved opaque-ref pattern, and the signed pagination cursor pattern is approved only at one named definition (`CURSOR_LOCATIONS`) with `maxLength <= 512`, enforced by a location check and pinned by tests; the pattern is not approved anywhere else. No existing class, cap or gate is loosened. Pinned by `tests/test_fleet_observe_contract.py`, `tests/test_fleet_observe_endpoints.py`, `tests/test_fleet_observe_digest_vectors.py` and `tests/test_content_class_lint.py`. Package version unchanged until a release is cut. - **BREAKING (pre-release). Agents-family cursor pagination (API revision Phase 3).** `GET /api/v1/projects/{project_id}/agents` takes `limit` (1-100, default 20; above 100 is a 400, never clamped) and `cursor` (opaque, `maxLength` 4096) instead of `page`/`per_page`; the free-text `style` and `tone` query filters are removed (customer text belongs in the search body), and `sort_by` is the closed enum `created_at`, `updated_at`, `name`, `agent_type_id`, `id`. `POST .../agents/search` takes `limit`/`cursor` in the body, and `GET .../agents/{agent_ref}/experiments` takes `limit`/`cursor` and returns the success envelope `{success, message, data:{agent_id, items, pagination}}` instead of the bare `{agent_id, total, experiments}`. List, search and experiments responses carry `pagination: {limit, next_cursor, has_more}` (no `total`, page number or offset). Agent-readiness: the portfolio search body takes `limit`/`cursor`, lifecycle-history takes `limit`/`cursor` (max 100, was `page`/`per_page` max 50) and the readiness detail takes `journey_limit`/`journey_cursor` (max 100, was `journey_page`/`journey_per_page`); `agent_readiness_portfolio_response_schema.json`, `agent_lifecycle_history_response_schema.json` and `agent_readiness_detail_response_schema.json` carry the same cursor pagination block (`journey.items` `maxItems` 100). `page`, `per_page` and `offset` are rejected by the backend. Disclosure-register rules chosen for the lifecycle-history pagination block (for reviewer check): `limit` and `has_more` are `protocol_accounting_count`, `next_cursor` is `opaque_lifecycle_reference`, the block itself stays `closed_public_structure`. Pending PR: not yet opened (TraigentSchema, feat/api-p3-agents-cursor-pagination). Package version unchanged until a release is cut. +- **BREAKING (pre-release). A `not_applicable` applicability decision requires a rationale.** `DecisionInput` gains an if/then: when `decision` is `not_applicable`, `rationale` is required and must hold at least one non-whitespace character (the 2000-character cap is unchanged). `applicable` and `unresolved` keep it optional, and a `carry: true` item is not re-validated. The Backend refuses the violation with a closed 400 `rationale_required` (new closed body `RationaleRequiredError`, declared beside the shared error envelope on the write's 400, acknowledged in `scripts/breaking_schema_allowlist.json`). Pre-release contract in the same slice as the Backend and Frontend. +- **BREAKING (pre-release). Compliance attestation signing is bound to the reviewed subject.** `AttestationCreateRequest` gains a REQUIRED `review_context` (64 lowercase hex): the opaque, server-issued, keyed freshness token the signer read from the evidence response (new `Ingredient.review_context`, required on `A` rows as a string or null, absent on other kinds). A stale value is refused with 409 `stale_review_context` and nothing is recorded; the sign operation also declares a 503 for when the server cannot issue or verify the token. The token is never derived from customer text and is not evidence: never store, log or export it. Coordinated pre-release break: the feature is dark in production and the Backend and Frontend change in the same slice (acknowledged in `scripts/breaking_schema_allowlist.json`). +- **Compliance document references: search by link substring (additive; contract only).** New operation `POST /api/v1/projects/{project_id}/agents/{agent_ref}/compliance-document-refs/search` (`project_compliance_document_refs.search_compliance_document_references`, `x-replay: read`) and closed request `DocumentReferenceSearchRequest` (`q` 1 to 200 characters after trimming, optional `include_withdrawn`, `page`, `per_page`). It is a read served as POST so the search text, which is customer content, stays out of URLs, logs and traces; it matches case-insensitively, as a literal substring, against the declared link and answers the existing `DocumentReferenceListResponse` with the list's ordering and paging. Marked `x-asserted-against-backend: false` until the Backend merges. Pinned by `tests/test_compliance_document_ref_contract.py`. - **Experiment list: best-trial fields on `ExperimentListRunSummary` (additive; optional, nullable).** `experiment_schema.json` gains `best_trial_id` (string or null) and `best_metrics` (object of numbers or null), the trial the server selected as best at finalize and its numeric metrics; both null when no trial succeeded. Not added to `required`. - **BREAKING (pre-release). Agent decisions and agent-lifecycle contracts on project-level `/api/v1` paths (API revision Phase 3, slice 2 PR-3).** The host-prompt decision operations move from `/api/v1beta/agent-decisions/{agent_id}/{ensure,latest}` and `/api/v1beta/agent-decisions/{decision_id}/answer` to `/api/v1/projects/{project_id}/agents/{agent_ref}/decisions/{ensure,latest,{decision_id}/answer}` (path parameter `agent_id` becomes `agent_ref`; operationIds become the policy-register ids `agent_decision.ensure_agent_decision`, `.get_latest_agent_decision`, `.answer_agent_decision`; bodies and error bodies unchanged). The wire field `agent_ref` of the agent-lifecycle revision registration request and response and of the lifecycle record response is renamed `lifecycle_agent_ref` (the underlying column and the `agent_` id format are unchanged); lifecycle route paths in schema descriptions and privacy captures now read `/api/v1/projects/{project_id}/agent-lifecycle/...`. The platform-admin `GET /api/v1/agents/admin/stats` operation leaves the public schema (private, served at `/api/v1/admin/agents/stats`). The agent-context resolver (`POST /api/v1/agent-context/resolve`) is a private portal operation and is not declared here. Package version unchanged until a release is cut. - **Audit evaluate contract, new `audit_evaluate/` domain (additive; contract only).** `POST /api/v1/projects/{project_id}/audit/evaluate` with closed request, success envelope, error and not-found problem schemas (every field carries a content class). Two content classes join the vocabulary: `version` (a bounded dotted numeric version, proven by its pattern) and `server_text` (server-composed text from fixed templates, bounded and noted; an assertion, not a keyword proof). The per-request problem id is an `opaque_ref` through one added fixed pattern (`^[0-9a-f]{32}(?![\s\S])`). `server_text` is accepted only at one allow-listed response location and is not a map-key class; the audit patterns end in an absolute-end assertion so a trailing newline is rejected. No existing schema changed. diff --git a/parity/python-js-sdk.json b/parity/python-js-sdk.json index 9e80e8ff..97281a88 100644 --- a/parity/python-js-sdk.json +++ b/parity/python-js-sdk.json @@ -399,7 +399,7 @@ "sdk032Surface": "Manifest Python pin advanced from d56e4353 to 6e8e4a54 (origin/develop, the SDK 0.32.0 release candidate) to cover two root exports the js-public-parity gate flagged unclassified on Traigent/Traigent#2861. requirement (traigent.runtime.decorator) is the runtime latency requirement decorator; traigent-js origin/main and origin/develop both export requirement from src/runtime/index.ts and list it in tests/integration/fixtures/api-surface.snapshot.json, so it is classified matched and added to requiredRootExports next to require. SnapshotBindingError (traigent.utils.exceptions) is the typed error of the Python opt-in snapshot store (S0 before dispatch, S1 from the terminal result, online G1); traigent-js has no snapshot store and no export of it (zero occurrences in src or its api-surface snapshot), so it is classified deferred-backlog, Python-only for now with no open JS design and no ticket. Owner may re-bucket." }, "schemaRefresh": { - "lastSchemaFileSha": "895cd9c9cd67c906e6a4cbfe7f62f77bcb89c2eefae204997a14b86f4a209f12", + "lastSchemaFileSha": "609ea4c25882e63bc9edd4e56d2ac87887ed1de553dd2789e7302f668521e948", "schemaFileCount": 666, "note": "Auto-stamped by scripts/refresh_parity.py. Do not hand-edit this block." } diff --git a/scripts/breaking_schema_allowlist.json b/scripts/breaking_schema_allowlist.json index 0303d81c..14f07a95 100644 --- a/scripts/breaking_schema_allowlist.json +++ b/scripts/breaking_schema_allowlist.json @@ -862,14 +862,14 @@ { "file": "execution/execution_endpoints.json", "rule": "property_added", - "reason": "identity_state is an explicit discriminator when present, with a closed enum of identified/unidentified and a strictly validated absent/legacy migration branch (expand-contract); rollout stays flag-off until Backend and strict consumers emit and handle it.", + "reason": "Identity_state is an explicit discriminator when present, with a closed enum of identified/unidentified and a strictly validated absent/legacy migration branch (expand-contract); rollout stays flag-off until Backend and strict consumers emit and handle it.", "version": "5.6.0", "pr": "#400" }, { "file": "execution/execution_endpoints.json", "rule": "type", - "reason": "agent_id is nullable only in the unidentified branch, with paired-null invariants, because inventing an agent would corrupt provenance; identified rows remain string-valued.", + "reason": "Agent_id is nullable only in the unidentified branch, with paired-null invariants, because inventing an agent would corrupt provenance; identified rows remain string-valued.", "version": "5.6.0", "pr": "#400" }, @@ -1496,7 +1496,7 @@ { "file": "optimization/session_submit_results_request_schema.json", "rule": "oneOf_added", - "reason": "measures and metadata.measures were a bare $ref to the flat MeasureResults dict, which only ever described HALF of what the backend's _validate_submission_measures dispatcher actually accepts -- it also routes a list of per-example ExampleMetrics results (the form carrying input_id/example_digest/output_digest/verified_match/signal_key_id) to validate_measures_list. A generated strict consumer built from the bare $ref would reject that list form even though the live backend accepts it. Replacing the bare $ref with oneOf [MeasureResults, array] makes the schema match the real dispatch contract instead of only documenting one branch of it. Confirmed non-breaking for existing map-form producers: test_submit_results_measures_inherit_measuresdict_contract and test_submit_results_legacy_metadata_measures_is_constrained (both pre-existing, unmodified) continue to pass -- a flat dict still validates via oneOf branch 0, and its bounds (max 50 keys, identifier keys, numeric|null values) are unchanged and still sourced from the single canonical MeasureResults definition, not duplicated.", + "reason": "Measures and metadata.measures were a bare $ref to the flat MeasureResults dict, which only ever described HALF of what the backend's _validate_submission_measures dispatcher actually accepts -- it also routes a list of per-example ExampleMetrics results (the form carrying input_id/example_digest/output_digest/verified_match/signal_key_id) to validate_measures_list. A generated strict consumer built from the bare $ref would reject that list form even though the live backend accepts it. Replacing the bare $ref with oneOf [MeasureResults, array] makes the schema match the real dispatch contract instead of only documenting one branch of it. Confirmed non-breaking for existing map-form producers: test_submit_results_measures_inherit_measuresdict_contract and test_submit_results_legacy_metadata_measures_is_constrained (both pre-existing, unmodified) continue to pass -- a flat dict still validates via oneOf branch 0, and its bounds (max 50 keys, identifier keys, numeric|null values) are unchanged and still sourced from the single canonical MeasureResults definition, not duplicated.", "version": "5.8.0", "pr": "#437" }, @@ -2460,7 +2460,7 @@ { "file": "datasets/dataset_schema.json", "rule": "property_added", - "reason": "current_version is a new, optional, nullable property (default null) added under a closed additionalProperties:false object as part of the R3 dataset-version content-identity contract. It carries a DatasetVersionV1 record via cross-file $ref for callers that want a content-addressable snapshot of a dataset revision. Old readers that VALIDATE against the previous schema reject a payload carrying this key (closed object); producers MUST OMIT the key -- never emit null -- until every consumer has upgraded to a schema version that knows it; readers that ignore unknown keys are unaffected.", + "reason": "Current_version is a new, optional, nullable property (default null) added under a closed additionalProperties:false object as part of the R3 dataset-version content-identity contract. It carries a DatasetVersionV1 record via cross-file $ref for callers that want a content-addressable snapshot of a dataset revision. Old readers that VALIDATE against the previous schema reject a payload carrying this key (closed object); producers MUST OMIT the key -- never emit null -- until every consumer has upgraded to a schema version that knows it; readers that ignore unknown keys are unaffected.", "version": "Unreleased", "pr": "https://github.com/Traigent/TraigentSchema/pull/468", "findings": [ @@ -2970,7 +2970,7 @@ { "file": "execution/experiment_group_schema.json", "rule": "property_added", - "reason": "dataset_label is a new optional, nullable member on ExperimentGroupOverview added to let the portal's agent+dataset history table show a human-readable dataset name (Benchmark.label) instead of an opaque canonical dataset_id or 'No dataset'. This is the bare-named-resource conservative heuristic: ExperimentGroupOverview is reused response-side only (GET /api/v1/experiment-groups and .../{group_id}), never as a request body, so a strict old response consumer with additionalProperties:false on a locally-hand-copied shape is the only theoretical break, and no such consumer exists in this workspace's own repos (Backend emits, Frontend/SDKs read via generated/loose types). The field is purely additive and display-only -- it is not in ExperimentGroupOverview's required list, is not referenced by any identity_state allOf branch (identified/unidentified/absent-legacy), and is not part of the group sort/tie-break vocabulary or any cursor/pagination key.", + "reason": "Dataset_label is a new optional, nullable member on ExperimentGroupOverview added to let the portal's agent+dataset history table show a human-readable dataset name (Benchmark.label) instead of an opaque canonical dataset_id or 'No dataset'. This is the bare-named-resource conservative heuristic: ExperimentGroupOverview is reused response-side only (GET /api/v1/experiment-groups and .../{group_id}), never as a request body, so a strict old response consumer with additionalProperties:false on a locally-hand-copied shape is the only theoretical break, and no such consumer exists in this workspace's own repos (Backend emits, Frontend/SDKs read via generated/loose types). The field is purely additive and display-only -- it is not in ExperimentGroupOverview's required list, is not referenced by any identity_state allOf branch (identified/unidentified/absent-legacy), and is not part of the group sort/tie-break vocabulary or any cursor/pagination key.", "version": "Unreleased", "pr": "#472", "findings": [ @@ -3022,7 +3022,7 @@ "fingerprint": "03311a9c93e55d69eb17372d76edad959da83ad6298206244b30fbd2a4b05eff" } ], - "reason": "selection is a new OPTIONAL member of the closed SessionAggregationDTO (R3 selection receipt: records the SDK's selection decision and binds it to the session's own trials). The gate flags it under the bare-named-resource conservative heuristic because the old shape was additionalProperties:false and is echoed back in the finalize response. The Backend only echoes session_aggregation it persisted from the SDK's own finalize request, and no producer emits selection yet (Backend normalizer is R3 PR 2, Python SDK producer is PR 3), so a current SDK strictly validating the echo never receives the member; the SDK upgrade that sends selection ships together with the reader. Unreleased. Acknowledged rather than silenced so the widening of a closed shape is visible in the contract history.", + "reason": "Selection is a new OPTIONAL member of the closed SessionAggregationDTO (R3 selection receipt: records the SDK's selection decision and binds it to the session's own trials). The gate flags it under the bare-named-resource conservative heuristic because the old shape was additionalProperties:false and is echoed back in the finalize response. The Backend only echoes session_aggregation it persisted from the SDK's own finalize request, and no producer emits selection yet (Backend normalizer is R3 PR 2, Python SDK producer is PR 3), so a current SDK strictly validating the echo never receives the member; the SDK upgrade that sends selection ships together with the reader. Unreleased. Acknowledged rather than silenced so the widening of a closed shape is visible in the contract history.", "version": "Unreleased", "pr": "#491" }, @@ -3059,7 +3059,7 @@ "file": "planned_projects_endpoints.json", "rule": "endpoint_removed", "pointer_prefix": "#/paths//api/v1beta/projects/{project_id}/core-exports/fine-tuning.manifest", - "reason": "exportProjectFineTuningManifest was declared at a drifted path (/core-exports/fine-tuning.manifest) that no Backend route implements (verified at TraigentBackend origin/develop efe0074ecf4c: the only `fine-tuning.manifest` route is `src/routes/analytics_routes.py:287`, mounted under /analytics; `git log -S'core-exports/fine-tuning' -- src/routes/` finds no commit registering the old path) -- the real, shipped route lives on the analytics blueprint and is mounted at /analytics/exports/fine-tuning.manifest by the v1beta project-scoped registrar. This is a same-operation path correction (operationId, parameters, and response schema are unchanged), not a removal of working functionality: at the pinned Backend ref the drifted path is unrouted (a 404), and the project-scoped served route is `GET /api/v1beta/projects//analytics/exports/fine-tuning.manifest` (`src/routes/api_v1beta.py:68` registers analytics_bp project-scoped; obligation_matrix_report.txt:5127). It is still a contract-breaking path rename for anyone who coded against the declared path. The catalog carries x-asserted-against-backend:false and is pre-release, which is why this ships as a path fix rather than a major bump. TraigentSchema#272. Callers already use the served path: TraigentFrontend src/services/coreMetricsService.ts:509, Traigent traigent/core_metrics/client.py:228, traigent-js src/core-metrics/index.ts:223 (all at origin/develop, 2026-09-17); no client references the removed path, so this rename breaks no known caller -- a reviewed pre-release exception, not a claim that the declared interface had no dependents in principle.", + "reason": "ExportProjectFineTuningManifest was declared at a drifted path (/core-exports/fine-tuning.manifest) that no Backend route implements (verified at TraigentBackend origin/develop efe0074ecf4c: the only `fine-tuning.manifest` route is `src/routes/analytics_routes.py:287`, mounted under /analytics; `git log -S'core-exports/fine-tuning' -- src/routes/` finds no commit registering the old path) -- the real, shipped route lives on the analytics blueprint and is mounted at /analytics/exports/fine-tuning.manifest by the v1beta project-scoped registrar. This is a same-operation path correction (operationId, parameters, and response schema are unchanged), not a removal of working functionality: at the pinned Backend ref the drifted path is unrouted (a 404), and the project-scoped served route is `GET /api/v1beta/projects//analytics/exports/fine-tuning.manifest` (`src/routes/api_v1beta.py:68` registers analytics_bp project-scoped; obligation_matrix_report.txt:5127). It is still a contract-breaking path rename for anyone who coded against the declared path. The catalog carries x-asserted-against-backend:false and is pre-release, which is why this ships as a path fix rather than a major bump. TraigentSchema#272. Callers already use the served path: TraigentFrontend src/services/coreMetricsService.ts:509, Traigent traigent/core_metrics/client.py:228, traigent-js src/core-metrics/index.ts:223 (all at origin/develop, 2026-09-17); no client references the removed path, so this rename breaks no known caller -- a reviewed pre-release exception, not a claim that the declared interface had no dependents in principle.", "version": "Unreleased", "pr": "https://github.com/Traigent/TraigentSchema/pull/483", "findings": [ @@ -6669,7 +6669,7 @@ { "file": "execution/experiment_group_schema.json", "rule": "property_added", - "reason": "agent_name is a new optional, nullable member on ExperimentGroupOverview added to let the portal's optimization-history table show the agent's human-readable name (Agent.name) instead of the opaque agent_id UUID. This is the bare-named-resource conservative heuristic: ExperimentGroupOverview is reused response-side only (GET /api/v1/experiment-groups and .../{group_id}), never as a request body, so a strict old response consumer with additionalProperties:false on a locally-hand-copied shape is the only theoretical break, and no such consumer exists in this workspace's own repos (Backend emits, Frontend/SDKs read via generated/loose types). The field is purely additive and display-only -- it is not in ExperimentGroupOverview's required list, is not referenced by any identity_state allOf branch (identified/unidentified/absent-legacy), and is not part of the group sort/tie-break vocabulary or any cursor/pagination key. Same shape and rationale as the dataset_label acknowledgement (#472).", + "reason": "Agent_name is a new optional, nullable member on ExperimentGroupOverview added to let the portal's optimization-history table show the agent's human-readable name (Agent.name) instead of the opaque agent_id UUID. This is the bare-named-resource conservative heuristic: ExperimentGroupOverview is reused response-side only (GET /api/v1/experiment-groups and .../{group_id}), never as a request body, so a strict old response consumer with additionalProperties:false on a locally-hand-copied shape is the only theoretical break, and no such consumer exists in this workspace's own repos (Backend emits, Frontend/SDKs read via generated/loose types). The field is purely additive and display-only -- it is not in ExperimentGroupOverview's required list, is not referenced by any identity_state allOf branch (identified/unidentified/absent-legacy), and is not part of the group sort/tie-break vocabulary or any cursor/pagination key. Same shape and rationale as the dataset_label acknowledgement (#472).", "version": "Unreleased", "pr": "branch fix/agent-name-optimization-history, Spine-Trail st_9ca8039ca435 (PR number pending)", "findings": [ @@ -7170,7 +7170,7 @@ "fingerprint": "7480ac132620feabe0f5a4769ca7c94a92a484a10ae68226a6a995dfa77711dc" } ], - "reason": "intentional tightening; contract unreleased; owner ruling 2026-09-14 no clients yet, remove legacy now. Input-hardening bounds (#138) on the session-create objectives: metric names and legacy string objectives are capped at 255 (the bound hybrid_session_create_request_schema.json already uses for metric); the four artifact digests are capped at 71 = len('sha256:') + 64, which restates the pattern the same property already enforces, so no previously valid digest is refused. Correction: that is not the whole story. Python's regex '$' also matches just before a final newline, so the pattern previously admitted a 72-character digest ending in a newline ('sha256:' + 64 hex + a trailing newline). The 71-character bound additionally rejects those trailing-newline digests. This is an intentional tightening; no digest without a trailing newline is affected.", + "reason": "Intentional tightening; contract unreleased; owner ruling 2026-09-14 no clients yet, remove legacy now. Input-hardening bounds (#138) on the session-create objectives: metric names and legacy string objectives are capped at 255 (the bound hybrid_session_create_request_schema.json already uses for metric); the four artifact digests are capped at 71 = len('sha256:') + 64, which restates the pattern the same property already enforces, so no previously valid digest is refused. Correction: that is not the whole story. Python's regex '$' also matches just before a final newline, so the pattern previously admitted a 72-character digest ending in a newline ('sha256:' + 64 hex + a trailing newline). The 71-character bound additionally rejects those trailing-newline digests. This is an intentional tightening; no digest without a trailing newline is affected.", "version": "Unreleased", "pr": "Traigent/TraigentSchema content-less branch feat/content-less (PR not yet opened; pending contract review)" }, @@ -10345,6 +10345,220 @@ "version": "Unreleased pending (TraigentSchema, feat/api-p3-agents-cursor-pagination; backend API revision Phase 3 agents-family cursor pagination)", "pr": "pending (TraigentSchema, feat/api-p3-agents-cursor-pagination, not yet opened)" }, + { + "file": "agent_readiness/compliance_applicability_endpoints.json", + "rule": "additionalProperties", + "findings": [ + { + "pointer": "#/paths//api/v1/projects/{project_id}/compliance-applicability/post/responses/400/content/application/json/schema", + "role": "response", + "subject": "additionalProperties", + "old": "closed (false)", + "new": "open (true/absent)", + "fingerprint": "c2c202802ef166fe12c41966e7a8960bfb2add363eed5e59d2ea4f1f52d40a87" + } + ], + "reason": "The applicability write's 400 now also admits the closed body RationaleRequiredError (reason rationale_required, fixed message, no obligation id, no client text), returned when a not_applicable decision has no non-blank rationale. The shared error envelope is unchanged. Pre-release contract, feature dark in production, backend and frontend change in the same slice.", + "version": "Unreleased pending (TraigentSchema, rationale_required; backend change pending)", + "pr": "pending (TraigentSchema, not yet opened)" + }, + { + "file": "agent_readiness/compliance_applicability_endpoints.json", + "rule": "oneOf_branch_count_changed", + "findings": [ + { + "pointer": "#/paths//api/v1/projects/{project_id}/compliance-applicability/post/responses/400/content/application/json/schema/oneOf", + "role": "response", + "subject": "oneOf", + "old": 8, + "new": 2, + "fingerprint": "5bffc6a818240984e45341594ac5454b9adca7db647b7d9db728128acf09b853" + } + ], + "reason": "The applicability write's 400 now also admits the closed body RationaleRequiredError (reason rationale_required, fixed message, no obligation id, no client text), returned when a not_applicable decision has no non-blank rationale. The shared error envelope is unchanged. Pre-release contract, feature dark in production, backend and frontend change in the same slice.", + "version": "Unreleased pending (TraigentSchema, rationale_required; backend change pending)", + "pr": "pending (TraigentSchema, not yet opened)" + }, + { + "file": "agent_readiness/compliance_applicability_endpoints.json", + "rule": "required", + "findings": [ + { + "pointer": "#/paths//api/v1/projects/{project_id}/compliance-applicability/post/responses/400/content/application/json/schema", + "role": "response", + "subject": "error", + "old": true, + "new": false, + "fingerprint": "8bb10cbb9e6569b4711fcd5af2e1b3cc1a11b51e5624d79bbb42f5d3a86a0f97" + }, + { + "pointer": "#/paths//api/v1/projects/{project_id}/compliance-applicability/post/responses/400/content/application/json/schema", + "role": "response", + "subject": "error_code", + "old": true, + "new": false, + "fingerprint": "2feb5cd4752257e876ead09eb984fc845d9bb1037b1a18ac18da1fe38c327481" + }, + { + "pointer": "#/paths//api/v1/projects/{project_id}/compliance-applicability/post/responses/400/content/application/json/schema", + "role": "response", + "subject": "message", + "old": true, + "new": false, + "fingerprint": "03a373ee13a7171d53ec206ed1593226d31620c922fba229c3fbda6d6a9e217c" + }, + { + "pointer": "#/paths//api/v1/projects/{project_id}/compliance-applicability/post/responses/400/content/application/json/schema", + "role": "response", + "subject": "success", + "old": true, + "new": false, + "fingerprint": "321ccde360df3001a1746b09a20a1a2906ab8ccbcd0b8a3431a38b5e4908b322" + } + ], + "reason": "The applicability write's 400 now also admits the closed body RationaleRequiredError (reason rationale_required, fixed message, no obligation id, no client text), returned when a not_applicable decision has no non-blank rationale. The shared error envelope is unchanged. Pre-release contract, feature dark in production, backend and frontend change in the same slice.", + "version": "Unreleased pending (TraigentSchema, rationale_required; backend change pending)", + "pr": "pending (TraigentSchema, not yet opened)" + }, + { + "file": "agent_readiness/compliance_applicability_endpoints.json", + "rule": "type", + "findings": [ + { + "pointer": "#/paths//api/v1/projects/{project_id}/compliance-applicability/post/responses/400/content/application/json/schema", + "role": "response", + "subject": { + "direction": "added", + "values": [ + "" + ] + }, + "old": [ + "object" + ], + "new": null, + "fingerprint": "222320e4a18804b3397e4fbde479f6d10b15a2c8989eac7ed86af592d630af1e" + } + ], + "reason": "The applicability write's 400 now also admits the closed body RationaleRequiredError (reason rationale_required, fixed message, no obligation id, no client text), returned when a not_applicable decision has no non-blank rationale. The shared error envelope is unchanged. Pre-release contract, feature dark in production, backend and frontend change in the same slice.", + "version": "Unreleased pending (TraigentSchema, rationale_required; backend change pending)", + "pr": "pending (TraigentSchema, not yet opened)" + }, + { + "file": "agent_readiness/compliance_attestation_endpoints.json", + "rule": "enum", + "findings": [ + { + "pointer": "#/paths//api/v1/projects/{project_id}/compliance-attestations/post/responses/409/content/application/json/schema/properties/error", + "role": "response", + "subject": { + "direction": "added", + "values": [ + "\"stale_review_context\"" + ] + }, + "old": [ + "\"linked_reference_invalid\"", + "\"linked_reference_required\"", + "\"stale_fingerprints\"", + "\"stale_statement\"" + ], + "new": [ + "\"linked_reference_invalid\"", + "\"linked_reference_required\"", + "\"stale_fingerprints\"", + "\"stale_review_context\"", + "\"stale_statement\"" + ], + "fingerprint": "90d9d431c3f21e0887d9a4c4c410e099adec4283cbac95238419adc54258cecf" + }, + { + "pointer": "#/paths//api/v1/projects/{project_id}/compliance-attestations/post/responses/409/content/application/json/schema/properties/error_code", + "role": "response", + "subject": { + "direction": "added", + "values": [ + "\"stale_review_context\"" + ] + }, + "old": [ + "\"linked_reference_invalid\"", + "\"linked_reference_required\"", + "\"stale_fingerprints\"", + "\"stale_statement\"" + ], + "new": [ + "\"linked_reference_invalid\"", + "\"linked_reference_required\"", + "\"stale_fingerprints\"", + "\"stale_review_context\"", + "\"stale_statement\"" + ], + "fingerprint": "82343c77d722469d216256967b99f02824fac1d1bee2a120f7a6104a5a5f068c" + }, + { + "pointer": "#/paths//api/v1/projects/{project_id}/compliance-attestations/post/responses/409/content/application/json/schema/properties/message", + "role": "response", + "subject": { + "direction": "added", + "values": [ + "\"The agent or its standing attestation changed since it was displayed.\"" + ] + }, + "old": [ + "\"A linked document reference is not valid for this agent.\"", + "\"A statement of this kind needs at least one linked document reference.\"", + "\"The agent changed since it was displayed.\"", + "\"The statement changed since it was displayed.\"" + ], + "new": [ + "\"A linked document reference is not valid for this agent.\"", + "\"A statement of this kind needs at least one linked document reference.\"", + "\"The agent changed since it was displayed.\"", + "\"The agent or its standing attestation changed since it was displayed.\"", + "\"The statement changed since it was displayed.\"" + ], + "fingerprint": "bd00b9fee51a6575400df4a15d58584c1df0f473bff78b568d3b3b92ae112bcb" + } + ], + "reason": "The sign operation's 409 answers a new closed reason stale_review_context (with its fixed message) when the echoed review_context no longer matches the server's recomputation. Pre-release contract, feature dark in production, backend and frontend change in the same slice.", + "version": "Unreleased pending (TraigentSchema, review_context; backend change pending)", + "pr": "pending (TraigentSchema, not yet opened)" + }, + { + "file": "agent_readiness/compliance_attestation_endpoints.json", + "rule": "required", + "findings": [ + { + "pointer": "#/paths//api/v1/projects/{project_id}/compliance-attestations/post/requestBody/content/application/json/schema", + "role": "request", + "subject": "review_context", + "old": false, + "new": true, + "fingerprint": "788eb146d6735c892b13ac5c53c7c186d5edf6ec9e0186dc886b75de10002aa8" + } + ], + "reason": "Attestation signing must echo review_context, the keyed freshness token read from the evidence response, so a signature is bound to the subject the signer reviewed. Coordinated pre-release break: the feature is dark in production and no external client signs; backend and frontend change in the same slice.", + "version": "Unreleased pending (TraigentSchema, review_context; backend change pending)", + "pr": "pending (TraigentSchema, not yet opened)" + }, + { + "file": "agent_readiness/compliance_evidence_response_schema.json", + "rule": "property_added", + "findings": [ + { + "pointer": "#/properties/ingredients/items/properties/review_context", + "role": "response", + "subject": "review_context", + "old": false, + "new": true, + "fingerprint": "4168aaf4afd50a070c88bb86d61e61f0a6ecc955a07d7aabcb54826ed89f0e6c" + } + ], + "reason": "A rows of the evidence response gain the review_context freshness token (string or null), a closed additive field that the signer echoes on sign. Pre-release contract; the backend is the only producer and the frontend reads it in the same slice.", + "version": "Unreleased pending (TraigentSchema, review_context; backend change pending)", + "pr": "pending (TraigentSchema, not yet opened)" + }, { "file": "evaluation/experiment_schema.json", "rule": "property_added", @@ -10517,7 +10731,7 @@ "fingerprint": "ec31f7b48772a83bb342974cb621deab96a1df1603d314a424a2e2b0feb378cc" } ], - "reason": "experiment_ref replaces experiment_id in the required set of the experiment trend response, following the move of the read to reference addressing. Pre-release contract with no external clients; the portal, both SDKs and the backend move in step with this change before adoption, so no released consumer is affected.", + "reason": "Experiment_ref replaces experiment_id in the required set of the experiment trend response, following the move of the read to reference addressing. Pre-release contract with no external clients; the portal, both SDKs and the backend move in step with this change before adoption, so no released consumer is affected.", "version": "Unreleased pending (TraigentSchema, feature/api-p33-w1b-experiment-read-contracts; backend API revision Phase 3 slice 3.3 window 1b)", "pr": "pending (TraigentSchema, feature/api-p33-w1b-experiment-read-contracts, not yet opened)" }, @@ -10764,7 +10978,7 @@ "fingerprint": "c05cb096f136affa4e3018fee4fb7735711ac9ff4a20cd79aca5af444da665a9" } ], - "reason": "truncated and empty_reason are added to the required list of the fine-tuning manifest response because the backend emits both on every successful export (core_domain_analytics_service.export_fine_tuning_manifest always sets 'truncated' and 'empty_reason', including empty and failed-to-record-job cases). Response-only requirement matching the real payload; it cannot reject any response the backend produces. A third-party producer or mock that omits them would now fail validation, which is the intended tightening: the old schema rejected the real payload, the new one accepts it.", + "reason": "Truncated and empty_reason are added to the required list of the fine-tuning manifest response because the backend emits both on every successful export (core_domain_analytics_service.export_fine_tuning_manifest always sets 'truncated' and 'empty_reason', including empty and failed-to-record-job cases). Response-only requirement matching the real payload; it cannot reject any response the backend produces. A third-party producer or mock that omits them would now fail validation, which is the intended tightening: the old schema rejected the real payload, the new one accepts it.", "version": "Unreleased (C3-PR1c, analytics contracts)", "pr": "pending (TraigentSchema, feature/api-p33-c3-analytics-contracts, not yet opened)" }, @@ -11064,7 +11278,7 @@ "fingerprint": "42c48b418108d39ce403798bdddde28344461c6c6c600d5bff500fa385f648ae" } ], - "reason": "path parameter takes the agent id the agents API returns; the agentref_ digest is retired for these routes and the service answers it with the masked 404. Clients must update their id validation and use the project-scoped paths", + "reason": "Path parameter takes the agent id the agents API returns; the agentref_ digest is retired for these routes and the service answers it with the masked 404. Clients must update their id validation and use the project-scoped paths", "version": "Unreleased", "pr": "pending (TraigentSchema, fix/reactive-agent-ref-is-agent-id)" } diff --git a/tests/test_compliance_applicability_contract.py b/tests/test_compliance_applicability_contract.py index 0de83ee9..a4323c5b 100644 --- a/tests/test_compliance_applicability_contract.py +++ b/tests/test_compliance_applicability_contract.py @@ -252,6 +252,17 @@ def test_valid_examples_conform(definition: str, factory: Any) -> None: _request, lambda r: r["decisions"][0].update(rationale="x" * 2001), ), + ( + "ApplicabilityRevisionCreateRequest", + _request, + lambda r: r["decisions"][0].update(decision="not_applicable", rationale=None) + or r["decisions"][0].pop("rationale"), + ), + ( + "ApplicabilityRevisionCreateRequest", + _request, + lambda r: r["decisions"][0].update(decision="not_applicable", rationale=" "), + ), ( "ApplicabilityRevisionCreateRequest", _request, @@ -440,3 +451,64 @@ def test_every_decision_record_names_the_revision_it_was_decided_in() -> None: assert _errors("ApplicabilityRevisionRecord", record) == [] record["decisions"][0].pop("decided_in_revision_id") assert _errors("ApplicabilityRevisionRecord", record) != [] + + +def test_not_applicable_requires_a_rationale_the_other_decisions_do_not() -> None: + """A not_applicable decision carries a non-empty rationale; the others may omit it.""" + + def item(decision: str, **extra: Any) -> dict[str, Any]: + return {"obligation_id": _OBL, "decision": decision, **extra} + + assert _errors("DecisionInput", item("not_applicable", rationale="Out of scope for this agent")) == [] + assert _errors("DecisionInput", item("not_applicable")) != [] + assert _errors("DecisionInput", item("not_applicable", rationale="")) != [] + assert _errors("DecisionInput", item("not_applicable", rationale=" \n\t ")) != [] + assert _errors("DecisionInput", item("applicable")) == [] + assert _errors("DecisionInput", item("unresolved")) == [] + assert _errors("DecisionItem", {"obligation_id": _OBL, "carry": True}) == [] + + +def test_rationale_required_is_a_closed_declared_400_on_the_write() -> None: + body = { + "success": False, + "message": "A rationale is required when an obligation is marked not applicable.", + "error": "rationale_required", + "error_code": "rationale_required", + } + assert _errors("RationaleRequiredError", body) == [] + assert _errors("RationaleRequiredError", {**body, "obligation_id": _OBL}) != [] + assert _errors("RationaleRequiredError", {**body, "error_code": "invalid_request"}) != [] + endpoints = load_json(ENDPOINTS_PATH) + post = endpoints["paths"]["/api/v1/projects/{project_id}/compliance-applicability"]["post"] + refs = [b["$ref"] for b in post["responses"]["400"]["content"]["application/json"]["schema"]["oneOf"]] + assert "./compliance_applicability_schema.json#/definitions/RationaleRequiredError" in refs + + +_BLANK_RATIONALES = [ + "", + " ", + " \t\n\r ", + "\u0085", + "\u00a0", + "\u200b", + "\u200c", + "\u200d", + "\ufeff", + "\u2060", + "\u3000", + " \ufeff\u200b\u2060 ", +] +_PRESENT_RATIONALES = ["a", "\ufeffa", "\u200bx\u200b", "\u05e9\u05dc\u05d5\u05dd", "\u4e2d\u6587", " why "] + + +@pytest.mark.parametrize("text", _BLANK_RATIONALES) +def test_a_blank_rationale_is_refused_for_not_applicable(text: str) -> None: + """Same case table as the backend and frontend tests: separators, controls, format characters.""" + item = {"obligation_id": _OBL, "decision": "not_applicable", "rationale": text} + assert _errors("DecisionInput", item) != [] + + +@pytest.mark.parametrize("text", _PRESENT_RATIONALES) +def test_a_visible_rationale_is_accepted_for_not_applicable(text: str) -> None: + item = {"obligation_id": _OBL, "decision": "not_applicable", "rationale": text} + assert _errors("DecisionInput", item) == [] diff --git a/tests/test_compliance_attestation_contract.py b/tests/test_compliance_attestation_contract.py index c83da062..3b2583c3 100644 --- a/tests/test_compliance_attestation_contract.py +++ b/tests/test_compliance_attestation_contract.py @@ -90,6 +90,7 @@ def _request() -> dict[str, Any]: "agent_id": "agent-1", "ingredient_id": "A1", "statement_digest": _DIGEST, + "review_context": "c" * 64, "outcome": "affirmed", "review_period_days": 90, } @@ -151,6 +152,10 @@ def test_valid_examples_conform(definition: str, factory: Any) -> None: ("definition", "factory", "mutate"), [ # Server-derived fields are never accepted from the client. + ("AttestationCreateRequest", _request, lambda r: r.pop("review_context")), + ("AttestationCreateRequest", _request, lambda r: r.update(review_context=None)), + ("AttestationCreateRequest", _request, lambda r: r.update(review_context="C" * 64)), + ("AttestationCreateRequest", _request, lambda r: r.update(review_context="c" * 63)), ("AttestationCreateRequest", _request, lambda r: r.update(signer_user_id="u")), ("AttestationCreateRequest", _request, lambda r: r.update(recorded_at=_NOW)), ("AttestationCreateRequest", _request, lambda r: r.update(tenant_id="t")), @@ -313,6 +318,7 @@ def test_evidence_response_accepts_an_attestation_summary_but_no_note() -> None: "title": "Example", "state": "SUPPORTED", "producer_ref": "ATTESTATION_RECORDS_V1", + "review_context": "d" * 64, "attestation": summary, "links": [], } @@ -484,3 +490,13 @@ def test_an_exported_record_requires_the_marker_fields(missing: str) -> None: record = _exported("current", "wording") del record[missing] assert _errors("ExportedAttestationRecord", record) != [] + + +def test_sign_operation_declares_stale_review_context_and_503() -> None: + operation = load_json(ENDPOINTS_PATH)["paths"][ + "/api/v1/projects/{project_id}/compliance-attestations" + ]["post"]["responses"] + body = operation["409"]["content"]["application/json"]["schema"]["properties"] + assert "stale_review_context" in body["error"]["enum"] + assert "stale_review_context" in body["error_code"]["enum"] + assert "503" in operation diff --git a/tests/test_compliance_document_ref_contract.py b/tests/test_compliance_document_ref_contract.py index 3bf52fd3..c07f7548 100644 --- a/tests/test_compliance_document_ref_contract.py +++ b/tests/test_compliance_document_ref_contract.py @@ -277,8 +277,43 @@ def test_endpoints_are_registered_and_wired() -> None: base, base + "/{reference_id}/withdrawals", "/api/v1/projects/{project_id}/agents/{agent_ref}/compliance-document-refs", + "/api/v1/projects/{project_id}/agents/{agent_ref}/compliance-document-refs/search", } for item in paths.values(): for operation in item.values(): assert operation["x-asserted-against-backend"] is False assert "429" in operation["responses"] + + +def test_search_is_a_body_only_read_with_a_closed_request() -> None: + base = "/api/v1/projects/{project_id}/agents/{agent_ref}/compliance-document-refs" + paths = load_json(ENDPOINTS_PATH)["paths"] + assert set(paths[base + "/search"]) == {"post"} + operation = paths[base + "/search"]["post"] + assert operation["operationId"] == "project_compliance_document_refs.search_compliance_document_references" + assert [p["name"] for p in operation["parameters"]] == ["project_id", "agent_ref"] + assert operation["x-replay"] == "read" + assert [p["in"] for p in operation["parameters"]] == ["path", "path"] + request_ref = operation["requestBody"]["content"]["application/json"]["schema"]["$ref"] + assert request_ref.endswith("#/definitions/DocumentReferenceSearchRequest") + ok = operation["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] + assert ok == paths[base]["get"]["responses"]["200"]["content"]["application/json"]["schema"][ + "$ref" + ] + assert {"400", "401", "403", "404", "429"} <= set(operation["responses"]) + for valid in ( + {"q": "tech"}, + {"q": "x" * 200, "include_withdrawn": True, "page": 3, "per_page": 100}, + ): + assert _errors("DocumentReferenceSearchRequest", valid) == [] + for invalid in ( + {}, + {"q": ""}, + {"q": "x" * 201}, + {"q": 5}, + {"q": "a", "page": 0}, + {"q": "a", "per_page": 101}, + {"q": "a", "include_withdrawn": "yes"}, + {"q": "a", "url": "https://x.example.test"}, + ): + assert _errors("DocumentReferenceSearchRequest", invalid) != [], invalid diff --git a/tests/test_compliance_evidence_contract.py b/tests/test_compliance_evidence_contract.py index 660a9a07..c4f09e0e 100644 --- a/tests/test_compliance_evidence_contract.py +++ b/tests/test_compliance_evidence_contract.py @@ -104,6 +104,7 @@ def _response() -> dict[str, Any]: "group": "Transparency", "title": "Example attestation", "state": "NOT_ASSESSED", + "review_context": "b" * 64, "links": [], }, ], @@ -156,6 +157,11 @@ def test_valid_populated_and_empty_packs() -> None: lambda r: r["ingredients"][0].update(group="Legal"), lambda r: r["ingredients"][0].update(producer_ref="free text"), lambda r: r["ingredients"][0].update(note="customer text"), + lambda r: r["ingredients"][1].pop("review_context"), # required on A rows + lambda r: r["ingredients"][1].update(review_context="B" * 64), + lambda r: r["ingredients"][1].update(review_context="b" * 63), + lambda r: r["ingredients"][0].update(review_context="b" * 64), # absent on non-A rows + lambda r: r["ingredients"][0].update(review_context=None), lambda r: r["ingredients"][0]["links"][0].update(relation="equal"), lambda r: r["ingredients"][0]["links"][0].update(relation="exact-ish"), lambda r: r["ingredients"][0]["links"][0].pop("limitations"), @@ -328,3 +334,10 @@ def test_coverage_ingredient_ids_over_cap_is_rejected_shape_only() -> None: assert len(set(unique)) == 101 assert _errors(_with_ids(**{**_ALL_EMPTY, "supported": unique[:100]})) == [] assert _errors(_with_ids(**{**_ALL_EMPTY, "supported": unique})) != [] + + +def test_review_context_is_a_digest_or_null_on_attestation_rows() -> None: + instance = copy.deepcopy(_response()) + assert _errors(instance) == [] + instance["ingredients"][1]["review_context"] = None + assert _errors(instance) == [] diff --git a/traigent_schema/schemas/agent_readiness/compliance_applicability_endpoints.json b/traigent_schema/schemas/agent_readiness/compliance_applicability_endpoints.json index d49c0284..39e243c3 100644 --- a/traigent_schema/schemas/agent_readiness/compliance_applicability_endpoints.json +++ b/traigent_schema/schemas/agent_readiness/compliance_applicability_endpoints.json @@ -44,11 +44,14 @@ } }, "400": { - "description": "Closed-request violation", + "description": "Closed-request violation. A not_applicable decision without a non-blank rationale is the distinct closed reason rationale_required; the body names no obligation and echoes no client text.", "content": { "application/json": { "schema": { - "$ref": "./agent_readiness_error_schema.json" + "oneOf": [ + { "$ref": "./agent_readiness_error_schema.json" }, + { "$ref": "./compliance_applicability_schema.json#/definitions/RationaleRequiredError" } + ] } } } diff --git a/traigent_schema/schemas/agent_readiness/compliance_applicability_schema.json b/traigent_schema/schemas/agent_readiness/compliance_applicability_schema.json index 462af245..f175642c 100644 --- a/traigent_schema/schemas/agent_readiness/compliance_applicability_schema.json +++ b/traigent_schema/schemas/agent_readiness/compliance_applicability_schema.json @@ -71,8 +71,16 @@ "type": "string", "minLength": 1, "maxLength": 2000, - "description": "Optional free text. CUSTOMER CONTENT: stored with the snapshot, returned only to project members, kept on user erasure, never logged and never sent to the Director, an LLM or observability." + "description": "Optional free text, except that it is REQUIRED (at least one character outside Unicode categories Z*, Cc and Cf: whitespace, control and zero-width/format characters alone count as blank; this schema lists the BMP code points explicitly, the server is the authority for the full rule) when `decision` is `not_applicable`. CUSTOMER CONTENT: stored with the snapshot, returned only to project members, kept on user erasure, never logged and never sent to the Director, an LLM or observability." } + }, + "if": { + "properties": { "decision": { "const": "not_applicable" } }, + "required": ["decision"] + }, + "then": { + "required": ["rationale"], + "properties": { "rationale": { "type": "string", "minLength": 1, "pattern": "[^\\u0000-\\u0020\\u007F-\\u00A0\\u00AD\\u0600-\\u0605\\u061C\\u06DD\\u070F\\u1680\\u180E\\u2000-\\u200F\\u2028-\\u202F\\u205F-\\u2064\\u2066-\\u206F\\u3000\\uFEFF\\uFFF9-\\uFFFB]" } } } }, "DecisionCarry": { @@ -89,6 +97,18 @@ "oneOf": [{ "$ref": "#/definitions/DecisionInput" }, { "$ref": "#/definitions/DecisionCarry" }], "description": "Either a new decision made in this submission, or `carry: true` for the predecessor's decision." }, + "RationaleRequiredError": { + "type": "object", + "additionalProperties": false, + "required": ["success", "message", "error", "error_code"], + "properties": { + "success": { "const": false }, + "message": { "const": "A rationale is required when an obligation is marked not applicable." }, + "error": { "const": "rationale_required" }, + "error_code": { "const": "rationale_required" } + }, + "description": "The closed 400 for a `not_applicable` decision whose rationale is absent, null, empty or whitespace only. Nothing is recorded. It names no obligation id and carries no client text." + }, "ApplicabilityRevisionCreateRequest": { "type": "object", "additionalProperties": false, diff --git a/traigent_schema/schemas/agent_readiness/compliance_attestation_endpoints.json b/traigent_schema/schemas/agent_readiness/compliance_attestation_endpoints.json index 19d3d72e..8cd24195 100644 --- a/traigent_schema/schemas/agent_readiness/compliance_attestation_endpoints.json +++ b/traigent_schema/schemas/agent_readiness/compliance_attestation_endpoints.json @@ -470,6 +470,7 @@ "enum": [ "The statement changed since it was displayed.", "The agent changed since it was displayed.", + "The agent or its standing attestation changed since it was displayed.", "A statement of this kind needs at least one linked document reference.", "A linked document reference is not valid for this agent." ] @@ -479,6 +480,7 @@ "enum": [ "stale_statement", "stale_fingerprints", + "stale_review_context", "linked_reference_required", "linked_reference_invalid" ] @@ -488,6 +490,7 @@ "enum": [ "stale_statement", "stale_fingerprints", + "stale_review_context", "linked_reference_required", "linked_reference_invalid" ] @@ -506,6 +509,16 @@ } } } + }, + "503": { + "description": "The server cannot issue or verify the review context right now; nothing is recorded", + "content": { + "application/json": { + "schema": { + "$ref": "./agent_readiness_error_schema.json" + } + } + } } } } diff --git a/traigent_schema/schemas/agent_readiness/compliance_attestation_schema.json b/traigent_schema/schemas/agent_readiness/compliance_attestation_schema.json index 5b6ef38a..14eb1cec 100644 --- a/traigent_schema/schemas/agent_readiness/compliance_attestation_schema.json +++ b/traigent_schema/schemas/agent_readiness/compliance_attestation_schema.json @@ -329,7 +329,8 @@ "ingredient_id", "statement_digest", "outcome", - "review_period_days" + "review_period_days", + "review_context" ], "properties": { "agent_id": { @@ -342,6 +343,11 @@ "type": "string", "pattern": "^[0-9a-f]{64}$" }, + "review_context": { + "type": "string", + "pattern": "^[0-9a-f]{64}$", + "description": "Echo the review_context of the evidence read the signer reviewed. A stale value is refused with 409 stale_review_context and nothing is recorded. Opaque, server-issued and never derived from customer text." + }, "outcome": { "$ref": "#/definitions/Outcome" }, diff --git a/traigent_schema/schemas/agent_readiness/compliance_document_ref_endpoints.json b/traigent_schema/schemas/agent_readiness/compliance_document_ref_endpoints.json index 4276f4ba..079dbaab 100644 --- a/traigent_schema/schemas/agent_readiness/compliance_document_ref_endpoints.json +++ b/traigent_schema/schemas/agent_readiness/compliance_document_ref_endpoints.json @@ -352,6 +352,108 @@ } } } + }, + "/api/v1/projects/{project_id}/agents/{agent_ref}/compliance-document-refs/search": { + "post": { + "summary": "Search the document references of one Agent by a substring of the link (project members only; the search text travels in the body)", + "description": "A read served as POST so the search text, which is customer content, stays out of URLs, access logs and traces. Case-insensitive substring match against the declared link; every character of the text is literal. Same members-only rule, response shape, ordering (newest first) and paging as the list; the text is never logged, audited or echoed. Takes no idempotency key and is never replayed.", + "operationId": "project_compliance_document_refs.search_compliance_document_references", + "x-asserted-against-backend": false, + "parameters": [ + { + "name": "project_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "agent_ref", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 512 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "./compliance_document_ref_schema.json#/definitions/DocumentReferenceSearchRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Matching document references, newest first", + "content": { + "application/json": { + "schema": { + "$ref": "./compliance_document_ref_schema.json#/definitions/DocumentReferenceListResponse" + } + } + } + }, + "400": { + "description": "Closed-request violation", + "content": { + "application/json": { + "schema": { + "$ref": "./agent_readiness_error_schema.json" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "./agent_readiness_error_schema.json" + } + } + } + }, + "403": { + "description": "Denied", + "content": { + "application/json": { + "schema": { + "$ref": "./agent_readiness_error_schema.json" + } + } + } + }, + "404": { + "description": "Not found, or the feature is off", + "content": { + "application/json": { + "schema": { + "$ref": "./agent_readiness_error_schema.json" + } + } + } + }, + "429": { + "description": "Too many requests \u2014 rate limit exceeded.", + "content": { + "application/json": { + "schema": { + "$ref": "../rate_limit_info_schema.json" + } + } + } + } + }, + "x-replay": "read" + } } } } diff --git a/traigent_schema/schemas/agent_readiness/compliance_document_ref_schema.json b/traigent_schema/schemas/agent_readiness/compliance_document_ref_schema.json index 587f268f..1b656b94 100644 --- a/traigent_schema/schemas/agent_readiness/compliance_document_ref_schema.json +++ b/traigent_schema/schemas/agent_readiness/compliance_document_ref_schema.json @@ -70,6 +70,36 @@ "properties": {}, "description": "Empty by design: a withdrawal carries no free text." }, + "DocumentReferenceSearchRequest": { + "type": "object", + "additionalProperties": false, + "required": ["q"], + "properties": { + "q": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "description": "CUSTOMER CONTENT. A case-insensitive substring matched against the declared document link; every character is literal (no wildcards). Trimmed of surrounding whitespace first: 1 to 200 characters after trimming, no control characters. Sent in the body only, never in a URL; the Backend never logs, audits or echoes it." + }, + "include_withdrawn": { + "type": "boolean", + "default": false, + "description": "When true, withdrawal rows and withdrawn references that match are listed too; a withdrawal row has no link, so it never matches a search text." + }, + "page": { + "type": "integer", + "minimum": 1, + "default": 1 + }, + "per_page": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 25 + } + }, + "description": "Closed request of the document-reference search (a read served as POST so the search text stays out of URLs). The agent is named in the path; actor, tenant and project are server-derived." + }, "DocumentReferenceRecord": { "type": "object", "additionalProperties": false, diff --git a/traigent_schema/schemas/agent_readiness/compliance_evidence_response_schema.json b/traigent_schema/schemas/agent_readiness/compliance_evidence_response_schema.json index 8b94780e..1d5f2630 100644 --- a/traigent_schema/schemas/agent_readiness/compliance_evidence_response_schema.json +++ b/traigent_schema/schemas/agent_readiness/compliance_evidence_response_schema.json @@ -206,8 +206,23 @@ "maxItems": 100, "description": "Obligations of the visible packs this ingredient may contribute to. Empty when no pack is visible.", "items": { "$ref": "#/definitions/RequirementLink" } + }, + "review_context": { + "type": ["string", "null"], + "pattern": "^[0-9a-f]{64}$", + "description": "Present on an `A` ingredient only (a string, or null when the agent configuration or the statement cannot be resolved, or the server has no key to issue it). An opaque, server-issued freshness token, keyed and never derived from customer text. A signer echoes it unchanged in AttestationCreateRequest.review_context; the server refuses a stale value with 409 stale_review_context. It is not evidence: never store, log or export it." } - } + }, + "allOf": [ + { + "if": { "properties": { "kind": { "const": "A" } }, "required": ["kind"] }, + "then": { "required": ["review_context"] } + }, + { + "if": { "properties": { "kind": { "enum": ["M", "D", "L"] } }, "required": ["kind"] }, + "then": { "not": { "required": ["review_context"] } } + } + ] } } } From 7578fd9a05d8ad4c57c146650272d0f7e607748b Mon Sep 17 00:00:00 2001 From: Nimrod Busany Date: Fri, 27 Nov 2026 08:22:32 +0200 Subject: [PATCH 2/2] docs(changelog): exact rationale rule and no rollout language in the compliance evidence fragment Co-Authored-By: Claude Opus 5.5 --- changelog.d/compliance-evidence-contracts.breaking.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/changelog.d/compliance-evidence-contracts.breaking.md b/changelog.d/compliance-evidence-contracts.breaking.md index a36804f3..3bb0e1c3 100644 --- a/changelog.d/compliance-evidence-contracts.breaking.md +++ b/changelog.d/compliance-evidence-contracts.breaking.md @@ -1,3 +1,3 @@ -- **A `not_applicable` applicability decision requires a rationale.** `DecisionInput` gains an if/then: when `decision` is `not_applicable`, `rationale` is required and must hold at least one non-whitespace character (the 2000-character cap is unchanged). `applicable` and `unresolved` keep it optional, and a `carry: true` item is not re-validated. The Backend refuses the violation with a closed 400 `rationale_required` (new closed body `RationaleRequiredError`, declared beside the shared error envelope on the write's 400, acknowledged in `scripts/breaking_schema_allowlist.json`). Pre-release contract in the same slice as the Backend and Frontend. -- **Compliance attestation signing is bound to the reviewed subject.** `AttestationCreateRequest` gains a REQUIRED `review_context` (64 lowercase hex): the opaque, server-issued, keyed freshness token the signer read from the evidence response (new `Ingredient.review_context`, required on `A` rows as a string or null, absent on other kinds). A stale value is refused with 409 `stale_review_context` and nothing is recorded; the sign operation also declares a 503 for when the server cannot issue or verify the token. The token is never derived from customer text and is not evidence: never store, log or export it. Coordinated pre-release break: the feature is dark in production and the Backend and Frontend change in the same slice (acknowledged in `scripts/breaking_schema_allowlist.json`). -- **Compliance document references: search by link substring (additive; contract only).** New operation `POST /api/v1/projects/{project_id}/agents/{agent_ref}/compliance-document-refs/search` (`project_compliance_document_refs.search_compliance_document_references`, `x-replay: read`) and closed request `DocumentReferenceSearchRequest` (`q` 1 to 200 characters after trimming, optional `include_withdrawn`, `page`, `per_page`). It is a read served as POST so the search text, which is customer content, stays out of URLs, logs and traces; it matches case-insensitively, as a literal substring, against the declared link and answers the existing `DocumentReferenceListResponse` with the list's ordering and paging. Marked `x-asserted-against-backend: false` until the Backend merges. Pinned by `tests/test_compliance_document_ref_contract.py`. +- **A `not_applicable` applicability decision requires a rationale.** `DecisionInput` gains an if/then: when `decision` is `not_applicable`, `rationale` is required and must hold at least one character that is not whitespace, a control character or a zero-width/format character (the 2000-character cap is unchanged). `applicable` and `unresolved` keep it optional, and a `carry: true` item is not re-validated. The Backend refuses the violation with a closed 400 `rationale_required` (new closed body `RationaleRequiredError`, declared beside the shared error envelope on the write's 400, acknowledged in `scripts/breaking_schema_allowlist.json`). +- **Compliance attestation signing is bound to the reviewed subject.** `AttestationCreateRequest` gains a REQUIRED `review_context` (64 lowercase hex): the opaque, server-issued, keyed freshness token the signer read from the evidence response (new `Ingredient.review_context`, required on `A` rows as a string or null, absent on other kinds). A stale value is refused with 409 `stale_review_context` and nothing is recorded; the sign operation also declares a 503 for when the server cannot issue or verify the token. The token is never derived from customer text and is not evidence: never store, log or export it. Acknowledged in `scripts/breaking_schema_allowlist.json`. +- **Compliance document references: search by link substring (additive; contract only).** New operation `POST /api/v1/projects/{project_id}/agents/{agent_ref}/compliance-document-refs/search` (`project_compliance_document_refs.search_compliance_document_references`, `x-replay: read`) and closed request `DocumentReferenceSearchRequest` (`q` 1 to 200 characters after trimming, optional `include_withdrawn`, `page`, `per_page`). It is a read served as POST so the search text, which is customer content, stays out of URLs, logs and traces; it matches case-insensitively, as a literal substring, against the declared link and answers the existing `DocumentReferenceListResponse` with the list's ordering and paging. Pinned by `tests/test_compliance_document_ref_contract.py`.