# bandit - Doramagic AI Context Pack

> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。

## 充分原则

- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。
- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。

## 给宿主 AI 的使用方式

你正在读取 Doramagic 为 bandit 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。

## Claim 消费规则

- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。
- **事实最低状态**：`supported`
- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。
- `weak`：只能作为低置信度线索，必须要求用户继续核实。
- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。
- `unverified`：不得作为事实使用，应明确说证据不足。
- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。

## 它最适合谁

- **想在安装前理解开源项目价值和边界的用户**：当前证据主要来自项目文档。 Claim：`clm_0002` unverified 0.25

## 它能做什么

- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`CONTRIBUTING.md` Claim：`clm_0001` supported 0.86

## 怎么开始

- `git clone https://github.com/<your username>/bandit.git` 证据：`CONTRIBUTING.md` Claim：`clm_0003` supported 0.86
- `pip install tox` 证据：`CONTRIBUTING.md` Claim：`clm_0004` supported 0.86

## 继续前判断卡

- **当前建议**：仅建议沙盒试装
- **为什么**：项目存在安装命令、宿主配置或本地写入线索，不建议直接进入主力环境，应先在隔离环境试装。

### 30 秒判断

- **现在怎么做**：仅建议沙盒试装
- **最小安全下一步**：先跑 Prompt Preview；若仍要安装，只在隔离环境试装
- **先别相信**：真实输出质量不能在安装前相信。
- **继续会触碰**：命令执行、本地环境或项目文件、宿主 AI 上下文

### 现在可以相信

- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`CONTRIBUTING.md` Claim：`clm_0001` supported 0.86
- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`CONTRIBUTING.md` Claim：`clm_0003` supported 0.86

### 现在还不能相信

- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。
- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。
- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。
- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。
- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。
- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。
- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`CONTRIBUTING.md`

### 继续会触碰什么

- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`CONTRIBUTING.md`
- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`CONTRIBUTING.md`
- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。

### 最小安全下一步

- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）
- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）
- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）

### 退出方式

- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。
- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。
- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。

## 哪些只能预览

- 解释项目适合谁和能做什么
- 基于项目文档演示典型对话流程
- 帮助用户判断是否值得安装或继续研究

## 哪些必须安装后验证

- 真实安装 Skill、插件或 CLI
- 执行脚本、修改本地文件或访问外部服务
- 验证真实输出质量、性能和兼容性

## 边界与风险判断卡

- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0005` inferred 0.45
- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`CONTRIBUTING.md` Claim：`clm_0006` supported 0.86
- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。
- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。
- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。

## 开工前工作上下文

### 加载顺序

- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。
- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。
- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。
- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。
- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。

### 任务路由

- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`CONTRIBUTING.md` Claim：`clm_0001` supported 0.86

### 上下文规模

- 文件总数：250
- 重要文件覆盖：40/250
- 证据索引条目：62
- 角色 / Skill 条目：3

### 证据不足时的处理

- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。
- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。
- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。
- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。

## Prompt Recipes

### 适配判断

- 目标：判断这个项目是否适合用户当前任务。
- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。

```text
请基于 bandit 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。
```

### 安装前体验

- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。
- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。

```text
请把 bandit 当作安装前体验资产，而不是已安装工具或真实运行环境。

请严格输出四段：
1. 先问我 3 个必要问题。
2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。
3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。
4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。

硬性边界：
- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。
- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。
- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。
- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。
- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。
- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。

```

### 角色 / Skill 选择

- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。
- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。

```text
请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。
```

### 风险预检

- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。
- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。

```text
请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。
```

### 宿主 AI 开工指令

- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。
- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。

```text
请基于 bandit 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。
```

## 角色 / Skill 索引

- 共索引 3 个角色 / Skill / 项目文档条目。

- **Contributing to Bandit**（project_doc）：Contributing to Bandit Thanks for considering to take part in the improvement of the Bandit project. Contributions are always welcome! Here are guidelines and rules that can be helpful if you plan to want to get involved in the project. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CONTRIBUTING.md`
- **Contributor Covenant Code of Conduct**（project_doc）：Contributor Covenant Code of Conduct 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CODE_OF_CONDUCT.md`
- **Security Policy**（project_doc）：Bandit is a tool designed to find security issues, so every effort is made that Bandit itself is also free of those issues. However, if you believe you have found a security vulnerability in this repository please open it privately via the Report a security vulnerability https://github.com/PyCQA/bandit/security/advisories/new link in the Issues tab. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`SECURITY.md`

## 证据索引

- 共索引 62 条证据。

- **Contributing to Bandit**（documentation）：Contributing to Bandit Thanks for considering to take part in the improvement of the Bandit project. Contributions are always welcome! Here are guidelines and rules that can be helpful if you plan to want to get involved in the project. 证据：`CONTRIBUTING.md`
- **License**（source_file）：Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 证据：`LICENSE`
- **Readme**（source_file）：.. image:: https://raw.githubusercontent.com/pycqa/bandit/main/logo/logotype-sm.png :alt: Bandit 证据：`README.rst`
- **Init**（source_file）：author = metadata.metadata "bandit" "Author" version = metadata.version "bandit" 证据：`bandit/__init__.py`
- **bandit/plugins/app debug.py**（source_file）：metadata name = bandit summary = Security oriented static analyser for python code. description file = README.rst author = PyCQA author email = code-quality@python.org home page = https://bandit.readthedocs.io/ license = Apache-2.0 classifiers = Development Status :: 5 - Production/Stable Environment :: Console Intended Audience :: Information Technology Intended Audience :: System Administrators Intended Audience :: Developers Operating System :: POSIX :: Linux Operating System :: MacOS :: MacOS X Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.11 Programming Language :: Python :: 3.12 Programming… 证据：`setup.cfg`
- **Setup**（source_file）：data files = man path = "doc/build/man/bandit.1" 证据：`setup.py`
- **Utils**（source_file）：r"""Utils module.""" def build conf dict name, bid, cwe, qualnames, message, level="MEDIUM" 证据：`bandit/blacklists/utils.py`
- **Check Requirements**（source_file）：git = None bandit args = sys.argv 1: baseline tmp file = " bandit baseline run.json " current commit = None default output format = "terminal" LOG = logging.getLogger name repo = None report basename = "bandit baseline result" valid baseline formats = "txt", "html", "json" def main ⋮---- parent commit = None output format = None ⋮---- report fname = None ⋮---- commit = repo.commit current commit = commit.hexsha ⋮---- commit = commit.parents 0 parent commit = commit.hexsha ⋮---- output type = ⋮---- bandit tmpfile = f"{t}/{baseline tmp file}" steps = return code = None ⋮---- bandit command = "bandit" + step "args" ⋮---- output = subprocess.check output bandit command ⋮---- output = e.output r… 证据：`bandit/cli/baseline.py`
- **Config Generator**（source_file）：PROG NAME = "bandit conf generator" LOG = logging.getLogger name template = """ def init logger ⋮---- log level = logging.INFO log format string = " % levelname 5s : % message s" ⋮---- handler = logging.StreamHandler sys.stdout ⋮---- def parse args ⋮---- help description = """Bandit Config Generator parser = argparse.ArgumentParser ⋮---- args = parser.parse args ⋮---- def get config settings ⋮---- config = {} ⋮---- fn name = plugin.name function = plugin.plugin ⋮---- fn module = importlib.import module function. module ⋮---- def main ⋮---- args = parse args yaml settings = get config settings ⋮---- skips = args.skips.split "," if args.skips else tests = args.tests.split "," if args.tests el… 证据：`bandit/cli/config_generator.py`
- **setup work - parse arguments, and initialize BanditManager**（source_file）：BASE CONFIG = "bandit.yaml" LOG = logging.getLogger def init logger log level=logging.INFO, log format=None ⋮---- log format string = constants.log format string ⋮---- log format string = log format ⋮---- handler = logging.StreamHandler sys.stderr ⋮---- def get options from ini ini path, target ⋮---- ini file = None ⋮---- ini file = ini path ⋮---- bandit files = ⋮---- ini file = bandit files 0 ⋮---- def init extensions def log option source default val, arg val, ini val, option name def running under virtualenv def get profile config, profile name, config path ⋮---- profile = {} ⋮---- profiles = config.get option "profiles" or {} profile = profiles.get profile name ⋮---- def log info args,… 证据：`bandit/cli/main.py`
- **Config**（source_file）：tomllib = None ⋮---- LOG = logging.getLogger name class BanditConfig ⋮---- def init self, config file=None ⋮---- f = open config file, "rb" ⋮---- def get option self, option string ⋮---- option levels = option string.split "." cur item = self. config ⋮---- cur item = cur item level ⋮---- def get setting self, setting name ⋮---- @property def config self def init settings self def init plugin name pattern self ⋮---- plugin name pattern = constants.plugin name pattern ⋮---- plugin name pattern = self.get option "plugin name pattern" ⋮---- def convert legacy config self ⋮---- updated profiles = self.convert names to ids ⋮---- def convert names to ids self ⋮---- extman = extension loader.MANAGE… 证据：`bandit/core/config.py`
- **override with "log format" option in config file**（source_file）：plugin name pattern = " .py" RANKING = "UNDEFINED", "LOW", "MEDIUM", "HIGH" RANKING VALUES = {"UNDEFINED": 1, "LOW": 3, "MEDIUM": 5, "HIGH": 10} CRITERIA = "SEVERITY", "UNDEFINED" , "CONFIDENCE", "UNDEFINED" ⋮---- CONFIDENCE DEFAULT = "UNDEFINED" FALSE VALUES = None, False, "False", 0, 0.0, 0j, "", , , {} override with "log format" option in config file log format string = " % module s \t% levelname s\t% message s" EXCLUDE = 证据：`bandit/core/constants.py`
- **NOTE tkelsey : for some reason this import can't be found when stevedore**（source_file）：def get url bid ⋮---- base url = f"https://bandit.readthedocs.io/en/{bandit. version }/" NOTE tkelsey : for some reason this import can't be found when stevedore loads up the formatter plugin that imports this file. It is available later though. ⋮---- info = extension loader.MANAGER.plugins by id.get bid ⋮---- info = extension loader.MANAGER.blacklist by id.get bid ⋮---- template = "blacklists/blacklist {kind}.html {id}-{name}" ⋮---- info = info.copy ⋮---- ext = template.format 证据：`bandit/core/docs_utils.py`
- **Extension Loader**（source_file）：LOG = logging.getLogger name class Manager ⋮---- builtin = "B001" ⋮---- def load formatters self, formatters namespace def load plugins self, plugins namespace ⋮---- def test has id plugin ⋮---- def get test id self, test name def load blacklists self, blacklist namespace ⋮---- blacklist = list self.blacklists mgr ⋮---- def validate profile self, profile ⋮---- union = set profile "include" & set profile "exclude" ⋮---- def check id self, test MANAGER = Manager 证据：`bandit/core/extension_loader.py`
- **"skip" is a tuple of name and reason, decode just the name**（source_file）：LOG = logging.getLogger name NOSEC COMMENT = re.compile r" PROGRESS THRESHOLD = 50 class BanditManager ⋮---- scope = ⋮---- """Get logger, config, AST handler, and result store ready :param config: config options object :type config: bandit.core.BanditConfig :param agg type: aggregation type :param debug: Whether to show debug messages or not :param verbose: Whether to show verbose output :param quiet: Whether to only show output in the case of an error :param profile name: Optional name of profile to use from cmd line :param ignore nosec: Whether to ignore nosec or not :return: """ ⋮---- profile = {} ⋮---- def get skipped self ⋮---- ret = "skip" is a tuple of name and reason, decode just th… 证据：`bandit/core/manager.py`
- **Utils**（source_file）：LOG = logging.getLogger name def get attr qual name node, aliases ⋮---- name = f"{ get attr qual name node.value, aliases }.{node.attr}" ⋮---- def get call name node, aliases def get func name node ⋮---- return node.name TODO tkelsey : get that qualname using enclosing scope def get qual attr node, aliases ⋮---- val = deepgetattr node, "value.id" ⋮---- prefix = aliases val ⋮---- prefix = deepgetattr node, "value.id" ⋮---- prefix = "" ⋮---- return "" TODO tkelsey : process other node types def deepgetattr obj, attr ⋮---- """Recurses through an attribute chain to get the ultimate value.""" ⋮---- obj = getattr obj, key ⋮---- class InvalidModulePath Exception class ConfigError Exception ⋮---- "… 证据：`bandit/core/utils.py`
- **build the results string to insert in the report**（source_file）：r""" ============== HTML formatter ============== This formatter outputs the issues as HTML. :Example: .. code-block:: html Bandit Report html { font-family: "Arial", sans-serif; } pre { font-family: "Monaco", monospace; } .bordered-box { border: 1px solid black; padding-top:.5em; padding-bottom:.5em; padding-left:1em; } .metrics-box { font-size: 1.1em; line-height: 130%; } .metrics-title { font-size: 1.5em; font-weight: 500; margin-bottom: .25em; } .issue-description { font-size: 1.3em; font-weight: 500; } .candidate-issues { margin-left: 2em; border-left: solid 1px; LightGray; padding-left: 5%; margin-top: .2em; margin-bottom: .2em; } .issue-block { border: 1px solid LightGray; padding-le… 证据：`bandit/formatters/html.py`
- **Json**（source_file）：r""" ============== JSON formatter ============== This formatter outputs the issues in JSON. :Example: .. code-block:: javascript { "errors": , "generated at": "2015-12-16T22:27:34Z", "metrics": { " totals": { "CONFIDENCE.HIGH": 1, "CONFIDENCE.LOW": 0, "CONFIDENCE.MEDIUM": 0, "CONFIDENCE.UNDEFINED": 0, "SEVERITY.HIGH": 0, "SEVERITY.LOW": 0, "SEVERITY.MEDIUM": 1, "SEVERITY.UNDEFINED": 0, "loc": 5, "nosec": 0 }, "examples/yaml load.py": { "CONFIDENCE.HIGH": 1, "CONFIDENCE.LOW": 0, "CONFIDENCE.MEDIUM": 0, "CONFIDENCE.UNDEFINED": 0, "SEVERITY.HIGH": 0, "SEVERITY.LOW": 0, "SEVERITY.MEDIUM": 1, "SEVERITY.UNDEFINED": 0, "loc": 5, "nosec": 0 } }, "results": { "code": "4 ystr = yaml.dump {'a' : 1, '… 证据：`bandit/formatters/json.py`
- **Utils**（source_file）：def wrap file object fileobj 证据：`bandit/formatters/utils.py`
- **Contributor Covenant Code of Conduct**（documentation）：Contributor Covenant Code of Conduct 证据：`CODE_OF_CONDUCT.md`
- **Security Policy**（documentation）：Bandit is a tool designed to find security issues, so every effort is made that Bandit itself is also free of those issues. However, if you believe you have found a security vulnerability in this repository please open it privately via the Report a security vulnerability https://github.com/PyCQA/bandit/security/advisories/new link in the Issues tab. 证据：`SECURITY.md`
- **Test Properties**（source_file）：LOG = logging.getLogger name def checks args ⋮---- def wrapper func ⋮---- def takes config args ⋮---- name = "" def takes config func ⋮---- name = args 0 . name ⋮---- name = args 0 ⋮---- def test id id val ⋮---- def has id func ⋮---- def accepts baseline args 证据：`bandit/core/test_properties.py`
- **Funding**（structured_config）：{ "version": "v1.0.0", "entity": { "type": "individual", "role": "maintainer", "name": "Eric Brown", "email": "eric wade brown@yahoo.com", "phone": "", "description": "I’m passionate about developing tools that empower engineers to produce secure, hardened code, reducing vulnerabilities and strengthening software integrity. With a focus on security automation, I aim to make secure coding practices more accessible and integrated into development workflows.", "webpageUrl": { "url": "https://github.com" } }, "projects": { "guid": "bandit", "name": "Bandit", "description": " Bandit is a tool designed to find common security issues in Python code.", "webpageUrl": { "url": "https://github.com/PyC… 证据：`funding.json`
- **.gitignore**（source_file）：env venv .python-version .pyc .DS Store .egg .egg-info .eggs/ .idea/ .vscode/ .tox .stestr build/ cover/ .coverage doc/build/ ChangeLog doc/source/api . .sw? AUTHORS 证据：`.gitignore`
- **.Pre Commit Config**（source_file）：exclude: ^ examples tools doc repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v6.0.0 hooks: - id: check-yaml - id: debug-statements - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/asottile/reorder-python-imports rev: v3.16.0 hooks: - id: reorder-python-imports args: --application-directories, '.:src', --py38-plus - repo: https://github.com/psf/black-pre-commit-mirror rev: 25.12.0 hooks: - id: black args: --line-length=79, --target-version=py38 - repo: https://github.com/asottile/pyupgrade rev: v3.21.2 hooks: - id: pyupgrade args: --py38-plus - repo: https://github.com/jorisroovers/gitlint rev: v0.19.1 hooks: - id: gitlint 证据：`.pre-commit-config.yaml`
- **.Pre Commit Hooks**（source_file）：- id: bandit name: bandit description: 'Bandit is a tool for finding common security issues in Python code' entry: bandit language: python language version: python3 types: python require serial: true 证据：`.pre-commit-hooks.yaml`
- **.Readthedocs**（source_file）：version: 2 build: os: ubuntu-lts-latest tools: python: "3.10" sphinx: configuration: doc/source/conf.py python: install: - requirements: requirements.txt - requirements: doc/requirements.txt - method: pip path: . extra requirements: - sarif 证据：`.readthedocs.yaml`
- **.Stestr**（source_file）：DEFAULT test path=./tests top dir=./ parallel class=True 证据：`.stestr.conf`
- **The order of packages is significant, because pip processes them in the order**（source_file）：The order of packages is significant, because pip processes them in the order of appearance. Changing the order has an impact on the overall integration process, which may cause wedges in the gate later. sphinx =4.0.0 BSD sphinx-rtd-theme =0.3.0 sphinx-copybutton 证据：`doc/requirements.txt`
- **Install Git required for pbr versioning**（source_file）：Install Git required for pbr versioning RUN apk add --no-cache git 证据：`docker/Dockerfile`
- **Binding**（source_file）：s = socket.socket socket.AF INET, socket.SOCK STREAM 证据：`examples/binding.py`
- **Cipher Modes**（source_file）：mode = ECB iv cipher = AES.new key, blockalgo.MODE CTR, iv mode = CBC iv 证据：`examples/cipher-modes.py`
- **Ciphers**（source_file）：key = b'Sixteen byte key' iv = Random.new .read pycrypto arc2.block size cipher = pycrypto arc2.new key, pycrypto arc2.MODE CFB, iv msg = iv + cipher.encrypt b'Attack at dawn' cipher = pycryptodomex arc2.new key, pycryptodomex arc2.MODE CFB, iv ⋮---- key = b'Very long and confidential key' nonce = Random.new .read 16 tempkey = SHA.new key+nonce .digest cipher = pycrypto arc4.new tempkey msg = nonce + cipher.encrypt b'Open the pod bay doors, HAL' cipher = pycryptodomex arc4.new tempkey ⋮---- iv = Random.new .read bs key = b'An arbitrarily long key' plaintext = b'docendo discimus ' plen = bs - divmod len plaintext ,bs 1 padding = plen plen padding = pack 'b' plen, padding bs = pycrypto blowfi… 证据：`examples/ciphers.py`
- **Crypto Md5**（source_file）：abc = str.replace hashlib.md5 "1" , " " 证据：`examples/crypto-md5.py`
- **Dill**（source_file）：pick = dill.dumps {'a': 'b', 'c': 'd'} ⋮---- file obj = io.BytesIO 证据：`examples/dill.py`
- **Django Sql Injection Extra**（source_file）：query = '"username" AS "username", FROM "auth user" WHERE 1=1 OR "username"=? --' ⋮---- where var = '1=1 OR 1=1 AND 1=1' ⋮---- where str = '1=1 OR 1=1 AND 1=1' ⋮---- tables var = 'django content type" WHERE "auth user"."username"="admin' ⋮---- tables str = 'django content type" WHERE "auth user"."username"="admin' 证据：`examples/django_sql_injection_extra.py`
- **Django Sql Injection Raw**（source_file）：raw = '"username" AS "val" FROM "auth user" WHERE "username"="admin" --' ⋮---- raw = '"username" AS "val" FROM "auth user"' \ 证据：`examples/django_sql_injection_raw.py`
- **Eval**（source_file）：class Test object ⋮---- def eval self def foo self 证据：`examples/eval.py`
- **Flask Debug**（source_file）：app = Flask name ⋮---- @app.route '/' def main 证据：`examples/flask_debug.py`
- **Ftplib**（source_file）：ftp = FTP 'ftp.debian.org' ⋮---- ftp = ftplib.FTP TLS 证据：`examples/ftplib.py`
- **Possible hardcoded password: 'ajklawejrkl42348swfgkg'**（source_file）：class SomeClass ⋮---- password = "class password" def someFunction user, password="Admin" def someFunction2 password def noMatch password def NoMatch2 password ⋮---- Possible hardcoded password: 'ajklawejrkl42348swfgkg' ⋮---- def noMatchObject ⋮---- obj = SomeClass ⋮---- def doLogin password="blerg" def NoMatch3 a, b ⋮---- password = "blerg" ⋮---- EMAIL PASSWORD = "secret" email pwd = 'emails secret' my secret password for email = 'd6s$f9g!j8mg7hw?n&2' passphrase='1234' def init self, auth scheme, auth token=None, auth username=None, auth password=None, auth link=None, kwargs ⋮---- Possible hardcoded password: 'pass' ⋮---- info = {"password": "12345"} info = {"password": password} 证据：`examples/hardcoded-passwords.py`
- **Httpoxy Cgihandler**（source_file）：def application environ, start response ⋮---- r = requests.get 'https://192.168.0.42/private/api/foobar', timeout=30 证据：`examples/httpoxy_cgihandler.py`
- **Httpoxy Twisted Directory**（source_file）：root = static.File "/root" 证据：`examples/httpoxy_twisted_directory.py`
- **Httpoxy Twisted Script**（source_file）：root = static.File "/root" 证据：`examples/httpoxy_twisted_script.py`
- **Huggingface Unsafe Download**（source_file）：unsafe model no revision = AutoModel.from pretrained "org/model name" unsafe model main = AutoModel.from pretrained unsafe model tag = AutoModel.from pretrained unsafe tokenizer no revision = AutoTokenizer.from pretrained "org/model name" unsafe tokenizer main = AutoTokenizer.from pretrained unsafe tokenizer tag = AutoTokenizer.from pretrained unsafe dataset no revision = load dataset "org dataset" unsafe dataset main = load dataset "org dataset", revision="main" unsafe dataset tag = load dataset "org dataset", revision="v1.0.0" unsafe file no revision = hf hub download unsafe file main = hf hub download unsafe file tag = hf hub download unsafe snapshot no revision = snapshot download repo… 证据：`examples/huggingface_unsafe_download.py`
- **Imports Function**（source_file）：os = import "os" pickle = import "pickle" sys = import "sys" subprocess = import "subprocess" ⋮---- a = 'subprocess' 证据：`examples/imports-function.py`
- **Imports With Importlib**（source_file）：a = importlib.import module 'os' b = importlib.import module 'pickle' c = importlib. import 'sys' d = importlib. import 'subprocess' e = importlib.import module MODULE MAP key f = importlib. import MODULE MAP key g = importlib.import module name='sys' h = importlib. import name='subprocess' i = importlib.import module name='subprocess', package='bar.baz' j = importlib. import name='sys', package='bar.baz' 证据：`examples/imports-with-importlib.py`
- **Jinja2 Templating**（source_file）：templateLoader = jinja2.FileSystemLoader searchpath="/" something = '' ⋮---- templateEnv = jinja2.Environment autoescape=True, ⋮---- templateEnv = jinja2.Environment autoescape=False, loader=templateLoader ⋮---- def fake func 证据：`examples/jinja2_templating.py`
- **Jsonpickle**（source_file）：pick = jsonpickle.encode {'a': 'b', 'c': 'd'} 证据：`examples/jsonpickle.py`
- **Logging Config Insecure Listen**（source_file）：t = logging.config.listen 9999 证据：`examples/logging_config_insecure_listen.py`
- **Long Set**（source_file）：long set = { 证据：`examples/long_set.py`
- **Mark Safe**（source_file）：mystr = ' Hello World ' mystr = safestring.mark safe mystr 证据：`examples/mark_safe.py`
- **Mark Safe Insecure**（source_file）：def insecure function text, cls='' my insecure str = insecure function 'insecure', cls='" onload="alert \'xss\' ' ⋮---- def try insecure cls='" onload="alert \'xss\' ' ⋮---- my insecure str = insecure function 'insecure', cls=cls ⋮---- my insecure str = 'Secure' ⋮---- def except insecure cls='" onload="alert \'xss\' ' def try else insecure cls='" onload="alert \'xss\' ' def finally insecure cls='" onload="alert \'xss\' ' def format arg insecure cls='" onload="alert \'xss\' ' def format startarg insecure cls='" onload="alert \'xss\' ' def format keywords insecure cls='" onload="alert \'xss\' ' def format kwargs insecure cls='" onload="alert \'xss\' ' def percent insecure cls='" onload="alert… 证据：`examples/mark_safe_insecure.py`
- **Mark Safe Secure**（source_file）：my secure str = ' Hello World ' ⋮---- also secure str = my secure str ⋮---- def try secure ⋮---- my secure str = 'Secure' ⋮---- def format secure ⋮---- my secure str = 'secure' ⋮---- my secure str = ' {} '.format my secure str ⋮---- def percent secure def with secure path def loop secure ⋮---- my secure str = '' ⋮---- def all secure case 证据：`examples/mark_safe_secure.py`
- **Markupsafe Markup Xss**（source_file）：content = " alert 'Hello, world!' " Markup f"unsafe {content}" B704 flask.Markup "unsafe {}".format content B704 ⋮---- Markup content B704 证据：`examples/markupsafe_markup_xss.py`
- **Markupsafe Markup Xss Allowed Calls**（source_file）：content = " alert 'Hello, world!' " ⋮---- cleaned = clean content 证据：`examples/markupsafe_markup_xss_allowed_calls.py`
- **Markupsafe Markup Xss Extend Markup Names**（source_file）：content = " alert 'Hello, world!' " 证据：`examples/markupsafe_markup_xss_extend_markup_names.py`
- **Marshal Deserialize**（source_file）：serialized = marshal.dumps {'a': 1} ⋮---- file obj = tempfile.TemporaryFile 证据：`examples/marshal_deserialize.py`
- **Mktemp**（source_file）：foo = 'hi' 证据：`examples/mktemp.py`
- **New Candidates All**（source_file）：def subprocess shell cmd def yaml load ⋮---- temp str = yaml.dump {'a': '1', 'b': '2'} y = yaml.load temp str ⋮---- def xml sax make parser 证据：`examples/new_candidates-all.py`
- 其余 2 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。

## 宿主 AI 必须遵守的规则

- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`CONTRIBUTING.md`, `LICENSE`, `README.rst`
- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`CONTRIBUTING.md`, `LICENSE`, `README.rst`

## 用户开工前应该回答的问题

- 你准备在哪个宿主 AI 或本地环境中使用它？
- 你只是想先体验工作流，还是准备真实安装？
- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？

## 验收标准

- 所有能力声明都能回指到 evidence_refs 中的文件路径。
- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。
- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。

---

## Doramagic Context Augmentation

下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。

## Human Manual 骨架

使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。

宿主 AI 硬性规则：
- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。
- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。
- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。

- **项目概览与快速开始**：importance `high`
  - source_paths: README.rst, bandit/__init__.py, bandit/__main__.py, setup.py, setup.cfg
- **核心架构与扫描引擎**：importance `high`
  - source_paths: bandit/core/manager.py, bandit/core/node_visitor.py, bandit/core/test_set.py, bandit/core/tester.py, bandit/core/issue.py
- **配置文件、排除规则与插件机制**：importance `high`
  - source_paths: bandit/core/config.py, bandit/core/utils.py, bandit/core/extension_loader.py, bandit/core/test_properties.py, bandit/cli/main.py
- **命令行工具、Baseline 与输出格式**：importance `medium`
  - source_paths: bandit/cli/main.py, bandit/cli/baseline.py, bandit/cli/config_generator.py, bandit/formatters/__init__.py, bandit/formatters/json.py

## Repo Inspection Evidence / 源码检查证据

- repo_clone_verified: true
- repo_inspection_verified: true
- repo_commit: `c4bfccf6fdf80559f2aad937246fb1b0c607a423`
- inspected_files: `README.rst`, `requirements.txt`, `examples/__init__.py`, `examples/assert.py`, `examples/binding.py`, `examples/cipher-modes.py`, `examples/ciphers.py`, `examples/crypto-md5.py`, `examples/dill.py`, `examples/django_sql_injection_extra.py`, `examples/django_sql_injection_raw.py`, `examples/eval.py`, `examples/exec.py`, `examples/flask_debug.py`, `examples/ftplib.py`, `examples/hardcoded-passwords.py`, `examples/hardcoded-tmp.py`, `examples/hashlib_new_insecure_functions.py`, `examples/httpoxy_cgihandler.py`, `examples/httpoxy_twisted_directory.py`

宿主 AI 硬性规则：
- 没有 repo_clone_verified=true 时，不得声称已经读过源码。
- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。
- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。

## Doramagic Pitfall Constraints / 踩坑约束

这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。

### Constraint 1: 来源证据：False negative: narrow argument-shape checks in B508/B509

- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：False negative: narrow argument-shape checks in B508/B509
- Why it matters: 可能影响授权、密钥配置或安全边界。
- Evidence: community_evidence:github | https://github.com/PyCQA/bandit/issues/1397 | 来源讨论提到 python 相关条件，需在安装/试用前复核。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 2: 能力判断依赖假设

- Trigger: README/documentation is current enough for a first validation pass.
- Host AI rule: 将假设转成下游验证清单。
- Why it matters: 假设不成立时，用户拿不到承诺的能力。
- Evidence: capability.assumptions | https://github.com/PyCQA/bandit | README/documentation is current enough for a first validation pass.
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 3: 维护活跃度未知

- Trigger: 未记录 last_activity_observed。
- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。
- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- Evidence: evidence.maintainer_signals | https://github.com/PyCQA/bandit | last_activity_observed missing
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

- Trigger: no_demo
- Evidence: downstream_validation.risk_items | https://github.com/PyCQA/bandit | no_demo; severity=medium
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 5: 存在评分风险

- Trigger: no_demo
- Why it matters: 风险会影响是否适合普通用户安装。
- Evidence: risks.scoring_risks | https://github.com/PyCQA/bandit | no_demo; severity=medium
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 6: 来源证据：Feature request: Adding Canary Credentials to detect supply chain compromise

- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature request: Adding Canary Credentials to detect supply chain compromise
- Why it matters: 可能影响授权、密钥配置或安全边界。
- Evidence: community_evidence:github | https://github.com/PyCQA/bandit/issues/1432 | 来源类型 github_issue 暴露的待验证使用条件。
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 7: issue/PR 响应质量未知

- Trigger: issue_or_pr_quality=unknown。
- Host AI rule: 抽样最近 issue/PR，判断是否长期无人处理。
- Why it matters: 用户无法判断遇到问题后是否有人维护。
- Evidence: evidence.maintainer_signals | https://github.com/PyCQA/bandit | issue_or_pr_quality=unknown
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。

### Constraint 8: 发布节奏不明确

- Trigger: release_recency=unknown。
- Host AI rule: 确认最近 release/tag 和 README 安装命令是否一致。
- Why it matters: 安装命令和文档可能落后于代码，用户踩坑概率升高。
- Evidence: evidence.maintainer_signals | https://github.com/PyCQA/bandit | release_recency=unknown
- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。
