agentforge-guard-presidio 0.2.3__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.
@@ -0,0 +1,49 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+
7
+ # Distribution / packaging
8
+ .Python
9
+ build/
10
+ dist/
11
+ *.egg-info/
12
+ *.egg
13
+ wheels/
14
+ sdist/
15
+ share/python-wheels/
16
+
17
+ # uv
18
+ .venv/
19
+ uv-cache/
20
+
21
+ # Testing
22
+ .pytest_cache/
23
+ .coverage
24
+ .coverage.*
25
+ htmlcov/
26
+ coverage.xml
27
+ .tox/
28
+ .mypy_cache/
29
+ .ruff_cache/
30
+ .hypothesis/
31
+
32
+ # Environment
33
+ .env
34
+ .envrc
35
+
36
+ # Editors
37
+ .vscode/
38
+ .idea/
39
+ *.swp
40
+ *.swo
41
+ *~
42
+
43
+ # OS
44
+ .DS_Store
45
+ Thumbs.db
46
+
47
+ # Project-local
48
+ *.local
49
+ .agentforge-state/.session-cache
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,52 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentforge-guard-presidio
3
+ Version: 0.2.3
4
+ Summary: Microsoft Presidio PII detector for AgentForge guardrails
5
+ Project-URL: Homepage, https://github.com/Scaffoldic/agentforge-py
6
+ Project-URL: Repository, https://github.com/Scaffoldic/agentforge-py
7
+ Project-URL: Documentation, https://github.com/Scaffoldic/agentforge-py
8
+ Project-URL: Changelog, https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/Scaffoldic/agentforge-py/issues
10
+ Author: The AgentForge Authors
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: agent,ai,guardrails,pii,presidio
14
+ Classifier: Development Status :: 2 - Pre-Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Security
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.13
23
+ Requires-Dist: agentforge-core~=0.2.3
24
+ Description-Content-Type: text/markdown
25
+
26
+ # agentforge-guard-presidio
27
+
28
+ [Microsoft Presidio](https://microsoft.github.io/presidio/) PII
29
+ detection + anonymisation for AgentForge guardrails (feat-018).
30
+
31
+ Adds the `presidio` validator to the `agentforge.yaml`
32
+ `modules.guardrails.output` section:
33
+
34
+ ```yaml
35
+ modules:
36
+ guardrails:
37
+ output:
38
+ - presidio:
39
+ entities: ["EMAIL_ADDRESS", "PHONE_NUMBER", "PERSON",
40
+ "CREDIT_CARD", "US_SSN", "IP_ADDRESS"]
41
+ score_threshold: 0.5
42
+ action: "redact" # "redact" | "score-only"
43
+ ```
44
+
45
+ ```bash
46
+ agentforge add module guard-presidio
47
+ ```
48
+
49
+ The default `score_threshold` of `0.5` is Presidio's recommended
50
+ balance between recall and false positives. Set lower for stricter
51
+ redaction, higher to reduce noise. `action: "score-only"` reports
52
+ the violations without modifying the content.
@@ -0,0 +1,27 @@
1
+ # agentforge-guard-presidio
2
+
3
+ [Microsoft Presidio](https://microsoft.github.io/presidio/) PII
4
+ detection + anonymisation for AgentForge guardrails (feat-018).
5
+
6
+ Adds the `presidio` validator to the `agentforge.yaml`
7
+ `modules.guardrails.output` section:
8
+
9
+ ```yaml
10
+ modules:
11
+ guardrails:
12
+ output:
13
+ - presidio:
14
+ entities: ["EMAIL_ADDRESS", "PHONE_NUMBER", "PERSON",
15
+ "CREDIT_CARD", "US_SSN", "IP_ADDRESS"]
16
+ score_threshold: 0.5
17
+ action: "redact" # "redact" | "score-only"
18
+ ```
19
+
20
+ ```bash
21
+ agentforge add module guard-presidio
22
+ ```
23
+
24
+ The default `score_threshold` of `0.5` is Presidio's recommended
25
+ balance between recall and false positives. Set lower for stricter
26
+ redaction, higher to reduce noise. `action: "score-only"` reports
27
+ the violations without modifying the content.
@@ -0,0 +1,55 @@
1
+ # agentforge-guard-presidio — Microsoft Presidio PII detection.
2
+ #
3
+ # Tier-3 sister package adding research-grade PII detection +
4
+ # anonymisation on top of the built-in `pii_redact_basic`. Wraps
5
+ # `presidio-analyzer` + `presidio-anonymizer`.
6
+
7
+ [project]
8
+ name = "agentforge-guard-presidio"
9
+ version = "0.2.3"
10
+ description = "Microsoft Presidio PII detector for AgentForge guardrails"
11
+ readme = "README.md"
12
+ requires-python = ">=3.13"
13
+ license = "Apache-2.0"
14
+ license-files = ["LICENSE"]
15
+ authors = [
16
+ {name = "The AgentForge Authors"},
17
+ ]
18
+ keywords = ["ai", "agent", "guardrails", "presidio", "pii"]
19
+ classifiers = [
20
+ "Development Status :: 2 - Pre-Alpha",
21
+ "Intended Audience :: Developers",
22
+ "License :: OSI Approved :: Apache Software License",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: Software Development :: Libraries :: Python Modules",
26
+ "Topic :: Security",
27
+ "Typing :: Typed",
28
+ ]
29
+
30
+ dependencies = [
31
+ "agentforge-core ~= 0.2.3",
32
+ ]
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/Scaffoldic/agentforge-py"
36
+ Repository = "https://github.com/Scaffoldic/agentforge-py"
37
+ Documentation = "https://github.com/Scaffoldic/agentforge-py"
38
+ Changelog = "https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md"
39
+ Issues = "https://github.com/Scaffoldic/agentforge-py/issues"
40
+
41
+ [project.entry-points."agentforge.guardrails.output"]
42
+ presidio = "agentforge_guard_presidio.validators:PresidioOutput"
43
+
44
+ [tool.uv.sources]
45
+ agentforge-core = { workspace = true }
46
+
47
+ [build-system]
48
+ requires = ["hatchling>=1.27"]
49
+ build-backend = "hatchling.build"
50
+
51
+ [tool.hatch.build.targets.wheel]
52
+ packages = ["src/agentforge_guard_presidio"]
53
+
54
+ [tool.hatch.build.targets.sdist]
55
+ include = ["src/agentforge_guard_presidio", "tests", "README.md", "LICENSE"]
@@ -0,0 +1,7 @@
1
+ """Microsoft Presidio PII detection wired as an AgentForge OutputValidator."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from agentforge_guard_presidio.validators import PresidioOutput
6
+
7
+ __all__ = ["PresidioOutput"]
@@ -0,0 +1,104 @@
1
+ """Internal Presidio runner protocol (feat-018).
2
+
3
+ `PresidioOutput` consumes a `PresidioRunner` so tests inject a
4
+ fake without requiring `presidio-analyzer` to be installed.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from typing import Protocol
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class PresidioFinding:
15
+ """Single PII match: entity type, span, confidence."""
16
+
17
+ entity_type: str
18
+ start: int
19
+ end: int
20
+ score: float
21
+
22
+
23
+ class PresidioRunner(Protocol):
24
+ """Slice of `presidio_analyzer.AnalyzerEngine` + anonymizer we
25
+ depend on.
26
+
27
+ `analyze(text, entities, score_threshold)` returns the matches
28
+ above the threshold. `anonymize(text, findings)` returns the
29
+ anonymised text with each match replaced by `<KIND>`.
30
+ """
31
+
32
+ async def analyze(
33
+ self,
34
+ text: str,
35
+ entities: list[str],
36
+ score_threshold: float,
37
+ ) -> list[PresidioFinding]: ...
38
+
39
+ async def anonymize(
40
+ self,
41
+ text: str,
42
+ findings: list[PresidioFinding],
43
+ ) -> str: ...
44
+
45
+
46
+ class _RealPresidioRunner:
47
+ """Production runner — lazy-imports `presidio_analyzer` and
48
+ `presidio_anonymizer`. Surfaces a clear `ModuleError` with pip
49
+ remediation if either isn't installed."""
50
+
51
+ def __init__(self) -> None:
52
+ self._analyzer: object | None = None
53
+ self._anonymizer: object | None = None
54
+
55
+ async def analyze(
56
+ self,
57
+ text: str,
58
+ entities: list[str],
59
+ score_threshold: float,
60
+ ) -> list[PresidioFinding]:
61
+ analyzer = self._get_analyzer()
62
+ results = analyzer.analyze(text=text, entities=entities, language="en") # type: ignore[attr-defined]
63
+ return [
64
+ PresidioFinding(
65
+ entity_type=r.entity_type,
66
+ start=r.start,
67
+ end=r.end,
68
+ score=float(r.score),
69
+ )
70
+ for r in results
71
+ if float(r.score) >= score_threshold
72
+ ]
73
+
74
+ async def anonymize(
75
+ self,
76
+ text: str,
77
+ findings: list[PresidioFinding],
78
+ ) -> str:
79
+ # Sort by start descending so replacements don't shift
80
+ # subsequent indices.
81
+ out = text
82
+ for f in sorted(findings, key=lambda x: x.start, reverse=True):
83
+ out = out[: f.start] + f"<{f.entity_type}>" + out[f.end :]
84
+ return out
85
+
86
+ def _get_analyzer(self) -> object:
87
+ if self._analyzer is not None:
88
+ return self._analyzer
89
+ try:
90
+ from presidio_analyzer import AnalyzerEngine # noqa: PLC0415
91
+ except ImportError as exc:
92
+ from agentforge_core.production.exceptions import ModuleError # noqa: PLC0415
93
+
94
+ msg = (
95
+ "presidio-analyzer is not installed. Install via "
96
+ "`pip install presidio-analyzer presidio-anonymizer` to "
97
+ "use `PresidioOutput`."
98
+ )
99
+ raise ModuleError(msg) from exc
100
+ self._analyzer = AnalyzerEngine()
101
+ return self._analyzer
102
+
103
+
104
+ __all__ = ["PresidioFinding", "PresidioRunner"]
@@ -0,0 +1,84 @@
1
+ """`PresidioOutput` — Microsoft Presidio adapter (feat-018)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, ClassVar
6
+
7
+ from agentforge_core.contracts.guardrails import OutputValidator
8
+ from agentforge_core.values.guardrails import ValidationResult
9
+
10
+ from agentforge_guard_presidio._runner import PresidioRunner
11
+
12
+ _DEFAULT_ENTITIES: tuple[str, ...] = (
13
+ "EMAIL_ADDRESS",
14
+ "PHONE_NUMBER",
15
+ "CREDIT_CARD",
16
+ "US_SSN",
17
+ "IP_ADDRESS",
18
+ )
19
+
20
+
21
+ class PresidioOutput(OutputValidator):
22
+ """Detect + (optionally) redact PII in the model's output."""
23
+
24
+ name: ClassVar[str] = "presidio"
25
+ description: ClassVar[str] = (
26
+ "Microsoft Presidio adapter — detects PII entities above "
27
+ "`score_threshold` and either replaces them with `<KIND>` "
28
+ "placeholders (`action: redact`) or reports them without "
29
+ "modification (`action: score-only`)."
30
+ )
31
+ cost_estimate_ms: ClassVar[int] = 40
32
+
33
+ def __init__(
34
+ self,
35
+ *,
36
+ entities: list[str] | None = None,
37
+ score_threshold: float = 0.5,
38
+ action: str = "redact",
39
+ runner: PresidioRunner | None = None,
40
+ ) -> None:
41
+ self._entities = list(entities or _DEFAULT_ENTITIES)
42
+ self._threshold = float(score_threshold)
43
+ if action not in {"redact", "score-only"}:
44
+ msg = f"unknown action {action!r}; expected 'redact' or 'score-only'."
45
+ raise ValueError(msg)
46
+ self._action = action
47
+ self._runner = runner if runner is not None else self._default_runner()
48
+
49
+ def _default_runner(self) -> PresidioRunner:
50
+ from agentforge_guard_presidio._runner import _RealPresidioRunner # noqa: PLC0415
51
+
52
+ return _RealPresidioRunner()
53
+
54
+ async def validate(self, content: str, context: dict[str, Any]) -> ValidationResult:
55
+ del context
56
+ findings = await self._runner.analyze(content, self._entities, self._threshold)
57
+ if not findings:
58
+ return ValidationResult.ok()
59
+
60
+ violations = tuple({f.entity_type for f in findings})
61
+ redacted: str | None = None
62
+ if self._action == "redact":
63
+ redacted = await self._runner.anonymize(content, findings)
64
+
65
+ return ValidationResult(
66
+ passed=False,
67
+ score=max(0.0, 1.0 - max(f.score for f in findings)),
68
+ violations=violations,
69
+ redacted_content=redacted,
70
+ metadata={
71
+ "findings": [
72
+ {
73
+ "entity_type": f.entity_type,
74
+ "start": f.start,
75
+ "end": f.end,
76
+ "score": f.score,
77
+ }
78
+ for f in findings
79
+ ],
80
+ },
81
+ )
82
+
83
+
84
+ __all__ = ["PresidioOutput"]
@@ -0,0 +1,113 @@
1
+ """Tests for `PresidioOutput` (feat-018 chunk 6)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ import pytest
8
+ from agentforge.testing import run_output_validator_conformance
9
+ from agentforge_guard_presidio import PresidioOutput
10
+ from agentforge_guard_presidio._runner import PresidioFinding
11
+
12
+
13
+ @dataclass
14
+ class PresidioFakeRunner:
15
+ """Inline fake runner — lives in this module to avoid the
16
+ workspace root conftest.py shadowing fixtures."""
17
+
18
+ findings: list[PresidioFinding] = field(default_factory=list)
19
+ received: list[str] = field(default_factory=list)
20
+
21
+ async def analyze(
22
+ self,
23
+ text: str,
24
+ entities: list[str],
25
+ score_threshold: float,
26
+ ) -> list[PresidioFinding]:
27
+ self.received.append(text)
28
+ return [
29
+ f for f in self.findings if f.entity_type in entities and f.score >= score_threshold
30
+ ]
31
+
32
+ async def anonymize(
33
+ self,
34
+ text: str,
35
+ findings: list[PresidioFinding],
36
+ ) -> str:
37
+ out = text
38
+ for f in sorted(findings, key=lambda x: x.start, reverse=True):
39
+ out = out[: f.start] + f"<{f.entity_type}>" + out[f.end :]
40
+ return out
41
+
42
+
43
+ @pytest.mark.asyncio
44
+ async def test_presidio_passes_clean_output() -> None:
45
+ fake = PresidioFakeRunner()
46
+ v = PresidioOutput(runner=fake)
47
+ result = await v.validate("The weather is nice today.", {})
48
+ assert result.passed
49
+
50
+
51
+ @pytest.mark.asyncio
52
+ async def test_presidio_detects_and_redacts_email() -> None:
53
+ fake = PresidioFakeRunner(
54
+ findings=[
55
+ PresidioFinding(entity_type="EMAIL_ADDRESS", start=13, end=30, score=0.95),
56
+ ],
57
+ )
58
+ v = PresidioOutput(runner=fake)
59
+ result = await v.validate("Email me at alice@example.com.", {})
60
+ assert not result.passed
61
+ assert "EMAIL_ADDRESS" in result.violations
62
+ assert "<EMAIL_ADDRESS>" in result.redacted_content # type: ignore[operator]
63
+
64
+
65
+ @pytest.mark.asyncio
66
+ async def test_presidio_score_only_action_no_redaction() -> None:
67
+ fake = PresidioFakeRunner(
68
+ findings=[
69
+ PresidioFinding(entity_type="EMAIL_ADDRESS", start=0, end=5, score=0.9),
70
+ ],
71
+ )
72
+ v = PresidioOutput(runner=fake, action="score-only")
73
+ result = await v.validate("alice@example.com is here", {})
74
+ assert not result.passed
75
+ assert result.redacted_content is None
76
+
77
+
78
+ def test_presidio_rejects_unknown_action() -> None:
79
+ with pytest.raises(ValueError, match="unknown action"):
80
+ PresidioOutput(action="block")
81
+
82
+
83
+ class _ContentAwareFake:
84
+ """Returns findings only when the text contains an `@`. Lets the
85
+ conformance suite see a benign-pass + obvious-fail pair."""
86
+
87
+ async def analyze(
88
+ self,
89
+ text: str,
90
+ entities: list[str],
91
+ score_threshold: float,
92
+ ) -> list[PresidioFinding]:
93
+ del entities, score_threshold
94
+ if "@" in text:
95
+ return [PresidioFinding(entity_type="EMAIL_ADDRESS", start=0, end=10, score=0.99)]
96
+ return []
97
+
98
+ async def anonymize(
99
+ self,
100
+ text: str,
101
+ findings: list[PresidioFinding],
102
+ ) -> str:
103
+ del findings
104
+ return text.replace("@", "<EMAIL_ADDRESS>")
105
+
106
+
107
+ @pytest.mark.asyncio
108
+ async def test_presidio_passes_conformance_suite() -> None:
109
+ await run_output_validator_conformance(
110
+ PresidioOutput(runner=_ContentAwareFake()),
111
+ benign="this is fine",
112
+ obvious_violation="alice@example.com is in this text",
113
+ )