Skip to content

Add exact LangChain policy middleware - #38

Merged
Deathcharge merged 2 commits into
mainfrom
codex/langchain-policy-middleware
Aug 2, 2026
Merged

Add exact LangChain policy middleware#38
Deathcharge merged 2 commits into
mainfrom
codex/langchain-policy-middleware

Conversation

@Deathcharge

Copy link
Copy Markdown
Owner

What changed

  • add optional exact-registry LangChain 1.3.14 sync/async tool-policy middleware
  • use native LangGraph interrupt/resume with fingerprint-bound approval evidence
  • enforce final raw arguments after outer middleware and re-evaluate fresh trusted facts on resume
  • add adversarial dependency-free tests plus real no-network approval, rejection, and mutation contracts
  • add a hashed optional dependency lock, dedicated CI lane, example, API/security/adoption documentation, and release guidance

Why

LangChain is a major agent runtime, but model-proposed tool metadata and a plain human-approved boolean are not sufficient authorization evidence. This adapter gives applications a public, reproducible integration that exact-matches the trusted tool registry and fails closed before a tool handler runs.

Impact and boundaries

The base package keeps zero runtime dependencies; LangChain imports only when the optional factory is called. Applications must place Samsarix last in the middleware list and retain responsibility for checkpointer protection, reviewer authentication, expiry, one-time resume, thread authorization, and non-transactional side effects.

Validation

  • python -m ruff check src tests integration_tests examples
  • python -m mypy src
  • python -m pytest — 531 passed, 95.72% branch-aware coverage
  • exact combined hash-locked development/LangChain installation — zero pin conflicts
  • real LangChain contract — 3 passed against langchain==1.3.14
  • no-network LangChain review/resume example
  • wheel and sdist build plus twine check
  • dependency-free built-wheel import with LangChain absent
  • built-wheel LangChain contract plus pip check
  • strict audit of requirements-langchain.lock — no known vulnerabilities
  • Bandit source scan — no medium/high findings

@coderabbitai

coderabbitai Bot commented Aug 2, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Deathcharge, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 46 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: d5185640-6f23-453a-9d45-4de427261841

📥 Commits

Reviewing files that changed from the base of the PR and between 18e39e3 and 91eaf77.

📒 Files selected for processing (4)
  • docs/LANGCHAIN.md
  • docs/PRODUCTIZATION.md
  • src/samsarix_ethics/langchain.py
  • tests/test_langchain.py

Summary by CodeRabbit

  • New Features

    • Added optional LangChain integration for policy-controlled tool execution.
    • Supports synchronous and asynchronous workflows, allow/deny decisions, human-review interruptions, exact-call approval, and fail-closed validation.
    • Added a no-network demonstration and public API support.
  • Documentation

    • Added setup, API, architecture, security, adoption, and release guidance for LangChain integrations.
  • Tests

    • Added comprehensive integration and contract coverage for approvals, rejections, argument handling, and runtime behavior.

Walkthrough

Added an optional LangChain and LangGraph policy adapter. It validates exact tool registries, enforces policy on final arguments, supports sync and async middleware, handles review interrupts, binds approvals to call fingerprints, and adds tests, documentation, examples, and CI contracts.

Changes

LangChain integration

Layer / File(s) Summary
Policy middleware and approval flow
src/samsarix_ethics/langchain.py
Added exact registry validation, request normalization, fingerprint generation, policy evaluation, review interrupts, approval verification, rejection messages, and sync/async middleware.
Public API and adapter contracts
src/samsarix_ethics/__init__.py, docs/API.md, docs/LANGCHAIN.md, docs/ARCHITECTURE.md, docs/ADOPTION.md, SECURITY.md, docs/PRODUCTIZATION.md
Exported the adapter API and documented setup, enforcement, approval binding, security boundaries, integration limits, and adoption evidence.
Mocked middleware validation
tests/test_langchain.py, tests/test_public_api.py
Added tests for validation, authorization, approval matching, provider behavior, malformed data, optional dependencies, public exports, and sync/async execution.
No-network agent contract and example
examples/langchain_policy_middleware_demo.py, integration_tests/test_langchain_sdk.py
Added a deterministic checkpointed agent example and exact-version contract tests for review, rejection, resumption, and transformed arguments.
Optional dependency and release validation
pyproject.toml, requirements-langchain.txt, .github/workflows/ci.yml, CONTRIBUTING.md, RELEASING.md, README.md, CHANGELOG.md, ROADMAP.md
Pinned LangChain 1.3.14, added installation and release guidance, and added a CI contract and attestation dependency.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Agent as LangChain agent
  participant Middleware as LangChainToolPolicy
  participant Policy as Policy engine
  participant Checkpointer as LangGraph checkpointer
  Agent->>Middleware: invoke tool with final arguments
  Middleware->>Policy: evaluate normalized call
  Policy-->>Middleware: review decision
  Middleware->>Checkpointer: persist interrupt and fingerprint
  Checkpointer-->>Agent: return review interrupt
  Agent->>Middleware: resume with approval evidence
  Middleware->>Policy: re-evaluate exact call
  Middleware-->>Agent: execute tool or return rejection
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 19.23% 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
Title check ✅ Passed The title clearly and concisely identifies the main change: adding exact LangChain policy middleware.
Description check ✅ Passed The description covers the change, rationale, security boundaries, compatibility, dependencies, validation, documentation, and release work.
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.
✨ 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/langchain-policy-middleware

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

🤖 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 `@docs/LANGCHAIN.md`:
- Around line 7-19: Update the LangChain example and its documented dependency
contract so the command using the langchain extra can run without undeclared
packages: either add the package providing PostgresSaver to the langchain extra,
or replace PostgresSaver with InMemorySaver and note that production deployments
require durable LangGraph checkpointing. Keep the create_agent example and
requirements-langchain.lock behavior consistent with the selected approach.

In `@src/samsarix_ethics/langchain.py`:
- Around line 230-242: Update _verify_response to encode both tool_call_id
operands and both tool_call_fingerprint operands to bytes before passing them to
hmac.compare_digest. Preserve the existing mismatch condition and ensure
non-ASCII identifiers raise the typed LangChainIntegrationError rather than a
TypeError.

In `@tests/test_langchain.py`:
- Around line 378-396: Update the invalid request coverage around
middleware.wrap_tool_call by pairing every malformed request with its specific
expected exception type instead of accepting the entire exception union.
Parameterize the cases or use request/exception tuples, and include the case
index or identifying input in parametrized test IDs so failures identify which
request regressed.
- Around line 431-449: Extend
test_async_middleware_authorizes_before_awaiting_handler after the
approved-review assertions with a rejected async review, asserting
awrap_tool_call returns the expected rejection ToolMessage and that calls
remains unchanged, proving the handler is not awaited.
- Around line 291-311: Replace the expected tool_call_fingerprint in the payload
assertion with a value computed directly from the relevant binding fingerprint
oracle, using the explicit expected tool-call inputs such as call ID, actor, and
request data. Do not derive the expectation through adapter.approval_for; keep
the assertion independent from _review_payload and _request.
🪄 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 6dfb32e1-43c7-4f19-90fc-af403c32c968

📥 Commits

Reviewing files that changed from the base of the PR and between 8e88fe5 and 18e39e3.

⛔ Files ignored due to path filters (1)
  • requirements-langchain.lock is excluded by !**/*.lock
📒 Files selected for processing (20)
  • .github/workflows/ci.yml
  • CHANGELOG.md
  • CONTRIBUTING.md
  • README.md
  • RELEASING.md
  • ROADMAP.md
  • SECURITY.md
  • docs/ADOPTION.md
  • docs/API.md
  • docs/ARCHITECTURE.md
  • docs/LANGCHAIN.md
  • docs/PRODUCTIZATION.md
  • examples/langchain_policy_middleware_demo.py
  • integration_tests/test_langchain_sdk.py
  • pyproject.toml
  • requirements-langchain.txt
  • src/samsarix_ethics/__init__.py
  • src/samsarix_ethics/langchain.py
  • tests/test_langchain.py
  • tests/test_public_api.py

Comment thread docs/LANGCHAIN.md
Comment thread src/samsarix_ethics/langchain.py
Comment thread tests/test_langchain.py
Comment thread tests/test_langchain.py Outdated
Comment thread tests/test_langchain.py
@Deathcharge
Deathcharge merged commit 47f59c9 into main Aug 2, 2026
9 checks passed
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.

1 participant