auditex 2.0.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.
Files changed (321) hide show
  1. auditex/__init__.py +23 -0
  2. auditex/__main__.py +4 -0
  3. auditex/answer_checks.py +292 -0
  4. auditex/answer_digest.py +407 -0
  5. auditex/answer_frames.json +40 -0
  6. auditex/assessment_review.py +355 -0
  7. auditex/assessment_sources.py +16 -0
  8. auditex/auth_runtime.py +218 -0
  9. auditex/bootstrap.py +340 -0
  10. auditex/ce_plus.py +684 -0
  11. auditex/cli.py +1599 -0
  12. auditex/command_builders.py +256 -0
  13. auditex/command_runner.py +386 -0
  14. auditex/compare.py +834 -0
  15. auditex/demo.py +476 -0
  16. auditex/evidence_db.py +8 -0
  17. auditex/explorer.py +1237 -0
  18. auditex/explorer_assets/LICENSE-lucide.txt +43 -0
  19. auditex/explorer_assets/explorer.css +509 -0
  20. auditex/explorer_assets/explorer.html +64 -0
  21. auditex/explorer_assets/explorer.js +990 -0
  22. auditex/explorer_assets/fonts/Barlow-400-latin-ext.woff2 +0 -0
  23. auditex/explorer_assets/fonts/Barlow-400-latin-ext.woff2.range +1 -0
  24. auditex/explorer_assets/fonts/Barlow-400-latin.woff2 +0 -0
  25. auditex/explorer_assets/fonts/Barlow-400-latin.woff2.range +1 -0
  26. auditex/explorer_assets/fonts/Barlow-600-latin-ext.woff2 +0 -0
  27. auditex/explorer_assets/fonts/Barlow-600-latin-ext.woff2.range +1 -0
  28. auditex/explorer_assets/fonts/Barlow-600-latin.woff2 +0 -0
  29. auditex/explorer_assets/fonts/Barlow-600-latin.woff2.range +1 -0
  30. auditex/explorer_assets/fonts/BarlowCondensed-600-latin-ext.woff2 +0 -0
  31. auditex/explorer_assets/fonts/BarlowCondensed-600-latin-ext.woff2.range +1 -0
  32. auditex/explorer_assets/fonts/BarlowCondensed-600-latin.woff2 +0 -0
  33. auditex/explorer_assets/fonts/BarlowCondensed-600-latin.woff2.range +1 -0
  34. auditex/explorer_assets/fonts/OFL.txt +93 -0
  35. auditex/exporters.py +95 -0
  36. auditex/external_assessments.py +319 -0
  37. auditex/features.py +15 -0
  38. auditex/gate.py +825 -0
  39. auditex/google_workspace/__init__.py +17 -0
  40. auditex/google_workspace/auth.py +403 -0
  41. auditex/google_workspace/client.py +688 -0
  42. auditex/google_workspace/collectors.py +998 -0
  43. auditex/google_workspace/findings.py +2330 -0
  44. auditex/google_workspace/normalize.py +773 -0
  45. auditex/google_workspace/run.py +1219 -0
  46. auditex/guided.py +338 -0
  47. auditex/local_answer.py +1045 -0
  48. auditex/mcp_paths.py +139 -0
  49. auditex/mcp_registry.py +270 -0
  50. auditex/mcp_server.py +1443 -0
  51. auditex/notify.py +763 -0
  52. auditex/operator_flow.py +47 -0
  53. auditex/output_writers.py +211 -0
  54. auditex/reporting.py +4699 -0
  55. auditex/rule_assessment.py +493 -0
  56. auditex/rules.py +356 -0
  57. auditex/run_bundle.py +544 -0
  58. auditex/scope_postcheck.py +81 -0
  59. auditex/scuba_adapters_aad.py +398 -0
  60. auditex/scuba_adapters_defender.py +162 -0
  61. auditex/scuba_adapters_exchange.py +63 -0
  62. auditex/scuba_adapters_powerplat.py +94 -0
  63. auditex/scuba_adapters_teams.py +230 -0
  64. auditex/scuba_projection.py +2345 -0
  65. auditex/scubagear_export.py +871 -0
  66. auditex/scubagear_prune_proof.py +575 -0
  67. auditex/setup_guide.py +668 -0
  68. auditex-2.0.0.data/data/auditex/agent/agent-prompt.md +60 -0
  69. auditex-2.0.0.data/data/auditex/agent/tenant-audit-skill.json +265 -0
  70. auditex-2.0.0.data/data/auditex/assets/auditex-logo-64.png +0 -0
  71. auditex-2.0.0.data/data/auditex/assets/auditex-logo.svg +14 -0
  72. auditex-2.0.0.data/data/auditex/configs/assessment-sources.json +145 -0
  73. auditex-2.0.0.data/data/auditex/configs/ce-plus-practice.json +1463 -0
  74. auditex-2.0.0.data/data/auditex/configs/collector-definitions.json +990 -0
  75. auditex-2.0.0.data/data/auditex/configs/collector-permissions.json +460 -0
  76. auditex-2.0.0.data/data/auditex/configs/collector-presets.json +82 -0
  77. auditex-2.0.0.data/data/auditex/configs/control-mappings.json +3560 -0
  78. auditex-2.0.0.data/data/auditex/configs/explainer-baselines.json +10987 -0
  79. auditex-2.0.0.data/data/auditex/configs/explainer-template.json +1 -0
  80. auditex-2.0.0.data/data/auditex/configs/explainer-what-to-collect.json +27838 -0
  81. auditex-2.0.0.data/data/auditex/configs/finding-templates.json +1503 -0
  82. auditex-2.0.0.data/data/auditex/configs/framework-catalog.json +509 -0
  83. auditex-2.0.0.data/data/auditex/configs/os-end-of-life.json +736 -0
  84. auditex-2.0.0.data/data/auditex/configs/report-sections.json +129 -0
  85. auditex-2.0.0.data/data/auditex/configs/risky-delegated-permissions.json +767 -0
  86. auditex-2.0.0.data/data/auditex/configs/rule-packs.json +1709 -0
  87. auditex-2.0.0.data/data/auditex/configs/scuba-policy-sections.json +1151 -0
  88. auditex-2.0.0.data/data/auditex/configs/scuba-rule-precheck.json +538 -0
  89. auditex-2.0.0.data/data/auditex/configs/scuba-scope-blind.json +197 -0
  90. auditex-2.0.0.data/data/auditex/configs/scuba-value-rules.json +22013 -0
  91. auditex-2.0.0.data/data/auditex/docs/guides/admin-permission-guide.md +507 -0
  92. auditex-2.0.0.data/data/auditex/docs/guides/ai-assessment.md +159 -0
  93. auditex-2.0.0.data/data/auditex/docs/guides/customer-handoff-guide.md +159 -0
  94. auditex-2.0.0.data/data/auditex/docs/guides/external-assessments.md +96 -0
  95. auditex-2.0.0.data/data/auditex/docs/guides/install-guide.md +377 -0
  96. auditex-2.0.0.data/data/auditex/docs/guides/local-answer.md +114 -0
  97. auditex-2.0.0.data/data/auditex/docs/guides/model-development.md +40 -0
  98. auditex-2.0.0.data/data/auditex/docs/guides/product-manual.md +521 -0
  99. auditex-2.0.0.data/data/auditex/docs/guides/reader-app-permissions.md +328 -0
  100. auditex-2.0.0.data/data/auditex/docs/guides/setup-guide.md +249 -0
  101. auditex-2.0.0.data/data/auditex/docs/guides/troubleshooting.md +214 -0
  102. auditex-2.0.0.data/data/auditex/docs/index.md +42 -0
  103. auditex-2.0.0.data/data/auditex/docs/legal/third-party-notices.md +117 -0
  104. auditex-2.0.0.data/data/auditex/docs/legal/trademarks.md +19 -0
  105. auditex-2.0.0.data/data/auditex/docs/provenance/explainer-baselines.md +98 -0
  106. auditex-2.0.0.data/data/auditex/docs/provenance/provenance.csv +44 -0
  107. auditex-2.0.0.data/data/auditex/docs/provenance/provenance.md +199 -0
  108. auditex-2.0.0.data/data/auditex/docs/reference/api-call-catalog.md +334 -0
  109. auditex-2.0.0.data/data/auditex/docs/reference/framework-mappings.md +638 -0
  110. auditex-2.0.0.data/data/auditex/docs/reference/output-contract.md +1878 -0
  111. auditex-2.0.0.data/data/auditex/docs/reference/security-privacy.md +1077 -0
  112. auditex-2.0.0.data/data/auditex/examples/demo_tenant/demo_tenant.json +1074 -0
  113. auditex-2.0.0.data/data/auditex/examples/demo_tenant/demo_tenant_remediated.json +1083 -0
  114. auditex-2.0.0.data/data/auditex/examples/google_workspace_sample.json +563 -0
  115. auditex-2.0.0.data/data/auditex/examples/sample_audit_bundle/admin_set_result.json +382 -0
  116. auditex-2.0.0.data/data/auditex/examples/sample_audit_bundle/endpoint_posture_result.json +363 -0
  117. auditex-2.0.0.data/data/auditex/examples/sample_audit_bundle/external_maester.json +38 -0
  118. auditex-2.0.0.data/data/auditex/examples/sample_audit_bundle/external_monkey365.json +66 -0
  119. auditex-2.0.0.data/data/auditex/examples/sample_audit_bundle/external_scubagear.json +41 -0
  120. auditex-2.0.0.data/data/auditex/examples/sample_audit_bundle/identity_controls_result.json +254 -0
  121. auditex-2.0.0.data/data/auditex/examples/sample_audit_bundle/known_bad_result.json +164 -0
  122. auditex-2.0.0.data/data/auditex/examples/sample_audit_bundle/sample_result.json +41 -0
  123. auditex-2.0.0.data/data/auditex/examples/sample_audit_bundle/update_rings_missing_result.json +103 -0
  124. auditex-2.0.0.data/data/auditex/profiles/app-readonly-full.md +11 -0
  125. auditex-2.0.0.data/data/auditex/profiles/exchange-reader.md +11 -0
  126. auditex-2.0.0.data/data/auditex/profiles/global-reader.md +11 -0
  127. auditex-2.0.0.data/data/auditex/profiles/intune-reader.md +11 -0
  128. auditex-2.0.0.data/data/auditex/profiles/security-reader.md +11 -0
  129. auditex-2.0.0.data/data/auditex/schemas/ai_context.schema.json +30 -0
  130. auditex-2.0.0.data/data/auditex/schemas/blocker.schema.json +14 -0
  131. auditex-2.0.0.data/data/auditex/schemas/blockers.schema.json +6 -0
  132. auditex-2.0.0.data/data/auditex/schemas/bundle_hashes.schema.json +38 -0
  133. auditex-2.0.0.data/data/auditex/schemas/capability_matrix.schema.json +41 -0
  134. auditex-2.0.0.data/data/auditex/schemas/ce_plus_practice.schema.json +653 -0
  135. auditex-2.0.0.data/data/auditex/schemas/collector_result.schema.json +13 -0
  136. auditex-2.0.0.data/data/auditex/schemas/explainer.schema.json +13 -0
  137. auditex-2.0.0.data/data/auditex/schemas/finding.schema.json +277 -0
  138. auditex-2.0.0.data/data/auditex/schemas/local_answer.schema.json +133 -0
  139. auditex-2.0.0.data/data/auditex/schemas/model_assessment-2026-10-27.1.schema.json +288 -0
  140. auditex-2.0.0.data/data/auditex/schemas/model_assessment-2026-10-27.schema.json +271 -0
  141. auditex-2.0.0.data/data/auditex/schemas/model_assessment-2026-10-28.schema.json +453 -0
  142. auditex-2.0.0.data/data/auditex/schemas/model_assessment-2026-10-29.schema.json +1245 -0
  143. auditex-2.0.0.data/data/auditex/schemas/model_assessment-2026-11-05.schema.json +1339 -0
  144. auditex-2.0.0.data/data/auditex/schemas/model_assessment.schema.json +1387 -0
  145. auditex-2.0.0.data/data/auditex/schemas/report_pack.schema.json +41 -0
  146. auditex-2.0.0.data/data/auditex/schemas/run_manifest.schema.json +195 -0
  147. auditex-2.0.0.data/data/auditex/schemas/summary.schema.json +32 -0
  148. auditex-2.0.0.data/data/auditex/schemas/targeted_users_coverage.schema.json +29 -0
  149. auditex-2.0.0.data/data/auditex/schemas/validation.schema.json +28 -0
  150. auditex-2.0.0.data/data/auditex/skills/app-readonly-escalation/SKILL.md +26 -0
  151. auditex-2.0.0.data/data/auditex/skills/auditex-operator/SKILL.md +43 -0
  152. auditex-2.0.0.data/data/auditex/skills/evidence-pack/SKILL.md +29 -0
  153. auditex-2.0.0.dist-info/METADATA +292 -0
  154. auditex-2.0.0.dist-info/RECORD +321 -0
  155. auditex-2.0.0.dist-info/WHEEL +5 -0
  156. auditex-2.0.0.dist-info/entry_points.txt +4 -0
  157. auditex-2.0.0.dist-info/licenses/LICENSE +202 -0
  158. auditex-2.0.0.dist-info/licenses/NOTICE +46 -0
  159. auditex-2.0.0.dist-info/top_level.txt +2 -0
  160. azure_tenant_audit/__init__.py +5 -0
  161. azure_tenant_audit/__main__.py +4 -0
  162. azure_tenant_audit/adapters/__init__.py +35 -0
  163. azure_tenant_audit/adapters/base.py +34 -0
  164. azure_tenant_audit/adapters/capabilities.py +43 -0
  165. azure_tenant_audit/adapters/m365_cli.py +156 -0
  166. azure_tenant_audit/adapters/m365dsc.py +124 -0
  167. azure_tenant_audit/adapters/powershell_graph.py +655 -0
  168. azure_tenant_audit/adapters/read_guard.py +738 -0
  169. azure_tenant_audit/adapters/teams_admin_rest.py +336 -0
  170. azure_tenant_audit/ai_context.py +159 -0
  171. azure_tenant_audit/api_inventory.py +927 -0
  172. azure_tenant_audit/argument_parser.py +121 -0
  173. azure_tenant_audit/assurance.py +349 -0
  174. azure_tenant_audit/attack_graph.py +986 -0
  175. azure_tenant_audit/auth_context.py +148 -0
  176. azure_tenant_audit/auth_runtime.py +81 -0
  177. azure_tenant_audit/autopilot.py +728 -0
  178. azure_tenant_audit/baselines.py +1372 -0
  179. azure_tenant_audit/break_glass.py +499 -0
  180. azure_tenant_audit/bundle_integrity.py +467 -0
  181. azure_tenant_audit/capability_gate.py +278 -0
  182. azure_tenant_audit/catalog.py +75 -0
  183. azure_tenant_audit/certificate_auth.py +342 -0
  184. azure_tenant_audit/chunk_reader.py +167 -0
  185. azure_tenant_audit/citations.py +45 -0
  186. azure_tenant_audit/cli.py +1323 -0
  187. azure_tenant_audit/cli_guard.py +335 -0
  188. azure_tenant_audit/collection_gaps.py +584 -0
  189. azure_tenant_audit/collection_markers.py +3 -0
  190. azure_tenant_audit/collector_runner.py +342 -0
  191. azure_tenant_audit/collectors/__init__.py +75 -0
  192. azure_tenant_audit/collectors/_capability_gated.py +169 -0
  193. azure_tenant_audit/collectors/_endpoint_reads.py +371 -0
  194. azure_tenant_audit/collectors/anti_phish_admission.py +345 -0
  195. azure_tenant_audit/collectors/app_consent.py +409 -0
  196. azure_tenant_audit/collectors/app_credentials.py +392 -0
  197. azure_tenant_audit/collectors/auth_methods.py +55 -0
  198. azure_tenant_audit/collectors/base.py +564 -0
  199. azure_tenant_audit/collectors/conditional_access.py +68 -0
  200. azure_tenant_audit/collectors/consent_policy.py +192 -0
  201. azure_tenant_audit/collectors/copilot_governance.py +68 -0
  202. azure_tenant_audit/collectors/cross_tenant_access.py +187 -0
  203. azure_tenant_audit/collectors/defender.py +80 -0
  204. azure_tenant_audit/collectors/defender_cloud_apps.py +43 -0
  205. azure_tenant_audit/collectors/directory_relationships.py +93 -0
  206. azure_tenant_audit/collectors/dns_posture.py +432 -0
  207. azure_tenant_audit/collectors/domains_hybrid.py +49 -0
  208. azure_tenant_audit/collectors/ediscovery.py +435 -0
  209. azure_tenant_audit/collectors/exchange.py +70 -0
  210. azure_tenant_audit/collectors/exchange_defender_commands.py +117 -0
  211. azure_tenant_audit/collectors/exchange_policy.py +438 -0
  212. azure_tenant_audit/collectors/external_identity.py +41 -0
  213. azure_tenant_audit/collectors/identity.py +262 -0
  214. azure_tenant_audit/collectors/identity_governance.py +297 -0
  215. azure_tenant_audit/collectors/identity_protection.py +125 -0
  216. azure_tenant_audit/collectors/intune.py +105 -0
  217. azure_tenant_audit/collectors/intune_depth.py +377 -0
  218. azure_tenant_audit/collectors/licensing.py +58 -0
  219. azure_tenant_audit/collectors/mailbox_forwarding.py +534 -0
  220. azure_tenant_audit/collectors/onedrive_posture.py +122 -0
  221. azure_tenant_audit/collectors/power_bi.py +83 -0
  222. azure_tenant_audit/collectors/power_platform.py +249 -0
  223. azure_tenant_audit/collectors/purview.py +274 -0
  224. azure_tenant_audit/collectors/reports_usage.py +162 -0
  225. azure_tenant_audit/collectors/security.py +78 -0
  226. azure_tenant_audit/collectors/sentinel_xdr.py +37 -0
  227. azure_tenant_audit/collectors/service_health.py +41 -0
  228. azure_tenant_audit/collectors/sharepoint.py +52 -0
  229. azure_tenant_audit/collectors/sharepoint_access.py +358 -0
  230. azure_tenant_audit/collectors/sharepoint_admin.py +440 -0
  231. azure_tenant_audit/collectors/targeted_users_coverage.py +799 -0
  232. azure_tenant_audit/collectors/teams.py +109 -0
  233. azure_tenant_audit/collectors/teams_policy.py +170 -0
  234. azure_tenant_audit/config.py +104 -0
  235. azure_tenant_audit/contracts.py +1084 -0
  236. azure_tenant_audit/cyber_essentials.py +195 -0
  237. azure_tenant_audit/data_handling.py +236 -0
  238. azure_tenant_audit/data_minimisation.py +201 -0
  239. azure_tenant_audit/detection_coverage.py +364 -0
  240. azure_tenant_audit/diagnostics.py +153 -0
  241. azure_tenant_audit/diffing.py +655 -0
  242. azure_tenant_audit/directory_relationships.py +31 -0
  243. azure_tenant_audit/dns_lookup.py +819 -0
  244. azure_tenant_audit/effective_admins.py +602 -0
  245. azure_tenant_audit/endpoint_posture.py +558 -0
  246. azure_tenant_audit/evidence_db.py +600 -0
  247. azure_tenant_audit/evidence_gates.py +186 -0
  248. azure_tenant_audit/evidence_refs.py +409 -0
  249. azure_tenant_audit/exchange_protection.py +237 -0
  250. azure_tenant_audit/explainer/__init__.py +52 -0
  251. azure_tenant_audit/explainer/adapter.py +35 -0
  252. azure_tenant_audit/explainer/baselines.py +450 -0
  253. azure_tenant_audit/explainer/collection.py +183 -0
  254. azure_tenant_audit/explainer/generate.py +224 -0
  255. azure_tenant_audit/explainer/render.py +214 -0
  256. azure_tenant_audit/explainer/textkit.py +336 -0
  257. azure_tenant_audit/explainer/view.py +100 -0
  258. azure_tenant_audit/exposure_lookup.py +498 -0
  259. azure_tenant_audit/external_sharing.py +529 -0
  260. azure_tenant_audit/finalize.py +373 -0
  261. azure_tenant_audit/findings.py +4648 -0
  262. azure_tenant_audit/friendly_names.py +165 -0
  263. azure_tenant_audit/graph.py +1098 -0
  264. azure_tenant_audit/guarded_io.py +1304 -0
  265. azure_tenant_audit/identity_controls.py +1698 -0
  266. azure_tenant_audit/normalize.py +3376 -0
  267. azure_tenant_audit/offline_replay.py +243 -0
  268. azure_tenant_audit/os_lifecycle.py +224 -0
  269. azure_tenant_audit/output.py +1109 -0
  270. azure_tenant_audit/output_redaction.py +2871 -0
  271. azure_tenant_audit/partner_domains.py +180 -0
  272. azure_tenant_audit/perf_runtime.py +106 -0
  273. azure_tenant_audit/power_bi.py +58 -0
  274. azure_tenant_audit/power_platform.py +141 -0
  275. azure_tenant_audit/presets.py +80 -0
  276. azure_tenant_audit/private_io.py +173 -0
  277. azure_tenant_audit/privileged_roles.py +246 -0
  278. azure_tenant_audit/probe.py +743 -0
  279. azure_tenant_audit/profiles.py +257 -0
  280. azure_tenant_audit/provider_registry.py +21 -0
  281. azure_tenant_audit/provider_runtime.py +127 -0
  282. azure_tenant_audit/resources.py +220 -0
  283. azure_tenant_audit/response.py +829 -0
  284. azure_tenant_audit/rule_parameters.py +167 -0
  285. azure_tenant_audit/run.py +552 -0
  286. azure_tenant_audit/run_files.py +182 -0
  287. azure_tenant_audit/scope_catalog.py +195 -0
  288. azure_tenant_audit/scuba_assessment.py +646 -0
  289. azure_tenant_audit/scuba_precheck.py +316 -0
  290. azure_tenant_audit/scuba_scope.py +213 -0
  291. azure_tenant_audit/secret_hygiene.py +717 -0
  292. azure_tenant_audit/selection.py +31 -0
  293. azure_tenant_audit/sensitive_users.py +178 -0
  294. azure_tenant_audit/shipped_content.py +122 -0
  295. azure_tenant_audit/strict_json.py +19 -0
  296. azure_tenant_audit/tenant_identity.py +267 -0
  297. azure_tenant_audit/text_validity.py +77 -0
  298. azure_tenant_audit/utils.py +38 -0
  299. azure_tenant_audit/value_rules/__init__.py +77 -0
  300. azure_tenant_audit/value_rules/aad_authz.py +140 -0
  301. azure_tenant_audit/value_rules/aad_pilot.py +439 -0
  302. azure_tenant_audit/value_rules/aad_roles.py +182 -0
  303. azure_tenant_audit/value_rules/catalogue.py +184 -0
  304. azure_tenant_audit/value_rules/conditional_access.py +673 -0
  305. azure_tenant_audit/value_rules/defender_cascade.py +274 -0
  306. azure_tenant_audit/value_rules/defender_dlp.py +209 -0
  307. azure_tenant_audit/value_rules/defender_phish.py +360 -0
  308. azure_tenant_audit/value_rules/defender_resolution.py +486 -0
  309. azure_tenant_audit/value_rules/defender_spam.py +222 -0
  310. azure_tenant_audit/value_rules/defender_targeted_users.py +182 -0
  311. azure_tenant_audit/value_rules/dns.py +339 -0
  312. azure_tenant_audit/value_rules/exo_open.py +56 -0
  313. azure_tenant_audit/value_rules/gates.py +52 -0
  314. azure_tenant_audit/value_rules/helpers.py +312 -0
  315. azure_tenant_audit/value_rules/lookups.py +311 -0
  316. azure_tenant_audit/value_rules/power_platform.py +149 -0
  317. azure_tenant_audit/value_rules/powerbi.py +138 -0
  318. azure_tenant_audit/value_rules/record.py +162 -0
  319. azure_tenant_audit/value_rules/sharepoint.py +125 -0
  320. azure_tenant_audit/versioning.py +47 -0
  321. azure_tenant_audit/waivers.py +304 -0
@@ -0,0 +1,1084 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ import sqlite3
6
+ from collections import Counter
7
+ from collections.abc import Mapping
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from .bundle_integrity import evidence_index_is_hashed
12
+ from .collection_gaps import list_truncations, section_gap_records
13
+ from .evidence_db import _FreshIndexProof, _verify_fresh_index, open_private_run_index
14
+ from .evidence_refs import ARTIFACT_REASONS, EvidenceIndex
15
+ from .provider_registry import provider_collectors
16
+ from .resources import list_resource_files, resolve_resource_path
17
+ from .run_files import UnsafeRunFileError, read_run_file, unbounded_writer_reads
18
+ from .tenant_identity import (
19
+ IDENTITY_FIELDS,
20
+ decode_identity_metadata,
21
+ reconcile_tenant_identity,
22
+ )
23
+ from .waivers import has_matching_waiver, is_accepted_status
24
+
25
+ CONTRACT_VERSION = "2026-11-11"
26
+ # The contract version from which every evidence reference must resolve. It is fixed: a bundle finalized
27
+ # under 2026-10-22 must keep failing on an unresolved reference after later contract bumps, so the legacy
28
+ # cut-off is tied to the version a bundle was finalized under and never to the current CONTRACT_VERSION.
29
+ REFS_MUST_RESOLVE_SINCE = "2026-10-22"
30
+
31
+ ROOT_REQUIRED_ARTIFACTS = (
32
+ "run-manifest.json",
33
+ "summary.json",
34
+ "reports/report-pack.json",
35
+ "index/evidence.sqlite",
36
+ "ai_context.json",
37
+ "validation.json",
38
+ )
39
+
40
+ _REQUIRED_FIELDS: dict[str, tuple[str, ...]] = {
41
+ "run-manifest.json": (
42
+ "schema_version",
43
+ "tenant_name",
44
+ "run_id",
45
+ "overall_status",
46
+ "mode",
47
+ "auditor_profile",
48
+ "selected_collectors",
49
+ "artifacts",
50
+ "evidence_db_path",
51
+ "ai_context_path",
52
+ "validation_path",
53
+ ),
54
+ "summary.json": ("schema_version", "tenant_name", "run_id", "collectors"),
55
+ "reports/report-pack.json": ("schema_version", "summary", "findings", "evidence_paths"),
56
+ "ai_context.json": ("schema_version", "run", "privacy", "counts", "coverage", "findings", "artifacts", "read_order"),
57
+ }
58
+
59
+ _EVIDENCE_REF_REQUIRED = ("artifact_path", "artifact_kind", "collector", "record_key")
60
+ # A reference that does not resolve in a bundle finalized before references had to resolve.
61
+ LEGACY_UNRESOLVED_REF = "legacy_unresolved_ref"
62
+ _AI_SAFE_SENSITIVE_KEYS = re.compile(
63
+ r"(access[_-]?token|refresh[_-]?token|client[_-]?secret|secret|password|credential|authorization|raw_claims)",
64
+ re.IGNORECASE,
65
+ )
66
+ # Identifier patterns that contain a sensitive-key token but refer to legitimate
67
+ # non-secret Microsoft 365 resources (``authorization_policy`` /
68
+ # ``credential_method`` / etc.). Live audits of real tenants surfaced
69
+ # ``authorization_policy`` and friends as false positives on 2026-05-09; the
70
+ # allowlist neutralises them without weakening the underlying regex.
71
+ _AI_SAFE_KEY_ALLOWLIST = re.compile(
72
+ r"^(authorization|credential)_"
73
+ r"(?:policy|policies|context|contexts|method|methods|metric|metrics|"
74
+ r"setting|settings|level|type|kind|state|status|class|admin|grant|grants|"
75
+ r"provider|providers|flow|flows)$"
76
+ r"|^(?:password|key|application|service_principal)_credentials$"
77
+ r"|^app_credentials$"
78
+ r"|^federated_credentials$"
79
+ r"|^is_passwordless_capable$"
80
+ r"|^(?:application|service_principal)_credential_objects$",
81
+ re.IGNORECASE,
82
+ )
83
+ _AI_SAFE_SENSITIVE_VALUES = re.compile(r"(Bearer\s+[A-Za-z0-9._-]+|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.)")
84
+ _SENSITIVE_CONTRACT_ARTIFACTS = (
85
+ "run-manifest.json",
86
+ "ai_context.json",
87
+ "reports/report-pack.json",
88
+ "normalized/auth_context.json",
89
+ )
90
+ # The optional local answer written by ``auditex explain`` (M10): validated against its schema when present; the
91
+ # product re-checks its content against the run's rule assessment whenever it reads it.
92
+ LOCAL_ANSWER_PATH = "local_answer.json"
93
+ LOCAL_ANSWER_SCHEMA = "schemas/local_answer.schema.json"
94
+ _OPTIONAL_MANIFEST_ARTIFACT_FIELDS = (
95
+ "data_handling_path",
96
+ "live_readiness_path",
97
+ "audit_plan_path",
98
+ "api_inventory_path",
99
+ )
100
+ # Canonical framework keys used by exporters / control-mappings. C3 fails the
101
+ # bundle if a finding's framework_mappings drifts from this set, since SARIF/
102
+ # OSCAL exporters depend on knowing the framework taxonomy at bundle-build
103
+ # time.
104
+ #
105
+ # ``cis_m365_v3`` is a deprecated legacy key: still accepted so older bundles
106
+ # and operator overrides validate, but shipped mappings emit ``cis_m365_v7``.
107
+ # configs/framework-catalog.json must list the same keys (tested).
108
+ _KNOWN_FRAMEWORK_KEYS = frozenset(
109
+ {
110
+ "cis_m365_v7",
111
+ "cis_m365_v3",
112
+ "cisa_scuba",
113
+ "ms_secure_score",
114
+ "ms_zero_trust",
115
+ "mcsb",
116
+ "cyber_essentials",
117
+ "google_workspace_baseline",
118
+ "nist_800_53",
119
+ "iso_27001",
120
+ "soc2",
121
+ "nis2",
122
+ "dora",
123
+ "mitre_attack",
124
+ }
125
+ )
126
+ # Provenance markers that are NOT in the audit collector REGISTRY but are
127
+ # still legitimate ``collector`` values on findings — they identify
128
+ # non-audit planes (response actions, etc.) that produce findings via a
129
+ # different runtime path. Keep this list short and explicit.
130
+ _KNOWN_NON_COLLECTOR_PROVENANCE = frozenset({"response", "toolchain", "windows365"})
131
+
132
+
133
+ def _read_json(path: Path, fallback: Any = None, *, run_dir: Path) -> Any:
134
+ try:
135
+ relative = path.relative_to(run_dir)
136
+ except ValueError:
137
+ relative = None
138
+ if relative is None:
139
+ raise UnsafeRunFileError("run-file", reason="outside") from None
140
+ try:
141
+ data = read_run_file(run_dir, relative)
142
+ except UnsafeRunFileError:
143
+ raise
144
+ except (FileNotFoundError, OSError):
145
+ return fallback
146
+ invalid = False
147
+ try:
148
+ text = data.decode("utf-8")
149
+ except UnicodeError:
150
+ invalid = True
151
+ if invalid:
152
+ raise UnsafeRunFileError("run-file") from None
153
+ try:
154
+ return json.loads(text)
155
+ except (json.JSONDecodeError, ValueError):
156
+ return fallback
157
+
158
+
159
+ def _issue(code: str, *, path: str | None = None, details: Any = None, severity: str = "error") -> dict[str, Any]:
160
+ payload: dict[str, Any] = {"code": code, "severity": severity}
161
+ if path is not None:
162
+ payload["path"] = path
163
+ if details is not None:
164
+ payload["details"] = details
165
+ return payload
166
+
167
+
168
+ def _validate_required_json_fields(run_dir: Path, issues: list[dict[str, Any]]) -> None:
169
+ for relative, required_fields in _REQUIRED_FIELDS.items():
170
+ path = run_dir / relative
171
+ payload = _read_json(path, fallback=None, run_dir=run_dir)
172
+ if not isinstance(payload, Mapping):
173
+ issues.append(_issue("invalid_json_artifact", path=relative))
174
+ continue
175
+ missing = [field for field in required_fields if field not in payload]
176
+ if missing:
177
+ issues.append(_issue("missing_json_required_fields", path=relative, details=missing))
178
+
179
+
180
+ def _load_findings(run_dir: Path, supplied: list[dict[str, Any]] | None) -> list[dict[str, Any]]:
181
+ if supplied is not None:
182
+ return [dict(item) for item in supplied if isinstance(item, Mapping)]
183
+ payload = _read_json(run_dir / "findings" / "findings.json", fallback=[], run_dir=run_dir)
184
+ return [dict(item) for item in payload if isinstance(item, Mapping)] if isinstance(payload, list) else []
185
+
186
+
187
+ # Finding statuses the engine writes: ``open``, and ``accepted_risk`` (with the waiver that matched) only.
188
+ # ``accepted`` and ``waived`` are read as accepted spellings; anything else is not a status the engine produces.
189
+ _ENGINE_FINDING_STATUSES = frozenset({"open"})
190
+
191
+
192
+ def _validate_finding_statuses(findings: list[dict[str, Any]], issues: list[dict[str, Any]]) -> None:
193
+ """A finding is accepted only by a matching waiver, and only known statuses are read as such.
194
+
195
+ An accepted status with no matching waiver (the engine always attaches the waiver it matched) is an
196
+ error: it is the one edit that turns a failing gate into a pass. A status the engine never writes
197
+ (``closed``, ``resolved``, anything else) is a warning; the gates count such a finding as open unless a
198
+ matching waiver stands behind it.
199
+ """
200
+ unwaived: list[str] = []
201
+ unknown: dict[str, list[str]] = {}
202
+ for position, finding in enumerate(findings):
203
+ finding_id = str(finding.get("id") or f"finding:{position}")
204
+ status = str(finding.get("status") or "open").strip().lower()
205
+ if is_accepted_status(status):
206
+ if not has_matching_waiver(finding):
207
+ unwaived.append(finding_id)
208
+ elif status not in _ENGINE_FINDING_STATUSES:
209
+ unknown.setdefault(status, []).append(finding_id)
210
+ if unwaived:
211
+ issues.append(_issue("unwaived_accepted_status", path="findings/findings.json", details=sorted(unwaived)[:20]))
212
+ for status, ids in sorted(unknown.items()):
213
+ issues.append(
214
+ _issue(
215
+ "unknown_finding_status",
216
+ path="findings/findings.json",
217
+ details={"status": status, "findings": sorted(ids)[:20]},
218
+ severity="warning",
219
+ )
220
+ )
221
+
222
+
223
+ def _is_legacy_bundle(manifest: Any) -> bool:
224
+ """Whether the run was finalized under a contract older than ``REFS_MUST_RESOLVE_SINCE``.
225
+
226
+ Such a bundle was written before references were required to resolve, so a citation that does
227
+ not resolve in it is the old builders' pattern (for example a raw payload cited for a fan-out
228
+ that has no row there), not a sign that the bundle was edited. The edit is what the hash
229
+ manifest and ``evidence_ref_hash_mismatch`` report. The cut-off is a fixed version, not the
230
+ current ``CONTRACT_VERSION``, so a later contract bump never relabels an edited citation.
231
+ """
232
+ if not isinstance(manifest, Mapping) or not manifest:
233
+ return False
234
+ version = manifest.get("schema_contract_version")
235
+ return not isinstance(version, str) or version < REFS_MUST_RESOLVE_SINCE
236
+
237
+
238
+ def _unresolved_code(reason: str | None, *, legacy: bool, proof_table: bool = False) -> str:
239
+ """The issue code for a reference that does not resolve."""
240
+ if reason in ARTIFACT_REASONS:
241
+ return "broken_report_proof_table_ref" if proof_table else "broken_evidence_ref"
242
+ if legacy:
243
+ return LEGACY_UNRESOLVED_REF
244
+ return "unresolved_report_proof_table_ref" if proof_table else "unresolved_evidence_ref"
245
+
246
+
247
+ def _validate_evidence_refs(
248
+ run_dir: Path,
249
+ findings: list[dict[str, Any]],
250
+ issues: list[dict[str, Any]],
251
+ index: EvidenceIndex,
252
+ *,
253
+ legacy: bool = False,
254
+ ) -> None:
255
+ """Every finding cites evidence, and every citation resolves inside the run directory.
256
+
257
+ A reference resolves when its artifact is a file inside ``run_dir`` and its ``json_pointer`` (or,
258
+ without one, its ``record_key``) exists in that artifact. ``content_hash``, when the reference
259
+ carries one, must still match the artifact bytes.
260
+ """
261
+ ids = [str(item.get("id")) for item in findings if item.get("id")]
262
+ duplicate_ids = sorted(key for key, count in Counter(ids).items() if count > 1)
263
+ if duplicate_ids:
264
+ issues.append(_issue("duplicate_finding_ids", path="findings/findings.json", details=duplicate_ids))
265
+
266
+ to_resolve: list[tuple[str, int, Mapping[str, Any]]] = []
267
+ for position, finding in enumerate(findings):
268
+ finding_id = str(finding.get("id") or f"finding:{position}")
269
+ refs = finding.get("evidence_refs")
270
+ if not isinstance(refs, list) or not refs:
271
+ issues.append(_issue("missing_evidence_refs", path="findings/findings.json", details=finding_id))
272
+ continue
273
+ for ref_index, ref in enumerate(refs):
274
+ if not isinstance(ref, Mapping):
275
+ issues.append(
276
+ _issue(
277
+ "invalid_evidence_ref",
278
+ path="findings/findings.json",
279
+ details={"finding_id": finding_id, "ref_index": ref_index},
280
+ )
281
+ )
282
+ continue
283
+ missing = [field for field in _EVIDENCE_REF_REQUIRED if not str(ref.get(field) or "").strip()]
284
+ if missing:
285
+ issues.append(
286
+ _issue(
287
+ "invalid_evidence_ref",
288
+ path="findings/findings.json",
289
+ details={"finding_id": finding_id, "ref_index": ref_index, "missing": missing},
290
+ )
291
+ )
292
+ if str(ref.get("artifact_path") or ""):
293
+ to_resolve.append((finding_id, ref_index, ref))
294
+
295
+ index.prime(ref for _finding, _position, ref in to_resolve)
296
+ for finding_id, ref_index, ref in to_resolve:
297
+ result = index.resolve(ref)
298
+ artifact_path = str(ref.get("artifact_path") or "")
299
+ if not result.resolved:
300
+ code = _unresolved_code(result.reason, legacy=legacy)
301
+ details: dict[str, Any] = {
302
+ "finding_id": finding_id,
303
+ "ref_index": ref_index,
304
+ "artifact_path": artifact_path,
305
+ "reason": result.reason,
306
+ }
307
+ for field in ("record_key", "json_pointer", "jsonl_line"):
308
+ if ref.get(field) not in (None, ""):
309
+ details[field] = ref.get(field)
310
+ issues.append(_issue(code, path="findings/findings.json", details=details))
311
+ continue
312
+ recorded = str(ref.get("content_hash") or "").strip()
313
+ if recorded and result.content_hash and recorded.lower() != result.content_hash:
314
+ issues.append(
315
+ _issue(
316
+ "evidence_ref_hash_mismatch",
317
+ path="findings/findings.json",
318
+ details={
319
+ "finding_id": finding_id,
320
+ "ref_index": ref_index,
321
+ "artifact_path": artifact_path,
322
+ "expected": recorded,
323
+ "actual": result.content_hash,
324
+ },
325
+ )
326
+ )
327
+
328
+
329
+ def _record_key_for_check(record: Mapping[str, Any], section_name: str, index: int) -> str:
330
+ """Mirror of evidence_db._record_key for validation purposes — must stay in
331
+ sync so the contract layer flags the same collisions the evidence DB will hit.
332
+ """
333
+ for key in ("key", "id", "display_name", "name", "collector", "surface"):
334
+ value = record.get(key)
335
+ if value is not None and str(value).strip():
336
+ return f"{section_name}:{value}" if key != "key" else str(value)
337
+ return f"{section_name}:{index}"
338
+
339
+
340
+ def _validate_record_key_uniqueness(run_dir: Path, issues: list[dict[str, Any]]) -> None:
341
+ normalized_dir = run_dir / "normalized"
342
+ if not normalized_dir.exists():
343
+ return
344
+ for path in sorted(normalized_dir.glob("*.json")):
345
+ payload = _read_json(path, fallback={}, run_dir=run_dir)
346
+ if not isinstance(payload, Mapping):
347
+ continue
348
+ records = payload.get("records")
349
+ if not isinstance(records, list) or not records:
350
+ continue
351
+ section_name = str(payload.get("kind") or path.stem)
352
+ seen: dict[str, int] = {}
353
+ duplicates: list[dict[str, Any]] = []
354
+ for index, record in enumerate(records):
355
+ if not isinstance(record, Mapping):
356
+ continue
357
+ key = _record_key_for_check(record, section_name, index)
358
+ previous = seen.get(key)
359
+ if previous is None:
360
+ seen[key] = index
361
+ continue
362
+ duplicates.append({"record_key": key, "first": previous, "second": index})
363
+ if duplicates:
364
+ issues.append(
365
+ _issue(
366
+ "duplicate_record_key",
367
+ path=str(path.relative_to(run_dir)),
368
+ details=duplicates[:25],
369
+ )
370
+ )
371
+
372
+
373
+ def _validate_finding_collectors(
374
+ findings: list[dict[str, Any]], issues: list[dict[str, Any]]
375
+ ) -> None:
376
+ """Every finding's ``collector`` field must reference a known collector
377
+ from the registry; otherwise SARIF / OSCAL exporters and notify sinks
378
+ cannot resolve provenance."""
379
+ try: # lazy import: contracts.py is imported earlier in the boot order
380
+ from .collectors import REGISTRY as _REGISTRY
381
+ except Exception: # noqa: BLE001 — never let import failure crash validation
382
+ return
383
+ known = set(_REGISTRY.keys()) | set(_KNOWN_NON_COLLECTOR_PROVENANCE)
384
+ try:
385
+ known.update(provider_collectors("google_workspace"))
386
+ except Exception: # noqa: BLE001
387
+ pass
388
+ for finding in findings:
389
+ collector = finding.get("collector")
390
+ if not isinstance(collector, str) or not collector.strip():
391
+ # Already covered by other validators; don't double-flag here.
392
+ continue
393
+ if collector not in known:
394
+ issues.append(
395
+ _issue(
396
+ "unknown_finding_collector",
397
+ path="findings/findings.json",
398
+ details={
399
+ "finding_id": str(finding.get("id") or ""),
400
+ "collector": collector,
401
+ },
402
+ )
403
+ )
404
+
405
+
406
+ def _validate_finding_framework_mappings(
407
+ findings: list[dict[str, Any]], issues: list[dict[str, Any]]
408
+ ) -> None:
409
+ """Each finding's ``framework_mappings`` must use canonical framework keys
410
+ and non-empty list-of-strings values. Drift breaks SARIF/OSCAL exporters
411
+ that depend on the framework taxonomy."""
412
+ for finding in findings:
413
+ mappings = finding.get("framework_mappings")
414
+ if mappings is None:
415
+ continue
416
+ finding_id = str(finding.get("id") or "")
417
+ if not isinstance(mappings, Mapping):
418
+ issues.append(
419
+ _issue(
420
+ "invalid_framework_mapping_value",
421
+ path="findings/findings.json",
422
+ details={"finding_id": finding_id, "reason": "framework_mappings is not an object"},
423
+ )
424
+ )
425
+ continue
426
+ for framework, controls in mappings.items():
427
+ if framework not in _KNOWN_FRAMEWORK_KEYS:
428
+ issues.append(
429
+ _issue(
430
+ "unknown_framework_mapping_key",
431
+ path="findings/findings.json",
432
+ details={
433
+ "finding_id": finding_id,
434
+ "framework": framework,
435
+ "known": sorted(_KNOWN_FRAMEWORK_KEYS),
436
+ },
437
+ )
438
+ )
439
+ continue
440
+ if not isinstance(controls, list) or not controls:
441
+ issues.append(
442
+ _issue(
443
+ "invalid_framework_mapping_value",
444
+ path="findings/findings.json",
445
+ details={
446
+ "finding_id": finding_id,
447
+ "framework": framework,
448
+ "reason": "value is not a non-empty list",
449
+ },
450
+ )
451
+ )
452
+ continue
453
+ empty = [
454
+ index
455
+ for index, control in enumerate(controls)
456
+ if not isinstance(control, str) or not control.strip()
457
+ ]
458
+ if empty:
459
+ issues.append(
460
+ _issue(
461
+ "invalid_framework_mapping_value",
462
+ path="findings/findings.json",
463
+ details={
464
+ "finding_id": finding_id,
465
+ "framework": framework,
466
+ "empty_or_non_string_indexes": empty[:25],
467
+ },
468
+ )
469
+ )
470
+
471
+
472
+ def _validate_normalized_records(run_dir: Path, issues: list[dict[str, Any]]) -> None:
473
+ normalized_dir = run_dir / "normalized"
474
+ if not normalized_dir.exists():
475
+ issues.append(_issue("missing_artifact_directory", path="normalized"))
476
+ return
477
+ for path in sorted(normalized_dir.glob("*.json")):
478
+ payload = _read_json(path, fallback={}, run_dir=run_dir)
479
+ if not isinstance(payload, Mapping):
480
+ issues.append(_issue("invalid_json_artifact", path=str(path.relative_to(run_dir))))
481
+ continue
482
+ records = payload.get("records")
483
+ if records is None:
484
+ continue
485
+ if not isinstance(records, list):
486
+ issues.append(_issue("invalid_records_shape", path=str(path.relative_to(run_dir))))
487
+ continue
488
+ bad: list[int] = []
489
+ for index, record in enumerate(records):
490
+ if not isinstance(record, Mapping):
491
+ bad.append(index)
492
+ continue
493
+ key = (
494
+ record.get("key")
495
+ or record.get("id")
496
+ or record.get("name")
497
+ or record.get("display_name")
498
+ or record.get("collector")
499
+ or record.get("surface")
500
+ )
501
+ if key is None or not str(key).strip():
502
+ bad.append(index)
503
+ if bad:
504
+ issues.append(_issue("bad_record_keys", path=str(path.relative_to(run_dir)), details=bad[:25]))
505
+
506
+
507
+ def _walk_sensitive_ai_safe(value: Any, path: str, hits: list[dict[str, Any]]) -> None:
508
+ if isinstance(value, Mapping):
509
+ for key, item in value.items():
510
+ key_text = str(key)
511
+ current = f"{path}/{key_text}" if path else key_text
512
+ if _AI_SAFE_SENSITIVE_KEYS.search(key_text) and not _AI_SAFE_KEY_ALLOWLIST.match(key_text):
513
+ hits.append({"path": current, "reason": "sensitive_key"})
514
+ _walk_sensitive_ai_safe(item, current, hits)
515
+ elif isinstance(value, list):
516
+ for index, item in enumerate(value):
517
+ _walk_sensitive_ai_safe(item, f"{path}[{index}]", hits)
518
+ elif isinstance(value, str) and _AI_SAFE_SENSITIVE_VALUES.search(value):
519
+ hits.append({"path": path, "reason": "sensitive_value"})
520
+
521
+
522
+ def _validate_ai_safe(run_dir: Path, issues: list[dict[str, Any]]) -> None:
523
+ ai_safe_dir = run_dir / "ai_safe"
524
+ if not ai_safe_dir.exists():
525
+ return
526
+ for path in sorted(ai_safe_dir.glob("*.json")):
527
+ payload = _read_json(path, fallback={}, run_dir=run_dir)
528
+ hits: list[dict[str, Any]] = []
529
+ _walk_sensitive_ai_safe(payload, "", hits)
530
+ if hits:
531
+ issues.append(_issue("unsafe_ai_safe_artifact", path=str(path.relative_to(run_dir)), details=hits[:25]))
532
+
533
+
534
+ def _validate_sensitive_contract_artifacts(run_dir: Path, issues: list[dict[str, Any]]) -> None:
535
+ for relative in _SENSITIVE_CONTRACT_ARTIFACTS:
536
+ path = run_dir / relative
537
+ if not path.exists():
538
+ continue
539
+ payload = _read_json(path, fallback={}, run_dir=run_dir)
540
+ hits: list[dict[str, Any]] = []
541
+ _walk_sensitive_ai_safe(payload, "", hits)
542
+ if hits:
543
+ issues.append(_issue("unsafe_contract_artifact", path=relative, details=hits[:25]))
544
+
545
+
546
+ def _validate_evidence_db(
547
+ run_dir: Path, issues: list[dict[str, Any]], *, read_only: bool = False,
548
+ _fresh_index_proof: _FreshIndexProof | None = None,
549
+ ) -> dict[str, Any]:
550
+ metadata: dict[str, Any] = {}
551
+
552
+ def inspect(conn: sqlite3.Connection) -> None:
553
+ nonlocal metadata
554
+ tables = {row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
555
+ required = {"run_meta", "section_stats", "normalized_records"}
556
+ missing = sorted(required - tables)
557
+ if missing:
558
+ issues.append(_issue("invalid_evidence_sqlite_schema", path="index/evidence.sqlite", details=missing))
559
+ if "run_meta" in tables:
560
+ metadata = decode_identity_metadata(dict(conn.execute("SELECT key, value FROM run_meta")))
561
+
562
+ try:
563
+ # A writer may validate the exact bytes it just produced using the
564
+ # schema and metadata captured while its private build was open.
565
+ if not read_only and _fresh_index_proof is not None:
566
+ _verify_fresh_index(run_dir, _fresh_index_proof)
567
+ missing = sorted({"run_meta", "section_stats", "normalized_records"} - _fresh_index_proof.tables)
568
+ if missing:
569
+ issues.append(_issue("invalid_evidence_sqlite_schema", path="index/evidence.sqlite", details=missing))
570
+ return decode_identity_metadata(_fresh_index_proof.metadata)
571
+ # SQLite consumers see a protected snapshot or an immutable in-place read; sidecars are never replayed.
572
+ with open_private_run_index(run_dir, hashed=evidence_index_is_hashed(run_dir),
573
+ record_notice=not read_only) as conn:
574
+ inspect(conn)
575
+ except UnsafeRunFileError:
576
+ raise
577
+ except FileNotFoundError:
578
+ if not read_only and _fresh_index_proof is not None:
579
+ raise UnsafeRunFileError("evidence index") from None
580
+ issues.append(_issue("missing_required_artifact", path="index/evidence.sqlite"))
581
+ except (sqlite3.DatabaseError, OSError) as exc:
582
+ issues.append(_issue("invalid_evidence_sqlite", path="index/evidence.sqlite", details=str(exc)))
583
+ return metadata
584
+
585
+
586
+ def _validate_tenant_identity(
587
+ run_dir: Path,
588
+ manifest: Mapping[str, Any],
589
+ ai_context: Any,
590
+ indexed: Mapping[str, Any],
591
+ issues: list[dict[str, Any]],
592
+ ) -> None:
593
+ summary = _read_json(run_dir / "summary.json", {}, run_dir=run_dir)
594
+ report = _read_json(run_dir / "reports/report-pack.json", {}, run_dir=run_dir)
595
+ report_summary = report.get("summary") if isinstance(report, Mapping) else {}
596
+ ai_run = ai_context.get("run") if isinstance(ai_context, Mapping) else {}
597
+ surfaces = {
598
+ "run-manifest.json": manifest,
599
+ "summary.json": summary if isinstance(summary, Mapping) else {},
600
+ "reports/report-pack.json#/summary": report_summary if isinstance(report_summary, Mapping) else {},
601
+ "ai_context.json#/run": ai_run if isinstance(ai_run, Mapping) else {},
602
+ "index/evidence.sqlite#run_meta": indexed,
603
+ }
604
+ if isinstance(report, Mapping) and any(key in report for key in IDENTITY_FIELDS):
605
+ surfaces["reports/report-pack.json"] = report
606
+ resolved = reconcile_tenant_identity(run_dir, surfaces, platform=str(manifest.get("platform") or "m365"))
607
+ if resolved["tenant_identity"]["status"] == "conflict":
608
+ issues.append(_issue("tenant_identity_conflict", path="run-manifest.json", details=resolved["tenant_identity"]["conflicts"]))
609
+
610
+
611
+ def _validate_manifest_artifact_paths(run_dir: Path, issues: list[dict[str, Any]]) -> dict[str, Any]:
612
+ manifest = _read_json(run_dir / "run-manifest.json", fallback={}, run_dir=run_dir)
613
+ if not isinstance(manifest, Mapping):
614
+ return {}
615
+ for field in _OPTIONAL_MANIFEST_ARTIFACT_FIELDS:
616
+ value = manifest.get(field)
617
+ if not value:
618
+ continue
619
+ relative = str(value)
620
+ if not (run_dir / relative).exists():
621
+ issues.append(_issue("missing_manifest_artifact", path=relative, details=field))
622
+ return dict(manifest)
623
+
624
+
625
+ def _validate_collection_gaps(run_dir: Path, manifest: Mapping[str, Any], issues: list[dict[str, Any]]) -> None:
626
+ """A list cut short is a coverage gap: the run is not ``ok`` and the manifest names the list."""
627
+ coverage_path = manifest.get("coverage_path")
628
+ if not coverage_path:
629
+ return
630
+ coverage = _read_json(run_dir / str(coverage_path), fallback=[], run_dir=run_dir)
631
+ coverage_rows = coverage if isinstance(coverage, list) else []
632
+ # A section-scoped read that was cut or refused leaves its collector ok; the manifest still has to name it. A
633
+ # warning, not an error: bundles from before section gaps were recorded stay valid.
634
+ unrecorded_sections = [
635
+ item
636
+ for item in section_gap_records(coverage_rows)
637
+ if (item["collector"], item["section"])
638
+ not in {
639
+ (str(entry.get("collector")), str(entry.get("section")))
640
+ for gap in manifest.get("coverage_gaps") or []
641
+ if isinstance(gap, Mapping)
642
+ for entry in gap.get("section_gaps") or []
643
+ if isinstance(entry, Mapping)
644
+ }
645
+ ]
646
+ if unrecorded_sections:
647
+ issues.append(
648
+ _issue("section_gap_not_recorded", path="run-manifest.json", details=unrecorded_sections[:25], severity="warning")
649
+ )
650
+ # Only rows that name a reason were written by a version that records gaps; bundles from before
651
+ # flagged a cut on an ``ok`` row with no reason and stay valid.
652
+ truncations = list_truncations(coverage_rows, require_reason=True)
653
+ if not truncations:
654
+ return
655
+ if manifest.get("overall_status") == "ok":
656
+ issues.append(_issue("truncated_list_reported_ok", path="run-manifest.json", details=truncations[:25]))
657
+ recorded = {
658
+ (str(item.get("collector")), str(item.get("list")))
659
+ for gap in manifest.get("coverage_gaps") or []
660
+ if isinstance(gap, Mapping)
661
+ for item in gap.get("truncated_lists") or []
662
+ if isinstance(item, Mapping)
663
+ }
664
+ missing = [item for item in truncations if (item["collector"], item["list"]) not in recorded]
665
+ if missing:
666
+ issues.append(_issue("collection_gap_not_recorded", path="run-manifest.json", details=missing[:25]))
667
+
668
+
669
+ def _validate_data_handling(run_dir: Path, manifest: Mapping[str, Any], issues: list[dict[str, Any]]) -> None:
670
+ relative = manifest.get("data_handling_path")
671
+ if not relative:
672
+ return
673
+ path = run_dir / str(relative)
674
+ payload = _read_json(path, fallback=None, run_dir=run_dir)
675
+ if not isinstance(payload, Mapping):
676
+ issues.append(_issue("invalid_json_artifact", path=str(relative)))
677
+ return
678
+ required = ("schema_version", "platform", "read_only", "content_reads", "write_actions", "provider_assertions")
679
+ missing = [key for key in required if key not in payload]
680
+ if missing:
681
+ issues.append(_issue("missing_json_required_fields", path=str(relative), details=missing))
682
+ return
683
+ if payload.get("read_only") is True and payload.get("write_actions") is True:
684
+ issues.append(_issue("invalid_data_handling_semantics", path=str(relative), details="read_only_with_write_actions"))
685
+ if payload.get("content_reads") is True:
686
+ issues.append(_issue("invalid_data_handling_semantics", path=str(relative), details="content_reads_enabled"))
687
+ assertions = payload.get("provider_assertions")
688
+ if not isinstance(assertions, Mapping):
689
+ issues.append(_issue("missing_json_required_fields", path=str(relative), details=["provider_assertions"]))
690
+ return
691
+ platform = str(payload.get("platform") or manifest.get("platform") or "m365")
692
+ if platform == "google_workspace":
693
+ forbidden = [
694
+ key
695
+ for key in ("gmail_body_reads", "drive_file_content_reads", "body_or_file_content_reads")
696
+ if assertions.get(key) is True
697
+ ]
698
+ if forbidden:
699
+ issues.append(_issue("invalid_data_handling_no_content_assertion", path=str(relative), details=forbidden))
700
+ elif assertions.get("body_or_file_content_reads") is True:
701
+ issues.append(
702
+ _issue("invalid_data_handling_no_content_assertion", path=str(relative), details=["body_or_file_content_reads"])
703
+ )
704
+
705
+
706
+ def _validate_live_readiness(run_dir: Path, manifest: Mapping[str, Any], issues: list[dict[str, Any]]) -> None:
707
+ relative = manifest.get("live_readiness_path")
708
+ if not relative:
709
+ return
710
+ path = run_dir / str(relative)
711
+ payload = _read_json(path, fallback=None, run_dir=run_dir)
712
+ if not isinstance(payload, Mapping):
713
+ issues.append(_issue("invalid_json_artifact", path=str(relative)))
714
+ return
715
+ missing = [key for key in ("trust_level", "selected_collectors", "can_trust", "cannot_trust") if key not in payload]
716
+ if missing:
717
+ issues.append(_issue("missing_json_required_fields", path=str(relative), details=missing))
718
+
719
+
720
+ def _validate_audit_plan(run_dir: Path, manifest: Mapping[str, Any], issues: list[dict[str, Any]]) -> None:
721
+ relative = manifest.get("audit_plan_path")
722
+ if not relative:
723
+ return
724
+ path = run_dir / str(relative)
725
+ payload = _read_json(path, fallback=None, run_dir=run_dir)
726
+ if not isinstance(payload, Mapping):
727
+ issues.append(_issue("invalid_json_artifact", path=str(relative)))
728
+ return
729
+ missing = [key for key in ("schema_version", "platform", "evidence_gates", "quality_gate") if key not in payload]
730
+ if missing:
731
+ issues.append(_issue("missing_json_required_fields", path=str(relative), details=missing))
732
+ gate = payload.get("quality_gate")
733
+ if not isinstance(gate, Mapping) or gate.get("status") not in {"complete", "partial", "unusable"}:
734
+ issues.append(_issue("invalid_audit_plan_quality_gate", path=str(relative)))
735
+
736
+
737
+ def _validate_api_inventory(run_dir: Path, manifest: Mapping[str, Any], issues: list[dict[str, Any]]) -> None:
738
+ relative = manifest.get("api_inventory_path")
739
+ if not relative:
740
+ return
741
+ path = run_dir / str(relative)
742
+ payload = _read_json(path, fallback=None, run_dir=run_dir)
743
+ if not isinstance(payload, Mapping):
744
+ issues.append(_issue("invalid_json_artifact", path=str(relative)))
745
+ return
746
+ missing = [key for key in ("schema_version", "platform", "declared_collectors", "observed_calls", "safety") if key not in payload]
747
+ if missing:
748
+ issues.append(_issue("missing_json_required_fields", path=str(relative), details=missing))
749
+ return
750
+ if not isinstance(payload.get("declared_collectors"), list) or not isinstance(payload.get("observed_calls"), list):
751
+ issues.append(_issue("invalid_api_inventory_shape", path=str(relative)))
752
+ safety = payload.get("safety")
753
+ if not isinstance(safety, Mapping):
754
+ issues.append(_issue("missing_json_required_fields", path=str(relative), details=["safety"]))
755
+ return
756
+ if safety.get("content_reads") is True or safety.get("no_content_reads") is False:
757
+ issues.append(_issue("invalid_api_inventory_safety", path=str(relative), details="content_reads_enabled"))
758
+ if str(manifest.get("plane") or "inventory") != "response" and (
759
+ safety.get("write_actions") is True or safety.get("read_only") is False
760
+ ):
761
+ issues.append(_issue("invalid_api_inventory_safety", path=str(relative), details="write_actions_in_audit_plane"))
762
+ ledger = payload.get("observed_ledger")
763
+ outside = ledger.get("outside_declared") if isinstance(ledger, Mapping) else None
764
+ outside_count = outside.get("count") if isinstance(outside, Mapping) else None
765
+ if isinstance(outside_count, int) and not isinstance(outside_count, bool) and outside_count > 0:
766
+ # A warning, not an error: the call may be a read the declaration did not name, but it has to be seen.
767
+ issues.append(
768
+ _issue(
769
+ "observed_call_outside_declared",
770
+ path=str(relative),
771
+ details={"count": outside_count, "graph": (outside.get("graph") or [])[:5],
772
+ "commands": (outside.get("commands") or [])[:5],
773
+ "teams_admin_rest": (outside.get("teams_admin_rest") or [])[:5]},
774
+ severity="warning",
775
+ )
776
+ )
777
+ for index, call in enumerate(payload.get("observed_calls") or []):
778
+ if not isinstance(call, Mapping):
779
+ issues.append(_issue("invalid_api_inventory_shape", path=str(relative), details={"observed_call_index": index}))
780
+ continue
781
+ method = str(call.get("method") or "").upper()
782
+ if str(manifest.get("plane") or "inventory") != "response" and method in {"POST", "PUT", "PATCH", "DELETE"}:
783
+ issues.append(
784
+ _issue(
785
+ "invalid_api_inventory_safety",
786
+ path=str(relative),
787
+ details={"observed_call_index": index, "method": method},
788
+ )
789
+ )
790
+
791
+
792
+ def _proof_row_ref(row: Mapping[str, Any]) -> dict[str, Any]:
793
+ return {
794
+ field: row.get(field)
795
+ for field in ("artifact_path", "record_key", "json_pointer", "jsonl_line")
796
+ if row.get(field) not in (None, "")
797
+ }
798
+
799
+
800
+ def _proof_rows(payload: Any) -> list[Any]:
801
+ rows = payload.get("proof_table") if isinstance(payload, Mapping) else None
802
+ return rows if isinstance(rows, list) else []
803
+
804
+
805
+ def _report_pack_refs(payload: Mapping[str, Any]) -> list[tuple[str, Mapping[str, Any]]]:
806
+ """References the report pack carries outside the findings: attack-path hops and report sections."""
807
+ refs: list[tuple[str, Mapping[str, Any]]] = []
808
+ if not isinstance(payload, Mapping):
809
+ return refs
810
+ attack_paths = payload.get("attack_paths")
811
+ for path_index, path in enumerate(attack_paths if isinstance(attack_paths, list) else []):
812
+ if not isinstance(path, Mapping):
813
+ continue
814
+ hops = path.get("hops")
815
+ for hop_index, hop in enumerate(hops if isinstance(hops, list) else []):
816
+ ref = hop.get("evidence_ref") if isinstance(hop, Mapping) else None
817
+ if isinstance(ref, Mapping):
818
+ refs.append((f"attack_paths[{path_index}].hops[{hop_index}]", ref))
819
+ for section, rows_key in (("detection_coverage", "signals"), ("public_footprint", "domains")):
820
+ block = payload.get(section)
821
+ rows = block.get(rows_key) if isinstance(block, Mapping) else None
822
+ for row_index, row in enumerate(rows if isinstance(rows, list) else []):
823
+ ref = row.get("evidence_ref") if isinstance(row, Mapping) else None
824
+ if isinstance(ref, Mapping):
825
+ refs.append((f"{section}.{rows_key}[{row_index}]", ref))
826
+ return [(where, ref) for where, ref in refs if str(ref.get("artifact_path") or "").strip()]
827
+
828
+
829
+ def _validate_report_pack(
830
+ run_dir: Path, issues: list[dict[str, Any]], index: EvidenceIndex, payload: Any, *, legacy: bool = False
831
+ ) -> None:
832
+ relative = "reports/report-pack.json"
833
+ if not isinstance(payload, Mapping):
834
+ return
835
+ for where, ref in _report_pack_refs(payload):
836
+ result = index.resolve(ref)
837
+ if not result.resolved:
838
+ issues.append(
839
+ _issue(
840
+ LEGACY_UNRESOLVED_REF
841
+ if legacy and result.reason not in ARTIFACT_REASONS
842
+ else "unresolved_report_evidence_ref",
843
+ path=relative,
844
+ details={
845
+ "location": where,
846
+ "artifact_path": str(ref.get("artifact_path") or ""),
847
+ "record_key": ref.get("record_key"),
848
+ "json_pointer": ref.get("json_pointer"),
849
+ "reason": result.reason,
850
+ },
851
+ )
852
+ )
853
+ proof_table = payload.get("proof_table")
854
+ if proof_table is None:
855
+ return
856
+ if not isinstance(proof_table, list):
857
+ issues.append(_issue("invalid_report_proof_table", path=relative, details="proof_table_not_list"))
858
+ return
859
+
860
+ findings = [dict(item) for item in payload.get("findings") or [] if isinstance(item, Mapping)]
861
+ finding_ids = {str(item.get("id")) for item in findings if item.get("id")}
862
+ covered_ids: set[str] = set()
863
+ for row_index, row in enumerate(proof_table):
864
+ if not isinstance(row, Mapping):
865
+ issues.append(_issue("invalid_report_proof_table", path=relative, details={"row_index": row_index}))
866
+ continue
867
+ if "proof_status" not in row and "evidence_count" in row and (row.get("finding_id") or row.get("id")):
868
+ covered_ids.add(str(row.get("finding_id") or row.get("id")))
869
+ continue
870
+ finding_id = str(row.get("finding_id") or row.get("id") or "").strip()
871
+ proof_status = str(row.get("proof_status") or "").strip()
872
+ missing = []
873
+ if not finding_id:
874
+ missing.append("finding_id")
875
+ if not proof_status:
876
+ missing.append("proof_status")
877
+ if proof_status == "supported":
878
+ missing.extend(
879
+ field
880
+ for field in ("artifact_path", "artifact_kind", "collector", "record_key")
881
+ if not str(row.get(field) or "").strip()
882
+ )
883
+ artifact_path = str(row.get("artifact_path") or "")
884
+ if artifact_path:
885
+ result = index.resolve(_proof_row_ref(row))
886
+ if not result.resolved:
887
+ code = _unresolved_code(result.reason, legacy=legacy, proof_table=True)
888
+ issues.append(
889
+ _issue(
890
+ code,
891
+ path=relative,
892
+ details={
893
+ "row_index": row_index,
894
+ "finding_id": finding_id,
895
+ "artifact_path": artifact_path,
896
+ "record_key": row.get("record_key"),
897
+ "reason": result.reason,
898
+ },
899
+ )
900
+ )
901
+ elif proof_status not in {"missing_evidence", "unsupported"}:
902
+ missing.append("proof_status:supported|missing_evidence|unsupported")
903
+ recorded_hash = str(row.get("content_hash") or "").strip()
904
+ if recorded_hash and str(row.get("artifact_path") or ""):
905
+ actual_hash = index.resolve(_proof_row_ref(row)).content_hash
906
+ if actual_hash and recorded_hash.lower() != actual_hash:
907
+ issues.append(
908
+ _issue(
909
+ "evidence_ref_hash_mismatch",
910
+ path=relative,
911
+ details={
912
+ "row_index": row_index,
913
+ "finding_id": finding_id,
914
+ "artifact_path": str(row.get("artifact_path")),
915
+ "expected": recorded_hash,
916
+ "actual": actual_hash,
917
+ },
918
+ )
919
+ )
920
+ if missing:
921
+ issues.append(
922
+ _issue(
923
+ "invalid_report_proof_table",
924
+ path=relative,
925
+ details={"row_index": row_index, "finding_id": finding_id, "missing": missing},
926
+ )
927
+ )
928
+ if finding_id:
929
+ covered_ids.add(finding_id)
930
+
931
+ missing_finding_rows = sorted(finding_ids - covered_ids)
932
+ if missing_finding_rows:
933
+ issues.append(
934
+ _issue(
935
+ "missing_report_proof_table_rows",
936
+ path=relative,
937
+ details=missing_finding_rows,
938
+ severity="warning",
939
+ )
940
+ )
941
+
942
+
943
+ def validate_local_answer(payload: Any) -> None:
944
+ """Check a local answer against ``schemas/local_answer.schema.json``; ValueError otherwise."""
945
+ from .resources import open_text_resource
946
+ from .scuba_assessment import _check
947
+
948
+ schema = json.loads(open_text_resource(LOCAL_ANSWER_SCHEMA))
949
+ _check(payload, schema, schema, "local_answer")
950
+ counts, items = payload["counts"], payload["items"]
951
+ if (counts["items"] != len(items) or payload["fixed_text_items"] != sum(item["fallback"] for item in items)
952
+ or any(counts[verdict] != sum(item["verdict"] == verdict for item in items)
953
+ for verdict in ("not_met", "met", "not_assessed", "not_applicable"))
954
+ or [item["item"] for item in items] != list(range(1, len(items) + 1))):
955
+ raise ValueError("Inconsistent local answer counts or item numbers")
956
+
957
+
958
+ def build_validation_report(
959
+ *,
960
+ run_dir: str | Path,
961
+ ai_context: dict[str, Any] | None = None,
962
+ findings: list[dict[str, Any]] | None = None,
963
+ required_artifacts: tuple[str, ...] = ROOT_REQUIRED_ARTIFACTS,
964
+ read_only: bool = False,
965
+ _fresh_index_proof: _FreshIndexProof | None = None,
966
+ ) -> dict[str, Any]:
967
+ if not read_only:
968
+ with unbounded_writer_reads():
969
+ return _build_validation_report(run_dir=run_dir, ai_context=ai_context, findings=findings,
970
+ required_artifacts=required_artifacts, read_only=read_only,
971
+ _fresh_index_proof=_fresh_index_proof)
972
+ return _build_validation_report(run_dir=run_dir, ai_context=ai_context, findings=findings,
973
+ required_artifacts=required_artifacts, read_only=read_only,
974
+ _fresh_index_proof=_fresh_index_proof)
975
+
976
+
977
+ def _build_validation_report(
978
+ *, run_dir: str | Path, ai_context: dict[str, Any] | None, findings: list[dict[str, Any]] | None,
979
+ required_artifacts: tuple[str, ...], read_only: bool, _fresh_index_proof: _FreshIndexProof | None,
980
+ ) -> dict[str, Any]:
981
+ run_path = Path(run_dir)
982
+ issues: list[dict[str, Any]] = []
983
+
984
+ for relative in required_artifacts:
985
+ if not (run_path / relative).exists():
986
+ # validation.json is allowed to be absent while the report itself is being built.
987
+ if relative == "validation.json":
988
+ continue
989
+ issues.append(_issue("missing_required_artifact", path=relative))
990
+
991
+ _validate_required_json_fields(run_path, issues)
992
+ from .scuba_assessment import MODEL_ASSESSMENT_PATH, validate_assessment
993
+
994
+ assessment_path = run_path / MODEL_ASSESSMENT_PATH
995
+ if assessment_path.exists() or assessment_path.is_symlink():
996
+ try:
997
+ assessment = json.loads(read_run_file(run_path, MODEL_ASSESSMENT_PATH).decode("utf-8"))
998
+ validate_assessment(assessment)
999
+ run_manifest = _read_json(run_path / "run-manifest.json", {}, run_dir=run_path)
1000
+ if not isinstance(run_manifest, Mapping) or assessment["run_id"] != run_manifest.get("run_id"):
1001
+ raise ValueError("Model assessment run_id mismatch")
1002
+ except UnsafeRunFileError:
1003
+ # An optional artifact is still guarded: a FIFO, link or alias is a fixed refusal, not a warning.
1004
+ raise
1005
+ except (OSError, ValueError, TypeError, KeyError, RecursionError):
1006
+ issues.append(_issue("invalid_model_assessment", path=MODEL_ASSESSMENT_PATH, severity="warning"))
1007
+ answer_path = run_path / LOCAL_ANSWER_PATH
1008
+ if answer_path.exists() or answer_path.is_symlink():
1009
+ try:
1010
+ answer = json.loads(read_run_file(run_path, LOCAL_ANSWER_PATH).decode("utf-8"))
1011
+ validate_local_answer(answer)
1012
+ run_manifest = _read_json(run_path / "run-manifest.json", {}, run_dir=run_path)
1013
+ if not isinstance(run_manifest, Mapping) or answer["run_id"] != run_manifest.get("run_id"):
1014
+ raise ValueError("Local answer run_id mismatch")
1015
+ except UnsafeRunFileError:
1016
+ raise
1017
+ except (OSError, ValueError, TypeError, KeyError, RecursionError):
1018
+ issues.append(_issue("invalid_local_answer", path=LOCAL_ANSWER_PATH, severity="warning"))
1019
+ loaded_findings = _load_findings(run_path, findings)
1020
+ # Each cited artifact is read once for the findings, the proof table and the report sections.
1021
+ report_pack = _read_json(run_path / "reports" / "report-pack.json", fallback=None, run_dir=run_path)
1022
+ legacy = _is_legacy_bundle(_read_json(run_path / "run-manifest.json", fallback=None, run_dir=run_path))
1023
+ evidence_index = EvidenceIndex(run_path, strict=read_only)
1024
+ evidence_index.prime(
1025
+ [
1026
+ *(
1027
+ ref
1028
+ for item in loaded_findings
1029
+ for ref in (item["evidence_refs"] if isinstance(item.get("evidence_refs"), list) else [])
1030
+ ),
1031
+ *(
1032
+ _proof_row_ref(row)
1033
+ for row in _proof_rows(report_pack)
1034
+ if isinstance(row, Mapping)
1035
+ and row.get("artifact_path")
1036
+ and (row.get("proof_status") == "supported" or row.get("content_hash"))
1037
+ ),
1038
+ *(ref for _where, ref in _report_pack_refs(report_pack)),
1039
+ ]
1040
+ )
1041
+ _validate_evidence_refs(run_path, loaded_findings, issues, evidence_index, legacy=legacy)
1042
+ _validate_normalized_records(run_path, issues)
1043
+ _validate_record_key_uniqueness(run_path, issues)
1044
+ _validate_finding_collectors(loaded_findings, issues)
1045
+ _validate_finding_statuses(loaded_findings, issues)
1046
+ _validate_finding_framework_mappings(loaded_findings, issues)
1047
+ _validate_ai_safe(run_path, issues)
1048
+ _validate_sensitive_contract_artifacts(run_path, issues)
1049
+ indexed_identity = _validate_evidence_db(run_path, issues, read_only=read_only,
1050
+ _fresh_index_proof=_fresh_index_proof)
1051
+ manifest = _validate_manifest_artifact_paths(run_path, issues)
1052
+ _validate_collection_gaps(run_path, manifest, issues)
1053
+ _validate_data_handling(run_path, manifest, issues)
1054
+ _validate_live_readiness(run_path, manifest, issues)
1055
+ _validate_audit_plan(run_path, manifest, issues)
1056
+ _validate_api_inventory(run_path, manifest, issues)
1057
+ _validate_report_pack(run_path, issues, evidence_index, report_pack, legacy=legacy)
1058
+
1059
+ context = ai_context if isinstance(ai_context, Mapping) else _read_json(run_path / "ai_context.json", fallback={}, run_dir=run_path)
1060
+ _validate_tenant_identity(run_path, manifest, context, indexed_identity, issues)
1061
+ if not isinstance(context, Mapping):
1062
+ issues.append(_issue("invalid_json_artifact", path="ai_context.json"))
1063
+ else:
1064
+ counts = context.get("counts")
1065
+ if not isinstance(counts, Mapping) or not isinstance(counts.get("normalized_counts"), Mapping):
1066
+ issues.append(_issue("missing_normalized_counts", path="ai_context.json"))
1067
+
1068
+ errors = [item for item in issues if item.get("severity") == "error"]
1069
+ return {
1070
+ "schema_version": CONTRACT_VERSION,
1071
+ "contract_version": CONTRACT_VERSION,
1072
+ "valid": not errors,
1073
+ "issue_count": len(issues),
1074
+ "error_count": len(errors),
1075
+ "warning_count": len(issues) - len(errors),
1076
+ "required_artifacts": list(required_artifacts),
1077
+ "issues": issues,
1078
+ }
1079
+
1080
+
1081
+ def contract_schema_manifest(schema_dir: str | Path = "schemas") -> dict[str, Any]:
1082
+ root = resolve_resource_path(schema_dir)
1083
+ schemas = [path.name for path in list_resource_files(schema_dir, "*.schema.json")]
1084
+ return {"contract_version": CONTRACT_VERSION, "schema_dir": str(root), "schemas": schemas}