bugx-cli 0.0.0-stage → 0.1.0
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 +280 -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 +50 -0
- package/core/agent/__init__.py +146 -0
- package/core/agent/agent_artifacts.py +764 -0
- package/core/agent/agent_eval.py +1073 -0
- package/core/agent/agent_execution.py +552 -0
- package/core/agent/agent_orchestrator.py +1345 -0
- package/core/agent/agent_targets.py +871 -0
- package/core/agent/agent_workspace.py +770 -0
- package/core/assets/README.md +24 -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/project-layout.md +42 -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 +1822 -0
- package/core/autonomous_cve/audit_campaign.py +1232 -0
- package/core/autonomous_cve/behavior_graph.py +459 -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 +100 -0
- package/core/bugx.md +1299 -0
- package/core/bugx_paths.py +1846 -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 +1199 -0
- package/core/cloud_sync/cloud_onboard.py +702 -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 +760 -0
- package/core/cloud_sync/network_transport.py +275 -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 +721 -0
- package/core/contracts/AGENT_GUIDE.md +362 -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 +390 -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 +859 -0
- package/core/coverage/coverage_evidence.py +977 -0
- package/core/coverage/coverage_forensics.py +115 -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 +236 -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 +2625 -0
- package/core/fuzzing/README.md +49 -0
- package/core/fuzzing/__init__.py +82 -0
- package/core/fuzzing/concurrency_fuzzer.py +382 -0
- package/core/fuzzing/differential_oracle.py +629 -0
- package/core/fuzzing/fuzz_input.py +1188 -0
- package/core/fuzzing/stateful_fuzzer.py +332 -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 +772 -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 +41 -0
- package/core/host_acp/cline.py +235 -0
- package/core/host_acp/codex.py +245 -0
- package/core/host_acp/dsh.py +48 -0
- package/core/host_acp/opencode.py +154 -0
- package/core/host_acp/pi.py +36 -0
- package/core/host_acp/zcode.py +41 -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 +435 -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 +721 -0
- package/core/host_runtime/host_probe.py +41 -0
- package/core/host_runtime/host_provider_arbitrator.py +777 -0
- package/core/host_runtime/host_registry.py +655 -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 +368 -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 +136 -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 +451 -0
- package/core/hosts/claude.py +157 -0
- package/core/hosts/cline.py +225 -0
- package/core/hosts/codex.py +948 -0
- package/core/hosts/dsh.py +518 -0
- package/core/hosts/opencode.py +358 -0
- package/core/hosts/pi.py +151 -0
- package/core/hosts/zcode.py +219 -0
- package/core/i18n.py +252 -0
- package/core/infra/README.md +39 -0
- package/core/infra/__init__.py +15 -0
- package/core/infra/build_info.py +86 -0
- package/core/infra/client_metadata.py +185 -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 +1041 -0
- package/core/launch_phases/finding_confirm_phase.py +387 -0
- package/core/launch_phases/finding_settlement.py +1245 -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 +791 -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 +682 -0
- package/core/launch_phases/post_commit.py +567 -0
- package/core/launch_phases/post_coverage_sync.py +591 -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 +1087 -0
- package/core/launch_phases/post_receipt.py +362 -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 +862 -0
- package/core/launch_phases/pre_state_builder.py +1286 -0
- package/core/launch_phases/report_sharing.py +414 -0
- package/core/launch_phases/round_orchestrator.py +1133 -0
- package/core/launch_phases/session_runtime.py +1623 -0
- package/core/launch_phases/startup_gates.py +1022 -0
- package/core/launch_phases/startup_interaction.py +947 -0
- package/core/launch_phases/startup_version_gate.py +873 -0
- package/core/launch_phases/supervisor_bridge.py +1224 -0
- package/core/launch_phases/supervisor_coverage.py +417 -0
- package/core/launch_phases/supervisor_degraded.py +1219 -0
- package/core/launch_phases/worker_barriers.py +414 -0
- package/core/launch_phases/worker_orchestrator.py +1166 -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 +226 -0
- package/core/ledger/archive_ops.py +572 -0
- package/core/ledger/auto_materialization.py +459 -0
- package/core/ledger/bug-log.md +22 -0
- package/core/ledger/cli.py +270 -0
- package/core/ledger/export_ops.py +549 -0
- package/core/ledger/finding_confirmation.py +1274 -0
- package/core/ledger/finding_io.py +299 -0
- package/core/ledger/finding_lifecycle.py +307 -0
- package/core/ledger/finding_verification.py +369 -0
- package/core/ledger/incidents.py +999 -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 +681 -0
- package/core/ledger/receipt_contract.py +253 -0
- package/core/ledger/schema.py +1192 -0
- package/core/ledger/sync_ops.py +935 -0
- package/core/ledger/tool_experience.py +682 -0
- package/core/ledger/verify_life.py +1526 -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 +697 -0
- package/core/mcp_handlers/channel_lifecycle.py +696 -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 +239 -0
- package/core/mcp_handlers/rpc_server.py +465 -0
- package/core/mcp_handlers/supervisor_handlers.py +1435 -0
- package/core/mcp_handlers/telemetry_handlers.py +227 -0
- package/core/mcp_handlers/tool_table.py +1015 -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 +605 -0
- package/core/mcp_runtime_support/verifier.py +810 -0
- package/core/metadata.txt +5 -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 +267 -0
- package/core/planning/dynamic_flow_analyzer.py +328 -0
- package/core/planning/impact_pruner.py +435 -0
- package/core/planning/intent_adjudicator.py +175 -0
- package/core/planning/judge_pipeline.py +1163 -0
- package/core/planning/logic_analysis.py +419 -0
- package/core/planning/prompt_harness.py +1702 -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 +73 -0
- package/core/probes/README.md +51 -0
- package/core/probes/SPEC.md +26 -0
- package/core/probes/__init__.py +70 -0
- package/core/probes/android_probe.py +384 -0
- package/core/probes/base.py +147 -0
- package/core/probes/codebase_memory_probe.py +590 -0
- package/core/probes/desktop_probe.py +238 -0
- package/core/probes/differential_probe.py +356 -0
- package/core/probes/efficiency_probe.py +168 -0
- package/core/probes/ios_binary_probe.py +368 -0
- package/core/probes/memory_probe.py +326 -0
- package/core/probes/miniprogram_probe.py +323 -0
- package/core/probes/mobile_probe.py +281 -0
- package/core/probes/native_probe.py +214 -0
- package/core/probes/openwiki_probe.py +193 -0
- package/core/probes/pattern_probe.py +347 -0
- package/core/probes/platform_probe.py +343 -0
- package/core/probes/probe_registry.py +1669 -0
- package/core/probes/sast_probe.py +1009 -0
- package/core/probes/sast_rules.py +841 -0
- package/core/probes/sca_scanner.py +731 -0
- package/core/probes/web_probe.py +359 -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 +311 -0
- package/core/project_profiler/constants.py +247 -0
- package/core/project_profiler/detector.py +392 -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 +265 -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 +465 -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 +313 -0
- package/core/repair/rsi_repair.py +348 -0
- package/core/repair/rsi_rounds.py +212 -0
- package/core/repair/rsi_scope.py +262 -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 +224 -0
- package/core/report_engine/authority.py +255 -0
- package/core/report_engine/finding_report.py +417 -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 +761 -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 +822 -0
- package/core/report_engine/visual_report_builder.py +796 -0
- package/core/report_engine/web-conformance.md +63 -0
- package/core/report_engine/web_conformance.py +459 -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 +1684 -0
- package/core/retrieval/codebase_memory_bridge.py +337 -0
- package/core/retrieval/context_assembler.py +234 -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 +909 -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 +1132 -0
- package/core/retrieval/universal_code_matcher.py +437 -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 +1393 -0
- package/core/runtime/daemon_runner.py +623 -0
- package/core/runtime/fixture_solidify.py +449 -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 +769 -0
- package/core/runtime/platform_adapter.py +579 -0
- package/core/runtime/prep_validate.py +476 -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 +963 -0
- package/core/runtime/provider_window.py +97 -0
- package/core/runtime/resume_ticket.py +115 -0
- package/core/runtime/scenario_eval.py +814 -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 +416 -0
- package/core/skills/bugx_mcp_server.py +1134 -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 +760 -0
- package/core/supervisor/checkpoint_handler.py +368 -0
- package/core/supervisor/checkpoint_pipeline.py +1322 -0
- package/core/supervisor/checkpoint_sync.py +640 -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 +659 -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 +124 -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 +308 -0
- package/core/supervisor/round_governor.py +306 -0
- package/core/supervisor/serial_authorization.py +500 -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 +223 -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 +999 -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 +402 -0
- package/core/webui/INTERFACE.md +50 -0
- package/core/webui/README.md +57 -0
- package/core/webui/SPEC.md +25 -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 +218 -0
- package/core/webui/adapters/cline.py +399 -0
- package/core/webui/adapters/codex.py +256 -0
- package/core/webui/adapters/dsh.py +173 -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 +1743 -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/favicon.png +0 -0
- package/core/webui/static/icon-192.png +0 -0
- package/core/webui/static/index.html +42 -0
- package/core/webui/static/manifest.webmanifest +19 -0
- package/core/webui/static/project-settings.css +6458 -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 +281 -0
- package/docs/07_distribution/README.md +16 -0
- package/docs/README.md +121 -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 +3067 -0
- package/ecosystem/integrations/opencode/opencode.json +118 -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/README.md +143 -0
- package/interfaces/bin/README.md +35 -0
- package/interfaces/bin/bugx.js +80 -0
- package/interfaces/cli/README.md +90 -0
- package/interfaces/cli/bugx_cli/__init__.py +4 -0
- package/interfaces/cli/bugx_cli/cli.py +1678 -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 +3944 -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 +1370 -0
- package/interfaces/cli/bugx_cli/commands/daemon.py +50 -0
- package/interfaces/cli/bugx_cli/commands/doctor.py +1345 -0
- package/interfaces/cli/bugx_cli/commands/goal.py +107 -0
- package/interfaces/cli/bugx_cli/commands/interaction.py +244 -0
- package/interfaces/cli/bugx_cli/commands/knowledge.py +617 -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 +2714 -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 +728 -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 +260 -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 +898 -0
- package/interfaces/cli/bugx_cli/host_adapters.py +1917 -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 +571 -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 +721 -0
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +1937 -0
- package/interfaces/cli/bugx_cli/infra/host_sync.py +545 -0
- package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +755 -0
- package/interfaces/cli/bugx_cli/infra/security.py +332 -0
- package/package.json +98 -4
- package/pyproject.toml +246 -0
- package/scripts/README.md +118 -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 +37 -0
- package/scripts/test-npm-wrapper.mjs +265 -0
|
@@ -0,0 +1,827 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""构建源码关系图、自动发现跨模块业务链路,并生成增量审计计划。"""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
# --- 引擎导入根(直接执行脚本时自举 core.* 命名空间)---
|
|
5
|
+
import sys as _sys
|
|
6
|
+
from pathlib import Path as _Path
|
|
7
|
+
|
|
8
|
+
for _p in _Path(__file__).resolve().parents:
|
|
9
|
+
if (_p / "core" / "bugx.md").is_file():
|
|
10
|
+
if str(_p) not in _sys.path:
|
|
11
|
+
_sys.path.insert(0, str(_p))
|
|
12
|
+
break
|
|
13
|
+
del _p
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import ast
|
|
20
|
+
import json
|
|
21
|
+
import re
|
|
22
|
+
import subprocess
|
|
23
|
+
from collections import defaultdict, deque
|
|
24
|
+
from dataclasses import asdict, dataclass
|
|
25
|
+
|
|
26
|
+
from core.retrieval import symbol_index
|
|
27
|
+
from core.retrieval import codebase_memory_bridge
|
|
28
|
+
|
|
29
|
+
SCHEMA_VERSION = 1
|
|
30
|
+
ENTRY_WORDS = {"main", "handler", "handle", "route", "endpoint", "command", "execute"}
|
|
31
|
+
SINK_WORDS = {
|
|
32
|
+
"save", "delete", "remove", "charge", "pay", "commit", "publish", "send",
|
|
33
|
+
"emit", "enqueue", "write", "update", "create",
|
|
34
|
+
}
|
|
35
|
+
SOURCE_EXTENSIONS = (
|
|
36
|
+
".py", ".js", ".mjs", ".cjs", ".jsx", ".ts", ".tsx", ".java", ".kt", ".kts", ".go",
|
|
37
|
+
".rs", ".swift", ".c", ".h", ".cc", ".cpp", ".cxx", ".cs", ".rb",
|
|
38
|
+
".php", ".vue", ".svelte",
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class GraphError(ValueError):
|
|
43
|
+
"""关系图或增量计划输入错误。"""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class Edge:
|
|
48
|
+
type: str
|
|
49
|
+
source: str
|
|
50
|
+
target: str
|
|
51
|
+
confidence: float
|
|
52
|
+
evidence: str
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class GraphPassCache:
|
|
56
|
+
"""Per-pass cache shared by the graph, unit and inventory steps of one pass.
|
|
57
|
+
|
|
58
|
+
``content`` is a ``symbol_index.SourceContentCache`` so every source file is
|
|
59
|
+
read once across the whole pass, and ``_graphs`` memoises graphs already
|
|
60
|
+
built in this pass so asking for the same root twice does not pay the full
|
|
61
|
+
index + parse cost again.
|
|
62
|
+
|
|
63
|
+
Lifetime is one caller-owned pass, never process-global: the audited
|
|
64
|
+
workspace can change between passes (edits, ``git checkout``, generated
|
|
65
|
+
files), so a process-wide cache would serve stale content. The memo hands
|
|
66
|
+
back the *same* graph object, so callers must treat it as read-only.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
__slots__ = ("content", "_graphs")
|
|
70
|
+
|
|
71
|
+
def __init__(self) -> None:
|
|
72
|
+
self.content = symbol_index.SourceContentCache()
|
|
73
|
+
self._graphs: dict[tuple[str, str], dict] = {}
|
|
74
|
+
|
|
75
|
+
def graph(self, root: Path, knowledge_graph: str) -> dict | None:
|
|
76
|
+
return self._graphs.get((str(root), knowledge_graph))
|
|
77
|
+
|
|
78
|
+
def remember(self, root: Path, knowledge_graph: str, graph: dict) -> None:
|
|
79
|
+
self._graphs[(str(root), knowledge_graph)] = graph
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _module_aliases(path: str) -> set[str]:
|
|
83
|
+
value = Path(path).with_suffix("").as_posix().replace("/", ".")
|
|
84
|
+
aliases = {value}
|
|
85
|
+
if value.endswith(".__init__"):
|
|
86
|
+
aliases.add(value[:-9])
|
|
87
|
+
parts = value.split(".")
|
|
88
|
+
for index in range(1, len(parts)):
|
|
89
|
+
aliases.add(".".join(parts[index:]))
|
|
90
|
+
return {item for item in aliases if item}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _symbol_id(path: str, qualified: str) -> str:
|
|
94
|
+
return f"symbol:{path}::{qualified}"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _file_id(path: str) -> str:
|
|
98
|
+
return f"file:{path}"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _name_from_node(source: str, node: ast.AST) -> str:
|
|
102
|
+
if isinstance(node, ast.Name):
|
|
103
|
+
return node.id
|
|
104
|
+
if isinstance(node, ast.Attribute):
|
|
105
|
+
base = _name_from_node(source, node.value)
|
|
106
|
+
return f"{base}.{node.attr}" if base else node.attr
|
|
107
|
+
try:
|
|
108
|
+
raw = ast.get_source_segment(source, node) or ""
|
|
109
|
+
# Evidence is later embedded in a Markdown table. Complex calls such
|
|
110
|
+
# as ``{...}.get(...)`` can span lines; keep the evidence one cell and
|
|
111
|
+
# prevent a source pipe from changing the table schema.
|
|
112
|
+
return re.sub(r"\s+", " ", raw).replace("|", "/").strip()[:240]
|
|
113
|
+
except (TypeError, ValueError):
|
|
114
|
+
return ""
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class _PythonRelations(ast.NodeVisitor):
|
|
118
|
+
def __init__(self, path: str, source: str, module_paths: dict[str, str],
|
|
119
|
+
symbols_by_file: dict[str, list[dict]], global_names: dict[str, list[str]]) -> None:
|
|
120
|
+
self.path = path
|
|
121
|
+
self.source = source
|
|
122
|
+
self.module_paths = module_paths
|
|
123
|
+
self.symbols_by_file = symbols_by_file
|
|
124
|
+
self.global_names = global_names
|
|
125
|
+
self.parents: list[str] = []
|
|
126
|
+
self.imported_symbols: dict[str, str] = {}
|
|
127
|
+
self.imported_modules: dict[str, str] = {}
|
|
128
|
+
self.edges: list[Edge] = []
|
|
129
|
+
|
|
130
|
+
def _caller(self) -> str:
|
|
131
|
+
if self.parents:
|
|
132
|
+
return _symbol_id(self.path, ".".join(self.parents))
|
|
133
|
+
return _file_id(self.path)
|
|
134
|
+
|
|
135
|
+
def _target_symbol(self, path: str, name: str) -> str | None:
|
|
136
|
+
candidates = [
|
|
137
|
+
_symbol_id(path, item["qualified_name"])
|
|
138
|
+
for item in self.symbols_by_file.get(path, [])
|
|
139
|
+
if item["name"] == name
|
|
140
|
+
]
|
|
141
|
+
return candidates[0] if len(candidates) == 1 else None
|
|
142
|
+
|
|
143
|
+
def visit_Import(self, node: ast.Import) -> None:
|
|
144
|
+
for alias in node.names:
|
|
145
|
+
target_path = self.module_paths.get(alias.name)
|
|
146
|
+
if not target_path:
|
|
147
|
+
continue
|
|
148
|
+
local = alias.asname or alias.name.split(".")[0]
|
|
149
|
+
self.imported_modules[local] = target_path
|
|
150
|
+
self.edges.append(Edge(
|
|
151
|
+
"imports", _file_id(self.path), _file_id(target_path), 0.95,
|
|
152
|
+
f"{self.path}:{node.lineno} import {alias.name}",
|
|
153
|
+
))
|
|
154
|
+
|
|
155
|
+
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
|
|
156
|
+
module = node.module or ""
|
|
157
|
+
target_path = self.module_paths.get(module)
|
|
158
|
+
if target_path:
|
|
159
|
+
self.edges.append(Edge(
|
|
160
|
+
"imports", _file_id(self.path), _file_id(target_path), 0.95,
|
|
161
|
+
f"{self.path}:{node.lineno} from {module}",
|
|
162
|
+
))
|
|
163
|
+
for alias in node.names:
|
|
164
|
+
local = alias.asname or alias.name
|
|
165
|
+
sub_mod = f"{module}.{alias.name}" if module else alias.name
|
|
166
|
+
sub_target_path = self.module_paths.get(sub_mod)
|
|
167
|
+
if sub_target_path:
|
|
168
|
+
self.imported_modules[local] = sub_target_path
|
|
169
|
+
self.edges.append(Edge(
|
|
170
|
+
"imports", _file_id(self.path), _file_id(sub_target_path), 0.95,
|
|
171
|
+
f"{self.path}:{node.lineno} from {module} import {alias.name}",
|
|
172
|
+
))
|
|
173
|
+
elif target_path:
|
|
174
|
+
target = self._target_symbol(target_path, alias.name)
|
|
175
|
+
if target:
|
|
176
|
+
self.imported_symbols[local] = target
|
|
177
|
+
|
|
178
|
+
def _visit_callable(self, node: ast.AST, name: str) -> None:
|
|
179
|
+
self.parents.append(name)
|
|
180
|
+
self.generic_visit(node)
|
|
181
|
+
self.parents.pop()
|
|
182
|
+
|
|
183
|
+
def visit_ClassDef(self, node: ast.ClassDef) -> None:
|
|
184
|
+
self._visit_callable(node, node.name)
|
|
185
|
+
|
|
186
|
+
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
|
|
187
|
+
self._visit_callable(node, node.name)
|
|
188
|
+
|
|
189
|
+
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
|
|
190
|
+
self._visit_callable(node, node.name)
|
|
191
|
+
|
|
192
|
+
def visit_Call(self, node: ast.Call) -> None:
|
|
193
|
+
raw_name = _name_from_node(self.source, node.func)
|
|
194
|
+
target: str | None = None
|
|
195
|
+
if isinstance(node.func, ast.Name):
|
|
196
|
+
target = self.imported_symbols.get(node.func.id)
|
|
197
|
+
if target is None:
|
|
198
|
+
target = self._target_symbol(self.path, node.func.id)
|
|
199
|
+
if target is None and len(self.global_names.get(node.func.id, [])) == 1:
|
|
200
|
+
target = self.global_names[node.func.id][0]
|
|
201
|
+
elif isinstance(node.func, ast.Attribute):
|
|
202
|
+
if isinstance(node.func.value, ast.Name):
|
|
203
|
+
module_path = self.imported_modules.get(node.func.value.id)
|
|
204
|
+
if module_path:
|
|
205
|
+
target = self._target_symbol(module_path, node.func.attr)
|
|
206
|
+
if target is None and len(self.global_names.get(node.func.attr, [])) == 1:
|
|
207
|
+
target = self.global_names[node.func.attr][0]
|
|
208
|
+
if target and target != self._caller():
|
|
209
|
+
self.edges.append(Edge(
|
|
210
|
+
"calls", self._caller(), target, 0.9,
|
|
211
|
+
f"{self.path}:{node.lineno} call {raw_name}",
|
|
212
|
+
))
|
|
213
|
+
self.generic_visit(node)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
IMPORT_PATTERNS = (
|
|
217
|
+
re.compile(r"\bfrom\s+['\"]([^'\"]+)['\"]"),
|
|
218
|
+
re.compile(r"\brequire\(\s*['\"]([^'\"]+)['\"]\s*\)"),
|
|
219
|
+
re.compile(r"\bimport\s+['\"]([^'\"]+)['\"]"),
|
|
220
|
+
re.compile(r"#include\s*[\"<]([^\">]+)[\">]"),
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
# tree-sitter 调用边:非 Python 语言的 calls 关系。置信度固定 0.5——
|
|
224
|
+
# 名字解析只有「本文件唯一符号 / 全局唯一符号」两档,比 Python AST 弱。
|
|
225
|
+
TS_CALL_CONFIDENCE = 0.5
|
|
226
|
+
_CALL_NODE_TYPES = {
|
|
227
|
+
"call_expression", "call", "method_invocation", "method_call",
|
|
228
|
+
"function_call", "call_expr",
|
|
229
|
+
}
|
|
230
|
+
_MEMBER_CALL_TYPES = {
|
|
231
|
+
"member_expression", "field_access", "scoped_identifier",
|
|
232
|
+
"selector_expression", "attribute",
|
|
233
|
+
}
|
|
234
|
+
_SIMPLE_NAME_TYPES = {"identifier", "field_identifier", "property_identifier", "constant"}
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _ts_call_name(function_node: object) -> str | None:
|
|
238
|
+
"""从调用节点的 function 字段提取被调名;支持直接名与成员访问。"""
|
|
239
|
+
if function_node is None:
|
|
240
|
+
return None
|
|
241
|
+
node_type = function_node.type
|
|
242
|
+
if node_type in _SIMPLE_NAME_TYPES:
|
|
243
|
+
return function_node.text.decode("utf-8", errors="replace")
|
|
244
|
+
if node_type in _MEMBER_CALL_TYPES:
|
|
245
|
+
for field in ("property", "field", "attribute", "name"):
|
|
246
|
+
member = function_node.child_by_field_name(field)
|
|
247
|
+
if member is not None:
|
|
248
|
+
return member.text.decode("utf-8", errors="replace")
|
|
249
|
+
return None
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _tree_sitter_call_edges(path: str, source: str, language: str,
|
|
253
|
+
symbols_by_file: dict[str, list[dict]],
|
|
254
|
+
global_names: dict[str, list[str]]) -> list[Edge]:
|
|
255
|
+
"""tree-sitter 提取非 Python 语言的 calls 边;后端缺失时静默降级。
|
|
256
|
+
|
|
257
|
+
未安装 tree-sitter 时不产生 parse_errors(imports 边仍由
|
|
258
|
+
_generic_import_edges 提供,图保持 complete);只把统计写进 summary。
|
|
259
|
+
"""
|
|
260
|
+
try:
|
|
261
|
+
from tree_sitter_language_pack import get_parser
|
|
262
|
+
except ImportError:
|
|
263
|
+
return []
|
|
264
|
+
try:
|
|
265
|
+
tree = get_parser(language).parse(source.encode("utf-8"))
|
|
266
|
+
except Exception: # 语言包对个别语法抛出多种运行时异常
|
|
267
|
+
return []
|
|
268
|
+
local_symbols = symbols_by_file.get(path, [])
|
|
269
|
+
edges: list[Edge] = []
|
|
270
|
+
|
|
271
|
+
def enclosing_id(parents: list[str]) -> str:
|
|
272
|
+
return _symbol_id(path, ".".join(parents)) if parents else _file_id(path)
|
|
273
|
+
|
|
274
|
+
def resolve(name: str) -> str | None:
|
|
275
|
+
candidates = [
|
|
276
|
+
_symbol_id(path, item["qualified_name"])
|
|
277
|
+
for item in local_symbols if item["name"] == name
|
|
278
|
+
]
|
|
279
|
+
if len(candidates) == 1:
|
|
280
|
+
return candidates[0]
|
|
281
|
+
globals_for_name = global_names.get(name, [])
|
|
282
|
+
if len(globals_for_name) == 1:
|
|
283
|
+
return globals_for_name[0]
|
|
284
|
+
return None
|
|
285
|
+
|
|
286
|
+
def walk(node: object, parents: list[str]) -> None:
|
|
287
|
+
kind = symbol_index.TREE_SITTER_NODE_KINDS.get(node.type)
|
|
288
|
+
child_parents = parents
|
|
289
|
+
if kind:
|
|
290
|
+
direct = node.child_by_field_name("name")
|
|
291
|
+
if direct is not None:
|
|
292
|
+
name = direct.text.decode("utf-8", errors="replace")
|
|
293
|
+
child_parents = [*parents, name]
|
|
294
|
+
if node.type in _CALL_NODE_TYPES:
|
|
295
|
+
callee = _ts_call_name(node.child_by_field_name("function"))
|
|
296
|
+
if callee:
|
|
297
|
+
target = resolve(callee)
|
|
298
|
+
caller = enclosing_id(child_parents)
|
|
299
|
+
if target and target != caller:
|
|
300
|
+
edges.append(Edge(
|
|
301
|
+
"calls", caller, target, TS_CALL_CONFIDENCE,
|
|
302
|
+
f"{path} call {callee}",
|
|
303
|
+
))
|
|
304
|
+
for child in node.named_children:
|
|
305
|
+
walk(child, child_parents)
|
|
306
|
+
|
|
307
|
+
walk(tree.root_node, [])
|
|
308
|
+
return edges
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _generic_import_edges(path: str, source: str,
|
|
312
|
+
path_lookup: dict[str, str]) -> list[Edge]:
|
|
313
|
+
result: list[Edge] = []
|
|
314
|
+
for line_number, line in enumerate(source.splitlines(), 1):
|
|
315
|
+
for pattern in IMPORT_PATTERNS:
|
|
316
|
+
for match in pattern.finditer(line):
|
|
317
|
+
raw = match.group(1)
|
|
318
|
+
# Relative JS/TS imports are unambiguous. For C/C++/Go and
|
|
319
|
+
# similar languages also try local-looking paths; bare package
|
|
320
|
+
# names remain external dependencies and are not false edges.
|
|
321
|
+
if not (
|
|
322
|
+
raw.startswith(".")
|
|
323
|
+
or "/" in raw
|
|
324
|
+
or Path(raw).suffix.lower() in SOURCE_EXTENSIONS
|
|
325
|
+
):
|
|
326
|
+
continue
|
|
327
|
+
candidate = (Path(path).parent / raw).as_posix()
|
|
328
|
+
target = None
|
|
329
|
+
for normalized in _import_path_candidates(candidate):
|
|
330
|
+
target = path_lookup.get(normalized)
|
|
331
|
+
if target:
|
|
332
|
+
break
|
|
333
|
+
if target:
|
|
334
|
+
result.append(Edge(
|
|
335
|
+
"imports", _file_id(path), _file_id(target), 0.8,
|
|
336
|
+
f"{path}:{line_number} import {raw}",
|
|
337
|
+
))
|
|
338
|
+
return result
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _import_path_candidates(candidate: str) -> list[str]:
|
|
342
|
+
"""Resolve extensionless and explicitly extended relative imports."""
|
|
343
|
+
path = Path(candidate)
|
|
344
|
+
normalized = path.as_posix()
|
|
345
|
+
candidates = [normalized]
|
|
346
|
+
if path.suffix:
|
|
347
|
+
candidates.append(path.with_suffix("").as_posix())
|
|
348
|
+
else:
|
|
349
|
+
candidates.extend(f"{normalized}{extension}" for extension in SOURCE_EXTENSIONS)
|
|
350
|
+
candidates.extend(
|
|
351
|
+
f"{normalized}/index{extension}" for extension in SOURCE_EXTENSIONS
|
|
352
|
+
)
|
|
353
|
+
candidates.extend(
|
|
354
|
+
f"{normalized}/__init__{extension}" for extension in SOURCE_EXTENSIONS
|
|
355
|
+
)
|
|
356
|
+
return list(dict.fromkeys(candidates))
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def build_graph(root: Path, knowledge_graph: str = "auto", *,
|
|
360
|
+
cache: GraphPassCache | None = None) -> dict:
|
|
361
|
+
"""Build the repository relationship graph.
|
|
362
|
+
|
|
363
|
+
``cache`` is an optional per-pass cache. When supplied, source files are
|
|
364
|
+
read once and shared with ``symbol_index``, and a second request for the
|
|
365
|
+
same root within the pass returns the graph already built instead of
|
|
366
|
+
re-indexing the whole repository. Omitting it keeps the original
|
|
367
|
+
build-everything-fresh behaviour.
|
|
368
|
+
"""
|
|
369
|
+
root = root.resolve()
|
|
370
|
+
if cache is None:
|
|
371
|
+
cache = GraphPassCache()
|
|
372
|
+
else:
|
|
373
|
+
memoized = cache.graph(root, knowledge_graph)
|
|
374
|
+
if memoized is not None:
|
|
375
|
+
return memoized
|
|
376
|
+
try:
|
|
377
|
+
index = symbol_index.index_repository(root, strict=True, cache=cache.content)
|
|
378
|
+
except symbol_index.SourceDiscoveryError as exc:
|
|
379
|
+
raise GraphError(str(exc)) from exc
|
|
380
|
+
symbols_by_file = {
|
|
381
|
+
item["path"]: item["symbols"] for item in index["files"]
|
|
382
|
+
}
|
|
383
|
+
module_paths: dict[str, str] = {}
|
|
384
|
+
path_lookup: dict[str, str] = {}
|
|
385
|
+
global_names: dict[str, list[str]] = defaultdict(list)
|
|
386
|
+
for item in index["files"]:
|
|
387
|
+
path = item["path"]
|
|
388
|
+
for alias in _module_aliases(path):
|
|
389
|
+
module_paths.setdefault(alias, path)
|
|
390
|
+
stem = str(Path(path).with_suffix(""))
|
|
391
|
+
path_lookup.setdefault(path, path)
|
|
392
|
+
for candidate in (stem, f"{stem}/index", f"{stem}/__init__"):
|
|
393
|
+
path_lookup.setdefault(candidate, path)
|
|
394
|
+
for symbol in item["symbols"]:
|
|
395
|
+
global_names[symbol["name"]].append(
|
|
396
|
+
_symbol_id(path, symbol["qualified_name"])
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
edges = [
|
|
400
|
+
Edge(item["type"], item["from"], item["to"], 1.0, "symbol-index")
|
|
401
|
+
for item in index["edges"]
|
|
402
|
+
]
|
|
403
|
+
parse_errors: list[dict] = []
|
|
404
|
+
for item in index["files"]:
|
|
405
|
+
path = item["path"]
|
|
406
|
+
if item.get("error"):
|
|
407
|
+
parse_errors.append({"path": path, "error": item["error"]})
|
|
408
|
+
if item["language"] == "python":
|
|
409
|
+
try:
|
|
410
|
+
source = cache.content.read_text(root / path)
|
|
411
|
+
tree = ast.parse(source)
|
|
412
|
+
except (OSError, SyntaxError) as exc:
|
|
413
|
+
if not any(error["path"] == path for error in parse_errors):
|
|
414
|
+
parse_errors.append({"path": path, "error": str(exc)})
|
|
415
|
+
continue
|
|
416
|
+
visitor = _PythonRelations(
|
|
417
|
+
path, source, module_paths, symbols_by_file, global_names,
|
|
418
|
+
)
|
|
419
|
+
visitor.visit(tree)
|
|
420
|
+
edges.extend(visitor.edges)
|
|
421
|
+
else:
|
|
422
|
+
try:
|
|
423
|
+
source = cache.content.read_text(root / path)
|
|
424
|
+
except OSError as exc:
|
|
425
|
+
raise GraphError(f"关系图无法读取 {path}: {exc}") from exc
|
|
426
|
+
edges.extend(_generic_import_edges(path, source, path_lookup))
|
|
427
|
+
language = symbol_index.TREE_SITTER_LANGUAGES.get(
|
|
428
|
+
Path(path).suffix.lower(),
|
|
429
|
+
)
|
|
430
|
+
if language and source:
|
|
431
|
+
edges.extend(_tree_sitter_call_edges(
|
|
432
|
+
path, source, language, symbols_by_file, global_names,
|
|
433
|
+
))
|
|
434
|
+
|
|
435
|
+
unique: dict[tuple[str, str, str], Edge] = {}
|
|
436
|
+
for edge in edges:
|
|
437
|
+
key = (edge.type, edge.source, edge.target)
|
|
438
|
+
previous = unique.get(key)
|
|
439
|
+
if previous is None or edge.confidence > previous.confidence:
|
|
440
|
+
unique[key] = edge
|
|
441
|
+
relationship_edges = [edge for edge in unique.values() if edge.type != "contains"]
|
|
442
|
+
graph = {
|
|
443
|
+
"schema_version": SCHEMA_VERSION,
|
|
444
|
+
"root": ".",
|
|
445
|
+
"nodes": index["nodes"],
|
|
446
|
+
"edges": [asdict(edge) for edge in unique.values()],
|
|
447
|
+
"parse_errors": parse_errors,
|
|
448
|
+
"complete": not parse_errors,
|
|
449
|
+
"summary": {
|
|
450
|
+
"files": index["summary"]["files"],
|
|
451
|
+
"symbols": index["summary"]["symbols"],
|
|
452
|
+
"relationships": len(relationship_edges),
|
|
453
|
+
"calls": sum(edge.type == "calls" for edge in relationship_edges),
|
|
454
|
+
"imports": sum(edge.type == "imports" for edge in relationship_edges),
|
|
455
|
+
"parse_errors": len(parse_errors),
|
|
456
|
+
},
|
|
457
|
+
}
|
|
458
|
+
try:
|
|
459
|
+
graph = codebase_memory_bridge.augment_graph(
|
|
460
|
+
root, graph, mode=knowledge_graph,
|
|
461
|
+
)
|
|
462
|
+
except codebase_memory_bridge.KnowledgeGraphError as exc:
|
|
463
|
+
raise GraphError(str(exc)) from exc
|
|
464
|
+
relationship_edges = [
|
|
465
|
+
edge for edge in graph["edges"] if edge["type"] != "contains"
|
|
466
|
+
]
|
|
467
|
+
graph["summary"].update({
|
|
468
|
+
"relationships": len(relationship_edges),
|
|
469
|
+
"calls": sum(edge["type"] == "calls" for edge in relationship_edges),
|
|
470
|
+
"imports": sum(edge["type"] == "imports" for edge in relationship_edges),
|
|
471
|
+
})
|
|
472
|
+
cache.remember(root, knowledge_graph, graph)
|
|
473
|
+
return graph
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _node_path(node_id: str) -> str:
|
|
477
|
+
value = node_id.split(":", 1)[-1]
|
|
478
|
+
return value.split("::", 1)[0]
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _node_label(node_id: str) -> str:
|
|
482
|
+
"""Return the callable/file label, excluding its directory path."""
|
|
483
|
+
value = node_id.split("::", 1)[-1]
|
|
484
|
+
if "::" not in node_id:
|
|
485
|
+
value = Path(value).stem
|
|
486
|
+
return value.rsplit(".", 1)[-1]
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _has_keyword(node_id: str, words: set[str]) -> bool:
|
|
490
|
+
"""Match semantic name tokens, not arbitrary substrings in file paths."""
|
|
491
|
+
tokens = set(re.findall(r"[A-Za-z0-9]+", _node_label(node_id).lower()))
|
|
492
|
+
return bool(tokens & words)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def _file_sequence(nodes: list[str]) -> tuple[str, ...]:
|
|
496
|
+
"""Collapse intra-file helper hops while preserving cross-file order."""
|
|
497
|
+
sequence: list[str] = []
|
|
498
|
+
for node in nodes:
|
|
499
|
+
path = _node_path(node)
|
|
500
|
+
if not sequence or sequence[-1] != path:
|
|
501
|
+
sequence.append(path)
|
|
502
|
+
return tuple(sequence)
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _strongly_connected_components(nodes: set[str], adjacency: dict[str, list[dict]]) \
|
|
506
|
+
-> list[list[str]]:
|
|
507
|
+
index = 0
|
|
508
|
+
indices: dict[str, int] = {}
|
|
509
|
+
lowlinks: dict[str, int] = {}
|
|
510
|
+
stack: list[str] = []
|
|
511
|
+
on_stack: set[str] = set()
|
|
512
|
+
components: list[list[str]] = []
|
|
513
|
+
|
|
514
|
+
def visit(node: str) -> None:
|
|
515
|
+
nonlocal index
|
|
516
|
+
indices[node] = index
|
|
517
|
+
lowlinks[node] = index
|
|
518
|
+
index += 1
|
|
519
|
+
stack.append(node)
|
|
520
|
+
on_stack.add(node)
|
|
521
|
+
for edge in adjacency.get(node, []):
|
|
522
|
+
target = edge["target"]
|
|
523
|
+
if target not in indices:
|
|
524
|
+
visit(target)
|
|
525
|
+
lowlinks[node] = min(lowlinks[node], lowlinks[target])
|
|
526
|
+
elif target in on_stack:
|
|
527
|
+
lowlinks[node] = min(lowlinks[node], indices[target])
|
|
528
|
+
if lowlinks[node] == indices[node]:
|
|
529
|
+
component: list[str] = []
|
|
530
|
+
while True:
|
|
531
|
+
member = stack.pop()
|
|
532
|
+
on_stack.remove(member)
|
|
533
|
+
component.append(member)
|
|
534
|
+
if member == node:
|
|
535
|
+
break
|
|
536
|
+
components.append(component)
|
|
537
|
+
|
|
538
|
+
for node in sorted(nodes):
|
|
539
|
+
if node not in indices:
|
|
540
|
+
visit(node)
|
|
541
|
+
return components
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _discover_business_flows_with_coverage(graph: dict, max_depth: int = 6) \
|
|
545
|
+
-> tuple[list[dict], list[dict]]:
|
|
546
|
+
if max_depth < 2:
|
|
547
|
+
raise GraphError("flow max depth 必须至少为 2")
|
|
548
|
+
# Imports describe module availability, not an executed business step.
|
|
549
|
+
# Traversing them here multiplies otherwise valid call paths; imports stay
|
|
550
|
+
# in the graph for dependency analysis and incremental impact planning.
|
|
551
|
+
relations = [edge for edge in graph["edges"] if edge["type"] == "calls"]
|
|
552
|
+
adjacency: dict[str, list[dict]] = defaultdict(list)
|
|
553
|
+
indegree: dict[str, int] = defaultdict(int)
|
|
554
|
+
for edge in relations:
|
|
555
|
+
adjacency[edge["source"]].append(edge)
|
|
556
|
+
indegree[edge["target"]] += 1
|
|
557
|
+
all_nodes = set(adjacency)
|
|
558
|
+
all_nodes.update(edge["target"] for edge in relations)
|
|
559
|
+
components = _strongly_connected_components(all_nodes, adjacency)
|
|
560
|
+
starts = [
|
|
561
|
+
node for node in adjacency
|
|
562
|
+
if indegree[node] == 0 or _has_keyword(node, ENTRY_WORDS)
|
|
563
|
+
]
|
|
564
|
+
paths: list[tuple[list[str], list[dict]]] = []
|
|
565
|
+
for start in sorted(set(starts)):
|
|
566
|
+
queue: deque[tuple[list[str], list[dict]]] = deque([([start], [])])
|
|
567
|
+
while queue:
|
|
568
|
+
nodes, path_edges = queue.popleft()
|
|
569
|
+
current = nodes[-1]
|
|
570
|
+
outgoing = [edge for edge in adjacency.get(current, []) if edge["target"] not in nodes]
|
|
571
|
+
is_sink = _has_keyword(current, SINK_WORDS)
|
|
572
|
+
if path_edges and (is_sink or not outgoing or len(nodes) >= max_depth):
|
|
573
|
+
if len({_node_path(node) for node in nodes}) >= 2:
|
|
574
|
+
paths.append((nodes, path_edges))
|
|
575
|
+
continue
|
|
576
|
+
for edge in outgoing:
|
|
577
|
+
queue.append(([*nodes, edge["target"]], [*path_edges, edge]))
|
|
578
|
+
|
|
579
|
+
covered_nodes = {node for nodes, _ in paths for node in nodes}
|
|
580
|
+
fallback_components: set[int] = set()
|
|
581
|
+
for component_index, component in enumerate(components):
|
|
582
|
+
component_nodes = set(component)
|
|
583
|
+
if len(component) < 2 or component_nodes.issubset(covered_nodes):
|
|
584
|
+
continue
|
|
585
|
+
start = sorted(component)[0]
|
|
586
|
+
queue: deque[tuple[list[str], list[dict]]] = deque([([start], [])])
|
|
587
|
+
while queue:
|
|
588
|
+
nodes, path_edges = queue.popleft()
|
|
589
|
+
current = nodes[-1]
|
|
590
|
+
outgoing = [
|
|
591
|
+
edge for edge in adjacency.get(current, [])
|
|
592
|
+
if edge["target"] not in nodes and edge["target"] in component
|
|
593
|
+
]
|
|
594
|
+
if path_edges and (not outgoing or len(nodes) >= max_depth):
|
|
595
|
+
paths.append((nodes, path_edges))
|
|
596
|
+
fallback_components.add(component_index)
|
|
597
|
+
covered_nodes.update(component)
|
|
598
|
+
break
|
|
599
|
+
for edge in outgoing:
|
|
600
|
+
queue.append(([*nodes, edge["target"]], [*path_edges, edge]))
|
|
601
|
+
|
|
602
|
+
# Every path here is already a call path; import-only dependency chains
|
|
603
|
+
# remain available through the graph's imports edges, not coverage tasks.
|
|
604
|
+
# Business coverage is a cross-file concern. Function-level differences
|
|
605
|
+
# are already scheduled as internal units; making every call-path variant
|
|
606
|
+
# a separate business task causes combinatorial growth in real projects.
|
|
607
|
+
# Keep one representative for each file sequence, while the graph still
|
|
608
|
+
# retains every symbol-level call edge for evidence and impact analysis.
|
|
609
|
+
deduplicated: dict[tuple[str, ...], tuple[list[str], list[dict]]] = {}
|
|
610
|
+
for nodes, path_edges in paths:
|
|
611
|
+
file_sequence = _file_sequence(nodes)
|
|
612
|
+
previous = deduplicated.get(file_sequence)
|
|
613
|
+
rank = (
|
|
614
|
+
sum(edge["type"] == "calls" for edge in path_edges),
|
|
615
|
+
len(nodes),
|
|
616
|
+
min(edge["confidence"] for edge in path_edges),
|
|
617
|
+
)
|
|
618
|
+
previous_rank = (-1, -1, -1.0) if previous is None else (
|
|
619
|
+
sum(edge["type"] == "calls" for edge in previous[1]),
|
|
620
|
+
len(previous[0]),
|
|
621
|
+
min(edge["confidence"] for edge in previous[1]),
|
|
622
|
+
)
|
|
623
|
+
if rank > previous_rank:
|
|
624
|
+
deduplicated[file_sequence] = (nodes, path_edges)
|
|
625
|
+
result = []
|
|
626
|
+
for index, (_, (nodes, path_edges)) in enumerate(sorted(deduplicated.items()), 1):
|
|
627
|
+
result.append({
|
|
628
|
+
"id": f"B{index:03d}",
|
|
629
|
+
"participants": nodes,
|
|
630
|
+
"files": list(_file_sequence(nodes)),
|
|
631
|
+
"edge_types": [edge["type"] for edge in path_edges],
|
|
632
|
+
"confidence": round(min(edge["confidence"] for edge in path_edges), 2),
|
|
633
|
+
"evidence": [edge["evidence"] for edge in path_edges],
|
|
634
|
+
})
|
|
635
|
+
uncovered = []
|
|
636
|
+
for component_index, component in enumerate(components):
|
|
637
|
+
if component_index in fallback_components or set(component).issubset(covered_nodes):
|
|
638
|
+
continue
|
|
639
|
+
uncovered.append({
|
|
640
|
+
"id": f"U{len(uncovered) + 1:03d}",
|
|
641
|
+
"nodes": sorted(component),
|
|
642
|
+
"files": list(dict.fromkeys(_node_path(node) for node in sorted(component))),
|
|
643
|
+
"reason": "no-entry-or-flow-path",
|
|
644
|
+
})
|
|
645
|
+
return result, uncovered
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def discover_business_flows(graph: dict, max_depth: int = 6) -> list[dict]:
|
|
649
|
+
"""Return business flows, preserving the historical list return type."""
|
|
650
|
+
flows, _ = _discover_business_flows_with_coverage(graph, max_depth)
|
|
651
|
+
return flows
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
def discover_business_flows_with_coverage(graph: dict, max_depth: int = 6) -> dict:
|
|
655
|
+
flows, uncovered = _discover_business_flows_with_coverage(graph, max_depth)
|
|
656
|
+
return {"flows": flows, "uncovered_components": uncovered}
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def _git_change_details(root: Path, base: str) -> list[dict[str, str]]:
|
|
660
|
+
try:
|
|
661
|
+
result = subprocess.run(
|
|
662
|
+
["git", "diff", "--name-status", "-M", base, "--"], cwd=root,
|
|
663
|
+
capture_output=True, text=True, timeout=30, check=False,
|
|
664
|
+
)
|
|
665
|
+
except OSError as exc:
|
|
666
|
+
raise GraphError(f"无法运行 git: {exc}") from exc
|
|
667
|
+
if result.returncode != 0:
|
|
668
|
+
raise GraphError(result.stderr.strip() or f"git diff {base} 失败")
|
|
669
|
+
changes: dict[str, dict[str, str]] = {}
|
|
670
|
+
for line in result.stdout.splitlines():
|
|
671
|
+
fields = line.split("\t")
|
|
672
|
+
if len(fields) < 2:
|
|
673
|
+
continue
|
|
674
|
+
status = fields[0]
|
|
675
|
+
if status.startswith(("R", "C")) and len(fields) >= 3:
|
|
676
|
+
old_path, new_path = fields[1].strip(), fields[2].strip()
|
|
677
|
+
changes[new_path] = {
|
|
678
|
+
"status": "renamed" if status.startswith("R") else "copied",
|
|
679
|
+
"path": new_path,
|
|
680
|
+
"old_path": old_path,
|
|
681
|
+
}
|
|
682
|
+
else:
|
|
683
|
+
path = fields[-1].strip()
|
|
684
|
+
status_name = {
|
|
685
|
+
"A": "added", "M": "modified", "D": "deleted",
|
|
686
|
+
"T": "type_changed", "U": "unmerged",
|
|
687
|
+
}.get(status[:1], status[:1].lower())
|
|
688
|
+
changes[path] = {"status": status_name, "path": path}
|
|
689
|
+
try:
|
|
690
|
+
untracked = subprocess.run(
|
|
691
|
+
["git", "ls-files", "--others", "--exclude-standard"], cwd=root,
|
|
692
|
+
capture_output=True, text=True, timeout=30, check=False,
|
|
693
|
+
)
|
|
694
|
+
except OSError as exc:
|
|
695
|
+
raise GraphError(f"无法运行 git: {exc}") from exc
|
|
696
|
+
if untracked.returncode != 0:
|
|
697
|
+
raise GraphError(untracked.stderr.strip() or "git ls-files 失败")
|
|
698
|
+
for line in untracked.stdout.splitlines():
|
|
699
|
+
path = line.strip()
|
|
700
|
+
if path:
|
|
701
|
+
changes.setdefault(path, {"status": "added", "path": path})
|
|
702
|
+
return [changes[path] for path in sorted(changes)]
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def changed_paths(root: Path, base: str) -> list[str]:
|
|
706
|
+
"""Return current and removed paths changed from ``base``."""
|
|
707
|
+
details = _git_change_details(root, base)
|
|
708
|
+
paths = {item["path"] for item in details}
|
|
709
|
+
paths.update(item["old_path"] for item in details if item.get("old_path"))
|
|
710
|
+
return sorted(paths)
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def incremental_plan(root: Path, base: str, depth: int = 2) -> dict:
|
|
714
|
+
root = root.resolve()
|
|
715
|
+
# One pass cache for the whole plan: build_graph, audit_units and
|
|
716
|
+
# inventory_snapshot all walk the same repository, so sharing the content
|
|
717
|
+
# cache turns three full re-reads into a single read per file.
|
|
718
|
+
cache = GraphPassCache()
|
|
719
|
+
graph = build_graph(root, cache=cache)
|
|
720
|
+
if not graph["complete"]:
|
|
721
|
+
raise GraphError(
|
|
722
|
+
"项目关系图不完整,拒绝生成增量计划: "
|
|
723
|
+
+ "; ".join(
|
|
724
|
+
f"{item['path']}: {item['error']}" for item in graph["parse_errors"][:5]
|
|
725
|
+
)
|
|
726
|
+
)
|
|
727
|
+
change_details = _git_change_details(root, base)
|
|
728
|
+
changed = sorted({item["path"] for item in change_details} | {
|
|
729
|
+
item["old_path"] for item in change_details if item.get("old_path")
|
|
730
|
+
})
|
|
731
|
+
changed_set = set(changed)
|
|
732
|
+
relations = [edge for edge in graph["edges"] if edge["type"] in {"calls", "imports"}]
|
|
733
|
+
neighbors: dict[str, set[str]] = defaultdict(set)
|
|
734
|
+
for edge in relations:
|
|
735
|
+
source_path = _node_path(edge["source"])
|
|
736
|
+
target_path = _node_path(edge["target"])
|
|
737
|
+
neighbors[source_path].add(target_path)
|
|
738
|
+
neighbors[target_path].add(source_path)
|
|
739
|
+
impacted = set(changed_set)
|
|
740
|
+
frontier = set(changed_set)
|
|
741
|
+
for _ in range(max(depth, 0)):
|
|
742
|
+
frontier = {target for source in frontier for target in neighbors.get(source, set())} - impacted
|
|
743
|
+
impacted.update(frontier)
|
|
744
|
+
units = []
|
|
745
|
+
try:
|
|
746
|
+
audit_units = symbol_index.audit_units(root, strict=True, cache=cache.content)
|
|
747
|
+
except symbol_index.SourceDiscoveryError as exc:
|
|
748
|
+
raise GraphError(str(exc)) from exc
|
|
749
|
+
for asset in symbol_index.discover_asset_paths(root, strict=True):
|
|
750
|
+
relative = asset.relative_to(root).as_posix()
|
|
751
|
+
audit_units.append({
|
|
752
|
+
"scope": relative, "path": relative, "name": asset.name,
|
|
753
|
+
"kind": "asset", "line": 1, "end_line": 1,
|
|
754
|
+
"parser": "asset-inventory", "error": None,
|
|
755
|
+
"content_hash": symbol_index.file_sha256(asset, cache=cache.content),
|
|
756
|
+
"language": "asset",
|
|
757
|
+
})
|
|
758
|
+
for unit in audit_units:
|
|
759
|
+
path = unit["path"]
|
|
760
|
+
if path not in impacted:
|
|
761
|
+
continue
|
|
762
|
+
score = 100 if path in changed_set else 60
|
|
763
|
+
score += 10 if any(word in unit["name"].lower() for word in ENTRY_WORDS | SINK_WORDS) else 0
|
|
764
|
+
units.append({**unit, "priority": score, "reason": (
|
|
765
|
+
"changed" if path in changed_set else "dependency-impact"
|
|
766
|
+
)})
|
|
767
|
+
units.sort(key=lambda item: (-item["priority"], item["scope"]))
|
|
768
|
+
inventory = symbol_index.inventory_snapshot(root, cache=cache.content)
|
|
769
|
+
return {
|
|
770
|
+
"schema_version": SCHEMA_VERSION,
|
|
771
|
+
"base": base,
|
|
772
|
+
"changed_paths": changed,
|
|
773
|
+
"changes": change_details,
|
|
774
|
+
"impacted_paths": sorted(impacted),
|
|
775
|
+
"units": units,
|
|
776
|
+
"inventory_hash": inventory["inventory_hash"],
|
|
777
|
+
"full_coverage_required": True,
|
|
778
|
+
"note": "增量计划只改变优先顺序,不替代最终全量覆盖门禁",
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def main(argv: list[str] | None = None) -> int:
|
|
783
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
784
|
+
parser.add_argument("command", choices=("scan", "flows", "incremental"),
|
|
785
|
+
nargs="?", default="scan")
|
|
786
|
+
parser.add_argument("--root", type=Path, default=Path.cwd())
|
|
787
|
+
parser.add_argument("--base", default="HEAD~1")
|
|
788
|
+
parser.add_argument("--depth", type=int, default=2)
|
|
789
|
+
parser.add_argument("--max-depth", type=int, default=6)
|
|
790
|
+
parser.add_argument("--json", action="store_true")
|
|
791
|
+
parser.add_argument("--strict", action="store_true")
|
|
792
|
+
parser.add_argument(
|
|
793
|
+
"--knowledge-graph", choices=("auto", "off", "on", "required"),
|
|
794
|
+
default="auto",
|
|
795
|
+
help="用 codebase-memory 增强调用关系;auto 仅在启动探针通过后启用",
|
|
796
|
+
)
|
|
797
|
+
args = parser.parse_args(argv)
|
|
798
|
+
try:
|
|
799
|
+
graph = build_graph(args.root, knowledge_graph=args.knowledge_graph)
|
|
800
|
+
if args.command == "flows":
|
|
801
|
+
payload = {"schema_version": SCHEMA_VERSION,
|
|
802
|
+
**discover_business_flows_with_coverage(graph, args.max_depth)}
|
|
803
|
+
elif args.command == "incremental":
|
|
804
|
+
payload = incremental_plan(args.root, args.base, args.depth)
|
|
805
|
+
else:
|
|
806
|
+
payload = graph
|
|
807
|
+
if args.json:
|
|
808
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
809
|
+
elif args.command == "scan":
|
|
810
|
+
print(
|
|
811
|
+
f"[project_graph] 文件 {graph['summary']['files']},符号 "
|
|
812
|
+
f"{graph['summary']['symbols']},关系 {graph['summary']['relationships']}"
|
|
813
|
+
)
|
|
814
|
+
else:
|
|
815
|
+
items = payload.get("flows", payload.get("units", []))
|
|
816
|
+
for item in items:
|
|
817
|
+
print(json.dumps(item, ensure_ascii=False))
|
|
818
|
+
if graph["summary"]["parse_errors"]:
|
|
819
|
+
return 1
|
|
820
|
+
return 0
|
|
821
|
+
except GraphError as exc:
|
|
822
|
+
print(f"[project_graph] ✗ {exc}", file=sys.stderr)
|
|
823
|
+
return 2
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
if __name__ == "__main__":
|
|
827
|
+
raise SystemExit(main())
|