bugx-cli 0.1.0 → 0.1.2
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/README.md +193 -185
- package/core/README.md +2 -2
- package/core/agent/README.md +2 -1
- package/core/agent/agent_artifacts.py +8 -6
- package/core/agent/agent_eval.py +136 -54
- package/core/agent/agent_execution.py +218 -52
- package/core/agent/agent_orchestrator.py +14 -8
- package/core/agent/agent_targets.py +8 -2
- package/core/agent/feature_baseline.py +150 -0
- package/core/assets/README.md +3 -2
- 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-hero-en.svg +74 -0
- package/core/assets/bugx-hero-zh.svg +74 -0
- package/core/assets/bugx-social-preview.svg +71 -0
- package/core/assets/bugx-wechat-group.png +0 -0
- package/core/assets/codex.png +0 -0
- package/core/assets/dsh.png +0 -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 +2 -0
- package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
- package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
- package/core/audit_packs/pitfalls/go_backend.json +66 -0
- package/core/audit_packs/pitfalls/java_spring.json +64 -0
- package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
- package/core/audit_packs/pitfalls/python_web.json +82 -0
- package/core/autonomous_cve/SPEC.md +1 -1
- package/core/autonomous_cve/attack_graph_store.py +152 -106
- package/core/autonomous_cve/behavior_graph.py +8 -2
- package/core/autonomous_cve/verifier.py +4 -1
- package/core/bugx.md +1 -1
- package/core/bugx_paths.py +43 -8
- package/core/cli-help.txt +66 -0
- package/core/cloud_sync/SPEC.md +1 -1
- package/core/cloud_sync/cloud_client.py +81 -11
- package/core/cloud_sync/cloud_onboard.py +42 -1
- package/core/cloud_sync/consent.py +33 -3
- package/core/cloud_sync/flywheel_client.py +186 -15
- package/core/cloud_sync/network_transport.py +24 -3
- package/core/cloud_sync/sensitive_filter.py +2 -2
- package/core/cloud_sync/sync_push.py +12 -10
- package/core/contracts/AGENT_GUIDE.md +6 -9
- package/core/contracts/README.md +2 -2
- package/core/contracts/bugx-runtime-contract.md +1 -1
- package/core/contracts/bugx-worker.md +1 -1
- package/core/contracts/engine_gap_contracts.py +86 -3
- package/core/coverage/coverage_discovery.py +599 -29
- package/core/coverage/coverage_evidence.py +47 -0
- package/core/coverage/coverage_forensics.py +9 -0
- package/core/coverage/coverage_validate.py +6 -1
- package/core/dev_harness/SPEC.md +1 -1
- package/core/engine-integrity.json +670 -442
- package/core/fuzzing/concurrency_fuzzer.py +53 -0
- package/core/fuzzing/differential_oracle.py +562 -27
- package/core/fuzzing/fuzz_input.py +109 -6
- package/core/fuzzing/stateful_fuzzer.py +72 -0
- package/core/governance/secret_redactor.py +22 -10
- package/core/host_acp/SPEC.md +1 -1
- package/core/host_acp/__init__.py +4 -4
- package/core/host_acp/claude.py +59 -1
- package/core/host_acp/cline.py +64 -1
- package/core/host_acp/codex.py +56 -1
- package/core/host_acp/dsh.py +59 -1
- package/core/host_acp/opencode.py +56 -1
- package/core/host_acp/pi.py +59 -1
- package/core/host_acp/zcode.py +59 -1
- package/core/host_runtime/SPEC.md +1 -1
- package/core/host_runtime/adapters.py +1 -1
- package/core/host_runtime/cline.py +13 -0
- package/core/host_runtime/host_evaluators.py +44 -4
- package/core/host_runtime/host_probe.py +1 -1
- package/core/host_runtime/host_provider_arbitrator.py +116 -62
- package/core/host_runtime/host_registry.py +15 -8
- package/core/host_runtime/mcp_registry_gate.py +12 -1
- package/core/host_runtime/pi.py +102 -0
- package/core/host_runtime/provider_facts.py +66 -0
- package/core/hosts/SPEC.md +1 -1
- package/core/hosts/__init__.py +6 -2
- package/core/hosts/_dsh_usage.py +1 -1
- package/core/hosts/base.py +32 -4
- package/core/hosts/claude.py +55 -0
- package/core/hosts/cline.py +6 -2
- package/core/hosts/codex.py +58 -0
- package/core/hosts/dsh.py +9 -1
- package/core/hosts/opencode.py +6 -6
- package/core/hosts/pi.py +159 -2
- package/core/infra/README.md +4 -2
- package/core/infra/__init__.py +2 -0
- package/core/infra/build_info.py +22 -3
- package/core/infra/client_metadata.py +1 -1
- package/core/infra/json_utils.py +22 -0
- package/core/launch_phases/README.md +6 -3
- package/core/launch_phases/SPEC.md +1 -1
- package/core/launch_phases/common.py +21 -2
- package/core/launch_phases/finding_confirm_phase.py +170 -5
- package/core/launch_phases/finding_settlement.py +188 -1
- package/core/launch_phases/judge_phase.py +69 -12
- package/core/launch_phases/orchestrator_controls.py +11 -7
- package/core/launch_phases/post_coverage_sync.py +9 -2
- package/core/launch_phases/post_phase.py +144 -8
- package/core/launch_phases/post_receipt.py +12 -1
- package/core/launch_phases/pre_phase.py +3 -3
- package/core/launch_phases/pre_recon_scout.py +66 -36
- package/core/launch_phases/pre_state_builder.py +23 -176
- package/core/launch_phases/report_sharing.py +3 -7
- package/core/launch_phases/round_orchestrator.py +129 -58
- package/core/launch_phases/semantic_recon.py +545 -0
- package/core/launch_phases/session_runtime.py +56 -9
- package/core/launch_phases/startup_gates.py +36 -8
- package/core/launch_phases/startup_interaction.py +68 -12
- package/core/launch_phases/startup_version_gate.py +13 -3
- package/core/launch_phases/supervisor_bridge.py +46 -17
- package/core/launch_phases/supervisor_coverage.py +8 -2
- package/core/launch_phases/supervisor_degraded.py +1 -9
- package/core/launch_phases/verify_loop.py +767 -0
- package/core/launch_phases/worker_barriers.py +15 -5
- package/core/launch_phases/worker_orchestrator.py +105 -25
- package/core/launch_phases/worker_prior.py +115 -0
- package/core/ledger/README.md +2 -1
- package/core/ledger/SPEC.md +1 -1
- package/core/ledger/_facade.py +2 -1
- package/core/ledger/archive_ops.py +60 -2
- package/core/ledger/cli.py +6 -1
- package/core/ledger/export_ops.py +6 -1
- package/core/ledger/finding_confirmation.py +48 -6
- package/core/ledger/finding_lifecycle.py +428 -5
- package/core/ledger/finding_verification.py +555 -10
- package/core/ledger/fp_ledger.py +255 -0
- package/core/ledger/incidents.py +10 -4
- package/core/ledger/patterns.py +10 -7
- package/core/ledger/receipt_contract.py +17 -1
- package/core/ledger/sync_ops.py +21 -16
- package/core/ledger/tool_experience.py +2 -1
- package/core/ledger/verify_life.py +88 -17
- package/core/locales/en-US.json +2 -2
- package/core/locales/zh-CN.json +2 -2
- package/core/mcp_handlers/SPEC.md +1 -1
- package/core/mcp_handlers/base.py +23 -3
- package/core/mcp_handlers/channel_lifecycle.py +85 -30
- package/core/mcp_handlers/retrieval_handlers.py +11 -1
- package/core/mcp_handlers/rpc_server.py +6 -1
- package/core/mcp_handlers/supervisor_handlers.py +32 -6
- package/core/mcp_handlers/tool_table.py +15 -0
- package/core/mcp_runtime_support/environment.py +0 -38
- package/core/mcp_runtime_support/verifier.py +0 -52
- package/core/metadata.txt +2 -3
- package/core/planning/README.md +2 -1
- package/core/planning/domain_router.py +4 -2
- package/core/planning/dynamic_flow_analyzer.py +219 -14
- package/core/planning/judge_pipeline.py +87 -4
- package/core/planning/prompt_harness.py +57 -15
- package/core/planning/prompt_policy_engine.py +386 -0
- package/core/planning/spec_harvester.py +4 -4
- package/core/probes/INTERFACE.md +11 -1
- package/core/probes/SPEC.md +11 -1
- package/core/probes/__init__.py +46 -40
- package/core/probes/android_probe.py +177 -9
- package/core/probes/codebase_memory_probe.py +57 -0
- package/core/probes/desktop_probe.py +104 -0
- package/core/probes/differential_probe.py +99 -21
- package/core/probes/efficiency_probe.py +64 -0
- package/core/probes/ios_binary_probe.py +105 -1
- package/core/probes/memory_probe.py +66 -0
- package/core/probes/miniprogram_probe.py +75 -13
- package/core/probes/mobile_probe.py +215 -30
- package/core/probes/native_probe.py +88 -0
- package/core/probes/openwiki_probe.py +70 -0
- package/core/probes/pattern_probe.py +106 -0
- package/core/probes/platform_probe.py +81 -0
- package/core/probes/probe_registry.py +108 -7
- package/core/probes/sast_fixture_corpus.py +340 -0
- package/core/probes/sast_probe.py +553 -52
- package/core/probes/sast_rules.py +668 -28
- package/core/probes/sca_scanner.py +48 -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 +373 -18
- package/core/project_profiler/SPEC.md +1 -1
- package/core/project_profiler/arbitrator.py +6 -1
- package/core/project_profiler/detector.py +8 -1
- package/core/project_profiler/strategy.py +51 -15
- package/core/prompts/README.md +4 -2
- package/core/prompts/command_routing_en.md +2 -2
- package/core/prompts/command_routing_zh.md +2 -2
- package/core/prompts/policies/prompt_policies.json +101 -0
- package/core/prompts/stages/stage_repair.md +1 -1
- package/core/prompts/stages/stage_verify.defensive.md +42 -0
- package/core/prompts/stages/stage_verify.md +44 -0
- package/core/repair/README.md +1 -1
- package/core/repair/l7_repair_loop.py +1 -4
- package/core/repair/rsi_fixer.py +4 -4
- package/core/repair/rsi_loop.py +1 -3
- package/core/repair/rsi_repair.py +7 -7
- package/core/repair/rsi_scope.py +27 -8
- package/core/report_engine/SPEC.md +1 -1
- package/core/report_engine/attestation.py +8 -4
- package/core/report_engine/finding_report.py +2 -1
- package/core/report_engine/models.py +7 -9
- package/core/report_engine/report_share.py +0 -8
- package/core/report_engine/sast_bridge.py +2 -2
- package/core/report_engine/server.py +18 -8
- package/core/report_engine/web-conformance.md +123 -18
- package/core/report_engine/web_conformance.py +21 -52
- package/core/retrieval/README.md +2 -1
- package/core/retrieval/SPEC.md +1 -1
- package/core/retrieval/code_analyzer.py +50 -14
- package/core/retrieval/context_assembler.py +7 -1
- package/core/retrieval/knowledge_sync.py +108 -14
- package/core/retrieval/pitfall_packs.py +277 -0
- package/core/retrieval/symbol_index.py +25 -6
- package/core/retrieval/universal_code_matcher.py +234 -49
- package/core/runtime/README.md +1 -1
- package/core/runtime/bugx_logging.py +78 -7
- package/core/runtime/fixture_solidify.py +5 -10
- package/core/runtime/global_telemetry.py +20 -0
- package/core/runtime/incident_eval.py +1 -1
- package/core/runtime/model_runner.py +4 -41
- package/core/runtime/platform_adapter.py +2 -2
- package/core/runtime/prep_validate.py +4 -2
- package/core/runtime/project_settings.py +2 -1
- package/core/runtime/scenario_eval.py +50 -8
- package/core/skills/bugx_docs_mcp_server.py +3 -1
- package/core/skills/bugx_mcp_server.py +29 -2
- package/core/skills/tools_kb.py +1 -1
- package/core/supervisor/README.md +1 -1
- package/core/supervisor/SPEC.md +1 -1
- package/core/supervisor/budget_governor.py +503 -9
- package/core/supervisor/checkpoint_pipeline.py +248 -6
- package/core/supervisor/checkpoint_sync.py +13 -0
- package/core/supervisor/claim_events.py +1 -1
- package/core/supervisor/finding_workflow.py +22 -5
- package/core/supervisor/lease_manager.py +1 -1
- package/core/supervisor/lifecycle_blocks.py +6 -1
- package/core/supervisor/rejection_remedies.py +52 -5
- package/core/supervisor/serial_authorization.py +48 -4
- package/core/supervisor/task_scheduler.py +2 -2
- package/core/supervisor/worker_checkpoint.py +8 -1
- package/core/supervisor/worker_runtime.py +8 -2
- package/core/supervisor_types/worker_claim.py +9 -0
- package/core/webui/README.md +1 -1
- package/core/webui/SPEC.md +2 -1
- package/core/webui/adapters/claude.py +5 -1
- package/core/webui/adapters/cline.py +10 -2
- package/core/webui/adapters/codex.py +5 -1
- package/core/webui/adapters/dsh.py +5 -1
- package/core/webui/docs_session_service.py +2 -2
- package/core/webui/mcp_inspector.py +11 -7
- 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/design-tokens.css +113 -0
- package/core/webui/static/index.html +14 -1
- package/core/webui/workspace_service.py +1 -1
- package/docs/07_distribution/01_README_NPM.md +193 -185
- package/ecosystem/integrations/README.md +1 -1
- package/ecosystem/integrations/dsh/mcp/package.json +1 -1
- package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
- package/ecosystem/integrations/dsh/ui/package.json +1 -1
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
- package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
- package/ecosystem/integrations/opencode/opencode.json +23 -12
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
- package/ecosystem/integrations/qoder/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
- package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
- package/interfaces/bin/bugx.js +37 -0
- package/interfaces/cli/bugx_cli/__init__.py +4 -2
- package/interfaces/cli/bugx_cli/cli.py +172 -69
- package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
- package/interfaces/cli/bugx_cli/commands/agent.py +461 -134
- package/interfaces/cli/bugx_cli/commands/audit.py +10 -9
- package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
- package/interfaces/cli/bugx_cli/commands/cloud.py +31 -22
- package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
- package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
- package/interfaces/cli/bugx_cli/commands/knowledge.py +5 -4
- package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
- package/interfaces/cli/bugx_cli/commands/plugin.py +58 -23
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
- package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
- package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
- package/interfaces/cli/bugx_cli/commands/project.py +6 -13
- package/interfaces/cli/bugx_cli/commands/report.py +2 -6
- package/interfaces/cli/bugx_cli/commands/system.py +524 -169
- package/interfaces/cli/bugx_cli/common.py +21 -15
- package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
- package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
- package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +35 -16
- package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
- package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
- package/interfaces/cli/bugx_cli/infra/security.py +13 -6
- package/package.json +30 -15
- package/pyproject.toml +60 -9
- package/scripts/ensure-python.mjs +7 -7
- package/scripts/sync-version.mjs +10 -21
- package/scripts/test-npm-wrapper.mjs +1 -1
- package/core/assets/bugx-hero-cn.png +0 -0
- package/core/assets/bugx-hero-en.png +0 -0
- package/core/webui/static/project-settings.css +0 -6458
- package/docs/07_distribution/README.md +0 -16
- package/docs/README.md +0 -121
- package/interfaces/README.md +0 -143
- package/interfaces/bin/README.md +0 -35
- package/interfaces/cli/README.md +0 -90
- package/scripts/README.md +0 -118
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""core/launch_phases/semantic_recon.py — Recon 阶段轻量语义侦察叠加层(P2 / T-006)。
|
|
3
|
+
|
|
4
|
+
在确定性静态图谱之上叠加三类高价值语义资产,严格遵守零外部依赖与非受信输入隔离:
|
|
5
|
+
1. ``implicit_routes``:动态分发、插件注册表、RPC/装饰器工厂等隐式入口路由;
|
|
6
|
+
2. ``auth_boundaries``:自定义鉴权中间件、装饰器、租户隔离与信任域切换点;
|
|
7
|
+
3. ``business_invariants``:状态机合法迁移、金额/库存守恒、幂等键等业务不变量。
|
|
8
|
+
|
|
9
|
+
核心门禁:
|
|
10
|
+
- 物理锚点核验:拒绝不存在文件、越界路径(``..``)、符号链接穿越及超界行号;
|
|
11
|
+
- 反提示词注入净化:剥离控制字符、截断 ≤200 字符、拦截典型 prompt-injection 载荷;
|
|
12
|
+
- 文件级 SHA-256 哈希绑定:目标源码一旦修改,该文件的过期语义自动过滤失效。
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import ast
|
|
18
|
+
import hashlib
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import tempfile
|
|
23
|
+
import time
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any, Callable, Mapping, Sequence
|
|
26
|
+
|
|
27
|
+
OVERLAY_SCHEMA_VERSION = 1
|
|
28
|
+
MAX_FIELD_CHARS = 200
|
|
29
|
+
MAX_CONTEXT_FILES = 24
|
|
30
|
+
MAX_CONTEXT_CHARS = 12000
|
|
31
|
+
|
|
32
|
+
_SKIP_DIRS = frozenset({
|
|
33
|
+
".git", ".bugx", "node_modules", "__pycache__", ".venv", "venv",
|
|
34
|
+
"dist", "build", ".next", "target", ".pytest_cache",
|
|
35
|
+
})
|
|
36
|
+
_CODE_SUFFIXES = frozenset({".py", ".js", ".ts", ".jsx", ".tsx", ".go", ".java", ".kt"})
|
|
37
|
+
_PRIORITY_KEYWORDS = (
|
|
38
|
+
"route", "router", "dispatch", "handler", "middleware", "auth", "guard",
|
|
39
|
+
"permission", "rbac", "tenant", "order", "payment", "billing", "balance",
|
|
40
|
+
"state", "workflow", "webhook", "rpc", "plugin",
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
_INJECTION_PATTERNS: tuple[re.Pattern[str], ...] = (
|
|
44
|
+
re.compile(r"(?i)ignore\s+(?:all\s+)?(?:previous|above|prior)\s+instructions?"),
|
|
45
|
+
re.compile(r"(?i)disregard\s+(?:all\s+)?(?:previous|prior)\s+instructions?"),
|
|
46
|
+
re.compile(r"(?i)you\s+are\s+now\s+(?:a|an|in)\s+"),
|
|
47
|
+
re.compile(r"(?i)</?(?:system|assistant|user|instruction|prompt)\b[^>]*>"),
|
|
48
|
+
re.compile(r"(?i)^\s*system\s*:"),
|
|
49
|
+
re.compile(r"(?i)mark\s+all\s+(?:findings|vulnerabilities|issues)\s+(?:as\s+)?safe"),
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def overlay_path(root: Path) -> Path:
|
|
54
|
+
return Path(root).resolve() / ".bugx" / "state" / "semantic-recon-overlay.json"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _sha256_bytes(data: bytes) -> str:
|
|
58
|
+
return hashlib.sha256(data).hexdigest()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _atomic_write_json(path: Path, payload: Mapping[str, Any]) -> None:
|
|
62
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
63
|
+
raw = json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True).encode("utf-8")
|
|
64
|
+
fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
|
|
65
|
+
try:
|
|
66
|
+
os.fchmod(fd, 0o600)
|
|
67
|
+
with os.fdopen(fd, "wb") as handle:
|
|
68
|
+
handle.write(raw)
|
|
69
|
+
handle.flush()
|
|
70
|
+
os.fsync(handle.fileno())
|
|
71
|
+
os.replace(tmp_name, path)
|
|
72
|
+
except BaseException:
|
|
73
|
+
try:
|
|
74
|
+
os.close(fd)
|
|
75
|
+
except OSError:
|
|
76
|
+
pass
|
|
77
|
+
try:
|
|
78
|
+
os.unlink(tmp_name)
|
|
79
|
+
except OSError:
|
|
80
|
+
pass
|
|
81
|
+
raise
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _sanitize_text(value: object, *, max_len: int = MAX_FIELD_CHARS) -> tuple[str, bool]:
|
|
85
|
+
"""Strip control chars, bound length, and neutralize prompt-injection payloads."""
|
|
86
|
+
raw = re.sub(r"[\x00-\x1f\x7f]+", " ", str(value or "")).strip()
|
|
87
|
+
injected = False
|
|
88
|
+
for pattern in _INJECTION_PATTERNS:
|
|
89
|
+
if pattern.search(raw):
|
|
90
|
+
raw = pattern.sub("[REDACTED_INJECTION]", raw)
|
|
91
|
+
injected = True
|
|
92
|
+
if len(raw) > max_len:
|
|
93
|
+
raw = raw[:max_len].rstrip()
|
|
94
|
+
return raw, injected
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _resolve_anchor(root: Path, rel_file: object, line: object) -> tuple[str, int, str] | None:
|
|
98
|
+
"""Physically verify file exists inside root (no traversal/symlink) and line is in bounds."""
|
|
99
|
+
if not isinstance(rel_file, str) or not rel_file.strip():
|
|
100
|
+
return None
|
|
101
|
+
if isinstance(line, bool) or not isinstance(line, int) or line < 1:
|
|
102
|
+
return None
|
|
103
|
+
candidate = Path(rel_file.replace("\\", "/").strip())
|
|
104
|
+
if candidate.is_absolute() or ".." in candidate.parts:
|
|
105
|
+
return None
|
|
106
|
+
resolved_root = Path(root).resolve()
|
|
107
|
+
cursor = resolved_root
|
|
108
|
+
for part in candidate.parts:
|
|
109
|
+
if part in {"", "."}:
|
|
110
|
+
continue
|
|
111
|
+
cursor = cursor / part
|
|
112
|
+
if cursor.is_symlink():
|
|
113
|
+
return None
|
|
114
|
+
try:
|
|
115
|
+
abs_path = (resolved_root / candidate).resolve()
|
|
116
|
+
rel_norm = abs_path.relative_to(resolved_root).as_posix()
|
|
117
|
+
except (OSError, ValueError):
|
|
118
|
+
return None
|
|
119
|
+
if not abs_path.is_file() or abs_path.is_symlink():
|
|
120
|
+
return None
|
|
121
|
+
try:
|
|
122
|
+
raw_bytes = abs_path.read_bytes()
|
|
123
|
+
except OSError:
|
|
124
|
+
return None
|
|
125
|
+
line_count = max(1, len(raw_bytes.decode("utf-8", errors="replace").splitlines()))
|
|
126
|
+
if line > line_count:
|
|
127
|
+
return None
|
|
128
|
+
return rel_norm, line, _sha256_bytes(raw_bytes)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _iter_candidate_files(root: Path, *, max_files: int = MAX_CONTEXT_FILES) -> list[Path]:
|
|
132
|
+
resolved_root = Path(root).resolve()
|
|
133
|
+
scored: list[tuple[int, str, Path]] = []
|
|
134
|
+
for dirpath, dirnames, filenames in os.walk(resolved_root):
|
|
135
|
+
dirnames[:] = sorted(d for d in dirnames if d not in _SKIP_DIRS and not d.startswith("."))
|
|
136
|
+
for fname in sorted(filenames):
|
|
137
|
+
fpath = Path(dirpath) / fname
|
|
138
|
+
if fpath.is_symlink() or fpath.suffix.lower() not in _CODE_SUFFIXES:
|
|
139
|
+
continue
|
|
140
|
+
rel = fpath.relative_to(resolved_root).as_posix()
|
|
141
|
+
rel_lower = rel.lower()
|
|
142
|
+
score = sum(2 for kw in _PRIORITY_KEYWORDS if kw in rel_lower)
|
|
143
|
+
scored.append((score, rel, fpath))
|
|
144
|
+
scored.sort(key=lambda item: (-item[0], item[1]))
|
|
145
|
+
return [item[2] for item in scored[:max_files]]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def collect_semantic_context_pack(
|
|
149
|
+
root: Path,
|
|
150
|
+
*,
|
|
151
|
+
max_files: int = MAX_CONTEXT_FILES,
|
|
152
|
+
max_chars: int = MAX_CONTEXT_CHARS,
|
|
153
|
+
) -> dict[str, Any]:
|
|
154
|
+
"""Build a bounded context pack for lightweight LLM semantic recon."""
|
|
155
|
+
resolved_root = Path(root).resolve()
|
|
156
|
+
files_payload: list[dict[str, Any]] = []
|
|
157
|
+
used = 0
|
|
158
|
+
for fpath in _iter_candidate_files(resolved_root, max_files=max_files):
|
|
159
|
+
rel = fpath.relative_to(resolved_root).as_posix()
|
|
160
|
+
try:
|
|
161
|
+
text = fpath.read_text(encoding="utf-8", errors="replace")
|
|
162
|
+
except OSError:
|
|
163
|
+
continue
|
|
164
|
+
remaining = max_chars - used
|
|
165
|
+
if remaining <= 128:
|
|
166
|
+
break
|
|
167
|
+
excerpt = text[: min(len(text), 2000, remaining)]
|
|
168
|
+
files_payload.append({
|
|
169
|
+
"file": rel,
|
|
170
|
+
"line_count": len(text.splitlines()),
|
|
171
|
+
"excerpt": excerpt,
|
|
172
|
+
})
|
|
173
|
+
used += len(excerpt)
|
|
174
|
+
return {
|
|
175
|
+
"schema_version": OVERLAY_SCHEMA_VERSION,
|
|
176
|
+
"root_name": resolved_root.name,
|
|
177
|
+
"file_count": len(files_payload),
|
|
178
|
+
"files": files_payload,
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _heuristic_extract_python(root: Path, fpath: Path) -> dict[str, list[dict[str, Any]]]:
|
|
183
|
+
"""Zero-dependency Python AST heuristic extractor for implicit routes, auth boundaries & invariants."""
|
|
184
|
+
rel = fpath.resolve().relative_to(Path(root).resolve()).as_posix()
|
|
185
|
+
routes: list[dict[str, Any]] = []
|
|
186
|
+
auths: list[dict[str, Any]] = []
|
|
187
|
+
invariants: list[dict[str, Any]] = []
|
|
188
|
+
try:
|
|
189
|
+
src = fpath.read_text(encoding="utf-8", errors="replace")
|
|
190
|
+
tree = ast.parse(src, filename=rel)
|
|
191
|
+
except (OSError, SyntaxError):
|
|
192
|
+
return {"implicit_routes": routes, "auth_boundaries": auths, "business_invariants": invariants}
|
|
193
|
+
|
|
194
|
+
for node in ast.walk(tree):
|
|
195
|
+
# 1. Implicit dispatch: getattr(..., action/method/handler) or HANDLERS/ROUTES dict registry
|
|
196
|
+
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "getattr":
|
|
197
|
+
routes.append({
|
|
198
|
+
"file": rel,
|
|
199
|
+
"line": getattr(node, "lineno", 1),
|
|
200
|
+
"endpoint_or_dispatch": "dynamic getattr() dispatch",
|
|
201
|
+
"handler": "dynamic_target",
|
|
202
|
+
"auth_required": "unknown",
|
|
203
|
+
"confidence": "medium",
|
|
204
|
+
"source": "heuristic_ast",
|
|
205
|
+
})
|
|
206
|
+
elif isinstance(node, ast.Assign):
|
|
207
|
+
for target in node.targets:
|
|
208
|
+
if isinstance(target, ast.Name) and any(
|
|
209
|
+
tok in target.id.upper() for tok in ("ROUTE", "HANDLER", "DISPATCH", "RPC_METHOD")
|
|
210
|
+
) and isinstance(node.value, ast.Dict):
|
|
211
|
+
routes.append({
|
|
212
|
+
"file": rel,
|
|
213
|
+
"line": getattr(node, "lineno", 1),
|
|
214
|
+
"endpoint_or_dispatch": f"registry table {target.id}",
|
|
215
|
+
"handler": target.id,
|
|
216
|
+
"auth_required": "unknown",
|
|
217
|
+
"confidence": "medium",
|
|
218
|
+
"source": "heuristic_ast",
|
|
219
|
+
})
|
|
220
|
+
elif isinstance(target, ast.Name) and any(
|
|
221
|
+
tok in target.id.upper() for tok in ("TRANSITION", "ALLOWED_STATE", "VALID_STATUS")
|
|
222
|
+
):
|
|
223
|
+
invariants.append({
|
|
224
|
+
"file": rel,
|
|
225
|
+
"line": getattr(node, "lineno", 1),
|
|
226
|
+
"entity": target.id,
|
|
227
|
+
"invariant_rule": f"explicit state transition table {target.id}",
|
|
228
|
+
"violation_impact": "state machine bypass if transition check is skipped",
|
|
229
|
+
"confidence": "medium",
|
|
230
|
+
"source": "heuristic_ast",
|
|
231
|
+
})
|
|
232
|
+
|
|
233
|
+
# 2. Custom auth middleware / guard functions
|
|
234
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
235
|
+
lname = node.name.lower()
|
|
236
|
+
if any(tok in lname for tok in ("require_auth", "check_auth", "verify_token", "auth_middleware", "require_role", "tenant_guard")):
|
|
237
|
+
auths.append({
|
|
238
|
+
"file": rel,
|
|
239
|
+
"line": getattr(node, "lineno", 1),
|
|
240
|
+
"mechanism": f"custom guard `{node.name}`",
|
|
241
|
+
"scope": rel,
|
|
242
|
+
"trust_transition": "untrusted request -> authenticated principal",
|
|
243
|
+
"confidence": "high",
|
|
244
|
+
"source": "heuristic_ast",
|
|
245
|
+
})
|
|
246
|
+
elif any(tok in lname for tok in ("transfer", "refund", "checkout", "withdraw", "transition_state", "approve_order")):
|
|
247
|
+
invariants.append({
|
|
248
|
+
"file": rel,
|
|
249
|
+
"line": getattr(node, "lineno", 1),
|
|
250
|
+
"entity": node.name,
|
|
251
|
+
"invariant_rule": f"business operation `{node.name}` requires non-negative conservation & valid state check",
|
|
252
|
+
"violation_impact": "financial/state integrity violation",
|
|
253
|
+
"confidence": "medium",
|
|
254
|
+
"source": "heuristic_ast",
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
return {
|
|
258
|
+
"implicit_routes": routes,
|
|
259
|
+
"auth_boundaries": auths,
|
|
260
|
+
"business_invariants": invariants,
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def heuristic_semantic_recon(root: Path, *, max_files: int = MAX_CONTEXT_FILES) -> dict[str, list[dict[str, Any]]]:
|
|
265
|
+
"""Offline zero-dependency semantic clue extractor across candidate files."""
|
|
266
|
+
combined: dict[str, list[dict[str, Any]]] = {
|
|
267
|
+
"implicit_routes": [],
|
|
268
|
+
"auth_boundaries": [],
|
|
269
|
+
"business_invariants": [],
|
|
270
|
+
}
|
|
271
|
+
for fpath in _iter_candidate_files(root, max_files=max_files):
|
|
272
|
+
if fpath.suffix.lower() == ".py":
|
|
273
|
+
part = _heuristic_extract_python(root, fpath)
|
|
274
|
+
for key in combined:
|
|
275
|
+
combined[key].extend(part[key])
|
|
276
|
+
return combined
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def validate_and_anchor_overlay(
|
|
280
|
+
root: Path,
|
|
281
|
+
raw_overlay: Mapping[str, Any],
|
|
282
|
+
) -> tuple[dict[str, Any], dict[str, str]]:
|
|
283
|
+
"""Physically verify file/line anchors & sanitize prompt-injection payloads (P2-D02)."""
|
|
284
|
+
watched_hashes: dict[str, str] = {}
|
|
285
|
+
rejected_hallucinations = 0
|
|
286
|
+
sanitized_injections = 0
|
|
287
|
+
|
|
288
|
+
def _clean_items(
|
|
289
|
+
items: object,
|
|
290
|
+
spec_fields: tuple[str, ...],
|
|
291
|
+
dedup_keys: tuple[str, ...],
|
|
292
|
+
) -> list[dict[str, Any]]:
|
|
293
|
+
nonlocal rejected_hallucinations, sanitized_injections
|
|
294
|
+
if not isinstance(items, Sequence) or isinstance(items, (str, bytes)):
|
|
295
|
+
return []
|
|
296
|
+
cleaned: list[dict[str, Any]] = []
|
|
297
|
+
seen: set[tuple[str, ...]] = set()
|
|
298
|
+
for entry in items:
|
|
299
|
+
if not isinstance(entry, Mapping):
|
|
300
|
+
rejected_hallucinations += 1
|
|
301
|
+
continue
|
|
302
|
+
anchor = _resolve_anchor(root, entry.get("file"), entry.get("line"))
|
|
303
|
+
if anchor is None:
|
|
304
|
+
rejected_hallucinations += 1
|
|
305
|
+
continue
|
|
306
|
+
rel_norm, line_no, file_hash = anchor
|
|
307
|
+
watched_hashes[rel_norm] = file_hash
|
|
308
|
+
record: dict[str, Any] = {"file": rel_norm, "line": line_no}
|
|
309
|
+
for field in spec_fields:
|
|
310
|
+
text, inj = _sanitize_text(entry.get(field, ""))
|
|
311
|
+
if inj:
|
|
312
|
+
sanitized_injections += 1
|
|
313
|
+
record[field] = text
|
|
314
|
+
conf = str(entry.get("confidence") or "medium").strip().lower()
|
|
315
|
+
record["confidence"] = conf if conf in {"high", "medium", "low"} else "medium"
|
|
316
|
+
src_tag, _ = _sanitize_text(entry.get("source") or "llm_semantic", max_len=48)
|
|
317
|
+
record["source"] = src_tag or "llm_semantic"
|
|
318
|
+
sig = tuple(str(record.get(k, "")) for k in dedup_keys)
|
|
319
|
+
if sig in seen:
|
|
320
|
+
continue
|
|
321
|
+
seen.add(sig)
|
|
322
|
+
cleaned.append(record)
|
|
323
|
+
return cleaned
|
|
324
|
+
|
|
325
|
+
routes = _clean_items(
|
|
326
|
+
raw_overlay.get("implicit_routes"),
|
|
327
|
+
("endpoint_or_dispatch", "handler", "auth_required"),
|
|
328
|
+
("file", "line", "endpoint_or_dispatch"),
|
|
329
|
+
)
|
|
330
|
+
auths = _clean_items(
|
|
331
|
+
raw_overlay.get("auth_boundaries"),
|
|
332
|
+
("mechanism", "scope", "trust_transition"),
|
|
333
|
+
("file", "line", "mechanism"),
|
|
334
|
+
)
|
|
335
|
+
invariants = _clean_items(
|
|
336
|
+
raw_overlay.get("business_invariants"),
|
|
337
|
+
("entity", "invariant_rule", "violation_impact"),
|
|
338
|
+
("file", "line", "entity", "invariant_rule"),
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
validated = {
|
|
342
|
+
"schema_version": OVERLAY_SCHEMA_VERSION,
|
|
343
|
+
"implicit_routes": routes,
|
|
344
|
+
"auth_boundaries": auths,
|
|
345
|
+
"business_invariants": invariants,
|
|
346
|
+
"audit_stats": {
|
|
347
|
+
"rejected_hallucinations": rejected_hallucinations,
|
|
348
|
+
"sanitized_injections": sanitized_injections,
|
|
349
|
+
"anchored_files": len(watched_hashes),
|
|
350
|
+
},
|
|
351
|
+
}
|
|
352
|
+
return validated, watched_hashes
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def run_semantic_recon_overlay(
|
|
356
|
+
root: Path,
|
|
357
|
+
*,
|
|
358
|
+
llm_analyzer: Callable[[Mapping[str, Any]], Mapping[str, Any]] | None = None,
|
|
359
|
+
max_files: int = MAX_CONTEXT_FILES,
|
|
360
|
+
max_chars: int = MAX_CONTEXT_CHARS,
|
|
361
|
+
persist: bool = True,
|
|
362
|
+
) -> dict[str, Any]:
|
|
363
|
+
"""Run dual-channel semantic recon (optional LLM + heuristic baseline), anchor-verify & persist."""
|
|
364
|
+
resolved_root = Path(root).resolve()
|
|
365
|
+
merged: dict[str, list[dict[str, Any]]] = {
|
|
366
|
+
"implicit_routes": [],
|
|
367
|
+
"auth_boundaries": [],
|
|
368
|
+
"business_invariants": [],
|
|
369
|
+
}
|
|
370
|
+
mode = "heuristic_fallback"
|
|
371
|
+
|
|
372
|
+
if llm_analyzer is not None:
|
|
373
|
+
context_pack = collect_semantic_context_pack(
|
|
374
|
+
resolved_root, max_files=max_files, max_chars=max_chars,
|
|
375
|
+
)
|
|
376
|
+
try:
|
|
377
|
+
llm_out = llm_analyzer(context_pack)
|
|
378
|
+
if isinstance(llm_out, Mapping):
|
|
379
|
+
for key in merged:
|
|
380
|
+
raw_list = llm_out.get(key)
|
|
381
|
+
if isinstance(raw_list, list):
|
|
382
|
+
for item in raw_list:
|
|
383
|
+
if isinstance(item, Mapping):
|
|
384
|
+
merged[key].append({"source": "llm_semantic", **dict(item)})
|
|
385
|
+
mode = "llm_plus_heuristic"
|
|
386
|
+
except Exception:
|
|
387
|
+
mode = "heuristic_fallback_after_llm_error"
|
|
388
|
+
|
|
389
|
+
heur = heuristic_semantic_recon(resolved_root, max_files=max_files)
|
|
390
|
+
for key in merged:
|
|
391
|
+
merged[key].extend(heur[key])
|
|
392
|
+
|
|
393
|
+
validated, watched_hashes = validate_and_anchor_overlay(resolved_root, merged)
|
|
394
|
+
payload = {
|
|
395
|
+
**validated,
|
|
396
|
+
"mode": mode,
|
|
397
|
+
"watched_file_hashes": watched_hashes,
|
|
398
|
+
"created_at": time.time(),
|
|
399
|
+
}
|
|
400
|
+
if persist:
|
|
401
|
+
_atomic_write_json(overlay_path(resolved_root), payload)
|
|
402
|
+
return payload
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def load_semantic_overlay(
|
|
406
|
+
root: Path,
|
|
407
|
+
*,
|
|
408
|
+
allow_stale: bool = False,
|
|
409
|
+
) -> dict[str, Any]:
|
|
410
|
+
"""Load persisted semantic overlay and drop entries whose anchored file hash drifted (P2-D03)."""
|
|
411
|
+
resolved_root = Path(root).resolve()
|
|
412
|
+
path = overlay_path(resolved_root)
|
|
413
|
+
if not path.is_file():
|
|
414
|
+
return {
|
|
415
|
+
"schema_version": OVERLAY_SCHEMA_VERSION,
|
|
416
|
+
"implicit_routes": [],
|
|
417
|
+
"auth_boundaries": [],
|
|
418
|
+
"business_invariants": [],
|
|
419
|
+
"stale_files": [],
|
|
420
|
+
}
|
|
421
|
+
try:
|
|
422
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
423
|
+
except (OSError, ValueError):
|
|
424
|
+
return {
|
|
425
|
+
"schema_version": OVERLAY_SCHEMA_VERSION,
|
|
426
|
+
"implicit_routes": [],
|
|
427
|
+
"auth_boundaries": [],
|
|
428
|
+
"business_invariants": [],
|
|
429
|
+
"stale_files": [],
|
|
430
|
+
}
|
|
431
|
+
if not isinstance(data, dict):
|
|
432
|
+
return {
|
|
433
|
+
"schema_version": OVERLAY_SCHEMA_VERSION,
|
|
434
|
+
"implicit_routes": [],
|
|
435
|
+
"auth_boundaries": [],
|
|
436
|
+
"business_invariants": [],
|
|
437
|
+
"stale_files": [],
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
watched = data.get("watched_file_hashes") if isinstance(data.get("watched_file_hashes"), dict) else {}
|
|
441
|
+
stale_files: set[str] = set()
|
|
442
|
+
for rel, expected_hash in watched.items():
|
|
443
|
+
if not isinstance(rel, str) or not isinstance(expected_hash, str):
|
|
444
|
+
continue
|
|
445
|
+
target = resolved_root / rel
|
|
446
|
+
if not target.is_file() or target.is_symlink():
|
|
447
|
+
stale_files.add(rel)
|
|
448
|
+
continue
|
|
449
|
+
try:
|
|
450
|
+
actual = _sha256_bytes(target.read_bytes())
|
|
451
|
+
except OSError:
|
|
452
|
+
stale_files.add(rel)
|
|
453
|
+
continue
|
|
454
|
+
if actual != expected_hash:
|
|
455
|
+
stale_files.add(rel)
|
|
456
|
+
|
|
457
|
+
def _filter_list(key: str) -> list[dict[str, Any]]:
|
|
458
|
+
raw = data.get(key)
|
|
459
|
+
if not isinstance(raw, list):
|
|
460
|
+
return []
|
|
461
|
+
out: list[dict[str, Any]] = []
|
|
462
|
+
for item in raw:
|
|
463
|
+
if not isinstance(item, dict):
|
|
464
|
+
continue
|
|
465
|
+
rel = str(item.get("file") or "")
|
|
466
|
+
is_stale = rel in stale_files
|
|
467
|
+
if is_stale and not allow_stale:
|
|
468
|
+
continue
|
|
469
|
+
copied = dict(item)
|
|
470
|
+
if is_stale:
|
|
471
|
+
copied["stale"] = True
|
|
472
|
+
out.append(copied)
|
|
473
|
+
return out
|
|
474
|
+
|
|
475
|
+
return {
|
|
476
|
+
"schema_version": int(data.get("schema_version") or OVERLAY_SCHEMA_VERSION),
|
|
477
|
+
"mode": data.get("mode", ""),
|
|
478
|
+
"implicit_routes": _filter_list("implicit_routes"),
|
|
479
|
+
"auth_boundaries": _filter_list("auth_boundaries"),
|
|
480
|
+
"business_invariants": _filter_list("business_invariants"),
|
|
481
|
+
"audit_stats": data.get("audit_stats") or {},
|
|
482
|
+
"stale_files": sorted(stale_files),
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def render_semantic_overlay_guidance(
|
|
487
|
+
overlay: Mapping[str, Any],
|
|
488
|
+
*,
|
|
489
|
+
target_files: Sequence[str] = (),
|
|
490
|
+
char_budget: int = 900,
|
|
491
|
+
) -> str:
|
|
492
|
+
"""Render target-filtered, budget-capped semantic recon guidance for Worker prompts."""
|
|
493
|
+
if char_budget <= 0 or not isinstance(overlay, Mapping):
|
|
494
|
+
return ""
|
|
495
|
+
wanted = {f.replace("\\", "/").strip() for f in target_files if isinstance(f, str) and f.strip()}
|
|
496
|
+
|
|
497
|
+
def _match(items: object) -> list[dict[str, Any]]:
|
|
498
|
+
if not isinstance(items, Sequence) or isinstance(items, (str, bytes)):
|
|
499
|
+
return []
|
|
500
|
+
res = [it for it in items if isinstance(it, dict)]
|
|
501
|
+
if wanted:
|
|
502
|
+
res = [it for it in res if str(it.get("file") or "") in wanted]
|
|
503
|
+
return res
|
|
504
|
+
|
|
505
|
+
routes = _match(overlay.get("implicit_routes"))
|
|
506
|
+
auths = _match(overlay.get("auth_boundaries"))
|
|
507
|
+
invs = _match(overlay.get("business_invariants"))
|
|
508
|
+
if not (routes or auths or invs):
|
|
509
|
+
return ""
|
|
510
|
+
|
|
511
|
+
lines = ["[语义侦察叠加层 (Semantic Recon Overlay)]"]
|
|
512
|
+
used = len(lines[0]) + 1
|
|
513
|
+
candidates: list[str] = []
|
|
514
|
+
for r in routes:
|
|
515
|
+
candidates.append(
|
|
516
|
+
f"- [隐式路由] {r.get('file')}:{r.get('line')} | {r.get('endpoint_or_dispatch')} -> "
|
|
517
|
+
f"{r.get('handler')} (auth={r.get('auth_required')})"
|
|
518
|
+
)
|
|
519
|
+
for a in auths:
|
|
520
|
+
candidates.append(
|
|
521
|
+
f"- [鉴权边界] {a.get('file')}:{a.get('line')} | {a.get('mechanism')} ({a.get('trust_transition')})"
|
|
522
|
+
)
|
|
523
|
+
for inv in invs:
|
|
524
|
+
candidates.append(
|
|
525
|
+
f"- [业务不变量] {inv.get('file')}:{inv.get('line')} | {inv.get('entity')}: {inv.get('invariant_rule')}"
|
|
526
|
+
)
|
|
527
|
+
|
|
528
|
+
for line in candidates:
|
|
529
|
+
if used + len(line) + 1 > char_budget:
|
|
530
|
+
break
|
|
531
|
+
lines.append(line)
|
|
532
|
+
used += len(line) + 1
|
|
533
|
+
return "\n".join(lines) if len(lines) > 1 else ""
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
__all__ = [
|
|
537
|
+
"OVERLAY_SCHEMA_VERSION",
|
|
538
|
+
"overlay_path",
|
|
539
|
+
"collect_semantic_context_pack",
|
|
540
|
+
"heuristic_semantic_recon",
|
|
541
|
+
"validate_and_anchor_overlay",
|
|
542
|
+
"run_semantic_recon_overlay",
|
|
543
|
+
"load_semantic_overlay",
|
|
544
|
+
"render_semantic_overlay_guidance",
|
|
545
|
+
]
|
|
@@ -7,6 +7,7 @@ import datetime as dt
|
|
|
7
7
|
import json
|
|
8
8
|
import math
|
|
9
9
|
import os
|
|
10
|
+
import sys
|
|
10
11
|
import time
|
|
11
12
|
import contextvars
|
|
12
13
|
from contextlib import contextmanager
|
|
@@ -313,7 +314,10 @@ def _default_runtime() -> dict:
|
|
|
313
314
|
"host": None,
|
|
314
315
|
"autonomous_mode": False,
|
|
315
316
|
"execute": False,
|
|
316
|
-
|
|
317
|
+
# F-RSI-20261112-077 后继(轮 77):校验层已统一正整数口径(0 拒绝),
|
|
318
|
+
# 默认态的「未声明」必须用 None 表达(与 worker_capacity 同构)——
|
|
319
|
+
# 默认值产 0 会让缺文件回退/reconcile 路径被自家校验炸掉。
|
|
320
|
+
"workers": None,
|
|
317
321
|
"worker_capacity": None,
|
|
318
322
|
"subagent_type": "bugx-worker",
|
|
319
323
|
"stagger_seconds": 0.0,
|
|
@@ -528,8 +532,14 @@ def _reconcile_orphaned_state_locked(state: dict, now: float | None = None) -> b
|
|
|
528
532
|
operation="lifecycle", gate="owner_cancelled",
|
|
529
533
|
reason="宿主取消 agent:owner 进程死亡而心跳仍新鲜(D27 取消回传)",
|
|
530
534
|
)
|
|
531
|
-
except Exception: # noqa: BLE001 - 回传失败不阻断 ownership 释放
|
|
532
|
-
|
|
535
|
+
except Exception as exc: # noqa: BLE001 - 回传失败不阻断 ownership 释放
|
|
536
|
+
# F-RSI-20261113-106:不阻断但必须留痕——D27 取消回传是宿主
|
|
537
|
+
# 取消信号的引擎侧落账,静默丢失会让「宿主为何释放所有权」
|
|
538
|
+
# 在 supervisor 权威链上无迹可查(与 F-104 同款可观测性守卫)。
|
|
539
|
+
print(
|
|
540
|
+
f"[launch_bugx] ⚠ D27 owner_cancelled 回传失败(ownership 释放不受影响): {exc}",
|
|
541
|
+
file=sys.stderr,
|
|
542
|
+
)
|
|
533
543
|
return True
|
|
534
544
|
|
|
535
545
|
if not is_dead:
|
|
@@ -702,6 +712,11 @@ def _read_runtime_state() -> dict:
|
|
|
702
712
|
"total_elapsed_seconds"):
|
|
703
713
|
if not is_number(state.get(key)) or state[key] < 0:
|
|
704
714
|
raise ValueError(f"运行计时文件 {key} 无效")
|
|
715
|
+
# F-RSI-20261112-087:segment_started_epoch 允许 None(默认/非运行态),
|
|
716
|
+
# 但出现必须是数字——垃圾值直通会在 orphan 恢复链的 _accrue 中裸崩。
|
|
717
|
+
seg = state.get("segment_started_epoch")
|
|
718
|
+
if seg is not None and (isinstance(seg, bool) or not is_number(seg)):
|
|
719
|
+
raise ValueError("运行计时文件 segment_started_epoch 无效(必须是数字或 null)")
|
|
705
720
|
if not isinstance(state.get("sessions_completed"), int) \
|
|
706
721
|
or isinstance(state["sessions_completed"], bool) \
|
|
707
722
|
or state["sessions_completed"] < 0:
|
|
@@ -738,10 +753,22 @@ def _read_runtime_state() -> dict:
|
|
|
738
753
|
raise ValueError("运行计时文件 execute 无效")
|
|
739
754
|
for key in ("workers", "worker_capacity"):
|
|
740
755
|
value = state.get(key)
|
|
741
|
-
if value is
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
756
|
+
if value is None:
|
|
757
|
+
continue
|
|
758
|
+
# F-RSI-20261112-077 后继(轮 77):0 是旧默认态泄漏(_default_runtime
|
|
759
|
+
# 曾产 0 并被 reconcile 落盘;消费侧历来把 0 当未声明吞掉)——归一为
|
|
760
|
+
# None 自动迁移存量项目,而非拒绝造成 engine 命令全面 Unhandled
|
|
761
|
+
# exception。拒绝保留给负数/布尔/非整数等真实非法值。
|
|
762
|
+
if not isinstance(value, int) or isinstance(value, bool):
|
|
763
|
+
raise ValueError(f"运行计时文件 {key} 无效(必须是正整数或未声明)")
|
|
764
|
+
if value == 0:
|
|
765
|
+
state[key] = None
|
|
766
|
+
print(
|
|
767
|
+
f"[bugx] ⚠️ 运行计时文件 {key}=0 为旧默认态残留,已归一为未声明(下次保存落盘)"
|
|
768
|
+
)
|
|
769
|
+
continue
|
|
770
|
+
if value < 0:
|
|
771
|
+
raise ValueError(f"运行计时文件 {key} 无效(必须是正整数或未声明)")
|
|
745
772
|
subagent_type = state.get("subagent_type")
|
|
746
773
|
if not isinstance(subagent_type, str) or not subagent_type.strip():
|
|
747
774
|
raise ValueError("运行计时文件 subagent_type 无效")
|
|
@@ -1044,9 +1071,21 @@ def append_runtime_event(state: dict, event: str, now: float,
|
|
|
1044
1071
|
def _accrue_running_segment(state: dict, now: float) -> None:
|
|
1045
1072
|
if state.get("state") != "running":
|
|
1046
1073
|
return
|
|
1047
|
-
started =
|
|
1074
|
+
started = state.get("segment_started_epoch")
|
|
1075
|
+
# F-RSI-20261112-087:默认态该键为 None,schema 校验此前也不覆盖它——
|
|
1076
|
+
# orphan 恢复链(进程死亡后重入)里 running+null 组合会让裸
|
|
1077
|
+
# float(state[...]) 抛 TypeError,中断会话无法恢复。无可累计起点时
|
|
1078
|
+
# 跳过累计并留痕,起点从下一次 reset_segment_timer 重建。
|
|
1079
|
+
if isinstance(started, bool) or not isinstance(started, (int, float)):
|
|
1080
|
+
print(
|
|
1081
|
+
"[launch_bugx] ⚠ segment_started_epoch 缺失或非法,跳过本段时长累计"
|
|
1082
|
+
f"(值={started!r});起点将由下次会话活动重建",
|
|
1083
|
+
file=sys.stderr,
|
|
1084
|
+
)
|
|
1085
|
+
state["segment_started_epoch"] = now
|
|
1086
|
+
return
|
|
1048
1087
|
state["session_elapsed_seconds"] = round(
|
|
1049
|
-
float(state["session_elapsed_seconds"]) + max(0.0, now - started), 3
|
|
1088
|
+
float(state["session_elapsed_seconds"]) + max(0.0, now - float(started)), 3
|
|
1050
1089
|
)
|
|
1051
1090
|
state["segment_started_epoch"] = now
|
|
1052
1091
|
|
|
@@ -1301,6 +1340,14 @@ def runtime_summary(now: float | None = None) -> dict:
|
|
|
1301
1340
|
|
|
1302
1341
|
def close_runtime(outcome: str, now: float | None = None,
|
|
1303
1342
|
reason: str | None = None) -> tuple[dict, bool]:
|
|
1343
|
+
# F-RSI-20261112-088:close_runtime 是公共 API 且 save_runtime 不做
|
|
1344
|
+
# schema 校验——非法 outcome 会直接落盘为非法 state 值,下次
|
|
1345
|
+
# load_runtime 必然抛「state 无效」,运行态整体变砖(只能手工修文件)。
|
|
1346
|
+
# close 的合法终态只有 completed/aborted,入口 fail-fast。
|
|
1347
|
+
if outcome not in ("completed", "aborted"):
|
|
1348
|
+
raise ValueError(
|
|
1349
|
+
f"close_runtime outcome 必须是 completed/aborted,收到 {outcome!r}"
|
|
1350
|
+
)
|
|
1304
1351
|
with runtime_lock():
|
|
1305
1352
|
state = load_runtime()
|
|
1306
1353
|
if not state["active"]:
|