Skip to content
Merged
Show file tree
Hide file tree
Changes from 96 commits
Commits
Show all changes
100 commits
Select commit Hold shift + click to select a range
7e3b65e
test: reproduce embedding deployment selected for chat synthesis
seonghobae Aug 20, 2026
817eaec
fix: isolate chat discovery from embedding endpoints
seonghobae Aug 20, 2026
c765ce4
test: cover chat capability isolation defenses
seonghobae Aug 20, 2026
6c2d263
docs: record embedding-to-chat incident boundary
seonghobae Aug 20, 2026
35c7bef
docs: normalize incident references to APA 7
seonghobae Aug 20, 2026
f01da9f
test: reproduce stale embedding agent runtime selection
seonghobae Aug 20, 2026
266561c
fix: enforce chat capability at runtime boundaries
seonghobae Aug 20, 2026
4b50126
refactor: share chat capability classifier
seonghobae Aug 20, 2026
bc004d0
fix: activate runtime chat capability guards
seonghobae Aug 20, 2026
8bf5db1
test: tighten runtime guard coverage surface
seonghobae Aug 20, 2026
d33d1d5
test: cover runtime guard installation idempotence
seonghobae Aug 20, 2026
7ae2d4d
docs: record stale-agent runtime containment
seonghobae Aug 20, 2026
db7b209
fix: integrate chat capability checks explicitly
seonghobae Aug 20, 2026
7739ca0
docs: normalize capability incident formatting
seonghobae Aug 20, 2026
3571869
ci: repair chat capability guards with source integration
seonghobae Aug 20, 2026
14571a5
ci: remove completed one-shot repair workflow
seonghobae Aug 20, 2026
c41aedb
Merge protected main into chat capability isolation
seonghobae Aug 20, 2026
480d6ef
test: reproduce embedding deployment selected for chat synthesis
seonghobae Aug 20, 2026
54b4403
fix: isolate chat discovery from embedding endpoints
seonghobae Aug 20, 2026
e557400
test: cover chat capability isolation defenses
seonghobae Aug 20, 2026
be2f191
docs: record embedding-to-chat incident boundary
seonghobae Aug 20, 2026
c1fc1ca
docs: normalize incident references to APA 7
seonghobae Aug 20, 2026
392ce6c
test: reproduce stale embedding agent runtime selection
seonghobae Aug 20, 2026
99f5c41
fix: enforce chat capability at runtime boundaries
seonghobae Aug 20, 2026
136426d
refactor: share chat capability classifier
seonghobae Aug 20, 2026
050b514
fix: activate runtime chat capability guards
seonghobae Aug 20, 2026
fa980bc
test: tighten runtime guard coverage surface
seonghobae Aug 20, 2026
3998ad1
test: cover runtime guard installation idempotence
seonghobae Aug 20, 2026
feeac9e
docs: record stale-agent runtime containment
seonghobae Aug 20, 2026
668cf86
fix: integrate chat capability checks explicitly
seonghobae Aug 20, 2026
64b4e70
docs: normalize capability incident formatting
seonghobae Aug 20, 2026
543cdc7
ci: verify final chat capability guards
seonghobae Aug 20, 2026
95a2649
fix: complete explicit chat capability guards
seonghobae Aug 20, 2026
92efe38
refactor: keep ModelClient internal to orchestrator module
seonghobae Aug 20, 2026
df20c19
test: separate chat transport from general synthesis roles
seonghobae Aug 20, 2026
8e86976
ci: verify transport and synthesis capability separation
seonghobae Aug 20, 2026
4fb286f
chore: remove superseded transport-role repair workflow
seonghobae Aug 20, 2026
ea2ca8d
test: remove out-of-scope transport-role experiment
seonghobae Aug 20, 2026
a30c390
test: define honest provider-diverse discovery bootstrap
seonghobae Aug 20, 2026
6578dc5
test: bind NIM keys to one provider family
seonghobae Aug 20, 2026
3f15912
test: reproduce chat transport and role boundary conflation
seonghobae Aug 20, 2026
1ca4015
fix: rank unknown prices honestly and diversify bootstrap providers
seonghobae Aug 20, 2026
33185ad
ci: verify chat transport and role boundaries safely
seonghobae Aug 20, 2026
a5a3840
chore: remove branch-mutating repair workflow
seonghobae Aug 20, 2026
cabb1b0
test: remove discarded transport-role experiment
seonghobae Aug 20, 2026
3e75b1e
test: reproduce transport and agent-role capability conflation
seonghobae Aug 20, 2026
104ba94
ci: verify transport and ordinary-agent capability boundaries
seonghobae Aug 20, 2026
9984ad2
chore: remove branch-mutating capability workflow
seonghobae Aug 20, 2026
0ec353d
fix: separate chat transport from synthesis roles
seonghobae Aug 20, 2026
67b4341
test: reproduce non-chat passthrough and batch bypasses
seonghobae Aug 20, 2026
06da0c0
fix(discovery): wire provider-diverse bootstrap into CLI
seonghobae Aug 20, 2026
50b879b
ci: verify passthrough and batch chat capability guards
seonghobae Aug 20, 2026
a806e39
fix: replace chat capability repair workflow with reviewed source
seonghobae Aug 20, 2026
a424c9d
test: preserve unknown model identifiers without capability fabrication
seonghobae Aug 20, 2026
d71762d
fix: avoid inferring guard roles from unrelated suffixes
seonghobae Aug 20, 2026
f03d226
Merge protected main into chat capability isolation
seonghobae Aug 20, 2026
6bd4e0c
ci: verify final chat capability contract
seonghobae Aug 20, 2026
290838c
chore: remove completed capability repair workflow
seonghobae Aug 20, 2026
a063113
test(discovery): expose ambiguous price and duplicate pool gaps
seonghobae Aug 20, 2026
2539ad5
fix(discovery): reject untrusted duplicate price evidence
seonghobae Aug 20, 2026
a78d3a6
fix(discovery): keep duplicate evidence comparison total
seonghobae Aug 20, 2026
75e15af
test(discovery): expose overflow, corrupt-row, and currency gaps
seonghobae Aug 20, 2026
183e7a8
fix(discovery): fail closed on malformed and incomparable price evidence
seonghobae Aug 20, 2026
c01733b
fix(cost): reject corrupt persisted price rows
seonghobae Aug 20, 2026
669d97f
ci: finalize chat transport and role capability boundaries
seonghobae Aug 20, 2026
c08a8a6
ci: finalize endpoint transport and agent role separation
seonghobae Aug 20, 2026
70757f6
chore: remove superseded capability repair workflow v2
seonghobae Aug 20, 2026
8c06c74
chore: remove superseded capability repair workflow v3
seonghobae Aug 20, 2026
8885ef2
ci: finalize chat capability boundaries on exact branch
seonghobae Aug 20, 2026
d1e06d5
fix: close chat capability review gaps
seonghobae Aug 20, 2026
22a3270
test: make unknown-identifier regression directly runnable
seonghobae Aug 20, 2026
60be2e4
test: make transport-role regression directly runnable
seonghobae Aug 20, 2026
e91a108
test: cover legacy completions and direct execution
seonghobae Aug 20, 2026
a4aef39
test: make chat-capability regression directly runnable
seonghobae Aug 20, 2026
f13ee66
docs: register chat capability regression checks
seonghobae Aug 20, 2026
88fee97
fix: exclude shieldgemma from general chat roles
seonghobae Aug 20, 2026
0777e14
test(cost): reject persisted partial price rows
seonghobae Aug 20, 2026
386c9a0
fix: reject incomplete persisted price rows
seonghobae Aug 20, 2026
5d989c6
feat: add contextual review gateway bootstrap
seonghobae Aug 20, 2026
04761e4
fix: preserve priced discovery and review routing
seonghobae Aug 20, 2026
3a0e9f4
fix: isolate review gateway chat candidates
seonghobae Aug 20, 2026
84a8999
fix: keep partial discovery prices unknown
seonghobae Aug 20, 2026
9041e78
fix: resolve review gateway auth through KV
seonghobae Aug 20, 2026
0071751
fix: keep auth outside provider bootstrap gate
seonghobae Aug 20, 2026
6c10b49
Merge embedding capability isolation into discovery stack
seonghobae Aug 20, 2026
6b603ef
docs: ground provider-diverse routing in research
seonghobae Aug 20, 2026
172a890
test: cover model discovery rejection paths
seonghobae Aug 21, 2026
bfdcdd0
fix: reject gte embedding models from chat roles
seonghobae Aug 21, 2026
d3a27db
fix: keep foreign currency prices out of ranking
seonghobae Aug 21, 2026
8d31fa5
merge: preserve provider-diverse gateway discovery
seonghobae Aug 21, 2026
17a5e42
Merge main into contextual review gateway
seonghobae Aug 24, 2026
e2ac971
Merge remote-tracking branch 'origin/main' into local-790
seonghobae Aug 25, 2026
9f848a8
Merge remote-tracking branch 'origin/main' into feat-opencode-review-…
seonghobae Aug 25, 2026
c649cdb
fix: preserve non-chat capability routing and price integrity
seonghobae Aug 25, 2026
b826099
Merge remote-tracking branch 'origin/main' into codex/pr790-review
seonghobae Aug 25, 2026
1c3b52a
Merge branch 'feat/opencode-review-gateway' of https://github.com/Con…
seonghobae Aug 25, 2026
ee216d0
fix: keep one canonical price parser
seonghobae Aug 25, 2026
26c8f31
Merge remote-tracking branch 'origin/main' into codex/pr790-review
seonghobae Aug 25, 2026
13bc939
docs: list chat capability check
seonghobae Aug 25, 2026
6acd0fb
fix: validate review gateway agent limit at CLI
seonghobae Aug 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,7 @@ python tests/test_chat_transport_role_separation.py
python tests/test_chat_capability_unknown_identifiers.py
python tests/test_chat_passthrough_capability_isolation.py
python tests/test_discovery_bootstrap_selection.py
python tests/test_review_gateway.py
Comment thread
seonghobae marked this conversation as resolved.
Resolved
python tests/test_provider_bootstrap.py
python tests/test_provider_bootstrap_secret_normalization.py
python tests/test_provider_catalog_bootstrap.py
Expand Down
21 changes: 21 additions & 0 deletions contextual_orchestrator/cost_ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,27 @@ def _parse_price_entry(
completion_price = _decimal_safe_price(raw["completion_price_per_1k"])
if prompt_price is None or completion_price is None:
return None
if not isinstance(raw, dict):
return None
try:
if (
"prompt_price_per_1k" not in raw
or "completion_price_per_1k" not in raw
or isinstance(raw["prompt_price_per_1k"], bool)
or isinstance(raw["completion_price_per_1k"], bool)
):
return None
prompt_price = float(raw["prompt_price_per_1k"])
completion_price = float(raw["completion_price_per_1k"])
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
except (OverflowError, TypeError, ValueError):
return None
if (
not math.isfinite(prompt_price)
or not math.isfinite(completion_price)
or prompt_price < 0
or completion_price < 0
):
return None
Comment thread
seonghobae marked this conversation as resolved.
Resolved
return PriceEntry(
provider_name=raw.get("provider_name", provider),
model_name=raw.get("model_name", model),
Expand Down
145 changes: 145 additions & 0 deletions contextual_orchestrator/review_gateway.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
"""Bootstrap a local authenticated gateway for trusted CI model reviews.

The five provider keys arrive from a deployment environment only as bootstrap
transport. They are immediately registered in the process-local KV, after
which model discovery and every provider request use the normal credential
registry path. This keeps the review sidecar useful without pretending that a
short-lived runner has a durable production credential store.
"""

from __future__ import annotations

import argparse
import os
from dataclasses import replace
from typing import Mapping

from .credentials import NotConfigured, get_credential, register_credential
from .cost_ledger import PriceBook
from .chat_capability import is_general_chat_agent_model_id
from .kv_config import InMemoryConfigStore
from .model_discovery import (
agent_from_discovered,
discover_all_models,
refresh_price_book,
select_bootstrap_discovered_agents,
)
from .orchestrator import ModelClient, TaskOrchestrator
from .server import SecurityConfig, serve

REVIEW_CREDENTIAL_NAMES: tuple[str, ...] = (
"BYTEZ_API_KEY",
"NVIDIA_NIM_API_KEY",
"NVIDIA_NIM_API_KEY_SUB",
"OPENROUTER_API_KEY",
"OPENAI_API_KEY",
)
DEFAULT_REVIEW_AGENT_LIMIT = 12
REVIEW_AUTH_CREDENTIAL_NAME = "CONTEXTUAL_ORCHESTRATOR_TOKEN"


def register_review_credentials(environment: Mapping[str, str]) -> tuple[str, ...]:
"""Register non-empty CI provider and gateway credentials in the KV.

``environment`` is bootstrap input only. The returned names contain no
secret values and are suitable for diagnostics or tests.
"""
registered: list[str] = []
for name in REVIEW_CREDENTIAL_NAMES:
value = environment.get(name, "").strip()
if value:
register_credential(name, value)
registered.append(name)
auth_value = environment.get(REVIEW_AUTH_CREDENTIAL_NAME, "").strip()
if auth_value:
register_credential(REVIEW_AUTH_CREDENTIAL_NAME, auth_value)
registered.append(REVIEW_AUTH_CREDENTIAL_NAME)
return tuple(registered)


def build_review_orchestrator(
environment: Mapping[str, str] | None = None,
*,
max_agents: int = DEFAULT_REVIEW_AGENT_LIMIT,
) -> TaskOrchestrator:
"""Build an enabled, cost-ranked orchestrator from discovered providers.

A missing provider key is allowed so the sidecar can use an available
subset. Starting with no provider key or no discovered model fails closed
rather than silently falling back to a mock or fabricated model.
"""
if type(max_agents) is not int or max_agents < 1:
raise ValueError("max_agents must be a positive integer")
source_environment = os.environ if environment is None else environment
registered = register_review_credentials(source_environment)
if not any(name in registered for name in REVIEW_CREDENTIAL_NAMES):
raise NotConfigured("review gateway requires at least one provider credential")

discovered, errors = discover_all_models()
if not discovered:
providers = ", ".join(sorted({error.provider_name for error in errors}))
detail = f"; failed providers: {providers}" if providers else ""
raise NotConfigured(f"review gateway discovered no provider models{detail}")

chat_discovered = [model for model in discovered if is_general_chat_agent_model_id(model.model_id)]
if not chat_discovered:
raise NotConfigured("review gateway discovered no general chat models")
price_book = PriceBook(InMemoryConfigStore())
refresh_price_book(chat_discovered, price_book)
selected = select_bootstrap_discovered_agents(chat_discovered, price_book, max_agents)
if not selected:
raise NotConfigured("review gateway selected no provider models")

agents = [
replace(
agent_from_discovered(model, priority=index),
disabled=False,
# The discovery catalog does not advertise reasoning, coding, or
# verification support. ``review`` is the gateway purpose, not a
# fabricated provider capability.
tags=("review",),
# TaskOrchestrator ranks larger priorities first. Discovery is
# already cheapest-first, so preserve that order for routing.
priority=-index,
)
Comment thread
seonghobae marked this conversation as resolved.
Resolved
for index, model in enumerate(selected)
Comment thread
seonghobae marked this conversation as resolved.
Resolved
Comment thread
seonghobae marked this conversation as resolved.
Resolved
Comment thread
seonghobae marked this conversation as resolved.
Resolved
]
Comment thread
seonghobae marked this conversation as resolved.
Resolved
Comment thread
seonghobae marked this conversation as resolved.
Resolved
return TaskOrchestrator(
agents,
client=ModelClient(max_output_tokens=32768),
)


def _build_parser() -> argparse.ArgumentParser:
"""Create the sidecar CLI parser with loopback-safe defaults."""
parser = argparse.ArgumentParser(description="Run the contextual review gateway sidecar.")
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=18080)
parser.add_argument("--max-agents", type=int, default=DEFAULT_REVIEW_AGENT_LIMIT)
parser.add_argument(
"--auth-token",
default="",
help="Explicit local bearer token; otherwise resolve --auth-token-key from the KV.",
)
parser.add_argument("--auth-token-key", default=REVIEW_AUTH_CREDENTIAL_NAME)
return parser


def main() -> None:
"""Discover providers and serve the authenticated OpenAI-compatible sidecar."""
args = _build_parser().parse_args()
register_review_credentials(os.environ)
auth_token = args.auth_token or get_credential(args.auth_token_key)
if not auth_token:
raise SystemExit(f"KV credential {args.auth_token_key!r} or --auth-token is required")
orchestrator = build_review_orchestrator(max_agents=args.max_agents)
Comment thread
seonghobae marked this conversation as resolved.
Resolved
serve(
orchestrator,
host=args.host,
port=args.port,
security=SecurityConfig(auth_token=auth_token),
)
Comment thread
seonghobae marked this conversation as resolved.
Resolved


if __name__ == "__main__": # pragma: no cover
main()
1 change: 0 additions & 1 deletion docs/doctoring/request-framing-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,3 @@ negative-length raw sockets, chunked raw sockets, and a short declared body.

Internet Engineering Task Force. (2022). *HTTP/1.1* (RFC 9112). RFC Editor.
https://www.rfc-editor.org/rfc/rfc9112.html

10 changes: 4 additions & 6 deletions docs/kv-credentials.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,12 +234,10 @@ uses (`TaskOrchestrator.sync_discovered_agents`, an idempotent upsert of
added **disabled**, so a newly found model never starts serving traffic
before an operator opts it in.

Cost-based auto-optimization reuses the existing price-table selector rather
than adding a new one: `model_discovery.refresh_price_book` writes any
provider-reported per-token pricing into `PriceBook`, and
`model_discovery.select_cheapest_discovered_agent` calls
`batch_routing.cheapest_upstream` to pick the lowest-cost candidate among
discovered models for a representative request shape.
Cost-based auto-optimization uses `model_discovery.refresh_price_book` to write
provider-reported per-token pricing into `PriceBook`. Discovery selectors rank
complete, valid price evidence first and keep unknown-priced candidates as a
deterministic fallback.

## Gateway direction

Expand Down
73 changes: 73 additions & 0 deletions tests/test_chat_capability.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""Boundary tests for model-family chat and orchestration-role capability gates."""

from __future__ import annotations

import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from contextual_orchestrator.chat_capability import ( # noqa: E402
is_chat_compatible_model_id,
is_general_chat_agent_model_id,
)


@pytest.mark.parametrize(
"model_id",
(
"bge-small-en",
"clip-vit",
"dall-e-3",
"e5-large",
"embed-model",
"embedding-model",
"embeddings-v2",
"gte-base",
"image-model",
"images-v2",
"moderation-latest",
"realtime-preview",
"rerank-v3",
"reranker-large",
"siglip-base",
"sora-video",
"speech-model",
"transcribe-large",
"transcription-v2",
"tts-1",
"whisper-1",
),
)
def test_endpoint_only_model_families_cannot_use_chat_transport(model_id: str) -> None:
"""Reject every explicitly known endpoint-only model family."""
assert is_chat_compatible_model_id(model_id) is False
assert is_general_chat_agent_model_id(model_id) is False


@pytest.mark.parametrize("model_id", ("embedder-v2", "moderator-v1", "reranking-v1", "transcriber-v1"))
def test_endpoint_prefixes_reject_unlisted_model_variants(model_id: str) -> None:
"""Reject future-looking family variants without matching exact tokens."""
assert is_chat_compatible_model_id(model_id) is False


def test_empty_and_non_string_identifiers_fail_closed() -> None:
"""Unknown identifier shapes never become eligible by accident."""
assert is_chat_compatible_model_id("") is False
assert is_chat_compatible_model_id(None) is False # type: ignore[arg-type]
assert is_general_chat_agent_model_id("") is False


@pytest.mark.parametrize("model_id", ("safety-classifier", "guard-model", "shieldgemma-2b", "nemo_guard_v2"))
def test_transport_compatible_policy_models_stay_out_of_general_agent_roles(model_id: str) -> None:
"""Safety and guard models may use chat transport but are not thinkers."""
assert is_chat_compatible_model_id(model_id) is True
assert is_general_chat_agent_model_id(model_id) is False


def test_normal_chat_identifier_remains_eligible() -> None:
"""A normal provider model remains eligible for both ordinary gates."""
assert is_chat_compatible_model_id("provider/gpt-5.5") is True
assert is_general_chat_agent_model_id("provider/gpt-5.5") is True
12 changes: 12 additions & 0 deletions tests/test_discovery_bootstrap_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,18 @@ def test_persisted_price_row_missing_one_component_remains_unknown() -> None:
assert price_book.get_price("partial_vendor", "partial-model") is None


def test_persisted_boolean_price_row_remains_unknown() -> None:
"""Do not coerce corrupt KV booleans into zero-cost price evidence."""
store = InMemoryConfigStore()
store.set(
"llm_price_entries",
"broken_vendor:broken-model",
{"prompt_price_per_1k": False, "completion_price_per_1k": False},
)

assert PriceBook(store).get_price("broken_vendor", "broken-model") is None


def test_invalid_catalog_prices_are_unknown_not_trusted_cost_evidence() -> None:
"""Reject negative, non-finite, and boolean provider price values."""
assert model_discovery._price_per_1k("-0.000001") is None
Expand Down
Loading
Loading