RagGovern 0.1.0__tar.gz
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.
- raggovern-0.1.0/.gitignore +11 -0
- raggovern-0.1.0/LICENSE +21 -0
- raggovern-0.1.0/PKG-INFO +96 -0
- raggovern-0.1.0/README.md +67 -0
- raggovern-0.1.0/benchmarks/scan.py +29 -0
- raggovern-0.1.0/docs/architecture.md +75 -0
- raggovern-0.1.0/docs/configuration.md +57 -0
- raggovern-0.1.0/docs/decisions.md +17 -0
- raggovern-0.1.0/docs/rules.md +101 -0
- raggovern-0.1.0/docs/trust-model.md +15 -0
- raggovern-0.1.0/examples/custom/pipeline.py +10 -0
- raggovern-0.1.0/examples/custom/settings.yaml +9 -0
- raggovern-0.1.0/examples/langchain/pipeline.py +14 -0
- raggovern-0.1.0/examples/langchain/requirements.txt +4 -0
- raggovern-0.1.0/examples/llamaindex/pipeline.py +9 -0
- raggovern-0.1.0/examples/llamaindex/pyproject.toml +4 -0
- raggovern-0.1.0/pyproject.toml +40 -0
- raggovern-0.1.0/schemas/ragguard-v1.json +342 -0
- raggovern-0.1.0/src/ragguard/__init__.py +8 -0
- raggovern-0.1.0/src/ragguard/__main__.py +4 -0
- raggovern-0.1.0/src/ragguard/adapters.py +30 -0
- raggovern-0.1.0/src/ragguard/analysis.py +395 -0
- raggovern-0.1.0/src/ragguard/catalog.py +113 -0
- raggovern-0.1.0/src/ragguard/cli.py +196 -0
- raggovern-0.1.0/src/ragguard/config.py +172 -0
- raggovern-0.1.0/src/ragguard/core.py +139 -0
- raggovern-0.1.0/src/ragguard/discovery.py +263 -0
- raggovern-0.1.0/src/ragguard/evidence.py +59 -0
- raggovern-0.1.0/src/ragguard/exceptions.py +2 -0
- raggovern-0.1.0/src/ragguard/findings.py +29 -0
- raggovern-0.1.0/src/ragguard/logging.py +16 -0
- raggovern-0.1.0/src/ragguard/metadata.py +153 -0
- raggovern-0.1.0/src/ragguard/models.py +177 -0
- raggovern-0.1.0/src/ragguard/py.typed +1 -0
- raggovern-0.1.0/src/ragguard/rules.py +431 -0
- raggovern-0.1.0/tests/conftest.py +24 -0
- raggovern-0.1.0/tests/fixtures/invalid.yaml +3 -0
- raggovern-0.1.0/tests/fixtures/partial/broken.py +1 -0
- raggovern-0.1.0/tests/fixtures/partial/config.json +1 -0
- raggovern-0.1.0/tests/fixtures/partial/unknown.py +3 -0
- raggovern-0.1.0/tests/test_analysis.py +95 -0
- raggovern-0.1.0/tests/test_cli.py +61 -0
- raggovern-0.1.0/tests/test_config.py +87 -0
- raggovern-0.1.0/tests/test_discovery.py +157 -0
- raggovern-0.1.0/tests/test_rules.py +131 -0
raggovern-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 RAG-GUARD contributors
|
|
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.
|
raggovern-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: RagGovern
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Local, evidence-backed static assessment for RAG projects
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Requires-Dist: pydantic<3,>=2.9
|
|
11
|
+
Requires-Dist: pyyaml<7,>=6
|
|
12
|
+
Requires-Dist: rich<16,>=13
|
|
13
|
+
Requires-Dist: typer<1,>=0.16
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
16
|
+
Requires-Dist: hatchling>=1.25; extra == 'dev'
|
|
17
|
+
Requires-Dist: mypy>=1.13; extra == 'dev'
|
|
18
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
19
|
+
Requires-Dist: ruff>=0.9; extra == 'dev'
|
|
20
|
+
Requires-Dist: types-pyyaml; extra == 'dev'
|
|
21
|
+
Provides-Extra: langchain
|
|
22
|
+
Requires-Dist: faiss-cpu; extra == 'langchain'
|
|
23
|
+
Requires-Dist: langchain-community; extra == 'langchain'
|
|
24
|
+
Requires-Dist: langchain-openai; extra == 'langchain'
|
|
25
|
+
Requires-Dist: langchain-text-splitters; extra == 'langchain'
|
|
26
|
+
Provides-Extra: llamaindex
|
|
27
|
+
Requires-Dist: llama-index-core; extra == 'llamaindex'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# RagGovern
|
|
31
|
+
|
|
32
|
+
RagGovern inventories RAG projects and checks their static configuration locally. It parses source as data and attaches source evidence to every finding. Install the release with `python -m pip install RagGovern`. The Python import and console command are both `ragguard`.
|
|
33
|
+
|
|
34
|
+
Python 3.11+ is supported. Development targets Python 3.12. Run the following commands from this repository in an activated virtual environment.
|
|
35
|
+
|
|
36
|
+
```console
|
|
37
|
+
python -m pip install -e ".[dev]"
|
|
38
|
+
ragguard init
|
|
39
|
+
ragguard config validate
|
|
40
|
+
ragguard scan examples/langchain
|
|
41
|
+
ragguard inspect examples/llamaindex --format mermaid
|
|
42
|
+
ragguard rules --format json
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
For an example with a threshold violation, run `ragguard scan examples/custom --format json`. The logging call that receives retrieved context produces a high-severity RG009 finding and exit code 1. Its evidence includes the relative file, source lines and logging function. The report omits the logged content.
|
|
46
|
+
|
|
47
|
+
## Python SDK
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from pathlib import Path
|
|
51
|
+
from ragguard import RAGGuard
|
|
52
|
+
|
|
53
|
+
guard = RAGGuard.from_config(Path("ragguard.yaml"), profile="ci")
|
|
54
|
+
snapshot = guard.inspect("examples/langchain")
|
|
55
|
+
print(snapshot.architecture.mermaid())
|
|
56
|
+
|
|
57
|
+
run = guard.scan("examples/custom")
|
|
58
|
+
for result in run.results:
|
|
59
|
+
for finding in result.findings:
|
|
60
|
+
print(finding.rule_id, finding.evidence.file, finding.evidence.line, finding.remediation)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`RAGGuard.init(path)` creates a policy. `RAGGuard.validate_config(path)` returns the effective typed settings. `guard.rules()` returns the catalog. JSON output is available from the CLI and through Pydantic's `model_dump_json()`.
|
|
64
|
+
|
|
65
|
+
## Working with results
|
|
66
|
+
|
|
67
|
+
Inspection covers Python sources, manifests, structured configuration, documentation and Dockerfile inventory. Recognized RAG roles range from document loading to citation formatting. Directed edges record observed call inputs and receivers. Confidence and diagnostics describe the limits of each assessment. A clean process exit can include unassessed rules.
|
|
68
|
+
|
|
69
|
+
| Command exit | Meaning |
|
|
70
|
+
|---|---|
|
|
71
|
+
| 0 | Command succeeded, below the configured finding threshold |
|
|
72
|
+
| 1 | A finding reached the severity threshold |
|
|
73
|
+
| 2 | Invalid policy, argument or path |
|
|
74
|
+
| 3 | Internal execution or rule error |
|
|
75
|
+
|
|
76
|
+
Use `--output new-report.json` to create a scan report. A plain scan writes to stdout. The static scanner needs no provider credentials or framework installations.
|
|
77
|
+
|
|
78
|
+
## Development and packaging
|
|
79
|
+
|
|
80
|
+
```console
|
|
81
|
+
python -m pytest
|
|
82
|
+
python -m ruff check .
|
|
83
|
+
python -m ruff format --check .
|
|
84
|
+
python -m mypy src
|
|
85
|
+
python -m build
|
|
86
|
+
python benchmarks/scan.py examples 5
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The wheel and source archive are written to `dist/`. The source tree includes three small framework examples and fixtures for incomplete or sensitive input. CI covers Windows, Linux and macOS.
|
|
90
|
+
|
|
91
|
+
- [Architecture, SDK extension points and Stage 2 handoff](docs/architecture.md)
|
|
92
|
+
- [Rule catalog and remediation guidance](docs/rules.md)
|
|
93
|
+
- [Configuration, precedence and coverage semantics](docs/configuration.md)
|
|
94
|
+
- [Threat model and static analysis limitations](docs/trust-model.md)
|
|
95
|
+
- [Implementation decisions](docs/decisions.md)
|
|
96
|
+
- [MIT license](LICENSE)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# RagGovern
|
|
2
|
+
|
|
3
|
+
RagGovern inventories RAG projects and checks their static configuration locally. It parses source as data and attaches source evidence to every finding. Install the release with `python -m pip install RagGovern`. The Python import and console command are both `ragguard`.
|
|
4
|
+
|
|
5
|
+
Python 3.11+ is supported. Development targets Python 3.12. Run the following commands from this repository in an activated virtual environment.
|
|
6
|
+
|
|
7
|
+
```console
|
|
8
|
+
python -m pip install -e ".[dev]"
|
|
9
|
+
ragguard init
|
|
10
|
+
ragguard config validate
|
|
11
|
+
ragguard scan examples/langchain
|
|
12
|
+
ragguard inspect examples/llamaindex --format mermaid
|
|
13
|
+
ragguard rules --format json
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
For an example with a threshold violation, run `ragguard scan examples/custom --format json`. The logging call that receives retrieved context produces a high-severity RG009 finding and exit code 1. Its evidence includes the relative file, source lines and logging function. The report omits the logged content.
|
|
17
|
+
|
|
18
|
+
## Python SDK
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from ragguard import RAGGuard
|
|
23
|
+
|
|
24
|
+
guard = RAGGuard.from_config(Path("ragguard.yaml"), profile="ci")
|
|
25
|
+
snapshot = guard.inspect("examples/langchain")
|
|
26
|
+
print(snapshot.architecture.mermaid())
|
|
27
|
+
|
|
28
|
+
run = guard.scan("examples/custom")
|
|
29
|
+
for result in run.results:
|
|
30
|
+
for finding in result.findings:
|
|
31
|
+
print(finding.rule_id, finding.evidence.file, finding.evidence.line, finding.remediation)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`RAGGuard.init(path)` creates a policy. `RAGGuard.validate_config(path)` returns the effective typed settings. `guard.rules()` returns the catalog. JSON output is available from the CLI and through Pydantic's `model_dump_json()`.
|
|
35
|
+
|
|
36
|
+
## Working with results
|
|
37
|
+
|
|
38
|
+
Inspection covers Python sources, manifests, structured configuration, documentation and Dockerfile inventory. Recognized RAG roles range from document loading to citation formatting. Directed edges record observed call inputs and receivers. Confidence and diagnostics describe the limits of each assessment. A clean process exit can include unassessed rules.
|
|
39
|
+
|
|
40
|
+
| Command exit | Meaning |
|
|
41
|
+
|---|---|
|
|
42
|
+
| 0 | Command succeeded, below the configured finding threshold |
|
|
43
|
+
| 1 | A finding reached the severity threshold |
|
|
44
|
+
| 2 | Invalid policy, argument or path |
|
|
45
|
+
| 3 | Internal execution or rule error |
|
|
46
|
+
|
|
47
|
+
Use `--output new-report.json` to create a scan report. A plain scan writes to stdout. The static scanner needs no provider credentials or framework installations.
|
|
48
|
+
|
|
49
|
+
## Development and packaging
|
|
50
|
+
|
|
51
|
+
```console
|
|
52
|
+
python -m pytest
|
|
53
|
+
python -m ruff check .
|
|
54
|
+
python -m ruff format --check .
|
|
55
|
+
python -m mypy src
|
|
56
|
+
python -m build
|
|
57
|
+
python benchmarks/scan.py examples 5
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The wheel and source archive are written to `dist/`. The source tree includes three small framework examples and fixtures for incomplete or sensitive input. CI covers Windows, Linux and macOS.
|
|
61
|
+
|
|
62
|
+
- [Architecture, SDK extension points and Stage 2 handoff](docs/architecture.md)
|
|
63
|
+
- [Rule catalog and remediation guidance](docs/rules.md)
|
|
64
|
+
- [Configuration, precedence and coverage semantics](docs/configuration.md)
|
|
65
|
+
- [Threat model and static analysis limitations](docs/trust-model.md)
|
|
66
|
+
- [Implementation decisions](docs/decisions.md)
|
|
67
|
+
- [MIT license](LICENSE)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Run with python benchmarks/scan.py [project] [repetitions]."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from statistics import median
|
|
6
|
+
from time import perf_counter
|
|
7
|
+
|
|
8
|
+
from ragguard import RAGGuard
|
|
9
|
+
from ragguard.config import Settings
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main() -> None:
|
|
13
|
+
parser = argparse.ArgumentParser()
|
|
14
|
+
parser.add_argument("project", nargs="?", type=Path, default=Path("examples"))
|
|
15
|
+
parser.add_argument("repetitions", nargs="?", type=int, default=5)
|
|
16
|
+
args = parser.parse_args()
|
|
17
|
+
if args.repetitions < 1:
|
|
18
|
+
parser.error("repetitions must be positive")
|
|
19
|
+
guard = RAGGuard(Settings(project=args.project))
|
|
20
|
+
times = []
|
|
21
|
+
for _ in range(args.repetitions):
|
|
22
|
+
start = perf_counter()
|
|
23
|
+
run = guard.scan()
|
|
24
|
+
times.append(perf_counter() - start)
|
|
25
|
+
print(f"{len(run.inventory.files)} files, median {median(times):.4f}s")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
if __name__ == "__main__":
|
|
29
|
+
main()
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Static architecture and extension contracts
|
|
2
|
+
|
|
3
|
+
The CLI and Python SDK enter through `RAGGuard`. A scan produces one `Snapshot` and passes it to the assessment engine. Inspection stops at the snapshot. All locations are project-relative and Python line numbers are one-based and inclusive.
|
|
4
|
+
|
|
5
|
+
```mermaid
|
|
6
|
+
flowchart LR
|
|
7
|
+
CLI --> SDK[RAGGuard]
|
|
8
|
+
App[Python caller] --> SDK
|
|
9
|
+
Policy[Validated Settings] --> SDK
|
|
10
|
+
SDK --> Scanner
|
|
11
|
+
Scanner --> Inventory[ProjectInventory]
|
|
12
|
+
Scanner --> Graph[ArchitectureGraph]
|
|
13
|
+
Scanner --> Observations
|
|
14
|
+
Inventory --> Snapshot
|
|
15
|
+
Graph --> Snapshot
|
|
16
|
+
Observations --> Snapshot
|
|
17
|
+
Snapshot --> Engine[StaticAssessment]
|
|
18
|
+
Rules[RuleRegistry] --> Engine
|
|
19
|
+
Engine --> Run[AssessmentRun]
|
|
20
|
+
Run --> Exporter
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## How evidence is produced
|
|
24
|
+
|
|
25
|
+
1. Discovery enumerates regular files in sorted order, prunes protected paths and checks file identity before reading. An inventory entry records discovery even when the file exceeds a parsing limit. Diagnostics identify gaps. Documentation and Dockerfiles are inventoried by name.
|
|
26
|
+
2. Manifest readers inspect project dependency tables, requirement lines, setup.cfg options and selected lockfile package tables. YAML, TOML and JSON readers recognize provider declarations and settings under named sections such as `retrieval` and `generation`. A declaration gives evidence of possible use.
|
|
27
|
+
3. The Python visitor resolves direct imports, aliases, simple assignments and literal keyword arguments. It handles recognized nested option dictionaries and tracks lexical scopes. Calls that consume another detected call's result produce a directed edge, from producer to consumer. A receiver edge represents a method call on a detected component. Separate configuration sections remain independent until there is evidence of wiring.
|
|
28
|
+
4. Each rule evaluates relevant observations or components, counts assessed and unresolved sites, and returns one result. A diagnostic or unknown component prevents a clean pass for the built-in rules. Positive local evidence can establish a pass for the specific criterion in the rule catalog.
|
|
29
|
+
5. Reports retain the inventory, architecture, result per rule and summary. The same input and policy produce the same report. Source locations can change while fingerprints remain stable. A fingerprint hashes the rule ID, relative path and a site anchor. The anchor uses scope, symbol and occurrence within that scope. Moving a file, renaming a symbol or inserting an earlier identical call can change its identity.
|
|
30
|
+
|
|
31
|
+
## Reading the graph
|
|
32
|
+
|
|
33
|
+
A confirmed component has a recognized, qualified technology symbol at a call site. An inferred component has a recognized local naming pattern or configuration section. An unknown component preserves a qualified, unclassified call in a recognized technology namespace. Other unsupported expressions may yield no component. An import confirms an import statement in source. A dependency record alone is inferred. Each technology record retains its own evidence and confidence.
|
|
34
|
+
|
|
35
|
+
`configured` lists recognized keyword names even when their values are expressions. `properties` contains the subset with statically resolved, exportable values. For example, `top_k=choose_limit()` records the setting without guessing its value. A declaration's incoming edges identify observed dependencies. The graph can describe possible wiring in code paths that never run.
|
|
36
|
+
|
|
37
|
+
## Public extension contracts
|
|
38
|
+
|
|
39
|
+
The structural protocols live in `ragguard.adapters`. Application code supplies trusted objects to the SDK. A plugin can be a small class with the methods shown below.
|
|
40
|
+
|
|
41
|
+
| Contract | Method | Integration point |
|
|
42
|
+
|---|---|---|
|
|
43
|
+
| Scanner | `discover(settings) -> Snapshot` | Inject with `RAGGuard(scanner=...)` to contribute evidence. |
|
|
44
|
+
| Rule | `info: RuleInfo` and `evaluate(snapshot, override) -> RuleResult` | Supply an iterable through `rules=`. IDs must be unique across built-ins and extensions. |
|
|
45
|
+
| AssessmentEngine | `assess(snapshot, settings) -> AssessmentRun` | Inject through `engine=` to assess existing evidence. |
|
|
46
|
+
| ReportExporter | `render(run) -> str` | Inject through `exporter=` for SDK file output, or call directly. |
|
|
47
|
+
| RuntimeAdapter | `snapshot() -> Snapshot` | A future host can explicitly obtain evidence and pass it to an engine. |
|
|
48
|
+
|
|
49
|
+
For example, a caller can compose one built-in rule into a deployment-specific engine.
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from ragguard import RAGGuard
|
|
53
|
+
from ragguard.core import StaticAssessment
|
|
54
|
+
from ragguard.rules import RuleRegistry, builtin_rules
|
|
55
|
+
|
|
56
|
+
registry = RuleRegistry(r for r in builtin_rules() if r.info.id == "RG007")
|
|
57
|
+
guard = RAGGuard(engine=StaticAssessment(registry))
|
|
58
|
+
run = guard.scan("examples/custom")
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Stage 2 handoff
|
|
62
|
+
|
|
63
|
+
Start with a versioned fixture containing sanitized query IDs, retrieved document IDs, ranks and expected relevant IDs. Define its provenance and a sibling evidence model before extending the snapshot schema. Implement an opt-in adapter for that fixture, then one offline retrieval evaluation through an assessment engine. Test a known score, an empty retrieval, absent labels and an unavailable adapter. Re-run the Stage 1 suite and compare static output on all three examples.
|
|
64
|
+
|
|
65
|
+
| Future module | Initial boundary |
|
|
66
|
+
|---|---|
|
|
67
|
+
| Evaluation | Consume labeled retrieval observations and record metric units, dataset identity and missing labels. |
|
|
68
|
+
| Security | Add passive checks over sanitized evidence through the existing rule interface. |
|
|
69
|
+
| Risk | Consume findings, confidence and explicitly supplied deployment context. |
|
|
70
|
+
| Governance | Map rule evidence to a versioned control catalog. |
|
|
71
|
+
| Assurance | Track evidence provenance, review decisions and assessment coverage. |
|
|
72
|
+
| Recommendations | Derive remediations from findings, including evidence and rule identity. |
|
|
73
|
+
| Reporting | Render the existing run via a report exporter. |
|
|
74
|
+
|
|
75
|
+
Keep adapters in optional extras once a real integration requires them. Version new serialized fields and exercise older fixtures when changing contracts.
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# Configuration reference
|
|
2
|
+
|
|
3
|
+
A policy file declares integer `version: 1`. The CLI reads `ragguard.yaml` from the invocation directory when present. Use `--config path` to select another file. Passing a project argument selects the scan target. Configuration discovery does not descend into that target. SDK callers select a file explicitly with `RAGGuard.from_config(path)`.
|
|
4
|
+
|
|
5
|
+
## Precedence and paths
|
|
6
|
+
|
|
7
|
+
The effective order is built-in defaults, file settings, selected profile, environment settings, then nonempty CLI options. An explicit `--profile` selects the profile ahead of `RAGGUARD_PROFILE`. Nested maps merge recursively. Sequences replace earlier sequences. A disabled rule always wins over an enabled rule. An empty enabled list skips every rule.
|
|
8
|
+
|
|
9
|
+
File and profile paths resolve against the policy directory. Environment and CLI paths resolve against the invocation directory. The supported environment settings are `RAGGUARD_PROFILE`, `RAGGUARD_PROJECT`, `RAGGUARD_SEVERITY_THRESHOLD` and `RAGGUARD_OUTPUT`. Applications can pass `environment={}` to `from_config` for an isolated policy.
|
|
10
|
+
|
|
11
|
+
```yaml
|
|
12
|
+
version: 1
|
|
13
|
+
project: .
|
|
14
|
+
include: ["**/*"]
|
|
15
|
+
exclude: ["experiments/**", "**/snapshots/**"]
|
|
16
|
+
severity_threshold: high
|
|
17
|
+
disabled_rules: [RG006]
|
|
18
|
+
overrides:
|
|
19
|
+
RG004: {limit: 2048}
|
|
20
|
+
RG005: {limit: 30, severity: high}
|
|
21
|
+
logging: {level: WARNING}
|
|
22
|
+
profiles:
|
|
23
|
+
ci:
|
|
24
|
+
severity_threshold: medium
|
|
25
|
+
limits: {max_files: 1200}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
| Setting | Meaning and defaults |
|
|
29
|
+
|---|---|
|
|
30
|
+
| project | Local project directory, default `.`. |
|
|
31
|
+
| include, exclude | Case-sensitive patterns on slash-separated relative paths. Prefix `**/` also permits a root-level match. Wildcards use Python fnmatch semantics, so `*` can span separators. Exclusion takes precedence. |
|
|
32
|
+
| enabled_rules, disabled_rules | Optional allowlist and denylist of IDs. The default enables all built-ins. Unknown IDs in the selected policy fail validation. |
|
|
33
|
+
| severity_threshold | Lowest severity that produces exit 1. Ordered levels are low, medium, high and critical. Default high. |
|
|
34
|
+
| overrides | Per-rule severity and numeric policy limit. RG003, RG004 and RG005 accept positive limits. |
|
|
35
|
+
| logging.level | WARNING, INFO or DEBUG. INFO emits an aggregate scan summary to stderr. |
|
|
36
|
+
| output | Optional new report path. The parent directory must exist. An existing file produces an input error. It applies to scan only. |
|
|
37
|
+
| profiles | Named overrides for the same settings. |
|
|
38
|
+
| limits.max_file_bytes | 512,000 bytes per parsed file, maximum 4,000,000. |
|
|
39
|
+
| limits.max_total_bytes | 32,000,000 bytes per scan, maximum 256,000,000. |
|
|
40
|
+
| limits.max_files | 4,000 inventory entries, maximum 100,000. |
|
|
41
|
+
| limits.max_entries | 40,000 directory entries examined, maximum 500,000. |
|
|
42
|
+
| limits.max_nodes | 30,000 AST nodes or metadata fields per file, maximum 100,000. |
|
|
43
|
+
|
|
44
|
+
Validate a policy using `ragguard config validate path/to/ragguard.yaml --profile ci`. The generated machine-readable schema ships in the repository and wheel. [Version 1 JSON Schema](../schemas/ragguard-v1.json)
|
|
45
|
+
|
|
46
|
+
## Assessment statuses and exit codes
|
|
47
|
+
|
|
48
|
+
| Rule status | Meaning |
|
|
49
|
+
|---|---|
|
|
50
|
+
| passed | At least one relevant site satisfied the static criterion and the rule has no unresolved sites or coverage gaps. |
|
|
51
|
+
| failed | At least one finding was emitted. The result can also contain unresolved sites. |
|
|
52
|
+
| skipped | Policy disabled this rule. |
|
|
53
|
+
| error | The rule raised an internal exception. Other rules can still return evidence. |
|
|
54
|
+
| not_applicable | Recognized evidence exists in the snapshot, with no applicable sites for this rule. |
|
|
55
|
+
| not_assessed | Insufficient evidence, unresolved values or incomplete coverage prevent a conclusion. |
|
|
56
|
+
|
|
57
|
+
Exit 0 means the command completed below the configured finding threshold. Exit 1 means a finding reached that threshold. Exit 2 means invalid arguments, policy or paths. Exit 3 means an internal failure, including a rule error. Incomplete assessments can exit 0. Consumers requiring coverage should inspect `summary.incomplete`, `results[].status`, unresolved counts and diagnostics. Disabling rules deliberately reduces assessment scope.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Implementation decisions
|
|
2
|
+
|
|
3
|
+
## ADR 001 · Keep the assessment local and provider independent
|
|
4
|
+
|
|
5
|
+
Stage 1 needs to inspect projects whose dependencies may be missing. The scanner consumes Python source and data formats through standard-library parsers and safe YAML. Provider SDKs remain optional. Integrations contribute sanitized snapshots through explicit Python protocols. This permits static use on an offline checkout and places runtime collection behind a separate interface.
|
|
6
|
+
|
|
7
|
+
## ADR 002 · Preserve uncertainty in the public data model
|
|
8
|
+
|
|
9
|
+
Inventory evidence, architecture edges and assessment conclusions have different meanings. Each component records detection status and confidence. Each rule reports an execution status, assessed count and unresolved count. A missing setting can generate a review request. An absent observation alone cannot establish a pass. Thresholds control process exit independently from coverage.
|
|
10
|
+
|
|
11
|
+
## ADR 003 · Prefer stable, reviewable report identities
|
|
12
|
+
|
|
13
|
+
Relative paths, lexical scopes, canonical symbols and site ordinals determine fingerprints. Excluding line numbers lets comparisons survive comments and blank lines. Reordering identical sites or moving a file can change identity. Deterministic traversal and declaration ordering permit exact JSON comparisons on identical input.
|
|
14
|
+
|
|
15
|
+
## ADR 004 · Ship a small installable core
|
|
16
|
+
|
|
17
|
+
The distribution name is `RagGovern`. The Python import and console command are `ragguard`. Hatchling builds the src-layout package. The wheel includes type information and the policy schema. The source distribution also carries examples, fixtures, benchmarks and documentation. Stage 1 uses the MIT license.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# Static rule catalog
|
|
2
|
+
|
|
3
|
+
The catalog ships eleven checks. A rule's confidence describes its static signal. Each finding also carries a classification, source evidence, impact, remediation and fingerprint.
|
|
4
|
+
|
|
5
|
+
Policy limits use tokens for RG003, the splitter's native size unit for RG004, and number of results for RG005. Tune them to the project's retrieval and cost requirements.
|
|
6
|
+
|
|
7
|
+
## RG001 · Missing timeout
|
|
8
|
+
|
|
9
|
+
Reliability · medium severity · medium confidence
|
|
10
|
+
|
|
11
|
+
Check the visible request deadline. Inspect timeout on generation and embedding declarations.
|
|
12
|
+
|
|
13
|
+
A stalled backend can hold request capacity. Set a finite timeout or document the upstream deadline.
|
|
14
|
+
|
|
15
|
+
## RG002 · Missing retry policy
|
|
16
|
+
|
|
17
|
+
Reliability · low severity · medium confidence
|
|
18
|
+
|
|
19
|
+
Check the visible retry budget. Inspect max_retries on generation and embedding declarations.
|
|
20
|
+
|
|
21
|
+
Transient errors may interrupt requests. Configure bounded retries or document deliberate fail-fast behavior.
|
|
22
|
+
|
|
23
|
+
## RG003 · Large context budget
|
|
24
|
+
|
|
25
|
+
Cost · medium severity · medium confidence
|
|
26
|
+
|
|
27
|
+
Compare explicit context budgets to a token limit. Flag context_size above the policy limit.
|
|
28
|
+
|
|
29
|
+
Large contexts may increase latency and cost. Measure token usage and set an appropriate context budget.
|
|
30
|
+
|
|
31
|
+
The default upper limit is 16,000.
|
|
32
|
+
|
|
33
|
+
## RG004 · Suspicious chunk geometry
|
|
34
|
+
|
|
35
|
+
Retrieval · medium severity · high confidence
|
|
36
|
+
|
|
37
|
+
Check chunk size and overlap. Check size against the policy and overlap against size.
|
|
38
|
+
|
|
39
|
+
Poor chunk boundaries may impair retrieval or duplicate context. Choose a positive size and an overlap smaller than it. Tune for the splitter's units.
|
|
40
|
+
|
|
41
|
+
The default upper limit is 4,096.
|
|
42
|
+
|
|
43
|
+
## RG005 · Retrieval bound
|
|
44
|
+
|
|
45
|
+
Retrieval · medium severity · medium confidence
|
|
46
|
+
|
|
47
|
+
Check explicit retrieval bounds. Check top_k against a policy range and request review for absent bounds.
|
|
48
|
+
|
|
49
|
+
Large result sets can saturate context and increase latency. Set top_k or verify and document backend limits.
|
|
50
|
+
|
|
51
|
+
The default upper limit is 100.
|
|
52
|
+
|
|
53
|
+
## RG006 · Hardcoded model identifier
|
|
54
|
+
|
|
55
|
+
Configuration · low severity · high confidence
|
|
56
|
+
|
|
57
|
+
Locate source-level model selection. Recognize model keywords resolving to source string literals.
|
|
58
|
+
|
|
59
|
+
Model changes may require a code release. Move identifiers to versioned deployment settings where appropriate.
|
|
60
|
+
|
|
61
|
+
## RG007 · Unsafe or unresolved YAML loader
|
|
62
|
+
|
|
63
|
+
Security · high severity · high confidence
|
|
64
|
+
|
|
65
|
+
Check YAML deserialization calls. Resolve PyYAML imports and inspect the Loader argument.
|
|
66
|
+
|
|
67
|
+
Unsafe construction can instantiate objects from untrusted input. Use yaml.safe_load or SafeLoader for untrusted YAML.
|
|
68
|
+
|
|
69
|
+
[Provider documentation](https://pyyaml.org/wiki/PyYAMLDocumentation)
|
|
70
|
+
|
|
71
|
+
## RG008 · Missing local error handler
|
|
72
|
+
|
|
73
|
+
Reliability · low severity · medium confidence
|
|
74
|
+
|
|
75
|
+
Review error boundaries. Check retrieval and generation calls for an enclosing try body with handlers.
|
|
76
|
+
|
|
77
|
+
Backend failures may propagate to users. Handle expected exceptions at a suitable application boundary.
|
|
78
|
+
|
|
79
|
+
## RG009 · Potentially sensitive logging
|
|
80
|
+
|
|
81
|
+
Privacy · high severity · medium confidence
|
|
82
|
+
|
|
83
|
+
Identify logging of sensitive inputs. Match logging arguments containing sensitive identifiers or recognized credentials.
|
|
84
|
+
|
|
85
|
+
Logs may retain user documents or secrets. Log identifiers and aggregate counts. Redact private content before logging.
|
|
86
|
+
|
|
87
|
+
## RG010 · Source attribution needs review
|
|
88
|
+
|
|
89
|
+
Assurance · low severity · low confidence
|
|
90
|
+
|
|
91
|
+
Look for source attribution alongside generation. Check for recognized citation calls in the same lexical scope.
|
|
92
|
+
|
|
93
|
+
Users may be unable to trace an answer to its sources. Carry document identifiers into answer citations and validate them.
|
|
94
|
+
|
|
95
|
+
## RG011 · Implicit component configuration
|
|
96
|
+
|
|
97
|
+
Configuration · low severity · medium confidence
|
|
98
|
+
|
|
99
|
+
Review implicit model and retrieval settings. Check for explicit model selection or retrieval count/threshold keywords.
|
|
100
|
+
|
|
101
|
+
Changing dependency defaults may alter behavior. Pin settings explicitly or record the defaults relied upon.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Trust boundaries and limitations
|
|
2
|
+
|
|
3
|
+
**Trusted inputs** include the installed package and its dependencies, the invoking application, operator policy and explicitly supplied plugin objects. A policy can select a local target and report destination. Run the installed CLI from a trusted working directory and pass an unfamiliar checkout as a project argument. The scanner treats target modules, dependency manifests and target configuration as data.
|
|
4
|
+
|
|
5
|
+
**Read and write behavior.** Scanning uses directory enumeration, bounded regular-file reads, Python AST parsing and local data parsers. Framework imports in a target never trigger dependency installation or dynamic plugin discovery. The static engine makes no network calls. The only application writes are exclusive creation of the starter file and an explicitly configured report. CLI JSON is emitted to stdout and aggregate logs use stderr.
|
|
6
|
+
|
|
7
|
+
**Filesystem coverage.** Discovery skips symbolic links and Windows reparse points, checks path resolution and compares opened file identity with the enumerated entry. It prunes common virtual environments, Git internals, caches, generated outputs, credential directories and dotenv files. A pyvenv.cfg marker prunes arbitrarily named virtual environments. Exclusions reduce coverage. Read failures, binary bytes in parsed content and reached limits produce diagnostics. Docs and Dockerfiles are inventoried without reading their bodies.
|
|
8
|
+
|
|
9
|
+
**Evidence minimization.** Evidence contains a structural signal, sanitized relative path and optional line range. Environment lookups contribute variable names. Recognized credential fields contribute their category. Arbitrary source snippets, environment values, prompt text and credential-field values are excluded from the report. Model identifiers and selected numeric settings are intentional report content. A central redactor masks common token strings, connection URLs, credential assignments and control characters. Organization-specific secrets deliberately placed in filenames, identifiers or ordinary model-name fields may require a private scanner or exporter. Treat reports as project metadata.
|
|
10
|
+
|
|
11
|
+
**Resource limits.** Traversal has entry, file and byte budgets. Python source has token and AST bounds. Configuration files use safe YAML construction with alias, nesting and event limits. Parser failures produce sanitized diagnostics. Run analysis on a stable checkout. A concurrently modified filesystem or a hostile process with the same OS permissions falls outside this trust boundary. For independently hostile tenants, use separate OS isolation and external memory and time limits.
|
|
12
|
+
|
|
13
|
+
**Interpretation.** Imports confirm declarations. A statically resolved keyword records a value at that site. An omitted keyword can be supplied by a caller, framework default, proxy, deployment configuration or wrapper. Dynamic imports, reflection, arbitrary control flow, class dispatch, cross-module data flow and provider defaults have limited or no coverage. The scanner recognizes a finite symbol catalog. Model invocations, retrieval quality, token consumption, citation correctness and regulatory compliance require additional evidence.
|
|
14
|
+
|
|
15
|
+
**Comparisons.** Report schema version 1 contains no timestamps or machine-specific root path. Compare findings by fingerprint within the same rule implementation and policy. Preserve the package version and policy alongside a report when comparing assessments over time.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def answer(query, services):
|
|
6
|
+
documents = services.retrieve_documents(query, top_k=8)
|
|
7
|
+
context = services.assemble_context(documents)
|
|
8
|
+
logging.info("Retrieved context %s", context)
|
|
9
|
+
result = services.generate_answer(context, model=os.getenv("GENERATION_MODEL"))
|
|
10
|
+
return services.add_citations(result, documents)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Static fixture. No installation of framework packages is needed to scan it."""
|
|
2
|
+
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
|
|
3
|
+
from langchain_community.vectorstores import FAISS
|
|
4
|
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def configure(documents):
|
|
8
|
+
splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=80)
|
|
9
|
+
chunks = splitter.split_documents(documents)
|
|
10
|
+
embedding = OpenAIEmbeddings(model="text-embedding-3-small")
|
|
11
|
+
index = FAISS.from_documents(chunks, embedding)
|
|
12
|
+
retriever = index.as_retriever(search_kwargs={"k": 6})
|
|
13
|
+
model = ChatOpenAI(model="gpt-4o-mini", temperature=0, timeout=20, max_retries=2)
|
|
14
|
+
return retriever, model
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
|
|
2
|
+
from llama_index.core.node_parser import SentenceSplitter
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def build(directory):
|
|
6
|
+
documents = SimpleDirectoryReader(directory).load_data()
|
|
7
|
+
splitter = SentenceSplitter(chunk_size=1024, chunk_overlap=32)
|
|
8
|
+
index = VectorStoreIndex.from_documents(documents, transformations=[splitter])
|
|
9
|
+
return index.as_retriever(similarity_top_k=4)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "RagGovern"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Local, evidence-backed static assessment for RAG projects"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
dependencies = ["pydantic>=2.9,<3", "typer>=0.16,<1", "rich>=13,<16", "PyYAML>=6,<7"]
|
|
13
|
+
classifiers = ["Development Status :: 3 - Alpha", "Programming Language :: Python :: 3"]
|
|
14
|
+
|
|
15
|
+
[project.optional-dependencies]
|
|
16
|
+
dev = ["pytest>=8", "ruff>=0.9", "mypy>=1.13", "types-PyYAML", "build>=1.2", "hatchling>=1.25"]
|
|
17
|
+
langchain = ["langchain-openai", "langchain-text-splitters", "langchain-community", "faiss-cpu"]
|
|
18
|
+
llamaindex = ["llama-index-core"]
|
|
19
|
+
[project.scripts]
|
|
20
|
+
ragguard = "ragguard.cli:app"
|
|
21
|
+
|
|
22
|
+
[tool.hatch.build.targets.wheel]
|
|
23
|
+
packages = ["src/ragguard"]
|
|
24
|
+
[tool.hatch.build.targets.wheel.force-include]
|
|
25
|
+
"schemas/ragguard-v1.json" = "ragguard/schemas/ragguard-v1.json"
|
|
26
|
+
[tool.hatch.build.targets.sdist]
|
|
27
|
+
include = ["/src", "/tests", "/examples", "/docs", "/schemas", "/benchmarks", "/README.md", "/LICENSE", "/pyproject.toml"]
|
|
28
|
+
[tool.ruff]
|
|
29
|
+
target-version = "py311"
|
|
30
|
+
line-length = 100
|
|
31
|
+
extend-exclude = ["tests/fixtures", "examples", ".cache"]
|
|
32
|
+
[tool.ruff.lint]
|
|
33
|
+
select = ["E4", "E7", "E9", "F", "I", "B", "UP"]
|
|
34
|
+
[tool.mypy]
|
|
35
|
+
python_version = "3.11"
|
|
36
|
+
strict = true
|
|
37
|
+
files = ["src"]
|
|
38
|
+
[tool.pytest.ini_options]
|
|
39
|
+
testpaths = ["tests"]
|
|
40
|
+
addopts = "-ra"
|