bugx-cli 0.1.0 → 0.1.1

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 (311) hide show
  1. package/README.md +190 -186
  2. package/core/README.md +2 -2
  3. package/core/agent/README.md +2 -1
  4. package/core/agent/agent_artifacts.py +8 -6
  5. package/core/agent/agent_eval.py +136 -54
  6. package/core/agent/agent_execution.py +218 -52
  7. package/core/agent/agent_orchestrator.py +14 -8
  8. package/core/agent/agent_targets.py +8 -2
  9. package/core/agent/feature_baseline.py +150 -0
  10. package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  11. package/core/assets/axe-core/LICENSE.txt +362 -0
  12. package/core/assets/axe-core/UPSTREAM.md +10 -0
  13. package/core/assets/axe-core/axe.min.js +12 -0
  14. package/core/assets/bugx-hero-en.svg +74 -0
  15. package/core/assets/bugx-hero-zh.svg +74 -0
  16. package/core/assets/codex.png +0 -0
  17. package/core/assets/dsh.png +0 -0
  18. package/core/assets/webui-chatgpt.jpg +0 -0
  19. package/core/assets/webui-session.jpg +0 -0
  20. package/core/assets/webui-skills.jpg +0 -0
  21. package/core/assets/webui-studio.jpg +0 -0
  22. package/core/assets/webui-zcode.jpg +0 -0
  23. package/core/assets/zcode.png +0 -0
  24. package/core/autonomous_cve/SPEC.md +1 -1
  25. package/core/autonomous_cve/attack_graph_store.py +152 -106
  26. package/core/autonomous_cve/behavior_graph.py +8 -2
  27. package/core/autonomous_cve/verifier.py +4 -1
  28. package/core/bugx.md +1 -1
  29. package/core/bugx_paths.py +43 -8
  30. package/core/cli-help.txt +66 -0
  31. package/core/cloud_sync/SPEC.md +1 -1
  32. package/core/cloud_sync/cloud_client.py +25 -6
  33. package/core/cloud_sync/cloud_onboard.py +42 -1
  34. package/core/cloud_sync/flywheel_client.py +16 -7
  35. package/core/cloud_sync/network_transport.py +24 -3
  36. package/core/cloud_sync/sensitive_filter.py +2 -2
  37. package/core/cloud_sync/sync_push.py +12 -10
  38. package/core/contracts/AGENT_GUIDE.md +6 -9
  39. package/core/contracts/README.md +2 -2
  40. package/core/contracts/bugx-runtime-contract.md +1 -1
  41. package/core/contracts/bugx-worker.md +1 -1
  42. package/core/contracts/engine_gap_contracts.py +86 -3
  43. package/core/coverage/coverage_discovery.py +599 -29
  44. package/core/coverage/coverage_evidence.py +47 -0
  45. package/core/coverage/coverage_forensics.py +9 -0
  46. package/core/coverage/coverage_validate.py +6 -1
  47. package/core/dev_harness/SPEC.md +1 -1
  48. package/core/engine-integrity.json +591 -419
  49. package/core/fuzzing/concurrency_fuzzer.py +53 -0
  50. package/core/fuzzing/differential_oracle.py +562 -27
  51. package/core/fuzzing/fuzz_input.py +109 -6
  52. package/core/fuzzing/stateful_fuzzer.py +72 -0
  53. package/core/governance/secret_redactor.py +22 -10
  54. package/core/host_acp/SPEC.md +1 -1
  55. package/core/host_acp/__init__.py +4 -4
  56. package/core/host_acp/claude.py +59 -1
  57. package/core/host_acp/cline.py +64 -1
  58. package/core/host_acp/codex.py +56 -1
  59. package/core/host_acp/dsh.py +59 -1
  60. package/core/host_acp/opencode.py +56 -1
  61. package/core/host_acp/pi.py +59 -1
  62. package/core/host_acp/zcode.py +59 -1
  63. package/core/host_runtime/SPEC.md +1 -1
  64. package/core/host_runtime/adapters.py +1 -1
  65. package/core/host_runtime/cline.py +13 -0
  66. package/core/host_runtime/host_evaluators.py +44 -4
  67. package/core/host_runtime/host_probe.py +1 -1
  68. package/core/host_runtime/host_provider_arbitrator.py +116 -62
  69. package/core/host_runtime/host_registry.py +15 -8
  70. package/core/host_runtime/mcp_registry_gate.py +12 -1
  71. package/core/host_runtime/pi.py +102 -0
  72. package/core/host_runtime/provider_facts.py +66 -0
  73. package/core/hosts/SPEC.md +1 -1
  74. package/core/hosts/__init__.py +6 -2
  75. package/core/hosts/_dsh_usage.py +1 -1
  76. package/core/hosts/base.py +32 -4
  77. package/core/hosts/claude.py +55 -0
  78. package/core/hosts/cline.py +6 -2
  79. package/core/hosts/codex.py +58 -0
  80. package/core/hosts/dsh.py +9 -1
  81. package/core/hosts/opencode.py +6 -6
  82. package/core/hosts/pi.py +159 -2
  83. package/core/infra/README.md +4 -2
  84. package/core/infra/__init__.py +2 -0
  85. package/core/infra/build_info.py +22 -3
  86. package/core/infra/client_metadata.py +1 -1
  87. package/core/infra/json_utils.py +22 -0
  88. package/core/launch_phases/README.md +2 -2
  89. package/core/launch_phases/SPEC.md +1 -1
  90. package/core/launch_phases/common.py +21 -2
  91. package/core/launch_phases/finding_confirm_phase.py +5 -1
  92. package/core/launch_phases/finding_settlement.py +188 -1
  93. package/core/launch_phases/judge_phase.py +69 -12
  94. package/core/launch_phases/orchestrator_controls.py +11 -7
  95. package/core/launch_phases/post_coverage_sync.py +9 -2
  96. package/core/launch_phases/post_phase.py +139 -3
  97. package/core/launch_phases/post_receipt.py +12 -1
  98. package/core/launch_phases/pre_phase.py +3 -3
  99. package/core/launch_phases/pre_recon_scout.py +53 -36
  100. package/core/launch_phases/pre_state_builder.py +23 -176
  101. package/core/launch_phases/round_orchestrator.py +15 -32
  102. package/core/launch_phases/session_runtime.py +56 -9
  103. package/core/launch_phases/startup_gates.py +36 -8
  104. package/core/launch_phases/startup_interaction.py +68 -12
  105. package/core/launch_phases/startup_version_gate.py +9 -3
  106. package/core/launch_phases/supervisor_bridge.py +46 -17
  107. package/core/launch_phases/supervisor_coverage.py +8 -2
  108. package/core/launch_phases/supervisor_degraded.py +1 -9
  109. package/core/launch_phases/worker_barriers.py +15 -5
  110. package/core/launch_phases/worker_orchestrator.py +105 -25
  111. package/core/ledger/README.md +1 -1
  112. package/core/ledger/SPEC.md +1 -1
  113. package/core/ledger/_facade.py +2 -1
  114. package/core/ledger/archive_ops.py +60 -2
  115. package/core/ledger/cli.py +6 -1
  116. package/core/ledger/export_ops.py +6 -1
  117. package/core/ledger/finding_confirmation.py +48 -6
  118. package/core/ledger/finding_lifecycle.py +428 -5
  119. package/core/ledger/finding_verification.py +44 -8
  120. package/core/ledger/incidents.py +10 -4
  121. package/core/ledger/patterns.py +10 -7
  122. package/core/ledger/receipt_contract.py +17 -1
  123. package/core/ledger/sync_ops.py +21 -16
  124. package/core/ledger/tool_experience.py +2 -1
  125. package/core/ledger/verify_life.py +88 -17
  126. package/core/locales/en-US.json +2 -2
  127. package/core/locales/zh-CN.json +2 -2
  128. package/core/mcp_handlers/SPEC.md +1 -1
  129. package/core/mcp_handlers/base.py +23 -3
  130. package/core/mcp_handlers/channel_lifecycle.py +85 -30
  131. package/core/mcp_handlers/retrieval_handlers.py +11 -1
  132. package/core/mcp_handlers/rpc_server.py +6 -1
  133. package/core/mcp_handlers/supervisor_handlers.py +32 -6
  134. package/core/mcp_handlers/tool_table.py +15 -0
  135. package/core/mcp_runtime_support/environment.py +0 -38
  136. package/core/mcp_runtime_support/verifier.py +0 -52
  137. package/core/metadata.txt +2 -3
  138. package/core/planning/README.md +1 -1
  139. package/core/planning/domain_router.py +4 -2
  140. package/core/planning/dynamic_flow_analyzer.py +219 -14
  141. package/core/planning/judge_pipeline.py +87 -4
  142. package/core/planning/prompt_harness.py +7 -5
  143. package/core/planning/spec_harvester.py +4 -4
  144. package/core/probes/INTERFACE.md +11 -1
  145. package/core/probes/SPEC.md +11 -1
  146. package/core/probes/__init__.py +46 -40
  147. package/core/probes/android_probe.py +177 -9
  148. package/core/probes/codebase_memory_probe.py +57 -0
  149. package/core/probes/desktop_probe.py +104 -0
  150. package/core/probes/differential_probe.py +99 -21
  151. package/core/probes/efficiency_probe.py +64 -0
  152. package/core/probes/ios_binary_probe.py +105 -1
  153. package/core/probes/memory_probe.py +66 -0
  154. package/core/probes/miniprogram_probe.py +75 -13
  155. package/core/probes/mobile_probe.py +215 -30
  156. package/core/probes/native_probe.py +88 -0
  157. package/core/probes/openwiki_probe.py +70 -0
  158. package/core/probes/pattern_probe.py +106 -0
  159. package/core/probes/platform_probe.py +81 -0
  160. package/core/probes/probe_registry.py +108 -7
  161. package/core/probes/sast_fixture_corpus.py +340 -0
  162. package/core/probes/sast_probe.py +553 -52
  163. package/core/probes/sast_rules.py +668 -28
  164. package/core/probes/sca_scanner.py +48 -0
  165. package/core/probes/ui_accessibility.py +149 -0
  166. package/core/probes/ui_audit.py +513 -0
  167. package/core/probes/ui_contract.py +273 -0
  168. package/core/probes/ui_evidence.py +212 -0
  169. package/core/probes/ui_measurements.py +314 -0
  170. package/core/probes/ui_repair.py +250 -0
  171. package/core/probes/ui_review.py +133 -0
  172. package/core/probes/ui_storybook.py +107 -0
  173. package/core/probes/ui_tokens.py +185 -0
  174. package/core/probes/ui_visual_diff.py +131 -0
  175. package/core/probes/web_probe.py +373 -18
  176. package/core/project_profiler/SPEC.md +1 -1
  177. package/core/project_profiler/arbitrator.py +6 -1
  178. package/core/project_profiler/detector.py +8 -1
  179. package/core/project_profiler/strategy.py +51 -15
  180. package/core/prompts/command_routing_en.md +2 -2
  181. package/core/prompts/command_routing_zh.md +2 -2
  182. package/core/prompts/stages/stage_repair.md +1 -1
  183. package/core/repair/README.md +1 -1
  184. package/core/repair/l7_repair_loop.py +1 -4
  185. package/core/repair/rsi_fixer.py +4 -4
  186. package/core/repair/rsi_loop.py +1 -3
  187. package/core/repair/rsi_repair.py +7 -7
  188. package/core/repair/rsi_scope.py +27 -8
  189. package/core/report_engine/SPEC.md +1 -1
  190. package/core/report_engine/attestation.py +8 -4
  191. package/core/report_engine/finding_report.py +2 -1
  192. package/core/report_engine/models.py +7 -9
  193. package/core/report_engine/sast_bridge.py +2 -2
  194. package/core/report_engine/server.py +18 -8
  195. package/core/report_engine/web-conformance.md +123 -18
  196. package/core/report_engine/web_conformance.py +21 -52
  197. package/core/retrieval/README.md +1 -1
  198. package/core/retrieval/SPEC.md +1 -1
  199. package/core/retrieval/code_analyzer.py +50 -14
  200. package/core/retrieval/context_assembler.py +7 -1
  201. package/core/retrieval/knowledge_sync.py +108 -14
  202. package/core/retrieval/symbol_index.py +25 -6
  203. package/core/retrieval/universal_code_matcher.py +234 -49
  204. package/core/runtime/README.md +1 -1
  205. package/core/runtime/bugx_logging.py +78 -7
  206. package/core/runtime/fixture_solidify.py +5 -10
  207. package/core/runtime/incident_eval.py +1 -1
  208. package/core/runtime/model_runner.py +4 -41
  209. package/core/runtime/platform_adapter.py +2 -2
  210. package/core/runtime/prep_validate.py +4 -2
  211. package/core/runtime/project_settings.py +2 -1
  212. package/core/runtime/scenario_eval.py +50 -8
  213. package/core/skills/bugx_docs_mcp_server.py +3 -1
  214. package/core/skills/bugx_mcp_server.py +29 -2
  215. package/core/skills/tools_kb.py +1 -1
  216. package/core/supervisor/README.md +1 -1
  217. package/core/supervisor/SPEC.md +1 -1
  218. package/core/supervisor/budget_governor.py +503 -9
  219. package/core/supervisor/checkpoint_pipeline.py +248 -6
  220. package/core/supervisor/checkpoint_sync.py +13 -0
  221. package/core/supervisor/claim_events.py +1 -1
  222. package/core/supervisor/finding_workflow.py +22 -5
  223. package/core/supervisor/lease_manager.py +1 -1
  224. package/core/supervisor/lifecycle_blocks.py +6 -1
  225. package/core/supervisor/rejection_remedies.py +52 -5
  226. package/core/supervisor/serial_authorization.py +48 -4
  227. package/core/supervisor/task_scheduler.py +2 -2
  228. package/core/supervisor/worker_checkpoint.py +8 -1
  229. package/core/supervisor/worker_runtime.py +8 -2
  230. package/core/supervisor_types/worker_claim.py +9 -0
  231. package/core/webui/README.md +1 -1
  232. package/core/webui/SPEC.md +2 -1
  233. package/core/webui/adapters/claude.py +5 -1
  234. package/core/webui/adapters/cline.py +10 -2
  235. package/core/webui/adapters/codex.py +5 -1
  236. package/core/webui/adapters/dsh.py +5 -1
  237. package/core/webui/docs_session_service.py +2 -2
  238. package/core/webui/mcp_inspector.py +11 -7
  239. package/core/webui/static/00-base.css +1060 -0
  240. package/core/webui/static/01-monitoring.css +802 -0
  241. package/core/webui/static/02-header-actions.css +321 -0
  242. package/core/webui/static/03-trigger-popover.css +697 -0
  243. package/core/webui/static/04-composer.css +628 -0
  244. package/core/webui/static/05-skills-center.css +878 -0
  245. package/core/webui/static/06-mcp-center.css +623 -0
  246. package/core/webui/static/07-skill-detail.css +265 -0
  247. package/core/webui/static/08-files-management.css +167 -0
  248. package/core/webui/static/09-files-center.css +386 -0
  249. package/core/webui/static/10-icons.css +105 -0
  250. package/core/webui/static/11-project-options.css +185 -0
  251. package/core/webui/static/12-profile-tab.css +383 -0
  252. package/core/webui/static/design-tokens.css +113 -0
  253. package/core/webui/static/index.html +14 -1
  254. package/core/webui/workspace_service.py +1 -1
  255. package/docs/07_distribution/01_README_NPM.md +190 -186
  256. package/ecosystem/integrations/README.md +1 -1
  257. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  258. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
  259. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  260. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
  261. package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
  262. package/ecosystem/integrations/opencode/opencode.json +23 -12
  263. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  264. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  265. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  266. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
  267. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  268. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  269. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  270. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
  271. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
  272. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
  273. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
  274. package/interfaces/bin/bugx.js +37 -0
  275. package/interfaces/cli/bugx_cli/__init__.py +4 -2
  276. package/interfaces/cli/bugx_cli/cli.py +11 -4
  277. package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
  278. package/interfaces/cli/bugx_cli/commands/agent.py +339 -73
  279. package/interfaces/cli/bugx_cli/commands/audit.py +2 -2
  280. package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
  281. package/interfaces/cli/bugx_cli/commands/cloud.py +4 -3
  282. package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
  283. package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
  284. package/interfaces/cli/bugx_cli/commands/knowledge.py +2 -0
  285. package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
  286. package/interfaces/cli/bugx_cli/commands/plugin.py +55 -20
  287. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
  288. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
  289. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
  290. package/interfaces/cli/bugx_cli/commands/report.py +2 -6
  291. package/interfaces/cli/bugx_cli/commands/system.py +11 -11
  292. package/interfaces/cli/bugx_cli/common.py +15 -7
  293. package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
  294. package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
  295. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
  296. package/interfaces/cli/bugx_cli/infra/engine_installer.py +18 -10
  297. package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
  298. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
  299. package/interfaces/cli/bugx_cli/infra/security.py +13 -6
  300. package/package.json +2 -1
  301. package/pyproject.toml +20 -8
  302. package/scripts/ensure-python.mjs +7 -7
  303. package/scripts/sync-version.mjs +10 -21
  304. package/scripts/test-npm-wrapper.mjs +1 -1
  305. package/core/webui/static/project-settings.css +0 -6458
  306. package/docs/07_distribution/README.md +0 -16
  307. package/docs/README.md +0 -121
  308. package/interfaces/README.md +0 -143
  309. package/interfaces/bin/README.md +0 -35
  310. package/interfaces/cli/README.md +0 -90
  311. package/scripts/README.md +0 -118
@@ -37,11 +37,106 @@ from core.ledger import finding_io
37
37
  SCHEMA_VERSION = 1
38
38
  TRIAGE_STATES = {
39
39
  "new", "unchanged", "confirmed", "accepted", "fixed", "resolved",
40
- "regressed", "false_positive", "unverified",
40
+ "regressed", "false_positive", "unverified", "refuted",
41
41
  }
42
42
  SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
43
43
  INCIDENT_ID_RE = re.compile(r"^I-[0-9a-f]{12}$")
44
44
 
45
+ # ---------------------------------------------------------------------------
46
+ # NR-5(REFUTED_QUALITY_AUDIT_2026-11-16 §5 schema 级附则):证伪台账元数据修复。
47
+ #
48
+ # 历史实证(同审计 §1.3,169 条 REFUTED 全量画像):
49
+ # * confirmation 字段 164/169 为同一字符串 `hypothesis-refuted-verified`,
50
+ # 零信息量,无法作为机读 oracle 区分各记录证伪方式;
51
+ # * block_reason 全部为空串——专用于承载证伪理由的字段未使用,理由只存在
52
+ # 于自由文本 evidence;
53
+ # * severity 全部塌缩为 info——假说原严重级丢失,无法对证伪错误做风险排序。
54
+ # 后果:下游无法机器筛假证伪(审计 §4 模式 5)。按仓库宪法允许破坏性变更,
55
+ # 旧格式(字符串 confirmation / 空 block_reason)不再适用,明确拒绝并给出
56
+ # 重建方式(补齐结构化字段后重判)。
57
+ # ---------------------------------------------------------------------------
58
+ REFUTED_BLOCK_REASONS = frozenset({
59
+ "non_reproducible", # 按字段语义无法复现触发路径
60
+ "by_design", # 语义豁免类(NR-3:必须绑定设计/数据流分析证据)
61
+ "fixed_upstream", # 既往修复已覆盖(对应审计 already-fixed 层)
62
+ "evidence_insufficient", # 现有证据不足以支撑缺陷存在
63
+ "dynamic_probe_cleared", # 动态反证探针已执行且未触发(唯一最强证伪型)
64
+ })
65
+ REFUTED_BLOCK_REASON_NOTE = (
66
+ "REFUTED 必须提供结构化 block_reason(枚举: "
67
+ + "/".join(sorted(REFUTED_BLOCK_REASONS))
68
+ + ");自由文本敷衍视为未提供(NR-5 fail-closed)"
69
+ )
70
+ # NR-5 重判通道:历史台账的假说原严重级已经丢失,任何人为补写都是伪造证据。
71
+ # `unknown` 是显式状态(必须携带理由与证据引用),与伪造枚举值严格区分;
72
+ # 消费方通过 refuted_strength() 把它识别为 legacy,不按证伪强度消费。
73
+ REFUTED_ORIGINAL_SEVERITY_UNKNOWN = "unknown"
74
+ REFUTED_LEGACY_STRENGTH = "legacy"
75
+ _LEGACY_REFUTED_CONFIRMATION_PREFIX = "hypothesis-refuted"
76
+
77
+
78
+ def is_legacy_refuted(finding: dict) -> bool:
79
+ """判定未重判的历史 REFUTED(字符串 confirmation + 空 block_reason,无 lifecycle)。"""
80
+ if not isinstance(finding, dict):
81
+ return False
82
+ if str(finding.get("status") or "").upper() != "REFUTED":
83
+ return False
84
+ lifecycle = finding.get("lifecycle")
85
+ if isinstance(lifecycle, dict) and lifecycle.get("state") in TRIAGE_STATES:
86
+ return False
87
+ confirmation = finding.get("confirmation")
88
+ return (
89
+ isinstance(confirmation, str)
90
+ and confirmation.strip().lower().startswith(_LEGACY_REFUTED_CONFIRMATION_PREFIX)
91
+ )
92
+
93
+
94
+ def refuted_strength(finding: dict) -> str:
95
+ """单一证伪强度口径:legacy / 结构化 block_reason / not_refuted。
96
+
97
+ 未重判的历史记录、或原严重级标为 unknown 的重判记录一律返回 ``legacy``,
98
+ 调用方不得把它们当作已具备可机器核验的证伪强度。
99
+ """
100
+ if not isinstance(finding, dict):
101
+ return "not_refuted"
102
+ lifecycle = finding.get("lifecycle")
103
+ is_refuted = is_legacy_refuted(finding) or (
104
+ isinstance(lifecycle, dict) and lifecycle.get("state") == "refuted"
105
+ )
106
+ if not is_refuted:
107
+ return "not_refuted"
108
+ validation = lifecycle.get("refuted_validation") if isinstance(lifecycle, dict) else None
109
+ if not isinstance(validation, dict):
110
+ return REFUTED_LEGACY_STRENGTH
111
+ if validation.get("original_severity") == REFUTED_ORIGINAL_SEVERITY_UNKNOWN:
112
+ return REFUTED_LEGACY_STRENGTH
113
+ block_reason = validation.get("block_reason")
114
+ return block_reason if block_reason in REFUTED_BLOCK_REASONS else REFUTED_LEGACY_STRENGTH
115
+
116
+
117
+ def _retriage_snapshot(finding: dict) -> dict:
118
+ snapshot = copy.deepcopy(finding)
119
+ snapshot.pop("retriage_history", None)
120
+ return snapshot
121
+
122
+
123
+ def _record_retriage(finding: dict, *, reason: str, source: str, revision: int) -> None:
124
+ """把重判前原记录写入不可篡改的 retriage_history(含 SHA 快照)。"""
125
+ snapshot = _retriage_snapshot(finding)
126
+ previous_sha256 = hashlib.sha256(json.dumps(
127
+ snapshot, ensure_ascii=False, sort_keys=True, separators=(",", ":"),
128
+ ).encode("utf-8")).hexdigest()
129
+ history = finding.get("retriage_history")
130
+ if not isinstance(history, list):
131
+ history = []
132
+ if len(history) >= 100:
133
+ raise LifecycleError("retriage_history 已达上限(100)")
134
+ history.append({
135
+ "reason": reason, "source": source, "revision": revision,
136
+ "previous_sha256": previous_sha256, "previous": snapshot,
137
+ })
138
+ finding["retriage_history"] = history
139
+
45
140
 
46
141
  class LifecycleError(ValueError):
47
142
  """findings 生命周期协议错误。"""
@@ -62,6 +157,12 @@ def _state(finding: dict) -> str:
62
157
  lifecycle = finding.get("lifecycle")
63
158
  if isinstance(lifecycle, dict) and lifecycle.get("state") in TRIAGE_STATES:
64
159
  return str(lifecycle["state"])
160
+ # NR-5 消费兼容:历史 REFUTED 没有 lifecycle,但状态就是 refuted。
161
+ # 旧实现返回 new,reconcile 会把已证伪记录重新计为新发现,并让
162
+ # 未验证回补通道误以为它们还在追踪中。这里按显式 legacy 标记识别,
163
+ # 强度仍需通过 refuted_strength() 判断,不能当已重判证据。
164
+ if is_legacy_refuted(finding):
165
+ return "refuted"
65
166
  return "new"
66
167
 
67
168
 
@@ -99,12 +200,17 @@ def reconcile(current_payload: dict, baseline_payload: dict | None = None) -> di
99
200
  "last_seen_run_id": current_run,
100
201
  "previous_state": prior_state,
101
202
  }
203
+ if is_legacy_refuted(item):
204
+ # 显式标记未重判,避免下游把「有 refuted 状态」误读为
205
+ # 「已有可机器核验的证伪强度」(NR-5 消费兼容)。
206
+ item["lifecycle"]["refuted_validation_status"] = REFUTED_LEGACY_STRENGTH
207
+ item["lifecycle"]["refuted_strength"] = REFUTED_LEGACY_STRENGTH
102
208
  active.append(item)
103
209
  counts[state] += 1
104
210
  unverified = []
105
211
  for finding in sorted(baseline_findings, key=lambda item: item["id"]):
106
212
  key = lifecycle_key(finding)
107
- if key in current_keys or _state(finding) in {"fixed", "resolved", "false_positive"}:
213
+ if key in current_keys or _state(finding) in {"fixed", "resolved", "false_positive", "refuted"}:
108
214
  continue
109
215
  item = dict(finding)
110
216
  item["fingerprint"] = key
@@ -173,6 +279,98 @@ def validate_fix_validation(value: object) -> dict:
173
279
  return value
174
280
 
175
281
 
282
+ def validate_refuted_validation(value: object, finding: dict | None = None,
283
+ *, allow_severity_restore: bool = False) -> dict:
284
+ """NR-5:``refuted`` 状态转移的强制结构化证伪协议(fail-closed)。
285
+
286
+ 契约(每条 REFUTED 都必须逐记录携带,禁止台账级同串复制):
287
+ * ``block_reason``:结构化证伪理由,必须取自 :data:`REFUTED_BLOCK_REASONS`
288
+ 枚举,自由文本敷衍视为未提供;
289
+ * ``refuted_by``:非空判定者标识(谁执行了证伪判定);
290
+ * ``refuted_evidence``:反证证据引用数组——**可为空数组,但结构必须存在**;
291
+ * ``original_severity``:假说原严重级。severity 保留原值禁止塌缩 info;
292
+ 仅当 finding 本身无 severity 时才允许落到 info。原始级别确实丢失时,
293
+ 允许显式写 ``"unknown"`` + ``severity_unknown_reason``(必须说明来源,
294
+ 禁止凭空补一个合法枚举值伪造证据),消费方按 legacy 处理。
295
+
296
+ 与既有 ``false_positive`` 强制 note(撤回级决定零理由禁止)同一模式,
297
+ 但比自由文本更强:理由字段本身结构化,下游可按 ``block_reason`` 枚举
298
+ 直接过滤证伪强度。``allow_severity_restore`` 仅供有证据的历史重判通道
299
+ 从 info 恢复原级;普通 triage 绝不开启,防止以"恢复"之名掩盖塌缩。
300
+ """
301
+ if not isinstance(value, dict):
302
+ raise LifecycleError("refuted 必须提供 refuted_validation(结构化证伪协议)")
303
+ block_reason = value.get("block_reason")
304
+ if not isinstance(block_reason, str) or block_reason not in REFUTED_BLOCK_REASONS:
305
+ raise LifecycleError(REFUTED_BLOCK_REASON_NOTE + f";得到: {block_reason!r}")
306
+ refuted_by = value.get("refuted_by")
307
+ if not isinstance(refuted_by, str) or not refuted_by.strip():
308
+ raise LifecycleError(
309
+ "refuted_validation.refuted_by 必须是非空判定者标识"
310
+ "(逐记录携带,禁止全台账同串复制)"
311
+ )
312
+ if len(refuted_by) > 200:
313
+ raise LifecycleError("refuted_validation.refuted_by 不得超过 200 字符")
314
+ refuted_evidence = value.get("refuted_evidence")
315
+ if not isinstance(refuted_evidence, list):
316
+ raise LifecycleError(
317
+ "refuted_validation.refuted_evidence 必须是数组(可为空,结构必须存在)"
318
+ )
319
+ for item in refuted_evidence:
320
+ if not isinstance(item, str) or not item.strip() or len(item) > 2000:
321
+ raise LifecycleError("refuted_evidence 元素必须是非空字符串(≤2000字符)")
322
+ severity_levels = tuple(
323
+ getattr(agent_eval, "FINDING_SEVERITY_LEVELS",
324
+ ("info", "low", "medium", "high", "critical"))
325
+ )
326
+ current = finding.get("severity") if isinstance(finding, dict) else None
327
+ current = (
328
+ str(current).strip().lower()
329
+ if isinstance(current, str) and current.strip() else None
330
+ )
331
+ original = value.get("original_severity")
332
+ if original == REFUTED_ORIGINAL_SEVERITY_UNKNOWN:
333
+ # 显式「原级已丢失」通道:不是枚举补全,而是把丢失事实留给消费方。
334
+ reason = value.get("severity_unknown_reason")
335
+ if not isinstance(reason, str) or not reason.strip() or len(reason) > 2000:
336
+ raise LifecycleError(
337
+ "original_severity=unknown 必须提供非空 severity_unknown_reason"
338
+ "(≤2000字符,说明原级为何不可得,禁止凭空补枚举)"
339
+ )
340
+ if current is not None and current != "info":
341
+ raise LifecycleError(
342
+ "original_severity=unknown 不得用于有真实 severity 的记录"
343
+ f"(当前 severity={current};未知原级无法证明未塌缩)"
344
+ )
345
+ validated = dict(value)
346
+ validated["severity_unknown_reason"] = reason.strip()
347
+ return validated
348
+ if original is None:
349
+ if current is not None and current != "info":
350
+ # finding 已带真实严重级却不随转移携带原级 ⇒ 判定塌缩,拒绝。
351
+ raise LifecycleError(
352
+ "refuted_validation 必须携带 original_severity"
353
+ f"(finding 现有 severity={current},禁止塌缩为 info)"
354
+ )
355
+ validated = dict(value)
356
+ validated["original_severity"] = "info" # 原级缺失才允许 info
357
+ return validated
358
+ if not isinstance(original, str) or original not in severity_levels:
359
+ raise LifecycleError(
360
+ f"refuted_validation.original_severity 无效: {original!r}"
361
+ f"(合法: {'/'.join(severity_levels)},原级丢失请用 "
362
+ f"{REFUTED_ORIGINAL_SEVERITY_UNKNOWN} + severity_unknown_reason)"
363
+ )
364
+ if current is not None and current != original and not (
365
+ allow_severity_restore and current == "info"
366
+ ):
367
+ raise LifecycleError(
368
+ f"REFUTED severity 塌缩: 记录 severity={current}"
369
+ f" 与假说原级 {original} 不一致(NR-5 禁止塌缩)"
370
+ )
371
+ return dict(value)
372
+
373
+
176
374
  def verify_fix_validation_artifacts(fix_validation: dict, root: Path,
177
375
  ledger: Path | None = None) -> list[str]:
178
376
  """复核 fixed 声明:工件哈希重算 + incident 存在性互查;返回错误清单。"""
@@ -233,7 +431,8 @@ def reopen(finding: dict, *, reason: str, revision: int) -> dict:
233
431
 
234
432
 
235
433
  def triage(payload: dict, finding_id: str, state: str, note: str | None = None,
236
- fix_validation: dict | None = None) -> dict:
434
+ fix_validation: dict | None = None,
435
+ refuted_validation: dict | None = None) -> dict:
237
436
  if state not in TRIAGE_STATES - {"unchanged", "regressed", "resolved", "unverified"}:
238
437
  raise LifecycleError(f"不可人工设置 lifecycle state: {state}")
239
438
  findings = payload.get("findings")
@@ -248,6 +447,41 @@ def triage(payload: dict, finding_id: str, state: str, note: str | None = None,
248
447
  raise LifecycleError("撤回 rejected/false_positive 必须通过宿主 reopen 接口")
249
448
  if state == "fixed":
250
449
  lifecycle["fix_validation"] = validate_fix_validation(fix_validation)
450
+ if state == "refuted":
451
+ # NR-5(2026-11-16 证伪质量审计 §5):REFUTED 与 false_positive 同为
452
+ # 撤回级决定,但历史台账 169 条 REFUTED 的 block_reason 全空、
453
+ # confirmation 164/169 同字符串、severity 全塌缩 info——证伪强度
454
+ # 无法机器筛选。此处 fail-closed:结构化证伪协议不完整即拒绝转移。
455
+ validated = validate_refuted_validation(refuted_validation, finding)
456
+ original = validated["original_severity"]
457
+ current = finding.get("severity")
458
+ if not (isinstance(current, str) and current.strip()):
459
+ # unknown 不是 severity 枚举值,不能写进 finding.severity。
460
+ finding["severity"] = (
461
+ "info" if original == REFUTED_ORIGINAL_SEVERITY_UNKNOWN else original
462
+ )
463
+ lifecycle["refuted_validation"] = validated
464
+ lifecycle["refuted_validation_status"] = (
465
+ REFUTED_LEGACY_STRENGTH
466
+ if original == REFUTED_ORIGINAL_SEVERITY_UNKNOWN else "retriated"
467
+ )
468
+ lifecycle["refuted_strength"] = refuted_strength({**finding, "lifecycle": lifecycle})
469
+ # confirmation 结构必须存在且逐记录携带判定者与反证证据引用,
470
+ # 从 schema 层消灭「全台账同字符串复制」(审计 §1.3 异常 1)。
471
+ finding["confirmation"] = {
472
+ "state": "refuted",
473
+ "block_reason": validated["block_reason"],
474
+ "refuted_by": validated["refuted_by"],
475
+ "refuted_evidence": list(validated["refuted_evidence"]),
476
+ "original_severity": original,
477
+ "refuted_validation_status": lifecycle["refuted_validation_status"],
478
+ }
479
+ if state == "false_positive" and not (note and note.strip()):
480
+ # F-RSI-20261115-128:false_positive 与 rejected 同为撤回级决定——
481
+ # 它把 finding 从 reconcile 的 unverified 追踪中消失(L128 过滤),
482
+ # 零理由即可把真缺陷撤出追踪。对齐 finding_confirmation.rejected
483
+ # 的强制理由语义(rejection_class + reason 必填)。
484
+ raise LifecycleError("false_positive 必须提供理由(note):撤回级决定不得零理由")
251
485
  lifecycle["state"] = state
252
486
  if note:
253
487
  lifecycle["triage_note"] = note
@@ -255,9 +489,179 @@ def triage(payload: dict, finding_id: str, state: str, note: str | None = None,
255
489
  return finding
256
490
 
257
491
 
492
+ def retriage_legacy_refuted(payload: dict, decisions: dict,
493
+ *, source: str | None = None) -> dict:
494
+ """NR-5 方案 A:按显式裁决重判历史 REFUTED,绝不批量补造丢失字段。
495
+
496
+ 输入 ``decisions`` 必须是人工/审计逐条裁决文件,格式::
497
+
498
+ {
499
+ "source": "DYNAMIC_REFUTATION_SAMPLE_...md#结论",
500
+ "decisions": [
501
+ {"id": "F-RSI-...", "block_reason": "dynamic_probe_cleared",
502
+ "refuted_by": "审计员/agent 标识",
503
+ "refuted_evidence": ["报告路径#章节", "工件 sha256"],
504
+ "original_severity": "unknown",
505
+ "severity_unknown_reason": "原始假说严重级未存档,禁止补写",
506
+ "occurrence": 1,
507
+ "note": "逐条判定说明"}
508
+ ]
509
+ }
510
+
511
+ ``occurrence`` 是同一 id 在台账中重复出现时的 1-based 序号(默认 1),
512
+ 让重复 id 也能逐副本裁决,绝不静默跳过其中一份。
513
+
514
+ 原级有确证材料时才允许填合法枚举,且必须附 ``severity_evidence``;
515
+ 否则只能填 ``unknown`` 并说明理由。未被裁决的历史记录保持原样,
516
+ 输出 summary 中计入 ``unchanged_legacy``,由消费方按 legacy 处理。
517
+ """
518
+ if not isinstance(payload, dict) or not isinstance(payload.get("findings"), list):
519
+ raise LifecycleError("重判输入 payload.findings 必须是数组")
520
+ if not isinstance(decisions, dict) or not isinstance(decisions.get("decisions"), list):
521
+ raise LifecycleError("重判裁决文件必须含 decisions 数组")
522
+ adjudication_source = source if source is not None else decisions.get("source")
523
+ if (not isinstance(adjudication_source, str) or not adjudication_source.strip()
524
+ or len(adjudication_source) > 500):
525
+ raise LifecycleError("重判必须提供非空 source(≤500字符,指向裁决依据)")
526
+ source = adjudication_source.strip()
527
+ findings = payload["findings"]
528
+ by_id: dict[str, list[dict]] = {}
529
+ for index, item in enumerate(findings, 1):
530
+ if not isinstance(item, dict) or not isinstance(item.get("id"), str):
531
+ raise LifecycleError(f"重判输入 finding #{index} 缺 id")
532
+ by_id.setdefault(item["id"], []).append(item)
533
+
534
+ seen: set[tuple[str, int]] = set()
535
+ retriated: list[str] = []
536
+ retriated_unknown: list[str] = []
537
+ transformed: set[int] = set()
538
+ for index, decision in enumerate(decisions["decisions"], 1):
539
+ if not isinstance(decision, dict):
540
+ raise LifecycleError(f"重判裁决 #{index} 必须是对象")
541
+ finding_id = decision.get("id")
542
+ if not isinstance(finding_id, str) or not finding_id.strip():
543
+ raise LifecycleError(f"重判裁决 #{index} 缺 id")
544
+ finding_id = finding_id.strip()
545
+ occurrence = decision.get("occurrence", 1)
546
+ if (not isinstance(occurrence, int) or isinstance(occurrence, bool)
547
+ or occurrence < 1):
548
+ raise LifecycleError(f"重判裁决 #{index} occurrence 必须是正整数")
549
+ key = (finding_id, occurrence)
550
+ if key in seen:
551
+ raise LifecycleError(
552
+ f"重判裁决重复: {finding_id}#{occurrence}"
553
+ "(同一 id 的不同副本请用不同 occurrence)"
554
+ )
555
+ seen.add(key)
556
+ copies = by_id.get(finding_id, [])
557
+ if occurrence > len(copies):
558
+ raise LifecycleError(
559
+ f"重判裁决指向不存在的 finding 副本: {finding_id}#{occurrence}"
560
+ f"(实际只有 {len(copies)} 份)"
561
+ )
562
+ finding = copies[occurrence - 1]
563
+ label = finding_id if occurrence == 1 else f"{finding_id}#{occurrence}"
564
+ if not is_legacy_refuted(finding):
565
+ raise LifecycleError(
566
+ f"{label} 不是未重判的 legacy REFUTED,拒绝覆盖已有裁决"
567
+ )
568
+ evidence = decision.get("refuted_evidence")
569
+ if (not isinstance(evidence, list) or not evidence
570
+ or any(not isinstance(item, str) or not item.strip() or len(item) > 2000
571
+ for item in evidence)):
572
+ raise LifecycleError(
573
+ f"{finding_id} 重判必须提供非空 refuted_evidence(逐条证据引用)"
574
+ )
575
+ original = decision.get("original_severity")
576
+ severity_evidence = decision.get("severity_evidence")
577
+ if original == REFUTED_ORIGINAL_SEVERITY_UNKNOWN:
578
+ if severity_evidence:
579
+ raise LifecycleError(
580
+ f"{finding_id} original_severity=unknown 不得同时携带 severity_evidence"
581
+ )
582
+ elif isinstance(original, str) and original.strip():
583
+ if (not isinstance(severity_evidence, list) or not severity_evidence
584
+ or any(not isinstance(item, str) or not item.strip()
585
+ or len(item) > 2000 for item in severity_evidence)):
586
+ raise LifecycleError(
587
+ f"{finding_id} 填写原严重级必须提供 severity_evidence 证据引用,"
588
+ "禁止凭空补枚举值"
589
+ )
590
+ validated = validate_refuted_validation(
591
+ decision, finding,
592
+ allow_severity_restore=(
593
+ isinstance(original, str)
594
+ and original not in {REFUTED_ORIGINAL_SEVERITY_UNKNOWN, "info"}
595
+ ),
596
+ )
597
+ note = decision.get("note")
598
+ if note is not None and (not isinstance(note, str) or len(note) > 2000):
599
+ raise LifecycleError(f"{finding_id} note 必须是字符串(≤2000字符)")
600
+ reason = (note or "NR-5 逐条 triage 重判").strip()
601
+
602
+ _record_retriage(finding, reason=reason, source=source, revision=len(
603
+ finding.get("retriage_history") or []))
604
+ lifecycle = dict(finding.get("lifecycle") or {})
605
+ lifecycle.update({
606
+ "state": "refuted",
607
+ "previous_state": "refuted",
608
+ "refuted_validation": validated,
609
+ "refuted_validation_status": (
610
+ REFUTED_LEGACY_STRENGTH
611
+ if validated["original_severity"] == REFUTED_ORIGINAL_SEVERITY_UNKNOWN
612
+ else "retriated"
613
+ ),
614
+ "retriage_source": source,
615
+ "triage_note": reason,
616
+ })
617
+ if validated["original_severity"] != REFUTED_ORIGINAL_SEVERITY_UNKNOWN:
618
+ # 有证据支持原级时写回,撤销历史 info 塌缩。
619
+ finding["severity"] = validated["original_severity"]
620
+ lifecycle["severity_evidence"] = list(severity_evidence)
621
+ finding["lifecycle"] = lifecycle
622
+ lifecycle["refuted_strength"] = refuted_strength(finding)
623
+ finding["block_reason"] = validated["block_reason"]
624
+ finding["confirmation"] = {
625
+ "state": "refuted",
626
+ "block_reason": validated["block_reason"],
627
+ "refuted_by": validated["refuted_by"],
628
+ "refuted_evidence": list(validated["refuted_evidence"]),
629
+ "original_severity": validated["original_severity"],
630
+ "refuted_validation_status": lifecycle["refuted_validation_status"],
631
+ }
632
+ # NR-5 §1.3 异常 2:证伪记录保留 reproducible=true 自相矛盾,
633
+ # 重判时显式纠正并在 lifecycle 留痕。
634
+ if finding.get("reproducible") is True:
635
+ finding["reproducible"] = False
636
+ lifecycle["reproducible_corrected"] = True
637
+ retriated.append(label)
638
+ transformed.add(id(finding))
639
+ if validated["original_severity"] == REFUTED_ORIGINAL_SEVERITY_UNKNOWN:
640
+ retriated_unknown.append(label)
641
+
642
+ unchanged_legacy = [
643
+ item["id"] for item in findings
644
+ if is_legacy_refuted(item) and id(item) not in transformed
645
+ ]
646
+ return {
647
+ "schema_version": SCHEMA_VERSION,
648
+ "retriage_source": source,
649
+ "findings": findings,
650
+ "summary": {
651
+ "total": len(findings),
652
+ "retriated": len(retriated),
653
+ "retriated_unknown": len(retriated_unknown),
654
+ "unchanged_legacy": len(unchanged_legacy),
655
+ },
656
+ "retriated_ids": retriated,
657
+ "retriated_unknown_ids": retriated_unknown,
658
+ "unchanged_legacy_ids": unchanged_legacy,
659
+ }
660
+
661
+
258
662
  def main(argv: list[str] | None = None) -> int:
259
663
  parser = argparse.ArgumentParser(description=__doc__)
260
- parser.add_argument("command", choices=("compare", "triage"))
664
+ parser.add_argument("command", choices=("compare", "triage", "retriage-legacy"))
261
665
  parser.add_argument("--current", type=Path, required=True)
262
666
  parser.add_argument("--baseline", type=Path)
263
667
  parser.add_argument("--root", type=Path, default=Path.cwd())
@@ -267,8 +671,15 @@ def main(argv: list[str] | None = None) -> int:
267
671
  parser.add_argument("--note")
268
672
  parser.add_argument("--fix-validation", type=Path,
269
673
  help="fixed 状态所需的真实目标复验 JSON")
674
+ parser.add_argument("--refuted-validation", type=Path,
675
+ help="refuted 状态所需的结构化证伪协议 JSON"
676
+ "(block_reason/refuted_by/refuted_evidence/original_severity)")
270
677
  parser.add_argument("--ledger", type=Path,
271
678
  help="可选错题账本;提供后对 incident_id 做存在性互查")
679
+ parser.add_argument("--decisions", type=Path,
680
+ help="retriage-legacy 所需的逐条裁决 JSON")
681
+ parser.add_argument("--source",
682
+ help="retriage-legacy 裁决依据(覆盖裁决文件中的 source)")
272
683
  args = parser.parse_args(argv)
273
684
  try:
274
685
  current = agent_eval.load_json(args.current)
@@ -276,13 +687,25 @@ def main(argv: list[str] | None = None) -> int:
276
687
  finding_io.load_and_validate(args.current, args.root)
277
688
  baseline = agent_eval.load_json(args.baseline) if args.baseline else None
278
689
  payload = reconcile(current, baseline)
690
+ elif args.command == "retriage-legacy":
691
+ if not args.decisions:
692
+ raise LifecycleError("retriage-legacy 必须提供 --decisions")
693
+ decisions = agent_eval.load_json(args.decisions)
694
+ payload = retriage_legacy_refuted(
695
+ current, decisions, source=args.source,
696
+ )
279
697
  else:
280
698
  if not args.id or not args.state:
281
699
  raise LifecycleError("triage 必须提供 --id 和 --state")
282
700
  fix_validation = (
283
701
  agent_eval.load_json(args.fix_validation) if args.fix_validation else None
284
702
  )
285
- triage(current, args.id, args.state, args.note, fix_validation)
703
+ refuted_validation = (
704
+ agent_eval.load_json(args.refuted_validation)
705
+ if args.refuted_validation else None
706
+ )
707
+ triage(current, args.id, args.state, args.note, fix_validation,
708
+ refuted_validation)
286
709
  if args.state == "fixed" and isinstance(fix_validation, dict):
287
710
  artifact_errors = verify_fix_validation_artifacts(
288
711
  fix_validation, args.root, args.ledger,
@@ -115,6 +115,12 @@ def _oracle_case(value: object, field: str) -> dict[str, object]:
115
115
  normalized["text"] = _text(value.get("text"), f"{field}.text", max_length=1024)
116
116
  else:
117
117
  normalized["path"] = _text(value.get("path"), f"{field}.path", max_length=256)
118
+ if "equals" not in value:
119
+ # F-RSI-20261115-122:equals 漏配会被 _matches 的 value == None
120
+ # 误判为命中(JSON 路径值恰为 null 时 None == None),漏配与
121
+ # 「期望 null」不可区分——构造期 fail-fast;显式传 null 保留
122
+ # (期望 null 值是合法判据语义)。
123
+ raise VerificationError(f"{field}.equals 缺失(期望 null 请显式传 null)")
118
124
  normalized["equals"] = value.get("equals")
119
125
  return normalized
120
126
 
@@ -301,7 +307,18 @@ def verify_finding(root: Path, finding: Mapping[str, object], recipe: Mapping[st
301
307
  raise VerificationError("artifact_root 越界") from exc
302
308
  verification_id = str(uuid.uuid4())
303
309
  directory = base / verification_id
304
- directory.mkdir(parents=True, exist_ok=False, mode=0o700)
310
+ records: list[dict[str, object]] = []
311
+ # F-RSI-20261110-021:artifact_root 不可写(只读挂载/磁盘满/权限收紧)时
312
+ # 目录创建与 BLOCKED receipt 落盘都会 OSError——此前裸异常冒出 verify_finding,
313
+ # 上游只能靠 dispatch 兜底丢结构化语义。降级为内存 BLOCKED receipt:
314
+ # receipt_path 置 None + degraded 标记,双跑照常执行(结果不落盘但可审计)。
315
+ degraded_storage = False
316
+ try:
317
+ directory.mkdir(parents=True, exist_ok=False, mode=0o700)
318
+ except OSError as exc:
319
+ degraded_storage = True
320
+ directory = None
321
+ storage_error = f"artifact_root 不可写({type(exc).__name__}: {exc})"
305
322
  records: list[dict[str, object]] = []
306
323
  try:
307
324
  for index in range(POSITIVE_RUNS_REQUIRED):
@@ -327,10 +344,20 @@ def verify_finding(root: Path, finding: Mapping[str, object], recipe: Mapping[st
327
344
  "request_id": request_id,
328
345
  "error": str(exc)[:512], "recipe_digest": spec.digest(),
329
346
  }
330
- _atomic_json(directory / "receipt.json", receipt)
347
+ if directory is not None:
348
+ try:
349
+ _atomic_json(directory / "receipt.json", receipt)
350
+ receipt["receipt_path"] = str(directory / "receipt.json")
351
+ except OSError:
352
+ pass # 落盘失败也返回内存 BLOCKED receipt(F-021 degraded)
353
+ else:
354
+ receipt["degraded"] = True
331
355
  return receipt
332
- positives_ok = len(records) == 3 and all(bool(item.get("oracle_matched")) for item in records[:2])
333
- negative_ok = bool(records[2].get("oracle_matched"))
356
+ positives_ok = (
357
+ len(records) == POSITIVE_RUNS_REQUIRED + 1
358
+ and all(bool(item.get("oracle_matched")) for item in records[:POSITIVE_RUNS_REQUIRED])
359
+ )
360
+ negative_ok = bool(records[POSITIVE_RUNS_REQUIRED].get("oracle_matched"))
334
361
  status = "CONFIRMED" if positives_ok and negative_ok else "CANDIDATE"
335
362
  receipt: dict[str, object] = {
336
363
  "protocol_version": PROTOCOL_VERSION,
@@ -347,14 +374,23 @@ def verify_finding(root: Path, finding: Mapping[str, object], recipe: Mapping[st
347
374
  "recipe_digest": spec.digest(),
348
375
  "oracle_reference": spec.oracle_reference,
349
376
  "oracle_hash": spec.oracle_hash,
350
- "positive_runs": records[:2],
351
- "negative_control": records[2],
377
+ "positive_runs": records[:POSITIVE_RUNS_REQUIRED],
378
+ "negative_control": records[POSITIVE_RUNS_REQUIRED],
352
379
  "raw_output_source": "engine",
353
- "receipt_path": str(directory / "receipt.json"),
380
+ "receipt_path": str(directory / "receipt.json") if directory is not None else None,
354
381
  "created_at": time.time(),
355
382
  }
356
383
  receipt["verification_digest"] = _sha256(_canonical(receipt))
357
- _atomic_json(directory / "receipt.json", receipt)
384
+ if directory is not None:
385
+ try:
386
+ _atomic_json(directory / "receipt.json", receipt)
387
+ receipt["receipt_path"] = str(directory / "receipt.json")
388
+ except OSError:
389
+ receipt["degraded"] = True
390
+ receipt["receipt_path"] = None
391
+ else:
392
+ receipt["degraded"] = True
393
+ receipt["receipt_path"] = None
358
394
  return receipt
359
395
 
360
396
 
@@ -441,10 +441,16 @@ def lookup_incidents(
441
441
  data = canonical_bytes(row)
442
442
  size = len(data)
443
443
  toks, _ = estimate_tokens(data)
444
- if byte_budget is not None and total_b + size > byte_budget:
445
- continue
446
- if token_budget is not None and total_t + toks > token_budget:
447
- continue
444
+ # F-RSI-20261115-127:identity 精确命中是调用方显式 signatures 的
445
+ # 查询意图本体,不得被预算挤掉——context 合法上限 64KB 可超
446
+ # byte_budget 20480,被 continue 跳过后低分 text 行反被塞入,
447
+ # 显式签名查询静默落空。预算只约束文本扫描的加分行;limit 硬顶
448
+ # 对全部行仍生效。
449
+ if not _identity_exact_hit:
450
+ if byte_budget is not None and total_b + size > byte_budget:
451
+ continue
452
+ if token_budget is not None and total_t + toks > token_budget:
453
+ continue
448
454
  result.append(row)
449
455
  total_b += size
450
456
  total_t += toks
@@ -174,16 +174,19 @@ def normalize_pattern(payload: Mapping[str, Any], now: str | None = None) -> dic
174
174
  "created_at": str(payload.get("created_at") or timestamp),
175
175
  "updated_at": str(payload.get("updated_at") or timestamp),
176
176
  "last_used_at": payload.get("last_used_at"),
177
- "use_count": int(payload.get("use_count", 0)), "hit_count": int(payload.get("hit_count", 0)),
178
- "miss_count": int(payload.get("miss_count", 0)),
179
- "false_positive_count": int(payload.get("false_positive_count", 0)),
180
- "rejected_count": int(payload.get("rejected_count", 0)),
181
177
  **extract_card_fields(payload),
182
178
  "routing_tags": extract_routing_tags(payload),
183
179
  }
184
- for field in ("use_count", "hit_count", "miss_count", "false_positive_count", "rejected_count"):
185
- if result[field] < 0:
186
- raise LessonLedgerError(f"{field} 不得小于 0")
180
+ # F-RSI-20261115-130:计数器字段显式校验——int() 隐式转换会把 bool 静默
181
+ # 折成 0/1、小数截断(3.9→3)、非数字裸抛 ValueError(非 LessonLedgerError,
182
+ # 穿过 except LessonLedgerError 调用链)。对齐 incidents.normalize_duration
183
+ # 的显式校验标准(bool 排除 + 整型 + 非负),消除同域两套标准。
184
+ for field in ("use_count", "hit_count", "miss_count",
185
+ "false_positive_count", "rejected_count"):
186
+ value = payload.get(field, 0)
187
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
188
+ raise LessonLedgerError(f"{field} 必须是非负整数(收到 {value!r})")
189
+ result[field] = value
187
190
  return result
188
191
 
189
192