flowharness-inspection 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.
Files changed (57) hide show
  1. flowharness_inspection-0.1.0/LICENSE +202 -0
  2. flowharness_inspection-0.1.0/PKG-INFO +25 -0
  3. flowharness_inspection-0.1.0/README.md +10 -0
  4. flowharness_inspection-0.1.0/pyproject.toml +30 -0
  5. flowharness_inspection-0.1.0/pyproject.toml.orig +29 -0
  6. flowharness_inspection-0.1.0/src/inspection/__init__.py +5 -0
  7. flowharness_inspection-0.1.0/src/inspection/api/__init__.py +1 -0
  8. flowharness_inspection-0.1.0/src/inspection/api/exit_codes.py +17 -0
  9. flowharness_inspection-0.1.0/src/inspection/application/__init__.py +1 -0
  10. flowharness_inspection-0.1.0/src/inspection/application/services.py +98 -0
  11. flowharness_inspection-0.1.0/src/inspection/domain/__init__.py +1 -0
  12. flowharness_inspection-0.1.0/src/inspection/domain/agent_config.py +157 -0
  13. flowharness_inspection-0.1.0/src/inspection/domain/agent_config_reader.py +352 -0
  14. flowharness_inspection-0.1.0/src/inspection/domain/badge.py +45 -0
  15. flowharness_inspection-0.1.0/src/inspection/domain/baseline.py +108 -0
  16. flowharness_inspection-0.1.0/src/inspection/domain/checks/__init__.py +50 -0
  17. flowharness_inspection-0.1.0/src/inspection/domain/checks/context.py +29 -0
  18. flowharness_inspection-0.1.0/src/inspection/domain/checks/contradiction.py +56 -0
  19. flowharness_inspection-0.1.0/src/inspection/domain/checks/contradiction_policy.py +57 -0
  20. flowharness_inspection-0.1.0/src/inspection/domain/checks/cost.py +246 -0
  21. flowharness_inspection-0.1.0/src/inspection/domain/checks/divergence.py +71 -0
  22. flowharness_inspection-0.1.0/src/inspection/domain/checks/duplication.py +37 -0
  23. flowharness_inspection-0.1.0/src/inspection/domain/checks/hygiene.py +59 -0
  24. flowharness_inspection-0.1.0/src/inspection/domain/checks/injection.py +48 -0
  25. flowharness_inspection-0.1.0/src/inspection/domain/checks/injection_corpus.py +53 -0
  26. flowharness_inspection-0.1.0/src/inspection/domain/checks/leakage.py +116 -0
  27. flowharness_inspection-0.1.0/src/inspection/domain/checks/leakage_corpus.py +133 -0
  28. flowharness_inspection-0.1.0/src/inspection/domain/checks/orphans.py +64 -0
  29. flowharness_inspection-0.1.0/src/inspection/domain/checks/quarantine.py +96 -0
  30. flowharness_inspection-0.1.0/src/inspection/domain/checks/quarantine_policy.py +45 -0
  31. flowharness_inspection-0.1.0/src/inspection/domain/metrics/__init__.py +5 -0
  32. flowharness_inspection-0.1.0/src/inspection/domain/metrics/base.py +203 -0
  33. flowharness_inspection-0.1.0/src/inspection/domain/metrics/factory.py +58 -0
  34. flowharness_inspection-0.1.0/src/inspection/domain/metrics/gate.py +151 -0
  35. flowharness_inspection-0.1.0/src/inspection/domain/metrics/gate_expr.py +104 -0
  36. flowharness_inspection-0.1.0/src/inspection/domain/normalization.py +23 -0
  37. flowharness_inspection-0.1.0/src/inspection/domain/path_safety.py +60 -0
  38. flowharness_inspection-0.1.0/src/inspection/domain/redaction.py +16 -0
  39. flowharness_inspection-0.1.0/src/inspection/domain/renderers/__init__.py +23 -0
  40. flowharness_inspection-0.1.0/src/inspection/domain/renderers/github.py +227 -0
  41. flowharness_inspection-0.1.0/src/inspection/domain/renderers/sarif.py +149 -0
  42. flowharness_inspection-0.1.0/src/inspection/domain/report.py +117 -0
  43. flowharness_inspection-0.1.0/src/inspection/domain/scoring.py +239 -0
  44. flowharness_inspection-0.1.0/src/inspection/domain/segmentation.py +68 -0
  45. flowharness_inspection-0.1.0/src/inspection/domain/similarity.py +31 -0
  46. flowharness_inspection-0.1.0/src/inspection/domain/snapshot.py +155 -0
  47. flowharness_inspection-0.1.0/src/inspection/domain/surfaces.py +222 -0
  48. flowharness_inspection-0.1.0/src/inspection/domain/units.py +90 -0
  49. flowharness_inspection-0.1.0/src/inspection/infrastructure/__init__.py +1 -0
  50. flowharness_inspection-0.1.0/src/inspection/infrastructure/agent_config.py +300 -0
  51. flowharness_inspection-0.1.0/src/inspection/infrastructure/filesystem.py +71 -0
  52. flowharness_inspection-0.1.0/src/inspection/infrastructure/policies.py +40 -0
  53. flowharness_inspection-0.1.0/src/inspection/policies/contradictions_v1.toml +82 -0
  54. flowharness_inspection-0.1.0/src/inspection/policies/quarantine_v1.toml +13 -0
  55. flowharness_inspection-0.1.0/src/inspection/policies/scoring_v1.toml +41 -0
  56. flowharness_inspection-0.1.0/src/inspection/policies/scoring_v2.toml +57 -0
  57. flowharness_inspection-0.1.0/src/inspection/py.typed +0 -0
@@ -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,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: flowharness-inspection
3
+ Version: 0.1.0
4
+ Summary: Inspection context — Architectural Drift Index and risk scan (FLOWHARNESS_SPEC.md §6.12)
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Programming Language :: Python :: 3.12
9
+ Classifier: Programming Language :: Python :: 3.13
10
+ Requires-Dist: flowharness-core==0.1.0
11
+ Requires-Dist: pyyaml>=6.0
12
+ Requires-Python: >=3.12
13
+ Project-URL: Homepage, https://github.com/flowharness-ai
14
+ Description-Content-Type: text/markdown
15
+
16
+ # flowharness-inspection
17
+
18
+ Inspection context — the static, local, deterministic agent-rules surface scanner. Provides the domain layer for classifying agent-rules surfaces (CLAUDE.md, .cursorrules, AGENTS.md, agent-harness bundles, etc.), reading and parsing them, running architectural drift/contradiction/divergence/risk checks, and scoring findings into a quarantine verdict and drift index.
19
+
20
+ This is an **internal library package** of the FlowHarness toolchain, published to PyPI as a transitive dependency of [`flowharness`](https://github.com/flowharness-ai) (the scan CLI) and [`flowharness-ci-runner`](https://github.com/flowharness-ai). Install those packages instead of depending on `flowharness-inspection` directly.
21
+
22
+ > **Note:** this package currently installs a top-level module named `inspection`. Prefer `uvx` (isolated environments) over `pip install` into a shared venv until the 0.2 module-namespace rename lands.
23
+
24
+ **License:** Apache-2.0
25
+ **Homepage:** https://github.com/flowharness-ai
@@ -0,0 +1,10 @@
1
+ # flowharness-inspection
2
+
3
+ Inspection context — the static, local, deterministic agent-rules surface scanner. Provides the domain layer for classifying agent-rules surfaces (CLAUDE.md, .cursorrules, AGENTS.md, agent-harness bundles, etc.), reading and parsing them, running architectural drift/contradiction/divergence/risk checks, and scoring findings into a quarantine verdict and drift index.
4
+
5
+ This is an **internal library package** of the FlowHarness toolchain, published to PyPI as a transitive dependency of [`flowharness`](https://github.com/flowharness-ai) (the scan CLI) and [`flowharness-ci-runner`](https://github.com/flowharness-ai). Install those packages instead of depending on `flowharness-inspection` directly.
6
+
7
+ > **Note:** this package currently installs a top-level module named `inspection`. Prefer `uvx` (isolated environments) over `pip install` into a shared venv until the 0.2 module-namespace rename lands.
8
+
9
+ **License:** Apache-2.0
10
+ **Homepage:** https://github.com/flowharness-ai
@@ -0,0 +1,30 @@
1
+ [project]
2
+ name = "flowharness-inspection"
3
+ version = "0.1.0"
4
+ readme = "README.md"
5
+ description = "Inspection context — Architectural Drift Index and risk scan (FLOWHARNESS_SPEC.md §6.12)"
6
+ requires-python = ">=3.12"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Programming Language :: Python :: 3.12",
12
+ "Programming Language :: Python :: 3.13",
13
+ ]
14
+ dependencies = [
15
+ "flowharness-core==0.1.0",
16
+ "pyyaml>=6.0",
17
+ ]
18
+
19
+ [project.urls]
20
+ Homepage = "https://github.com/flowharness-ai"
21
+
22
+ [build-system]
23
+ requires = ["uv_build>=0.9.0,<0.10.0"]
24
+ build-backend = "uv_build"
25
+
26
+ [tool.uv.build-backend]
27
+ module-name = "inspection"
28
+
29
+ [tool.uv.sources.flowharness-core]
30
+ workspace = true
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "flowharness-inspection"
3
+ version = "0.1.0"
4
+ readme = "README.md"
5
+ description = "Inspection context — Architectural Drift Index and risk scan (FLOWHARNESS_SPEC.md §6.12)"
6
+ requires-python = ">=3.12"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Programming Language :: Python :: 3.12",
12
+ "Programming Language :: Python :: 3.13",
13
+ ]
14
+ # Internal deps pin ==0.1.0: the six OSS packages version in lockstep (release.yml builds
15
+ # them from one tag), and [tool.uv.sources] workspace=true overrides these locally.
16
+ dependencies = ["flowharness-core==0.1.0", "pyyaml>=6.0"]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/flowharness-ai"
20
+
21
+ [build-system]
22
+ requires = ["uv_build>=0.9.0,<0.10.0"]
23
+ build-backend = "uv_build"
24
+
25
+ [tool.uv.build-backend]
26
+ module-name = "inspection"
27
+
28
+ [tool.uv.sources]
29
+ flowharness-core = { workspace = true }
@@ -0,0 +1,5 @@
1
+ """Inspection context (FLOWHARNESS_SPEC.md §6.12) — the Phase-0 wedge.
2
+
3
+ Static, local, deterministic scan over a project's agent-rules surface.
4
+ Zero network, zero model calls on the default path.
5
+ """
@@ -0,0 +1 @@
1
+ """Inspection api layer — edge schemas and adapters; never imported by domain or application."""
@@ -0,0 +1,17 @@
1
+ """Verdict -> process exit code (adapter concern, not domain).
2
+
3
+ PASS=0, NEEDS_HUMAN=1, FAIL=2 (SPEC §6.12.2). NEEDS_HUMAN is a distinct non-zero
4
+ code so CI can hold differently from a hard FAIL; NEEDS_HUMAN is never auto-approved.
5
+ """
6
+
7
+ from core import Verdict
8
+
9
+ _EXIT_CODES: dict[Verdict, int] = {
10
+ Verdict.PASS: 0,
11
+ Verdict.NEEDS_HUMAN: 1,
12
+ Verdict.FAIL: 2,
13
+ }
14
+
15
+
16
+ def exit_code_for(verdict: Verdict) -> int:
17
+ return _EXIT_CODES[verdict]
@@ -0,0 +1 @@
1
+ """Inspection service layer — the only orchestration point (P&G ch.4)."""
@@ -0,0 +1,98 @@
1
+ """Inspection service layer — the scan use case (P&G ch.4).
2
+
3
+ PR 0.5: the report carries the RulesSnapshot, the drift + risk findings, the
4
+ RiskAssessment (verdict from the QuarantineGate), the DriftIndex (scored), and the
5
+ content-addressed report_hash. Report assembly lives in domain/report.py.
6
+ """
7
+
8
+ import json
9
+ from collections.abc import Iterable, Sequence
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Protocol, cast
13
+
14
+ from core import Check, Finding
15
+ from inspection.domain.baseline import (
16
+ BaselineDiff,
17
+ BaselineRecord,
18
+ diff_against_baseline,
19
+ take_baseline,
20
+ )
21
+ from inspection.domain.checks import CheckContext, default_drift_checks, default_risk_checks
22
+ from inspection.domain.checks.quarantine import RiskAssessment
23
+ from inspection.domain.report import build_inspection_report
24
+ from inspection.domain.scoring import DriftIndex, score_drift, scoring_policy_fingerprint
25
+ from inspection.domain.snapshot import RawSurfaceFile, take_snapshot
26
+
27
+
28
+ class SurfaceReader(Protocol):
29
+ """Port: enumerate the raw agent-rules surface of a directory."""
30
+
31
+ def read(self, root: Path) -> Iterable[RawSurfaceFile]: ...
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class ScanResult:
36
+ report: bytes
37
+ assessment: RiskAssessment
38
+ drift_index: DriftIndex
39
+ findings: tuple[Finding, ...]
40
+ baseline_record: BaselineRecord # this scan as a committable baseline (--set-baseline)
41
+ baseline_diff: BaselineDiff | None # populated only when a baseline was provided
42
+
43
+
44
+ def scan_directory(
45
+ root: Path,
46
+ reader: SurfaceReader,
47
+ context: CheckContext,
48
+ baseline: BaselineRecord | None = None,
49
+ checks: Sequence[Check] | None = None,
50
+ ) -> ScanResult:
51
+ """Run the scan and render the canonical report bytes plus the risk verdict and index.
52
+
53
+ `checks` injects the check composition via the `core.Check` port (DIP, mirroring
54
+ the `SurfaceReader` seam); `None` keeps the default drift+risk tuple byte-for-byte.
55
+
56
+ Byte-level canonicalisation lives here, once: sorted keys, no whitespace
57
+ drift, UTF-8, trailing newline, and no timestamps in the body (§6.12.5).
58
+ """
59
+ if checks is None:
60
+ # WHY: each element implements the core.Check port; the cast performs the
61
+ # heterogeneous-tuple→Sequence widening (mypy infers the concrete per-element
62
+ # tuple type rather than the common Check supertype).
63
+ checks = cast("Sequence[Check]", (*default_drift_checks(), *default_risk_checks()))
64
+ snapshot, reader_findings = take_snapshot(reader.read(root))
65
+ findings: list[Finding] = list(reader_findings)
66
+ for check in checks:
67
+ findings.extend(check.run(snapshot, context))
68
+ findings.sort(key=lambda f: (f.check_id, f.subject_ref, f.evidence))
69
+
70
+ assessment = RiskAssessment.from_findings(findings, context.quarantine_policy)
71
+ drift_index = score_drift(
72
+ findings,
73
+ context.scoring_policy,
74
+ baseline_ref=context.baseline_ref if baseline is None else "lockfile",
75
+ snapshot_hash=snapshot.snapshot_hash,
76
+ )
77
+ diff = (
78
+ diff_against_baseline(findings, baseline, drift_index.display)
79
+ if baseline is not None
80
+ else None
81
+ )
82
+ report = build_inspection_report(
83
+ snapshot,
84
+ findings,
85
+ assessment,
86
+ drift_index,
87
+ scoring_policy_fingerprint(context.scoring_policy),
88
+ baseline_diff=diff,
89
+ )
90
+ report_bytes = json.dumps(report, sort_keys=True, ensure_ascii=False).encode() + b"\n"
91
+ return ScanResult(
92
+ report=report_bytes,
93
+ assessment=assessment,
94
+ drift_index=drift_index,
95
+ findings=tuple(findings),
96
+ baseline_record=take_baseline(findings, snapshot.snapshot_hash, drift_index.display),
97
+ baseline_diff=diff,
98
+ )
@@ -0,0 +1 @@
1
+ """Inspection domain layer — frozen VOs and invariants. Imports stdlib + core only."""
@@ -0,0 +1,157 @@
1
+ """AgentConfigGraph — normalized VO for orchestration-graph inspection (CI-PR2 §Step 2).
2
+
3
+ A single normalized shape that CrewAI Python configs, LangGraph YAML/JSON, and future
4
+ harness readers all reduce to. Integer-only limits (bp/micro-units at the display edge)
5
+ so `content_hash()` is stable and CI-PR3's loop/cycle/ceiling checks stay pure. Producers
6
+ (readers, CI-PR2b): the stdlib-`ast` CrewAI reader lives in the domain peer
7
+ `inspection/domain/agent_config_reader.py` (ast is stdlib → domain-legal); the PyYAML
8
+ reader lives in `inspection/infrastructure/agent_config.py` (third-party ⇒ infrastructure).
9
+
10
+ Design (docs/architecture/flowharness-ci-PR-ROADMAP.md §CI-PR2 Step 2):
11
+
12
+ - **Node** carries the safety-relevant ceilings CI-PR3 checks: `max_iterations`,
13
+ `max_rpm`, `max_execution_time_s`, `token_ceiling`, `cost_ceiling_micro`,
14
+ `allow_delegation`. All optional (a static reader can't always determine them);
15
+ `None` MEANS "unbounded" for the loop/ceiling checks.
16
+ - **DelegationEdge** connects two node ids; CI-PR3's recursive_delegation_check does
17
+ DFS over these.
18
+ - **AgentConfigGraph** freezes the whole thing and mixes in `ContentHashable` so
19
+ identical graphs from two readers produce identical hashes (byte-parity across
20
+ languages, D8-14).
21
+
22
+ `node_ids` are stable strings the reader picks (typically the CrewAI class name or the
23
+ LangGraph node id); the graph rejects duplicate ids and dangling edges at construction.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from dataclasses import dataclass, field
29
+
30
+ from core import DomainError
31
+ from core.content_hash import ContentHashable
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class AgentNode:
36
+ """One node in the agent orchestration graph. CI-PR3 loop/cycle/ceiling checks read
37
+ from this. `None` on a limit means UNBOUNDED — the exact signal that triggers
38
+ HIGH/MEDIUM findings in CI-PR3.
39
+
40
+ Fields extended in CI-PR2b (per docs/architecture/ci_governance_spec.md §3.4):
41
+ `name`, `source_ref`, `line`, `llm_ref`. All defaulted so CI-PR2a tests stay green;
42
+ CI-PR3's `token_ceiling_check` needs `llm_ref` to discriminate spending vs
43
+ non-spending nodes and `line` for the SourceAnchor on findings."""
44
+
45
+ node_id: str
46
+ role: str = ""
47
+ max_iterations: int | None = None
48
+ max_rpm: int | None = None
49
+ max_execution_time_s: int | None = None
50
+ token_ceiling: int | None = None
51
+ cost_ceiling_micro: int | None = None # cost in USD x 1_000_000 (integer, float-free)
52
+ allow_delegation: bool = False
53
+ # CI-PR2b VO extension (spec §3.4). Defaulted for backwards compat.
54
+ name: str = ""
55
+ source_ref: str = "" # posix relpath of the source file
56
+ line: int | None = None # 1-based; parser's lineno for the Agent() call / class def
57
+ llm_ref: str | None = None # e.g. "gpt-4o" — presence means the node WILL spend
58
+
59
+ def __post_init__(self) -> None:
60
+ if not self.node_id:
61
+ raise DomainError("agent_node_id_blank")
62
+ for attr, value in (
63
+ ("max_iterations", self.max_iterations),
64
+ ("max_rpm", self.max_rpm),
65
+ ("max_execution_time_s", self.max_execution_time_s),
66
+ ("token_ceiling", self.token_ceiling),
67
+ ("cost_ceiling_micro", self.cost_ceiling_micro),
68
+ ):
69
+ if value is not None and value < 0:
70
+ raise DomainError(f"agent_node_{attr}_negative")
71
+ if self.line is not None and self.line <= 0:
72
+ raise DomainError("agent_node_line_invalid")
73
+
74
+
75
+ # CI-PR2b: edge kinds enumerated (spec §3.4). Strings not StrEnum so the VO hash
76
+ # stays JSON-native and cross-language byte-parity survives.
77
+ DELEGATION_EDGE_KINDS: frozenset[str] = frozenset({"delegation", "task_chain", "tool"})
78
+
79
+
80
+ @dataclass(frozen=True, slots=True)
81
+ class DelegationEdge:
82
+ """`source` may delegate to `target`. CI-PR3's recursive_delegation_check walks
83
+ these to detect cycles. `kind` (spec §3.4) discriminates a delegating hierarchy
84
+ from task-chain dependencies and tool-use edges."""
85
+
86
+ source: str
87
+ target: str
88
+ kind: str = "delegation"
89
+
90
+ def __post_init__(self) -> None:
91
+ if not self.source or not self.target:
92
+ raise DomainError("delegation_edge_endpoints_blank")
93
+ if self.kind not in DELEGATION_EDGE_KINDS:
94
+ raise DomainError("delegation_edge_kind_unknown")
95
+
96
+
97
+ @dataclass(frozen=True, slots=True)
98
+ class AgentConfigGraph(ContentHashable):
99
+ """A frozen orchestration graph — the reader's output, CI-PR3's input.
100
+
101
+ `nodes` MUST have unique ids; every edge endpoint MUST refer to a known node
102
+ (otherwise the graph would silently classify unreachable branches as bounded).
103
+ Producers set `harness_ref` to a stable string identifying the source
104
+ ("crewai", "langgraph", …) so consumers can route findings back to a spec section."""
105
+
106
+ nodes: tuple[AgentNode, ...] = field(default_factory=tuple)
107
+ edges: tuple[DelegationEdge, ...] = field(default_factory=tuple)
108
+ harness_ref: str = ""
109
+
110
+ def __post_init__(self) -> None:
111
+ ids: set[str] = set()
112
+ for n in self.nodes:
113
+ if n.node_id in ids:
114
+ raise DomainError("agent_graph_duplicate_node_id")
115
+ ids.add(n.node_id)
116
+ for e in self.edges:
117
+ if e.source not in ids or e.target not in ids:
118
+ raise DomainError("agent_graph_edge_endpoint_unknown")
119
+
120
+ def _hash_payload(self) -> object:
121
+ # Sort so a producer's node/edge iteration order doesn't leak into the hash;
122
+ # CI-PR3 needs stable output regardless of reader ordering.
123
+ # NB: `line` is NOT hashed — it's a rendering-only anchor and is not
124
+ # cross-Python-version stable (per adversarial review, ast lineno drift).
125
+ return {
126
+ "harness_ref": self.harness_ref,
127
+ "nodes": [
128
+ {
129
+ "node_id": n.node_id,
130
+ "role": n.role,
131
+ "name": n.name,
132
+ "source_ref": n.source_ref,
133
+ "llm_ref": n.llm_ref,
134
+ "max_iterations": n.max_iterations,
135
+ "max_rpm": n.max_rpm,
136
+ "max_execution_time_s": n.max_execution_time_s,
137
+ "token_ceiling": n.token_ceiling,
138
+ "cost_ceiling_micro": n.cost_ceiling_micro,
139
+ "allow_delegation": n.allow_delegation,
140
+ }
141
+ for n in sorted(self.nodes, key=lambda x: x.node_id)
142
+ ],
143
+ "edges": [
144
+ {"source": e.source, "target": e.target, "kind": e.kind}
145
+ for e in sorted(self.edges, key=lambda x: (x.source, x.target, x.kind))
146
+ ],
147
+ }
148
+
149
+ def graph_hash(self) -> str:
150
+ """Alias for `content_hash()` — spec-named identifier CI-PR3 fixtures use."""
151
+ return self.content_hash()
152
+
153
+ def node(self, node_id: str) -> AgentNode | None:
154
+ for n in self.nodes:
155
+ if n.node_id == node_id:
156
+ return n
157
+ return None