Skip to content

test: add evidence trust witnesses - #345

Merged
Sinity merged 1 commit into
masterfrom
feature/test/evidence-trust-witnesses
Apr 22, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/test/evidence-trust-witnesses

Conversation

@Sinity

@Sinity Sinity commented Apr 22, 2026 •

Copy link
Copy Markdown
Owner

Closes #335.

Summary

Adds trust metadata to proof evidence, catalog checks for runner determinism, and a privacy-aware witness metadata contract.

Problem

The proof runners from #333 could produce semantic evidence, but the evidence envelopes did not yet record enough provenance to judge trust, replay risk, privacy handling, or witness adequacy. The catalog also could not flag runners that omitted trust metadata or environmental assumptions.

Solution

  • Extended proof evidence trust metadata with code revision, dirty state, schema version, input and environment fingerprints, runner version, freshness, and origin.
  • Added controlled and uncontrolled dimensions to runner environment contracts, with catalog self-quality checks for missing dimensions and missing trust fields.
  • Stamped runtime proof-runner evidence envelopes with repository and input/environment fingerprints while keeping observed state privacy-safe.
  • Added polylogue.proof.witnesses for witness metadata validation, including privacy records, minimization status, preserved semantic facts, and strict handling for known-failing witnesses.
  • Classified the existing tests/data/golden/tool-use-json.md fixture with committed witness metadata under tests/witnesses/.
  • Refreshed docs/verification-catalog.md from the generated catalog.

Verification

pytest -q -n 0 tests/unit/proof tests/unit/devtools/test_render_verification_catalog.py tests/unit/devtools/test_regression_capture.py tests/unit/infra/test_regression_cases.py
ruff check polylogue/proof tests/unit/proof tests/unit/devtools/test_render_verification_catalog.py tests/witnesses
mypy polylogue/proof tests/unit/proof tests/unit/devtools/test_render_verification_catalog.py
devtools render-all --check
devtools verify --quick
devtools verify
git push -u origin feature/test/evidence-trust-witnesses  # pre-push quick gate passed

@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR expands the proof system with witness metadata and trust provenance tracking. It introduces a new witnesses module for loading and validating witness artifacts with privacy metadata, extends EvidenceEnvelope with runtime-derived trust fields (code revision, schema version, environment fingerprint), adds environment dimension tracking to runner bindings, enhances catalog quality checks for runner environment validation, and updates documentation with new dimension metadata.

Changes

Cohort / File(s) Summary
Proof Models
polylogue/proof/models.py
Extended EnvironmentContract with controlled_dimensions and uncontrolled_dimensions tuple fields; extended TrustMetadata with 9 new optional provenance fields (code revision, dirty state, schema version, digests, environment/runner fingerprints, freshness, origin).
Witness System
polylogue/proof/witnesses.py, tests/unit/proof/test_witnesses.py, tests/witnesses/golden-tool-use-json.witness.json
Added new witnesses module defining PrivacyRecord, WitnessMetadata dataclasses with validation, and loader functions; introduced schema version, directory constants, and origin/minimization/privacy state literals; committed witness validation enforces privacy metadata for live-derived witnesses and semantic fact preservation; added comprehensive unit tests and first committed witness fixture.
Proof Runners & Trust Metadata
polylogue/proof/runners.py
Implemented _runtime_trust_metadata() to populate trust metadata at envelope construction with git revision, dirty state, schema version, and JSON digests of provider schema and environment payload; replaced inline metadata construction with computed values.
Catalog & Quality Checks
polylogue/proof/catalog.py
Added _missing_runner_environment_dimensions_check() quality check validating runner environment declarations; refactored _stale_trust_metadata_check() to validate trust field presence via _missing_runner_trust_fields(); enhanced default _runner_binding() to populate EnvironmentContract with controlled dimensions and enriched TrustMetadata with all provenance fields.
Rendering & Documentation
polylogue/proof/rendering.py, docs/verification-catalog.md
Updated _render_runner_bindings() to include controlled/uncontrolled dimension counts in environment metadata; added catalog.runner_environment_dimensions quality-check entry to verification catalog with all existing runner bindings now populated with dimension metadata.
Public API & Exports
polylogue/proof/__init__.py
Expanded __all__ with 8 new exports: PrivacyRecord, WitnessMetadata, committed_witness_errors, load_committed_witnesses from witnesses module; SchemaValueGenerationObservation, provider_capability_subjects, run_provider_capability_evidence, run_schema_value_generation_evidence from runners/subjects.
Test Coverage
tests/unit/proof/test_catalog.py, tests/unit/proof/test_evidence_runners.py, tests/unit/proof/test_schema_provider_obligations.py, tests/unit/devtools/test_render_verification_catalog.py
Extended existing tests to assert controlled dimension presence, validate new trust metadata fields (runner_version, origin, schema_version, fingerprints), verify quality-check behavior for empty environments; updated test data construction to include dimension and trust metadata; disabled Hypothesis deadline for property-based test.

Possibly related issues

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes


🐰✨ Witness records hop through committed paths,
Trust fingerprints guide each proof's dance,
Environment dimensions now declared with care—
Privacy-safe journeys minimized to what's fair! 🔐

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive Title mentions 'evidence trust witnesses' but omits the broader context of runner environment dimensions, privacy-safe witness metadata, and catalog quality checks that constitute major aspects of the changeset. Consider a more comprehensive title like 'feat: add trust metadata, witness lifecycle, and runner environment validation' or clarify scope with a more descriptive prefix.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed Description follows the template with comprehensive Summary, Problem, Solution, and Verification sections; it addresses all major changes and includes exact verification commands.
Linked Issues check ✅ Passed All acceptance criteria from #335 are met: trust metadata added to envelopes, catalog checks for missing dimensions/trust fields, privacy records implemented, fixture classified, witness metadata with semantic facts/minimization, and known-failing handling established.
Out of Scope Changes check ✅ Passed All code changes directly support the objectives of #335: trust metadata fields, environment contracts, witness validation, catalog checks, rendering updates, and test coverage—no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/test/evidence-trust-witnesses

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6d7ca63de6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread polylogue/proof/runners.py Resolved
Comment thread polylogue/proof/runners.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 13

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@polylogue/proof/catalog.py`:
- Around line 446-458: The trust metadata uses sentinel-looking literals
(code_revision and environment_fingerprint) that could be mistaken for real
digests; update the TrustMetadata instantiation in catalog.py to make these
explicit sentinels (e.g., change code_revision="catalog-reviewed" to
code_revision="static:catalog-reviewed" and
environment_fingerprint="catalog-runner-environment-v1" to
environment_fingerprint="static:catalog-runner-environment-v1") or alternatively
add a clear module-level comment above the TrustMetadata usage explaining these
values are static sentinels (not SHAs/hashes) so downstream consumers of
TrustMetadata know not to parse them as real digests; ensure you edit the lines
setting code_revision and environment_fingerprint in the TrustMetadata block to
reflect the chosen approach.
- Around line 508-535: In _missing_runner_environment_dimensions_check, when
returning the ERROR OutcomeCheck for missing runners you only include the
`missing` IDs in `details` and lose the `uncontrolled` runner identifiers;
update the ERROR branch so `details` contains both lists (e.g., a combined list
or a structured list with both `missing` and `uncontrolled` entries) and keep
`breakdown` as-is; use the existing variables `missing` and `uncontrolled` and
ensure the `count`/`summary` still reflect the current semantics while
preserving the uncontrolled runner identifiers in the returned OutcomeCheck.
- Around line 490-505: _missing_runner_trust_fields currently omits
provider_schema_digest and input_fingerprint from its validation list; update
the tuple in _missing_runner_trust_fields (function in
polylogue/proof/catalog.py) to include ("provider_schema_digest",
trust.provider_schema_digest) and ("input_fingerprint", trust.input_fingerprint)
so those TrustMetadata fields are checked for None/empty strings as the others
are, preserving the existing None/empty-string check logic and return behavior.

In `@polylogue/proof/runners.py`:
- Around line 29-32: _REVIEWED_AT and _RUNTIME_RUNNER_VERSION are hardcoded
which causes stale provenance; replace them with dynamic values: compute
reviewed_at by reading the git commit timestamp for this file (cache the result)
and derive runner_version from the package version or the same git revision used
elsewhere. Update references to the constants (_REVIEWED_AT and
_RUNTIME_RUNNER_VERSION) so they are populated at import/runtime via helper
functions (e.g., get_runner_reviewed_at() and get_runner_version()) that use the
repo/git utilities already in the codebase and include caching to avoid repeated
git calls.
- Around line 553-572: The environment_payload currently only includes static
RunnerBinding fields (runner, evidence_class, cost_tier) so
environment_fingerprint doesn't reflect real runtime state; update the code that
builds environment_payload (used in EvidenceEnvelope.build and passed into
_runtime_trust_metadata) to include resolved controlled_dimensions from
obligation.runner.environment.controlled_dimensions plus runtime-observed values
relevant to the runner contract (e.g., restricted os.environ entries for
required_env/controlled_dimensions, sys.version, platform info,
sqlite3.sqlite_version, locale/timezone, terminal width/color mode, seed/clock
policy, feature flags) and ensure those values are canonicalized before hashing;
alternatively, if you intentionally want a binding-only fingerprint, add a clear
comment/documentation where environment_payload is constructed stating this
field is a "binding fingerprint" (not full environment) and adjust catalog/test
expectations accordingly.
- Around line 630-632: Duplicate JSON+SHA256 fingerprint logic exists: replace
the local _json_digest with a reuse of the existing implementation in
polylogue.proof.models (named _fingerprint) by importing and calling it;
alternatively, if preferred for clarity, expose _fingerprint as a public
function (e.g., fingerprint_json) in polylogue.proof.models and call that from
the runner. Update references in _json_digest callers to use the
imported/re-exported function so the single canonical JSON digest implementation
(the function currently named _fingerprint) is used everywhere.
- Around line 605-627: The git subprocess calls in _git_revision(),
_git_dirty_state() (which both call _git_stdout()) are executed per envelope and
should be cached so a single process returns the same revision/dirty-state for
every envelope; fix by memoizing these functions (e.g., decorate _git_revision
and _git_dirty_state with functools.lru_cache(maxsize=1) or compute module-level
constants at import using a one-time call to _git_stdout) so subprocess.run is
invoked only once per process and all envelopes observe the same values.

In `@polylogue/proof/witnesses.py`:
- Around line 184-200: The current flow silently overwrites duplicate
witness.witness_id keys; fix by detecting duplicates right after loading in
load_committed_witnesses (which uses load_witnesses -> WitnessMetadata.read).
After getting the tuple of WitnessMetadata, build a mapping/count of
witness.witness_id values, and if any id appears more than once raise a clear
exception (e.g., ValueError) listing the duplicate IDs and their source files,
or alternatively return a structured JSON error to be consumed by
committed_witness_errors; ensure the check references WitnessMetadata.read,
load_witnesses, load_committed_witnesses, and witness.witness_id so duplicates
are flagged instead of overwritten.
- Around line 21-24: The _string_tuple function currently filters values using
str(value).strip() but returns the unstripped str(value), allowing whitespace
like trailing newlines to slip through into preserved_semantic_facts/notes;
change the implementation to compute stripped_value = str(value).strip() and
only include stripped_value in the resulting tuple (use stripped_value for both
the guard and stored result) inside the _string_tuple function to ensure stored
entries have leading/trailing whitespace removed.
- Around line 38-49: PrivacyRecord.from_payload currently coerces any unknown
private_material string to "not_observed", letting misspelled or unexpected
values bypass live_commit_errors(); change this to strict validation by adding a
helper (patterned after _origin / _minimization_status) that accepts only the
canonical values "observed" or "not_observed" and raises a ValueError on unknown
inputs, then call that helper from PrivacyRecord.from_payload to set
private_material (do not silently coerce); reference PrivacyRecord.from_payload,
the new helper (e.g. _private_material_state_or_raise), and ensure behavior ties
into live_commit_errors() / validation_errors() expectations.
- Around line 91-120: from_payload currently treats booleans as ints and
silently coalesces non-int types to 0; change the schema_version validation in
WitnessMetadata.from_payload to enforce an actual integer (and explicitly reject
bool) and raise a clear TypeError for other types instead of defaulting to 0;
specifically, check schema_version_raw for type int and not bool (and optionally
accept numeric strings only if you intentionally parse them), then compare to
WITNESS_SCHEMA_VERSION and raise a ValueError for mismatches—this will ensure
schema_version_raw is validated before use.

In `@tests/unit/proof/test_evidence_runners.py`:
- Around line 42-48: Add a negative-case assertion to ensure the two distinct
fingerprints are different: after the existing checks on
envelope.trust.input_fingerprint and envelope.trust.environment_fingerprint, add
an assertion that envelope.trust.input_fingerprint !=
envelope.trust.environment_fingerprint to catch regressions where both digests
are accidentally computed from the same payload (e.g., both using
observed_state).

In `@tests/unit/proof/test_witnesses.py`:
- Around line 14-23: The test
test_committed_witness_catalog_classifies_existing_fixture_by_provenance is
fragile: replace the direct next(...) lookup with an explicit filter + assert to
produce a clear error when the fixture is missing (e.g., collect matches = [w
for w in witnesses if w.witness_id == "golden.tool-use-json"]; assert matches;
witness = matches[0]); also make path assertions robust by anchoring
witness.path to the repository root instead of a relative literal (use the test
file's resolved parent via Path(__file__).resolve() or pytest's rootdir to build
the expected Path) so comparisons against
Path("tests/data/golden/tool-use-json.md") do not depend on cwd; keep other
checks (committed_witness_errors(witnesses), witness.origin, witness.provenance
keys) unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 4ced75d1-28dc-438e-a536-42e28d696908

📥 Commits

Reviewing files that changed from the base of the PR and between 531d5ca and 6d7ca63.

📒 Files selected for processing (13)
  • docs/verification-catalog.md
  • polylogue/proof/__init__.py
  • polylogue/proof/catalog.py
  • polylogue/proof/models.py
  • polylogue/proof/rendering.py
  • polylogue/proof/runners.py
  • polylogue/proof/witnesses.py
  • tests/unit/devtools/test_render_verification_catalog.py
  • tests/unit/proof/test_catalog.py
  • tests/unit/proof/test_evidence_runners.py
  • tests/unit/proof/test_schema_provider_obligations.py
  • tests/unit/proof/test_witnesses.py
  • tests/witnesses/golden-tool-use-json.witness.json

Comment on lines 446 to 458
trust=TrustMetadata(
producer="polylogue.proof.catalog",
reviewed_at=_REVIEWED_AT,
level="authored",
privacy="repo-local metadata only; no archive payloads",
code_revision="catalog-reviewed",
dirty_state=False,
schema_version=SCHEMA_VERSION,
environment_fingerprint="catalog-runner-environment-v1",
runner_version=_RUNNER_VERSION,
freshness="static review refreshed with generated catalog",
origin="authored-catalog",
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Placeholder-looking code_revision="catalog-reviewed" and hardcoded environment_fingerprint.

These are authored constants rather than derived values, which is fine for the catalog's own static runners, but the strings look like sentinels that may be confused with real digests. Consider naming them explicitly as sentinels (e.g., "static:catalog-reviewed", "static:catalog-runner-environment-v1") or documenting via a module-level comment so downstream consumers of TrustMetadata don't attempt to parse them as git SHAs / content hashes.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/proof/catalog.py` around lines 446 - 458, The trust metadata uses
sentinel-looking literals (code_revision and environment_fingerprint) that could
be mistaken for real digests; update the TrustMetadata instantiation in
catalog.py to make these explicit sentinels (e.g., change
code_revision="catalog-reviewed" to code_revision="static:catalog-reviewed" and
environment_fingerprint="catalog-runner-environment-v1" to
environment_fingerprint="static:catalog-runner-environment-v1") or alternatively
add a clear module-level comment above the TrustMetadata usage explaining these
values are static sentinels (not SHAs/hashes) so downstream consumers of
TrustMetadata know not to parse them as real digests; ensure you edit the lines
setting code_revision and environment_fingerprint in the TrustMetadata block to
reflect the chosen approach.

Comment on lines +490 to +505
def _missing_runner_trust_fields(trust: TrustMetadata) -> list[str]:
missing: list[str] = []
for field_name, value in (
("producer", trust.producer),
("reviewed_at", trust.reviewed_at),
("code_revision", trust.code_revision),
("dirty_state", trust.dirty_state),
("schema_version", trust.schema_version),
("environment_fingerprint", trust.environment_fingerprint),
("runner_version", trust.runner_version),
("freshness", trust.freshness),
("origin", trust.origin),
):
if value is None or (isinstance(value, str) and not value.strip()):
missing.append(field_name)
return missing

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check whether any runner binding elsewhere is expected to populate these fields,
# so the asymmetry between TrustMetadata schema and catalog check is intentional.
rg -nP --type=py -C2 '\b(provider_schema_digest|input_fingerprint)\b'

Repository: Sinity/polylogue

Length of output: 2135


Include provider_schema_digest and input_fingerprint in the trust field validation.

_missing_runner_trust_fields checks seven fields but omits provider_schema_digest and input_fingerprint, which are defined in TrustMetadata and actively populated in polylogue/proof/runners.py (lines 590–591). Tests explicitly validate that input_fingerprint is not None (test_evidence_runners.py:45–46), confirming these fields are expected to carry values. The function should validate all declared fields consistently.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/proof/catalog.py` around lines 490 - 505,
_missing_runner_trust_fields currently omits provider_schema_digest and
input_fingerprint from its validation list; update the tuple in
_missing_runner_trust_fields (function in polylogue/proof/catalog.py) to include
("provider_schema_digest", trust.provider_schema_digest) and
("input_fingerprint", trust.input_fingerprint) so those TrustMetadata fields are
checked for None/empty strings as the others are, preserving the existing
None/empty-string check logic and return behavior.

Comment on lines +508 to +535
def _missing_runner_environment_dimensions_check(runners: tuple[RunnerBinding, ...]) -> OutcomeCheck:
missing = [
runner.id
for runner in runners
if not runner.environment.controlled_dimensions and not runner.environment.uncontrolled_dimensions
]
uncontrolled = [
f"{runner.id}: {', '.join(runner.environment.uncontrolled_dimensions)}"
for runner in runners
if runner.environment.uncontrolled_dimensions
]
if missing:
return OutcomeCheck(
name="catalog.runner_environment_dimensions",
status=OutcomeStatus.ERROR,
summary=f"runner environment dimensions missing: {len(missing)}",
count=len(missing),
details=missing[:50],
breakdown={"missing": len(missing), "uncontrolled": len(uncontrolled)},
)
return OutcomeCheck(
name="catalog.runner_environment_dimensions",
status=OutcomeStatus.OK,
summary=f"runner environment dimensions declared; uncontrolled dimensions: {len(uncontrolled)}",
count=len(uncontrolled),
details=uncontrolled[:50],
breakdown={"missing": 0, "uncontrolled": len(uncontrolled)},
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Uncontrolled-dimension runners are hidden when any runner is missing dimensions entirely.

In the ERROR branch (Line 519-527) you emit details only for runners with fully empty environment contracts. Runners that declare uncontrolled_dimensions still get reported in breakdown["uncontrolled"] as a bare count, but their identifiers are dropped. When both conditions co-occur, operators can see that there are uncontrolled dimensions somewhere but can't tell which runners — defeating the self-quality signal the check is meant to provide.

♻️ Suggested fix to surface uncontrolled runner details on error too
     if missing:
         return OutcomeCheck(
             name="catalog.runner_environment_dimensions",
             status=OutcomeStatus.ERROR,
             summary=f"runner environment dimensions missing: {len(missing)}",
             count=len(missing),
-            details=missing[:50],
+            details=(missing + uncontrolled)[:50],
             breakdown={"missing": len(missing), "uncontrolled": len(uncontrolled)},
         )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/proof/catalog.py` around lines 508 - 535, In
_missing_runner_environment_dimensions_check, when returning the ERROR
OutcomeCheck for missing runners you only include the `missing` IDs in `details`
and lose the `uncontrolled` runner identifiers; update the ERROR branch so
`details` contains both lists (e.g., a combined list or a structured list with
both `missing` and `uncontrolled` entries) and keep `breakdown` as-is; use the
existing variables `missing` and `uncontrolled` and ensure the `count`/`summary`
still reflect the current semantics while preserving the uncontrolled runner
identifiers in the returned OutcomeCheck.

Comment on lines 29 to +32
_REVIEWED_AT = "2026-04-22T00:00:00+00:00"
_OUTPUT_SAMPLE_LIMIT = 1_000
_REPO_ROOT = Path(__file__).resolve().parents[2]
_RUNTIME_RUNNER_VERSION = "proof-runners.v1"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

_RUNTIME_RUNNER_VERSION and _REVIEWED_AT are hardcoded constants.

Both values are static: "proof-runners.v1" never changes as runner code evolves, and _REVIEWED_AT = "2026-04-22T00:00:00+00:00" will still be emitted on 2027-01-01. That undermines the freshness/provenance guarantees the new trust fields are meant to provide — stale reviewed_at will silently fly through catalog.runner_trust_metadata unless staleness is computed elsewhere from a separate source.

Consider sourcing reviewed_at from the git commit time of the runner file (cached) and deriving runner_version from a package version or the same git revision you already look up.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/proof/runners.py` around lines 29 - 32, _REVIEWED_AT and
_RUNTIME_RUNNER_VERSION are hardcoded which causes stale provenance; replace
them with dynamic values: compute reviewed_at by reading the git commit
timestamp for this file (cache the result) and derive runner_version from the
package version or the same git revision used elsewhere. Update references to
the constants (_REVIEWED_AT and _RUNTIME_RUNNER_VERSION) so they are populated
at import/runtime via helper functions (e.g., get_runner_reviewed_at() and
get_runner_version()) that use the repo/git utilities already in the codebase
and include caching to avoid repeated git calls.

Comment on lines +553 to 572
environment_payload: JSONDocument = {
"runner": obligation.runner.runner,
"evidence_class": obligation.runner.evidence_class,
"cost_tier": obligation.runner.cost_tier,
}
return EvidenceEnvelope.build(
obligation_id=obligation.id,
status=status,
evidence=evidence,
counterexample=counterexample,
reproducer=reproducer,
environment={
"runner": obligation.runner.runner,
"evidence_class": obligation.runner.evidence_class,
"cost_tier": obligation.runner.cost_tier,
},
environment=environment_payload,
provenance=provenance,
trust=TrustMetadata(
trust=_runtime_trust_metadata(
producer=producer,
reviewed_at=_REVIEWED_AT,
level="generated",
privacy="repo-local command metadata or seeded fixture ids only",
obligation=obligation,
observed_state=observed_state,
environment=environment_payload,
),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

environment_fingerprint does not fingerprint the actual environment.

environment_payload contains only runner, evidence_class, and cost_tier — static RunnerBinding attributes that are already covered by obligation_id. The SHA256 of this payload is therefore identical for every invocation of a given binding and does not capture any of the runner-environment contract dimensions the PR/issue #335 calls out (timezone, locale, terminal width/color mode, random seeds, clock policy, filesystem ordering, SQLite features, feature flags, controlled/uncontrolled dimension values).

As a result, the new catalog check catalog.runner_environment_dimensions plus the test assertion that environment_fingerprint is a 64-char hex digest give a false sense of coverage: a change to TZ, LC_ALL, Python version, or SQLite build would not change the fingerprint.

Consider hashing, at minimum, the resolved values of obligation.runner.environment.controlled_dimensions together with runtime-observed values (e.g. os.environ subset for required_env / controlled_dimensions, sys.version, sqlite3.sqlite_version). Otherwise, document explicitly that this field is a "binding fingerprint," not an environment one, to avoid misleading downstream validators.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/proof/runners.py` around lines 553 - 572, The environment_payload
currently only includes static RunnerBinding fields (runner, evidence_class,
cost_tier) so environment_fingerprint doesn't reflect real runtime state; update
the code that builds environment_payload (used in EvidenceEnvelope.build and
passed into _runtime_trust_metadata) to include resolved controlled_dimensions
from obligation.runner.environment.controlled_dimensions plus runtime-observed
values relevant to the runner contract (e.g., restricted os.environ entries for
required_env/controlled_dimensions, sys.version, platform info,
sqlite3.sqlite_version, locale/timezone, terminal width/color mode, seed/clock
policy, feature flags) and ensure those values are canonicalized before hashing;
alternatively, if you intentionally want a binding-only fingerprint, add a clear
comment/documentation where environment_payload is constructed stating this
field is a "binding fingerprint" (not full environment) and adjust catalog/test
expectations accordingly.

Comment on lines +38 to +49
@classmethod
def from_payload(cls, payload: JSONDocument) -> PrivacyRecord:
private_material_raw = str(payload.get("private_material", "not_observed"))
private_material: PrivateMaterialState = "observed" if private_material_raw == "observed" else "not_observed"
return cls(
private_material=private_material,
transformed=bool(payload.get("transformed", False)),
redacted=bool(payload.get("redacted", False)),
discarded=bool(payload.get("discarded", False)),
retained=bool(payload.get("retained", False)),
notes=_string_tuple(payload.get("notes", [])),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

PrivacyRecord.from_payload silently coerces unknown private_material values to "not_observed", bypassing privacy validation.

Any typo or unexpected value (e.g. "Observed", "retained", "OBSERVED") is silently mapped to "not_observed" at line 41. Because live_commit_errors() only runs when private_material == "observed", a misspelled witness will pass validation_errors() without any live-commit privacy checks being applied — directly weakening the PR's stated requirement that live-derived witnesses include privacy/redaction metadata before commit.

Prefer strict validation consistent with _origin / _minimization_status:

🛡️ Proposed fix
     `@classmethod`
     def from_payload(cls, payload: JSONDocument) -> PrivacyRecord:
-        private_material_raw = str(payload.get("private_material", "not_observed"))
-        private_material: PrivateMaterialState = "observed" if private_material_raw == "observed" else "not_observed"
+        private_material = _private_material_state(payload.get("private_material", "not_observed"))
         return cls(
             private_material=private_material,

Plus a helper alongside _origin / _minimization_status that raises on unknown values.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/proof/witnesses.py` around lines 38 - 49,
PrivacyRecord.from_payload currently coerces any unknown private_material string
to "not_observed", letting misspelled or unexpected values bypass
live_commit_errors(); change this to strict validation by adding a helper
(patterned after _origin / _minimization_status) that accepts only the canonical
values "observed" or "not_observed" and raises a ValueError on unknown inputs,
then call that helper from PrivacyRecord.from_payload to set private_material
(do not silently coerce); reference PrivacyRecord.from_payload, the new helper
(e.g. _private_material_state_or_raise), and ensure behavior ties into
live_commit_errors() / validation_errors() expectations.

Comment on lines +91 to +120
@classmethod
def from_payload(cls, payload: JSONDocument) -> WitnessMetadata:
schema_version_raw = payload.get("schema_version")
schema_version = schema_version_raw if isinstance(schema_version_raw, int) else 0
if schema_version != WITNESS_SCHEMA_VERSION:
raise ValueError(f"unsupported witness schema_version: {schema_version}")
privacy_payload = payload.get("privacy")
privacy = (
PrivacyRecord.from_payload(require_json_document(privacy_payload, context="witness privacy"))
if privacy_payload is not None
else None
)
return cls(
witness_id=str(payload["witness_id"]),
path=str(payload["path"]),
origin=_origin(payload.get("origin")),
provenance=require_json_document(payload.get("provenance", {}), context="witness provenance"),
preserved_semantic_facts=_string_tuple(payload.get("preserved_semantic_facts", [])),
minimization_status=_minimization_status(payload.get("minimization_status")),
privacy=privacy,
committed=bool(payload.get("committed", True)),
known_failing=bool(payload.get("known_failing", False)),
xfail_strict=bool(payload.get("xfail_strict", False)),
linked_issue=str(payload["linked_issue"]) if payload.get("linked_issue") is not None else None,
rejection_reason=(
str(payload["rejection_reason"]) if payload.get("rejection_reason") is not None else None
),
notes=_string_tuple(payload.get("notes", [])),
schema_version=schema_version,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Schema-version check accepts bool and silently drops non-int types.

isinstance(schema_version_raw, int) is True for bool (e.g. "schema_version": true passes as 1 and then compares equal to WITNESS_SCHEMA_VERSION). Also, a string like "1" is coerced to 0, which surfaces as "unsupported witness schema_version: 0" rather than a clearer type error. Consider tightening:

-        schema_version_raw = payload.get("schema_version")
-        schema_version = schema_version_raw if isinstance(schema_version_raw, int) else 0
-        if schema_version != WITNESS_SCHEMA_VERSION:
-            raise ValueError(f"unsupported witness schema_version: {schema_version}")
+        schema_version_raw = payload.get("schema_version")
+        if not isinstance(schema_version_raw, int) or isinstance(schema_version_raw, bool):
+            raise ValueError(f"witness schema_version must be an integer: {schema_version_raw!r}")
+        if schema_version_raw != WITNESS_SCHEMA_VERSION:
+            raise ValueError(f"unsupported witness schema_version: {schema_version_raw}")
+        schema_version = schema_version_raw
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/proof/witnesses.py` around lines 91 - 120, from_payload currently
treats booleans as ints and silently coalesces non-int types to 0; change the
schema_version validation in WitnessMetadata.from_payload to enforce an actual
integer (and explicitly reject bool) and raise a clear TypeError for other types
instead of defaulting to 0; specifically, check schema_version_raw for type int
and not bool (and optionally accept numeric strings only if you intentionally
parse them), then compare to WITNESS_SCHEMA_VERSION and raise a ValueError for
mismatches—this will ensure schema_version_raw is validated before use.

Comment on lines +184 to +200
def load_witnesses(paths: Iterable[Path]) -> tuple[WitnessMetadata, ...]:
return tuple(WitnessMetadata.read(path) for path in sorted(paths))


def load_committed_witnesses(root: Path = COMMITTED_WITNESS_DIR) -> tuple[WitnessMetadata, ...]:
if not root.exists():
return ()
return load_witnesses(root.glob("*.witness.json"))


def committed_witness_errors(witnesses: Iterable[WitnessMetadata]) -> JSONDocument:
errors: JSONDocument = {}
for witness in witnesses:
witness_errors = witness.validation_errors()
if witness_errors:
errors[witness.witness_id] = list(witness_errors)
return errors

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Duplicate witness_id entries are silently overwritten.

committed_witness_errors keys its result dict by witness.witness_id, and load_committed_witnesses loads every *.witness.json in the tree without checking uniqueness. Two committed fixtures with the same witness_id would (a) produce an ambiguous mapping in the error report and (b) not be flagged as a catalog-quality failure. Consider asserting uniqueness at load time or emitting a dedicated error in committed_witness_errors.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/proof/witnesses.py` around lines 184 - 200, The current flow
silently overwrites duplicate witness.witness_id keys; fix by detecting
duplicates right after loading in load_committed_witnesses (which uses
load_witnesses -> WitnessMetadata.read). After getting the tuple of
WitnessMetadata, build a mapping/count of witness.witness_id values, and if any
id appears more than once raise a clear exception (e.g., ValueError) listing the
duplicate IDs and their source files, or alternatively return a structured JSON
error to be consumed by committed_witness_errors; ensure the check references
WitnessMetadata.read, load_witnesses, load_committed_witnesses, and
witness.witness_id so duplicates are flagged instead of overwritten.

Comment on lines +42 to +48
assert envelope.trust.runner_version == "proof-runners.v1"
assert envelope.trust.origin == "proof-runner"
assert envelope.trust.schema_version == 1
assert envelope.trust.input_fingerprint is not None
assert len(envelope.trust.input_fingerprint) == 64
assert envelope.trust.environment_fingerprint is not None
assert len(envelope.trust.environment_fingerprint) == 64

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Assertions verify runtime trust metadata shape; consider also covering a negative case.

The added checks pin runner_version, origin, schema_version, and 64-char SHA256 fingerprints — good. Consider a companion assertion that input_fingerprint != environment_fingerprint (they're hashed from distinct payloads) so a future regression where both inputs collide into one digest (e.g. both fed observed_state) is caught.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/proof/test_evidence_runners.py` around lines 42 - 48, Add a
negative-case assertion to ensure the two distinct fingerprints are different:
after the existing checks on envelope.trust.input_fingerprint and
envelope.trust.environment_fingerprint, add an assertion that
envelope.trust.input_fingerprint != envelope.trust.environment_fingerprint to
catch regressions where both digests are accidentally computed from the same
payload (e.g., both using observed_state).

Comment on lines +14 to +23
def test_committed_witness_catalog_classifies_existing_fixture_by_provenance() -> None:
witnesses = load_committed_witnesses()
witness = next(item for item in witnesses if item.witness_id == "golden.tool-use-json")

assert committed_witness_errors(witnesses) == {}
assert Path(witness.path).exists()
assert Path(witness.path) == Path("tests/data/golden/tool-use-json.md")
assert witness.origin == "golden-surface-snapshot"
assert witness.provenance["fixture_kind"] == "golden-rendering-snapshot"
assert witness.provenance["raw_material"] == "synthetic"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Minor: use a debuggable lookup + anchor fixture paths to the repo root.

Two small fragilities:

  1. Line 16: next(item for item in witnesses if item.witness_id == "golden.tool-use-json") raises StopIteration if the fixture is ever renamed/removed, which pytest surfaces as an uninformative error. A small helper or explicit filter+assert gives a clearer failure.
  2. Lines 15 and 20: load_committed_witnesses() uses the default COMMITTED_WITNESS_DIR (relative tests/witnesses) and the assertion compares against Path("tests/data/golden/tool-use-json.md"). Both silently depend on pytest running from the repo root. Anchoring via rootpath / pytest's rootdir fixture (or a module-level Path(__file__).resolve().parents[N]) would make the test robust to invocation cwd.
♻️ Suggested shape
-def test_committed_witness_catalog_classifies_existing_fixture_by_provenance() -> None:
-    witnesses = load_committed_witnesses()
-    witness = next(item for item in witnesses if item.witness_id == "golden.tool-use-json")
-
-    assert committed_witness_errors(witnesses) == {}
-    assert Path(witness.path).exists()
-    assert Path(witness.path) == Path("tests/data/golden/tool-use-json.md")
+def test_committed_witness_catalog_classifies_existing_fixture_by_provenance() -> None:
+    witnesses = load_committed_witnesses()
+    matches = [w for w in witnesses if w.witness_id == "golden.tool-use-json"]
+    assert matches, "expected committed witness 'golden.tool-use-json' to be present"
+    witness = matches[0]
+
+    assert committed_witness_errors(witnesses) == {}
+    repo_root = Path(__file__).resolve().parents[3]
+    assert (repo_root / witness.path).exists()
+    assert Path(witness.path) == Path("tests/data/golden/tool-use-json.md")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def test_committed_witness_catalog_classifies_existing_fixture_by_provenance() -> None:
witnesses = load_committed_witnesses()
witness = next(item for item in witnesses if item.witness_id == "golden.tool-use-json")
assert committed_witness_errors(witnesses) == {}
assert Path(witness.path).exists()
assert Path(witness.path) == Path("tests/data/golden/tool-use-json.md")
assert witness.origin == "golden-surface-snapshot"
assert witness.provenance["fixture_kind"] == "golden-rendering-snapshot"
assert witness.provenance["raw_material"] == "synthetic"
def test_committed_witness_catalog_classifies_existing_fixture_by_provenance() -> None:
witnesses = load_committed_witnesses()
matches = [w for w in witnesses if w.witness_id == "golden.tool-use-json"]
assert matches, "expected committed witness 'golden.tool-use-json' to be present"
witness = matches[0]
assert committed_witness_errors(witnesses) == {}
repo_root = Path(__file__).resolve().parents[3]
assert (repo_root / witness.path).exists()
assert Path(witness.path) == Path("tests/data/golden/tool-use-json.md")
assert witness.origin == "golden-surface-snapshot"
assert witness.provenance["fixture_kind"] == "golden-rendering-snapshot"
assert witness.provenance["raw_material"] == "synthetic"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/proof/test_witnesses.py` around lines 14 - 23, The test
test_committed_witness_catalog_classifies_existing_fixture_by_provenance is
fragile: replace the direct next(...) lookup with an explicit filter + assert to
produce a clear error when the fixture is missing (e.g., collect matches = [w
for w in witnesses if w.witness_id == "golden.tool-use-json"]; assert matches;
witness = matches[0]); also make path assertions robust by anchoring
witness.path to the repository root instead of a relative literal (use the test
file's resolved parent via Path(__file__).resolve() or pytest's rootdir to build
the expected Path) so comparisons against
Path("tests/data/golden/tool-use-json.md") do not depend on cwd; keep other
checks (committed_witness_errors(witnesses), witness.origin, witness.provenance
keys) unchanged.

@Sinity
Sinity merged commit 1e42dbf into master Apr 22, 2026
14 checks passed
@Sinity
Sinity deleted the feature/test/evidence-trust-witnesses branch April 22, 2026 04:22
Sinity added a commit that referenced this pull request Apr 22, 2026
Closes #335.

## Summary

Adds trust metadata to proof evidence, catalog checks for runner determinism, and a privacy-aware witness metadata contract.

## Problem

The proof runners from #333 could produce semantic evidence, but the evidence envelopes did not yet record enough provenance to judge trust, replay risk, privacy handling, or witness adequacy. The catalog also could not flag runners that omitted trust metadata or environmental assumptions.

## Solution

- Extended proof evidence trust metadata with code revision, dirty state, schema version, input and environment fingerprints, runner version, freshness, and origin.
- Added controlled and uncontrolled dimensions to runner environment contracts, with catalog self-quality checks for missing dimensions and missing trust fields.
- Stamped runtime proof-runner evidence envelopes with repository and input/environment fingerprints while keeping observed state privacy-safe.
- Added `polylogue.proof.witnesses` for witness metadata validation, including privacy records, minimization status, preserved semantic facts, and strict handling for known-failing witnesses.
- Classified the existing `tests/data/golden/tool-use-json.md` fixture with committed witness metadata under `tests/witnesses/`.
- Refreshed `docs/verification-catalog.md` from the generated catalog.

## Verification

```text
pytest -q -n 0 tests/unit/proof tests/unit/devtools/test_render_verification_catalog.py tests/unit/devtools/test_regression_capture.py tests/unit/infra/test_regression_cases.py
ruff check polylogue/proof tests/unit/proof tests/unit/devtools/test_render_verification_catalog.py tests/witnesses
mypy polylogue/proof tests/unit/proof tests/unit/devtools/test_render_verification_catalog.py
devtools render-all --check
devtools verify --quick
devtools verify
git push -u origin feature/test/evidence-trust-witnesses  # pre-push quick gate passed
```
Sinity added a commit that referenced this pull request Apr 22, 2026
The proof runners from #333 could produce semantic evidence, but
the evidence envelopes didn't record enough provenance to judge
trust, replay risk, privacy handling, or witness adequacy. The
catalog also couldn't flag runners that omitted trust metadata or
environmental assumptions.

Extends proof evidence trust metadata with code revision, dirty
state, schema version, input and environment fingerprints, runner
version, freshness, and origin. Adds controlled and uncontrolled
dimensions to runner environment contracts, with catalog
self-quality checks for missing dimensions and missing trust
fields. Stamps runtime proof-runner evidence envelopes with
repository and input/environment fingerprints while keeping
observed state privacy-safe. Adds `polylogue.proof.witnesses` for
witness metadata validation, including privacy records,
minimization status, preserved semantic facts, and strict handling
for known-failing witnesses. Classifies the existing
`tool-use-json.md` golden fixture with committed witness metadata
under `tests/witnesses/`.

Verification: ruff + mypy + pytest over proof / render-verification-
catalog / regression-capture / regression-cases suites; devtools
render-all --check, verify and --quick green.

Closes #335
Sinity added a commit that referenced this pull request Apr 22, 2026
The proof runners from #333 could produce semantic evidence, but
the evidence envelopes didn't record enough provenance to judge
trust, replay risk, privacy handling, or witness adequacy. The
catalog also couldn't flag runners that omitted trust metadata or
environmental assumptions.

Extends proof evidence trust metadata with code revision, dirty
state, schema version, input and environment fingerprints, runner
version, freshness, and origin. Adds controlled and uncontrolled
dimensions to runner environment contracts, with catalog
self-quality checks for missing dimensions and missing trust
fields. Stamps runtime proof-runner evidence envelopes with
repository and input/environment fingerprints while keeping
observed state privacy-safe. Adds `polylogue.proof.witnesses` for
witness metadata validation, including privacy records,
minimization status, preserved semantic facts, and strict handling
for known-failing witnesses. Classifies the existing
`tool-use-json.md` golden fixture with committed witness metadata
under `tests/witnesses/`.

Verification: ruff + mypy + pytest over proof / render-verification-
catalog / regression-capture / regression-cases suites; devtools
render-all --check, verify and --quick green.

Closes #335
Sinity added a commit that referenced this pull request Apr 22, 2026
The proof runners from #333 could produce semantic evidence, but
the evidence envelopes didn't record enough provenance to judge
trust, replay risk, privacy handling, or witness adequacy. The
catalog also couldn't flag runners that omitted trust metadata or
environmental assumptions.

Extends proof evidence trust metadata with code revision, dirty
state, schema version, input and environment fingerprints, runner
version, freshness, and origin. Adds controlled and uncontrolled
dimensions to runner environment contracts, with catalog
self-quality checks for missing dimensions and missing trust
fields. Stamps runtime proof-runner evidence envelopes with
repository and input/environment fingerprints while keeping
observed state privacy-safe. Adds `polylogue.proof.witnesses` for
witness metadata validation, including privacy records,
minimization status, preserved semantic facts, and strict handling
for known-failing witnesses. Classifies the existing
`tool-use-json.md` golden fixture with committed witness metadata
under `tests/witnesses/`.

Verification: ruff + mypy + pytest over proof / render-verification-
catalog / regression-capture / regression-cases suites; devtools
render-all --check, verify and --quick green.

Closes #335
@Sinity

Sinity commented Apr 28, 2026

Copy link
Copy Markdown
Owner Author

🤖 Post-hoc audit note: this PR received bot review feedback verified against current HEAD as part of #544. 15 finding(s) confirmed still present → tracked in #550.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test: add evidence trust, privacy-safe witnesses, and minimization

1 participant