code-audit-validator 1.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- code_audit_validator-1.2.0.dist-info/METADATA +294 -0
- code_audit_validator-1.2.0.dist-info/RECORD +8 -0
- code_audit_validator-1.2.0.dist-info/WHEEL +5 -0
- code_audit_validator-1.2.0.dist-info/entry_points.txt +2 -0
- code_audit_validator-1.2.0.dist-info/licenses/LICENSE +202 -0
- code_audit_validator-1.2.0.dist-info/licenses/NOTICE +3 -0
- code_audit_validator-1.2.0.dist-info/top_level.txt +1 -0
- code_audit_validator.py +648 -0
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: code-audit-validator
|
|
3
|
+
Version: 1.2.0
|
|
4
|
+
Summary: Deterministic conformance checker for AUDIT.md agent-audit outputs — CyberSkill code-audit-framework
|
|
5
|
+
Author-email: CyberSkill <info@cyberskill.world>
|
|
6
|
+
License:
|
|
7
|
+
Apache License
|
|
8
|
+
Version 2.0, January 2004
|
|
9
|
+
http://www.apache.org/licenses/
|
|
10
|
+
|
|
11
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
12
|
+
|
|
13
|
+
1. Definitions.
|
|
14
|
+
|
|
15
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
16
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
17
|
+
|
|
18
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
19
|
+
the copyright owner that is granting the License.
|
|
20
|
+
|
|
21
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
22
|
+
other entities that control, are controlled by, or are under common
|
|
23
|
+
control with that entity. For the purposes of this definition,
|
|
24
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
25
|
+
direction or management of such entity, whether by contract or
|
|
26
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
27
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
28
|
+
|
|
29
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
30
|
+
exercising permissions granted by this License.
|
|
31
|
+
|
|
32
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
33
|
+
including but not limited to software source code, documentation
|
|
34
|
+
source, and configuration files.
|
|
35
|
+
|
|
36
|
+
"Object" form shall mean any form resulting from mechanical
|
|
37
|
+
transformation or translation of a Source form, including but
|
|
38
|
+
not limited to compiled object code, generated documentation,
|
|
39
|
+
and conversions to other media types.
|
|
40
|
+
|
|
41
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
42
|
+
Object form, made available under the License, as indicated by a
|
|
43
|
+
copyright notice that is included in or attached to the work
|
|
44
|
+
(an example is provided in the Appendix below).
|
|
45
|
+
|
|
46
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
47
|
+
form, that is based on (or derived from) the Work and for which the
|
|
48
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
49
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
50
|
+
of this License, Derivative Works shall not include works that remain
|
|
51
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
52
|
+
the Work and Derivative Works thereof.
|
|
53
|
+
|
|
54
|
+
"Contribution" shall mean any work of authorship, including
|
|
55
|
+
the original version of the Work and any modifications or additions
|
|
56
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
57
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
58
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
59
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
60
|
+
means any form of electronic, verbal, or written communication sent
|
|
61
|
+
to the Licensor or its representatives, including but not limited to
|
|
62
|
+
communication on electronic mailing lists, source code control systems,
|
|
63
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
64
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
65
|
+
excluding communication that is conspicuously marked or otherwise
|
|
66
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
67
|
+
|
|
68
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
69
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
70
|
+
subsequently incorporated within the Work.
|
|
71
|
+
|
|
72
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
73
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
74
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
75
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
76
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
77
|
+
Work and such Derivative Works in Source or Object form.
|
|
78
|
+
|
|
79
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
80
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
81
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
82
|
+
(except as stated in this section) patent license to make, have made,
|
|
83
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
84
|
+
where such license applies only to those patent claims licensable
|
|
85
|
+
by such Contributor that are necessarily infringed by their
|
|
86
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
87
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
88
|
+
institute patent litigation against any entity (including a
|
|
89
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
90
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
91
|
+
or contributory patent infringement, then any patent licenses
|
|
92
|
+
granted to You under this License for that Work shall terminate
|
|
93
|
+
as of the date such litigation is filed.
|
|
94
|
+
|
|
95
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
96
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
97
|
+
modifications, and in Source or Object form, provided that You
|
|
98
|
+
meet the following conditions:
|
|
99
|
+
|
|
100
|
+
(a) You must give any other recipients of the Work or
|
|
101
|
+
Derivative Works a copy of this License; and
|
|
102
|
+
|
|
103
|
+
(b) You must cause any modified files to carry prominent notices
|
|
104
|
+
stating that You changed the files; and
|
|
105
|
+
|
|
106
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
107
|
+
that You distribute, all copyright, patent, trademark, and
|
|
108
|
+
attribution notices from the Source form of the Work,
|
|
109
|
+
excluding those notices that do not pertain to any part of
|
|
110
|
+
the Derivative Works; and
|
|
111
|
+
|
|
112
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
113
|
+
distribution, then any Derivative Works that You distribute must
|
|
114
|
+
include a readable copy of the attribution notices contained
|
|
115
|
+
within such NOTICE file, excluding those notices that do not
|
|
116
|
+
pertain to any part of the Derivative Works, in at least one
|
|
117
|
+
of the following places: within a NOTICE text file distributed
|
|
118
|
+
as part of the Derivative Works; within the Source form or
|
|
119
|
+
documentation, if provided along with the Derivative Works; or,
|
|
120
|
+
within a display generated by the Derivative Works, if and
|
|
121
|
+
wherever such third-party notices normally appear. The contents
|
|
122
|
+
of the NOTICE file are for informational purposes only and
|
|
123
|
+
do not modify the License. You may add Your own attribution
|
|
124
|
+
notices within Derivative Works that You distribute, alongside
|
|
125
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
126
|
+
that such additional attribution notices cannot be construed
|
|
127
|
+
as modifying the License.
|
|
128
|
+
|
|
129
|
+
You may add Your own copyright statement to Your modifications and
|
|
130
|
+
may provide additional or different license terms and conditions
|
|
131
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
132
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
133
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
134
|
+
the conditions stated in this License.
|
|
135
|
+
|
|
136
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
137
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
138
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
139
|
+
this License, without any additional terms or conditions.
|
|
140
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
141
|
+
the terms of any separate license agreement you may have executed
|
|
142
|
+
with Licensor regarding such Contributions.
|
|
143
|
+
|
|
144
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
145
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
146
|
+
except as required for reasonable and customary use in describing the
|
|
147
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
148
|
+
|
|
149
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
150
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
151
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
152
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
153
|
+
implied, including, without limitation, any warranties or conditions
|
|
154
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
155
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
156
|
+
appropriateness of using or redistributing the Work and assume any
|
|
157
|
+
risks associated with Your exercise of permissions under this License.
|
|
158
|
+
|
|
159
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
160
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
161
|
+
unless required by applicable law (such as deliberate and grossly
|
|
162
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
163
|
+
liable to You for damages, including any direct, indirect, special,
|
|
164
|
+
incidental, or consequential damages of any character arising as a
|
|
165
|
+
result of this License or out of the use or inability to use the
|
|
166
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
167
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
168
|
+
other commercial damages or losses), even if such Contributor
|
|
169
|
+
has been advised of the possibility of such damages.
|
|
170
|
+
|
|
171
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
172
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
173
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
174
|
+
or other liability obligations and/or rights consistent with this
|
|
175
|
+
License. However, in accepting such obligations, You may act only
|
|
176
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
177
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
178
|
+
defend, and hold each Contributor harmless for any liability
|
|
179
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
180
|
+
of your accepting any such warranty or additional liability.
|
|
181
|
+
|
|
182
|
+
END OF TERMS AND CONDITIONS
|
|
183
|
+
|
|
184
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
185
|
+
|
|
186
|
+
To apply the Apache License to your work, attach the following
|
|
187
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
188
|
+
replaced with your own identifying information. (Don't include
|
|
189
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
190
|
+
comment syntax for the file format. We also recommend that a
|
|
191
|
+
file or class name and description of purpose be included on the
|
|
192
|
+
same "printed page" as the copyright notice for easier
|
|
193
|
+
identification within third-party archives.
|
|
194
|
+
|
|
195
|
+
Copyright 2026 CYBERSKILL SOFTWARE SOLUTIONS CONSULTANCY AND DEVELOPMENT JOINT STOCK COMPANY
|
|
196
|
+
|
|
197
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
198
|
+
you may not use this file except in compliance with the License.
|
|
199
|
+
You may obtain a copy of the License at
|
|
200
|
+
|
|
201
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
202
|
+
|
|
203
|
+
Unless required by applicable law or agreed to in writing, software
|
|
204
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
205
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
206
|
+
See the License for the specific language governing permissions and
|
|
207
|
+
limitations under the License.
|
|
208
|
+
|
|
209
|
+
Project-URL: Homepage, https://github.com/cyberskill-official/code-audit-framework
|
|
210
|
+
Project-URL: Changelog, https://github.com/cyberskill-official/code-audit-framework/blob/main/CHANGELOG.md
|
|
211
|
+
Keywords: ai-agents,code-audit,llm,evals,prompt-engineering
|
|
212
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
213
|
+
Classifier: Intended Audience :: Developers
|
|
214
|
+
Classifier: Programming Language :: Python :: 3
|
|
215
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
216
|
+
Requires-Python: >=3.9
|
|
217
|
+
Description-Content-Type: text/markdown
|
|
218
|
+
License-File: LICENSE
|
|
219
|
+
License-File: NOTICE
|
|
220
|
+
Dynamic: license-file
|
|
221
|
+
|
|
222
|
+
# evals/ — regression gate for AUDIT.md
|
|
223
|
+
|
|
224
|
+
Every change to `AUDIT.md` must keep this suite green. The harness validates
|
|
225
|
+
**agent outputs** (a run's `docs/BACKLOG.md` + `docs/HANDOFF.md`) against the
|
|
226
|
+
machine-checkable subset of the protocol's rules, and proves each rule is
|
|
227
|
+
**load-bearing** by fault injection: a `B*` fixture plants a known fault set
|
|
228
|
+
(usually exactly one; `B16` deliberately plants three to verify exact-set
|
|
229
|
+
reporting), and the validator must catch exactly that set — no more, no less.
|
|
230
|
+
A trap that stops tripping means a rule has silently died. `G*` fixtures are
|
|
231
|
+
the precision half: compliant-but-tricky outputs (negated prose, redaction
|
|
232
|
+
markers, adversarial formatting, minimal-valid) that must NOT trip anything —
|
|
233
|
+
the suite proves rules fire *and* don't over-fire.
|
|
234
|
+
|
|
235
|
+
Two checks make the rest load-bearing: `TEMPLATE-NONCONFORMANT` (output that
|
|
236
|
+
doesn't follow the Phase 2 template can no longer silently escape the other
|
|
237
|
+
tripwires — BS-12) and the CONFIG preflight (`CONFIG-PLACEHOLDER` /
|
|
238
|
+
`CONFIG-BAD-ENUM`, which also auto-loads `PROTECTED_AREAS` from the target's
|
|
239
|
+
AUDIT.md so R3 needs no `--protected` double entry — BS-13).
|
|
240
|
+
|
|
241
|
+
## Files
|
|
242
|
+
|
|
243
|
+
| File | Role |
|
|
244
|
+
|---|---|
|
|
245
|
+
| `code_audit_validator.py` | The validator implementation. Zero dependencies (stdlib only); published to PyPI as `code-audit-validator`. |
|
|
246
|
+
| `validate.py` | Repo-side CLI shim over the module above — every documented `python3 evals/validate.py …` invocation goes through it. |
|
|
247
|
+
| `fixtures/` | `G*` = compliant outputs that must pass. `B*` = fault-injection traps that must fail with declared codes. |
|
|
248
|
+
| `rules.json` | Rule registry: rule → AUDIT.md anchor → violation codes → fixtures proving it. Coverage gaps are declared honestly. |
|
|
249
|
+
| `baseline.json` | Last recorded matrix (fixture → outcome) pinned to an AUDIT.md version + sha256. |
|
|
250
|
+
| `run-evals.sh` | Runner; `--record` refreshes `baseline.json`. |
|
|
251
|
+
|
|
252
|
+
## Commands
|
|
253
|
+
|
|
254
|
+
```bash
|
|
255
|
+
python3 evals/validate.py --all # full suite, human output
|
|
256
|
+
python3 evals/validate.py --all --json # machine-readable
|
|
257
|
+
./evals/run-evals.sh --record # run + pin baseline to current AUDIT.md
|
|
258
|
+
python3 evals/validate.py --run <dir> # validate a real run's docs/ output
|
|
259
|
+
python3 evals/validate.py --run <dir> --report json # structured findings export (loops, tasks, metrics, violations)
|
|
260
|
+
python3 evals/validate.py --run <dir> --report sarif # GitHub code-scanning format
|
|
261
|
+
python3 evals/scripts/retro-summary.py # retro scores per protocol version (did each release help?)
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
Point `--run` at the target repo root (or its `docs/`): if the target's
|
|
265
|
+
`AUDIT.md` is found, its CONFIG is preflighted and `PROTECTED_AREAS` is loaded
|
|
266
|
+
automatically; `--protected` extends it.
|
|
267
|
+
|
|
268
|
+
## Adding a fixture
|
|
269
|
+
|
|
270
|
+
1. Create `evals/fixtures/<Gnn|Bnn>-<slug>/` with `fixture.yaml` + `docs/BACKLOG.md` (and `docs/HANDOFF.md` if relevant).
|
|
271
|
+
2. `fixture.yaml` is flat `key: value` (no YAML library needed):
|
|
272
|
+
|
|
273
|
+
```yaml
|
|
274
|
+
id: B11-my-trap
|
|
275
|
+
description: one line
|
|
276
|
+
expect: fail # or pass
|
|
277
|
+
expected_violations: [R1-NO-OUTPUT]
|
|
278
|
+
exercises_rules: [R1]
|
|
279
|
+
protected_areas: []
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
3. For `expect: fail`, the validator must report **exactly** `expected_violations` — plant one fault per fixture unless the fixture's purpose is exact-set verification (B16). Keep `docs/BACKLOG.md` template-conformant (Mode line + tables or the R7 line) so the planted fault is the only signal; ship a near-miss `G*` sibling when adding a new rule, so precision is pinned alongside recall.
|
|
283
|
+
4. Register the fixture in `rules.json` under the rule(s) it exercises — `validate.py --all` fails on registry drift in either direction (BS-10).
|
|
284
|
+
5. Run `./evals/run-evals.sh --record`.
|
|
285
|
+
|
|
286
|
+
## What the validator cannot see (declared gaps)
|
|
287
|
+
|
|
288
|
+
The authoritative register is [`improve/BLINDSPOTS.md`](../improve/BLINDSPOTS.md)
|
|
289
|
+
— one row per blind spot, with status and evidence. Headlines:
|
|
290
|
+
|
|
291
|
+
- Whether code changes were genuinely valuable (retro item 9 — human judgment).
|
|
292
|
+
- Whether findings were padded (retro item 3 — judgment; the validator only guarantees padding is never *required*).
|
|
293
|
+
- Live-agent properties: actual command execution, 3-strike counting, resume behavior (R4). For hard guarantees on those, use deterministic hooks/CI in the target repo, not prompt text.
|
|
294
|
+
- Run completeness: `--run` accepts a docs/ directory without HANDOFF.md (legitimate mid-flight). When reviewing a run that claims to be finished, confirm HANDOFF.md exists yourself (BS-09).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
code_audit_validator.py,sha256=wHjVqctyszLqItjOWsTHXKmyOcukGWdRCw5ves2l-F8,30632
|
|
2
|
+
code_audit_validator-1.2.0.dist-info/licenses/LICENSE,sha256=jJWC4b-3FDgRCe4Gfdb_n-LKUnciQNXYULpwys0F1R4,11408
|
|
3
|
+
code_audit_validator-1.2.0.dist-info/licenses/NOTICE,sha256=rVFViBLv6GtWf1Yuva-PqX2fvBqiSSC1RbClpiW9Xw4,187
|
|
4
|
+
code_audit_validator-1.2.0.dist-info/METADATA,sha256=BzBqsVFjHzrISdJNR9UgsDo_dz_PmaEeV-tJa9TluHo,18367
|
|
5
|
+
code_audit_validator-1.2.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
6
|
+
code_audit_validator-1.2.0.dist-info/entry_points.txt,sha256=I-SCERpk7v5kYRjNyednulZ0G9JWZGvylSOK3UnsxLo,66
|
|
7
|
+
code_audit_validator-1.2.0.dist-info/top_level.txt,sha256=O3Z8CSTQ2fXolXghQQeFgrc6AmS3PYRi15K7XYBr3IQ,21
|
|
8
|
+
code_audit_validator-1.2.0.dist-info/RECORD,,
|
|
@@ -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 2026 CYBERSKILL SOFTWARE SOLUTIONS CONSULTANCY AND DEVELOPMENT JOINT STOCK COMPANY
|
|
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 @@
|
|
|
1
|
+
code_audit_validator
|
code_audit_validator.py
ADDED
|
@@ -0,0 +1,648 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""code_audit_validator — deterministic conformance checker for AUDIT.md outputs.
|
|
3
|
+
|
|
4
|
+
(Repo-side CLI: `python3 evals/validate.py`, a thin shim over this module —
|
|
5
|
+
kept so the PyPI install claims `code_audit_validator`, not the generic
|
|
6
|
+
top-level name `validate`.)
|
|
7
|
+
|
|
8
|
+
Checks a run's docs/ directory (BACKLOG.md + HANDOFF.md) against the
|
|
9
|
+
machine-checkable subset of AUDIT.md's core rules:
|
|
10
|
+
|
|
11
|
+
R1-NO-OUTPUT measured baseline/metric without a verbatim fenced output block
|
|
12
|
+
R1-UNLINKED-OUTPUT measured row whose verify command appears in no fenced block
|
|
13
|
+
R1-NO-REASON UNMEASURED / NOT-APPLICABLE without a (reason)
|
|
14
|
+
R1-GUI-TOOL GUI tool (profiler/inspector/devtools) used as a Verify command
|
|
15
|
+
R2-UNCITED target is neither cited-with-URL nor labeled INTERNAL / N-A
|
|
16
|
+
R2-NONNUMERIC banned non-numeric target word (Minimal / High / Strict / ...)
|
|
17
|
+
R3-PROTECTED DONE task references a path under protected_areas
|
|
18
|
+
R5-BAD-STATUS task status outside { OPEN, IN-PROGRESS, DONE, BLOCKED }
|
|
19
|
+
R5-BAD-SEV severity outside { Critical, High, Medium, Low }
|
|
20
|
+
R5-BAD-ID task ID not matching L<loop>-T<n>
|
|
21
|
+
R6-NO-ROOTCAUSE BLOCKED task without a "Root cause:" note
|
|
22
|
+
R8-SECRET unredacted credential pattern in any output file
|
|
23
|
+
P5-NO-STOP-REASON HANDOFF.md does not cite which stop condition fired
|
|
24
|
+
HANDOFF-BAD-MSTATUS metrics Status outside the closed metric-status set
|
|
25
|
+
GATED-UNAPPROVED-EXEC executed task not on the loop's `Approved:` line (gated mode)
|
|
26
|
+
TEMPLATE-NONCONFORMANT BACKLOG.md does not follow the Phase 2 template, so the
|
|
27
|
+
rule tripwires above cannot see it (BLINDSPOTS BS-12)
|
|
28
|
+
CONFIG-PLACEHOLDER a CONFIG value in the target's AUDIT.md still contains
|
|
29
|
+
unedited <placeholder> text (Phase 0 preflight)
|
|
30
|
+
CONFIG-BAD-ENUM MODE / DEPTH / BENCHMARK_MODE / SEVERITY_FLOOR outside its
|
|
31
|
+
allowed set (Phase 0 preflight)
|
|
32
|
+
|
|
33
|
+
A loop with zero findings is VALID (R7): absence of tasks is never a violation.
|
|
34
|
+
|
|
35
|
+
When the run directory (or its parent, if you point --run at docs/ itself)
|
|
36
|
+
contains the target's AUDIT.md, the CONFIG block is preflighted and
|
|
37
|
+
PROTECTED_AREAS is loaded from it automatically — `--protected` then extends
|
|
38
|
+
rather than replaces it (closes the double-entry gap, review item G-F).
|
|
39
|
+
|
|
40
|
+
Usage:
|
|
41
|
+
python3 evals/validate.py --run <dir-containing-docs> [--protected p1,p2]
|
|
42
|
+
python3 evals/validate.py --run <dir> --report json # structured findings export
|
|
43
|
+
python3 evals/validate.py --run <dir> --report sarif # GitHub code-scanning format
|
|
44
|
+
python3 evals/validate.py --all # run every fixture, compare to expectations
|
|
45
|
+
python3 evals/validate.py --all --json # machine-readable results
|
|
46
|
+
|
|
47
|
+
Exit codes: 0 = all good; 1 = violations / fixture mismatch; 2 = usage error.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
import argparse
|
|
51
|
+
import json
|
|
52
|
+
import re
|
|
53
|
+
import sys
|
|
54
|
+
from pathlib import Path
|
|
55
|
+
|
|
56
|
+
HERE = Path(__file__).resolve().parent
|
|
57
|
+
FIXTURES = HERE / "fixtures"
|
|
58
|
+
|
|
59
|
+
TASK_STATUSES = {"OPEN", "IN-PROGRESS", "DONE", "BLOCKED"}
|
|
60
|
+
SEVERITIES = {"Critical", "High", "Medium", "Low"}
|
|
61
|
+
METRIC_STATUSES = {"MEASURED", "UNMEASURED", "NOT-APPLICABLE"}
|
|
62
|
+
ID_RE = re.compile(r"^L\d+-T\d+$")
|
|
63
|
+
|
|
64
|
+
GUI_TOOLS = [
|
|
65
|
+
"react profiler", "react devtools", "chrome devtools", "devtools",
|
|
66
|
+
"browser inspector", "web inspector", "xcode instruments", "instruments.app",
|
|
67
|
+
"lighthouse panel", "performance tab", "network tab", "profiler tab",
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
SECRET_PATTERNS = [
|
|
71
|
+
("aws-key", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),
|
|
72
|
+
("github-token", re.compile(r"\bghp_[A-Za-z0-9]{36}\b")),
|
|
73
|
+
("gitlab-token", re.compile(r"\bglpat-[A-Za-z0-9_-]{20}\b")),
|
|
74
|
+
("stripe-key", re.compile(r"\bsk_live_[A-Za-z0-9]{16,}\b")),
|
|
75
|
+
("anthropic-key", re.compile(r"\bsk-ant-[A-Za-z0-9_-]{16,}\b")),
|
|
76
|
+
("openai-key", re.compile(r"\bsk-proj-[A-Za-z0-9_-]{20,}\b")),
|
|
77
|
+
("google-api-key", re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b")),
|
|
78
|
+
("npm-token", re.compile(r"\bnpm_[A-Za-z0-9]{36}\b")),
|
|
79
|
+
("slack-token", re.compile(r"\bxox[bpoas]-[0-9A-Za-z-]{10,}\b")),
|
|
80
|
+
("private-key", re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |PGP )?PRIVATE KEY-----")),
|
|
81
|
+
("jwt", re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b")),
|
|
82
|
+
]
|
|
83
|
+
|
|
84
|
+
BANNED_TARGET_WORDS = {
|
|
85
|
+
"minimal", "high", "strict", "low", "medium", "fast", "slow", "good",
|
|
86
|
+
"great", "optimal", "best-in-class", "world-class", "enterprise-grade",
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
UNMEASURED_RE = re.compile(r"\b(UNMEASURED|NOT-APPLICABLE)\b")
|
|
90
|
+
REASONED_RE = re.compile(r"\b(?:UNMEASURED|NOT-APPLICABLE)\s*\([^)]+\)")
|
|
91
|
+
URL_RE = re.compile(r"https?://\S+")
|
|
92
|
+
STOP_RE = re.compile(r"Stop condition:\s*\(?[abc]\)?", re.IGNORECASE)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
CELL_SPLIT_RE = re.compile(r"(?<!\\)\|") # an escaped \| is cell CONTENT, not a separator
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def norm(cell: str) -> str:
|
|
99
|
+
"""Strip markdown wrapping without mangling shell syntax: backticks go
|
|
100
|
+
everywhere, but * and _ are stripped only at the edges (emphasis), so
|
|
101
|
+
commands like `wc -l src/*.py` survive intact. Escaped pipes (\\|) are
|
|
102
|
+
unescaped back to literal | so commands like `grep -cE "TODO\\|FIXME"`
|
|
103
|
+
round-trip to what the agent actually ran (fixture G05)."""
|
|
104
|
+
s = cell.strip().replace("`", "").replace("\\|", "|")
|
|
105
|
+
return re.sub(r"^[*_]+|[*_]+$", "", s).strip()
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def split_cells(line: str):
|
|
109
|
+
return [norm(c) for c in CELL_SPLIT_RE.split(line.strip().strip("|"))]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def parse_tables(text: str):
|
|
113
|
+
"""Yield (header_cells, rows, end_line_idx) for every markdown table."""
|
|
114
|
+
lines = text.splitlines()
|
|
115
|
+
i = 0
|
|
116
|
+
while i < len(lines):
|
|
117
|
+
line = lines[i].strip()
|
|
118
|
+
if line.startswith("|") and i + 1 < len(lines) and re.match(r"^\|[\s:|-]+\|?$", lines[i + 1].strip()):
|
|
119
|
+
header = split_cells(line)
|
|
120
|
+
rows, j = [], i + 2
|
|
121
|
+
while j < len(lines) and lines[j].strip().startswith("|"):
|
|
122
|
+
cells = split_cells(lines[j])
|
|
123
|
+
if any(cells):
|
|
124
|
+
rows.append(cells)
|
|
125
|
+
j += 1
|
|
126
|
+
yield header, rows, j
|
|
127
|
+
i = j
|
|
128
|
+
else:
|
|
129
|
+
i += 1
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def section_fences(text: str, after_line: int):
|
|
133
|
+
"""Contents of fenced code blocks between after_line and the next heading."""
|
|
134
|
+
lines = text.splitlines()
|
|
135
|
+
fences, current, inside = [], [], False
|
|
136
|
+
for line in lines[after_line:]:
|
|
137
|
+
if not inside and re.match(r"^#{1,3}\s", line):
|
|
138
|
+
break
|
|
139
|
+
if line.strip().startswith("```"):
|
|
140
|
+
if inside:
|
|
141
|
+
fences.append("\n".join(current))
|
|
142
|
+
current = []
|
|
143
|
+
inside = not inside
|
|
144
|
+
continue
|
|
145
|
+
if inside:
|
|
146
|
+
current.append(line)
|
|
147
|
+
return fences
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def col(header, *names):
|
|
151
|
+
"""Index of first header cell containing any of names (case-insensitive)."""
|
|
152
|
+
low = [h.lower() for h in header]
|
|
153
|
+
for n in names:
|
|
154
|
+
for i, h in enumerate(low):
|
|
155
|
+
if n in h:
|
|
156
|
+
return i
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def check_benchmark_like_table(header, rows, end_idx, text, violations, src, is_handoff):
|
|
161
|
+
mi = col(header, "metric")
|
|
162
|
+
bi = col(header, "baseline")
|
|
163
|
+
ti = col(header, "target")
|
|
164
|
+
vi = col(header, "verify")
|
|
165
|
+
si = col(header, "status")
|
|
166
|
+
if mi is None or bi is None:
|
|
167
|
+
return
|
|
168
|
+
has_measured_row = False
|
|
169
|
+
measured_rows = [] # (metric, verify) pairs claiming a measurement
|
|
170
|
+
for r in rows:
|
|
171
|
+
def cell(ix):
|
|
172
|
+
return r[ix] if ix is not None and ix < len(r) else ""
|
|
173
|
+
baseline, target, verify = cell(bi), cell(ti), cell(vi)
|
|
174
|
+
# R1 — escape hatch must carry a reason
|
|
175
|
+
for v in (baseline, cell(si) if is_handoff else ""):
|
|
176
|
+
if UNMEASURED_RE.search(v) and not REASONED_RE.search(v):
|
|
177
|
+
# In HANDOFF the reason may live in the Baseline/Final cells; only
|
|
178
|
+
# flag the cell that itself claims UNMEASURED without any reason nearby.
|
|
179
|
+
if not REASONED_RE.search(" ".join(r)):
|
|
180
|
+
violations.append((f"R1-NO-REASON", src, f"'{v}' lacks (reason): row {r[:2]}"))
|
|
181
|
+
# Which rows claim a measurement?
|
|
182
|
+
if is_handoff:
|
|
183
|
+
status = cell(si)
|
|
184
|
+
if status and status not in METRIC_STATUSES:
|
|
185
|
+
violations.append(("HANDOFF-BAD-MSTATUS", src, f"Status '{status}' not in {sorted(METRIC_STATUSES)}"))
|
|
186
|
+
if status == "MEASURED":
|
|
187
|
+
has_measured_row = True
|
|
188
|
+
measured_rows.append((cell(mi), verify))
|
|
189
|
+
else:
|
|
190
|
+
if baseline and not UNMEASURED_RE.search(baseline):
|
|
191
|
+
has_measured_row = True
|
|
192
|
+
measured_rows.append((cell(mi), verify))
|
|
193
|
+
# R2 — honest targets
|
|
194
|
+
if ti is not None and target:
|
|
195
|
+
t = target.strip()
|
|
196
|
+
t_low = t.lower().rstrip(".")
|
|
197
|
+
if t_low in BANNED_TARGET_WORDS:
|
|
198
|
+
violations.append(("R2-NONNUMERIC", src, f"banned non-numeric target '{t}'"))
|
|
199
|
+
elif not (
|
|
200
|
+
URL_RE.search(t)
|
|
201
|
+
or "internal target" in t_low
|
|
202
|
+
or "no external benchmark applicable" in t_low
|
|
203
|
+
or t_low in {"n-a", "n/a", "—", "-"}
|
|
204
|
+
):
|
|
205
|
+
violations.append(("R2-UNCITED", src, f"target '{t}' has no URL and no INTERNAL label"))
|
|
206
|
+
# R1 — GUI tools are not verification
|
|
207
|
+
if verify:
|
|
208
|
+
v_low = verify.lower()
|
|
209
|
+
for tool in GUI_TOOLS:
|
|
210
|
+
if tool in v_low:
|
|
211
|
+
violations.append(("R1-GUI-TOOL", src, f"'{verify}' is a GUI tool, not a shell command"))
|
|
212
|
+
break
|
|
213
|
+
# R1 — measured rows need verbatim output nearby…
|
|
214
|
+
fences = section_fences(text, end_idx)
|
|
215
|
+
if has_measured_row and not fences:
|
|
216
|
+
violations.append(("R1-NO-OUTPUT", src, "table has MEASURED/measured rows but no fenced raw-output block before next heading"))
|
|
217
|
+
# …and each measured row must be traceable to ITS verify command
|
|
218
|
+
elif fences:
|
|
219
|
+
joined = "\n".join(fences)
|
|
220
|
+
for metric, verify in measured_rows:
|
|
221
|
+
if verify and verify not in {"—", "-", ""} and verify not in joined:
|
|
222
|
+
violations.append(("R1-UNLINKED-OUTPUT", src, f"measured metric '{metric}': verify command '{verify}' appears in no fenced output block"))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def check_task_table(header, rows, violations, src, protected):
|
|
226
|
+
ii = col(header, "id")
|
|
227
|
+
sev_i = col(header, "sev")
|
|
228
|
+
st_i = col(header, "status")
|
|
229
|
+
d_i = col(header, "description")
|
|
230
|
+
if ii is None or st_i is None:
|
|
231
|
+
return
|
|
232
|
+
for r in rows:
|
|
233
|
+
def cell(ix):
|
|
234
|
+
return r[ix] if ix is not None and ix < len(r) else ""
|
|
235
|
+
tid, sev, status, desc = cell(ii), cell(sev_i), cell(st_i), cell(d_i)
|
|
236
|
+
if tid and not ID_RE.match(tid):
|
|
237
|
+
violations.append(("R5-BAD-ID", src, f"task id '{tid}' != L<loop>-T<n>"))
|
|
238
|
+
if status and status not in TASK_STATUSES:
|
|
239
|
+
violations.append(("R5-BAD-STATUS", src, f"status '{status}' not in {sorted(TASK_STATUSES)}"))
|
|
240
|
+
if sev and sev not in SEVERITIES:
|
|
241
|
+
violations.append(("R5-BAD-SEV", src, f"severity '{sev}' not in {sorted(SEVERITIES)}"))
|
|
242
|
+
if status == "BLOCKED" and "root cause" not in " ".join(r).lower():
|
|
243
|
+
violations.append(("R6-NO-ROOTCAUSE", src, f"BLOCKED task '{tid}' has no 'Root cause:' note"))
|
|
244
|
+
if status == "DONE" and protected:
|
|
245
|
+
joined = " ".join(r)
|
|
246
|
+
for p in protected:
|
|
247
|
+
if p and p in joined:
|
|
248
|
+
violations.append(("R3-PROTECTED", src, f"DONE task '{tid}' touches protected path '{p}'"))
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
APPROVED_RE = re.compile(r"^Approved:\s*(.+)$", re.MULTILINE)
|
|
252
|
+
MODE_GATED_RE = re.compile(r"(?mi)^\s*-?\s*Mode:\s*gated\b")
|
|
253
|
+
EXECUTED_STATUSES = {"DONE", "IN-PROGRESS", "BLOCKED"}
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def check_approvals(text, violations, src):
|
|
257
|
+
"""Gated-mode invariant: every executed task (DONE / IN-PROGRESS /
|
|
258
|
+
BLOCKED) in a loop section must be listed on that section's `Approved:`
|
|
259
|
+
line. The check fires when the line exists OR the section echoes
|
|
260
|
+
`Mode: gated` (v1.1.0) — a gated loop with executed tasks and no
|
|
261
|
+
`Approved:` line is a violation, not an exemption. Sections declaring
|
|
262
|
+
neither are treated as autonomous and not checked."""
|
|
263
|
+
sections = re.split(r"(?m)^## (?=Loop\b)", text)
|
|
264
|
+
for sec in sections:
|
|
265
|
+
m = APPROVED_RE.search(sec)
|
|
266
|
+
gated = MODE_GATED_RE.search(sec) is not None
|
|
267
|
+
if not m and not gated:
|
|
268
|
+
continue
|
|
269
|
+
if m:
|
|
270
|
+
raw = m.group(1).strip()
|
|
271
|
+
approved = set() if raw.lower() == "none" else {norm(x) for x in raw.split(",") if x.strip()}
|
|
272
|
+
else:
|
|
273
|
+
approved = set()
|
|
274
|
+
for header, rows, _ in parse_tables(sec):
|
|
275
|
+
ii, st_i = col(header, "id"), col(header, "status")
|
|
276
|
+
if ii is None or st_i is None or col(header, "metric") is not None:
|
|
277
|
+
continue
|
|
278
|
+
for r in rows:
|
|
279
|
+
tid = r[ii] if ii < len(r) else ""
|
|
280
|
+
status = r[st_i] if st_i < len(r) else ""
|
|
281
|
+
if status in EXECUTED_STATUSES and tid and tid not in approved:
|
|
282
|
+
why = ("not on this loop's Approved: line" if m
|
|
283
|
+
else "this gated loop has no Approved: line at all")
|
|
284
|
+
violations.append(("GATED-UNAPPROVED-EXEC", src,
|
|
285
|
+
f"task '{tid}' is {status} but {why}"))
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def check_secrets(text, violations, src):
|
|
289
|
+
for kind, pat in SECRET_PATTERNS:
|
|
290
|
+
for m in pat.finditer(text):
|
|
291
|
+
ctx = text[max(0, m.start() - 40):m.start()]
|
|
292
|
+
if "[REDACTED:" in ctx + m.group(0):
|
|
293
|
+
continue
|
|
294
|
+
violations.append(("R8-SECRET", src, f"unredacted {kind} matching '{m.group(0)[:12]}…'"))
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
MODE_LINE_RE = re.compile(r"(?mi)^\s*-?\s*Mode:\s*\S+")
|
|
298
|
+
NO_FINDINGS_RE = re.compile(r"No significant findings", re.IGNORECASE)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def check_template_conformance(text, violations, src):
|
|
302
|
+
"""BLINDSPOTS BS-12 — the meta-tripwire. Every other check activates only
|
|
303
|
+
when output LOOKS like the Phase 2 template (pipe tables, headings, Mode
|
|
304
|
+
echo); a run that emits prose instead silently escapes all of them. This
|
|
305
|
+
converts that silent escape into a violation, making the rest of the rule
|
|
306
|
+
set load-bearing. Per loop section the template requires a `Mode:` line in
|
|
307
|
+
Scope & method, and EITHER (benchmark table AND task table) OR the R7
|
|
308
|
+
"No significant findings" line (a tabled-baselines-but-no-tasks loop also
|
|
309
|
+
carries that line, so benchmark-table-only sections remain conformant)."""
|
|
310
|
+
sections = re.split(r"(?m)^##\s+(?=Loop\b)", text)[1:]
|
|
311
|
+
if not sections:
|
|
312
|
+
violations.append(("TEMPLATE-NONCONFORMANT", src,
|
|
313
|
+
"no '## Loop <N>' section found — output does not follow the Phase 2 template"))
|
|
314
|
+
return
|
|
315
|
+
for sec in sections:
|
|
316
|
+
loop_id = (sec.splitlines() or ["?"])[0].strip()
|
|
317
|
+
if not MODE_LINE_RE.search(sec):
|
|
318
|
+
violations.append(("TEMPLATE-NONCONFORMANT", src,
|
|
319
|
+
f"'{loop_id}': Scope & method has no 'Mode:' line (required since v1.1.0)"))
|
|
320
|
+
tables = list(parse_tables(sec))
|
|
321
|
+
has_bench = any(col(h, "metric") is not None and col(h, "baseline") is not None for h, _, _ in tables)
|
|
322
|
+
has_task = any(col(h, "id") is not None and col(h, "status") is not None
|
|
323
|
+
and col(h, "metric") is None for h, _, _ in tables)
|
|
324
|
+
if not (has_bench and has_task) and not NO_FINDINGS_RE.search(sec):
|
|
325
|
+
violations.append(("TEMPLATE-NONCONFORMANT", src,
|
|
326
|
+
f"'{loop_id}': missing benchmark and/or task table and no 'No significant findings' line"))
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
CONFIG_ENUMS = {
|
|
330
|
+
"MODE": {"gated", "autonomous"},
|
|
331
|
+
"DEPTH": {"quick", "standard", "deep"},
|
|
332
|
+
"BENCHMARK_MODE": {"auto", "provided", "none"},
|
|
333
|
+
"SEVERITY_FLOOR": {"Critical", "High", "Medium", "Low"},
|
|
334
|
+
}
|
|
335
|
+
PLACEHOLDER_RE = re.compile(r"<[^<>\n]*>")
|
|
336
|
+
CONFIG_KEY_RE = re.compile(r"^([A-Z][A-Z_]+):\s*(.*)$")
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def parse_audit_config(audit_md: Path):
|
|
340
|
+
"""Flat KEY: value parse of the CONFIG block in a target repo's AUDIT.md.
|
|
341
|
+
Trailing `# comment` text is stripped; placeholder text is preserved."""
|
|
342
|
+
cfg, in_config = {}, False
|
|
343
|
+
for line in audit_md.read_text(encoding="utf-8").splitlines():
|
|
344
|
+
if re.match(r"^##\s*CONFIG\b", line):
|
|
345
|
+
in_config = True
|
|
346
|
+
continue
|
|
347
|
+
if in_config and re.match(r"^##\s", line):
|
|
348
|
+
break
|
|
349
|
+
if not in_config:
|
|
350
|
+
continue
|
|
351
|
+
m = CONFIG_KEY_RE.match(line.strip())
|
|
352
|
+
if not m:
|
|
353
|
+
continue
|
|
354
|
+
key, raw = m.groups()
|
|
355
|
+
cfg[key] = re.split(r"\s+#", raw, 1)[0].strip()
|
|
356
|
+
return cfg
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def check_config_preflight(target_root: Path, violations, protected):
|
|
360
|
+
"""Phase 0 CONFIG preflight (review gap G-D) + PROTECTED_AREAS auto-load
|
|
361
|
+
(gap G-F). Runs only when the target's AUDIT.md is present; placeholder
|
|
362
|
+
values never silently configure anything."""
|
|
363
|
+
audit = target_root / "AUDIT.md"
|
|
364
|
+
if not audit.exists():
|
|
365
|
+
return
|
|
366
|
+
cfg = parse_audit_config(audit)
|
|
367
|
+
for key, val in cfg.items():
|
|
368
|
+
if PLACEHOLDER_RE.search(val):
|
|
369
|
+
violations.append(("CONFIG-PLACEHOLDER", "AUDIT.md",
|
|
370
|
+
f"{key} still contains unedited template text: '{val[:60]}'"))
|
|
371
|
+
elif key in CONFIG_ENUMS and val and val not in CONFIG_ENUMS[key]:
|
|
372
|
+
violations.append(("CONFIG-BAD-ENUM", "AUDIT.md",
|
|
373
|
+
f"{key} '{val}' not in {sorted(CONFIG_ENUMS[key])}"))
|
|
374
|
+
areas = cfg.get("PROTECTED_AREAS", "")
|
|
375
|
+
if areas and not PLACEHOLDER_RE.search(areas):
|
|
376
|
+
for p in areas.split(","):
|
|
377
|
+
p = p.strip()
|
|
378
|
+
if p and p not in protected:
|
|
379
|
+
protected.append(p)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def validate_run(run_dir: Path, protected=None):
|
|
383
|
+
"""Validate one run directory (containing docs/BACKLOG.md, docs/HANDOFF.md)."""
|
|
384
|
+
protected = list(protected or [])
|
|
385
|
+
violations = []
|
|
386
|
+
docs = run_dir / "docs" if (run_dir / "docs").is_dir() else run_dir
|
|
387
|
+
# The target repo's root is docs/'s parent — whether --run was pointed at
|
|
388
|
+
# the repo root or at docs/ itself. CONFIG preflight may extend `protected`.
|
|
389
|
+
check_config_preflight(docs.parent, violations, protected)
|
|
390
|
+
backlog = docs / "BACKLOG.md"
|
|
391
|
+
handoff = docs / "HANDOFF.md"
|
|
392
|
+
if not backlog.exists():
|
|
393
|
+
violations.append(("MISSING-FILE", "docs/BACKLOG.md", "file not found"))
|
|
394
|
+
if backlog.exists():
|
|
395
|
+
text = backlog.read_text(encoding="utf-8")
|
|
396
|
+
check_template_conformance(text, violations, "BACKLOG.md")
|
|
397
|
+
check_secrets(text, violations, "BACKLOG.md")
|
|
398
|
+
check_approvals(text, violations, "BACKLOG.md")
|
|
399
|
+
for header, rows, end in parse_tables(text):
|
|
400
|
+
if col(header, "metric") is not None and col(header, "final") is None:
|
|
401
|
+
check_benchmark_like_table(header, rows, end, text, violations, "BACKLOG.md", is_handoff=False)
|
|
402
|
+
elif col(header, "status") is not None and col(header, "id") is not None:
|
|
403
|
+
check_task_table(header, rows, violations, "BACKLOG.md", protected)
|
|
404
|
+
if handoff.exists():
|
|
405
|
+
text = handoff.read_text(encoding="utf-8")
|
|
406
|
+
check_secrets(text, violations, "HANDOFF.md")
|
|
407
|
+
if not STOP_RE.search(text):
|
|
408
|
+
violations.append(("P5-NO-STOP-REASON", "HANDOFF.md", "no 'Stop condition: (a|b|c)' line"))
|
|
409
|
+
for header, rows, end in parse_tables(text):
|
|
410
|
+
if col(header, "metric") is not None:
|
|
411
|
+
check_benchmark_like_table(header, rows, end, text, violations, "HANDOFF.md", is_handoff=(col(header, "final") is not None))
|
|
412
|
+
elif col(header, "status") is not None and col(header, "id") is not None:
|
|
413
|
+
check_task_table(header, rows, violations, "HANDOFF.md", protected)
|
|
414
|
+
return violations
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
LOOP_HEAD_RE = re.compile(r"^Loop\s+(\d+)\s*(?:—|-)?\s*(.*)$")
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def build_report(run_dir: Path, protected, violations):
|
|
421
|
+
"""Findings export (review gap G-G): one structured object per run, for
|
|
422
|
+
roll-ups across projects, trend dashboards, and client-facing summaries.
|
|
423
|
+
Parses the same artifacts the validator checks — no second source of truth."""
|
|
424
|
+
import datetime
|
|
425
|
+
docs = run_dir / "docs" if (run_dir / "docs").is_dir() else run_dir
|
|
426
|
+
audit = docs.parent / "AUDIT.md"
|
|
427
|
+
protocol_version = None
|
|
428
|
+
protected = list(protected)
|
|
429
|
+
if audit.exists():
|
|
430
|
+
m = re.search(r"v\d+\.\d+\.\d+", audit.read_text(encoding="utf-8").splitlines()[0])
|
|
431
|
+
protocol_version = m.group(0) if m else None
|
|
432
|
+
check_config_preflight(docs.parent, [], protected) # mirror the auto-load; violations already counted
|
|
433
|
+
report = {
|
|
434
|
+
"schema": "code-audit-framework/report@1",
|
|
435
|
+
"generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
|
|
436
|
+
"run_dir": str(run_dir),
|
|
437
|
+
"protocol_version": protocol_version,
|
|
438
|
+
"protected_areas": protected,
|
|
439
|
+
"loops": [],
|
|
440
|
+
"metrics": [],
|
|
441
|
+
"summary": {},
|
|
442
|
+
}
|
|
443
|
+
backlog = docs / "BACKLOG.md"
|
|
444
|
+
if backlog.exists():
|
|
445
|
+
text = backlog.read_text(encoding="utf-8")
|
|
446
|
+
for sec in re.split(r"(?m)^##\s+(?=Loop\b)", text)[1:]:
|
|
447
|
+
first = (sec.splitlines() or [""])[0]
|
|
448
|
+
hm = LOOP_HEAD_RE.match(first.strip())
|
|
449
|
+
mode_m = re.search(r"(?mi)^\s*-?\s*Mode:\s*(\S+)", sec)
|
|
450
|
+
appr_m = APPROVED_RE.search(sec)
|
|
451
|
+
loop = {
|
|
452
|
+
"loop": int(hm.group(1)) if hm else None,
|
|
453
|
+
"date": (hm.group(2).strip() or None) if hm else None,
|
|
454
|
+
"mode": mode_m.group(1) if mode_m else None,
|
|
455
|
+
"approved": ([] if appr_m.group(1).strip().lower() == "none"
|
|
456
|
+
else [norm(x) for x in appr_m.group(1).split(",") if x.strip()]) if appr_m else None,
|
|
457
|
+
"no_significant_findings": bool(NO_FINDINGS_RE.search(sec)),
|
|
458
|
+
"tasks": [],
|
|
459
|
+
}
|
|
460
|
+
for header, rows, _ in parse_tables(sec):
|
|
461
|
+
ii, st_i = col(header, "id"), col(header, "status")
|
|
462
|
+
if ii is None or st_i is None or col(header, "metric") is not None:
|
|
463
|
+
continue
|
|
464
|
+
sev_i, vec_i, d_i, v_i = (col(header, "sev"), col(header, "vector"),
|
|
465
|
+
col(header, "description"), col(header, "verify"))
|
|
466
|
+
for r in rows:
|
|
467
|
+
def cell(ix):
|
|
468
|
+
return r[ix] if ix is not None and ix < len(r) else ""
|
|
469
|
+
if cell(ii):
|
|
470
|
+
loop["tasks"].append({
|
|
471
|
+
"id": cell(ii), "severity": cell(sev_i), "status": cell(st_i),
|
|
472
|
+
"vector": cell(vec_i), "description": cell(d_i), "verify": cell(v_i),
|
|
473
|
+
})
|
|
474
|
+
report["loops"].append(loop)
|
|
475
|
+
handoff = docs / "HANDOFF.md"
|
|
476
|
+
if handoff.exists():
|
|
477
|
+
text = handoff.read_text(encoding="utf-8")
|
|
478
|
+
for header, rows, _ in parse_tables(text):
|
|
479
|
+
mi, fi = col(header, "metric"), col(header, "final")
|
|
480
|
+
if mi is None or fi is None:
|
|
481
|
+
continue
|
|
482
|
+
bi, di, ti, vi, si = (col(header, "baseline"), col(header, "delta"),
|
|
483
|
+
col(header, "target"), col(header, "verify"), col(header, "status"))
|
|
484
|
+
for r in rows:
|
|
485
|
+
def cell(ix):
|
|
486
|
+
return r[ix] if ix is not None and ix < len(r) else ""
|
|
487
|
+
if cell(mi):
|
|
488
|
+
report["metrics"].append({
|
|
489
|
+
"metric": cell(mi), "baseline": cell(bi), "final": cell(fi),
|
|
490
|
+
"delta": cell(di), "target": cell(ti), "verify": cell(vi), "status": cell(si),
|
|
491
|
+
})
|
|
492
|
+
tasks = [t for l in report["loops"] for t in l["tasks"]]
|
|
493
|
+
by = lambda key: {k: sum(1 for t in tasks if t[key] == k) # noqa: E731
|
|
494
|
+
for k in sorted({t[key] for t in tasks if t[key]})}
|
|
495
|
+
vio_codes = {}
|
|
496
|
+
for c, _, _ in violations:
|
|
497
|
+
vio_codes[c] = vio_codes.get(c, 0) + 1
|
|
498
|
+
report["summary"] = {
|
|
499
|
+
"loops": len(report["loops"]),
|
|
500
|
+
"tasks": len(tasks),
|
|
501
|
+
"tasks_by_status": by("status"),
|
|
502
|
+
"tasks_by_severity": by("severity"),
|
|
503
|
+
"metrics_measured": sum(1 for m in report["metrics"] if m["status"] == "MEASURED"),
|
|
504
|
+
"violations": len(violations),
|
|
505
|
+
"violations_by_code": dict(sorted(vio_codes.items())),
|
|
506
|
+
"clean": not violations,
|
|
507
|
+
}
|
|
508
|
+
report["violations"] = [{"code": c, "file": s, "detail": d} for c, s, d in violations]
|
|
509
|
+
return report
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def to_sarif(report):
|
|
513
|
+
"""Minimal SARIF 2.1.0 for GitHub code scanning (review F5, optional output)."""
|
|
514
|
+
rules, results = {}, []
|
|
515
|
+
for v in report["violations"]:
|
|
516
|
+
rules.setdefault(v["code"], {"id": v["code"], "name": v["code"],
|
|
517
|
+
"shortDescription": {"text": v["code"]}})
|
|
518
|
+
results.append({
|
|
519
|
+
"ruleId": v["code"],
|
|
520
|
+
"level": "error",
|
|
521
|
+
"message": {"text": v["detail"]},
|
|
522
|
+
"locations": [{"physicalLocation": {"artifactLocation": {"uri": f"docs/{v['file']}"
|
|
523
|
+
if not v["file"].endswith("AUDIT.md") else v["file"]}}}],
|
|
524
|
+
})
|
|
525
|
+
return {
|
|
526
|
+
"$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
|
|
527
|
+
"version": "2.1.0",
|
|
528
|
+
"runs": [{
|
|
529
|
+
"tool": {"driver": {
|
|
530
|
+
"name": "code-audit-framework",
|
|
531
|
+
"informationUri": "https://github.com/cyberskill-official/code-audit-framework",
|
|
532
|
+
"version": (report.get("protocol_version") or "unknown").lstrip("v"),
|
|
533
|
+
"rules": list(rules.values()),
|
|
534
|
+
}},
|
|
535
|
+
"results": results,
|
|
536
|
+
}],
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def load_fixture_meta(fdir: Path):
|
|
541
|
+
"""fixture.yaml is intentionally flat key: value (no YAML dependency)."""
|
|
542
|
+
meta = {"id": fdir.name, "expect": "pass", "expected_violations": [], "protected_areas": [], "exercises_rules": []}
|
|
543
|
+
f = fdir / "fixture.yaml"
|
|
544
|
+
if f.exists():
|
|
545
|
+
for line in f.read_text(encoding="utf-8").splitlines():
|
|
546
|
+
line = line.strip()
|
|
547
|
+
if ":" not in line or line.startswith("#"):
|
|
548
|
+
continue
|
|
549
|
+
k, _, v = line.partition(":")
|
|
550
|
+
k, v = k.strip(), v.strip()
|
|
551
|
+
if k in ("expected_violations", "protected_areas", "exercises_rules"):
|
|
552
|
+
meta[k] = [x.strip() for x in v.strip("[]").split(",") if x.strip()]
|
|
553
|
+
elif k in ("id", "expect", "description"):
|
|
554
|
+
meta[k] = v
|
|
555
|
+
return meta
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def check_registry(fixture_dirs):
|
|
559
|
+
"""Registry drift guard (improve/BLINDSPOTS.md BS-10): rules.json must
|
|
560
|
+
agree with fixtures/ on disk, in both directions. A rule referencing a
|
|
561
|
+
missing fixture means its coverage silently died; an unregistered fixture
|
|
562
|
+
means coverage the registry does not own."""
|
|
563
|
+
problems = []
|
|
564
|
+
reg = HERE / "rules.json"
|
|
565
|
+
if not reg.exists():
|
|
566
|
+
return ["rules.json missing — registry is mandatory"]
|
|
567
|
+
try:
|
|
568
|
+
data = json.loads(reg.read_text(encoding="utf-8"))
|
|
569
|
+
except json.JSONDecodeError as e:
|
|
570
|
+
return [f"rules.json unparseable: {e}"]
|
|
571
|
+
on_disk = {d.name for d in fixture_dirs}
|
|
572
|
+
referenced = set()
|
|
573
|
+
for rule in data.get("rules", []):
|
|
574
|
+
for fx in rule.get("fixtures_exercising", []):
|
|
575
|
+
referenced.add(fx)
|
|
576
|
+
if fx not in on_disk:
|
|
577
|
+
problems.append(f"rules.json: {rule.get('rule_id', '?')} references missing fixture '{fx}'")
|
|
578
|
+
for d in sorted(on_disk - referenced):
|
|
579
|
+
problems.append(f"fixture '{d}' exists on disk but is registered under no rule in rules.json")
|
|
580
|
+
return problems
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def run_all(as_json=False):
|
|
584
|
+
results, ok = [], True
|
|
585
|
+
fixtures = sorted(d for d in FIXTURES.iterdir() if d.is_dir())
|
|
586
|
+
registry_problems = check_registry(fixtures)
|
|
587
|
+
ok &= not registry_problems
|
|
588
|
+
for fdir in fixtures:
|
|
589
|
+
meta = load_fixture_meta(fdir)
|
|
590
|
+
violations = validate_run(fdir, protected=meta["protected_areas"])
|
|
591
|
+
codes = sorted({c for c, _, _ in violations})
|
|
592
|
+
expected = sorted(set(meta["expected_violations"]))
|
|
593
|
+
if meta["expect"] == "pass":
|
|
594
|
+
fixture_ok = not violations
|
|
595
|
+
verdict_note = "clean" if fixture_ok else f"unexpected: {codes}"
|
|
596
|
+
else: # expect: fail — the validator MUST catch exactly the planted faults
|
|
597
|
+
fixture_ok = codes == expected
|
|
598
|
+
verdict_note = "trapped as expected" if fixture_ok else f"expected {expected}, got {codes}"
|
|
599
|
+
ok &= fixture_ok
|
|
600
|
+
results.append({
|
|
601
|
+
"fixture": meta["id"], "expect": meta["expect"],
|
|
602
|
+
"violations": [f"{c} [{s}] {d}" for c, s, d in violations],
|
|
603
|
+
"codes": codes, "ok": fixture_ok, "note": verdict_note,
|
|
604
|
+
})
|
|
605
|
+
summary = {"fixtures": len(results), "passed": sum(r["ok"] for r in results), "all_ok": ok,
|
|
606
|
+
"registry_problems": registry_problems, "results": results}
|
|
607
|
+
if as_json:
|
|
608
|
+
print(json.dumps(summary, indent=2))
|
|
609
|
+
else:
|
|
610
|
+
for p in registry_problems:
|
|
611
|
+
print(f"[FAIL] REGISTRY DRIFT — {p}")
|
|
612
|
+
for r in results:
|
|
613
|
+
print(f"[{'PASS' if r['ok'] else 'FAIL'}] {r['fixture']:32s} expect={r['expect']:4s} → {r['note']}")
|
|
614
|
+
print(f"\n{summary['passed']}/{summary['fixtures']} fixtures OK — "
|
|
615
|
+
+ ("ALL GREEN" if ok else "REGRESSIONS PRESENT"))
|
|
616
|
+
return 0 if ok else 1
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def main():
|
|
620
|
+
ap = argparse.ArgumentParser()
|
|
621
|
+
ap.add_argument("--run", help="validate one run directory (containing docs/)")
|
|
622
|
+
ap.add_argument("--all", action="store_true", help="run the full fixture suite")
|
|
623
|
+
ap.add_argument("--json", action="store_true")
|
|
624
|
+
ap.add_argument("--report", choices=["json", "sarif"],
|
|
625
|
+
help="with --run: emit a structured findings report instead of plain violations")
|
|
626
|
+
ap.add_argument("--protected", default="", help="comma-separated protected paths (extends the target AUDIT.md's PROTECTED_AREAS)")
|
|
627
|
+
args = ap.parse_args()
|
|
628
|
+
if args.all:
|
|
629
|
+
sys.exit(run_all(as_json=args.json))
|
|
630
|
+
if args.run:
|
|
631
|
+
protected = [p for p in args.protected.split(",") if p]
|
|
632
|
+
v = validate_run(Path(args.run), protected=protected)
|
|
633
|
+
if args.report:
|
|
634
|
+
report = build_report(Path(args.run), protected, v)
|
|
635
|
+
print(json.dumps(to_sarif(report) if args.report == "sarif" else report, indent=2))
|
|
636
|
+
elif args.json:
|
|
637
|
+
print(json.dumps([{"code": c, "file": s, "detail": d} for c, s, d in v], indent=2))
|
|
638
|
+
else:
|
|
639
|
+
for c, s, d in v:
|
|
640
|
+
print(f"VIOLATION {c} [{s}] {d}")
|
|
641
|
+
print("CLEAN — no violations" if not v else f"{len(v)} violation(s)")
|
|
642
|
+
sys.exit(0 if not v else 1)
|
|
643
|
+
ap.print_help()
|
|
644
|
+
sys.exit(2)
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
if __name__ == "__main__":
|
|
648
|
+
main()
|