Skip to content

feat(quality): add local context evidence - #303

Merged
abiorh-claw merged 14 commits into
mainfrom
codex/ws-qual-002-02-context-evidence
Aug 9, 2026
Merged

feat(quality): add local context evidence#303
abiorh-claw merged 14 commits into
mainfrom
codex/ws-qual-002-02-context-evidence

Conversation

@Abiorh001

@Abiorh001 Abiorh001 commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

Workstream PR Trust Bundle

Chunk

WS-QUAL-002-02 - Local Coverage-Context Evidence

Goal

Emit bounded, non-authoritative callable-to-test candidate evidence from exact
local coverage contexts without adding hosted CI infrastructure.

Intent And Planning Context

  • Intent: ../INTENT.md
  • Chunk contract: ../chunks/WS-QUAL-002-02-context-evidence.md

What Changed

  • Added manual context-evidence generation and validation commands.
  • Reused semantic-lane collection and completion custody.
  • Mapped per-test coverage contexts to exact callable spans.
  • Added digest, exact-head, clean-tree, runtime, size, path, overwrite, privacy,
    and non-authoritative-schema controls.
  • Added focused fail-closed tests and operational documentation.

Why It Changed

Imports and coverage totals do not show which exact tests execute a callable.
This bounded evidence makes later ownership review better informed without
claiming that inferred execution proves assertions or reviewed ownership.

Design Chosen

One local-only artifact uses the existing lane plugin for collection and
completion, coverage.py test contexts for line evidence, and an independent
schema that catalogue validation cannot consume.

Alternatives Rejected

  • Hosted collection was rejected because this calibration chunk must add no CI
    cost or required gate.
  • Import-based inference was rejected because importing code does not prove
    behavior execution.
  • Automatic catalogue population was rejected because candidate evidence is
    not reviewed ownership.

Scope Control

Allowed Files Changed

  • WS-QUAL-002 plan, status, contract, and review evidence.
  • backend/scripts/behavior_ownership.py and run_test_lanes.py.
  • Their focused tests and backend testing operations documentation.

Files Outside Stated Scope

  • None.

Product Behavior

  • No Workstream product behavior changed.
  • Product behavior changed and is explained here.

Evidence

Commands Run

cd backend
.venv/bin/ruff check scripts/behavior_ownership.py scripts/run_test_lanes.py \
  tests/test_behavior_ownership.py tests/test_ci_test_lanes.py
.venv/bin/python -m pytest -q \
  tests/test_behavior_ownership.py tests/test_ci_test_lanes.py
.venv/bin/coverage erase
.venv/bin/python -m pytest -q --cov=scripts.behavior_ownership \
  --cov-report=term tests/test_behavior_ownership.py
python3 ../scripts/check_markdown_links.py
python3 ../scripts/check_stale_workstream_wording.py
git diff --check origin/main...HEAD

Result Summary

124 focused tests passed.
90 behavior-ownership tests passed.
scripts.behavior_ownership coverage: 91 percent.
Ruff, Markdown links, stale wording, and diff integrity passed.

The exact implementation-head calibration completed 90 nodes in 18.12 seconds
and emitted 141,701 bytes, below both adoption limits.

Acceptance Criteria Proof

  • Exact head, callable lines, and collected nodes are bound and validated.
  • Collection and completion reuse run_test_lanes.py.
  • Candidate evidence cannot satisfy reviewed catalogue ownership.
  • The artifact is local, separate, non-catalogue, and never committed.
  • No workflow or required check invokes the command.
  • Runtime and artifact size remain below two minutes and 10 MiB.
  • Artifact fields exclude environment values, secrets, payloads, and logs.
  • Validation fails closed on stale, partial, skipped, deselected,
    digest-mismatched, overwritten, or timeout evidence.

Test Delta

Tests Added

  • Context artifact identity, digest, exact-head, callable, path, size, runtime,
    collection, completion, skip/deselect, coverage, and privacy behavior.
  • Minimal sanitized collection environment and timeout forwarding.

Tests Modified

  • Existing collection mocks accept the canonical optional timeout contract.

Tests Removed Or Skipped

  • None.

Internal Reviewer Results

Reviewed implementation SHA: 836865b1d84d06f534c0c45f551e72f335d810aa

Reviewed at: 2026-08-09

Reviewer run IDs: qual002_02_{arch,qa,security,ci,reuse,test_delta}

Reviewer Result Blocking Findings Notes
Senior engineering N/A - proportionate L1 review None Required focused tracks cover this bounded tool
QA/test PASS AFTER FIXES None Exact-head and fail-closed custody repaired
Security/auth PASS AFTER FIXES None Environment, path, digest, and Git custody reviewed
Product/ops N/A - no product behavior None Local engineering evidence only
Architecture PASS None Non-authoritative boundary preserved
CI integrity PASS None No workflow or gate weakening
Docs N/A - focused operational update None Links and stale wording pass
Reuse/dedup PASS None Canonical collector reused
Test delta PASS None Additive tests; none skipped or weakened

External Review

Source Status Notes
CodeRabbit PASS AFTER FIXES Valid earlier findings addressed; newest run rate-limited
GitHub checks Pending Exact-head checks are running

CI And Gate Integrity

  • No workflow weakening.
  • No lint/test/docstring gate weakening.
  • No coverage threshold weakening.
  • No package script weakening.
  • No unpinned new GitHub Action.
  • Checkout credential persistence disabled where checkout is used.

Remaining Risks

The artifact is candidate evidence only. It cannot establish reviewed ownership
and no authoritative catalogue consumer accepts it.

Follow-Up Work

Use this evidence during later bounded catalogue-population chunks. Promote a
public lane-runner API only if a second consumer needs the same custody path.

Human Review Focus

Please inspect the non-authoritative boundary, shared runtime budget,
secret-free subprocesses, exact-head callable custody, and lack of hosted-CI
changes.

Human Merge Ownership

  • I can explain what changed.
  • I can explain why it changed.
  • I know what could break.
  • I accept the remaining risks.
  • The user explicitly approved this specific PR for merge.

@coderabbitai

coderabbitai Bot commented Aug 9, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Added context-evidence generation and validation for behavior ownership. The tooling executes exact pytest nodes with coverage contexts, writes bounded non-authoritative artifacts, validates integrity and completeness, exposes CLI commands, and documents local operation.

Changes

Context evidence

Layer / File(s) Summary
Evidence contract and scope
.agent-loop/initiatives/WS-QUAL-002-behavior-ownership-catalogue/chunks/WS-QUAL-002-02-context-evidence.md, backend/scripts/behavior_ownership.py
Defines allowed and prohibited paths, artifact schema, custody rules, limits, rejection criteria, and verification commands.
Evidence generation flow
backend/scripts/behavior_ownership.py
Adds exact pytest collection and execution, per-test coverage contexts, callable line mapping, environment sanitization, bounded runtime, and exclusive artifact writing.
Evidence validation and test coverage
backend/scripts/behavior_ownership.py, backend/tests/test_behavior_ownership.py
Adds CLI validation and tests for identity, digest, freshness, completeness, coverage, unsafe paths, malformed data, size, and runtime limits.
Operational records and implementation status
.agent-loop/initiatives/WS-QUAL-002-behavior-ownership-catalogue/, docs/operations_backend_testing.md
Records implementation and review results and documents local artifact generation and validation.
Estimated code review effort: 4 (Complex) ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant build_context_evidence
  participant pytest
  participant Coverage
  participant Artifact
  CLI->>build_context_evidence: Provide target and test module
  build_context_evidence->>pytest: Collect and execute exact nodes
  pytest->>Coverage: Record per-test coverage contexts
  Coverage-->>build_context_evidence: Return covered lines
  build_context_evidence->>Artifact: Write digest-bound evidence
  Artifact-->>CLI: Return generation result
Loading

Possibly related PRs

Suggested reviewers: abiorh-claw

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.71% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely identifies the main change: adding local context evidence.
Description check ✅ Passed The description follows the trust-bundle template and documents scope, design, evidence, tests, risks, and review status.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/ws-qual-002-02-context-evidence

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.

@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: 2

🧹 Nitpick comments (1)
backend/tests/test_behavior_ownership.py (1)

879-950: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add fail-closed cases for the post-execution branches.

test_context_builder_fails_closed_before_execution stops at the collection phase. The following build_context_evidence guards have no test:

  • context_test_failure when the execution run returns a non-zero code.
  • incomplete_context_execution when collected or completed does not equal the collected nodes.
  • weakened_context_execution when a node is skipped or deselected.
  • missing_context_coverage when the coverage file is absent.
  • context_runtime_exceeded when the execution subprocess raises subprocess.TimeoutExpired.

These branches carry the evidence-integrity guarantees of the tool. The fake_run helper at Line 660 already provides the injection point for each case.

As per coding guidelines: "New or materially changed backend subsystems must maintain at least 90% test coverage".

Do you want me to generate the additional parameterized cases?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/tests/test_behavior_ownership.py` around lines 879 - 950, Add
parameterized fail-closed cases to
test_context_builder_fails_closed_before_execution, extending the fake_run
injection used by build_context_evidence to cover non-zero execution, incomplete
collected/completed nodes, skipped or deselected nodes, missing coverage output,
and subprocess.TimeoutExpired. Assert BehaviorOwnershipError with
context_test_failure, incomplete_context_execution, weakened_context_execution,
missing_context_coverage, and context_runtime_exceeded respectively, while
preserving the existing pre-execution cases.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/scripts/behavior_ownership.py`:
- Around line 649-663: The collection and execution phases must share one total
runtime budget, and both timeout paths must raise
BehaviorOwnershipError("context_runtime_exceeded"). In
backend/scripts/behavior_ownership.py lines 649-663, update
build_context_evidence to compute remaining time from started before each
subprocess.run, pass that remaining value as timeout, and catch
subprocess.TimeoutExpired for both collection and execution. In
docs/operations_backend_testing.md lines 236-238, retain the “runs over two
minutes” wording once the shared budget is implemented; otherwise revise it to
describe per-phase limits and the post-execution total check.
- Around line 557-566: The _coverage_lines_by_context flow should record a short
evidence-limitation note that fixture setup and teardown coverage contexts are
intentionally excluded because only |run contexts are processed. Add this note
alongside the existing missing_test_context handling without changing the
current context filtering or result behavior.

---

Nitpick comments:
In `@backend/tests/test_behavior_ownership.py`:
- Around line 879-950: Add parameterized fail-closed cases to
test_context_builder_fails_closed_before_execution, extending the fake_run
injection used by build_context_evidence to cover non-zero execution, incomplete
collected/completed nodes, skipped or deselected nodes, missing coverage output,
and subprocess.TimeoutExpired. Assert BehaviorOwnershipError with
context_test_failure, incomplete_context_execution, weakened_context_execution,
missing_context_coverage, and context_runtime_exceeded respectively, while
preserving the existing pre-execution cases.
🪄 Autofix

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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b41d300f-16d9-41f0-8c44-16cc994036cc

📥 Commits

Reviewing files that changed from the base of the PR and between b2e2c61 and 27a80f8.

📒 Files selected for processing (8)
  • .agent-loop/initiatives/WS-QUAL-002-behavior-ownership-catalogue/CHUNK_MAP.md
  • .agent-loop/initiatives/WS-QUAL-002-behavior-ownership-catalogue/STATUS.md
  • .agent-loop/initiatives/WS-QUAL-002-behavior-ownership-catalogue/chunks/WS-QUAL-002-02-context-evidence.md
  • .agent-loop/initiatives/WS-QUAL-002-behavior-ownership-catalogue/reviews/WS-QUAL-002-02-internal-review-evidence.md
  • .agent-loop/initiatives/WS-QUAL-002-behavior-ownership-catalogue/reviews/WS-QUAL-002-02-pr-trust-bundle.md
  • backend/scripts/behavior_ownership.py
  • backend/tests/test_behavior_ownership.py
  • docs/operations_backend_testing.md

Comment on lines +557 to +566
for context in sorted(data.measured_contexts()):
node = context.removesuffix("|run")
if node not in completed_nodes:
continue
data.set_query_contexts([f"^{re.escape(context)}$"])
lines = data.lines(str(target_path.resolve())) or []
result.setdefault(node, set()).update(lines)
data.set_query_contexts(None)
if set(result) != completed_nodes:
raise BehaviorOwnershipError("missing_test_context")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

pytest-cov cov-context=test coverage context name suffix run setup teardown

💡 Result:

When you use the --cov-context=test option with pytest-cov, the plugin records separate coverage data for individual tests during a single test suite execution [1][2]. This functionality leverages the context-switching capabilities of Coverage.py [1][3]. The context name recorded in the coverage database is constructed by combining the pytest test ID with the specific phase of execution [1][4]. These two components are separated by a pipe symbol (|) [1][5]: Context format: <test_id>| The phase can be one of three values: setup, run, or teardown [1][4]. Examples of these contexts include: - test_functions.py::test_addition|run [1][4] - test_fancy.py::test_parametrized[1-101]|setup [1][4] - test_oldschool.py::RegressionTests::test_error|run [1][4] For parameterized tests, the test ID includes the specific parameter values, and each set of parameters is recorded as a distinct context [1][5]. To visualize these contexts in an HTML coverage report, you must enable the show_contexts option in your.coveragerc file [1][5]: [html] show_contexts = True Once enabled, the HTML report will display an annotation on covered lines indicating the number of contexts that executed that line; clicking the annotation reveals the list of specific contexts [1][5].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the dependency specification and the relevant behavior helper.
printf 'Dependency references:\n'
rg -n "pytest-cov|cov-context" -S pyproject.toml backend backend/scripts || true

printf '\nbehavior_ownership relevant section:\n'
sed -n '530,575p' backend/scripts/behavior_ownership.py

printf '\nCall sites / usage of _coverage_lines_by_context:\n'
rg -n "_coverage_lines_by_context|BehaviorOwnershipError|missing_test_context" backend/scripts/behavior_ownership.py

Repository: Flow-Research/workstream

Length of output: 11234


Document fixture coverage as intentionally excluded.

pytest-cov==7.1.0 uses <test_id>|<phase> contexts where phase is setup, run, or teardown. _coverage_lines_by_context only accepts |run, so fixture setup teardown coverage lines are not included. If a node has coverage only in setup or teardown (for example |setup), missing_test_context is raised. Add a short evidence-limitation note recording this fixture-line exclusion.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/scripts/behavior_ownership.py` around lines 557 - 566, The
_coverage_lines_by_context flow should record a short evidence-limitation note
that fixture setup and teardown coverage contexts are intentionally excluded
because only |run contexts are processed. Add this note alongside the existing
missing_test_context handling without changing the current context filtering or
result behavior.

Source: Linters/SAST tools

Comment thread backend/scripts/behavior_ownership.py Outdated
@abiorh-claw
abiorh-claw self-requested a review August 9, 2026 10:53
@abiorh-claw
abiorh-claw merged commit 3565b3c into main Aug 9, 2026
11 checks passed
@abiorh-claw
abiorh-claw deleted the codex/ws-qual-002-02-context-evidence branch August 9, 2026 12:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants