From dc9bd7e85853ca99d8ceba07b4f14ccc7db037b0 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 10:27:19 +0530 Subject: [PATCH 01/33] fix: address source classification inheritance review --- CHANGELOG.md | 10 + VERSIONING.md | 6 +- compatibility/golden/event-factory.json | 2 +- ...oved-action-completed-before-approval.json | 10 +- .../approved-action-digest-mismatch.json | 10 +- .../appraisal/approved-action-matches.json | 10 +- ...pproved-action-names-unknown-approval.json | 10 +- .../approved-action-policy-mismatch.json | 10 +- .../invalid/action-without-digest.json | 2 +- .../aggregate-cost-without-rollup.json | 2 +- .../derived-data-flow-missing-observed.json | 1 + .../invalid/model-call-with-rollup.json | 2 +- .../fixtures/invalid/numeric-timestamp.json | 2 +- conformance/fixtures/invalid/raw-content.json | 2 +- .../invalid/usage-without-measurement.json | 2 +- .../fixtures/invalid/zero-trace-id.json | 2 +- conformance/fixtures/valid/action.json | 2 +- conformance/fixtures/valid/approval.json | 2 +- conformance/fixtures/valid/data-flow.json | 2 +- .../fixtures/valid/derived-data-flow.json | 1 + conformance/fixtures/valid/evidence.json | 2 +- .../fixtures/valid/policy-decision.json | 2 +- conformance/fixtures/valid/usage.json | 2 +- .../0001-source-classification-inheritance.md | 58 ++++++ docs/data-flow-classification.md | 58 ++++++ packages/typescript/package-lock.json | 4 +- packages/typescript/package.json | 2 +- .../typescript/schemas/action.schema.json | 2 +- .../typescript/schemas/approval.schema.json | 2 +- .../typescript/schemas/common.schema.json | 2 +- .../typescript/schemas/data-flow.schema.json | 179 +++++++++++++++--- .../typescript/schemas/envelope.schema.json | 4 +- .../typescript/schemas/evidence.schema.json | 2 +- .../schemas/policy-decision.schema.json | 2 +- packages/typescript/schemas/usage.schema.json | 2 +- packages/typescript/src/data-flow.ts | 70 ++++++- packages/typescript/test/data-flow.test.ts | 71 ++++++- pyproject.toml | 2 +- spec/VERSION | 2 +- spec/schema/action.schema.json | 2 +- spec/schema/approval.schema.json | 2 +- spec/schema/common.schema.json | 2 +- spec/schema/data-flow.schema.json | 179 +++++++++++++++--- spec/schema/envelope.schema.json | 4 +- spec/schema/evidence.schema.json | 2 +- spec/schema/policy-decision.schema.json | 2 +- spec/schema/usage.schema.json | 2 +- src/agentrust_telemetry/__init__.py | 13 +- src/agentrust_telemetry/data_flow.py | 122 +++++++++++- .../schemas/action.schema.json | 2 +- .../schemas/approval.schema.json | 2 +- .../schemas/common.schema.json | 2 +- .../schemas/data-flow.schema.json | 179 +++++++++++++++--- .../schemas/envelope.schema.json | 4 +- .../schemas/evidence.schema.json | 2 +- .../schemas/policy-decision.schema.json | 2 +- .../schemas/usage.schema.json | 2 +- tests/test_data_flow.py | 116 ++++++++++++ tests/test_installed_python_controls.py | 2 +- tools/installed_python_controls.py | 2 + 60 files changed, 1045 insertions(+), 158 deletions(-) create mode 100644 conformance/fixtures/invalid/derived-data-flow-missing-observed.json create mode 100644 conformance/fixtures/valid/derived-data-flow.json create mode 100644 docs/adr/0001-source-classification-inheritance.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 90bb344..5ceaa2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ ### Added +- Derived `data_flow.observed` events can include trusted source classifications. + The Python and TypeScript SDKs compute an effective label using an explicit + per-taxonomy order, retain the output classifier's observed label, and emit + metadata-only source references. Source-label authenticity and lineage + completeness remain caller responsibilities. The contract advances to + `0.2.0-alpha.1`: consumers pinned to pre-0.2 schema copies reject events + carrying these fields and must update their schema copy before consuming + opted-in derived-flow events; producers that omit both fields retain the + previous event shape. + - Shared Python/TypeScript delivery-fault tests for dropped, duplicated and reordered projections and lost persistence acknowledgements, plus Python OpenTelemetry sampling/export-failure coverage. These tests do not establish diff --git a/VERSIONING.md b/VERSIONING.md index 30ea1a9..d298789 100644 --- a/VERSIONING.md +++ b/VERSIONING.md @@ -6,9 +6,9 @@ The telemetry contract uses semantic versioning independently from SDK versions, - Minor: backward-compatible optional field, event, or enum addition with defined older-consumer behavior. - Major: removal, changed meaning, new required field, or incompatible canonicalization. -The current contract version is `0.1.0-alpha.6`. Python publishes the equivalent -PEP 440 version `0.1.0a6`; npm and the Git tag use `0.1.0-alpha.6` and -`v0.1.0-alpha.6`. Pre-1.0 changes may be incompatible and must be called out +The current contract version is `0.2.0-alpha.1`. Python publishes the equivalent +PEP 440 version `0.2.0a1`; npm and the Git tag use `0.2.0-alpha.1` and +`v0.2.0-alpha.1`. Pre-1.0 changes may be incompatible and must be called out explicitly. Published GitHub releases are the sole release trigger. The release tag must diff --git a/compatibility/golden/event-factory.json b/compatibility/golden/event-factory.json index 651f08a..0bd06d0 100644 --- a/compatibility/golden/event-factory.json +++ b/compatibility/golden/event-factory.json @@ -1 +1 @@ -{"agent_id":"agent-1","event_id":"018f0f7d-7a13-7cc2-8000-000000000042","event_type":"usage.recorded","input_tokens":7,"operation":"chat","producer":{"name":"parity-test","version":"1.0.0"},"run_id":"run-1","scope":"model_call","spec_version":"0.1.0-alpha.6","time_unix_nano":"1787079000000000000","workflow_id":"workflow-1"} +{"agent_id":"agent-1","event_id":"018f0f7d-7a13-7cc2-8000-000000000042","event_type":"usage.recorded","input_tokens":7,"operation":"chat","producer":{"name":"parity-test","version":"1.0.0"},"run_id":"run-1","scope":"model_call","spec_version":"0.2.0-alpha.1","time_unix_nano":"1787079000000000000","workflow_id":"workflow-1"} diff --git a/conformance/appraisal/approved-action-completed-before-approval.json b/conformance/appraisal/approved-action-completed-before-approval.json index b413e7f..def1cfa 100644 --- a/conformance/appraisal/approved-action-completed-before-approval.json +++ b/conformance/appraisal/approved-action-completed-before-approval.json @@ -29,7 +29,7 @@ "resource_type": "git.repository", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079600000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "workflow_id": "workflow-build-feature" @@ -51,7 +51,7 @@ "requested_at_unix_nano": "1787079500000000000", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079500000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "policy_event_id": "018f0f7d-7a13-7cc2-8000-000000000001", @@ -77,7 +77,7 @@ "requested_at_unix_nano": "1787079500000000000", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079580000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "policy_event_id": "018f0f7d-7a13-7cc2-8000-000000000001", @@ -115,12 +115,12 @@ "id": "requirements-graph", "kind": "knowledge_graph" }, - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079400000000000", "transformation": "metadata_only" }, { - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "event_id": "018f0f7d-7a13-7cc2-8000-000000000006", "event_type": "action.executed", "time_unix_nano": "1787079570000000000", diff --git a/conformance/appraisal/approved-action-digest-mismatch.json b/conformance/appraisal/approved-action-digest-mismatch.json index b7d88d1..35c89f5 100644 --- a/conformance/appraisal/approved-action-digest-mismatch.json +++ b/conformance/appraisal/approved-action-digest-mismatch.json @@ -29,7 +29,7 @@ "resource_type": "git.repository", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079600000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "workflow_id": "workflow-build-feature" @@ -51,7 +51,7 @@ "requested_at_unix_nano": "1787079500000000000", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079500000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "policy_event_id": "018f0f7d-7a13-7cc2-8000-000000000001", @@ -77,7 +77,7 @@ "requested_at_unix_nano": "1787079500000000000", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079580000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "policy_event_id": "018f0f7d-7a13-7cc2-8000-000000000001", @@ -115,12 +115,12 @@ "id": "requirements-graph", "kind": "knowledge_graph" }, - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079400000000000", "transformation": "metadata_only" }, { - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "event_id": "018f0f7d-7a13-7cc2-8000-000000000006", "event_type": "action.executed", "time_unix_nano": "1787079650000000000", diff --git a/conformance/appraisal/approved-action-matches.json b/conformance/appraisal/approved-action-matches.json index 7e1dccd..36d703f 100644 --- a/conformance/appraisal/approved-action-matches.json +++ b/conformance/appraisal/approved-action-matches.json @@ -29,7 +29,7 @@ "resource_type": "git.repository", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079600000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "workflow_id": "workflow-build-feature" @@ -51,7 +51,7 @@ "requested_at_unix_nano": "1787079500000000000", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079500000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "policy_event_id": "018f0f7d-7a13-7cc2-8000-000000000001", @@ -77,7 +77,7 @@ "requested_at_unix_nano": "1787079500000000000", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079580000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "policy_event_id": "018f0f7d-7a13-7cc2-8000-000000000001", @@ -115,12 +115,12 @@ "id": "requirements-graph", "kind": "knowledge_graph" }, - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079400000000000", "transformation": "metadata_only" }, { - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "event_id": "018f0f7d-7a13-7cc2-8000-000000000006", "event_type": "action.executed", "time_unix_nano": "1787079650000000000", diff --git a/conformance/appraisal/approved-action-names-unknown-approval.json b/conformance/appraisal/approved-action-names-unknown-approval.json index 807b746..630db97 100644 --- a/conformance/appraisal/approved-action-names-unknown-approval.json +++ b/conformance/appraisal/approved-action-names-unknown-approval.json @@ -29,7 +29,7 @@ "resource_type": "git.repository", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079600000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "workflow_id": "workflow-build-feature" @@ -51,7 +51,7 @@ "requested_at_unix_nano": "1787079500000000000", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079500000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "policy_event_id": "018f0f7d-7a13-7cc2-8000-000000000001", @@ -77,7 +77,7 @@ "requested_at_unix_nano": "1787079500000000000", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079580000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "policy_event_id": "018f0f7d-7a13-7cc2-8000-000000000001", @@ -115,12 +115,12 @@ "id": "requirements-graph", "kind": "knowledge_graph" }, - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079400000000000", "transformation": "metadata_only" }, { - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "event_id": "018f0f7d-7a13-7cc2-8000-000000000006", "event_type": "action.executed", "time_unix_nano": "1787079650000000000", diff --git a/conformance/appraisal/approved-action-policy-mismatch.json b/conformance/appraisal/approved-action-policy-mismatch.json index 1d0fa0d..80a781a 100644 --- a/conformance/appraisal/approved-action-policy-mismatch.json +++ b/conformance/appraisal/approved-action-policy-mismatch.json @@ -29,7 +29,7 @@ "resource_type": "git.repository", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079600000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "workflow_id": "workflow-build-feature" @@ -51,7 +51,7 @@ "requested_at_unix_nano": "1787079500000000000", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079500000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "policy_event_id": "018f0f7d-7a13-7cc2-8000-000000000001", @@ -77,7 +77,7 @@ "requested_at_unix_nano": "1787079500000000000", "run_id": "run-governed-sdlc-001", "span_id": "00f067aa0ba902b7", - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079580000000000", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "policy_event_id": "018f0f7d-7a13-7cc2-8000-000000000001", @@ -115,12 +115,12 @@ "id": "requirements-graph", "kind": "knowledge_graph" }, - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "time_unix_nano": "1787079400000000000", "transformation": "metadata_only" }, { - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "event_id": "018f0f7d-7a13-7cc2-8000-000000000006", "event_type": "action.executed", "time_unix_nano": "1787079650000000000", diff --git a/conformance/fixtures/invalid/action-without-digest.json b/conformance/fixtures/invalid/action-without-digest.json index e213968..974395c 100644 --- a/conformance/fixtures/invalid/action-without-digest.json +++ b/conformance/fixtures/invalid/action-without-digest.json @@ -1,5 +1,5 @@ { - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "event_id": "018f0f7d-7a13-7cc2-8000-000000000096", "event_type": "action.executed", "time_unix_nano": "1787079650000000000", diff --git a/conformance/fixtures/invalid/aggregate-cost-without-rollup.json b/conformance/fixtures/invalid/aggregate-cost-without-rollup.json index e30cf7a..90a90af 100644 --- a/conformance/fixtures/invalid/aggregate-cost-without-rollup.json +++ b/conformance/fixtures/invalid/aggregate-cost-without-rollup.json @@ -1 +1 @@ -{"agent_id":"agent-1","cost":{"amount":1,"currency":"USD","source":"aggregate"},"event_id":"018f0f7d-7a13-7cc2-8000-000000000009","event_type":"usage.recorded","operation":"chat","producer":{"name":"test","version":"1"},"run_id":"run-1","scope":"model_call","spec_version":"0.1.0-alpha.6","time_unix_nano":"1"} +{"agent_id":"agent-1","cost":{"amount":1,"currency":"USD","source":"aggregate"},"event_id":"018f0f7d-7a13-7cc2-8000-000000000009","event_type":"usage.recorded","operation":"chat","producer":{"name":"test","version":"1"},"run_id":"run-1","scope":"model_call","spec_version":"0.2.0-alpha.1","time_unix_nano":"1"} diff --git a/conformance/fixtures/invalid/derived-data-flow-missing-observed.json b/conformance/fixtures/invalid/derived-data-flow-missing-observed.json new file mode 100644 index 0000000..7c1fb0c --- /dev/null +++ b/conformance/fixtures/invalid/derived-data-flow-missing-observed.json @@ -0,0 +1 @@ +{"agent_id":"spiffe://example.test/agent/architect","classification":{"producer":"example-dlp","taxonomy":"example.enterprise.v1","value":"confidential"},"content_digest":{"algorithm":"sha256","value":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"},"destination":{"id":"architecture-agent","kind":"agent"},"direction":"read","event_id":"018f0f7d-7a13-7cc2-8000-000000000004","event_type":"data_flow.observed","policy_decision":"allow","producer":{"name":"example-dataflow-adapter","version":"0.1.0"},"purpose":"generate_architecture","run_id":"run-governed-sdlc-001","size_bytes":18342,"source":{"id":"requirements-graph","kind":"knowledge_graph"},"source_classifications":[{"classification":{"producer":"example-dlp","taxonomy":"example.enterprise.v1","value":"public"},"source":{"id":"public-faq","kind":"knowledge_graph"}},{"classification":{"producer":"trusted-label-store","taxonomy":"example.enterprise.v1","value":"confidential"},"source":{"id":"private-staff-notes","kind":"document"}}],"spec_version":"0.2.0-alpha.1","time_unix_nano":"1787079400000000000","transformation":"aggregated"} diff --git a/conformance/fixtures/invalid/model-call-with-rollup.json b/conformance/fixtures/invalid/model-call-with-rollup.json index b00a499..469f23d 100644 --- a/conformance/fixtures/invalid/model-call-with-rollup.json +++ b/conformance/fixtures/invalid/model-call-with-rollup.json @@ -1 +1 @@ -{"agent_id":"agent-1","aggregation":{"cost_coverage":0,"cost_sources":[],"event_count":1,"method":"sum","token_coverage":{"input_tokens":1}},"event_id":"018f0f7d-7a13-7cc2-8000-000000000010","event_type":"usage.recorded","input_tokens":1,"operation":"chat","producer":{"name":"test","version":"1"},"run_id":"run-1","scope":"model_call","spec_version":"0.1.0-alpha.6","time_unix_nano":"1"} +{"agent_id":"agent-1","aggregation":{"cost_coverage":0,"cost_sources":[],"event_count":1,"method":"sum","token_coverage":{"input_tokens":1}},"event_id":"018f0f7d-7a13-7cc2-8000-000000000010","event_type":"usage.recorded","input_tokens":1,"operation":"chat","producer":{"name":"test","version":"1"},"run_id":"run-1","scope":"model_call","spec_version":"0.2.0-alpha.1","time_unix_nano":"1"} diff --git a/conformance/fixtures/invalid/numeric-timestamp.json b/conformance/fixtures/invalid/numeric-timestamp.json index cbce58e..b589784 100644 --- a/conformance/fixtures/invalid/numeric-timestamp.json +++ b/conformance/fixtures/invalid/numeric-timestamp.json @@ -1 +1 @@ -{"agent_id":"agent-1","event_id":"018f0f7d-7a13-7cc2-8000-000000000011","event_type":"usage.recorded","input_tokens":1,"operation":"chat","producer":{"name":"test","version":"1"},"run_id":"run-1","scope":"model_call","spec_version":"0.1.0-alpha.6","time_unix_nano":1787079700000000000} +{"agent_id":"agent-1","event_id":"018f0f7d-7a13-7cc2-8000-000000000011","event_type":"usage.recorded","input_tokens":1,"operation":"chat","producer":{"name":"test","version":"1"},"run_id":"run-1","scope":"model_call","spec_version":"0.2.0-alpha.1","time_unix_nano":1787079700000000000} diff --git a/conformance/fixtures/invalid/raw-content.json b/conformance/fixtures/invalid/raw-content.json index 6ff4aca..48c1fd7 100644 --- a/conformance/fixtures/invalid/raw-content.json +++ b/conformance/fixtures/invalid/raw-content.json @@ -1 +1 @@ -{"agent_id":"spiffe://example.test/agent/coder","event_id":"018f0f7d-7a13-7cc2-8000-000000000006","event_type":"usage.recorded","input_tokens":10,"operation":"chat","producer":{"name":"bad-adapter","version":"0.1.0"},"prompt":"copy the production credential","run_id":"run-unsafe","scope":"model_call","spec_version":"0.1.0-alpha.6","time_unix_nano":"1787079700000000000"} +{"agent_id":"spiffe://example.test/agent/coder","event_id":"018f0f7d-7a13-7cc2-8000-000000000006","event_type":"usage.recorded","input_tokens":10,"operation":"chat","producer":{"name":"bad-adapter","version":"0.1.0"},"prompt":"copy the production credential","run_id":"run-unsafe","scope":"model_call","spec_version":"0.2.0-alpha.1","time_unix_nano":"1787079700000000000"} diff --git a/conformance/fixtures/invalid/usage-without-measurement.json b/conformance/fixtures/invalid/usage-without-measurement.json index 393c2b5..bb2c634 100644 --- a/conformance/fixtures/invalid/usage-without-measurement.json +++ b/conformance/fixtures/invalid/usage-without-measurement.json @@ -1 +1 @@ -{"agent_id":"agent-1","event_id":"018f0f7d-7a13-7cc2-8000-000000000008","event_type":"usage.recorded","operation":"chat","producer":{"name":"test","version":"1"},"run_id":"run-1","scope":"model_call","spec_version":"0.1.0-alpha.6","time_unix_nano":"1"} +{"agent_id":"agent-1","event_id":"018f0f7d-7a13-7cc2-8000-000000000008","event_type":"usage.recorded","operation":"chat","producer":{"name":"test","version":"1"},"run_id":"run-1","scope":"model_call","spec_version":"0.2.0-alpha.1","time_unix_nano":"1"} diff --git a/conformance/fixtures/invalid/zero-trace-id.json b/conformance/fixtures/invalid/zero-trace-id.json index 43d6490..d06e0e0 100644 --- a/conformance/fixtures/invalid/zero-trace-id.json +++ b/conformance/fixtures/invalid/zero-trace-id.json @@ -1 +1 @@ -{"action_type":"repository.read","agent_id":"agent-1","decision":"allow","enforcement_mode":"enforce","evaluation_duration_ns":1,"event_id":"018f0f7d-7a13-7cc2-8000-000000000007","event_type":"policy.decision","policy":{"engine":"opa","engine_version":"1.0"},"producer":{"name":"test","version":"1"},"resource_type":"repository","run_id":"run-1","spec_version":"0.1.0-alpha.6","time_unix_nano":"1","trace_id":"00000000000000000000000000000000"} +{"action_type":"repository.read","agent_id":"agent-1","decision":"allow","enforcement_mode":"enforce","evaluation_duration_ns":1,"event_id":"018f0f7d-7a13-7cc2-8000-000000000007","event_type":"policy.decision","policy":{"engine":"opa","engine_version":"1.0"},"producer":{"name":"test","version":"1"},"resource_type":"repository","run_id":"run-1","spec_version":"0.2.0-alpha.1","time_unix_nano":"1","trace_id":"00000000000000000000000000000000"} diff --git a/conformance/fixtures/valid/action.json b/conformance/fixtures/valid/action.json index f7bc2da..6ebd6a5 100644 --- a/conformance/fixtures/valid/action.json +++ b/conformance/fixtures/valid/action.json @@ -1,5 +1,5 @@ { - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "event_id": "018f0f7d-7a13-7cc2-8000-000000000006", "event_type": "action.executed", "time_unix_nano": "1787079650000000000", diff --git a/conformance/fixtures/valid/approval.json b/conformance/fixtures/valid/approval.json index 55daab7..aa2232b 100644 --- a/conformance/fixtures/valid/approval.json +++ b/conformance/fixtures/valid/approval.json @@ -1 +1 @@ -{"action_digest":{"algorithm":"sha256","value":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"},"actor_id":"reviewer-7d91","actor_type":"human","agent_id":"spiffe://example.test/agent/coder","approval_id":"approval-001","event_id":"018f0f7d-7a13-7cc2-8000-000000000002","event_type":"approval.approved","producer":{"name":"example-approval-adapter","version":"0.1.0"},"requested_at_unix_nano":"1787079500000000000","run_id":"run-governed-sdlc-001","span_id":"00f067aa0ba902b7","spec_version":"0.1.0-alpha.6","time_unix_nano":"1787079580000000000","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"} +{"action_digest":{"algorithm":"sha256","value":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"},"actor_id":"reviewer-7d91","actor_type":"human","agent_id":"spiffe://example.test/agent/coder","approval_id":"approval-001","event_id":"018f0f7d-7a13-7cc2-8000-000000000002","event_type":"approval.approved","producer":{"name":"example-approval-adapter","version":"0.1.0"},"requested_at_unix_nano":"1787079500000000000","run_id":"run-governed-sdlc-001","span_id":"00f067aa0ba902b7","spec_version":"0.2.0-alpha.1","time_unix_nano":"1787079580000000000","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"} diff --git a/conformance/fixtures/valid/data-flow.json b/conformance/fixtures/valid/data-flow.json index 9ac5e63..35c1124 100644 --- a/conformance/fixtures/valid/data-flow.json +++ b/conformance/fixtures/valid/data-flow.json @@ -1 +1 @@ -{"agent_id":"spiffe://example.test/agent/architect","classification":{"producer":"example-dlp","taxonomy":"example.enterprise.v1","value":"confidential"},"content_digest":{"algorithm":"sha256","value":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"},"destination":{"id":"architecture-agent","kind":"agent"},"direction":"read","event_id":"018f0f7d-7a13-7cc2-8000-000000000004","event_type":"data_flow.observed","policy_decision":"allow","producer":{"name":"example-dataflow-adapter","version":"0.1.0"},"purpose":"generate_architecture","run_id":"run-governed-sdlc-001","size_bytes":18342,"source":{"id":"requirements-graph","kind":"knowledge_graph"},"spec_version":"0.1.0-alpha.6","time_unix_nano":"1787079400000000000","transformation":"metadata_only"} +{"agent_id":"spiffe://example.test/agent/architect","classification":{"producer":"example-dlp","taxonomy":"example.enterprise.v1","value":"confidential"},"content_digest":{"algorithm":"sha256","value":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"},"destination":{"id":"architecture-agent","kind":"agent"},"direction":"read","event_id":"018f0f7d-7a13-7cc2-8000-000000000004","event_type":"data_flow.observed","policy_decision":"allow","producer":{"name":"example-dataflow-adapter","version":"0.1.0"},"purpose":"generate_architecture","run_id":"run-governed-sdlc-001","size_bytes":18342,"source":{"id":"requirements-graph","kind":"knowledge_graph"},"spec_version":"0.2.0-alpha.1","time_unix_nano":"1787079400000000000","transformation":"metadata_only"} diff --git a/conformance/fixtures/valid/derived-data-flow.json b/conformance/fixtures/valid/derived-data-flow.json new file mode 100644 index 0000000..36c0b61 --- /dev/null +++ b/conformance/fixtures/valid/derived-data-flow.json @@ -0,0 +1 @@ +{"agent_id":"spiffe://example.test/agent/architect","classification":{"producer":"example-dlp","taxonomy":"example.enterprise.v1","value":"confidential"},"content_digest":{"algorithm":"sha256","value":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"},"destination":{"id":"architecture-agent","kind":"agent"},"direction":"read","event_id":"018f0f7d-7a13-7cc2-8000-000000000004","event_type":"data_flow.observed","observed_classification":{"producer":"example-dlp","taxonomy":"example.enterprise.v1","value":"public"},"policy_decision":"allow","producer":{"name":"example-dataflow-adapter","version":"0.1.0"},"purpose":"generate_architecture","run_id":"run-governed-sdlc-001","size_bytes":18342,"source":{"id":"requirements-graph","kind":"knowledge_graph"},"source_classifications":[{"classification":{"producer":"example-dlp","taxonomy":"example.enterprise.v1","value":"public"},"source":{"id":"public-faq","kind":"knowledge_graph"}},{"classification":{"producer":"trusted-label-store","taxonomy":"example.enterprise.v1","value":"confidential"},"source":{"id":"private-staff-notes","kind":"document"}}],"spec_version":"0.2.0-alpha.1","time_unix_nano":"1787079400000000000","transformation":"aggregated"} diff --git a/conformance/fixtures/valid/evidence.json b/conformance/fixtures/valid/evidence.json index e3345f6..c64bd27 100644 --- a/conformance/fixtures/valid/evidence.json +++ b/conformance/fixtures/valid/evidence.json @@ -1 +1 @@ -{"capture_profile":"metadata_only","chain_digest":{"algorithm":"sha256","value":"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"},"completeness":"complete","event_id":"018f0f7d-7a13-7cc2-8000-000000000005","event_type":"evidence.run_closed","producer":{"name":"agentrust-telemetry","version":"0.1.0-alpha.6"},"run_id":"run-governed-sdlc-001","sequence":14,"spec_version":"0.1.0-alpha.6","time_unix_nano":"1787079700000000000"} +{"capture_profile":"metadata_only","chain_digest":{"algorithm":"sha256","value":"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"},"completeness":"complete","event_id":"018f0f7d-7a13-7cc2-8000-000000000005","event_type":"evidence.run_closed","producer":{"name":"agentrust-telemetry","version":"0.2.0-alpha.1"},"run_id":"run-governed-sdlc-001","sequence":14,"spec_version":"0.2.0-alpha.1","time_unix_nano":"1787079700000000000"} diff --git a/conformance/fixtures/valid/policy-decision.json b/conformance/fixtures/valid/policy-decision.json index 9be6cb8..7bcb967 100644 --- a/conformance/fixtures/valid/policy-decision.json +++ b/conformance/fixtures/valid/policy-decision.json @@ -1 +1 @@ -{"action_type":"repository.write","agent_id":"spiffe://example.test/agent/coder","decision":"deny","enforcement_mode":"enforce","evaluation_duration_ns":182000,"event_id":"018f0f7d-7a13-7cc2-8000-000000000001","event_type":"policy.decision","policy":{"bundle_digest":{"algorithm":"sha256","value":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"engine":"cedar","engine_version":"4.3.0","policy_id":"repo-write"},"producer":{"name":"example-policy-adapter","version":"0.1.0"},"reason_codes":["BRANCH_PROTECTED"],"resource_type":"git.repository","run_id":"run-governed-sdlc-001","span_id":"00f067aa0ba902b7","spec_version":"0.1.0-alpha.6","time_unix_nano":"1787079600000000000","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","workflow_id":"workflow-build-feature"} +{"action_type":"repository.write","agent_id":"spiffe://example.test/agent/coder","decision":"deny","enforcement_mode":"enforce","evaluation_duration_ns":182000,"event_id":"018f0f7d-7a13-7cc2-8000-000000000001","event_type":"policy.decision","policy":{"bundle_digest":{"algorithm":"sha256","value":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"engine":"cedar","engine_version":"4.3.0","policy_id":"repo-write"},"producer":{"name":"example-policy-adapter","version":"0.1.0"},"reason_codes":["BRANCH_PROTECTED"],"resource_type":"git.repository","run_id":"run-governed-sdlc-001","span_id":"00f067aa0ba902b7","spec_version":"0.2.0-alpha.1","time_unix_nano":"1787079600000000000","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","workflow_id":"workflow-build-feature"} diff --git a/conformance/fixtures/valid/usage.json b/conformance/fixtures/valid/usage.json index 88e82bb..62b16a9 100644 --- a/conformance/fixtures/valid/usage.json +++ b/conformance/fixtures/valid/usage.json @@ -1 +1 @@ -{"agent_id":"spiffe://example.test/agent/coder","cost":{"amount":0.0124,"currency":"USD","pricing_version":"provider-2026-08-01","source":"provider"},"event_id":"018f0f7d-7a13-7cc2-8000-000000000003","event_type":"usage.recorded","input_tokens":4200,"operation":"chat","output_tokens":812,"producer":{"name":"example-usage-adapter","version":"0.1.0"},"provider":"example-ai","request_model":"example-model-2","run_id":"run-governed-sdlc-001","scope":"model_call","spec_version":"0.1.0-alpha.6","time_unix_nano":"1787079590000000000","workflow_id":"workflow-build-feature"} +{"agent_id":"spiffe://example.test/agent/coder","cost":{"amount":0.0124,"currency":"USD","pricing_version":"provider-2026-08-01","source":"provider"},"event_id":"018f0f7d-7a13-7cc2-8000-000000000003","event_type":"usage.recorded","input_tokens":4200,"operation":"chat","output_tokens":812,"producer":{"name":"example-usage-adapter","version":"0.1.0"},"provider":"example-ai","request_model":"example-model-2","run_id":"run-governed-sdlc-001","scope":"model_call","spec_version":"0.2.0-alpha.1","time_unix_nano":"1787079590000000000","workflow_id":"workflow-build-feature"} diff --git a/docs/adr/0001-source-classification-inheritance.md b/docs/adr/0001-source-classification-inheritance.md new file mode 100644 index 0000000..c077702 --- /dev/null +++ b/docs/adr/0001-source-classification-inheritance.md @@ -0,0 +1,58 @@ +# ADR 0001: Source classification inheritance for derived data flows + +- Status: Accepted for implementation after maintainer review on 2026-11-19 +- Date: 2026-11-19 +- Scope: `data_flow.observed` contract and Python/TypeScript reference SDKs + +## Context + +An agent may derive a summary, extract, aggregate, or memory from multiple inputs. The classifier that observes the resulting value may assign a less restrictive label than one or more contributing sources. Recording only that output label loses the source-side classification context and can make the derived event appear less restricted than its inputs. + +The SDK does not own customer data stores or DLP policy. It cannot safely fetch or reclassify source content, and model-authored labels are not an acceptable trust source. + +## Decision + +Accept already-computed source classification metadata from the caller. The caller is responsible for obtaining it from a trusted upstream DLP classifier, policy engine, or label store and for supplying the complete set of contributing sources. + +For a single explicitly declared total order within one taxonomy, compute: + +`effective = max(observed_output, source_1, ..., source_n)` + +The order is supplied as least-to-most restrictive labels; labels are never compared lexically and no universal hierarchy is inferred. + +The optional event fields are: + +- `observed_classification`: the output classifier's result before inheritance; +- `source_classifications`: one source endpoint and its classification metadata for every supplied contributing source; +- `classification`: the effective result after applying the explicit order. + +The two lineage fields must appear together. Existing direct data-flow calls remain unchanged when neither is supplied. The implementation bounds lineage to 1,024 sources and rejects empty lineage, duplicate endpoint references, unknown labels, mixed taxonomies, and missing or mismatched ordering input. Events carry references and labels only, never source content. + +## Trust and security boundaries + +This mechanism propagates caller-supplied labels; it does not authenticate them, prove lineage completeness, or make an incorrect source label correct. Integrators must not pass model-authored labels without trusted validation. + +It does not implement declassification, reclassification, revocation propagation, or authorization. Those controls remain with the policy and data-governance systems that own the source data. + +Endpoint identifiers remain metadata and may still be sensitive. Integrators must pseudonymize them according to the existing data-flow classification guidance. + +## Alternatives considered + +1. **Classify source values inside the SDK.** Rejected because the SDK does not own source data access or a trusted policy engine. It would expand data exposure and couple the telemetry SDK to adopter-specific DLP systems. +2. **Trust labels generated by the model or transformation.** Rejected because model-authored labels are not an authoritative source of policy metadata. +3. **Derive order from label strings.** Rejected because lexical order is not a classification policy and differs across taxonomies. +4. **Emit only the effective label.** Rejected because it hides the output classifier's observation and source lineage, weakening auditability. + +## Compatibility and versioning + +The contract version advances from `0.1.0-alpha.6` to `0.2.0-alpha.1`, with matching Python and TypeScript package versions. The two lineage fields remain optional as a pair, so producers that omit them retain the previous event shape. + +The schemas are closed to unknown properties. A consumer pinned to a pre-0.2 schema will reject an event containing the new fields even though they are optional at the producer. Consumers must update their schema copy to 0.2 before processing opted-in derived-flow events. This is an explicit pre-1.0 compatibility change and is called out in the Unreleased changelog. + +## Consequences + +- Adopters retain responsibility for source-label provenance and complete lineage. +- The source and output classifications become auditable without retaining raw data. +- The same explicit taxonomy order is required in both SDKs. +- Consumers pinned to pre-0.2 closed schemas must update their schema copy before processing events that opt into source-label inheritance. +- A future declassification or retroactive reclassification design must be handled separately. diff --git a/docs/data-flow-classification.md b/docs/data-flow-classification.md index e5d4dd3..58f3937 100644 --- a/docs/data-flow-classification.md +++ b/docs/data-flow-classification.md @@ -26,3 +26,61 @@ The AGT `DataAccessDecision` adapter maps only its allow/deny result, agent ID, evaluation time, and ordered `DataClassification` tier under taxonomy `agt.data_classification.v1`. It deliberately omits free-form reason, categories, owner, geography, and matched-policy fields. + + +## Derived flows and source-label inheritance + +For a summary, aggregation, extraction, or memory compaction step, pass the +trusted classifications of every contributing source together with an explicit +`ClassificationOrder` for their shared taxonomy. The ordered `levels` are listed +from least to most restrictive. The SDK records the classifier's output label as +`observed_classification`, computes `classification` as the strictest of that +output and every source label, and emits `source_classifications` containing only +source endpoint references and classification metadata. + +```python +order = ClassificationOrder( + "example.enterprise.v1", + ("public", "internal", "confidential", "restricted"), +) + +classified_data_flow( + factory, + output_classifier, + summary, + run_id="run-1", + agent_id="agent-1", + direction="output", + source=DataEndpoint("transform", "summarizer"), + destination=DataEndpoint("memory", "summary-1"), + purpose="memory-compaction", + source_classifications=[ + SourceClassification( + DataEndpoint("document", "staff-notes"), + ClassificationResult( + "example.enterprise.v1", "confidential", "trusted-label-store" + ), + ), + ], + classification_order=order, +) +``` + +This API accepts **already-computed source labels**. It does not authenticate +those labels, verify that the source list is complete, or prevent callers from +passing untrusted/model-authored labels. Obtain source labels from a trusted +classifier or policy/label store, and supply the complete lineage. Unknown labels, +mixed taxonomies, duplicate source references, missing lineage, or a missing +order are rejected. At most 1,024 sources may be attached to one event. The SDK +does not infer declassification or implement reclassification/revocation +propagation. Existing direct-flow calls remain unchanged when the two new +arguments are omitted. Both lineage fields are optional as a pair, so producers +that do not opt in retain the previous event shape. However, consumers using +pre-0.2 closed schemas reject events that include these fields; update the schema +copy to 0.2 before consuming opted-in derived-flow events. + +Source identity is the `(kind, id)` pair. Because `id` is optional, two distinct +same-kind endpoints without IDs are treated as duplicate references; provide +stable, pseudonymized IDs when multiple same-kind sources must be distinguished. +The Python API accepts a bounded iterable of source classifications, while the +TypeScript API requires a readonly array. diff --git a/packages/typescript/package-lock.json b/packages/typescript/package-lock.json index 7ff630d..52a6334 100644 --- a/packages/typescript/package-lock.json +++ b/packages/typescript/package-lock.json @@ -1,12 +1,12 @@ { "name": "@agentrust-io/telemetry", - "version": "0.1.0-alpha.6", + "version": "0.2.0-alpha.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@agentrust-io/telemetry", - "version": "0.1.0-alpha.6", + "version": "0.2.0-alpha.1", "license": "MIT", "dependencies": { "@opentelemetry/api": "^1.9.0", diff --git a/packages/typescript/package.json b/packages/typescript/package.json index af838a9..c868aca 100644 --- a/packages/typescript/package.json +++ b/packages/typescript/package.json @@ -1,6 +1,6 @@ { "name": "@agentrust-io/telemetry", - "version": "0.1.0-alpha.6", + "version": "0.2.0-alpha.1", "description": "TypeScript reference SDK for AgenTrust governance telemetry", "keywords": ["ai-agents", "governance", "opentelemetry", "observability", "telemetry"], "type": "module", diff --git a/packages/typescript/schemas/action.schema.json b/packages/typescript/schemas/action.schema.json index d54edaa..b9059ae 100644 --- a/packages/typescript/schemas/action.schema.json +++ b/packages/typescript/schemas/action.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/action.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/action.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/packages/typescript/schemas/approval.schema.json b/packages/typescript/schemas/approval.schema.json index f63560d..59be43b 100644 --- a/packages/typescript/schemas/approval.schema.json +++ b/packages/typescript/schemas/approval.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/approval.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/approval.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/packages/typescript/schemas/common.schema.json b/packages/typescript/schemas/common.schema.json index 784a609..e55d5a2 100644 --- a/packages/typescript/schemas/common.schema.json +++ b/packages/typescript/schemas/common.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/common.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/common.schema.json", "$defs": { "event_id": {"type": "string", "format": "uuid"}, "time_unix_nano": {"type": "string", "pattern": "^(0|[1-9][0-9]{0,19})$"}, diff --git a/packages/typescript/schemas/data-flow.schema.json b/packages/typescript/schemas/data-flow.schema.json index 694b1a5..195b288 100644 --- a/packages/typescript/schemas/data-flow.schema.json +++ b/packages/typescript/schemas/data-flow.schema.json @@ -1,43 +1,170 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/data-flow.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/data-flow.schema.json", "allOf": [ - {"$ref": "envelope.schema.json"}, + { + "$ref": "envelope.schema.json" + }, { "type": "object", - "required": ["agent_id", "event_type", "direction", "source", "destination", "classification", "purpose", "policy_decision"], + "required": [ + "agent_id", + "event_type", + "direction", + "source", + "destination", + "classification", + "purpose", + "policy_decision" + ], "properties": { - "event_type": {"const": "data_flow.observed"}, - "direction": {"enum": ["input", "output", "read", "write", "send", "receive"]}, - "source": {"$ref": "#/$defs/endpoint"}, - "destination": {"$ref": "#/$defs/endpoint"}, + "event_type": { + "const": "data_flow.observed" + }, + "direction": { + "enum": [ + "input", + "output", + "read", + "write", + "send", + "receive" + ] + }, + "source": { + "$ref": "#/$defs/endpoint" + }, + "destination": { + "$ref": "#/$defs/endpoint" + }, "classification": { - "type": "object", - "required": ["taxonomy", "value", "producer"], - "properties": { - "taxonomy": {"$ref": "common.schema.json#/$defs/nonempty"}, - "value": {"$ref": "common.schema.json#/$defs/nonempty"}, - "producer": {"$ref": "common.schema.json#/$defs/nonempty"} + "$ref": "#/$defs/classification" + }, + "purpose": { + "$ref": "common.schema.json#/$defs/nonempty" + }, + "policy_decision": { + "enum": [ + "allow", + "deny", + "challenge", + "not_applicable", + "error", + "not_evaluated" + ] + }, + "content_digest": { + "$ref": "common.schema.json#/$defs/digest" + }, + "size_bytes": { + "type": "integer", + "minimum": 0 + }, + "token_count": { + "type": "integer", + "minimum": 0 + }, + "media_type": { + "type": "string", + "minLength": 1, + "maxLength": 255 + }, + "transformation": { + "enum": [ + "none", + "redacted", + "masked", + "tokenized", + "aggregated", + "metadata_only" + ] + }, + "observed_classification": { + "$ref": "#/$defs/classification" + }, + "source_classifications": { + "type": "array", + "minItems": 1, + "maxItems": 1024, + "items": { + "type": "object", + "required": [ + "source", + "classification" + ], + "properties": { + "source": { + "$ref": "#/$defs/endpoint" + }, + "classification": { + "$ref": "#/$defs/classification" + } + }, + "additionalProperties": false + } + } + }, + "allOf": [ + { + "if": { + "required": [ + "observed_classification" + ] }, - "additionalProperties": false - }, - "purpose": {"$ref": "common.schema.json#/$defs/nonempty"}, - "policy_decision": {"enum": ["allow", "deny", "challenge", "not_applicable", "error", "not_evaluated"]}, - "content_digest": {"$ref": "common.schema.json#/$defs/digest"}, - "size_bytes": {"type": "integer", "minimum": 0}, - "token_count": {"type": "integer", "minimum": 0}, - "media_type": {"type": "string", "minLength": 1, "maxLength": 255}, - "transformation": {"enum": ["none", "redacted", "masked", "tokenized", "aggregated", "metadata_only"]} - } + "then": { + "required": [ + "source_classifications" + ] + } + }, + { + "if": { + "required": [ + "source_classifications" + ] + }, + "then": { + "required": [ + "observed_classification" + ] + } + } + ] } ], "$defs": { "endpoint": { "type": "object", - "required": ["kind"], + "required": [ + "kind" + ], + "properties": { + "kind": { + "$ref": "common.schema.json#/$defs/nonempty" + }, + "id": { + "$ref": "common.schema.json#/$defs/nonempty" + } + }, + "additionalProperties": false + }, + "classification": { + "type": "object", + "required": [ + "taxonomy", + "value", + "producer" + ], "properties": { - "kind": {"$ref": "common.schema.json#/$defs/nonempty"}, - "id": {"$ref": "common.schema.json#/$defs/nonempty"} + "taxonomy": { + "$ref": "common.schema.json#/$defs/nonempty" + }, + "value": { + "$ref": "common.schema.json#/$defs/nonempty" + }, + "producer": { + "$ref": "common.schema.json#/$defs/nonempty" + } }, "additionalProperties": false } diff --git a/packages/typescript/schemas/envelope.schema.json b/packages/typescript/schemas/envelope.schema.json index e6cb7af..af64291 100644 --- a/packages/typescript/schemas/envelope.schema.json +++ b/packages/typescript/schemas/envelope.schema.json @@ -1,10 +1,10 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/envelope.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/envelope.schema.json", "type": "object", "required": ["spec_version", "event_id", "event_type", "time_unix_nano", "run_id", "producer"], "properties": { - "spec_version": {"const": "0.1.0-alpha.6"}, + "spec_version": {"const": "0.2.0-alpha.1"}, "event_id": {"$ref": "common.schema.json#/$defs/event_id"}, "event_type": {"type": "string", "pattern": "^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$", "maxLength": 128}, "time_unix_nano": {"$ref": "common.schema.json#/$defs/time_unix_nano"}, diff --git a/packages/typescript/schemas/evidence.schema.json b/packages/typescript/schemas/evidence.schema.json index f3aa2c6..9d0ae04 100644 --- a/packages/typescript/schemas/evidence.schema.json +++ b/packages/typescript/schemas/evidence.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/evidence.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/evidence.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/packages/typescript/schemas/policy-decision.schema.json b/packages/typescript/schemas/policy-decision.schema.json index bd48937..29da5fe 100644 --- a/packages/typescript/schemas/policy-decision.schema.json +++ b/packages/typescript/schemas/policy-decision.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/policy-decision.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/policy-decision.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/packages/typescript/schemas/usage.schema.json b/packages/typescript/schemas/usage.schema.json index 90bd5d0..2ce149b 100644 --- a/packages/typescript/schemas/usage.schema.json +++ b/packages/typescript/schemas/usage.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/usage.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/usage.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/packages/typescript/src/data-flow.ts b/packages/typescript/src/data-flow.ts index 7437ab4..9b79cd4 100644 --- a/packages/typescript/src/data-flow.ts +++ b/packages/typescript/src/data-flow.ts @@ -12,16 +12,80 @@ export class DataEndpoint { constructor(readonly kind: string, readonly id?: string) { identifier(kind, "endpoint kind"); if (id !== undefined) identifier(id, "endpoint id"); } asEventValue(): {kind: string; id?: string} { return {kind: this.kind, ...(this.id === undefined ? {} : {id: this.id})}; } } + +export class SourceClassification { + constructor(readonly source: DataEndpoint, readonly classification: ClassificationResult) { + if (!(source instanceof DataEndpoint)) throw new TypeError("source must be a DataEndpoint"); + if (!(classification instanceof ClassificationResult)) throw new TypeError("classification must be a ClassificationResult"); + } +} + +export class ClassificationOrder { + readonly levels: readonly string[]; + + constructor(readonly taxonomy: string, levels: readonly string[]) { + identifier(taxonomy, "classification taxonomy"); + if (!Array.isArray(levels) || levels.length === 0) throw new Error("classification levels must be a non-empty array"); + for (const level of levels) identifier(level, "classification level"); + if (new Set(levels).size !== levels.length) throw new Error("classification levels must be unique"); + this.levels = Object.freeze([...levels]); + } + + rank(result: ClassificationResult): number { + if (!(result instanceof ClassificationResult)) throw new TypeError("classification must be a ClassificationResult"); + if (result.taxonomy !== this.taxonomy) throw new Error(`taxonomy mismatch: expected ${this.taxonomy}, got ${result.taxonomy}`); + const rank = this.levels.indexOf(result.value); + if (rank < 0) throw new Error(`unknown classification value for ${this.taxonomy}: ${result.value}`); + return rank; + } +} + +function derivedClassificationFields( + observed: ClassificationResult, + sources: readonly SourceClassification[] | undefined, + order: ClassificationOrder | undefined, +): Record { + if (sources === undefined && order === undefined) return {}; + if (sources === undefined || order === undefined) throw new Error("sourceClassifications and classificationOrder must be supplied together"); + if (!(order instanceof ClassificationOrder)) throw new TypeError("classificationOrder must be a ClassificationOrder"); + order.rank(observed); + if (!Array.isArray(sources) || sources.length === 0) throw new Error("derived data must identify at least one source"); + if (sources.length > 1024) throw new Error("derived data may identify at most 1024 sources"); + + const seen = new Set(); + let effective = observed; + let effectiveRank = order.rank(observed); + const sourceValues = sources.map((record) => { + if (!(record instanceof SourceClassification)) throw new TypeError("each source must be a SourceClassification"); + const key = `${record.source.kind}\u0000${record.source.id ?? ""}`; + if (seen.has(key)) throw new Error("duplicate source reference"); + seen.add(key); + const rank = order.rank(record.classification); + if (rank > effectiveRank) { effective = record.classification; effectiveRank = rank; } + return { + source: record.source.asEventValue(), + classification: {taxonomy: record.classification.taxonomy, value: record.classification.value, producer: record.classification.producer}, + }; + }); + + return { + classification: {taxonomy: effective.taxonomy, value: effective.value, producer: effective.producer}, + observed_classification: {taxonomy: observed.taxonomy, value: observed.value, producer: observed.producer}, + source_classifications: sourceValues, + }; +} + export interface DataClassifier {classify(value: unknown): ClassificationResult} -export function classifiedDataFlow(factory: EventFactory, classifier: DataClassifier, value: unknown, options: {runId: string; agentId: string; direction: string; source: DataEndpoint; destination: DataEndpoint; purpose: string; policyDecision?: string; contentDigest?: Digest; sizeBytes?: number; tokenCount?: number; mediaType?: string; transformation?: string; envelope?: Omit}): NormalizedEvent { +export function classifiedDataFlow(factory: EventFactory, classifier: DataClassifier, value: unknown, options: {runId: string; agentId: string; direction: string; source: DataEndpoint; destination: DataEndpoint; purpose: string; policyDecision?: string; contentDigest?: Digest; sizeBytes?: number; tokenCount?: number; mediaType?: string; transformation?: string; sourceClassifications?: readonly SourceClassification[]; classificationOrder?: ClassificationOrder; envelope?: Omit}): NormalizedEvent { const result = classifier.classify(value); if (!(result instanceof ClassificationResult)) throw new TypeError("classifier must return ClassificationResult"); identifier(options.purpose, "purpose"); if (options.mediaType !== undefined && (!MEDIA_TYPE.test(options.mediaType) || options.mediaType.length > 255)) throw new Error("mediaType must be a parameter-free type/subtype identifier"); for (const [field, amount] of [["sizeBytes", options.sizeBytes], ["tokenCount", options.tokenCount]] as const) if (amount !== undefined && (!Number.isSafeInteger(amount) || amount < 0)) throw new Error(`${field} must be a non-negative safe integer`); + const derived = derivedClassificationFields(result, options.sourceClassifications, options.classificationOrder); return factory.build("data_flow.observed", {runId: options.runId, agentId: options.agentId, ...options.envelope}, { - direction: options.direction, source: options.source.asEventValue(), destination: options.destination.asEventValue(), classification: {taxonomy: result.taxonomy, value: result.value, producer: result.producer}, purpose: options.purpose, policy_decision: options.policyDecision ?? "not_evaluated", + direction: options.direction, source: options.source.asEventValue(), destination: options.destination.asEventValue(), classification: (derived.classification as Record | undefined) ?? {taxonomy: result.taxonomy, value: result.value, producer: result.producer}, ...omitClassification(derived), purpose: options.purpose, policy_decision: options.policyDecision ?? "not_evaluated", ...present("content_digest", options.contentDigest), ...present("size_bytes", options.sizeBytes), ...present("token_count", options.tokenCount), ...present("media_type", options.mediaType), ...present("transformation", options.transformation), }); } @@ -41,6 +105,8 @@ export function agtDataAccessFlow(factory: EventFactory, decision: Record classification}, undefined, {...options, agentId: required(rec.agent_id, "AGT data access agent_id"), policyDecision: rec.allowed ? "allow" : "deny", envelope: {timeUnixNano: timestampNs(rec.evaluated_at, "evaluated_at"), ...options.envelope}}); } +function omitClassification(fields: Record): Record { const {classification: _classification, ...rest} = fields; return rest; } + function identifier(value: unknown, field: string): string { if (typeof value !== "string" || !IDENTIFIER.test(value) || value.includes("://")) throw new Error(`${field} must be a 1-256 character metadata identifier without whitespace, URLs, query strings, fragments, or key/value delimiters`); return value; } function required(value: unknown, field: string): string { if (typeof value !== "string" || !value) throw new Error(`${field} must be a non-empty string`); return value; } function object(value: unknown, field: string): Record { if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${field} must be an object`); return value as Record; } diff --git a/packages/typescript/test/data-flow.test.ts b/packages/typescript/test/data-flow.test.ts index 6d10e30..1250b1e 100644 --- a/packages/typescript/test/data-flow.test.ts +++ b/packages/typescript/test/data-flow.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import {agtDataAccessFlow, ClassificationResult, classifiedDataFlow, DataEndpoint, EventFactory, SchemaValidator} from "../src/index.js"; +import {agtDataAccessFlow, ClassificationOrder, ClassificationResult, classifiedDataFlow, DataEndpoint, EventFactory, SchemaValidator, SourceClassification} from "../src/index.js"; const factory = new EventFactory(SchemaValidator.bundled(), {name: "data-tests", version: "1"}, () => 1n, () => "018f0f7d-7a13-7cc2-8000-000000000042"); test("classifier sees content while the event contains only closed metadata", () => { @@ -22,3 +22,72 @@ test("AGT access maps only tier, decision, agent, and time", () => { assert.throws(() => agtDataAccessFlow(factory, {...decision, evaluated_at: "1969-12-31T23:59:59Z"}, {runId: "run-1", direction: "read", source: new DataEndpoint("database", "customer-records"), destination: new DataEndpoint("agent", "builder"), purpose: "requirements-analysis"}), /evaluated_at is invalid/); assert.throws(() => agtDataAccessFlow(factory, null as unknown as Record, {runId: "run-1", direction: "read", source: new DataEndpoint("database", "customer-records"), destination: new DataEndpoint("agent", "builder"), purpose: "requirements-analysis"}), /must be an object/); }); + + +test("derived flow inherits the strictest source label and emits metadata only", () => { + const taxonomy = "example.enterprise.v1"; + const order = new ClassificationOrder(taxonomy, ["public", "internal", "confidential", "restricted"]); + const observed = new ClassificationResult(taxonomy, "public", "output-dlp"); + const event = classifiedDataFlow(factory, {classify: () => observed}, "summary text", { + runId: "run-1", agentId: "agent-1", direction: "output", + source: new DataEndpoint("transform", "summarizer"), + destination: new DataEndpoint("memory", "summary-1"), purpose: "memory-compaction", + transformation: "aggregated", classificationOrder: order, + sourceClassifications: [ + new SourceClassification(new DataEndpoint("document", "public-faq"), new ClassificationResult(taxonomy, "public", "source-dlp")), + new SourceClassification(new DataEndpoint("document", "staff-notes"), new ClassificationResult(taxonomy, "confidential", "trusted-label-store")), + ], + }); + assert.equal((event.classification as Record).value, "confidential"); + assert.equal((event.observed_classification as Record).value, "public"); + assert.equal((event.source_classifications as unknown[]).length, 2); + assert.equal(JSON.stringify(event).includes("summary text"), false); +}); +test("derived flow rejects missing, duplicate, and incomparable source labels", () => { + const taxonomy = "example.enterprise.v1"; + const order = new ClassificationOrder(taxonomy, ["public", "confidential"]); + const output = new ClassificationResult(taxonomy, "public", "dlp"); + const options = {runId: "r", agentId: "a", direction: "output", source: new DataEndpoint("transform"), destination: new DataEndpoint("memory"), purpose: "compaction"}; + assert.throws(() => classifiedDataFlow(factory, {classify: () => output}, "summary", {...options, sourceClassifications: []}), /supplied together/); + assert.throws(() => classifiedDataFlow(factory, {classify: () => output}, "summary", {...options, sourceClassifications: [], classificationOrder: order}), /at least one source/); + const duplicate = new SourceClassification(new DataEndpoint("document", "same"), new ClassificationResult(taxonomy, "confidential", "dlp")); + assert.throws(() => classifiedDataFlow(factory, {classify: () => output}, "summary", {...options, sourceClassifications: [duplicate, duplicate], classificationOrder: order}), /duplicate source/); + const mismatched = new SourceClassification(new DataEndpoint("document", "other"), new ClassificationResult("example.other.v1", "confidential", "dlp")); + assert.throws(() => classifiedDataFlow(factory, {classify: () => output}, "summary", {...options, sourceClassifications: [mismatched], classificationOrder: order}), /taxonomy mismatch/); + const unknown = new SourceClassification(new DataEndpoint("document", "unknown"), new ClassificationResult(taxonomy, "top_secret", "dlp")); + assert.throws(() => classifiedDataFlow(factory, {classify: () => output}, "summary", {...options, sourceClassifications: [unknown], classificationOrder: order}), /unknown classification value/); + const tooMany = Array.from({length: 1025}, (_, index) => new SourceClassification(new DataEndpoint("document", `source-${index}`), new ClassificationResult(taxonomy, "public", "dlp"))); + assert.throws(() => classifiedDataFlow(factory, {classify: () => output}, "summary", {...options, sourceClassifications: tooMany, classificationOrder: order}), /at most 1024/); + const exactlyLimit = Array.from({length: 1024}, (_, index) => new SourceClassification(new DataEndpoint("document", `source-${index}`), new ClassificationResult(taxonomy, "public", "dlp"))); + const atLimit = classifiedDataFlow(factory, {classify: () => output}, "summary", {...options, sourceClassifications: exactlyLimit, classificationOrder: order}); + assert.equal((atLimit.source_classifications as unknown[]).length, 1024); +}); + + +test("output classification is not downgraded and wins ties", () => { + const taxonomy = "example.enterprise.v1"; + const order = new ClassificationOrder(taxonomy, ["public", "confidential", "restricted"]); + const source = new SourceClassification( + new DataEndpoint("document", "staff-notes"), + new ClassificationResult(taxonomy, "confidential", "trusted-label-store"), + ); + const options = { + runId: "run-1", agentId: "agent-1", direction: "output", + source: new DataEndpoint("transform", "summarizer"), + destination: new DataEndpoint("memory", "summary-1"), + purpose: "memory-compaction", + sourceClassifications: [source], + classificationOrder: order, + }; + + const stricterOutput = new ClassificationResult(taxonomy, "restricted", "output-dlp"); + const event = classifiedDataFlow(factory, {classify: () => stricterOutput}, "summary", options); + assert.equal((event.classification as Record).value, "restricted"); + assert.equal((event.classification as Record).producer, "output-dlp"); + + const tiedOutput = new ClassificationResult(taxonomy, "confidential", "output-dlp"); + const tiedEvent = classifiedDataFlow(factory, {classify: () => tiedOutput}, "summary", options); + assert.equal((tiedEvent.classification as Record).value, "confidential"); + assert.equal((tiedEvent.classification as Record).producer, "output-dlp"); +}); + diff --git a/pyproject.toml b/pyproject.toml index 7fc3940..8871199 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "agentrust-telemetry" -version = "0.1.0a6" +version = "0.2.0a1" description = "Backend-neutral governance telemetry for AI-agent runtimes" readme = "README.md" requires-python = ">=3.10" diff --git a/spec/VERSION b/spec/VERSION index 88b971b..21c9ee8 100644 --- a/spec/VERSION +++ b/spec/VERSION @@ -1 +1 @@ -0.1.0-alpha.6 +0.2.0-alpha.1 diff --git a/spec/schema/action.schema.json b/spec/schema/action.schema.json index d54edaa..b9059ae 100644 --- a/spec/schema/action.schema.json +++ b/spec/schema/action.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/action.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/action.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/spec/schema/approval.schema.json b/spec/schema/approval.schema.json index f63560d..59be43b 100644 --- a/spec/schema/approval.schema.json +++ b/spec/schema/approval.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/approval.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/approval.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/spec/schema/common.schema.json b/spec/schema/common.schema.json index 784a609..e55d5a2 100644 --- a/spec/schema/common.schema.json +++ b/spec/schema/common.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/common.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/common.schema.json", "$defs": { "event_id": {"type": "string", "format": "uuid"}, "time_unix_nano": {"type": "string", "pattern": "^(0|[1-9][0-9]{0,19})$"}, diff --git a/spec/schema/data-flow.schema.json b/spec/schema/data-flow.schema.json index 694b1a5..195b288 100644 --- a/spec/schema/data-flow.schema.json +++ b/spec/schema/data-flow.schema.json @@ -1,43 +1,170 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/data-flow.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/data-flow.schema.json", "allOf": [ - {"$ref": "envelope.schema.json"}, + { + "$ref": "envelope.schema.json" + }, { "type": "object", - "required": ["agent_id", "event_type", "direction", "source", "destination", "classification", "purpose", "policy_decision"], + "required": [ + "agent_id", + "event_type", + "direction", + "source", + "destination", + "classification", + "purpose", + "policy_decision" + ], "properties": { - "event_type": {"const": "data_flow.observed"}, - "direction": {"enum": ["input", "output", "read", "write", "send", "receive"]}, - "source": {"$ref": "#/$defs/endpoint"}, - "destination": {"$ref": "#/$defs/endpoint"}, + "event_type": { + "const": "data_flow.observed" + }, + "direction": { + "enum": [ + "input", + "output", + "read", + "write", + "send", + "receive" + ] + }, + "source": { + "$ref": "#/$defs/endpoint" + }, + "destination": { + "$ref": "#/$defs/endpoint" + }, "classification": { - "type": "object", - "required": ["taxonomy", "value", "producer"], - "properties": { - "taxonomy": {"$ref": "common.schema.json#/$defs/nonempty"}, - "value": {"$ref": "common.schema.json#/$defs/nonempty"}, - "producer": {"$ref": "common.schema.json#/$defs/nonempty"} + "$ref": "#/$defs/classification" + }, + "purpose": { + "$ref": "common.schema.json#/$defs/nonempty" + }, + "policy_decision": { + "enum": [ + "allow", + "deny", + "challenge", + "not_applicable", + "error", + "not_evaluated" + ] + }, + "content_digest": { + "$ref": "common.schema.json#/$defs/digest" + }, + "size_bytes": { + "type": "integer", + "minimum": 0 + }, + "token_count": { + "type": "integer", + "minimum": 0 + }, + "media_type": { + "type": "string", + "minLength": 1, + "maxLength": 255 + }, + "transformation": { + "enum": [ + "none", + "redacted", + "masked", + "tokenized", + "aggregated", + "metadata_only" + ] + }, + "observed_classification": { + "$ref": "#/$defs/classification" + }, + "source_classifications": { + "type": "array", + "minItems": 1, + "maxItems": 1024, + "items": { + "type": "object", + "required": [ + "source", + "classification" + ], + "properties": { + "source": { + "$ref": "#/$defs/endpoint" + }, + "classification": { + "$ref": "#/$defs/classification" + } + }, + "additionalProperties": false + } + } + }, + "allOf": [ + { + "if": { + "required": [ + "observed_classification" + ] }, - "additionalProperties": false - }, - "purpose": {"$ref": "common.schema.json#/$defs/nonempty"}, - "policy_decision": {"enum": ["allow", "deny", "challenge", "not_applicable", "error", "not_evaluated"]}, - "content_digest": {"$ref": "common.schema.json#/$defs/digest"}, - "size_bytes": {"type": "integer", "minimum": 0}, - "token_count": {"type": "integer", "minimum": 0}, - "media_type": {"type": "string", "minLength": 1, "maxLength": 255}, - "transformation": {"enum": ["none", "redacted", "masked", "tokenized", "aggregated", "metadata_only"]} - } + "then": { + "required": [ + "source_classifications" + ] + } + }, + { + "if": { + "required": [ + "source_classifications" + ] + }, + "then": { + "required": [ + "observed_classification" + ] + } + } + ] } ], "$defs": { "endpoint": { "type": "object", - "required": ["kind"], + "required": [ + "kind" + ], + "properties": { + "kind": { + "$ref": "common.schema.json#/$defs/nonempty" + }, + "id": { + "$ref": "common.schema.json#/$defs/nonempty" + } + }, + "additionalProperties": false + }, + "classification": { + "type": "object", + "required": [ + "taxonomy", + "value", + "producer" + ], "properties": { - "kind": {"$ref": "common.schema.json#/$defs/nonempty"}, - "id": {"$ref": "common.schema.json#/$defs/nonempty"} + "taxonomy": { + "$ref": "common.schema.json#/$defs/nonempty" + }, + "value": { + "$ref": "common.schema.json#/$defs/nonempty" + }, + "producer": { + "$ref": "common.schema.json#/$defs/nonempty" + } }, "additionalProperties": false } diff --git a/spec/schema/envelope.schema.json b/spec/schema/envelope.schema.json index e6cb7af..af64291 100644 --- a/spec/schema/envelope.schema.json +++ b/spec/schema/envelope.schema.json @@ -1,10 +1,10 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/envelope.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/envelope.schema.json", "type": "object", "required": ["spec_version", "event_id", "event_type", "time_unix_nano", "run_id", "producer"], "properties": { - "spec_version": {"const": "0.1.0-alpha.6"}, + "spec_version": {"const": "0.2.0-alpha.1"}, "event_id": {"$ref": "common.schema.json#/$defs/event_id"}, "event_type": {"type": "string", "pattern": "^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$", "maxLength": 128}, "time_unix_nano": {"$ref": "common.schema.json#/$defs/time_unix_nano"}, diff --git a/spec/schema/evidence.schema.json b/spec/schema/evidence.schema.json index f3aa2c6..9d0ae04 100644 --- a/spec/schema/evidence.schema.json +++ b/spec/schema/evidence.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/evidence.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/evidence.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/spec/schema/policy-decision.schema.json b/spec/schema/policy-decision.schema.json index bd48937..29da5fe 100644 --- a/spec/schema/policy-decision.schema.json +++ b/spec/schema/policy-decision.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/policy-decision.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/policy-decision.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/spec/schema/usage.schema.json b/spec/schema/usage.schema.json index 90bd5d0..2ce149b 100644 --- a/spec/schema/usage.schema.json +++ b/spec/schema/usage.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/usage.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/usage.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/src/agentrust_telemetry/__init__.py b/src/agentrust_telemetry/__init__.py index 1f542a8..3754bd2 100644 --- a/src/agentrust_telemetry/__init__.py +++ b/src/agentrust_telemetry/__init__.py @@ -15,7 +15,14 @@ opa_decision_log, ) from .client import EmitResult, TelemetryClient -from .data_flow import ClassificationResult, DataClassifier, DataEndpoint, classified_data_flow +from .data_flow import ( + ClassificationOrder, + ClassificationResult, + DataClassifier, + DataEndpoint, + SourceClassification, + classified_data_flow, +) from .context import ContextIds, active_context_ids from .errors import ( ContextMismatchError, @@ -37,9 +44,11 @@ "ContextIds", "ContextMismatchError", "CostObservation", + "ClassificationOrder", "ClassificationResult", "DataClassifier", "DataEndpoint", + "SourceClassification", "AgtGovernanceEventSink", "EmitResult", "EventValidationError", @@ -77,4 +86,4 @@ "finalize_trace", ] -__version__ = "0.1.0a6" +__version__ = "0.2.0a1" diff --git a/src/agentrust_telemetry/data_flow.py b/src/agentrust_telemetry/data_flow.py index 23512b8..d82e931 100644 --- a/src/agentrust_telemetry/data_flow.py +++ b/src/agentrust_telemetry/data_flow.py @@ -4,7 +4,8 @@ import re from dataclasses import dataclass -from typing import Any, Protocol +from itertools import islice +from typing import Any, Iterable, Protocol, Sequence _IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}") _MEDIA_TYPE = re.compile(r"[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+") @@ -44,6 +45,115 @@ class EventFactoryLike(Protocol): def build(self, event_type: str, **fields: Any) -> dict[str, Any]: ... +@dataclass(frozen=True) +class SourceClassification: + """Trusted classification metadata for one contributing source.""" + + source: DataEndpoint + classification: ClassificationResult + + def __post_init__(self) -> None: + if not isinstance(self.source, DataEndpoint): + raise TypeError("source must be a DataEndpoint") + if not isinstance(self.classification, ClassificationResult): + raise TypeError("classification must be a ClassificationResult") + + +@dataclass(frozen=True) +class ClassificationOrder: + """Explicit least-to-most restrictive order for one taxonomy.""" + + taxonomy: str + levels: Sequence[str] + + def __post_init__(self) -> None: + _identifier(self.taxonomy, "classification taxonomy") + if not isinstance(self.levels, (tuple, list)) or not self.levels: + raise ValueError("classification levels must be a non-empty sequence") + levels = tuple(self.levels) + for level in levels: + _identifier(level, "classification level") + if len(set(levels)) != len(levels): + raise ValueError("classification levels must be unique") + object.__setattr__(self, "levels", levels) + + def rank(self, result: ClassificationResult) -> int: + if not isinstance(result, ClassificationResult): + raise TypeError("classification must be a ClassificationResult") + if result.taxonomy != self.taxonomy: + raise ValueError( + f"taxonomy mismatch: expected {self.taxonomy}, got {result.taxonomy}" + ) + try: + return self.levels.index(result.value) + except ValueError as exc: + raise ValueError( + f"unknown classification value for {self.taxonomy}: {result.value}" + ) from exc + + +def _derived_classification_fields( + observed: ClassificationResult, + sources: Iterable[SourceClassification] | None, + order: ClassificationOrder | None, +) -> dict[str, Any]: + if sources is None and order is None: + return {} + if sources is None or order is None: + raise ValueError( + "source_classifications and classification_order must be supplied together" + ) + if not isinstance(order, ClassificationOrder): + raise TypeError("classification_order must be a ClassificationOrder") + order.rank(observed) + try: + records = tuple(islice(iter(sources), 1025)) + except TypeError as exc: + raise TypeError("source_classifications must be iterable") from exc + if not records: + raise ValueError("derived data must identify at least one source") + if len(records) > 1024: + raise ValueError("derived data may identify at most 1024 sources") + + seen: set[tuple[str, str | None]] = set() + candidates = [observed] + event_sources: list[dict[str, Any]] = [] + for record in records: + if not isinstance(record, SourceClassification): + raise TypeError("each source must be a SourceClassification") + key = (record.source.kind, record.source.id) + if key in seen: + raise ValueError("duplicate source reference") + seen.add(key) + order.rank(record.classification) + candidates.append(record.classification) + event_sources.append({ + "source": record.source.as_event_value(), + "classification": { + "taxonomy": record.classification.taxonomy, + "value": record.classification.value, + "producer": record.classification.producer, + }, + }) + + # Keep the output label on ties; source labels can only raise its rank. + effective = max(candidates, key=order.rank) + return { + "classification": { + "taxonomy": effective.taxonomy, + "value": effective.value, + "producer": effective.producer, + }, + "observed_classification": { + "taxonomy": observed.taxonomy, + "value": observed.value, + "producer": observed.producer, + }, + "source_classifications": event_sources, + } + + + def classified_data_flow( factory: EventFactoryLike, classifier: DataClassifier, @@ -61,6 +171,8 @@ def classified_data_flow( token_count: int | None = None, media_type: str | None = None, transformation: str | None = None, + source_classifications: Iterable[SourceClassification] | None = None, + classification_order: ClassificationOrder | None = None, **envelope: Any, ) -> dict[str, Any]: """Classify ``value`` and emit only the classifier's closed metadata result.""" @@ -73,6 +185,9 @@ def classified_data_flow( or len(media_type) > 255 ): raise ValueError("media_type must be a parameter-free type/subtype identifier") + derived = _derived_classification_fields( + result, source_classifications, classification_order + ) optional = { "content_digest": content_digest, "size_bytes": size_bytes, @@ -87,11 +202,12 @@ def classified_data_flow( direction=direction, source=source.as_event_value(), destination=destination.as_event_value(), - classification={ + classification=derived.get("classification", { "taxonomy": result.taxonomy, "value": result.value, "producer": result.producer, - }, + }), + **{key: item for key, item in derived.items() if key != "classification"}, purpose=purpose, policy_decision=policy_decision, **{key: item for key, item in optional.items() if item is not None}, diff --git a/src/agentrust_telemetry/schemas/action.schema.json b/src/agentrust_telemetry/schemas/action.schema.json index d54edaa..b9059ae 100644 --- a/src/agentrust_telemetry/schemas/action.schema.json +++ b/src/agentrust_telemetry/schemas/action.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/action.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/action.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/src/agentrust_telemetry/schemas/approval.schema.json b/src/agentrust_telemetry/schemas/approval.schema.json index f63560d..59be43b 100644 --- a/src/agentrust_telemetry/schemas/approval.schema.json +++ b/src/agentrust_telemetry/schemas/approval.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/approval.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/approval.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/src/agentrust_telemetry/schemas/common.schema.json b/src/agentrust_telemetry/schemas/common.schema.json index 784a609..e55d5a2 100644 --- a/src/agentrust_telemetry/schemas/common.schema.json +++ b/src/agentrust_telemetry/schemas/common.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/common.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/common.schema.json", "$defs": { "event_id": {"type": "string", "format": "uuid"}, "time_unix_nano": {"type": "string", "pattern": "^(0|[1-9][0-9]{0,19})$"}, diff --git a/src/agentrust_telemetry/schemas/data-flow.schema.json b/src/agentrust_telemetry/schemas/data-flow.schema.json index 694b1a5..195b288 100644 --- a/src/agentrust_telemetry/schemas/data-flow.schema.json +++ b/src/agentrust_telemetry/schemas/data-flow.schema.json @@ -1,43 +1,170 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/data-flow.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/data-flow.schema.json", "allOf": [ - {"$ref": "envelope.schema.json"}, + { + "$ref": "envelope.schema.json" + }, { "type": "object", - "required": ["agent_id", "event_type", "direction", "source", "destination", "classification", "purpose", "policy_decision"], + "required": [ + "agent_id", + "event_type", + "direction", + "source", + "destination", + "classification", + "purpose", + "policy_decision" + ], "properties": { - "event_type": {"const": "data_flow.observed"}, - "direction": {"enum": ["input", "output", "read", "write", "send", "receive"]}, - "source": {"$ref": "#/$defs/endpoint"}, - "destination": {"$ref": "#/$defs/endpoint"}, + "event_type": { + "const": "data_flow.observed" + }, + "direction": { + "enum": [ + "input", + "output", + "read", + "write", + "send", + "receive" + ] + }, + "source": { + "$ref": "#/$defs/endpoint" + }, + "destination": { + "$ref": "#/$defs/endpoint" + }, "classification": { - "type": "object", - "required": ["taxonomy", "value", "producer"], - "properties": { - "taxonomy": {"$ref": "common.schema.json#/$defs/nonempty"}, - "value": {"$ref": "common.schema.json#/$defs/nonempty"}, - "producer": {"$ref": "common.schema.json#/$defs/nonempty"} + "$ref": "#/$defs/classification" + }, + "purpose": { + "$ref": "common.schema.json#/$defs/nonempty" + }, + "policy_decision": { + "enum": [ + "allow", + "deny", + "challenge", + "not_applicable", + "error", + "not_evaluated" + ] + }, + "content_digest": { + "$ref": "common.schema.json#/$defs/digest" + }, + "size_bytes": { + "type": "integer", + "minimum": 0 + }, + "token_count": { + "type": "integer", + "minimum": 0 + }, + "media_type": { + "type": "string", + "minLength": 1, + "maxLength": 255 + }, + "transformation": { + "enum": [ + "none", + "redacted", + "masked", + "tokenized", + "aggregated", + "metadata_only" + ] + }, + "observed_classification": { + "$ref": "#/$defs/classification" + }, + "source_classifications": { + "type": "array", + "minItems": 1, + "maxItems": 1024, + "items": { + "type": "object", + "required": [ + "source", + "classification" + ], + "properties": { + "source": { + "$ref": "#/$defs/endpoint" + }, + "classification": { + "$ref": "#/$defs/classification" + } + }, + "additionalProperties": false + } + } + }, + "allOf": [ + { + "if": { + "required": [ + "observed_classification" + ] }, - "additionalProperties": false - }, - "purpose": {"$ref": "common.schema.json#/$defs/nonempty"}, - "policy_decision": {"enum": ["allow", "deny", "challenge", "not_applicable", "error", "not_evaluated"]}, - "content_digest": {"$ref": "common.schema.json#/$defs/digest"}, - "size_bytes": {"type": "integer", "minimum": 0}, - "token_count": {"type": "integer", "minimum": 0}, - "media_type": {"type": "string", "minLength": 1, "maxLength": 255}, - "transformation": {"enum": ["none", "redacted", "masked", "tokenized", "aggregated", "metadata_only"]} - } + "then": { + "required": [ + "source_classifications" + ] + } + }, + { + "if": { + "required": [ + "source_classifications" + ] + }, + "then": { + "required": [ + "observed_classification" + ] + } + } + ] } ], "$defs": { "endpoint": { "type": "object", - "required": ["kind"], + "required": [ + "kind" + ], + "properties": { + "kind": { + "$ref": "common.schema.json#/$defs/nonempty" + }, + "id": { + "$ref": "common.schema.json#/$defs/nonempty" + } + }, + "additionalProperties": false + }, + "classification": { + "type": "object", + "required": [ + "taxonomy", + "value", + "producer" + ], "properties": { - "kind": {"$ref": "common.schema.json#/$defs/nonempty"}, - "id": {"$ref": "common.schema.json#/$defs/nonempty"} + "taxonomy": { + "$ref": "common.schema.json#/$defs/nonempty" + }, + "value": { + "$ref": "common.schema.json#/$defs/nonempty" + }, + "producer": { + "$ref": "common.schema.json#/$defs/nonempty" + } }, "additionalProperties": false } diff --git a/src/agentrust_telemetry/schemas/envelope.schema.json b/src/agentrust_telemetry/schemas/envelope.schema.json index e6cb7af..af64291 100644 --- a/src/agentrust_telemetry/schemas/envelope.schema.json +++ b/src/agentrust_telemetry/schemas/envelope.schema.json @@ -1,10 +1,10 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/envelope.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/envelope.schema.json", "type": "object", "required": ["spec_version", "event_id", "event_type", "time_unix_nano", "run_id", "producer"], "properties": { - "spec_version": {"const": "0.1.0-alpha.6"}, + "spec_version": {"const": "0.2.0-alpha.1"}, "event_id": {"$ref": "common.schema.json#/$defs/event_id"}, "event_type": {"type": "string", "pattern": "^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$", "maxLength": 128}, "time_unix_nano": {"$ref": "common.schema.json#/$defs/time_unix_nano"}, diff --git a/src/agentrust_telemetry/schemas/evidence.schema.json b/src/agentrust_telemetry/schemas/evidence.schema.json index f3aa2c6..9d0ae04 100644 --- a/src/agentrust_telemetry/schemas/evidence.schema.json +++ b/src/agentrust_telemetry/schemas/evidence.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/evidence.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/evidence.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/src/agentrust_telemetry/schemas/policy-decision.schema.json b/src/agentrust_telemetry/schemas/policy-decision.schema.json index bd48937..29da5fe 100644 --- a/src/agentrust_telemetry/schemas/policy-decision.schema.json +++ b/src/agentrust_telemetry/schemas/policy-decision.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/policy-decision.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/policy-decision.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/src/agentrust_telemetry/schemas/usage.schema.json b/src/agentrust_telemetry/schemas/usage.schema.json index 90bd5d0..2ce149b 100644 --- a/src/agentrust_telemetry/schemas/usage.schema.json +++ b/src/agentrust_telemetry/schemas/usage.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://agentrust-io.com/telemetry/v0.1/schema/usage.schema.json", + "$id": "https://agentrust-io.com/telemetry/v0.2/schema/usage.schema.json", "allOf": [ {"$ref": "envelope.schema.json"}, { diff --git a/tests/test_data_flow.py b/tests/test_data_flow.py index 0260a72..ed51f83 100644 --- a/tests/test_data_flow.py +++ b/tests/test_data_flow.py @@ -149,5 +149,121 @@ def test_structured_agt_classification_is_a_value_error(self): with self.assertRaisesRegex(ValueError, "unsupported AGT data classification"): agt_data_classification(SimpleNamespace(classification=bad)) + + def test_derived_flow_inherits_strictest_source_classification(self): + from agentrust_telemetry import ClassificationOrder, SourceClassification + + taxonomy = "example.enterprise.v1" + order = ClassificationOrder( + taxonomy, ("public", "internal", "confidential", "restricted") + ) + observed = ClassificationResult(taxonomy, "public", "output-dlp") + classifier = RecordingClassifier(observed) + event = classified_data_flow( + self.factory, classifier, "summary text", + run_id="run-1", agent_id="agent-1", direction="output", + source=DataEndpoint("transform", "summarizer"), + destination=DataEndpoint("memory", "summary-1"), + purpose="memory-compaction", transformation="aggregated", + source_classifications=[ + SourceClassification(DataEndpoint("document", "public-faq"), + ClassificationResult(taxonomy, "public", "source-dlp")), + SourceClassification(DataEndpoint("document", "staff-notes"), + ClassificationResult(taxonomy, "confidential", "trusted-label-store")), + ], + classification_order=order, + ) + self.assertEqual(event["classification"]["value"], "confidential") + self.assertEqual(event["observed_classification"]["value"], "public") + self.assertEqual(len(event["source_classifications"]), 2) + self.assertNotIn("summary text", repr(event)) + + def test_derived_flow_requires_complete_unique_same_taxonomy_lineage(self): + from agentrust_telemetry import ClassificationOrder, SourceClassification + + taxonomy = "example.enterprise.v1" + order = ClassificationOrder(taxonomy, ("public", "confidential")) + common = dict( + run_id="run-1", agent_id="agent-1", direction="output", + source=DataEndpoint("transform"), destination=DataEndpoint("memory"), + purpose="memory-compaction", + ) + classifier = RecordingClassifier(ClassificationResult(taxonomy, "public", "dlp")) + with self.assertRaisesRegex(ValueError, "supplied together"): + classified_data_flow(self.factory, classifier, "summary", **common, + source_classifications=[],) + with self.assertRaisesRegex(ValueError, "at least one source"): + classified_data_flow(self.factory, classifier, "summary", **common, + source_classifications=[], classification_order=order) + duplicate = SourceClassification(DataEndpoint("document", "same"), + ClassificationResult(taxonomy, "confidential", "dlp")) + with self.assertRaisesRegex(ValueError, "duplicate source"): + classified_data_flow(self.factory, classifier, "summary", **common, + source_classifications=[duplicate, duplicate], classification_order=order) + wrong_taxonomy = SourceClassification(DataEndpoint("document", "other"), + ClassificationResult("example.other.v1", "confidential", "dlp")) + with self.assertRaisesRegex(ValueError, "taxonomy mismatch"): + classified_data_flow(self.factory, classifier, "summary", **common, + source_classifications=[wrong_taxonomy], classification_order=order) + + unknown = SourceClassification(DataEndpoint("document", "unknown"), + ClassificationResult(taxonomy, "top_secret", "dlp")) + with self.assertRaisesRegex(ValueError, "unknown classification value"): + classified_data_flow(self.factory, classifier, "summary", **common, + source_classifications=[unknown], classification_order=order) + + too_many = (SourceClassification(DataEndpoint("document", f"source-{i}"), + ClassificationResult(taxonomy, "public", "dlp")) for i in range(1025)) + with self.assertRaisesRegex(ValueError, "at most 1024"): + classified_data_flow(self.factory, classifier, "summary", **common, + source_classifications=too_many, classification_order=order) + + exactly_limit = [ + SourceClassification( + DataEndpoint("document", f"source-{i}"), + ClassificationResult(taxonomy, "public", "dlp"), + ) + for i in range(1024) + ] + at_limit = classified_data_flow( + self.factory, classifier, "summary", **common, + source_classifications=exactly_limit, classification_order=order, + ) + self.assertEqual(len(at_limit["source_classifications"]), 1024) + + + def test_output_classification_is_not_downgraded_and_wins_ties(self): + from agentrust_telemetry import ClassificationOrder, SourceClassification + + taxonomy = "example.enterprise.v1" + order = ClassificationOrder(taxonomy, ("public", "confidential", "restricted")) + source = SourceClassification( + DataEndpoint("document", "staff-notes"), + ClassificationResult(taxonomy, "confidential", "trusted-label-store"), + ) + common = dict( + run_id="run-1", agent_id="agent-1", direction="output", + source=DataEndpoint("transform", "summarizer"), + destination=DataEndpoint("memory", "summary-1"), + purpose="memory-compaction", + source_classifications=[source], + classification_order=order, + ) + + stricter_output = ClassificationResult(taxonomy, "restricted", "output-dlp") + event = classified_data_flow( + self.factory, RecordingClassifier(stricter_output), "summary", **common + ) + self.assertEqual(event["classification"]["value"], "restricted") + self.assertEqual(event["classification"]["producer"], "output-dlp") + + tied_output = ClassificationResult(taxonomy, "confidential", "output-dlp") + tied_event = classified_data_flow( + self.factory, RecordingClassifier(tied_output), "summary", **common + ) + self.assertEqual(tied_event["classification"]["value"], "confidential") + self.assertEqual(tied_event["classification"]["producer"], "output-dlp") + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_installed_python_controls.py b/tests/test_installed_python_controls.py index 710369b..8d1a56a 100644 --- a/tests/test_installed_python_controls.py +++ b/tests/test_installed_python_controls.py @@ -31,7 +31,7 @@ def setUp(self): def test_real_controls(self): counts = controls_module.check_controls(self.controls, self.validator, self.factory, self.error) - self.assertEqual(counts, {"valid": 6, "invalid": 7}) + self.assertEqual(counts, {"valid": 7, "invalid": 8}) def test_accept_all_is_caught(self): with self.assertRaisesRegex(AssertionError, "invalid control admitted"): diff --git a/tools/installed_python_controls.py b/tools/installed_python_controls.py index d197700..11086fe 100644 --- a/tools/installed_python_controls.py +++ b/tools/installed_python_controls.py @@ -12,6 +12,7 @@ "action.json", "approval.json", "data-flow.json", + "derived-data-flow.json", "evidence.json", "policy-decision.json", "usage.json" @@ -19,6 +20,7 @@ "invalid": [ "action-without-digest.json", "aggregate-cost-without-rollup.json", + "derived-data-flow-missing-observed.json", "model-call-with-rollup.json", "numeric-timestamp.json", "raw-content.json", From aa5fc2b454f0f7c5e8f16f36b529844d17c3f1c2 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 10:31:37 +0530 Subject: [PATCH 02/33] fix(validation): resolve bundled v0.2 schemas --- packages/typescript/src/validation.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/typescript/src/validation.ts b/packages/typescript/src/validation.ts index 7eb835f..9d20bce 100644 --- a/packages/typescript/src/validation.ts +++ b/packages/typescript/src/validation.ts @@ -46,7 +46,7 @@ export class SchemaValidator { } #compile(ajv: InstanceType, name: string): ValidateFunction { - const id = `https://agentrust-io.com/telemetry/v0.1/schema/${name}`; + const id = `https://agentrust-io.com/telemetry/v0.2/schema/${name}`; const validator = ajv.getSchema(id); if (!validator) throw new EventValidationError(`required schema is missing: ${name}`); return validator; From 065bc802fe965ee6351cd0c713918fb2fce7dc2e Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 10:31:39 +0530 Subject: [PATCH 03/33] fix(factory): emit telemetry contract 0.2.0-alpha.1 --- src/agentrust_telemetry/adapters/base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/agentrust_telemetry/adapters/base.py b/src/agentrust_telemetry/adapters/base.py index 4d406dd..e45ddc6 100644 --- a/src/agentrust_telemetry/adapters/base.py +++ b/src/agentrust_telemetry/adapters/base.py @@ -55,7 +55,7 @@ def build( raise ValueError(f"payload cannot override envelope fields: {collision}") timestamp = self._clock_ns() if time_unix_nano is None else time_unix_nano event: dict[str, Any] = { - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "event_id": event_id or str(self._event_id_factory()), "event_type": event_type, "time_unix_nano": _unix_nano(timestamp), From a93f96fc916c6570a13c40f908e61cd430bc2d6b Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 10:31:42 +0530 Subject: [PATCH 04/33] fix(factory): emit telemetry contract 0.2.0-alpha.1 --- packages/typescript/src/factory.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/typescript/src/factory.ts b/packages/typescript/src/factory.ts index f744325..3718f7c 100644 --- a/packages/typescript/src/factory.ts +++ b/packages/typescript/src/factory.ts @@ -26,7 +26,7 @@ export class EventFactory { if (collisions.length) throw new Error(`payload cannot override envelope fields: ${collisions.join(", ")}`); const normalizedPayload = Object.fromEntries(Object.entries(payload).map(([key, value]) => [key, key.endsWith("_at_unix_nano") ? unixNano(value) : value])); const event = { - spec_version: "0.1.0-alpha.6" as const, + spec_version: "0.2.0-alpha.1" as const, event_id: fields.eventId ?? this.eventIdFactory(), event_type: eventType, time_unix_nano: unixNano(fields.timeUnixNano ?? this.clockNs()), run_id: fields.runId, producer: structuredClone(this.#producer), ...normalizedPayload, From ba6dcaa1365954e0d9294f0823417f2de36be581 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 10:31:44 +0530 Subject: [PATCH 05/33] fix(types): align normalized event contract version --- packages/typescript/src/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/typescript/src/types.ts b/packages/typescript/src/types.ts index c526075..6ba5a2b 100644 --- a/packages/typescript/src/types.ts +++ b/packages/typescript/src/types.ts @@ -1,6 +1,6 @@ export type Scalar = string | number | boolean; export type NormalizedEvent = Record & { - spec_version: "0.1.0-alpha.6"; + spec_version: "0.2.0-alpha.1"; event_id: string; event_type: string; time_unix_nano: string; From d9d21926f52df23aabf21c9ef3c959bad3bc4812 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:26:43 +0530 Subject: [PATCH 06/33] test: regenerate evidence chain golden for 0.2 contract --- compatibility/golden/evidence-chain.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/compatibility/golden/evidence-chain.json b/compatibility/golden/evidence-chain.json index 068ff6e..e0b8e01 100644 --- a/compatibility/golden/evidence-chain.json +++ b/compatibility/golden/evidence-chain.json @@ -6,13 +6,13 @@ "fixture": "policy-decision.json", "sequence": 0, "previous_digest": null, - "digest": "c3fd2bb7704407815e6cb1ee5b5f3d50508dd497356b526342ea36577e17ae29" + "digest": "1a5c5a1e3fdd101d54c712faeee70c5a6f76a0ab77a73ecdf3a57890bf4d1afb" }, { "fixture": "usage.json", "sequence": 1, - "previous_digest": "c3fd2bb7704407815e6cb1ee5b5f3d50508dd497356b526342ea36577e17ae29", - "digest": "e64ea4ae430587db42355be9885d47e338c3a2ac1d90a15a6f8b815a2a96a31b" + "previous_digest": "1a5c5a1e3fdd101d54c712faeee70c5a6f76a0ab77a73ecdf3a57890bf4d1afb", + "digest": "9961dd1ae7cd1526ced87eee0012e10db68318bc07234b0913209d26a427a691" } ] } From 7db0b582c0f752bea66b7c18a6d5803201ef47b3 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:26:47 +0530 Subject: [PATCH 07/33] test: update tool transcript digest for 0.2 envelope --- tests/test_trace_adapter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_trace_adapter.py b/tests/test_trace_adapter.py index 6aa91ad..45b94f5 100644 --- a/tests/test_trace_adapter.py +++ b/tests/test_trace_adapter.py @@ -77,7 +77,7 @@ def test_action_events_create_truthful_tool_transcript(self): self.assertRegex(record["tool_transcript"]["hash"], r"^sha256:[0-9a-f]{64}$") self.assertEqual( record["tool_transcript"]["hash"], - "sha256:c6a971b931d1b54e98a88184c50cba44084463279186b4cab7401d91354c128e", + "sha256:080177729364d9d2a2d7afc4d94e61b70831f658fd8429265770a26d2c3fbd3b", ) changed = fixture("action.json") From a9f1ad14736011d911a1b44a4b7fa3f0485c3f8c Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:26:51 +0530 Subject: [PATCH 08/33] test: update TypeScript transcript digest for 0.2 envelope --- packages/typescript/test/trace-finalizer.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/typescript/test/trace-finalizer.test.ts b/packages/typescript/test/trace-finalizer.test.ts index c21dd42..9b20d23 100644 --- a/packages/typescript/test/trace-finalizer.test.ts +++ b/packages/typescript/test/trace-finalizer.test.ts @@ -22,7 +22,7 @@ test("finalizer derives claims then signs, validates, and self-verifies", () => }); test("tool transcript uses the shared RFC 8785 sequence/event digest", () => { const record = finalizeTrace(snapshot([fixture("action.json")]), config, {signingKey: "private", codec: new RecordingCodec()}); - assert.deepEqual(record.tool_transcript, {hash: "sha256:c6a971b931d1b54e98a88184c50cba44084463279186b4cab7401d91354c128e", call_count: 1}); + assert.deepEqual(record.tool_transcript, {hash: "sha256:080177729364d9d2a2d7afc4d94e61b70831f658fd8429265770a26d2c3fbd3b", call_count: 1}); const changed = fixture("action.json"); changed.outcome = "error"; changed.error_type = "remote_error"; assert.notEqual((finalizeTrace(snapshot([changed]), config, {signingKey: "private", codec: new RecordingCodec()}).tool_transcript as Record).hash, (record.tool_transcript as Record).hash); }); From d8844d5df60d37196f95fb2ef97e142c553bbf6d Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:26:56 +0530 Subject: [PATCH 09/33] test: align fuzz seeds with 0.2 conformance fixtures --- .clusterfuzzlite/_fuzz_seeds.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/.clusterfuzzlite/_fuzz_seeds.py b/.clusterfuzzlite/_fuzz_seeds.py index ae126b2..fed3a12 100644 --- a/.clusterfuzzlite/_fuzz_seeds.py +++ b/.clusterfuzzlite/_fuzz_seeds.py @@ -23,7 +23,7 @@ 'result_digest': {'algorithm': 'sha256', 'value': 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'}, 'run_id': 'run-governed-sdlc-001', - 'spec_version': '0.1.0-alpha.6', + 'spec_version': '0.2.0-alpha.1', 'target': {'id': 'example/repository', 'kind': 'git.repository'}, 'time_unix_nano': '1787079650000000000', 'workflow_id': 'workflow-build-feature'}, @@ -39,7 +39,7 @@ 'requested_at_unix_nano': '1787079500000000000', 'run_id': 'run-governed-sdlc-001', 'span_id': '00f067aa0ba902b7', - 'spec_version': '0.1.0-alpha.6', + 'spec_version': '0.2.0-alpha.1', 'time_unix_nano': '1787079580000000000', 'trace_id': '4bf92f3577b34da6a3ce929d0e0e4736'}, 'data-flow': {'agent_id': 'spiffe://example.test/agent/architect', @@ -58,7 +58,7 @@ 'run_id': 'run-governed-sdlc-001', 'size_bytes': 18342, 'source': {'id': 'requirements-graph', 'kind': 'knowledge_graph'}, - 'spec_version': '0.1.0-alpha.6', + 'spec_version': '0.2.0-alpha.1', 'time_unix_nano': '1787079400000000000', 'transformation': 'metadata_only'}, 'evidence': {'capture_profile': 'metadata_only', @@ -67,10 +67,10 @@ 'completeness': 'complete', 'event_id': '018f0f7d-7a13-7cc2-8000-000000000005', 'event_type': 'evidence.run_closed', - 'producer': {'name': 'agentrust-telemetry', 'version': '0.1.0-alpha.6'}, + 'producer': {'name': 'agentrust-telemetry', 'version': '0.2.0-alpha.1'}, 'run_id': 'run-governed-sdlc-001', 'sequence': 14, - 'spec_version': '0.1.0-alpha.6', + 'spec_version': '0.2.0-alpha.1', 'time_unix_nano': '1787079700000000000'}, 'policy-decision': {'action_type': 'repository.write', 'agent_id': 'spiffe://example.test/agent/coder', @@ -89,7 +89,7 @@ 'resource_type': 'git.repository', 'run_id': 'run-governed-sdlc-001', 'span_id': '00f067aa0ba902b7', - 'spec_version': '0.1.0-alpha.6', + 'spec_version': '0.2.0-alpha.1', 'time_unix_nano': '1787079600000000000', 'trace_id': '4bf92f3577b34da6a3ce929d0e0e4736', 'workflow_id': 'workflow-build-feature'}, @@ -108,7 +108,7 @@ 'request_model': 'example-model-2', 'run_id': 'run-governed-sdlc-001', 'scope': 'model_call', - 'spec_version': '0.1.0-alpha.6', + 'spec_version': '0.2.0-alpha.1', 'time_unix_nano': '1787079590000000000', 'workflow_id': 'workflow-build-feature'}} From bb0681be29aee29d176238511ef6005003f80e78 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:27:00 +0530 Subject: [PATCH 10/33] test: update release tag expectation for contract 0.2 --- tests/test_repository_gates.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_repository_gates.py b/tests/test_repository_gates.py index 40b1c44..8fee46d 100644 --- a/tests/test_repository_gates.py +++ b/tests/test_repository_gates.py @@ -78,10 +78,10 @@ def test_contract_version_rejects_unsupported_spellings(self): check_versions.ecosystem_versions("0.1") def test_release_tag_must_match_contract(self): - self.assertEqual(check_release_tag.validate_tag("v0.1.0-alpha.6"), []) + self.assertEqual(check_release_tag.validate_tag("v0.2.0-alpha.1"), []) self.assertEqual( check_release_tag.validate_tag("v0.1.0"), - ["release tag 'v0.1.0' must equal 'v0.1.0-alpha.6'"], + ["release tag 'v0.1.0' must equal 'v0.2.0-alpha.1'"], ) def test_otel_matrix_matches_shipped_projection(self): From 0803ad2817c489fb1b0a6463ebe02f88d7fcbb35 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:27:11 +0530 Subject: [PATCH 11/33] fix: cap data-flow counts at JavaScript safe integers --- spec/schema/data-flow.schema.json | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/spec/schema/data-flow.schema.json b/spec/schema/data-flow.schema.json index 195b288..39632a8 100644 --- a/spec/schema/data-flow.schema.json +++ b/spec/schema/data-flow.schema.json @@ -58,11 +58,13 @@ }, "size_bytes": { "type": "integer", - "minimum": 0 + "minimum": 0, + "maximum": 9007199254740991 }, "token_count": { "type": "integer", - "minimum": 0 + "minimum": 0, + "maximum": 9007199254740991 }, "media_type": { "type": "string", From 50612d9fdd51c76063e85678f9f4b41c221a06fc Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:27:15 +0530 Subject: [PATCH 12/33] fix: cap data-flow counts at JavaScript safe integers --- src/agentrust_telemetry/schemas/data-flow.schema.json | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/agentrust_telemetry/schemas/data-flow.schema.json b/src/agentrust_telemetry/schemas/data-flow.schema.json index 195b288..39632a8 100644 --- a/src/agentrust_telemetry/schemas/data-flow.schema.json +++ b/src/agentrust_telemetry/schemas/data-flow.schema.json @@ -58,11 +58,13 @@ }, "size_bytes": { "type": "integer", - "minimum": 0 + "minimum": 0, + "maximum": 9007199254740991 }, "token_count": { "type": "integer", - "minimum": 0 + "minimum": 0, + "maximum": 9007199254740991 }, "media_type": { "type": "string", From 8fed288b4816173b98317c3eb815267938bc8a66 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:27:20 +0530 Subject: [PATCH 13/33] fix: cap data-flow counts at JavaScript safe integers --- packages/typescript/schemas/data-flow.schema.json | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/typescript/schemas/data-flow.schema.json b/packages/typescript/schemas/data-flow.schema.json index 195b288..39632a8 100644 --- a/packages/typescript/schemas/data-flow.schema.json +++ b/packages/typescript/schemas/data-flow.schema.json @@ -58,11 +58,13 @@ }, "size_bytes": { "type": "integer", - "minimum": 0 + "minimum": 0, + "maximum": 9007199254740991 }, "token_count": { "type": "integer", - "minimum": 0 + "minimum": 0, + "maximum": 9007199254740991 }, "media_type": { "type": "string", From 584a01df0a46f178e8295ab42a2dc3200fca6a66 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:27:45 +0530 Subject: [PATCH 14/33] docs: update README contract version --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2ea06c5..b1cd2ea 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ AgenTrust Telemetry is a shared format for the governance facts an AI agent prod In technical terms, this repository defines a backend-neutral contract, a fixed set of event formats that works with any monitoring or storage system, for policy decisions, approval lifecycles, usage, classified data flows, and evidence lifecycle events. It works alongside OpenTelemetry. It is not a tracing backend, policy engine, agent framework, or dashboard. -> **Status:** alpha contract `0.1.0-alpha.6`. No stable SDK API or compatibility guarantee exists yet. +> **Status:** alpha contract `0.2.0-alpha.1`. No stable SDK API or compatibility guarantee exists yet. ## Why From 0c2d8e96151102bd45e057edeca29e7168ae599a Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:27:50 +0530 Subject: [PATCH 15/33] docs: update TypeScript README contract version --- packages/typescript/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/typescript/README.md b/packages/typescript/README.md index 010e681..6f54ac3 100644 --- a/packages/typescript/README.md +++ b/packages/typescript/README.md @@ -1,6 +1,6 @@ # `@agentrust-io/telemetry` -TypeScript reference SDK for the AgenTrust Telemetry `0.1.0-alpha.6` contract. +TypeScript reference SDK for the AgenTrust Telemetry `0.2.0-alpha.1` contract. This alpha Node package validates the same closed schemas and metadata-only privacy profile as the Python SDK. It supplies event construction, caller-owned From f40de4694639543096c81fbd5f31e397e44c4ac9 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:28:37 +0530 Subject: [PATCH 16/33] fix: validate derived flow inputs before classification --- src/agentrust_telemetry/data_flow.py | 60 ++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 17 deletions(-) diff --git a/src/agentrust_telemetry/data_flow.py b/src/agentrust_telemetry/data_flow.py index d82e931..43c87f7 100644 --- a/src/agentrust_telemetry/data_flow.py +++ b/src/agentrust_telemetry/data_flow.py @@ -3,9 +3,10 @@ from __future__ import annotations import re +from collections.abc import Iterable, Sequence from dataclasses import dataclass from itertools import islice -from typing import Any, Iterable, Protocol, Sequence +from typing import Any, Protocol _IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}") _MEDIA_TYPE = re.compile(r"[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+") @@ -68,7 +69,7 @@ class ClassificationOrder: def __post_init__(self) -> None: _identifier(self.taxonomy, "classification taxonomy") - if not isinstance(self.levels, (tuple, list)) or not self.levels: + if not isinstance(self.levels, Sequence) or isinstance(self.levels, (str, bytes, bytearray)) or not self.levels: raise ValueError("classification levels must be a non-empty sequence") levels = tuple(self.levels) for level in levels: @@ -92,20 +93,19 @@ def rank(self, result: ClassificationResult) -> int: ) from exc -def _derived_classification_fields( - observed: ClassificationResult, +def _validate_source_classifications( sources: Iterable[SourceClassification] | None, order: ClassificationOrder | None, -) -> dict[str, Any]: +) -> tuple[SourceClassification, ...] | None: + """Validate caller-supplied lineage before invoking an expensive classifier.""" if sources is None and order is None: - return {} + return None if sources is None or order is None: raise ValueError( "source_classifications and classification_order must be supplied together" ) if not isinstance(order, ClassificationOrder): raise TypeError("classification_order must be a ClassificationOrder") - order.rank(observed) try: records = tuple(islice(iter(sources), 1025)) except TypeError as exc: @@ -116,8 +116,6 @@ def _derived_classification_fields( raise ValueError("derived data may identify at most 1024 sources") seen: set[tuple[str, str | None]] = set() - candidates = [observed] - event_sources: list[dict[str, Any]] = [] for record in records: if not isinstance(record, SourceClassification): raise TypeError("each source must be a SourceClassification") @@ -126,6 +124,24 @@ def _derived_classification_fields( raise ValueError("duplicate source reference") seen.add(key) order.rank(record.classification) + return records + + +def _derived_classification_fields( + observed: ClassificationResult, + records: tuple[SourceClassification, ...] | None, + order: ClassificationOrder | None, +) -> dict[str, Any]: + if records is None and order is None: + return {} + if records is None or order is None: + raise ValueError( + "source_classifications and classification_order must be supplied together" + ) + order.rank(observed) + candidates = [observed] + event_sources: list[dict[str, Any]] = [] + for record in records: candidates.append(record.classification) event_sources.append({ "source": record.source.as_event_value(), @@ -136,7 +152,8 @@ def _derived_classification_fields( }, }) - # Keep the output label on ties; source labels can only raise its rank. + # max() is stable: the observed output wins equal-rank ties, then the first + # source at a higher rank wins ties with later sources in input order. effective = max(candidates, key=order.rank) return { "classification": { @@ -153,7 +170,6 @@ def _derived_classification_fields( } - def classified_data_flow( factory: EventFactoryLike, classifier: DataClassifier, @@ -176,18 +192,28 @@ def classified_data_flow( **envelope: Any, ) -> dict[str, Any]: """Classify ``value`` and emit only the classifier's closed metadata result.""" - result = classifier.classify(value) - if not isinstance(result, ClassificationResult): - raise TypeError("classifier must return ClassificationResult") _identifier(purpose, "purpose") + if not isinstance(source, DataEndpoint) or not isinstance(destination, DataEndpoint): + raise TypeError("source and destination must be DataEndpoint instances") if media_type is not None and ( not isinstance(media_type, str) or _MEDIA_TYPE.fullmatch(media_type) is None or len(media_type) > 255 ): raise ValueError("media_type must be a parameter-free type/subtype identifier") - derived = _derived_classification_fields( - result, source_classifications, classification_order - ) + for field, amount in (("size_bytes", size_bytes), ("token_count", token_count)): + if amount is not None and ( + isinstance(amount, bool) or not isinstance(amount, int) + or amount < 0 or amount > 9007199254740991 + ): + raise ValueError(f"{field} must be a non-negative safe integer") + records = _validate_source_classifications(source_classifications, classification_order) + + # Only invoke the adopter-owned classifier after inexpensive argument and + # lineage checks have passed. + result = classifier.classify(value) + if not isinstance(result, ClassificationResult): + raise TypeError("classifier must return ClassificationResult") + derived = _derived_classification_fields(result, records, classification_order) optional = { "content_digest": content_digest, "size_bytes": size_bytes, From 0f740810cac9663284212b082e817f826d5454d1 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:29:07 +0530 Subject: [PATCH 17/33] fix: freeze classification metadata and validate lineage early --- packages/typescript/src/data-flow.ts | 71 ++++++++++++++++++++-------- 1 file changed, 51 insertions(+), 20 deletions(-) diff --git a/packages/typescript/src/data-flow.ts b/packages/typescript/src/data-flow.ts index 9b79cd4..d648a85 100644 --- a/packages/typescript/src/data-flow.ts +++ b/packages/typescript/src/data-flow.ts @@ -6,10 +6,19 @@ const MEDIA_TYPE = /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+$/; type Digest = {algorithm: string; value: string}; export class ClassificationResult { - constructor(readonly taxonomy: string, readonly value: string, readonly producer: string) { identifier(taxonomy, "classification taxonomy"); identifier(value, "classification value"); identifier(producer, "classification producer"); } + constructor(readonly taxonomy: string, readonly value: string, readonly producer: string) { + identifier(taxonomy, "classification taxonomy"); + identifier(value, "classification value"); + identifier(producer, "classification producer"); + Object.freeze(this); + } } export class DataEndpoint { - constructor(readonly kind: string, readonly id?: string) { identifier(kind, "endpoint kind"); if (id !== undefined) identifier(id, "endpoint id"); } + constructor(readonly kind: string, readonly id?: string) { + identifier(kind, "endpoint kind"); + if (id !== undefined) identifier(id, "endpoint id"); + Object.freeze(this); + } asEventValue(): {kind: string; id?: string} { return {kind: this.kind, ...(this.id === undefined ? {} : {id: this.id})}; } } @@ -17,6 +26,7 @@ export class SourceClassification { constructor(readonly source: DataEndpoint, readonly classification: ClassificationResult) { if (!(source instanceof DataEndpoint)) throw new TypeError("source must be a DataEndpoint"); if (!(classification instanceof ClassificationResult)) throw new TypeError("classification must be a ClassificationResult"); + Object.freeze(this); } } @@ -29,6 +39,7 @@ export class ClassificationOrder { for (const level of levels) identifier(level, "classification level"); if (new Set(levels).size !== levels.length) throw new Error("classification levels must be unique"); this.levels = Object.freeze([...levels]); + Object.freeze(this); } rank(result: ClassificationResult): number { @@ -40,34 +51,49 @@ export class ClassificationOrder { } } -function derivedClassificationFields( - observed: ClassificationResult, +function validateSourceClassifications( sources: readonly SourceClassification[] | undefined, order: ClassificationOrder | undefined, -): Record { - if (sources === undefined && order === undefined) return {}; +): readonly SourceClassification[] | undefined { + if (sources === undefined && order === undefined) return undefined; if (sources === undefined || order === undefined) throw new Error("sourceClassifications and classificationOrder must be supplied together"); if (!(order instanceof ClassificationOrder)) throw new TypeError("classificationOrder must be a ClassificationOrder"); - order.rank(observed); if (!Array.isArray(sources) || sources.length === 0) throw new Error("derived data must identify at least one source"); if (sources.length > 1024) throw new Error("derived data may identify at most 1024 sources"); const seen = new Set(); - let effective = observed; - let effectiveRank = order.rank(observed); - const sourceValues = sources.map((record) => { + for (const record of sources) { if (!(record instanceof SourceClassification)) throw new TypeError("each source must be a SourceClassification"); - const key = `${record.source.kind}\u0000${record.source.id ?? ""}`; + const key = `${record.source.kind}\\u0000${record.source.id ?? ""}`; if (seen.has(key)) throw new Error("duplicate source reference"); seen.add(key); + order.rank(record.classification); + } + return [...sources]; +} + +function derivedClassificationFields( + observed: ClassificationResult, + sources: readonly SourceClassification[] | undefined, + order: ClassificationOrder | undefined, +): Record { + if (sources === undefined && order === undefined) return {}; + if (sources === undefined || order === undefined) throw new Error("sourceClassifications and classificationOrder must be supplied together"); + order.rank(observed); + + const sourceValues = sources.map((record) => ({ + source: record.source.asEventValue(), + classification: {taxonomy: record.classification.taxonomy, value: record.classification.value, producer: record.classification.producer}, + })); + let effective = observed; + let effectiveRank = order.rank(observed); + for (const record of sources) { const rank = order.rank(record.classification); if (rank > effectiveRank) { effective = record.classification; effectiveRank = rank; } - return { - source: record.source.asEventValue(), - classification: {taxonomy: record.classification.taxonomy, value: record.classification.value, producer: record.classification.producer}, - }; - }); + } + // The output label wins ties with source labels; the first source at a + // strictly higher rank wins ties with later sources in input array order. return { classification: {taxonomy: effective.taxonomy, value: effective.value, producer: effective.producer}, observed_classification: {taxonomy: observed.taxonomy, value: observed.value, producer: observed.producer}, @@ -78,12 +104,17 @@ function derivedClassificationFields( export interface DataClassifier {classify(value: unknown): ClassificationResult} export function classifiedDataFlow(factory: EventFactory, classifier: DataClassifier, value: unknown, options: {runId: string; agentId: string; direction: string; source: DataEndpoint; destination: DataEndpoint; purpose: string; policyDecision?: string; contentDigest?: Digest; sizeBytes?: number; tokenCount?: number; mediaType?: string; transformation?: string; sourceClassifications?: readonly SourceClassification[]; classificationOrder?: ClassificationOrder; envelope?: Omit}): NormalizedEvent { - const result = classifier.classify(value); - if (!(result instanceof ClassificationResult)) throw new TypeError("classifier must return ClassificationResult"); identifier(options.purpose, "purpose"); + if (!(options.source instanceof DataEndpoint) || !(options.destination instanceof DataEndpoint)) throw new TypeError("source and destination must be DataEndpoint instances"); if (options.mediaType !== undefined && (!MEDIA_TYPE.test(options.mediaType) || options.mediaType.length > 255)) throw new Error("mediaType must be a parameter-free type/subtype identifier"); - for (const [field, amount] of [["sizeBytes", options.sizeBytes], ["tokenCount", options.tokenCount]] as const) if (amount !== undefined && (!Number.isSafeInteger(amount) || amount < 0)) throw new Error(`${field} must be a non-negative safe integer`); - const derived = derivedClassificationFields(result, options.sourceClassifications, options.classificationOrder); + for (const [field, amount] of [["sizeBytes", options.sizeBytes], ["tokenCount", options.tokenCount]] as const) if (amount !== undefined && (!Number.isSafeInteger(amount) || amount < 0 || amount > Number.MAX_SAFE_INTEGER)) throw new Error(`${field} must be a non-negative safe integer`); + const records = validateSourceClassifications(options.sourceClassifications, options.classificationOrder); + + // Validate cheap arguments and source lineage before the potentially costly + // adopter-owned classifier is invoked. + const result = classifier.classify(value); + if (!(result instanceof ClassificationResult)) throw new TypeError("classifier must return ClassificationResult"); + const derived = derivedClassificationFields(result, records, options.classificationOrder); return factory.build("data_flow.observed", {runId: options.runId, agentId: options.agentId, ...options.envelope}, { direction: options.direction, source: options.source.asEventValue(), destination: options.destination.asEventValue(), classification: (derived.classification as Record | undefined) ?? {taxonomy: result.taxonomy, value: result.value, producer: result.producer}, ...omitClassification(derived), purpose: options.purpose, policy_decision: options.policyDecision ?? "not_evaluated", ...present("content_digest", options.contentDigest), ...present("size_bytes", options.sizeBytes), ...present("token_count", options.tokenCount), ...present("media_type", options.mediaType), ...present("transformation", options.transformation), From 5c766e18a62d0db0aec6b8e5fbb1b7482e8a5836 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:29:34 +0530 Subject: [PATCH 18/33] fix: enforce data-flow lineage semantics in schema validation --- src/agentrust_telemetry/validation.py | 70 +++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/src/agentrust_telemetry/validation.py b/src/agentrust_telemetry/validation.py index 5305a10..6aa619e 100644 --- a/src/agentrust_telemetry/validation.py +++ b/src/agentrust_telemetry/validation.py @@ -4,6 +4,7 @@ import json import math +import re from importlib.resources import as_file, files from pathlib import Path from typing import Any @@ -14,6 +15,8 @@ from .errors import EventValidationError +METADATA_IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}") + EVENT_SCHEMAS = { "action.executed": "action.schema.json", "policy.decision": "policy-decision.schema.json", @@ -84,6 +87,71 @@ def _prohibited_paths(value: Any, prefix: str = "$") -> list[str]: found.extend(_prohibited_paths(child, f"{prefix}[{index}]")) return found +def _data_flow_semantic_errors(event: dict[str, Any]) -> list[str]: + """Enforce data-flow invariants that JSON Schema cannot express.""" + messages: list[str] = [] + + def check_identifier(value: Any, path: str) -> None: + if ( + not isinstance(value, str) + or METADATA_IDENTIFIER.fullmatch(value) is None + or "://" in value + ): + messages.append(f"{path} must use the metadata identifier profile") + + def check_endpoint(value: Any, path: str) -> None: + if not isinstance(value, dict): + return + if "kind" in value: + check_identifier(value["kind"], f"{path}.kind") + if "id" in value: + check_identifier(value["id"], f"{path}.id") + + def check_classification(value: Any, path: str) -> str | None: + if not isinstance(value, dict): + return None + for key in ("taxonomy", "value", "producer"): + if key in value: + check_identifier(value[key], f"{path}.{key}") + taxonomy = value.get("taxonomy") + return taxonomy if isinstance(taxonomy, str) else None + + check_identifier(event.get("purpose"), "$.purpose") + check_endpoint(event.get("source"), "$.source") + check_endpoint(event.get("destination"), "$.destination") + taxonomies = [ + taxonomy + for taxonomy in ( + check_classification(event.get("classification"), "$.classification"), + check_classification(event.get("observed_classification"), "$.observed_classification"), + ) + if taxonomy is not None + ] + + sources = event.get("source_classifications") + if isinstance(sources, list): + seen: set[tuple[str, str | None]] = set() + for index, record in enumerate(sources): + if not isinstance(record, dict): + continue + path = f"$.source_classifications[{index}]" + endpoint = record.get("source") + check_endpoint(endpoint, f"{path}.source") + classification = record.get("classification") + taxonomy = check_classification(classification, f"{path}.classification") + if taxonomy is not None: + taxonomies.append(taxonomy) + if isinstance(endpoint, dict) and isinstance(endpoint.get("kind"), str): + key = (endpoint["kind"], endpoint.get("id")) + if key in seen: + messages.append(f"{path}.source duplicates a prior (kind, id) reference") + seen.add(key) + + if len(set(taxonomies)) > 1: + messages.append("all data-flow classifications must use the same taxonomy") + return messages + + class SchemaValidator: @classmethod @@ -134,6 +202,8 @@ def validate(self, event: dict[str, Any]) -> None: privacy_paths = _prohibited_paths(event) messages = [error.message for error in errors] messages.extend(f"{path} is prohibited by metadata_only" for path in privacy_paths) + if event.get("event_type") == "data_flow.observed": + messages.extend(_data_flow_semantic_errors(event)) attributes = event.get("attributes", {}) if isinstance(attributes, dict): for key in sorted(set(attributes) - self.allowed_attribute_keys): From a981dc887bbf341036e37cdd04021fb15b18ba25 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:29:50 +0530 Subject: [PATCH 19/33] fix: enforce data-flow lineage semantics in TS validator --- packages/typescript/src/validation.ts | 51 ++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/packages/typescript/src/validation.ts b/packages/typescript/src/validation.ts index 9d20bce..f01ca53 100644 --- a/packages/typescript/src/validation.ts +++ b/packages/typescript/src/validation.ts @@ -11,7 +11,7 @@ const EVENT_SCHEMAS: Record = { "usage.recorded": "usage.schema.json", "data_flow.observed": "data-flow.schema.json", }; -const PROHIBITED = new Set([ +const METADATA_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}$/;\nconst PROHIBITED = new Set([ "prompt", "completion", "source_code", "tool_arguments", "tool_result", "authorization", "credential", "secret", "access_token", "refresh_token", ]); @@ -61,6 +61,7 @@ export class SchemaValidator { const messages: string[] = []; if (!validator(value)) messages.push(...formatErrors(validator.errors)); findProhibited(value, "$", messages); + if (eventType === "data_flow.observed") messages.push(...dataFlowSemanticErrors(value)); if (isRecord(value.attributes)) { for (const key of Object.keys(value.attributes).sort()) { if (!this.#allowedAttributes.has(key)) messages.push(`$.attributes.${key} is not in the metadata_only attribute allowlist`); @@ -73,6 +74,54 @@ export class SchemaValidator { function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } + +function dataFlowSemanticErrors(event: Record): string[] { + const messages: string[] = []; + const taxonomies: string[] = []; + const identifier = (value: unknown, path: string): void => { + if (typeof value !== "string" || !METADATA_IDENTIFIER.test(value) || value.includes("://")) { + messages.push(`${path} must use the metadata identifier profile`); + } + }; + const endpoint = (value: unknown, path: string): void => { + if (!isRecord(value)) return; + if ("kind" in value) identifier(value.kind, `${path}.kind`); + if ("id" in value) identifier(value.id, `${path}.id`); + }; + const classification = (value: unknown, path: string): void => { + if (!isRecord(value)) return; + for (const field of ["taxonomy", "value", "producer"] as const) { + if (field in value) identifier(value[field], `${path}.${field}`); + } + if (typeof value.taxonomy === "string") taxonomies.push(value.taxonomy); + }; + + identifier(event.purpose, "$.purpose"); + endpoint(event.source, "$.source"); + endpoint(event.destination, "$.destination"); + classification(event.classification, "$.classification"); + classification(event.observed_classification, "$.observed_classification"); + + if (Array.isArray(event.source_classifications)) { + const seen = new Set(); + event.source_classifications.forEach((item, index) => { + if (!isRecord(item)) return; + const path = `$.source_classifications[${index}]`; + endpoint(item.source, `${path}.source`); + classification(item.classification, `${path}.classification`); + if (isRecord(item.source) && typeof item.source.kind === "string") { + const id = typeof item.source.id === "string" ? item.source.id : ""; + const key = `${item.source.kind}\\u0000${id}`; + if (seen.has(key)) messages.push(`${path}.source duplicates a prior (kind, id) reference`); + seen.add(key); + } + }); + } + if (new Set(taxonomies).size > 1) { + messages.push("all data-flow classifications must use the same taxonomy"); + } + return messages; +} function formatErrors(errors: ErrorObject[] | null | undefined): string[] { return (errors ?? []).map((error) => `${error.instancePath || "$"} ${error.message ?? "is invalid"}`); } From b487e4f4620381295150078077e959a18fe20db1 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:30:26 +0530 Subject: [PATCH 20/33] test: cover lineage validation and metadata safety --- tests/test_data_flow.py | 78 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/tests/test_data_flow.py b/tests/test_data_flow.py index ed51f83..aad5812 100644 --- a/tests/test_data_flow.py +++ b/tests/test_data_flow.py @@ -1,4 +1,6 @@ +import copy import sys +from collections.abc import Sequence import unittest from datetime import datetime, timezone from enum import IntEnum @@ -13,6 +15,7 @@ ClassificationResult, DataEndpoint, EventFactory, + EventValidationError, SchemaValidator, agt_data_access_flow, classified_data_flow, @@ -265,5 +268,80 @@ def test_output_classification_is_not_downgraded_and_wins_ties(self): self.assertEqual(tied_event["classification"]["producer"], "output-dlp") + def test_classification_order_accepts_general_string_sequences(self): + class Levels(Sequence): + def __getitem__(self, index): + return ("public", "confidential")[index] + + def __len__(self): + return 2 + + from agentrust_telemetry import ClassificationOrder + + order = ClassificationOrder("example.enterprise.v1", Levels()) + self.assertEqual( + order.rank(ClassificationResult("example.enterprise.v1", "confidential", "dlp")), + 1, + ) + + def test_cheap_lineage_and_size_checks_precede_classifier(self): + from agentrust_telemetry import ClassificationOrder, SourceClassification + + taxonomy = "example.enterprise.v1" + classifier = RecordingClassifier(ClassificationResult(taxonomy, "public", "dlp")) + duplicate = SourceClassification( + DataEndpoint("document", "same"), + ClassificationResult(taxonomy, "confidential", "trusted-store"), + ) + common = dict( + run_id="run-1", agent_id="agent-1", direction="output", + source=DataEndpoint("transform"), destination=DataEndpoint("memory"), + purpose="memory-compaction", + ) + order = ClassificationOrder(taxonomy, ("public", "confidential")) + with self.assertRaisesRegex(ValueError, "duplicate source"): + classified_data_flow( + self.factory, classifier, "summary", **common, + source_classifications=(duplicate for _ in range(2)), + classification_order=order, + ) + self.assertIsNone(classifier.seen) + + with self.assertRaisesRegex(ValueError, "safe integer"): + classified_data_flow( + self.factory, classifier, "summary", **common, + size_bytes=9007199254740992, + ) + self.assertIsNone(classifier.seen) + + def test_schema_validator_enforces_lineage_identifier_and_safe_integer_rules(self): + validator = SchemaValidator(ROOT / "spec" / "schema") + fixture_path = ROOT / "conformance" / "fixtures" / "valid" / "derived-data-flow.json" + event = json.loads(fixture_path.read_text(encoding="utf-8")) + + duplicate = copy.deepcopy(event) + duplicate["source_classifications"][1]["source"] = copy.deepcopy( + duplicate["source_classifications"][0]["source"] + ) + with self.assertRaisesRegex(EventValidationError, "duplicates a prior"): + validator.validate(duplicate) + + mixed = copy.deepcopy(event) + mixed["source_classifications"][0]["classification"]["taxonomy"] = "other.taxonomy" + with self.assertRaisesRegex(EventValidationError, "same taxonomy"): + validator.validate(mixed) + + invalid_identifier = copy.deepcopy(event) + invalid_identifier["source_classifications"][0]["source"]["kind"] = "customer data" + with self.assertRaisesRegex(EventValidationError, "metadata identifier profile"): + validator.validate(invalid_identifier) + + unsafe_integer = copy.deepcopy(event) + unsafe_integer["size_bytes"] = 9007199254740992 + with self.assertRaises(EventValidationError): + validator.validate(unsafe_integer) + + + if __name__ == "__main__": unittest.main() From 7278fd6f731c0b6793e7c32ab137872953247f74 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:30:52 +0530 Subject: [PATCH 21/33] test: cover runtime immutability and validator lineage rules --- packages/typescript/test/data-flow.test.ts | 76 ++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/packages/typescript/test/data-flow.test.ts b/packages/typescript/test/data-flow.test.ts index 1250b1e..fd8ec8c 100644 --- a/packages/typescript/test/data-flow.test.ts +++ b/packages/typescript/test/data-flow.test.ts @@ -91,3 +91,79 @@ test("output classification is not downgraded and wins ties", () => { assert.equal((tiedEvent.classification as Record).producer, "output-dlp"); }); + +test("classification metadata objects are immutable at runtime", () => { + const taxonomy = "example.enterprise.v1"; + const classification = new ClassificationResult(taxonomy, "confidential", "trusted-store"); + const endpoint = new DataEndpoint("document", "staff-notes"); + const source = new SourceClassification(endpoint, classification); + const order = new ClassificationOrder(taxonomy, ["public", "confidential"]); + for (const value of [classification, endpoint, source, order]) assert.equal(Object.isFrozen(value), true); + assert.equal(Object.isFrozen(order.levels), true); + assert.equal(Reflect.set(classification, "value", "public"), false); + assert.equal(Reflect.set(endpoint, "id", "replacement"), false); + assert.equal(Reflect.set(order, "taxonomy", "other.taxonomy"), false); + assert.deepEqual(order.levels, ["public", "confidential"]); +}); + +test("cheap lineage validation runs before the classifier", () => { + const taxonomy = "example.enterprise.v1"; + const order = new ClassificationOrder(taxonomy, ["public", "confidential"]); + const classification = new ClassificationResult(taxonomy, "confidential", "trusted-store"); + const duplicate = new SourceClassification(new DataEndpoint("document", "same"), classification); + let called = false; + const options = { + runId: "run-1", agentId: "agent-1", direction: "output", + source: new DataEndpoint("transform"), destination: new DataEndpoint("memory"), + purpose: "memory-compaction", + sourceClassifications: [duplicate, duplicate], + classificationOrder: order, + }; + assert.throws(() => classifiedDataFlow(factory, {classify: () => { + called = true; + return new ClassificationResult(taxonomy, "public", "dlp"); + }}, "summary", options), /duplicate source/); + assert.equal(called, false); +}); + +test("SchemaValidator enforces data-flow lineage, identifier, and integer invariants", () => { + const taxonomy = "example.enterprise.v1"; + const order = new ClassificationOrder(taxonomy, ["public", "confidential"]); + const sources = [ + new SourceClassification(new DataEndpoint("document", "public-faq"), + new ClassificationResult(taxonomy, "public", "source-dlp")), + new SourceClassification(new DataEndpoint("document", "staff-notes"), + new ClassificationResult(taxonomy, "confidential", "trusted-store")), + ]; + const event = classifiedDataFlow(factory, + {classify: () => new ClassificationResult(taxonomy, "public", "output-dlp")}, + "summary", { + runId: "run-1", agentId: "agent-1", direction: "output", + source: new DataEndpoint("transform", "summarizer"), + destination: new DataEndpoint("memory", "summary-1"), + purpose: "memory-compaction", + sourceClassifications: sources, + classificationOrder: order, + }); + const validator = SchemaValidator.bundled(); + const clone = () => JSON.parse(JSON.stringify(event)) as Record; + + const duplicate = clone(); + const duplicateSources = duplicate.source_classifications as Array>; + duplicateSources[1]!.source = {...duplicateSources[0]!.source as Record}; + assert.throws(() => validator.validate(duplicate), /duplicates a prior/); + + const mixed = clone(); + const mixedSources = mixed.source_classifications as Array>; + (mixedSources[0]!.classification as Record).taxonomy = "other.taxonomy"; + assert.throws(() => validator.validate(mixed), /same taxonomy/); + + const badIdentifier = clone(); + const badSources = badIdentifier.source_classifications as Array>; + (badSources[0]!.source as Record).kind = "customer data"; + assert.throws(() => validator.validate(badIdentifier), /metadata identifier profile/); + + const unsafe = clone(); + unsafe.size_bytes = Number.MAX_SAFE_INTEGER + 1; + assert.throws(() => validator.validate(unsafe)); +}); From 341d61be070d376244ee77916caa5146bfb2c1ae Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:31:32 +0530 Subject: [PATCH 22/33] docs: clarify 0.2 migration and source tie ordering --- docs/data-flow-classification.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/data-flow-classification.md b/docs/data-flow-classification.md index 58f3937..569f85c 100644 --- a/docs/data-flow-classification.md +++ b/docs/data-flow-classification.md @@ -73,14 +73,19 @@ classifier or policy/label store, and supply the complete lineage. Unknown label mixed taxonomies, duplicate source references, missing lineage, or a missing order are rejected. At most 1,024 sources may be attached to one event. The SDK does not infer declassification or implement reclassification/revocation -propagation. Existing direct-flow calls remain unchanged when the two new -arguments are omitted. Both lineage fields are optional as a pair, so producers -that do not opt in retain the previous event shape. However, consumers using -pre-0.2 closed schemas reject events that include these fields; update the schema -copy to 0.2 before consuming opted-in derived-flow events. +propagation. Existing direct-flow calls retain the previous data-flow +payload shape when the two new arguments are omitted. + +This is a 0.2 contract change, not merely an optional-field change. Every event +from a 0.2 SDK carries `spec_version: 0.2.0-alpha.1`; therefore consumers pinned +to pre-0.2 closed schemas reject all events from the new SDK, including ordinary +direct-flow events that omit both lineage fields. Update the schema copy and +validator to 0.2 before consuming any event produced by a 0.2 SDK. Source identity is the `(kind, id)` pair. Because `id` is optional, two distinct same-kind endpoints without IDs are treated as duplicate references; provide stable, pseudonymized IDs when multiple same-kind sources must be distinguished. The Python API accepts a bounded iterable of source classifications, while the -TypeScript API requires a readonly array. +TypeScript API requires a readonly array. When several sources share the highest rank, the first source in supplied +order wins the deterministic tie-break; iterable/array order is therefore part +of the contract. From 66f9a02ab10b1abd08bc3112f0157829bb8f31a7 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:31:36 +0530 Subject: [PATCH 23/33] docs: update ADR compatibility and tie semantics --- docs/adr/0001-source-classification-inheritance.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/adr/0001-source-classification-inheritance.md b/docs/adr/0001-source-classification-inheritance.md index c077702..3961347 100644 --- a/docs/adr/0001-source-classification-inheritance.md +++ b/docs/adr/0001-source-classification-inheritance.md @@ -26,7 +26,7 @@ The optional event fields are: - `source_classifications`: one source endpoint and its classification metadata for every supplied contributing source; - `classification`: the effective result after applying the explicit order. -The two lineage fields must appear together. Existing direct data-flow calls remain unchanged when neither is supplied. The implementation bounds lineage to 1,024 sources and rejects empty lineage, duplicate endpoint references, unknown labels, mixed taxonomies, and missing or mismatched ordering input. Events carry references and labels only, never source content. +The two lineage fields must appear together. Existing direct data-flow calls remain unchanged when neither is supplied. The implementation bounds lineage to 1,024 sources and rejects empty lineage, duplicate endpoint references, unknown labels, mixed taxonomies, and missing or mismatched ordering input. When several sources share the highest rank, the first source in supplied iterable/array order wins the deterministic tie-break. Events carry references and labels only, never source content. ## Trust and security boundaries @@ -45,9 +45,9 @@ Endpoint identifiers remain metadata and may still be sensitive. Integrators mus ## Compatibility and versioning -The contract version advances from `0.1.0-alpha.6` to `0.2.0-alpha.1`, with matching Python and TypeScript package versions. The two lineage fields remain optional as a pair, so producers that omit them retain the previous event shape. +The contract version advances from `0.1.0-alpha.6` to `0.2.0-alpha.1`, with matching Python and TypeScript package versions. The two lineage fields remain optional as a pair, so producers that omit them retain the previous data-flow payload shape. -The schemas are closed to unknown properties. A consumer pinned to a pre-0.2 schema will reject an event containing the new fields even though they are optional at the producer. Consumers must update their schema copy to 0.2 before processing opted-in derived-flow events. This is an explicit pre-1.0 compatibility change and is called out in the Unreleased changelog. +The envelope version is part of every event. All events emitted by a 0.2 SDK carry `spec_version: 0.2.0-alpha.1`, including direct data-flow events that omit the optional lineage fields. Because schemas are closed and the pre-0.2 envelope requires the earlier version, a consumer pinned to a pre-0.2 schema rejects every event from the 0.2 SDK, not only opted-in derived-flow events. Consumers must update their schema copy and validator to 0.2 before consuming any event emitted by a 0.2 SDK. This is an explicit pre-1.0 compatibility change and is called out in the Unreleased changelog. ## Consequences From f99d1e210bfeb5feb9a04fdfec7da3212fb24def Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:31:40 +0530 Subject: [PATCH 24/33] docs: correct 0.2 changelog compatibility statement --- CHANGELOG.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ceaa2b..9f4439b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,10 +9,12 @@ per-taxonomy order, retain the output classifier's observed label, and emit metadata-only source references. Source-label authenticity and lineage completeness remain caller responsibilities. The contract advances to - `0.2.0-alpha.1`: consumers pinned to pre-0.2 schema copies reject events - carrying these fields and must update their schema copy before consuming - opted-in derived-flow events; producers that omit both fields retain the - previous event shape. + `0.2.0-alpha.1`: every event emitted by a 0.2 SDK carries the new envelope + version, so consumers pinned to pre-0.2 closed schemas reject all events from + the new SDK, including direct-flow events that omit both lineage fields. + Consumers must update their schema copy and validator to 0.2 before + consuming any event emitted by a 0.2 SDK; producers that omit both lineage + fields retain the previous data-flow payload shape. - Shared Python/TypeScript delivery-fault tests for dropped, duplicated and reordered projections and lost persistence acknowledgements, plus Python From df2879dbdcf3278334ca421896241f2eb6b2fa66 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:32:29 +0530 Subject: [PATCH 25/33] test: add shared derived-flow event golden --- compatibility/golden/derived-data-flow.json | 58 +++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 compatibility/golden/derived-data-flow.json diff --git a/compatibility/golden/derived-data-flow.json b/compatibility/golden/derived-data-flow.json new file mode 100644 index 0000000..c50179e --- /dev/null +++ b/compatibility/golden/derived-data-flow.json @@ -0,0 +1,58 @@ +{ + "spec_version": "0.2.0-alpha.1", + "event_id": "018f0f7d-7a13-7cc2-8000-000000000042", + "event_type": "data_flow.observed", + "time_unix_nano": "1787079400000000000", + "run_id": "run-golden-derived-flow", + "producer": { + "name": "derived-flow-golden", + "version": "1.0.0" + }, + "agent_id": "agent-1", + "direction": "output", + "source": { + "kind": "transform", + "id": "summarizer" + }, + "destination": { + "kind": "memory", + "id": "summary-1" + }, + "classification": { + "taxonomy": "example.enterprise.v1", + "value": "confidential", + "producer": "trusted-label-store" + }, + "observed_classification": { + "taxonomy": "example.enterprise.v1", + "value": "public", + "producer": "output-dlp" + }, + "source_classifications": [ + { + "source": { + "kind": "knowledge_graph", + "id": "public-faq" + }, + "classification": { + "taxonomy": "example.enterprise.v1", + "value": "public", + "producer": "source-dlp" + } + }, + { + "source": { + "kind": "document", + "id": "staff-notes" + }, + "classification": { + "taxonomy": "example.enterprise.v1", + "value": "confidential", + "producer": "trusted-label-store" + } + } + ], + "purpose": "memory-compaction", + "policy_decision": "allow", + "transformation": "aggregated" +} From 763ab89b3b44bca8f461a7d14e5d8449a643108b Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:34:19 +0530 Subject: [PATCH 26/33] test: verify derived-flow shared golden in Python --- tests/test_data_flow.py | 51 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/tests/test_data_flow.py b/tests/test_data_flow.py index aad5812..dcd2b80 100644 --- a/tests/test_data_flow.py +++ b/tests/test_data_flow.py @@ -1,7 +1,8 @@ import copy +import json import sys -from collections.abc import Sequence import unittest +from collections.abc import Sequence from datetime import datetime, timezone from enum import IntEnum from pathlib import Path @@ -343,5 +344,53 @@ def test_schema_validator_enforces_lineage_identifier_and_safe_integer_rules(sel + def test_derived_flow_matches_shared_cross_language_golden(self): + from agentrust_telemetry import ClassificationOrder, SourceClassification + + expected = json.loads( + (ROOT / "compatibility" / "golden" / "derived-data-flow.json").read_text( + encoding="utf-8" + ) + ) + factory = EventFactory( + SchemaValidator(ROOT / "spec" / "schema"), + producer_name="derived-flow-golden", + producer_version="1.0.0", + clock_ns=lambda: 1, + event_id_factory=lambda: "018f0f7d-7a13-7cc2-8000-000000000042", + ) + taxonomy = "example.enterprise.v1" + event = classified_data_flow( + factory, + RecordingClassifier(ClassificationResult(taxonomy, "public", "output-dlp")), + "summary", + run_id="run-golden-derived-flow", + agent_id="agent-1", + direction="output", + source=DataEndpoint("transform", "summarizer"), + destination=DataEndpoint("memory", "summary-1"), + purpose="memory-compaction", + policy_decision="allow", + transformation="aggregated", + source_classifications=[ + SourceClassification( + DataEndpoint("knowledge_graph", "public-faq"), + ClassificationResult(taxonomy, "public", "source-dlp"), + ), + SourceClassification( + DataEndpoint("document", "staff-notes"), + ClassificationResult(taxonomy, "confidential", "trusted-label-store"), + ), + ], + classification_order=ClassificationOrder( + taxonomy, ("public", "internal", "confidential", "restricted") + ), + event_id="018f0f7d-7a13-7cc2-8000-000000000042", + time_unix_nano="1787079400000000000", + ) + self.assertEqual(event, expected) + + + if __name__ == "__main__": unittest.main() From 39786e52a5dc995631fc4ebfe4396cefb8658f50 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:34:24 +0530 Subject: [PATCH 27/33] test: verify derived-flow shared golden in TypeScript --- packages/typescript/test/data-flow.test.ts | 50 ++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/packages/typescript/test/data-flow.test.ts b/packages/typescript/test/data-flow.test.ts index fd8ec8c..9577734 100644 --- a/packages/typescript/test/data-flow.test.ts +++ b/packages/typescript/test/data-flow.test.ts @@ -1,7 +1,10 @@ import assert from "node:assert/strict"; +import {readFileSync} from "node:fs"; import test from "node:test"; +import {fileURLToPath} from "node:url"; import {agtDataAccessFlow, ClassificationOrder, ClassificationResult, classifiedDataFlow, DataEndpoint, EventFactory, SchemaValidator, SourceClassification} from "../src/index.js"; +const root = fileURLToPath(new URL("../../../", import.meta.url)); const factory = new EventFactory(SchemaValidator.bundled(), {name: "data-tests", version: "1"}, () => 1n, () => "018f0f7d-7a13-7cc2-8000-000000000042"); test("classifier sees content while the event contains only closed metadata", () => { const secret = {prompt: "customer@example.test token=secret", source_code: "private"}; let seen: unknown; @@ -167,3 +170,50 @@ test("SchemaValidator enforces data-flow lineage, identifier, and integer invari unsafe.size_bytes = Number.MAX_SAFE_INTEGER + 1; assert.throws(() => validator.validate(unsafe)); }); + + +test("derived flow matches the shared Python/TypeScript golden event", () => { + const expected = JSON.parse(readFileSync( + `${root}/compatibility/golden/derived-data-flow.json`, "utf8" + )) as Record; + const goldenFactory = new EventFactory( + SchemaValidator.bundled(), + {name: "derived-flow-golden", version: "1.0.0"}, + () => 1n, + () => "018f0f7d-7a13-7cc2-8000-000000000042", + ); + const taxonomy = "example.enterprise.v1"; + const event = classifiedDataFlow( + goldenFactory, + {classify: () => new ClassificationResult(taxonomy, "public", "output-dlp")}, + "summary", + { + runId: "run-golden-derived-flow", + agentId: "agent-1", + direction: "output", + source: new DataEndpoint("transform", "summarizer"), + destination: new DataEndpoint("memory", "summary-1"), + purpose: "memory-compaction", + policyDecision: "allow", + transformation: "aggregated", + sourceClassifications: [ + new SourceClassification( + new DataEndpoint("knowledge_graph", "public-faq"), + new ClassificationResult(taxonomy, "public", "source-dlp"), + ), + new SourceClassification( + new DataEndpoint("document", "staff-notes"), + new ClassificationResult(taxonomy, "confidential", "trusted-label-store"), + ), + ], + classificationOrder: new ClassificationOrder( + taxonomy, ["public", "internal", "confidential", "restricted"] + ), + envelope: { + eventId: "018f0f7d-7a13-7cc2-8000-000000000042", + timeUnixNano: "1787079400000000000", + }, + }, + ); + assert.deepEqual(event, expected); +}); From fb15973fb2f408d941fde74c3b57c5cd6b42c2c1 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:37:34 +0530 Subject: [PATCH 28/33] fix: correct TypeScript validator declaration formatting --- packages/typescript/src/validation.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/typescript/src/validation.ts b/packages/typescript/src/validation.ts index f01ca53..6843e22 100644 --- a/packages/typescript/src/validation.ts +++ b/packages/typescript/src/validation.ts @@ -11,7 +11,8 @@ const EVENT_SCHEMAS: Record = { "usage.recorded": "usage.schema.json", "data_flow.observed": "data-flow.schema.json", }; -const METADATA_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}$/;\nconst PROHIBITED = new Set([ +const METADATA_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}$/; +const PROHIBITED = new Set([ "prompt", "completion", "source_code", "tool_arguments", "tool_result", "authorization", "credential", "secret", "access_token", "refresh_token", ]); From 6b6c29b35a07e99d8a0806e59140943fa7626319 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Fri, 20 Nov 2026 22:39:02 +0530 Subject: [PATCH 29/33] test: trigger local fork validation for PR 132 --- validation/pr132-trigger.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 validation/pr132-trigger.txt diff --git a/validation/pr132-trigger.txt b/validation/pr132-trigger.txt new file mode 100644 index 0000000..6eb6f41 --- /dev/null +++ b/validation/pr132-trigger.txt @@ -0,0 +1 @@ +Temporary trigger for the PR 132 validation workflow. Removed after the run. \ No newline at end of file From 9cd4f7e66fa7ab54484e2d9bea10bda517d7e73a Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Sat, 21 Nov 2026 12:16:51 +0530 Subject: [PATCH 30/33] fix(examples): use metadata label for governed workflow endpoint --- examples/governed_workflow.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/governed_workflow.py b/examples/governed_workflow.py index 2e34eb7..a41b942 100644 --- a/examples/governed_workflow.py +++ b/examples/governed_workflow.py @@ -204,7 +204,7 @@ def run_scenario() -> dict[str, Any]: span_id=span_id, direction="read", source={"kind": "repository", "id": "application-source"}, - destination={"kind": "agent", "id": AGENT_ID}, + destination={"kind": "agent", "id": "builder"}, classification={ "taxonomy": "example.enterprise.v1", "value": "confidential", From 0d12cc2b32213aa90339aab798c71bb0ebc27c86 Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Sat, 21 Nov 2026 12:16:56 +0530 Subject: [PATCH 31/33] fix(examples): update manual event to telemetry 0.2 --- examples/manual_governance.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/manual_governance.py b/examples/manual_governance.py index fd7f62f..0ceab5c 100644 --- a/examples/manual_governance.py +++ b/examples/manual_governance.py @@ -14,7 +14,7 @@ def emit(self, record): event = { - "spec_version": "0.1.0-alpha.6", + "spec_version": "0.2.0-alpha.1", "event_id": str(uuid.uuid4()), "event_type": "policy.decision", "time_unix_nano": str(time.time_ns()), From aafe6987b4c52d5d1545c3a5069b623359a55ffe Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Sat, 21 Nov 2026 12:18:29 +0530 Subject: [PATCH 32/33] chore: remove temporary PR validation trigger --- validation/pr132-trigger.txt | 1 - 1 file changed, 1 deletion(-) delete mode 100644 validation/pr132-trigger.txt diff --git a/validation/pr132-trigger.txt b/validation/pr132-trigger.txt deleted file mode 100644 index 6eb6f41..0000000 --- a/validation/pr132-trigger.txt +++ /dev/null @@ -1 +0,0 @@ -Temporary trigger for the PR 132 validation workflow. Removed after the run. \ No newline at end of file From 47c27d666c1018fa7c6f60ddb575119c9e68e66f Mon Sep 17 00:00:00 2001 From: Prakash Chand Jain Date: Sat, 28 Nov 2026 21:34:38 +0530 Subject: [PATCH 33/33] docs: clarify 0.2 consumer compatibility --- docs/adr/0001-source-classification-inheritance.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/adr/0001-source-classification-inheritance.md b/docs/adr/0001-source-classification-inheritance.md index 3961347..abe3183 100644 --- a/docs/adr/0001-source-classification-inheritance.md +++ b/docs/adr/0001-source-classification-inheritance.md @@ -54,5 +54,5 @@ The envelope version is part of every event. All events emitted by a 0.2 SDK car - Adopters retain responsibility for source-label provenance and complete lineage. - The source and output classifications become auditable without retaining raw data. - The same explicit taxonomy order is required in both SDKs. -- Consumers pinned to pre-0.2 closed schemas must update their schema copy before processing events that opt into source-label inheritance. +- Consumers pinned to pre-0.2 closed schemas must update their schema copy before processing any event emitted by a 0.2 SDK. - A future declassification or retroactive reclassification design must be handled separately.