bugx-cli 0.0.0-stage → 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.
- package/LICENSE +55 -0
- package/README.md +284 -2
- package/core/CATALOG.json +141 -0
- package/core/README.md +254 -0
- package/core/adapters/README.md +35 -0
- package/core/adapters/android-interaction.json +81 -0
- package/core/adapters/android.json +24 -0
- package/core/adapters/desktop-macos.json +20 -0
- package/core/adapters/ios-interaction.json +34 -0
- package/core/adapters/ios.json +23 -0
- package/core/adapters/memory-macos.json +24 -0
- package/core/agent/README.md +51 -0
- package/core/agent/__init__.py +146 -0
- package/core/agent/agent_artifacts.py +766 -0
- package/core/agent/agent_eval.py +1155 -0
- package/core/agent/agent_execution.py +718 -0
- package/core/agent/agent_orchestrator.py +1351 -0
- package/core/agent/agent_targets.py +877 -0
- package/core/agent/agent_workspace.py +770 -0
- package/core/agent/feature_baseline.py +150 -0
- package/core/assets/README.md +24 -0
- package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
- package/core/assets/axe-core/LICENSE.txt +362 -0
- package/core/assets/axe-core/UPSTREAM.md +10 -0
- package/core/assets/axe-core/axe.min.js +12 -0
- package/core/assets/bugx-avatar-1024.png +0 -0
- package/core/assets/bugx-avatar-512.png +0 -0
- package/core/assets/bugx-avatar-tight.svg +23 -0
- package/core/assets/bugx-avatar.svg +28 -0
- package/core/assets/bugx-hero-cn.png +0 -0
- package/core/assets/bugx-hero-en.png +0 -0
- package/core/assets/bugx-hero-en.svg +74 -0
- package/core/assets/bugx-hero-zh.svg +74 -0
- package/core/assets/codex.png +0 -0
- package/core/assets/dsh.png +0 -0
- package/core/assets/project-layout.md +42 -0
- package/core/assets/webui-chatgpt.jpg +0 -0
- package/core/assets/webui-session.jpg +0 -0
- package/core/assets/webui-skills.jpg +0 -0
- package/core/assets/webui-studio.jpg +0 -0
- package/core/assets/webui-zcode.jpg +0 -0
- package/core/assets/zcode.png +0 -0
- package/core/audit_packs/README.md +37 -0
- package/core/audit_packs/data-audit/manifest.json +94 -0
- package/core/audit_packs/data-audit/stages/00-scope.md +14 -0
- package/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
- package/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
- package/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
- package/core/audit_packs/desktop-audit/manifest.json +123 -0
- package/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
- package/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
- package/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
- package/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
- package/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
- package/core/audit_packs/memory-testing.md +227 -0
- package/core/audit_packs/mobile-audit/manifest.json +155 -0
- package/core/audit_packs/mobile-audit/modules/android.md +19 -0
- package/core/audit_packs/mobile-audit/modules/h5.md +18 -0
- package/core/audit_packs/mobile-audit/modules/ios.md +25 -0
- package/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
- package/core/audit_packs/mobile-audit/modules/webview.md +18 -0
- package/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
- package/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
- package/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
- package/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
- package/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
- package/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
- package/core/audit_packs/native-audit/manifest.json +127 -0
- package/core/audit_packs/native-audit/stages/00-scope.md +14 -0
- package/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
- package/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
- package/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
- package/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
- package/core/audit_packs/platform-testing.md +174 -0
- package/core/audit_packs/web-audit/manifest.json +191 -0
- package/core/audit_packs/web-audit/modules/graphql.md +5 -0
- package/core/audit_packs/web-audit/modules/h5.md +18 -0
- package/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
- package/core/audit_packs/web-audit/modules/oauth.md +4 -0
- package/core/audit_packs/web-audit/modules/upload.md +4 -0
- package/core/audit_packs/web-audit/modules/websocket.md +4 -0
- package/core/audit_packs/web-audit/stages/00-scope.md +13 -0
- package/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
- package/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
- package/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
- package/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
- package/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
- package/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
- package/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
- package/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
- package/core/autonomous_cve/INTERFACE.md +61 -0
- package/core/autonomous_cve/README.md +58 -0
- package/core/autonomous_cve/SPEC.md +25 -0
- package/core/autonomous_cve/__init__.py +109 -0
- package/core/autonomous_cve/attack_graph.py +1096 -0
- package/core/autonomous_cve/attack_graph_store.py +1868 -0
- package/core/autonomous_cve/audit_campaign.py +1232 -0
- package/core/autonomous_cve/behavior_graph.py +465 -0
- package/core/autonomous_cve/ghsa_advisories.py +174 -0
- package/core/autonomous_cve/models.py +93 -0
- package/core/autonomous_cve/mutator.py +87 -0
- package/core/autonomous_cve/patcher.py +126 -0
- package/core/autonomous_cve/scout.py +278 -0
- package/core/autonomous_cve/synthesizer.py +207 -0
- package/core/autonomous_cve/verifier.py +103 -0
- package/core/bugx.md +1299 -0
- package/core/bugx_paths.py +1881 -0
- package/core/cli-help.txt +66 -0
- package/core/cloud_sync/INTERFACE.md +32 -0
- package/core/cloud_sync/README.md +62 -0
- package/core/cloud_sync/SPEC.md +25 -0
- package/core/cloud_sync/__init__.py +23 -0
- package/core/cloud_sync/auto_sync.py +398 -0
- package/core/cloud_sync/cloud_client.py +1218 -0
- package/core/cloud_sync/cloud_onboard.py +743 -0
- package/core/cloud_sync/cloud_schema.py +648 -0
- package/core/cloud_sync/consent.py +81 -0
- package/core/cloud_sync/device_identity.py +307 -0
- package/core/cloud_sync/endpoint_router.py +415 -0
- package/core/cloud_sync/flywheel_client.py +769 -0
- package/core/cloud_sync/network_transport.py +296 -0
- package/core/cloud_sync/onboard_wizard.py +493 -0
- package/core/cloud_sync/sensitive_filter.py +285 -0
- package/core/cloud_sync/sync_pull.py +695 -0
- package/core/cloud_sync/sync_push.py +723 -0
- package/core/contracts/AGENT_GUIDE.md +359 -0
- package/core/contracts/README.md +34 -0
- package/core/contracts/bugx-blackbox.md +541 -0
- package/core/contracts/bugx-opencode.md +469 -0
- package/core/contracts/bugx-quick.md +44 -0
- package/core/contracts/bugx-runtime-contract.md +353 -0
- package/core/contracts/bugx-worker.md +470 -0
- package/core/contracts/engine_gap_contracts.py +473 -0
- package/core/coverage/README.md +70 -0
- package/core/coverage/__init__.py +106 -0
- package/core/coverage/coverage_ai_review.py +185 -0
- package/core/coverage/coverage_backfill.py +54 -0
- package/core/coverage/coverage_bootstrap.py +713 -0
- package/core/coverage/coverage_business.py +36 -0
- package/core/coverage/coverage_cli.py +715 -0
- package/core/coverage/coverage_discovery.py +1429 -0
- package/core/coverage/coverage_evidence.py +1024 -0
- package/core/coverage/coverage_forensics.py +124 -0
- package/core/coverage/coverage_gate.py +277 -0
- package/core/coverage/coverage_intelligence.py +734 -0
- package/core/coverage/coverage_manifest.py +396 -0
- package/core/coverage/coverage_platform.py +77 -0
- package/core/coverage/coverage_validate.py +241 -0
- package/core/coverage/module_coverage.py +157 -0
- package/core/dev_harness/INTERFACE.md +20 -0
- package/core/dev_harness/README.md +21 -0
- package/core/dev_harness/SPEC.md +25 -0
- package/core/dev_harness/__init__.py +5 -0
- package/core/dev_harness/interaction_preset.py +408 -0
- package/core/engine-integrity.json +2797 -0
- package/core/fuzzing/README.md +49 -0
- package/core/fuzzing/__init__.py +82 -0
- package/core/fuzzing/concurrency_fuzzer.py +435 -0
- package/core/fuzzing/differential_oracle.py +1164 -0
- package/core/fuzzing/fuzz_input.py +1291 -0
- package/core/fuzzing/stateful_fuzzer.py +404 -0
- package/core/governance/README.md +61 -0
- package/core/governance/__init__.py +130 -0
- package/core/governance/capacity_planner.py +124 -0
- package/core/governance/dependency_lock.py +317 -0
- package/core/governance/goal_governor.py +754 -0
- package/core/governance/guide_budget.py +458 -0
- package/core/governance/lockdown.sh +50 -0
- package/core/governance/readonly_enforcer.py +154 -0
- package/core/governance/runtime_tool_gate.py +373 -0
- package/core/governance/secret_redactor.py +784 -0
- package/core/governance/token_budget.py +38 -0
- package/core/host_acp/INTERFACE.md +36 -0
- package/core/host_acp/README.md +51 -0
- package/core/host_acp/SPEC.md +25 -0
- package/core/host_acp/__init__.py +121 -0
- package/core/host_acp/base.py +111 -0
- package/core/host_acp/claude.py +99 -0
- package/core/host_acp/cline.py +298 -0
- package/core/host_acp/codex.py +300 -0
- package/core/host_acp/dsh.py +106 -0
- package/core/host_acp/opencode.py +209 -0
- package/core/host_acp/pi.py +94 -0
- package/core/host_acp/zcode.py +99 -0
- package/core/host_runtime/INTERFACE.md +24 -0
- package/core/host_runtime/README.md +62 -0
- package/core/host_runtime/SPEC.md +25 -0
- package/core/host_runtime/__init__.py +21 -0
- package/core/host_runtime/adapters.py +412 -0
- package/core/host_runtime/autonomous_runner.py +1152 -0
- package/core/host_runtime/cline.py +448 -0
- package/core/host_runtime/common.py +103 -0
- package/core/host_runtime/free_models.py +786 -0
- package/core/host_runtime/host_bootstrap.py +389 -0
- package/core/host_runtime/host_evaluators.py +761 -0
- package/core/host_runtime/host_probe.py +41 -0
- package/core/host_runtime/host_provider_arbitrator.py +831 -0
- package/core/host_runtime/host_registry.py +662 -0
- package/core/host_runtime/host_usage.py +127 -0
- package/core/host_runtime/mcp_process_tracker.py +509 -0
- package/core/host_runtime/mcp_registry_gate.py +379 -0
- package/core/host_runtime/pi.py +102 -0
- package/core/host_runtime/provider_facts.py +66 -0
- package/core/hosts/INTERFACE.md +51 -0
- package/core/hosts/README.md +67 -0
- package/core/hosts/SPEC.md +25 -0
- package/core/hosts/__init__.py +140 -0
- package/core/hosts/_base_usage.py +152 -0
- package/core/hosts/_codex_usage.py +297 -0
- package/core/hosts/_dsh_usage.py +184 -0
- package/core/hosts/_mcp_toml.py +365 -0
- package/core/hosts/_zcode_usage.py +269 -0
- package/core/hosts/base.py +479 -0
- package/core/hosts/claude.py +212 -0
- package/core/hosts/cline.py +229 -0
- package/core/hosts/codex.py +1006 -0
- package/core/hosts/dsh.py +526 -0
- package/core/hosts/opencode.py +358 -0
- package/core/hosts/pi.py +308 -0
- package/core/hosts/zcode.py +219 -0
- package/core/i18n.py +252 -0
- package/core/infra/README.md +41 -0
- package/core/infra/__init__.py +17 -0
- package/core/infra/build_info.py +105 -0
- package/core/infra/client_metadata.py +185 -0
- package/core/infra/json_utils.py +22 -0
- package/core/infra/python_runtime.py +540 -0
- package/core/infra/safe_xml.py +221 -0
- package/core/launch_bugx.py +118 -0
- package/core/launch_phases/INTERFACE.md +31 -0
- package/core/launch_phases/README.md +106 -0
- package/core/launch_phases/SPEC.md +25 -0
- package/core/launch_phases/__init__.py +29 -0
- package/core/launch_phases/candidate_revalidation.py +484 -0
- package/core/launch_phases/common.py +1060 -0
- package/core/launch_phases/finding_confirm_phase.py +391 -0
- package/core/launch_phases/finding_settlement.py +1432 -0
- package/core/launch_phases/findings_adjudication.py +666 -0
- package/core/launch_phases/findings_snapshot.py +357 -0
- package/core/launch_phases/judge_phase.py +848 -0
- package/core/launch_phases/lesson_context.py +536 -0
- package/core/launch_phases/lifecycle_reporter.py +627 -0
- package/core/launch_phases/orchestrator_controls.py +686 -0
- package/core/launch_phases/post_commit.py +567 -0
- package/core/launch_phases/post_coverage_sync.py +598 -0
- package/core/launch_phases/post_dry_run.py +817 -0
- package/core/launch_phases/post_observability.py +367 -0
- package/core/launch_phases/post_phase.py +1223 -0
- package/core/launch_phases/post_receipt.py +373 -0
- package/core/launch_phases/post_round_lifecycle.py +786 -0
- package/core/launch_phases/pre_phase.py +1029 -0
- package/core/launch_phases/pre_recon_scout.py +879 -0
- package/core/launch_phases/pre_state_builder.py +1133 -0
- package/core/launch_phases/report_sharing.py +414 -0
- package/core/launch_phases/round_orchestrator.py +1116 -0
- package/core/launch_phases/session_runtime.py +1670 -0
- package/core/launch_phases/startup_gates.py +1050 -0
- package/core/launch_phases/startup_interaction.py +1003 -0
- package/core/launch_phases/startup_version_gate.py +879 -0
- package/core/launch_phases/supervisor_bridge.py +1253 -0
- package/core/launch_phases/supervisor_coverage.py +423 -0
- package/core/launch_phases/supervisor_degraded.py +1211 -0
- package/core/launch_phases/worker_barriers.py +424 -0
- package/core/launch_phases/worker_orchestrator.py +1246 -0
- package/core/launch_phases/worker_prior.py +749 -0
- package/core/ledger/INTERFACE.md +35 -0
- package/core/ledger/README.md +160 -0
- package/core/ledger/SPEC.md +25 -0
- package/core/ledger/__init__.py +67 -0
- package/core/ledger/_facade.py +227 -0
- package/core/ledger/archive_ops.py +630 -0
- package/core/ledger/auto_materialization.py +459 -0
- package/core/ledger/bug-log.md +22 -0
- package/core/ledger/cli.py +275 -0
- package/core/ledger/export_ops.py +554 -0
- package/core/ledger/finding_confirmation.py +1316 -0
- package/core/ledger/finding_io.py +299 -0
- package/core/ledger/finding_lifecycle.py +730 -0
- package/core/ledger/finding_verification.py +405 -0
- package/core/ledger/incidents.py +1005 -0
- package/core/ledger/lesson-replay-cases.json +20 -0
- package/core/ledger/lesson_ledger.py +241 -0
- package/core/ledger/lesson_replay.py +272 -0
- package/core/ledger/life_ledger.py +668 -0
- package/core/ledger/mistake-book.md +130 -0
- package/core/ledger/patterns.py +684 -0
- package/core/ledger/receipt_contract.py +269 -0
- package/core/ledger/schema.py +1192 -0
- package/core/ledger/sync_ops.py +940 -0
- package/core/ledger/tool_experience.py +683 -0
- package/core/ledger/verify_life.py +1597 -0
- package/core/lesson-ledger.json +275 -0
- package/core/locales/README.md +19 -0
- package/core/locales/en-US.json +462 -0
- package/core/locales/zh-CN.json +462 -0
- package/core/mcp_handlers/INTERFACE.md +75 -0
- package/core/mcp_handlers/README.md +62 -0
- package/core/mcp_handlers/SPEC.md +25 -0
- package/core/mcp_handlers/__init__.py +128 -0
- package/core/mcp_handlers/base.py +717 -0
- package/core/mcp_handlers/channel_lifecycle.py +751 -0
- package/core/mcp_handlers/graph_handlers.py +222 -0
- package/core/mcp_handlers/knowledge_handlers.py +536 -0
- package/core/mcp_handlers/mining_handlers.py +586 -0
- package/core/mcp_handlers/resource_prompt_table.py +116 -0
- package/core/mcp_handlers/retrieval_handlers.py +249 -0
- package/core/mcp_handlers/rpc_server.py +470 -0
- package/core/mcp_handlers/supervisor_handlers.py +1461 -0
- package/core/mcp_handlers/telemetry_handlers.py +227 -0
- package/core/mcp_handlers/tool_table.py +1030 -0
- package/core/mcp_runtime_support/README.md +21 -0
- package/core/mcp_runtime_support/__init__.py +1 -0
- package/core/mcp_runtime_support/common.py +363 -0
- package/core/mcp_runtime_support/environment.py +567 -0
- package/core/mcp_runtime_support/verifier.py +758 -0
- package/core/metadata.txt +4 -0
- package/core/planning/README.md +157 -0
- package/core/planning/__init__.py +242 -0
- package/core/planning/capability_plan.py +187 -0
- package/core/planning/capability_planner.py +195 -0
- package/core/planning/domain_archetype.py +542 -0
- package/core/planning/domain_router.py +269 -0
- package/core/planning/dynamic_flow_analyzer.py +533 -0
- package/core/planning/impact_pruner.py +435 -0
- package/core/planning/intent_adjudicator.py +175 -0
- package/core/planning/judge_pipeline.py +1246 -0
- package/core/planning/logic_analysis.py +419 -0
- package/core/planning/prompt_harness.py +1704 -0
- package/core/planning/source_inspector.py +267 -0
- package/core/planning/spec_harvester.py +449 -0
- package/core/planning/target_sandbox_manager.py +573 -0
- package/core/planning/test_capability_verifier.py +1364 -0
- package/core/planning/tools-kb.md +38 -0
- package/core/planning/unit_kind.py +122 -0
- package/core/probes/INTERFACE.md +83 -0
- package/core/probes/README.md +51 -0
- package/core/probes/SPEC.md +36 -0
- package/core/probes/__init__.py +76 -0
- package/core/probes/android_probe.py +552 -0
- package/core/probes/base.py +147 -0
- package/core/probes/codebase_memory_probe.py +647 -0
- package/core/probes/desktop_probe.py +342 -0
- package/core/probes/differential_probe.py +434 -0
- package/core/probes/efficiency_probe.py +232 -0
- package/core/probes/ios_binary_probe.py +472 -0
- package/core/probes/memory_probe.py +392 -0
- package/core/probes/miniprogram_probe.py +385 -0
- package/core/probes/mobile_probe.py +466 -0
- package/core/probes/native_probe.py +302 -0
- package/core/probes/openwiki_probe.py +263 -0
- package/core/probes/pattern_probe.py +453 -0
- package/core/probes/platform_probe.py +424 -0
- package/core/probes/probe_registry.py +1770 -0
- package/core/probes/sast_fixture_corpus.py +340 -0
- package/core/probes/sast_probe.py +1510 -0
- package/core/probes/sast_rules.py +1481 -0
- package/core/probes/sca_scanner.py +779 -0
- package/core/probes/ui_accessibility.py +149 -0
- package/core/probes/ui_audit.py +513 -0
- package/core/probes/ui_contract.py +273 -0
- package/core/probes/ui_evidence.py +212 -0
- package/core/probes/ui_measurements.py +314 -0
- package/core/probes/ui_repair.py +250 -0
- package/core/probes/ui_review.py +133 -0
- package/core/probes/ui_storybook.py +107 -0
- package/core/probes/ui_tokens.py +185 -0
- package/core/probes/ui_visual_diff.py +131 -0
- package/core/probes/web_probe.py +714 -0
- package/core/project_profiler/INTERFACE.md +62 -0
- package/core/project_profiler/README.md +53 -0
- package/core/project_profiler/SPEC.md +28 -0
- package/core/project_profiler/__init__.py +201 -0
- package/core/project_profiler/arbitrator.py +316 -0
- package/core/project_profiler/constants.py +247 -0
- package/core/project_profiler/detector.py +399 -0
- package/core/project_profiler/extractors.py +836 -0
- package/core/project_profiler/fingerprint.py +116 -0
- package/core/project_profiler/storage.py +258 -0
- package/core/project_profiler/strategy.py +301 -0
- package/core/prompts/README.md +35 -0
- package/core/prompts/codex_dialog_dispatch.md +9 -0
- package/core/prompts/command_routing_en.md +42 -0
- package/core/prompts/command_routing_zh.md +42 -0
- package/core/prompts/l0_router.md +47 -0
- package/core/prompts/rules/anti_patterns.md +16 -0
- package/core/prompts/rules/concurrency_rules.md +14 -0
- package/core/prompts/rules/memory_leak_rules.md +13 -0
- package/core/prompts/rules/prompt_injection_defense.md +13 -0
- package/core/prompts/stages/stage_explore.md +31 -0
- package/core/prompts/stages/stage_gate.md +43 -0
- package/core/prompts/stages/stage_mutate.md +42 -0
- package/core/prompts/stages/stage_repair.md +85 -0
- package/core/repair/README.md +74 -0
- package/core/repair/__init__.py +169 -0
- package/core/repair/fix_watchlist.py +391 -0
- package/core/repair/l7_dynamic.py +418 -0
- package/core/repair/l7_repair_loop.py +462 -0
- package/core/repair/l7_selfcheck.py +862 -0
- package/core/repair/minimize_repro.py +466 -0
- package/core/repair/patch_synthesizer.py +617 -0
- package/core/repair/regression_pack.py +379 -0
- package/core/repair/rsi_fixer.py +910 -0
- package/core/repair/rsi_loop.py +311 -0
- package/core/repair/rsi_repair.py +348 -0
- package/core/repair/rsi_rounds.py +212 -0
- package/core/repair/rsi_scope.py +281 -0
- package/core/repair/self_heal.py +604 -0
- package/core/repair/test_generator.py +1108 -0
- package/core/repair/test_quality_auditor.py +410 -0
- package/core/repair/test_strategy.py +511 -0
- package/core/report_engine/INTERFACE.md +59 -0
- package/core/report_engine/README.md +69 -0
- package/core/report_engine/SPEC.md +28 -0
- package/core/report_engine/__init__.py +47 -0
- package/core/report_engine/attestation.py +228 -0
- package/core/report_engine/authority.py +255 -0
- package/core/report_engine/finding_report.py +418 -0
- package/core/report_engine/formal_report_builder.py +924 -0
- package/core/report_engine/html_renderers.py +696 -0
- package/core/report_engine/models.py +759 -0
- package/core/report_engine/pdf_exporter.py +231 -0
- package/core/report_engine/projects_assets.py +730 -0
- package/core/report_engine/report_client.py +743 -0
- package/core/report_engine/report_data_builder.py +388 -0
- package/core/report_engine/report_share.py +459 -0
- package/core/report_engine/sast_bridge.py +116 -0
- package/core/report_engine/server.py +832 -0
- package/core/report_engine/visual_report_builder.py +796 -0
- package/core/report_engine/web-conformance.md +168 -0
- package/core/report_engine/web_conformance.py +428 -0
- package/core/report_engine/workbench_assets.py +484 -0
- package/core/retrieval/INTERFACE.md +20 -0
- package/core/retrieval/README.md +161 -0
- package/core/retrieval/SPEC.md +25 -0
- package/core/retrieval/__init__.py +3 -0
- package/core/retrieval/code_analyzer.py +1720 -0
- package/core/retrieval/codebase_memory_bridge.py +337 -0
- package/core/retrieval/context_assembler.py +240 -0
- package/core/retrieval/corpus_fetch.py +369 -0
- package/core/retrieval/graph_ego.py +597 -0
- package/core/retrieval/knowledge_auto.py +662 -0
- package/core/retrieval/knowledge_sources.py +168 -0
- package/core/retrieval/knowledge_sync.py +1003 -0
- package/core/retrieval/memory_store.py +480 -0
- package/core/retrieval/query_planner.py +1020 -0
- package/core/retrieval/rrf_engine.py +137 -0
- package/core/retrieval/slice_extractor.py +1209 -0
- package/core/retrieval/slice_normalizer.py +373 -0
- package/core/retrieval/slice_spec.py +357 -0
- package/core/retrieval/symbol_index.py +1151 -0
- package/core/retrieval/universal_code_matcher.py +622 -0
- package/core/retrieval/xerj_bridge.py +476 -0
- package/core/retrieval/xerj_supervisor.py +362 -0
- package/core/rules/README.md +33 -0
- package/core/rules/ios/PROVENANCE.json +30 -0
- package/core/rules/ios/crypto.yaml +36 -0
- package/core/rules/ios/network.yaml +20 -0
- package/core/rules/ios/resilience.yaml +47 -0
- package/core/rules/ios/storage.yaml +48 -0
- package/core/rules/mastg/LICENSE +173 -0
- package/core/rules/mastg/PROVENANCE.json +270 -0
- package/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
- package/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
- package/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
- package/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
- package/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
- package/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
- package/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
- package/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
- package/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
- package/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
- package/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
- package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
- package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
- package/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
- package/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
- package/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
- package/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
- package/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
- package/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
- package/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
- package/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
- package/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
- package/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
- package/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
- package/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
- package/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
- package/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
- package/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
- package/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
- package/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
- package/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
- package/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
- package/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
- package/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
- package/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
- package/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
- package/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
- package/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
- package/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
- package/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
- package/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
- package/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
- package/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
- package/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
- package/core/rules/mastg/mastg-android-strictmode.yml +10 -0
- package/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
- package/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
- package/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
- package/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
- package/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
- package/core/rules/miniprogram/PROVENANCE.json +26 -0
- package/core/rules/miniprogram/network.yaml +37 -0
- package/core/rules/miniprogram/platform.yaml +36 -0
- package/core/rules/miniprogram/storage.yaml +48 -0
- package/core/rules/mobsfscan-swift/LICENSE +165 -0
- package/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
- package/core/rules/mobsfscan-swift/auth.yaml +59 -0
- package/core/rules/mobsfscan-swift/crypto.yaml +66 -0
- package/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
- package/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
- package/core/rules/mobsfscan-swift/logging.yaml +23 -0
- package/core/rules/mobsfscan-swift/network.yaml +55 -0
- package/core/rules/mobsfscan-swift/resilience.yaml +29 -0
- package/core/rules/mobsfscan-swift/secrets.yaml +33 -0
- package/core/rules/mobsfscan-swift/storage.yaml +29 -0
- package/core/rules/mobsfscan-swift/webview.yaml +32 -0
- package/core/runtime/README.md +198 -0
- package/core/runtime/__init__.py +3 -0
- package/core/runtime/bugx_logging.py +1464 -0
- package/core/runtime/daemon_runner.py +623 -0
- package/core/runtime/fixture_solidify.py +444 -0
- package/core/runtime/global_telemetry.py +549 -0
- package/core/runtime/incident_eval.py +148 -0
- package/core/runtime/interaction.py +605 -0
- package/core/runtime/interaction_store.py +435 -0
- package/core/runtime/interactive_menu.py +95 -0
- package/core/runtime/log_analytics.py +922 -0
- package/core/runtime/mining_quality_framework.py +1387 -0
- package/core/runtime/model_runner.py +732 -0
- package/core/runtime/platform_adapter.py +579 -0
- package/core/runtime/prep_validate.py +478 -0
- package/core/runtime/project_graph.py +827 -0
- package/core/runtime/project_init.py +481 -0
- package/core/runtime/project_profile.py +224 -0
- package/core/runtime/project_settings.py +964 -0
- package/core/runtime/provider_window.py +97 -0
- package/core/runtime/resume_ticket.py +115 -0
- package/core/runtime/scenario_eval.py +856 -0
- package/core/runtime/seed_drill.py +549 -0
- package/core/runtime/self_audit.py +550 -0
- package/core/runtime/session_profile.py +205 -0
- package/core/runtime/setup_ui_env.py +229 -0
- package/core/runtime/startup_environment.py +859 -0
- package/core/runtime/sync_store.py +1421 -0
- package/core/runtime/tool_install_targets.py +18 -0
- package/core/schemas/README.md +35 -0
- package/core/schemas/agent-graph.schema.json +368 -0
- package/core/schemas/attack-graph.schema.json +88 -0
- package/core/schemas/evidence-bundle.schema.json +33 -0
- package/core/schemas/skill-pack.schema.json +230 -0
- package/core/schemas/worker-checkpoint.schema.json +119 -0
- package/core/secure_atomic.py +289 -0
- package/core/seed_corpus/README.md +55 -0
- package/core/seed_corpus/c.txt +29 -0
- package/core/seed_corpus/cpp.txt +32 -0
- package/core/seed_corpus/css.txt +70 -0
- package/core/seed_corpus/go.txt +46 -0
- package/core/seed_corpus/java.txt +30 -0
- package/core/seed_corpus/javascript.txt +55 -0
- package/core/seed_corpus/kotlin.txt +28 -0
- package/core/seed_corpus/python.txt +71 -0
- package/core/seed_corpus/rust.txt +53 -0
- package/core/seed_corpus/swift.txt +29 -0
- package/core/seed_corpus/typescript.txt +29 -0
- package/core/skills/README.md +53 -0
- package/core/skills/__init__.py +189 -0
- package/core/skills/bugx_docs_mcp_server.py +418 -0
- package/core/skills/bugx_mcp_server.py +1161 -0
- package/core/skills/mcp_runtime.py +968 -0
- package/core/skills/mcp_session_proof.py +605 -0
- package/core/skills/mobile_ui_inspector.py +405 -0
- package/core/skills/skill_pack.py +1214 -0
- package/core/skills/skill_synthesizer.py +1153 -0
- package/core/skills/tools_kb.py +313 -0
- package/core/supervisor/INTERFACE.md +121 -0
- package/core/supervisor/README.md +209 -0
- package/core/supervisor/SPEC.md +25 -0
- package/core/supervisor/__init__.py +175 -0
- package/core/supervisor/audit_supervisor.py +1015 -0
- package/core/supervisor/budget_governor.py +1254 -0
- package/core/supervisor/checkpoint_handler.py +368 -0
- package/core/supervisor/checkpoint_pipeline.py +1564 -0
- package/core/supervisor/checkpoint_sync.py +653 -0
- package/core/supervisor/claim_events.py +74 -0
- package/core/supervisor/claim_sync.py +590 -0
- package/core/supervisor/cli.py +812 -0
- package/core/supervisor/context_sync.py +55 -0
- package/core/supervisor/coverage_sync.py +115 -0
- package/core/supervisor/finding_commit.py +470 -0
- package/core/supervisor/finding_sync.py +688 -0
- package/core/supervisor/finding_workflow.py +676 -0
- package/core/supervisor/finish_policy.py +224 -0
- package/core/supervisor/finish_sync.py +185 -0
- package/core/supervisor/graph_sync.py +669 -0
- package/core/supervisor/lease_manager.py +788 -0
- package/core/supervisor/lifecycle_blocks.py +129 -0
- package/core/supervisor/next_round_sync.py +126 -0
- package/core/supervisor/observability.py +140 -0
- package/core/supervisor/recovery_sync.py +165 -0
- package/core/supervisor/rejection_remedies.py +355 -0
- package/core/supervisor/round_governor.py +306 -0
- package/core/supervisor/serial_authorization.py +544 -0
- package/core/supervisor/start_sync.py +87 -0
- package/core/supervisor/state_store.py +249 -0
- package/core/supervisor/supervisor_host.py +511 -0
- package/core/supervisor/supervisor_models.py +1143 -0
- package/core/supervisor/systemic_failure.py +104 -0
- package/core/supervisor/task_scheduler.py +1640 -0
- package/core/supervisor/worker_checkpoint.py +230 -0
- package/core/supervisor/worker_execution.py +265 -0
- package/core/supervisor/worker_handoff.py +192 -0
- package/core/supervisor/worker_lifecycle.py +396 -0
- package/core/supervisor/worker_runtime.py +1005 -0
- package/core/supervisor/worker_sync.py +89 -0
- package/core/supervisor_types/README.md +36 -0
- package/core/supervisor_types/__init__.py +0 -0
- package/core/supervisor_types/exceptions.py +52 -0
- package/core/supervisor_types/graph_models.py +357 -0
- package/core/supervisor_types/path_containment.py +151 -0
- package/core/supervisor_types/target_fingerprint.py +310 -0
- package/core/supervisor_types/worker_claim.py +411 -0
- package/core/webui/INTERFACE.md +50 -0
- package/core/webui/README.md +57 -0
- package/core/webui/SPEC.md +26 -0
- package/core/webui/__init__.py +11 -0
- package/core/webui/adapters/__init__.py +27 -0
- package/core/webui/adapters/base.py +87 -0
- package/core/webui/adapters/bugx.py +102 -0
- package/core/webui/adapters/claude.py +222 -0
- package/core/webui/adapters/cline.py +407 -0
- package/core/webui/adapters/codex.py +260 -0
- package/core/webui/adapters/dsh.py +177 -0
- package/core/webui/adapters/opencode.py +218 -0
- package/core/webui/adapters/pi.py +272 -0
- package/core/webui/adapters/registry.py +100 -0
- package/core/webui/adapters/zcode.py +312 -0
- package/core/webui/api_routes_post.py +668 -0
- package/core/webui/dispatcher.py +1376 -0
- package/core/webui/docs_session_service.py +473 -0
- package/core/webui/handler.py +674 -0
- package/core/webui/ide_cloud_service.py +526 -0
- package/core/webui/mcp_inspector.py +1747 -0
- package/core/webui/static/00-base.css +1060 -0
- package/core/webui/static/01-monitoring.css +802 -0
- package/core/webui/static/02-header-actions.css +321 -0
- package/core/webui/static/03-trigger-popover.css +697 -0
- package/core/webui/static/04-composer.css +628 -0
- package/core/webui/static/05-skills-center.css +878 -0
- package/core/webui/static/06-mcp-center.css +623 -0
- package/core/webui/static/07-skill-detail.css +265 -0
- package/core/webui/static/08-files-management.css +167 -0
- package/core/webui/static/09-files-center.css +386 -0
- package/core/webui/static/10-icons.css +105 -0
- package/core/webui/static/11-project-options.css +185 -0
- package/core/webui/static/12-profile-tab.css +383 -0
- package/core/webui/static/assets/index-CXAsl8mr.js +333 -0
- package/core/webui/static/assets/index-DHQUtWtx.css +1 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
- package/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
- package/core/webui/static/design-tokens.css +113 -0
- package/core/webui/static/favicon.png +0 -0
- package/core/webui/static/icon-192.png +0 -0
- package/core/webui/static/index.html +55 -0
- package/core/webui/static/manifest.webmanifest +19 -0
- package/core/webui/static/project-settings.js +9602 -0
- package/core/webui/static/sw.js +8 -0
- package/core/webui/workspace_service.py +218 -0
- package/docs/07_distribution/01_README_NPM.md +285 -0
- package/ecosystem/README.md +129 -0
- package/ecosystem/integrations/README.md +38 -0
- package/ecosystem/integrations/cline/skills/bugx/SKILL.md +69 -0
- package/ecosystem/integrations/dsh/agents/bugx.md +27 -0
- package/ecosystem/integrations/dsh/dsh-patch.yml +18 -0
- package/ecosystem/integrations/dsh/mcp/cordis.patch.yml +4 -0
- package/ecosystem/integrations/dsh/mcp/index.js +219 -0
- package/ecosystem/integrations/dsh/mcp/package.json +28 -0
- package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +70 -0
- package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +229 -0
- package/ecosystem/integrations/dsh/ui/client.js +87 -0
- package/ecosystem/integrations/dsh/ui/cordis.patch.yml +4 -0
- package/ecosystem/integrations/dsh/ui/index.js +7 -0
- package/ecosystem/integrations/dsh/ui/package.json +27 -0
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +53 -0
- package/ecosystem/integrations/opencode/mcp-lock.json +3075 -0
- package/ecosystem/integrations/opencode/opencode.json +129 -0
- package/ecosystem/integrations/pi/extensions/bugx/README.md +12 -0
- package/ecosystem/integrations/pi/extensions/bugx/index.ts +299 -0
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +11 -0
- package/ecosystem/integrations/pi/skills/bugx/SKILL.md +69 -0
- package/ecosystem/integrations/qoder/CONNECTORS.md +54 -0
- package/ecosystem/integrations/qoder/connector-meta.json +21 -0
- package/ecosystem/integrations/workbuddy/connector-meta.json +19 -0
- package/ecosystem/integrations/workbuddy/icon.png +0 -0
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +70 -0
- package/ecosystem/plugins/README.md +37 -0
- package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +17 -0
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +16 -0
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +41 -0
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +19 -0
- package/ecosystem/plugins/bugx/agents/bugx-judge.md +71 -0
- package/ecosystem/plugins/bugx/agents/bugx-worker.md +31 -0
- package/ecosystem/plugins/bugx/agents/bugx.md +74 -0
- package/ecosystem/plugins/bugx/assets/bugx-avatar-512.png +0 -0
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +118 -0
- package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
- package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +229 -0
- package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
- package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
- package/interfaces/bin/bugx.js +117 -0
- package/interfaces/cli/bugx_cli/__init__.py +6 -0
- package/interfaces/cli/bugx_cli/cli.py +1685 -0
- package/interfaces/cli/bugx_cli/commands/__init__.py +1 -0
- package/interfaces/cli/bugx_cli/commands/advisory.py +94 -0
- package/interfaces/cli/bugx_cli/commands/agent.py +4210 -0
- package/interfaces/cli/bugx_cli/commands/audit.py +632 -0
- package/interfaces/cli/bugx_cli/commands/autonomous.py +260 -0
- package/interfaces/cli/bugx_cli/commands/cloud.py +1371 -0
- package/interfaces/cli/bugx_cli/commands/daemon.py +50 -0
- package/interfaces/cli/bugx_cli/commands/doctor.py +1590 -0
- package/interfaces/cli/bugx_cli/commands/goal.py +107 -0
- package/interfaces/cli/bugx_cli/commands/interaction.py +248 -0
- package/interfaces/cli/bugx_cli/commands/knowledge.py +619 -0
- package/interfaces/cli/bugx_cli/commands/lifecycle.py +2763 -0
- package/interfaces/cli/bugx_cli/commands/patch.py +1014 -0
- package/interfaces/cli/bugx_cli/commands/plugin.py +2749 -0
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +1446 -0
- package/interfaces/cli/bugx_cli/commands/plugin_cline.py +269 -0
- package/interfaces/cli/bugx_cli/commands/plugin_codex.py +74 -0
- package/interfaces/cli/bugx_cli/commands/plugin_funide.py +729 -0
- package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +216 -0
- package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +710 -0
- package/interfaces/cli/bugx_cli/commands/project.py +670 -0
- package/interfaces/cli/bugx_cli/commands/report.py +256 -0
- package/interfaces/cli/bugx_cli/commands/skill.py +251 -0
- package/interfaces/cli/bugx_cli/commands/stats.py +133 -0
- package/interfaces/cli/bugx_cli/commands/system.py +2567 -0
- package/interfaces/cli/bugx_cli/common.py +906 -0
- package/interfaces/cli/bugx_cli/host_adapters.py +1892 -0
- package/interfaces/cli/bugx_cli/hosts/__init__.py +80 -0
- package/interfaces/cli/bugx_cli/hosts/base.py +99 -0
- package/interfaces/cli/bugx_cli/hosts/registry.py +573 -0
- package/interfaces/cli/bugx_cli/hosts/template_engine.py +188 -0
- package/interfaces/cli/bugx_cli/infra/__init__.py +209 -0
- package/interfaces/cli/bugx_cli/infra/ai_advisor.py +851 -0
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +1945 -0
- package/interfaces/cli/bugx_cli/infra/host_sync.py +548 -0
- package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +826 -0
- package/interfaces/cli/bugx_cli/infra/security.py +339 -0
- package/package.json +99 -4
- package/pyproject.toml +258 -0
- package/scripts/ensure-python.mjs +97 -0
- package/scripts/isolate-npm-readme.mjs +40 -0
- package/scripts/runtime.lock.json +31 -0
- package/scripts/sync-version.mjs +26 -0
- package/scripts/test-npm-wrapper.mjs +265 -0
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""core/ledger/archive_ops.py - FTS 审计重建与事件分段归档 (DOC-036)。"""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import datetime as dt
|
|
7
|
+
import hashlib
|
|
8
|
+
import gzip
|
|
9
|
+
import io
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import sqlite3
|
|
13
|
+
import tempfile
|
|
14
|
+
import time
|
|
15
|
+
import zlib
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Mapping
|
|
18
|
+
|
|
19
|
+
import sys
|
|
20
|
+
|
|
21
|
+
#: 归档段**压缩**体积上限。gzip 压缩比可超过 1000x,几 KB 的炸弹就能膨胀到
|
|
22
|
+
#: 数十 GB,因此压缩侧与解压侧都必须设限(SEC-08)。
|
|
23
|
+
MAX_SEGMENT_BYTES = 64 * 1024 * 1024
|
|
24
|
+
#: 归档段**解压后**累计字节上限。
|
|
25
|
+
MAX_SEGMENT_INFLATED_BYTES = 256 * 1024 * 1024
|
|
26
|
+
#: 分块解压的块大小。
|
|
27
|
+
_SEGMENT_CHUNK_BYTES = 1 << 20
|
|
28
|
+
|
|
29
|
+
# DES-02:原先这里的 ``_LedgerProxy`` 经 ``sys.modules.get("lesson_ledger")``
|
|
30
|
+
# 反向取符号,与顶层 Facade 构成双向依赖环;现改为经同级解析表
|
|
31
|
+
# (``core/ledger/_facade.py``)取**定义该符号的兄弟模块**,且延迟导入,
|
|
32
|
+
# 因此 ``ledger/*`` 不再依赖 ``lesson_ledger``,方向变为单向。
|
|
33
|
+
from core.ledger._facade import LedgerProxy
|
|
34
|
+
|
|
35
|
+
_ledger = LedgerProxy()
|
|
36
|
+
# _ledger.SCHEMA_VERSION delegates to _ledger.SCHEMA_VERSION
|
|
37
|
+
FTS_COLUMNS = ("pattern_id", "category", "title", "root_cause", "reflection", "probes", "aliases")
|
|
38
|
+
|
|
39
|
+
#: F-134: 归档 root_hash 的**库外只读锚**文件名。root_hash 不能再只与 manifest
|
|
40
|
+
#: 同存 DB meta 由库内两份数据互证;必须另存到与 DB 物理分离的独立文件,
|
|
41
|
+
#: 深度校验以「DB manifest 重算值 vs 库外锚」判定,缺失/损坏一律 fail-closed。
|
|
42
|
+
ARCHIVE_ANCHOR_NAME = ".archive-root.anchor"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _archive_anchor_path(outdir: str | os.PathLike[str]) -> Path:
|
|
46
|
+
return Path(outdir) / ARCHIVE_ANCHOR_NAME
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _write_archive_anchor(anchor: Path, root_hash: str,
|
|
50
|
+
manifest: list[dict[str, Any]]) -> None:
|
|
51
|
+
"""把归档根哈希原子写入库外只读锚(与 SQLite DB 物理分离)。"""
|
|
52
|
+
payload = {
|
|
53
|
+
"archive_root_hash": root_hash,
|
|
54
|
+
"manifest_sha256": hashlib.sha256(_canon(manifest)).hexdigest(),
|
|
55
|
+
}
|
|
56
|
+
blob = json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")
|
|
57
|
+
fd, tmp_name = tempfile.mkstemp(prefix=".anchor-", suffix=".tmp", dir=anchor.parent)
|
|
58
|
+
tmp = Path(tmp_name)
|
|
59
|
+
try:
|
|
60
|
+
with os.fdopen(fd, "wb") as handle:
|
|
61
|
+
handle.write(blob)
|
|
62
|
+
handle.flush()
|
|
63
|
+
os.fsync(handle.fileno())
|
|
64
|
+
os.chmod(tmp, 0o444)
|
|
65
|
+
os.replace(tmp, anchor)
|
|
66
|
+
except BaseException:
|
|
67
|
+
if tmp.is_file():
|
|
68
|
+
tmp.unlink()
|
|
69
|
+
raise
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class _ErrorMeta(type):
|
|
73
|
+
def __instancecheck__(cls, instance):
|
|
74
|
+
return isinstance(instance, _ledger.LessonLedgerError)
|
|
75
|
+
def __subclasscheck__(cls, subclass):
|
|
76
|
+
return issubclass(subclass, _ledger.LessonLedgerError)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class LessonLedgerError(Exception, metaclass=_ErrorMeta):
|
|
80
|
+
def __new__(cls, *args, **kwargs):
|
|
81
|
+
return _ledger.LessonLedgerError(*args, **kwargs)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _tx(*args, **kwargs): return _ledger.ledger_transaction(*args, **kwargs)
|
|
85
|
+
def _conn(*args, **kwargs): return _ledger.connect_ledger(*args, **kwargs)
|
|
86
|
+
def _meta_value(*args, **kwargs): return _ledger.get_meta_value(*args, **kwargs)
|
|
87
|
+
def database_path(*args, **kwargs): return _ledger.database_path(*args, **kwargs)
|
|
88
|
+
def _validate(*args, **kwargs): return _ledger.validate_pattern(*args, **kwargs)
|
|
89
|
+
def _event(*args, **kwargs): return _ledger.record_event(*args, **kwargs)
|
|
90
|
+
def _canon(*args, **kwargs): return _ledger.canonical_bytes(*args, **kwargs)
|
|
91
|
+
def _now(*args, **kwargs): return _ledger.now_iso(*args, **kwargs)
|
|
92
|
+
def _archive_manifest(*args, **kwargs): return _ledger.archive_manifest(*args, **kwargs)
|
|
93
|
+
def _incident_content(*args, **kwargs): return _ledger.incident_content(*args, **kwargs)
|
|
94
|
+
|
|
95
|
+
# ---- DOC-008 TASK-008-012/013:FTS 深度校验与原子重建、event 分段归档 ----
|
|
96
|
+
|
|
97
|
+
def fts_expected_row(c: sqlite3.Connection, key: str) -> list[str] | None:
|
|
98
|
+
row = c.execute(
|
|
99
|
+
"SELECT category,title,root_cause,reflection FROM patterns WHERE pattern_id=?", (key,)
|
|
100
|
+
).fetchone()
|
|
101
|
+
if not row:
|
|
102
|
+
return None
|
|
103
|
+
probes = " ".join(x[0] for x in c.execute(
|
|
104
|
+
"SELECT value FROM probes WHERE pattern_id=? AND kind!='card' ORDER BY ordinal", (key,)))
|
|
105
|
+
aliases = " ".join(x[0] for x in c.execute(
|
|
106
|
+
"SELECT alias FROM aliases WHERE pattern_id=?", (key,)))
|
|
107
|
+
return [key, str(row[0]), str(row[1]), str(row[2]), str(row[3]), probes, aliases]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def fts_audit(c: sqlite3.Connection) -> list[str]:
|
|
111
|
+
"""比对事实表与 FTS 投影,返回 issue 列表(空列表即一致)。
|
|
112
|
+
|
|
113
|
+
覆盖:missing row、orphan row、pattern_id 重复行,以及 category/title/
|
|
114
|
+
root_cause/reflection/probes/aliases 七列投影不一致。
|
|
115
|
+
"""
|
|
116
|
+
try:
|
|
117
|
+
actual_rows = c.execute(
|
|
118
|
+
f"SELECT {','.join(FTS_COLUMNS)} FROM patterns_fts"
|
|
119
|
+
).fetchall()
|
|
120
|
+
except sqlite3.Error as exc:
|
|
121
|
+
return [f"patterns_fts 无法读取: {exc}"]
|
|
122
|
+
issues: list[str] = []
|
|
123
|
+
seen: dict[str, list[list[str]]] = {}
|
|
124
|
+
for row in actual_rows:
|
|
125
|
+
key = str(row[0])
|
|
126
|
+
seen.setdefault(key, []).append(["" if value is None else str(value) for value in row])
|
|
127
|
+
for key, rows in sorted(seen.items()):
|
|
128
|
+
if len(rows) > 1:
|
|
129
|
+
issues.append(f"fts duplicate row: {key}")
|
|
130
|
+
pattern_keys = {str(r[0]) for r in c.execute("SELECT pattern_id FROM patterns")}
|
|
131
|
+
for key in sorted(pattern_keys - set(seen)):
|
|
132
|
+
issues.append(f"fts missing row: {key}")
|
|
133
|
+
for key in sorted(set(seen) - pattern_keys):
|
|
134
|
+
issues.append(f"fts orphan row: {key}")
|
|
135
|
+
for key in sorted(pattern_keys & set(seen)):
|
|
136
|
+
expected = fts_expected_row(c, key)
|
|
137
|
+
if expected is not None and seen[key][0] != expected:
|
|
138
|
+
issues.append(f"fts projection mismatch: {key}")
|
|
139
|
+
return issues
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def rebuild_fts(path: str | os.PathLike[str]) -> dict[str, Any]:
|
|
143
|
+
"""在临时表重建 FTS,逐条生成后原子替换;不改变任何业务语义。
|
|
144
|
+
|
|
145
|
+
重建前后 facts/state_hash 完全不变(FTS 是派生数据,不入 state hash);
|
|
146
|
+
发现过投影损坏时先写 fts-degraded 事件,重建完成写 fts-rebuilt 事件。
|
|
147
|
+
"""
|
|
148
|
+
def go(c):
|
|
149
|
+
issues_before = fts_audit(c)
|
|
150
|
+
backend = "fts5" if _meta_value(c, "fts5") == "1" else "fallback"
|
|
151
|
+
keys = [str(r[0]) for r in c.execute("SELECT pattern_id FROM patterns ORDER BY pattern_id")]
|
|
152
|
+
rebuilt = 0
|
|
153
|
+
c.execute("DROP TABLE IF EXISTS patterns_fts_rebuild")
|
|
154
|
+
try:
|
|
155
|
+
if backend == "fts5":
|
|
156
|
+
c.execute(
|
|
157
|
+
"CREATE VIRTUAL TABLE patterns_fts_rebuild USING fts5("
|
|
158
|
+
"pattern_id UNINDEXED,category,title,root_cause,reflection,probes,aliases)"
|
|
159
|
+
)
|
|
160
|
+
else:
|
|
161
|
+
c.execute(
|
|
162
|
+
"CREATE TABLE patterns_fts_rebuild(pattern_id TEXT PRIMARY KEY,category TEXT,"
|
|
163
|
+
"title TEXT,root_cause TEXT,reflection TEXT,probes TEXT,aliases TEXT)"
|
|
164
|
+
)
|
|
165
|
+
for key in keys:
|
|
166
|
+
row = fts_expected_row(c, key)
|
|
167
|
+
if row is None:
|
|
168
|
+
continue
|
|
169
|
+
c.execute(
|
|
170
|
+
f"INSERT INTO patterns_fts_rebuild VALUES ({','.join('?' * len(FTS_COLUMNS))})",
|
|
171
|
+
row,
|
|
172
|
+
)
|
|
173
|
+
rebuilt += 1
|
|
174
|
+
# 逐条比对临时表结果后才允许替换;比对失败则整个事务回滚。
|
|
175
|
+
for key in keys:
|
|
176
|
+
expected = fts_expected_row(c, key)
|
|
177
|
+
got = c.execute(
|
|
178
|
+
f"SELECT {','.join(FTS_COLUMNS)} FROM patterns_fts_rebuild WHERE pattern_id=?",
|
|
179
|
+
(key,),
|
|
180
|
+
).fetchone()
|
|
181
|
+
actual = ["" if value is None else str(value) for value in got] if got else None
|
|
182
|
+
if expected is not None and actual != expected:
|
|
183
|
+
raise LessonLedgerError(f"FTS 重建逐条比对失败: {key}")
|
|
184
|
+
c.execute("DROP TABLE IF EXISTS patterns_fts")
|
|
185
|
+
c.execute("ALTER TABLE patterns_fts_rebuild RENAME TO patterns_fts")
|
|
186
|
+
finally:
|
|
187
|
+
c.execute("DROP TABLE IF EXISTS patterns_fts_rebuild")
|
|
188
|
+
if issues_before:
|
|
189
|
+
_event(c, "fts-degraded", {"issues": issues_before})
|
|
190
|
+
_event(c, "fts-rebuilt", {
|
|
191
|
+
"backend": backend, "rebuilt_rows": rebuilt,
|
|
192
|
+
"degraded_issues_found": len(issues_before),
|
|
193
|
+
})
|
|
194
|
+
remaining_issues = fts_audit(c)
|
|
195
|
+
if remaining_issues:
|
|
196
|
+
raise LessonLedgerError("FTS 重建后仍不一致: " + "; ".join(remaining_issues))
|
|
197
|
+
return {"status": "rebuilt", "backend": backend, "rebuilt_rows": rebuilt,
|
|
198
|
+
"degraded_issues_found": len(issues_before),
|
|
199
|
+
"issues": issues_before}
|
|
200
|
+
return _tx(path, go)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def event_from_row_values(seq: int, typ: str, at: str, payload_text: str,
|
|
204
|
+
prev_hash: str, hash_value: str) -> dict[str, Any]:
|
|
205
|
+
try:
|
|
206
|
+
payload = json.loads(payload_text)
|
|
207
|
+
except (TypeError, json.JSONDecodeError) as exc:
|
|
208
|
+
raise LessonLedgerError(f"归档事件 payload 不是有效 JSON (seq={seq})") from exc
|
|
209
|
+
event = {"seq": int(seq), "type": typ, "at": at, "payload": payload,
|
|
210
|
+
"prev_hash": prev_hash, "hash": hash_value}
|
|
211
|
+
recomputed = hashlib.sha256(_canon({k: v for k, v in event.items() if k != "hash"})).hexdigest()
|
|
212
|
+
if recomputed != hash_value:
|
|
213
|
+
raise LessonLedgerError(f"归档事件 hash 校验失败 (seq={seq})")
|
|
214
|
+
return event
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _confined_segment(outdir: Path, raw: object) -> Path:
|
|
218
|
+
"""把 manifest 里的 ``segment`` 名解析为 ``outdir`` 内的普通文件。
|
|
219
|
+
|
|
220
|
+
SEC-08:旧实现只做 ``outdir / str(entry.get("segment"))`` 加
|
|
221
|
+
``is_symlink/is_file`` 检查。``outdir / "/etc/passwd"`` 会得到绝对路径、
|
|
222
|
+
``../x`` 会越出目录,两者都能通过旧检查,从而读取 outdir 之外的任意文件。
|
|
223
|
+
这里强制 canonical 前缀约束 + 拒绝绝对路径与 ``..``。
|
|
224
|
+
"""
|
|
225
|
+
if not isinstance(raw, str) or not raw.strip():
|
|
226
|
+
raise LessonLedgerError(f"归档段名无效: {raw!r}")
|
|
227
|
+
name = raw.strip()
|
|
228
|
+
candidate = Path(name)
|
|
229
|
+
if candidate.is_absolute() or ".." in candidate.parts:
|
|
230
|
+
raise LessonLedgerError(f"归档段路径越界: {name}")
|
|
231
|
+
try:
|
|
232
|
+
base = outdir.resolve()
|
|
233
|
+
lexical = base / candidate
|
|
234
|
+
resolved = lexical.resolve()
|
|
235
|
+
resolved.relative_to(base)
|
|
236
|
+
except (OSError, RuntimeError, ValueError) as exc:
|
|
237
|
+
raise LessonLedgerError(f"归档段路径越界: {name}") from exc
|
|
238
|
+
if lexical.is_symlink() or resolved.is_symlink():
|
|
239
|
+
raise LessonLedgerError(f"归档段不能是符号链接: {name}")
|
|
240
|
+
if not resolved.is_file():
|
|
241
|
+
raise LessonLedgerError(f"归档段缺失或不安全: {name}")
|
|
242
|
+
return resolved
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _read_segment_blob(segment: Path, *, max_bytes: int | None = None) -> bytes:
|
|
246
|
+
"""按上限读取压缩段,避免把超大文件整体读入内存。
|
|
247
|
+
|
|
248
|
+
上限在**调用时**解析模块常量(而非默认参数),这样上限只有一个真源,
|
|
249
|
+
也便于测试注入更小的阈值。
|
|
250
|
+
"""
|
|
251
|
+
limit = MAX_SEGMENT_BYTES if max_bytes is None else max_bytes
|
|
252
|
+
try:
|
|
253
|
+
size = segment.stat().st_size
|
|
254
|
+
except OSError as exc:
|
|
255
|
+
raise LessonLedgerError(f"归档段不可读: {segment.name}") from exc
|
|
256
|
+
if size > limit:
|
|
257
|
+
raise LessonLedgerError(
|
|
258
|
+
f"归档段超过 {limit} 字节上限({size}): {segment.name}"
|
|
259
|
+
)
|
|
260
|
+
try:
|
|
261
|
+
return segment.read_bytes()
|
|
262
|
+
except OSError as exc:
|
|
263
|
+
raise LessonLedgerError(f"归档段不可读: {segment.name}") from exc
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _inflate_segment(
|
|
267
|
+
blob: bytes,
|
|
268
|
+
*,
|
|
269
|
+
name: str,
|
|
270
|
+
max_bytes: int | None = None,
|
|
271
|
+
) -> str:
|
|
272
|
+
"""分块解压并累计字节上限(替代一次性 ``gzip.decompress``)。
|
|
273
|
+
|
|
274
|
+
SEC-08:``gzip.decompress`` 会把完整膨胀结果放进内存,项目内投放一个
|
|
275
|
+
gzip 炸弹即可把审计宿主打到 OOM。这里逐块读取并在超限时立即中止。
|
|
276
|
+
|
|
277
|
+
上限在调用时解析模块常量,理由同 :func:`_read_segment_blob`。
|
|
278
|
+
"""
|
|
279
|
+
limit = MAX_SEGMENT_INFLATED_BYTES if max_bytes is None else max_bytes
|
|
280
|
+
chunks: list[bytes] = []
|
|
281
|
+
total = 0
|
|
282
|
+
try:
|
|
283
|
+
with gzip.GzipFile(fileobj=io.BytesIO(blob)) as handle:
|
|
284
|
+
while True:
|
|
285
|
+
chunk = handle.read(_SEGMENT_CHUNK_BYTES)
|
|
286
|
+
if not chunk:
|
|
287
|
+
break
|
|
288
|
+
total += len(chunk)
|
|
289
|
+
if total > limit:
|
|
290
|
+
raise LessonLedgerError(
|
|
291
|
+
f"归档段解压后超过 {limit} 字节上限: {name}"
|
|
292
|
+
)
|
|
293
|
+
chunks.append(chunk)
|
|
294
|
+
except LessonLedgerError:
|
|
295
|
+
raise
|
|
296
|
+
except (OSError, EOFError, zlib.error) as exc:
|
|
297
|
+
raise LessonLedgerError(f"归档段无法解压: {name}: {exc}") from exc
|
|
298
|
+
try:
|
|
299
|
+
return b"".join(chunks).decode("utf-8")
|
|
300
|
+
except UnicodeDecodeError as exc:
|
|
301
|
+
raise LessonLedgerError(f"归档段无法解压: {name}: {exc}") from exc
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def load_archived_events(output_dir: str | os.PathLike[str],
|
|
305
|
+
*, manifest: list[dict[str, Any]] | None = None,
|
|
306
|
+
verify_manifest: bool = True) -> list[dict[str, Any]]:
|
|
307
|
+
"""读取并校验 event 归档段;可独立使用,也可按 DB manifest 校验。
|
|
308
|
+
|
|
309
|
+
无 manifest 时按文件名排序做内部链与跨段链接校验;提供 manifest 时
|
|
310
|
+
额外核对 segment_sha256 / record_count / 边界字段。历史链由此完整
|
|
311
|
+
可证明(归档不截断审计证明)。
|
|
312
|
+
|
|
313
|
+
``verify_manifest=True`` 且**提供了 manifest** 时,``segment_sha256`` 与
|
|
314
|
+
``record_count`` 是必填字段:可选字段意味着「删掉它就能跳过校验」,
|
|
315
|
+
等于把完整性证明降级为自选动作(SEC-08)。
|
|
316
|
+
"""
|
|
317
|
+
outdir = Path(output_dir)
|
|
318
|
+
if not outdir.is_dir():
|
|
319
|
+
raise LessonLedgerError(f"归档目录不存在: {outdir}")
|
|
320
|
+
# 字段强制只对「调用方提供了 manifest」生效;无 manifest 时本就没有可核对的
|
|
321
|
+
# 声明值,此时仅做内部链校验(既有语义)。
|
|
322
|
+
enforce_fields = verify_manifest and manifest is not None
|
|
323
|
+
if manifest is None:
|
|
324
|
+
names = sorted(p.name for p in outdir.glob("events-*.jsonl.gz"))
|
|
325
|
+
entries: list[dict[str, Any]] = [{"segment": name} for name in names]
|
|
326
|
+
else:
|
|
327
|
+
entries = manifest
|
|
328
|
+
if not entries:
|
|
329
|
+
return []
|
|
330
|
+
events: list[dict[str, Any]] = []
|
|
331
|
+
prev_last_hash = ""
|
|
332
|
+
for entry in entries:
|
|
333
|
+
if not isinstance(entry, dict):
|
|
334
|
+
raise LessonLedgerError(f"归档 manifest 条目必须是对象: {entry!r}")
|
|
335
|
+
segment = _confined_segment(outdir, entry.get("segment"))
|
|
336
|
+
blob = _read_segment_blob(segment)
|
|
337
|
+
if enforce_fields:
|
|
338
|
+
expected_digest = entry.get("segment_sha256")
|
|
339
|
+
if not isinstance(expected_digest, str) or not expected_digest:
|
|
340
|
+
raise LessonLedgerError(
|
|
341
|
+
f"归档段缺少 segment_sha256,拒绝未经完整性校验的归档段: {segment.name}"
|
|
342
|
+
)
|
|
343
|
+
if hashlib.sha256(blob).hexdigest() != expected_digest:
|
|
344
|
+
raise LessonLedgerError(f"归档段 sha256 不一致: {segment.name}")
|
|
345
|
+
elif verify_manifest and entry.get("segment_sha256"):
|
|
346
|
+
if hashlib.sha256(blob).hexdigest() != entry["segment_sha256"]:
|
|
347
|
+
raise LessonLedgerError(f"归档段 sha256 不一致: {segment.name}")
|
|
348
|
+
text = _inflate_segment(blob, name=segment.name)
|
|
349
|
+
lines = [line for line in text.splitlines() if line.strip()]
|
|
350
|
+
if enforce_fields:
|
|
351
|
+
if entry.get("record_count") is None:
|
|
352
|
+
raise LessonLedgerError(f"归档段缺少 record_count: {segment.name}")
|
|
353
|
+
if len(lines) != int(entry["record_count"]):
|
|
354
|
+
raise LessonLedgerError(f"归档段记录数不一致: {segment.name}")
|
|
355
|
+
elif verify_manifest and entry.get("record_count") is not None \
|
|
356
|
+
and len(lines) != int(entry["record_count"]):
|
|
357
|
+
raise LessonLedgerError(f"归档段记录数不一致: {segment.name}")
|
|
358
|
+
running_prev = prev_last_hash
|
|
359
|
+
for line in lines:
|
|
360
|
+
try:
|
|
361
|
+
raw = json.loads(line)
|
|
362
|
+
except json.JSONDecodeError as exc:
|
|
363
|
+
raise LessonLedgerError(f"归档段行不是有效 JSON: {segment.name}") from exc
|
|
364
|
+
event = event_from_row_values(
|
|
365
|
+
raw.get("seq"), str(raw.get("type")), str(raw.get("at")),
|
|
366
|
+
json.dumps(raw.get("payload"), ensure_ascii=False, sort_keys=True,
|
|
367
|
+
separators=(",", ":")),
|
|
368
|
+
str(raw.get("prev_hash")), str(raw.get("hash")),
|
|
369
|
+
)
|
|
370
|
+
if event["prev_hash"] != running_prev:
|
|
371
|
+
raise LessonLedgerError(f"归档段 hash 链断裂: {segment.name}")
|
|
372
|
+
running_prev = event["hash"]
|
|
373
|
+
events.append(event)
|
|
374
|
+
first_seq: int | None = None
|
|
375
|
+
last_seq: int | None = None
|
|
376
|
+
if lines:
|
|
377
|
+
first_seq = events[len(events) - len(lines)]["seq"]
|
|
378
|
+
last_seq = events[-1]["seq"]
|
|
379
|
+
if verify_manifest and entry.get("first_seq") is not None \
|
|
380
|
+
and (first_seq != int(entry["first_seq"]) or last_seq != int(entry["last_seq"])):
|
|
381
|
+
raise LessonLedgerError(f"归档段 seq 边界不一致: {segment.name}")
|
|
382
|
+
prev_last_hash = running_prev
|
|
383
|
+
return events
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def validate_deep(path: str | os.PathLike[str]) -> dict[str, Any]:
|
|
387
|
+
"""DOC-008 §9 深度校验:事实表、事件链、state hash、receipt、tombstone、
|
|
388
|
+
FTS 投影与归档段全部独立验证;任何一项失败都整体失败。"""
|
|
389
|
+
db = database_path(path)
|
|
390
|
+
issues: list[str] = []
|
|
391
|
+
with _conn(db, readonly=True) as c:
|
|
392
|
+
if c.execute("PRAGMA integrity_check").fetchone()[0] != "ok":
|
|
393
|
+
issues.append(f"integrity_check 失败: {db}")
|
|
394
|
+
schema = _meta_value(c, "schema_version")
|
|
395
|
+
if schema != str(_ledger.SCHEMA_VERSION):
|
|
396
|
+
issues.append(f"schema_version 无效: {schema!r}")
|
|
397
|
+
try:
|
|
398
|
+
_validate(c, db)
|
|
399
|
+
except LessonLedgerError as exc:
|
|
400
|
+
issues.append(str(exc))
|
|
401
|
+
# evidence receipt 内容哈希
|
|
402
|
+
for r in c.execute("SELECT * FROM evidence_receipts ORDER BY receipt_id"):
|
|
403
|
+
item = {
|
|
404
|
+
"receipt_id": r[0], "subject_type": r[1], "subject_id": r[2],
|
|
405
|
+
"run_id": r[3], "lifecycle_id": r[4], "round": int(r[5]),
|
|
406
|
+
"artifact_hash": r[6], "created_at": r[7],
|
|
407
|
+
}
|
|
408
|
+
if hashlib.sha256(_canon(item)).hexdigest() != r[8]:
|
|
409
|
+
issues.append(f"evidence_receipt 哈希不一致: {r[0]}")
|
|
410
|
+
# consumption event 内容哈希
|
|
411
|
+
for r in c.execute("SELECT * FROM consumption_events ORDER BY event_id"):
|
|
412
|
+
item = {
|
|
413
|
+
"event_id": r[0], "subject_type": r[1], "subject_id": r[2],
|
|
414
|
+
"event_type": r[3], "lifecycle_id": r[4], "run_id": r[5],
|
|
415
|
+
"created_at": r[6],
|
|
416
|
+
}
|
|
417
|
+
if hashlib.sha256(_canon(item)).hexdigest() != r[7]:
|
|
418
|
+
issues.append(f"consumption_event 哈希不一致: {r[0]}")
|
|
419
|
+
# incident 内容哈希(tombstone/status 变更会更新 updated_at,
|
|
420
|
+
# 但 content 只覆盖业务字段,因此仍可独立复算)
|
|
421
|
+
for r in c.execute("SELECT * FROM incidents ORDER BY incident_id"):
|
|
422
|
+
try:
|
|
423
|
+
routing_tags = json.loads(r[17]) if r[17] else {}
|
|
424
|
+
except (TypeError, ValueError):
|
|
425
|
+
issues.append(f"incident routing_tags JSON 无效: {r[0]}")
|
|
426
|
+
routing_tags = {}
|
|
427
|
+
content = {
|
|
428
|
+
"signature": r[2], "summary": r[3], "context": r[4],
|
|
429
|
+
"before_snippet": r[5], "after_snippet": r[6], "diff_ref": r[7],
|
|
430
|
+
"commit_ref": r[8], "decision": r[9], "duration_seconds": r[10],
|
|
431
|
+
"lifecycle_id": r[11], "round": r[12], "pattern_id": r[1],
|
|
432
|
+
"routing_tags": routing_tags,
|
|
433
|
+
}
|
|
434
|
+
# v13 had no fingerprint column; preserve its legacy hash projection.
|
|
435
|
+
fingerprint = r[18] if len(r) > 18 else None
|
|
436
|
+
if fingerprint is not None:
|
|
437
|
+
content["finding_fingerprint"] = fingerprint
|
|
438
|
+
try:
|
|
439
|
+
content_hash = hashlib.sha256(_canon(_incident_content(content))).hexdigest()
|
|
440
|
+
except LessonLedgerError as exc:
|
|
441
|
+
issues.append(f"incident 内容无效: {r[0]} ({exc})")
|
|
442
|
+
continue
|
|
443
|
+
if content_hash != r[16]:
|
|
444
|
+
issues.append(f"incident 内容哈希不一致: {r[0]}")
|
|
445
|
+
# tool experience 内容哈希
|
|
446
|
+
for r in c.execute("SELECT * FROM tool_experience ORDER BY tool_name,category"):
|
|
447
|
+
content = {
|
|
448
|
+
"tool_name": r[0], "category": r[1], "experience_level": r[2],
|
|
449
|
+
"record_version": int(r[3]), "use_count": int(r[4]),
|
|
450
|
+
"hit_count": int(r[5]), "miss_count": int(r[6]),
|
|
451
|
+
"false_positive_count": int(r[7]), "rejected_count": int(r[8]),
|
|
452
|
+
"independent_lifecycle_count": int(r[9]),
|
|
453
|
+
"first_observed_at": r[10], "last_observed_at": r[11],
|
|
454
|
+
"tool_version": r[12], "device_id": r[13],
|
|
455
|
+
"deleted": bool(r[14]), "deleted_at": r[15],
|
|
456
|
+
}
|
|
457
|
+
if hashlib.sha256(_canon(
|
|
458
|
+
{k: content[k] for k in sorted(content)})).hexdigest() != r[17]:
|
|
459
|
+
issues.append(f"tool_experience 哈希不一致: {r[0]}/{r[1]}")
|
|
460
|
+
issues.extend(fts_audit(c))
|
|
461
|
+
# 归档段与 active 链边界
|
|
462
|
+
manifest = _archive_manifest(c)
|
|
463
|
+
archived_total = sum(int(entry.get("record_count", 0)) for entry in manifest)
|
|
464
|
+
active_first = c.execute(
|
|
465
|
+
"SELECT seq,prev_hash FROM events ORDER BY seq LIMIT 1"
|
|
466
|
+
).fetchone()
|
|
467
|
+
archived_seq = _meta_value(c, "archive_last_seq")
|
|
468
|
+
if manifest:
|
|
469
|
+
root = hashlib.sha256(_canon(manifest)).hexdigest()
|
|
470
|
+
# F-134: 只比 DB 内 manifest 与 DB 内 archive_root_hash 不算完整性校验;
|
|
471
|
+
# 必须与库外只读锚互证,锚缺失/损坏/不符一律 fail-closed。
|
|
472
|
+
archive_dir = _meta_value(c, "archive_dir")
|
|
473
|
+
anchor = _archive_anchor_path(archive_dir) if archive_dir else None
|
|
474
|
+
if anchor is None or not anchor.is_file():
|
|
475
|
+
issues.append("archive_root_hash 库外锚缺失,拒绝通过深度校验")
|
|
476
|
+
else:
|
|
477
|
+
try:
|
|
478
|
+
anchor_data = json.loads(anchor.read_text(encoding="utf-8"))
|
|
479
|
+
except (OSError, ValueError) as exc:
|
|
480
|
+
issues.append(f"archive_root_hash 库外锚损坏: {exc}")
|
|
481
|
+
anchor_data = None
|
|
482
|
+
if anchor_data is not None:
|
|
483
|
+
if str(anchor_data.get("archive_root_hash", "")) != root:
|
|
484
|
+
issues.append("archive_root_hash 与库外锚不一致")
|
|
485
|
+
if str(anchor_data.get("manifest_sha256", "")) != root:
|
|
486
|
+
issues.append("archive manifest 摘要与库外锚不一致")
|
|
487
|
+
if _meta_value(c, "archive_root_hash") != root:
|
|
488
|
+
issues.append("archive_root_hash 与 manifest 不一致")
|
|
489
|
+
if not archive_dir or not Path(archive_dir).is_dir():
|
|
490
|
+
issues.append("archive_dir 缺失,无法验证归档段")
|
|
491
|
+
else:
|
|
492
|
+
try:
|
|
493
|
+
archived = load_archived_events(archive_dir, manifest=manifest)
|
|
494
|
+
if len(archived) != archived_total:
|
|
495
|
+
issues.append("归档段事件总数与 manifest 不一致")
|
|
496
|
+
if archived and active_first:
|
|
497
|
+
if archived[-1]["hash"] != active_first[1] \
|
|
498
|
+
or int(archived_seq) + 1 != int(active_first[0]):
|
|
499
|
+
issues.append("归档链末端与 active 链起点不连续")
|
|
500
|
+
except LessonLedgerError as exc:
|
|
501
|
+
issues.append(str(exc))
|
|
502
|
+
elif active_first and int(active_first[0]) != 1:
|
|
503
|
+
issues.append("无归档时首个 active 事件必须是 seq=1")
|
|
504
|
+
counts = {
|
|
505
|
+
"patterns": c.execute("SELECT COUNT(*) FROM patterns").fetchone()[0],
|
|
506
|
+
"incidents": c.execute("SELECT COUNT(*) FROM incidents").fetchone()[0],
|
|
507
|
+
"receipts": c.execute("SELECT COUNT(*) FROM evidence_receipts").fetchone()[0],
|
|
508
|
+
"consumption_events": c.execute("SELECT COUNT(*) FROM consumption_events").fetchone()[0],
|
|
509
|
+
"tool_experience": c.execute("SELECT COUNT(*) FROM tool_experience").fetchone()[0],
|
|
510
|
+
}
|
|
511
|
+
if issues:
|
|
512
|
+
raise LessonLedgerError("深度校验失败:\n- " + "\n- ".join(sorted(issues)))
|
|
513
|
+
return {"status": "valid", "database": str(db), "counts": counts,
|
|
514
|
+
"events_active": count_active_events(db), "events_archived": archived_total,
|
|
515
|
+
"fts_backend": "fts5"}
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def count_active_events(path: str | os.PathLike[str]) -> int:
|
|
519
|
+
db = database_path(path)
|
|
520
|
+
with _conn(db, readonly=True) as c:
|
|
521
|
+
return int(c.execute("SELECT COUNT(*) FROM events").fetchone()[0])
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def archive_events(path: str | os.PathLike[str], output_dir: str | os.PathLike[str],
|
|
525
|
+
*, keep_tail: int = 0) -> dict[str, Any]:
|
|
526
|
+
"""把闭合区间 events 写入压缩 JSONL segment 并从 active 库删除。
|
|
527
|
+
|
|
528
|
+
崩溃安全顺序(DOC-008 §10.7):
|
|
529
|
+
1) 先在一致性读边界取事件快照并生成确定性 segment 字节;
|
|
530
|
+
2) segment 以临时文件写入、fsync 后原子发布到最终路径;
|
|
531
|
+
3) 再开写事务:校验 head 未变 → 删除已归档区间 → 写入 manifest、
|
|
532
|
+
archive root hash、最后归档 seq/hash(新的连续起点证明)→ 提交;
|
|
533
|
+
同批把 root_hash 原子写入库外只读锚(与 DB 物理分离,F-134);
|
|
534
|
+
4) 发布成功但事务失败的进程内异常会删除未登记的 segment 文件与库外锚;
|
|
535
|
+
5) 进程中断留下的孤儿文件内容是确定性的,重跑会用相同字节覆盖收敛。
|
|
536
|
+
"""
|
|
537
|
+
if not isinstance(keep_tail, int) or isinstance(keep_tail, bool) or keep_tail < 0:
|
|
538
|
+
raise LessonLedgerError("keep_tail 必须是非负整数")
|
|
539
|
+
db = database_path(path)
|
|
540
|
+
outdir = Path(output_dir)
|
|
541
|
+
if outdir.is_symlink():
|
|
542
|
+
raise LessonLedgerError(f"拒绝使用符号链接归档目录: {outdir}")
|
|
543
|
+
outdir.mkdir(parents=True, exist_ok=True)
|
|
544
|
+
with _conn(db, readonly=True) as src:
|
|
545
|
+
_validate(src, db)
|
|
546
|
+
manifest = _archive_manifest(src)
|
|
547
|
+
head_snapshot = _meta_value(src, "head_hash")
|
|
548
|
+
rows = [
|
|
549
|
+
{"seq": int(r[0]), "type": str(r[1]), "at": str(r[2]),
|
|
550
|
+
"payload": json.loads(r[3]), "prev_hash": str(r[4]), "hash": str(r[5])}
|
|
551
|
+
for r in src.execute("SELECT * FROM events ORDER BY seq")
|
|
552
|
+
]
|
|
553
|
+
cutoff = len(rows) - keep_tail
|
|
554
|
+
if cutoff <= 0:
|
|
555
|
+
return {"status": "no-op", "archived_events": 0,
|
|
556
|
+
"active_events": len(rows),
|
|
557
|
+
"events_archived_total": sum(int(e.get("record_count", 0)) for e in manifest)}
|
|
558
|
+
segment_rows = rows[:cutoff]
|
|
559
|
+
first, last = segment_rows[0], segment_rows[-1]
|
|
560
|
+
lines = "".join(
|
|
561
|
+
json.dumps(row, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n"
|
|
562
|
+
for row in segment_rows
|
|
563
|
+
)
|
|
564
|
+
# mtime=0 保证同区间字节级确定:中断后的重跑可以无损覆盖孤儿文件。
|
|
565
|
+
blob = gzip.compress(lines.encode("utf-8"), mtime=0)
|
|
566
|
+
name = f"events-{first['seq']:012d}-{last['seq']:012d}.jsonl.gz"
|
|
567
|
+
final = outdir / name
|
|
568
|
+
entry = {
|
|
569
|
+
"segment": name,
|
|
570
|
+
"first_seq": first["seq"], "last_seq": last["seq"],
|
|
571
|
+
"previous_hash": first["prev_hash"], "last_hash": last["hash"],
|
|
572
|
+
"segment_sha256": hashlib.sha256(blob).hexdigest(),
|
|
573
|
+
"record_count": len(segment_rows),
|
|
574
|
+
}
|
|
575
|
+
new_manifest = manifest + [entry]
|
|
576
|
+
root_hash = hashlib.sha256(_canon(new_manifest)).hexdigest()
|
|
577
|
+
fd, tmp_name = tempfile.mkstemp(prefix=".segment-", suffix=".tmp", dir=outdir)
|
|
578
|
+
tmp = Path(tmp_name)
|
|
579
|
+
published = False
|
|
580
|
+
anchor_path: Path | None = None
|
|
581
|
+
anchor_published = False
|
|
582
|
+
try:
|
|
583
|
+
with os.fdopen(fd, "wb") as handle:
|
|
584
|
+
handle.write(blob)
|
|
585
|
+
handle.flush()
|
|
586
|
+
os.fsync(handle.fileno())
|
|
587
|
+
os.replace(tmp, final)
|
|
588
|
+
published = True
|
|
589
|
+
|
|
590
|
+
# F-134: 库外只读锚与 DB 分离写入;若 DB 事务失败,异常路径一并撤销。
|
|
591
|
+
anchor_path = _archive_anchor_path(outdir)
|
|
592
|
+
_write_archive_anchor(anchor_path, root_hash, new_manifest)
|
|
593
|
+
anchor_published = True
|
|
594
|
+
|
|
595
|
+
def go(c):
|
|
596
|
+
if _meta_value(c, "head_hash") != head_snapshot:
|
|
597
|
+
raise LessonLedgerError("归档期间账本发生变化,拒绝提交本次归档")
|
|
598
|
+
c.execute("DELETE FROM events WHERE seq<=?", (last["seq"],))
|
|
599
|
+
c.executemany(
|
|
600
|
+
"INSERT OR REPLACE INTO meta(key,value) VALUES(?,?)",
|
|
601
|
+
[
|
|
602
|
+
("archive_manifest", json.dumps(new_manifest, ensure_ascii=False,
|
|
603
|
+
sort_keys=True)),
|
|
604
|
+
("archive_root_hash", root_hash),
|
|
605
|
+
("archive_last_seq", str(last["seq"])),
|
|
606
|
+
("archive_last_hash", last["hash"]),
|
|
607
|
+
("archive_dir", str(outdir)),
|
|
608
|
+
],
|
|
609
|
+
)
|
|
610
|
+
|
|
611
|
+
_tx(path, go)
|
|
612
|
+
return {
|
|
613
|
+
"status": "archived", "segment": str(final),
|
|
614
|
+
"archived_events": len(segment_rows),
|
|
615
|
+
"first_seq": first["seq"], "last_seq": last["seq"],
|
|
616
|
+
"archive_root_hash": root_hash,
|
|
617
|
+
"active_events": count_active_events(path),
|
|
618
|
+
"events_archived_total": sum(int(e.get("record_count", 0)) for e in new_manifest),
|
|
619
|
+
}
|
|
620
|
+
except BaseException:
|
|
621
|
+
try:
|
|
622
|
+
if published:
|
|
623
|
+
final.unlink()
|
|
624
|
+
elif tmp.is_file():
|
|
625
|
+
tmp.unlink()
|
|
626
|
+
if anchor_published and anchor_path is not None:
|
|
627
|
+
anchor_path.unlink()
|
|
628
|
+
except OSError:
|
|
629
|
+
pass
|
|
630
|
+
raise
|