claude-verified-agent 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,208 @@
1
+ Metadata-Version: 2.4
2
+ Name: claude-verified-agent
3
+ Version: 0.2.0
4
+ Summary: End-to-end verified agent demo: inter-agent memory (agent-context-bridge) + cited-or-refused RAG (cited-rag) + CI safety gates (llm-eval-ci). Stdlib only, offline, no API key.
5
+ Author-email: shenn667 <lehdev@yandex.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/shenn667/claude-verified-agent
8
+ Keywords: agents,rag,citations,evals,offline,claude
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Requires-Python: >=3.12
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
19
+ Provides-Extra: pillars
20
+ Requires-Dist: agent-context-bridge>=0.4.0; extra == "pillars"
21
+ Requires-Dist: cited-rag>=0.2.0; extra == "pillars"
22
+ Requires-Dist: llm-eval-ci>=0.2.0; extra == "pillars"
23
+ Dynamic: license-file
24
+
25
+ # claude-verified-agent
26
+
27
+ [![CI](https://github.com/shenn667/claude-verified-agent/actions/workflows/ci.yml/badge.svg)](https://github.com/shenn667/claude-verified-agent/actions/workflows/ci.yml)
28
+ [![PyPI](https://img.shields.io/pypi/v/claude-verified-agent.svg)](https://pypi.org/project/claude-verified-agent/)
29
+ [![Python 3.12+](https://img.shields.io/badge/python-3.12%2B-blue.svg)](https://www.python.org/downloads/)
30
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
31
+ [![offline](https://img.shields.io/badge/offline-stdlib--only-lightgrey.svg)](https://github.com/shenn667/claude-verified-agent)
32
+
33
+ **An end-to-end verified agent: every answer is cited or refused, every
34
+ delivery passes safety gates, every run is CI-blocked on regression.**
35
+
36
+ No hallucination by design, no PII/injection leak by gate, no silent
37
+ regression by suite. Stdlib-only core, fully offline, no API key.
38
+
39
+ ```bash
40
+ pip install -e .
41
+ make demo # 1 command: cited answer + refusal + gate verdicts
42
+ make banking-demo # banking & SecOps vertical: 4 asserted offline cases
43
+ make test # 48 contract tests (pytest, offline)
44
+ make gates # 4 llm-eval-ci suites, exit != 0 blocks CI
45
+ ```
46
+
47
+ ## Architecture
48
+
49
+ ```text
50
+ question
51
+ |
52
+ v
53
+ [1] record-contexte (agent-context-bridge)
54
+ | acb record question + answer | acb search past context
55
+ v
56
+ [2] ask cite (cited-rag)
57
+ | BM25 + TF-IDF -> RRF -> verbatim sentences + [file:L1-L2]
58
+ | max_score < 0.35 or fidelity < 0.5 -> "Insufficient evidence"
59
+ v
60
+ [3] gate (llm-eval-ci)
61
+ | no_pii_leak + no_injection_obey over the produced answer
62
+ | red gate -> refusal (raw text never delivered)
63
+ v
64
+ cited answer | refusal (no-evidence / safety-gate)
65
+ ```
66
+
67
+ Each stage prefers its pillar implementation and degrades to a compact
68
+ stdlib equivalent when the pillar is not installed (`backends` field of
69
+ every answer states which implementation served each stage, so the demo
70
+ output is auditable). Set `CVA_FORCE_FALLBACK=1` to exercise the portable
71
+ path — the 48 tests pass identically on both paths.
72
+
73
+ ## The 3 pillars (used, not rewritten)
74
+
75
+ | Stage | Pillar repo | How it is used here |
76
+ |-------|--------------|---------------------|
77
+ | Inter-agent memory | [agent-context-bridge](https://github.com/shenn667/agent-context-bridge) | `MemoryStore` + `ContextRecord` + `search_records`: every question and every verdict is recorded (`acb record` semantics) and past context is searched before retrieval |
78
+ | Cited RAG | [cited-rag](https://github.com/shenn667/cited-rag) | `build_index_data` + `Retriever.search` + `generate_answer`: hybrid retrieval, extractive verbatim answers with exact `[file:L1-L2]` citations, `Insufficient evidence` refusal with zero citations |
79
+ | CI gates | [llm-eval-ci](https://github.com/shenn667/llm-eval-ci) | `check_no_pii_leak` + `check_no_injection_obey` gate every answer; `evals/*.json` suites run via `llm-eval run` with blocking exit codes |
80
+
81
+ ## Eval results (reproduce with `make gates` + `make test`)
82
+
83
+ `llm-eval run` on the bundled suites (deterministic, offline):
84
+
85
+ | Suite | Cases | Result |
86
+ |-------|-------|--------|
87
+ | `evals/non_regression.json` | cited answers (contains + citation regex + PII-free), off-corpus refusal | 3/3 passed, exit 0 |
88
+ | `evals/schema.json` | JSON payload contract (cited + refused shapes, budgets) | 2/2 passed, exit 0 |
89
+ | `evals/tripwires.json` | PII request refused, injection-laced prompt refused | 2/2 passed, exit 0 |
90
+ | `evals/banking_compliance.json` | banking cited answer, off-corpus refusal, PII gate, injection gate, masked memory | 5/5 passed, exit 0 |
91
+
92
+ `pytest`: **48/48 passed** on the pillar path and **48/48 passed** with
93
+ `CVA_FORCE_FALLBACK=1` (portable stdlib path): exact verbatim citations,
94
+ refusal with zero citations, gate blocks PII/injection strings,
95
+ injection-laced questions never obeyed, answer determinism, JSON contract,
96
+ memory records, backend auditability. The count is 14 core contract tests
97
+ (`tests/test_verified_agent.py`) plus 34 banking-compliance tests
98
+ (`tests/test_banking_compliance.py`, 16 cases × 2 backends).
99
+
100
+ The red path (a leaked PII string or an obeyed injection **fails** the
101
+ gate, exit 1) is proven in `pytest`, not in the suites: the suites must
102
+ stay green or CI blocks.
103
+
104
+ ## Banking & SecOps Compliance Use Case (B2B)
105
+
106
+ A regulated-banking vertical built on the same verified pipeline, shipped
107
+ under `examples/banking-compliance/`. The corpus is **100% synthetic** —
108
+ four bilingual (FR + EN) markdown files for the fictional *Banque Exemple
109
+ SA / Example Bank SA*. Every file opens with a `SYNTHETIC` header; there is
110
+ **zero real enterprise data**, no real PII, and no actual regulatory text
111
+ (the BCEAO-inspired audit policy is explicitly labelled synthetic).
112
+
113
+ Topics: PCI DSS controls (AES-256 at rest, TLS 1.2+ in transit, PAN
114
+ masking first-6/last-4, HSM key storage, 90-day key rotation), BCEAO-inspired
115
+ audit logs (10-year retention, WORM integrity, NTP sync, maker/checker),
116
+ a SecOps ransomware playbook (VLAN isolation, east-west blocking, forensic
117
+ image before rebuild, RSSI/CISO escalation within 1 hour, 72-hour regulator
118
+ notification), and IAM privileged access (mandatory bastion, phishing-resistant
119
+ MFA, quarterly review, JIT elevation, session recording) ending in an
120
+ assistant-secrecy section that serves as the injection tripwire target.
121
+
122
+ The offline demo (`demo_banking.py`, tempfile workspace, no API key) runs
123
+ four cases with hard asserts (exit 1 on any failure):
124
+
125
+ | Case | Question theme | Expected outcome |
126
+ |------|----------------|------------------|
127
+ | C1 | PCI DSS key-rotation frequency (in-corpus) | cited verbatim answer, gate PASS |
128
+ | C2 | off-corpus trading query | `no-evidence` refusal, zero citations |
129
+ | C3 | IBAN + PAN + email probe | gate blocks `no_pii_leak`; no raw value in answer or workspace; memory masked |
130
+ | C4 | injection-laced IAM question | `safety-gate` refusal via `no_injection_obey` |
131
+
132
+ ```bash
133
+ make banking-demo # 4 asserted cases, offline, exit 0 on success
134
+ make gates # 4 blocking eval suites (incl. banking_compliance)
135
+ make test # 48 contract tests, both backends
136
+ ```
137
+
138
+ **PAN gate extension.** The pillar PII patterns are frozen and carry no
139
+ card-number rule, so the agent-side gate (`verified_agent.gates`) now
140
+ supplements **both** backends with Luhn-validated PAN detection
141
+ (`_luhn_ok` + `_pan_candidates`): 13-19 digit runs (separators
142
+ stripped) that pass the Luhn checksum are flagged as `pan` under
143
+ `no_pii_leak` and masked. Detection and masking share one overlap-safe
144
+ span collector (`_collect_spans`), so a greedy IBAN match can no longer
145
+ swallow an adjacent PAN and a phone sub-pattern cannot leave an IBAN
146
+ fragment in the masked output (no raw value or digit fragment survives).
147
+ `4111111111111111` is detected; `4111111111111112` (bad Luhn) is not.
148
+ The demo and the 34 banking tests
149
+ pass identically on the native-pillar path and with `CVA_FORCE_FALLBACK=1`.
150
+
151
+ ## Quickstart (3 commands)
152
+
153
+ ```bash
154
+ pip install -e .
155
+ make demo # offline demo, no key
156
+ make gates # 4 blocking eval suites
157
+ ```
158
+
159
+ CI (`.github/workflows/ci.yml`): job `pytest` + job `gates` (one step per
160
+ suite, `llm-eval run` when installed, stdlib fallback runner otherwise).
161
+ Any red gate fails the build.
162
+
163
+ ## Watchdog wrapper (autonomous, stdlib)
164
+
165
+ The repo includes an autonomous watchdog wrapper: `scripts/run_watchdog.py`
166
+ (stdlib-only, Popen + start_new_session + 2 reader threads + 1s loop +
167
+ 900s timeout + 300s stall detection + process-group kill, bounded output).
168
+
169
+ ```bash
170
+ python3 scripts/run_watchdog.py --target demo --json
171
+ python3 scripts/run_watchdog.py --target gates --json --timeout 900 --stall-timeout 300
172
+ python3 scripts/run_watchdog.py --target all --json
173
+ ```
174
+
175
+ With `--json`, the wrapper emits an additive JSON summary with at least:
176
+ `job_id`/`run_id`, `status` (`DONE|FAILED|TIMEOUT|STALLED`), `exit_code`,
177
+ `started_at`, `finished_at`, `duration_s`, `reason`, `tail`.
178
+
179
+ Makefile: the `demo-wd` and `gates-wd` targets go through the watchdog;
180
+ `demo` and `gates` stay unchanged for compatibility.
181
+
182
+ ## Verification (3 trials)
183
+
184
+ `scripts/verify_3_trials.py` runs three independent trials (byte-compile,
185
+ `pytest -q`, `make gates`) with the current interpreter (`sys.executable`).
186
+ The verdict is `PASS 3/3` only if every trial passes:
187
+
188
+ ```bash
189
+ python3 scripts/verify_3_trials.py
190
+ ```
191
+
192
+ ## Action gate / status JSON
193
+
194
+ - `verified_agent.gates.run_suite_file` applies action-gate semantics: `0` allow, `2` deny (red gate / failed checks), `1` ask / fail-closed (usage, env, invalid, parse, unknown). On a red gate, no raw output is echoed; only the id, failed checks, and safe/masked info.
195
+ - `VerifiedAgent.ask()` adds additive top-level fields `scores`, `rejected`, `backtracks_count` without breaking the existing `backends` field (`memory`, `rag`, `gate`).
196
+ - `emit_summary(result, json_mode=False)` and `print_status(result, json_mode=False)` are exposed; `demo/demo.py --json` uses this path.
197
+
198
+ ## Links
199
+
200
+ - Dataset (Hugging Face): https://huggingface.co/datasets/SHENNN667/cited-rag-golden-52
201
+ (published under namespace `SHENNN667` — no write rights on `shenn667`;
202
+ the lowercase `shenn667/...` URL returns 401, do not use it as the main link)
203
+ - Eval page: https://shenn667.github.io/eval/ (live, deployed from
204
+ `shenn667/shenn667.github.io` main branch)
205
+
206
+ ## License
207
+
208
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,9 @@
1
+ claude_verified_agent-0.2.0.dist-info/licenses/LICENSE,sha256=XKTrANYTBSuL8H4K0bs2OE5lXwz-0lwXAHmw3HIPVSw,1065
2
+ verified_agent/__init__.py,sha256=o8WqR0wRVcT5-GQ3Vx8qdkH2Ze8qb2cn9Kom3uV3fgs,236
3
+ verified_agent/agent.py,sha256=zcdazmj3FDEMPOSoYRTEwNrCHaQ6Z34ti3I-FSnTsw8,19075
4
+ verified_agent/gates.py,sha256=9YqNp89olYC1lhhussV-5YJck6mL29IAfB709lHpB70,18423
5
+ verified_agent/memory.py,sha256=rT-IBvWk3r9_eNlLeSqiNSbGocU2lLHHYIzEZj9WmaQ,6924
6
+ claude_verified_agent-0.2.0.dist-info/METADATA,sha256=rg3GgeixfXj69E1kfQhc1LW6ZqDA49OqARYajbtgNcA,10400
7
+ claude_verified_agent-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ claude_verified_agent-0.2.0.dist-info/top_level.txt,sha256=34TY6-vA7au1qb80TlPrsj6rOwqm1GwLC-hkJxuFP2Q,15
9
+ claude_verified_agent-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 shenn667
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ verified_agent
@@ -0,0 +1,6 @@
1
+ """claude-verified-agent: end-to-end verified agent over 3 local pillars."""
2
+
3
+ __version__ = "0.2.0"
4
+
5
+ from .agent import AgentConfig, VerifiedAgent, ask, emit_summary, print_status # noqa: F401
6
+ from .gates import run_gate # noqa: F401
@@ -0,0 +1,410 @@
1
+ """Verified agent: memory -> cited RAG -> safety gate -> answer-or-refusal.
2
+
3
+ Pipeline (one question, fully offline, stdlib + 3 local pillars):
4
+
5
+ 1. **record-contexte** (agent-context-bridge): the question is recorded as a
6
+ shared memory item and past memory is searched for context.
7
+ 2. **ask cité** (cited-rag): hybrid BM25+TF-IDF retrieval, extractive answer
8
+ where every sentence is verbatim + cited ``[file:L1-L2]``, refusal with
9
+ ``Insufficient evidence`` when ``max_score < min_score``.
10
+ 3. **gate** (llm-eval-ci): ``no_pii_leak`` + ``no_injection_obey`` tripwires
11
+ over the produced answer. Red gate -> refusal, never the raw text.
12
+ 4. **réponse ou refus**: cited answer, or refusal (no-evidence / gate-blocked).
13
+
14
+ Each stage prefers its pillar implementation and falls back to a compact
15
+ stdlib equivalent when the pillar is not installed, so ``pytest`` and the
16
+ demo run identically everywhere. The ``backends`` field of every answer
17
+ states which implementation served each stage (auditability).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import re
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+ from typing import Any, Dict, List, Tuple
27
+
28
+ from . import gates
29
+ from .memory import AgentMemory
30
+
31
+ REFUSAL_NO_EVIDENCE = ("Insufficient evidence — I can't help answer "
32
+ "from the indexed corpus.")
33
+ REFUSAL_GATE = ("Refused by safety gate (PII/injection tripwire) — "
34
+ "I can't help with that.")
35
+ CITATION_RE = re.compile(r"\[([^[\]]+):L(\d+)-L(\d+)\]")
36
+
37
+ _STOPWORDS = frozenset(
38
+ "a an the and or but of to in on for with is are was were be been "
39
+ "what how why when where which who does do did can could should would "
40
+ "it its this that these those there here from as at by nous les des du "
41
+ "une un et ou est sont dans pour avec que qui quoi comment".split())
42
+
43
+
44
+ def _tokens(text: str) -> List[str]:
45
+ toks = re.findall(r"[a-z0-9]+", text.lower())
46
+ return [t for t in toks if t not in _STOPWORDS]
47
+
48
+
49
+ @dataclass
50
+ class AgentConfig:
51
+ corpus_dir: str | Path
52
+ workspace_dir: str | Path
53
+ k: int = 5
54
+ min_score: float = 0.35
55
+ agent_name: str = "verified-agent"
56
+
57
+
58
+ class VerifiedAgent:
59
+ """One-shot verified Q&A over a local markdown corpus."""
60
+
61
+ def __init__(self, config: AgentConfig):
62
+ self.config = config
63
+ self.memory = AgentMemory(config.workspace_dir)
64
+ self.backends = {"memory": self.memory.backend,
65
+ "rag": "unavailable", "gate": "unavailable"}
66
+ self._rag: Any = None
67
+ self._fallback_chunks: List[Dict[str, Any]] = []
68
+ self._init_rag()
69
+
70
+ # -- RAG init ------------------------------------------------------
71
+ def _init_rag(self) -> None:
72
+ import os as _os
73
+ if _os.environ.get("CVA_FORCE_FALLBACK") != "1":
74
+ try:
75
+ from cited_rag.index import build_index_data # type: ignore
76
+ from cited_rag.retrieval import Retriever # type: ignore
77
+ data, _warnings = build_index_data(str(self.config.corpus_dir))
78
+ self._rag = Retriever(data)
79
+ self.backends["rag"] = "cited-rag"
80
+ return
81
+ except Exception:
82
+ pass
83
+ self._fallback_chunks = self._build_fallback_chunks(
84
+ Path(self.config.corpus_dir))
85
+ self._rag = None
86
+ self.backends["rag"] = "stdlib-fallback"
87
+
88
+ @staticmethod
89
+ def _build_fallback_chunks(root: Path) -> List[Dict[str, Any]]:
90
+ chunks: List[Dict[str, Any]] = []
91
+ if not root.is_dir():
92
+ return chunks
93
+ for path in sorted(root.rglob("*")):
94
+ if not path.is_file() or path.suffix.lower() not in (".md", ".txt"):
95
+ continue
96
+ try:
97
+ rel = str(path.relative_to(root))
98
+ lines = path.read_text(encoding="utf-8",
99
+ errors="replace").splitlines()
100
+ except OSError:
101
+ continue
102
+ step, width, start = 30, 40, 0
103
+ while start < len(lines):
104
+ end = min(start + width, len(lines))
105
+ text = "\n".join(lines[start:end])
106
+ if text.strip():
107
+ chunks.append({"file": rel, "start_line": start + 1,
108
+ "end_line": end, "text": text})
109
+ if end >= len(lines):
110
+ break
111
+ start += step
112
+ return chunks
113
+
114
+ # -- retrieval ------------------------------------------------------
115
+ def _retrieve(self, question: str) -> Tuple[List[Dict[str, Any]], float]:
116
+ """Return (hits, max_score). Hit: {chunk, score}."""
117
+ if self._rag is not None:
118
+ hits = self._rag.search(question, k=self.config.k)
119
+ max_score = max((h["score"] for h in hits), default=0.0)
120
+ return hits, max_score
121
+ qtoks = _tokens(question)
122
+ if not qtoks or not self._fallback_chunks:
123
+ return [], 0.0
124
+ scored = []
125
+ for chunk in self._fallback_chunks:
126
+ ctoks = set(_tokens(chunk["text"]))
127
+ matched = sum(1 for t in set(qtoks) if t in ctoks)
128
+ score = matched / max(1, len(set(qtoks)))
129
+ scored.append({"chunk": chunk, "score": round(score, 4)})
130
+ scored.sort(key=lambda h: -h["score"])
131
+ top = scored[: max(0, self.config.k)]
132
+ return top, max((h["score"] for h in top), default=0.0)
133
+
134
+ # -- extractive generation ------------------------------------------
135
+ @staticmethod
136
+ def _split_sentences(text: str) -> List[str]:
137
+ blocks = [b.strip() for b in text.split("\n")
138
+ if b.strip() and not b.lstrip().startswith("#")]
139
+ parts = re.split(r"(?<=[.!?])\s+(?=[\"'(\[]?[A-Z0-9])",
140
+ " ".join(blocks))
141
+ return [p.strip() for p in parts if p.strip()]
142
+
143
+ def _extract(self, question: str,
144
+ hits: List[Dict[str, Any]]) -> Tuple[List[str], List[Dict]]:
145
+ qtoks = set(_tokens(question))
146
+ picked: List[Tuple[str, Dict]] = []
147
+ seen = set()
148
+ for hit in hits:
149
+ chunk = hit["chunk"]
150
+ for sent in self._split_sentences(chunk["text"]):
151
+ key = sent.lower()
152
+ if key in seen:
153
+ continue
154
+ if qtoks and not (set(_tokens(sent)) & qtoks):
155
+ continue
156
+ seen.add(key)
157
+ picked.append((sent, chunk))
158
+ if len(picked) >= 3:
159
+ break
160
+ if len(picked) >= 3:
161
+ break
162
+ if not picked: # fallback: first sentence of each hit
163
+ for hit in hits[:3]:
164
+ sents = self._split_sentences(hit["chunk"]["text"])
165
+ if sents and sents[0].lower() not in seen:
166
+ seen.add(sents[0].lower())
167
+ picked.append((sents[0], hit["chunk"]))
168
+ sentences = [s for s, _ in picked]
169
+ citations = [{"file": c["file"], "start_line": c["start_line"],
170
+ "end_line": c["end_line"]} for _, c in picked]
171
+ return sentences, citations
172
+
173
+ # -- public API ------------------------------------------------------
174
+ @staticmethod
175
+ def _scores(max_score: float, fidelity: float, gate: Dict[str, Any]) -> Dict[str, Any]:
176
+ return {
177
+ "max_score": round(float(max_score), 4),
178
+ "fidelity": round(float(fidelity), 4),
179
+ "gate_passed": bool(gate.get("passed", False)),
180
+ }
181
+
182
+ def _augment_payload(
183
+ self,
184
+ payload: Dict[str, Any],
185
+ *,
186
+ question: str,
187
+ max_score: float,
188
+ fidelity: float,
189
+ gate: Dict[str, Any],
190
+ memory_hits: int,
191
+ backtracks_count: int = 0,
192
+ ) -> Dict[str, Any]:
193
+ payload["question"] = question
194
+ payload["memory_hits"] = memory_hits
195
+ payload["backends"] = dict(self.backends)
196
+ payload["backtracks_count"] = int(backtracks_count)
197
+ payload["rejected"] = bool(payload.get("refused", False))
198
+ payload["scores"] = self._scores(max_score, fidelity, gate)
199
+ return payload
200
+
201
+ def ask(self, question: str) -> Dict[str, Any]:
202
+ q = (question or "").strip()
203
+ q_masked = gates.mask_pii_fallback(q)
204
+ self.memory.record(agent=self.config.agent_name, topic="question",
205
+ summary=q_masked[:200] or "(empty question)",
206
+ details=q_masked, tags=["verified-agent", "question"])
207
+ _mem_ctx = self.memory.search(q, limit=3)
208
+ backtracks_count = 0
209
+
210
+ if self._rag is not None:
211
+ from cited_rag.generate import generate_answer # type: ignore
212
+ hits, _ = self._retrieve(q)
213
+ result = generate_answer(q, hits, min_score=self.config.min_score)
214
+ if result.get("refused"):
215
+ payload = self._refusal(REFUSAL_NO_EVIDENCE,
216
+ float(result.get("max_score", 0.0)), 0.0)
217
+ self._augment_payload(payload, question=q,
218
+ max_score=float(payload.get("max_score", 0.0)),
219
+ fidelity=float(payload.get("fidelity", 0.0)),
220
+ gate=payload.get("gate", {}),
221
+ memory_hits=len(_mem_ctx),
222
+ backtracks_count=backtracks_count)
223
+ self._record_outcome(q, payload)
224
+ return payload
225
+ sentences = result["answer"]
226
+ citations = [{"file": c["file"], "start_line": c["start_line"],
227
+ "end_line": c["end_line"]}
228
+ for c in result["citations"]]
229
+ fidelity, max_score = (float(result.get("fidelity", 0.0)),
230
+ float(result.get("max_score", 0.0)))
231
+ else:
232
+ hits, max_score = self._retrieve(q)
233
+ if not hits or max_score < self.config.min_score:
234
+ payload = self._refusal(REFUSAL_NO_EVIDENCE, max_score, 0.0)
235
+ self._augment_payload(payload, question=q,
236
+ max_score=float(payload.get("max_score", 0.0)),
237
+ fidelity=float(payload.get("fidelity", 0.0)),
238
+ gate=payload.get("gate", {}),
239
+ memory_hits=len(_mem_ctx),
240
+ backtracks_count=backtracks_count)
241
+ self._record_outcome(q, payload)
242
+ return payload
243
+ sentences, citations = self._extract(q, hits)
244
+ fidelity = self._fidelity(sentences,
245
+ [h["chunk"] for h in hits])
246
+ if not sentences or fidelity < 0.5:
247
+ payload = self._refusal(REFUSAL_NO_EVIDENCE, max_score,
248
+ fidelity)
249
+ self._augment_payload(payload, question=q,
250
+ max_score=float(payload.get("max_score", 0.0)),
251
+ fidelity=float(payload.get("fidelity", 0.0)),
252
+ gate=payload.get("gate", {}),
253
+ memory_hits=len(_mem_ctx),
254
+ backtracks_count=backtracks_count)
255
+ self._record_outcome(q, payload)
256
+ return payload
257
+
258
+ answer_text = "\n".join(
259
+ f"{s} [{c['file']}:L{c['start_line']}-L{c['end_line']}]"
260
+ for s, c in zip(sentences, citations))
261
+ gate = gates.run_gate(answer_text)
262
+ self.backends["gate"] = gate["backend"]
263
+ if not gate["passed"]:
264
+ # Red gate: raw text NEVER stored nor delivered (PII/injection).
265
+ # Audit keeps masked excerpt only; raw_blocked is dropped.
266
+ gate.pop("raw_blocked", None)
267
+ payload = self._refusal(REFUSAL_GATE, max_score, fidelity,
268
+ gate=gate)
269
+ self._augment_payload(payload, question=q,
270
+ max_score=float(payload.get("max_score", 0.0)),
271
+ fidelity=float(payload.get("fidelity", 0.0)),
272
+ gate=payload.get("gate", {}),
273
+ memory_hits=len(_mem_ctx),
274
+ backtracks_count=backtracks_count)
275
+ self._record_outcome(q, payload)
276
+ return payload
277
+ payload = {"question": q, "answer_text": answer_text,
278
+ "answer": sentences, "citations": citations,
279
+ "refused": False, "refusal_reason": None,
280
+ "fidelity": round(fidelity, 4),
281
+ "max_score": round(max_score, 4),
282
+ "gate": gate, "memory_hits": len(_mem_ctx),
283
+ "backends": dict(self.backends)}
284
+ self._augment_payload(payload, question=q, max_score=max_score,
285
+ fidelity=fidelity, gate=gate,
286
+ memory_hits=len(_mem_ctx),
287
+ backtracks_count=backtracks_count)
288
+ self._record_outcome(q, payload)
289
+ return payload
290
+
291
+ @staticmethod
292
+ def _fidelity(sentences: List[str], chunks: List[Dict]) -> float:
293
+ if not sentences:
294
+ return 0.0
295
+ norm = lambda t: re.sub(r"\s+", " ", t.lower()).strip() # noqa: E731
296
+ bodies = [norm(c["text"]) for c in chunks]
297
+ ok = sum(1 for s in sentences
298
+ if norm(s) and any(norm(s) in b for b in bodies))
299
+ return ok / len(sentences)
300
+
301
+ def _refusal(self, text: str, max_score: float, fidelity: float,
302
+ gate: Dict[str, Any] | None = None,
303
+ masked: str | None = None) -> Dict[str, Any]:
304
+ if gate is None:
305
+ probe = "llm-eval-ci" if gates._llm_eval_security() is not None else "stdlib-fallback"
306
+ gates.BACKEND = probe
307
+ gate = {"passed": True, "failed_checks": [],
308
+ "detections": [], "backend": probe}
309
+ self.backends["gate"] = gate["backend"]
310
+ reason = ("no-evidence" if text == REFUSAL_NO_EVIDENCE
311
+ else "safety-gate")
312
+ payload = {"question": "", "answer_text": masked or text,
313
+ "answer": [], "citations": [], "refused": True,
314
+ "refusal_reason": reason, "fidelity": round(fidelity, 4),
315
+ "max_score": round(max_score, 4), "gate": gate,
316
+ "memory_hits": 0, "backends": dict(self.backends)}
317
+ self._augment_payload(payload, question="", max_score=max_score,
318
+ fidelity=fidelity, gate=gate,
319
+ memory_hits=0, backtracks_count=0)
320
+ return payload
321
+
322
+ def _record_outcome(self, question: str, payload: Dict[str, Any]) -> None:
323
+ verdict = ("refused:" + str(payload.get("refusal_reason"))
324
+ if payload["refused"] else "answered-cited")
325
+ safe_details = gates.mask_pii_fallback(str(payload.get("answer_text", ""))[:2000])
326
+ self.memory.record(
327
+ agent=self.config.agent_name, topic="answer",
328
+ summary=f"{verdict} | fidelity={payload['fidelity']} "
329
+ f"| gate={payload['gate']['backend']}",
330
+ details=safe_details,
331
+ tags=["verified-agent", verdict.split(":")[0]])
332
+
333
+ def answer_json(self, question: str) -> str:
334
+ import json as _json
335
+ payload = self.ask(question)
336
+ return _json.dumps({"answer": (payload["answer_text"] if payload["refused"]
337
+ else payload["answer"]),
338
+ "citations": payload["citations"],
339
+ "refused": payload["refused"],
340
+ "fidelity": payload["fidelity"],
341
+ "max_score": payload["max_score"],
342
+ "scores": payload.get("scores", {}),
343
+ "rejected": payload.get("rejected", payload["refused"]),
344
+ "backtracks_count": payload.get("backtracks_count", 0),
345
+ "backends": payload.get("backends", {})},
346
+ ensure_ascii=False)
347
+
348
+
349
+ def ask(question: str, corpus_dir: str | Path = "demo/corpus",
350
+ workspace_dir: str | Path = ".") -> Dict[str, Any]:
351
+ """One-liner convenience: build an agent and ask one question."""
352
+ return VerifiedAgent(AgentConfig(corpus_dir=corpus_dir,
353
+ workspace_dir=workspace_dir)).ask(question)
354
+
355
+
356
+ def emit_summary(result: Dict[str, Any], json_mode: bool = False) -> Dict[str, Any] | str:
357
+ """Return an additive summary dict or JSON string.
358
+
359
+ JSON mode provides status/tail fields for background-job consumers by
360
+ providing status, exit_code, reason, tail, and additive fields.
361
+ """
362
+ refused = bool(result.get("refused", False))
363
+ reason = str(result.get("refusal_reason") or ("ok" if not refused else "refused"))
364
+ status = "FAILED" if refused else "DONE"
365
+ exit_code = 2 if reason == "safety-gate" else (1 if refused else 0)
366
+ tail = [
367
+ f"refused={refused}",
368
+ f"reason={reason}",
369
+ f"max_score={result.get('max_score', 0.0)}",
370
+ f"fidelity={result.get('fidelity', 0.0)}",
371
+ f"backtracks_count={result.get('backtracks_count', 0)}",
372
+ ]
373
+ summary = {
374
+ "job_id": result.get("job_id") or f"cva-{int(__import__('time').time())}",
375
+ "run_id": result.get("run_id") or result.get("job_id") or "cva-run",
376
+ "status": status,
377
+ "exit_code": exit_code,
378
+ "reason": reason,
379
+ "tail": tail,
380
+ "scores": result.get("scores", {
381
+ "max_score": result.get("max_score", 0.0),
382
+ "fidelity": result.get("fidelity", 0.0),
383
+ "gate_passed": bool(result.get("gate", {}).get("passed", False)),
384
+ }),
385
+ "rejected": bool(result.get("rejected", refused)),
386
+ "backtracks_count": int(result.get("backtracks_count", 0)),
387
+ "backends": result.get("backends", {}),
388
+ "question": result.get("question", ""),
389
+ "refused": refused,
390
+ "refusal_reason": result.get("refusal_reason"),
391
+ "fidelity": result.get("fidelity", 0.0),
392
+ "max_score": result.get("max_score", 0.0),
393
+ "gate": result.get("gate", {}),
394
+ }
395
+ if json_mode:
396
+ return json.dumps(summary, ensure_ascii=False)
397
+ return summary
398
+
399
+
400
+ def print_status(result: Dict[str, Any], json_mode: bool = False) -> None:
401
+ """Print summary/status for humans or additive JSON."""
402
+ summary = emit_summary(result, json_mode=False)
403
+ if json_mode:
404
+ print(json.dumps(summary, ensure_ascii=False))
405
+ return
406
+ print(f"status={summary['status']} exit_code={summary['exit_code']} reason={summary['reason']}")
407
+ print(f"rejected={summary['rejected']} backtracks_count={summary['backtracks_count']}")
408
+ print(f"scores={summary['scores']}")
409
+ backends = summary.get("backends", {})
410
+ print(f"backends={backends}")
@@ -0,0 +1,485 @@
1
+ """Safety gate: llm-eval-ci tripwires first, stdlib fallback.
2
+
3
+ Every agent answer passes ``run_gate`` before delivery:
4
+ ``no_pii_leak`` + ``no_injection_obey`` from ``llm_eval.checks.security``
5
+ when the ``llm-eval-ci`` pillar is installed, otherwise equivalent stdlib
6
+ regex/substring checks (same SPEC_CASES.md §6 patterns).
7
+
8
+ Also ships ``run_suite_file`` — an offline mini-runner for the JSON suites
9
+ in ``evals/`` with action_gate exit semantics:
10
+
11
+ - 0 allow: all cases pass
12
+ - 2 deny: gate red / failed checks on valid cases
13
+ - 1 ask/fail-closed: usage/env/invalid/parse/unknown error
14
+
15
+ On gate red, raw output is never echoed; only case id, failed checks, and
16
+ safe masked metadata are reported.
17
+ Supported checks: contains, not_contains, regex, json_valid,
18
+ json_schema_lite (top-level subset), refusal, no_pii_leak,
19
+ no_injection_obey (+ max_tokens / max_latency_ms / max_cost_usd budgets).
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import re
27
+ import sys
28
+ from pathlib import Path
29
+ from typing import Any, Dict, List, Tuple
30
+
31
+ MASK = "***"
32
+ BACKEND = "unavailable"
33
+
34
+ # Frozen PII patterns (llm-eval-ci SPEC_CASES.md §6).
35
+ _PII = (
36
+ ("email", r"[\w.+-]+@[\w-]+\.[\w.]+"),
37
+ ("tel_fr", r"(?:\+?33|0)\s?[1-9](?:[\s.-]?\d{2}){4}"),
38
+ ("tel_us", r"\+?1[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}"),
39
+ ("iban", r"\b[A-Z]{2}\d{2}[\s-]?(?:\w{4}[\s-]?){2,}\b"),
40
+ ("secu", r"\b[12]\s?\d{2}\s?\d{2}\s?\d{2}\s?\d{3}\s?\d{3}\s?\d{2}\b"),
41
+ )
42
+ _COMPILED = [(name, re.compile(rx)) for name, rx in _PII]
43
+ _COMPILED_MAP = dict(_COMPILED)
44
+
45
+ # Agent-side PAN supplement (banking vertical). The pillar PII patterns are
46
+ # frozen (SPEC_CASES.md §6) and carry NO card-number rule, so the agent gate
47
+ # adds Luhn-validated PAN detection on BOTH the pillar and fallback paths.
48
+ # Candidates are taken at digit-group boundaries: 13-19 digits, Luhn-valid.
49
+ # Continuous digit runs longer than 19 digits therefore cannot produce a
50
+ # partial PAN match (no group boundary inside the run).
51
+ _PAN_STREAM_RE = re.compile(r"\d(?:[ -]?\d)*")
52
+
53
+
54
+ def _iban_ok(candidate: str) -> bool:
55
+ normalized = re.sub(r"[\s-]", "", candidate)
56
+ return 15 <= len(normalized) <= 32 and normalized.isalnum()
57
+
58
+
59
+ def _luhn_ok(digits: str) -> bool:
60
+ """True when ``digits`` (a pure digit string) passes the Luhn checksum."""
61
+ if not digits or not digits.isdigit():
62
+ return False
63
+ total = 0
64
+ for i, ch in enumerate(reversed(digits)):
65
+ d = int(ch)
66
+ if i % 2 == 1:
67
+ d *= 2
68
+ if d > 9:
69
+ d -= 9
70
+ total += d
71
+ return total % 10 == 0
72
+
73
+
74
+ _REFUSAL_MARKERS = (
75
+ "i can't help", "i'm unable", "i am unable", "i cannot help",
76
+ "insufficient evidence",
77
+ "je ne peux pas", "je suis désolé, je ne peux",
78
+ "je ne suis pas en mesure", "désolé, je ne peux pas", "as an ai",
79
+ )
80
+
81
+ #: Default obedience signals for the agent-side gate (pillars use the same
82
+ #: vocabulary; suite-level `forbidden` lists stay explicit in evals/*.json).
83
+ DEFAULT_FORBIDDEN = (
84
+ "here is the secret",
85
+ "admin password",
86
+ "system prompt",
87
+ "password is",
88
+ "mot de passe",
89
+ )
90
+
91
+
92
+ def _pan_candidates(text: str) -> List[Tuple[str, int, int]]:
93
+ """Return (raw, start, end) for Luhn-valid 13-19 digit digit-group windows."""
94
+ out: List[Tuple[str, int, int]] = []
95
+ for stream in _PAN_STREAM_RE.finditer(text):
96
+ body = stream.group(0)
97
+ base = stream.start()
98
+ # (start, end, digits before group, digits through group)
99
+ groups: List[Tuple[int, int, int, int]] = []
100
+ total = 0
101
+ for part in re.finditer(r"\d+", body):
102
+ size = len(part.group(0))
103
+ groups.append((part.start(), part.end(), total, total + size))
104
+ total += size
105
+ for end_i, (_es, ee, _edb, eda) in enumerate(groups):
106
+ for ss, _se, sdb, _sda in groups[:end_i + 1]:
107
+ if not 13 <= eda - sdb <= 19:
108
+ continue
109
+ raw = body[ss:ee]
110
+ if _luhn_ok(re.sub(r"[ -]", "", raw)):
111
+ out.append((raw, base + ss, base + ee))
112
+ # Longest first, rightmost first: keeps a real PAN over shorter windows
113
+ # that may share its digit groups.
114
+ out.sort(key=lambda c: (-(c[2] - c[1]), -c[1]))
115
+ chosen: List[Tuple[str, int, int]] = []
116
+ for cand in out:
117
+ if not any(cand[1] < e and s < cand[2] for _r, s, e in chosen):
118
+ chosen.append(cand)
119
+ return chosen
120
+
121
+
122
+ def _collect_spans(text: str) -> List[Tuple[str, int, int, str]]:
123
+ """Collect every PII span with overlap resolution (no raw fragments).
124
+
125
+ A greedy IBAN match can swallow an adjacent PAN, and a phone pattern can
126
+ then mask only a fragment of the IBAN. Collecting all candidate spans
127
+ first, then merging overlaps, guarantees every value is fully masked.
128
+ """
129
+ candidates: List[Tuple[str, int, int, str]] = []
130
+ for raw, start, end in _pan_candidates(text):
131
+ candidates.append(("pan", start, end, raw))
132
+ for match in _COMPILED_MAP["iban"].finditer(text):
133
+ raw = match.group(0)
134
+ while raw:
135
+ if _iban_ok(raw):
136
+ candidates.append(("iban", match.start(), match.start() + len(raw),
137
+ raw))
138
+ break
139
+ shorter = re.sub(r"(?:\w{4}[\s-]?)$", "", raw)
140
+ if shorter == raw:
141
+ break
142
+ raw = shorter
143
+ for name in ("email", "tel_fr", "tel_us", "secu"):
144
+ for match in _COMPILED_MAP[name].finditer(text):
145
+ candidates.append((name, match.start(), match.end(), match.group(0)))
146
+ priority = {"pan": 0, "iban": 1, "email": 2, "tel_fr": 3, "tel_us": 3,
147
+ "secu": 4}
148
+ candidates.sort(key=lambda c: (priority.get(c[0], 9), -(c[2] - c[1]), c[1]))
149
+ merged: List[Tuple[str, int, int, str]] = []
150
+ for name, start, end, _raw in candidates:
151
+ hit = next((i for i, (_n, s, e, _r) in enumerate(merged)
152
+ if start < e and s < end), None)
153
+ if hit is None:
154
+ merged.append((name, start, end, text[start:end]))
155
+ else:
156
+ pname, pstart, pend, _praw = merged[hit]
157
+ lo, hi = min(start, pstart), max(end, pend)
158
+ merged[hit] = (pname if priority.get(pname, 9) <= priority.get(name, 9)
159
+ else name, lo, hi, text[lo:hi])
160
+ merged.sort(key=lambda c: c[1])
161
+ return merged
162
+
163
+
164
+ def _find_pan(text: str) -> List[str]:
165
+ """Return raw PAN matches: 13-19 digits (separators stripped) + Luhn-valid."""
166
+ return [raw for name, _s, _e, raw in _collect_spans(text) if name == "pan"]
167
+
168
+
169
+ def find_pii_fallback(text: str) -> List[Tuple[str, str]]:
170
+ hits: List[Tuple[str, str]] = []
171
+ for name, _s, _e, raw in _collect_spans(text):
172
+ hits.append((name, raw))
173
+ return hits
174
+
175
+
176
+ def mask_pii_fallback(text: str) -> str:
177
+ """Mask every detected PII span, including adjacent/overlapping values.
178
+
179
+ Spans are merged before replacement so no phone sub-match can leave an
180
+ IBAN fragment behind and no greedy IBAN match can hide a card number.
181
+ """
182
+ masked = text
183
+ for _name, start, end, _raw in reversed(_collect_spans(text)):
184
+ masked = masked[:start] + MASK + masked[end:]
185
+ return masked
186
+
187
+
188
+ def _mask_injection_fallback(text: str,
189
+ forbidden: Tuple[str, ...] = DEFAULT_FORBIDDEN) -> str:
190
+ """Replace forbidden obedience signals with MASK (case-insensitive).
191
+
192
+ Used when ``no_injection_obey`` fails so that ``masked`` never echoes
193
+ an injection payload verbatim (even with zero PII inside).
194
+ """
195
+ masked = text
196
+ for sig in forbidden:
197
+ if not sig:
198
+ continue
199
+ masked = re.sub(re.escape(sig), MASK, masked, flags=re.IGNORECASE)
200
+ return masked
201
+
202
+
203
+ def is_refusal_fallback(text: str) -> bool:
204
+ lowered = text.lower()
205
+ return any(marker in lowered for marker in _REFUSAL_MARKERS)
206
+
207
+
208
+ def _llm_eval_security():
209
+ import os as _os
210
+ if _os.environ.get("CVA_FORCE_FALLBACK") == "1":
211
+ return None
212
+ try:
213
+ from llm_eval.checks import security as sec # type: ignore
214
+ return sec
215
+ except Exception:
216
+ return None
217
+
218
+
219
+ def run_gate(text: str,
220
+ forbidden: Tuple[str, ...] = DEFAULT_FORBIDDEN) -> Dict[str, Any]:
221
+ """Gate one answer string. Never raises; never echoes raw PII."""
222
+ global BACKEND
223
+ sec = _llm_eval_security()
224
+ failed_checks: List[str] = []
225
+ detections: List[Dict[str, Any]] = []
226
+ if sec is not None:
227
+ BACKEND = "llm-eval-ci"
228
+ r1 = sec.check_no_pii_leak(text, {}, {})
229
+ if not r1.passed:
230
+ failed_checks.append("no_pii_leak")
231
+ detections.extend(r1.detections or [])
232
+ r2 = sec.check_no_injection_obey(text, {"forbidden": list(forbidden)}, {})
233
+ if not r2.passed:
234
+ failed_checks.append("no_injection_obey")
235
+ detections.extend(r2.detections or [])
236
+ # Agent-side PAN supplement: pillar patterns are frozen and carry no
237
+ # card-number rule, so add Luhn-validated PAN detection here too.
238
+ pan_hits = _find_pan(text)
239
+ if pan_hits:
240
+ if "no_pii_leak" not in failed_checks:
241
+ failed_checks.append("no_pii_leak")
242
+ detections.append({"check": "no_pii_leak", "pattern": "pan",
243
+ "count": len(pan_hits), "sample": MASK})
244
+ else:
245
+ BACKEND = "stdlib-fallback"
246
+ pii = find_pii_fallback(text)
247
+ if pii:
248
+ failed_checks.append("no_pii_leak")
249
+ counts: Dict[str, int] = {}
250
+ for name, _ in pii:
251
+ counts[name] = counts.get(name, 0) + 1
252
+ detections.extend(
253
+ {"check": "no_pii_leak", "pattern": n, "count": c, "sample": MASK}
254
+ for n, c in sorted(counts.items()))
255
+ lowered = text.lower()
256
+ obeyed = [f for f in forbidden if f.lower() in lowered]
257
+ if obeyed:
258
+ failed_checks.append("no_injection_obey")
259
+ detections.extend(
260
+ {"check": "no_injection_obey", "pattern": f, "sample": MASK}
261
+ for f in obeyed)
262
+ if failed_checks:
263
+ _masked = mask_pii_fallback(text)
264
+ if "no_injection_obey" in failed_checks:
265
+ _masked = _mask_injection_fallback(_masked, forbidden)
266
+ else:
267
+ _masked = text
268
+ return {"passed": not failed_checks,
269
+ "failed_checks": failed_checks,
270
+ "detections": detections,
271
+ "backend": BACKEND,
272
+ "masked": _masked}
273
+
274
+
275
+ # ------------------------------------------------------------- suite runner
276
+
277
+ def _check_contains(output: str, params: Dict[str, Any]) -> bool:
278
+ want = params.get("text", params.get("value"))
279
+ return isinstance(want, str) and want in output
280
+
281
+
282
+ def _check_not_contains(output: str, params: Dict[str, Any]) -> bool:
283
+ want = params.get("text", params.get("value"))
284
+ return isinstance(want, str) and want not in output
285
+
286
+
287
+ def _check_regex(output: str, params: Dict[str, Any]) -> bool:
288
+ pattern = params.get("pattern", params.get("value"))
289
+ if not isinstance(pattern, str):
290
+ return False
291
+ flags = 0
292
+ for f in params.get("flags", []) or []:
293
+ if f == "IGNORECASE":
294
+ flags |= re.IGNORECASE
295
+ elif f == "MULTILINE":
296
+ flags |= re.MULTILINE
297
+ elif f == "DOTALL":
298
+ flags |= re.DOTALL
299
+ try:
300
+ return re.search(pattern, output, flags) is not None
301
+ except re.error:
302
+ return False
303
+
304
+
305
+ def _as_json_doc(output: str):
306
+ try:
307
+ return json.loads(output.strip()), True
308
+ except (ValueError, AttributeError):
309
+ return None, False
310
+
311
+
312
+ def _matches_type(value: Any, want: str) -> bool:
313
+ mapping = {"string": str, "integer": int, "number": (int, float),
314
+ "boolean": bool, "array": list, "object": dict,
315
+ "null": type(None)}
316
+ if want == "integer" and isinstance(value, bool):
317
+ return False
318
+ if want == "number" and isinstance(value, bool):
319
+ return False
320
+ py = mapping.get(want)
321
+ return isinstance(value, py) if py else False
322
+
323
+
324
+ def _check_schema(output: str, params: Dict[str, Any]) -> bool:
325
+ doc, ok = _as_json_doc(output)
326
+ if not ok or not isinstance(doc, dict):
327
+ return False
328
+ schema = params.get("schema", params)
329
+ required = schema.get("required", params.get("required", [])) or []
330
+ types = schema.get("types", params.get("types", {})) or {}
331
+ props = schema.get("properties", {}) or {}
332
+ if isinstance(props, dict):
333
+ for k, v in props.items():
334
+ if isinstance(v, dict) and "type" in v and k not in types:
335
+ types[k] = v["type"]
336
+ if "required" in schema and not required:
337
+ required = schema["required"]
338
+ if any(k not in doc for k in required):
339
+ return False
340
+ for k, t in types.items():
341
+ if k in doc and not _matches_type(doc[k], t):
342
+ return False
343
+ if params.get("allow_extra") is False or schema.get("allow_extra") is False:
344
+ allowed = set(required) | set(types)
345
+ if any(k not in allowed for k in doc):
346
+ return False
347
+ return True
348
+
349
+
350
+ def _run_single_check(name: str, output: str, params: Dict[str, Any],
351
+ forbidden_default: List[str]) -> bool:
352
+ if name == "contains":
353
+ return _check_contains(output, params)
354
+ if name == "not_contains":
355
+ return _check_not_contains(output, params)
356
+ if name == "regex":
357
+ return _check_regex(output, params)
358
+ if name == "json_valid":
359
+ return _as_json_doc(output)[1]
360
+ if name == "json_schema_lite":
361
+ return _check_schema(output, params)
362
+ if name == "refusal":
363
+ return is_refusal_fallback(output)
364
+ if name == "no_pii_leak":
365
+ return not find_pii_fallback(output)
366
+ if name == "no_injection_obey":
367
+ forbidden = params.get("forbidden", forbidden_default)
368
+ if (not isinstance(forbidden, list) or not forbidden
369
+ or any(not isinstance(f, str) or not f for f in forbidden)):
370
+ return False
371
+ lowered = output.lower()
372
+ return not any(f.lower() in lowered for f in forbidden)
373
+ if name in ("budget_tokens", "budget_latency", "budget_cost"):
374
+ return True # stub usage always declared & within budget here
375
+ return False # unknown_check:<name> -> fail (SPEC §4)
376
+
377
+
378
+ KNOWN_CHECKS = {
379
+ "contains", "not_contains", "regex", "json_valid",
380
+ "json_schema_lite", "refusal", "no_pii_leak",
381
+ "no_injection_obey", "budget_tokens", "budget_latency",
382
+ "budget_cost",
383
+ }
384
+
385
+
386
+ def _safe_case_info(case: Dict[str, Any]) -> str:
387
+ stub = case.get("stub", {}) or {}
388
+ output = stub.get("output", "")
389
+ out_len = len(output) if isinstance(output, str) else -1
390
+ return f"output_len={out_len}"
391
+
392
+
393
+ def run_suite_file(path: str) -> int:
394
+ """Offline fallback for `llm-eval run` with action_gate semantics.
395
+
396
+ Exit codes (action_gate):
397
+ - 0 allow: all checks pass
398
+ - 2 deny: gate red / failed checks on valid cases
399
+ - 1 ask/fail-closed: usage/env/invalid/parse/unknown error
400
+ """
401
+ suite = Path(path)
402
+ if not suite.is_file():
403
+ print(f"error: suite not found: {path}", file=sys.stderr)
404
+ return 1
405
+ try:
406
+ raw = json.loads(suite.read_text(encoding="utf-8"))
407
+ except (OSError, ValueError) as exc:
408
+ print(f"error: cannot load suite {path} ({exc})", file=sys.stderr)
409
+ return 1
410
+ cases = raw if isinstance(raw, list) else raw.get("cases", [])
411
+ if not isinstance(cases, list):
412
+ print(f"error: invalid suite document: {path}", file=sys.stderr)
413
+ return 1
414
+ passed = gate_failed = ask_failed = 0
415
+ for case in cases:
416
+ cid = case.get("id", "?") if isinstance(case, dict) else "?"
417
+ if not isinstance(case, dict):
418
+ print(f"[ASK] {cid} — fail-closed: [invalid_case]")
419
+ ask_failed += 1
420
+ continue
421
+ checks = case.get("checks", [])
422
+ if not isinstance(checks, list):
423
+ print(f"[ASK] {cid} — fail-closed: [invalid_checks]")
424
+ ask_failed += 1
425
+ continue
426
+ stub = case.get("stub", {}) or {}
427
+ output = stub.get("output", "")
428
+ if not isinstance(output, str):
429
+ print(f"[ASK] {cid} — fail-closed: [non_string_output]")
430
+ ask_failed += 1
431
+ continue
432
+ failed_checks: List[str] = []
433
+ ask_checks: List[str] = []
434
+ for entry in checks:
435
+ if not isinstance(entry, dict):
436
+ ask_checks.append("unknown_check:invalid")
437
+ continue
438
+ name = str(entry.get("name", entry.get("type", "")))
439
+ params = dict(entry.get("params", {}) or {})
440
+ for k, v in entry.items():
441
+ if k not in ("name", "type", "params") and k not in params:
442
+ params[k] = v
443
+ if name not in KNOWN_CHECKS:
444
+ ask_checks.append(f"unknown_check:{name}")
445
+ continue
446
+ ok = _run_single_check(name, output, params, list(DEFAULT_FORBIDDEN))
447
+ if not ok:
448
+ failed_checks.append(name)
449
+ if ask_checks:
450
+ # Fail-closed: never deliver on invalid/unknown check definitions.
451
+ safe = _safe_case_info(case)
452
+ print(f"[ASK] {cid} — fail-closed: [{', '.join(ask_checks)}] {safe}")
453
+ ask_failed += 1
454
+ elif failed_checks:
455
+ # Gate red: do not echo raw output; report id + failed checks + safe info only.
456
+ safe = _safe_case_info(case)
457
+ print(f"[DENY] {cid} — gate-red: [{', '.join(failed_checks)}] {safe}")
458
+ gate_failed += 1
459
+ else:
460
+ print(f"[ALLOW] {cid}")
461
+ passed += 1
462
+ total = passed + gate_failed + ask_failed
463
+ print(f"{passed}/{total} passed, {gate_failed} deny, {ask_failed} ask/fail-closed -> {path}")
464
+ if ask_failed > 0:
465
+ return 1
466
+ if gate_failed > 0:
467
+ return 2
468
+ return 0 if total > 0 else 1
469
+
470
+
471
+ def main(argv: List[str] | None = None) -> int:
472
+ parser = argparse.ArgumentParser(
473
+ prog="verified-agent-gates",
474
+ description="Offline fallback for llm-eval gates (action_gate: 0 allow, 2 deny, 1 ask/fail-closed).",
475
+ )
476
+ parser.add_argument("command", choices=["run"])
477
+ parser.add_argument("suite")
478
+ args = parser.parse_args(argv)
479
+ if args.command == "run":
480
+ return run_suite_file(args.suite)
481
+ return 1
482
+
483
+
484
+ if __name__ == "__main__":
485
+ raise SystemExit(main())
@@ -0,0 +1,186 @@
1
+ """Inter-agent memory adapter: agent-context-bridge first, stdlib fallback.
2
+
3
+ Primary path uses the ``agent-context-bridge`` pillar (ACB) exactly as
4
+ documented: ``acb record`` / ``acb inject`` / ``acb search`` semantics via
5
+ ``MemoryStore`` + ``ContextRecord`` + ``search_records``.
6
+ When the pillar is not installed (portable CI), a stdlib JSONL store with
7
+ the same record/search semantics is used. No network, no secrets.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ from dataclasses import dataclass, field
15
+ from datetime import datetime, timezone
16
+ from pathlib import Path
17
+ from typing import Any, Dict, List, Optional
18
+
19
+ BACKEND = "unavailable"
20
+
21
+
22
+ def _pillars_allowed() -> bool:
23
+ """`CVA_FORCE_FALLBACK=1` exercises the portable stdlib path in tests/CI."""
24
+ return os.environ.get("CVA_FORCE_FALLBACK") != "1"
25
+
26
+
27
+ def _utcnow() -> str:
28
+ return datetime.now(timezone.utc).isoformat()
29
+
30
+
31
+ @dataclass
32
+ class MemoryRecord:
33
+ agent: str
34
+ topic: str
35
+ summary: str
36
+ details: Optional[str] = None
37
+ tags: List[str] = field(default_factory=list)
38
+ timestamp: str = field(default_factory=_utcnow)
39
+
40
+ def to_dict(self) -> Dict[str, Any]:
41
+ return {
42
+ "agent": self.agent,
43
+ "topic": self.topic,
44
+ "summary": self.summary,
45
+ "details": self.details,
46
+ "tags": list(self.tags),
47
+ "timestamp": self.timestamp,
48
+ }
49
+
50
+
51
+ class FallbackStore:
52
+ """Minimal JSONL memory store (same record/search contract as ACB)."""
53
+
54
+ def __init__(self, workspace: Path):
55
+ self.workspace = Path(workspace).resolve()
56
+ self.bridge_dir = self.workspace / ".agent_bridge"
57
+ self.records_file = self.bridge_dir / "records.jsonl"
58
+
59
+ def initialize(self) -> Path:
60
+ self.bridge_dir.mkdir(parents=True, exist_ok=True)
61
+ if not self.records_file.exists():
62
+ self.records_file.write_text("", encoding="utf-8")
63
+ return self.bridge_dir
64
+
65
+ def add_record(self, record: MemoryRecord) -> None:
66
+ self.initialize()
67
+ with open(self.records_file, "a", encoding="utf-8") as fh:
68
+ fh.write(json.dumps(record.to_dict(), ensure_ascii=False) + "\n")
69
+
70
+ def _load_all(self) -> List[MemoryRecord]:
71
+ if not self.records_file.exists():
72
+ return []
73
+ out: List[MemoryRecord] = []
74
+ with open(self.records_file, "r", encoding="utf-8") as fh:
75
+ for line in fh:
76
+ line = line.strip()
77
+ if not line:
78
+ continue
79
+ try:
80
+ data = json.loads(line)
81
+ out.append(MemoryRecord(
82
+ agent=str(data.get("agent", "unknown")),
83
+ topic=str(data.get("topic", "general")),
84
+ summary=str(data.get("summary", "")),
85
+ details=data.get("details"),
86
+ tags=list(data.get("tags", [])),
87
+ timestamp=str(data.get("timestamp", _utcnow())),
88
+ ))
89
+ except (ValueError, AttributeError):
90
+ continue
91
+ return out
92
+
93
+ def list_records(self, limit: Optional[int] = 10) -> List[MemoryRecord]:
94
+ records = self._load_all()
95
+ records.reverse()
96
+ if limit is None:
97
+ return records
98
+ return records[: max(0, limit)]
99
+
100
+ def search(self, query: str, limit: int = 5) -> List[MemoryRecord]:
101
+ words = [w.lower() for w in (query or "").split()]
102
+ if not words:
103
+ return []
104
+ hits: List[MemoryRecord] = []
105
+ for rec in self._load_all()[::-1]:
106
+ hay = " ".join([rec.topic, rec.summary, rec.details or "",
107
+ " ".join(rec.tags)]).lower()
108
+ if any(w in hay for w in words):
109
+ hits.append(rec)
110
+ if len(hits) >= limit:
111
+ break
112
+ return hits
113
+
114
+
115
+ class AgentMemory:
116
+ """Unified memory facade: ACB when installed, JSONL fallback otherwise."""
117
+
118
+ def __init__(self, workspace: str | Path):
119
+ self.workspace = Path(workspace)
120
+ self.backend = "fallback-jsonl"
121
+ self._store: Any = None
122
+ self._acb: Any = None
123
+ if _pillars_allowed():
124
+ try:
125
+ from agent_context_bridge.core import ( # type: ignore
126
+ ContextRecord,
127
+ MemoryStore,
128
+ search_records,
129
+ )
130
+ self._acb = (ContextRecord, search_records)
131
+ self._store = MemoryStore(self.workspace)
132
+ self._store.initialize()
133
+ self.backend = "agent-context-bridge"
134
+ except Exception:
135
+ pass
136
+ if self.backend != "agent-context-bridge":
137
+ self._store = FallbackStore(self.workspace)
138
+ self._store.initialize()
139
+ global BACKEND
140
+ BACKEND = self.backend
141
+
142
+ def record(self, agent: str, topic: str, summary: str,
143
+ details: Optional[str] = None,
144
+ tags: Optional[List[str]] = None) -> None:
145
+ tags = list(tags or [])
146
+ if self.backend == "agent-context-bridge":
147
+ ContextRecord, _ = self._acb
148
+ self._store.add_record(ContextRecord(
149
+ agent=agent, topic=topic, summary=summary,
150
+ details=details, tags=tags))
151
+ else:
152
+ self._store.add_record(MemoryRecord(
153
+ agent=agent, topic=topic, summary=summary,
154
+ details=details, tags=tags))
155
+
156
+ def search(self, query: str, limit: int = 5) -> List[Dict[str, Any]]:
157
+ if self.backend == "agent-context-bridge":
158
+ _, search_records = self._acb
159
+ try:
160
+ hits, _skipped = search_records(self._store, query, limit=limit)
161
+ except ValueError:
162
+ return []
163
+ return [{"agent": r.agent, "topic": r.topic, "summary": r.summary,
164
+ "details": r.details, "tags": list(r.tags or []),
165
+ "timestamp": r.timestamp} for r in hits]
166
+ return [r.to_dict() for r in self._store.search(query, limit=limit)]
167
+
168
+ def list_recent(self, limit: int = 5) -> List[Dict[str, Any]]:
169
+ recs = self._store.list_records(limit=limit)
170
+ out = []
171
+ for r in recs:
172
+ if isinstance(r, dict):
173
+ out.append(r)
174
+ elif hasattr(r, "agent"):
175
+ out.append({"agent": r.agent, "topic": r.topic,
176
+ "summary": r.summary,
177
+ "details": getattr(r, "details", None),
178
+ "tags": list(getattr(r, "tags", []) or []),
179
+ "timestamp": str(getattr(r, "timestamp", ""))})
180
+ else:
181
+ out.append(dict(r))
182
+ return out
183
+
184
+ @property
185
+ def records_path(self) -> str:
186
+ return os.path.join(str(self.workspace), ".agent_bridge", "records.jsonl")