# agentlock - Doramagic AI Context Pack

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

## 充分原则

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

## 给宿主 AI 的使用方式

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

## Claim 消费规则

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

## 它最适合谁

- **AI 研究者或研究型 Agent 构建者**：README 明确围绕研究、实验或论文工作流展开。 证据：`README.md` Claim：`clm_0002` supported 0.86
- **正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**：README 或插件配置提到多个宿主 AI。 证据：`README.md` Claim：`clm_0003` supported 0.86

## 它能做什么

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

## 怎么开始

- `pip install agentlock` 证据：`README.md` Claim：`clm_0004` supported 0.86, `clm_0005` supported 0.86, `clm_0006` supported 0.86, `clm_0007` supported 0.86 等
- `pip install agentlock[langchain]    # LangChain` 证据：`README.md` Claim：`clm_0005` supported 0.86
- `pip install agentlock[crewai]       # CrewAI` 证据：`README.md` Claim：`clm_0006` supported 0.86
- `pip install agentlock[autogen]      # AutoGen` 证据：`README.md` Claim：`clm_0007` supported 0.86
- `pip install agentlock[mcp]          # Model Context Protocol` 证据：`README.md` Claim：`clm_0008` supported 0.86
- `pip install agentlock[fastapi]      # FastAPI` 证据：`README.md` Claim：`clm_0009` supported 0.86
- `pip install agentlock[flask]        # Flask` 证据：`README.md` Claim：`clm_0010` supported 0.86
- `pip install agentlock[crypto]       # Ed25519 signed receipts` 证据：`README.md` Claim：`clm_0011` supported 0.86
- `pip install agentlock[all]          # Everything` 证据：`README.md` Claim：`clm_0012` supported 0.86
- `git clone https://github.com/webpro255/agentlock.git` 证据：`README.md` Claim：`clm_0013` supported 0.86

## 继续前判断卡

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

### 30 秒判断

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

### 现在可以相信

- **适合人群线索：AI 研究者或研究型 Agent 构建者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86
- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0003` supported 0.86
- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86
- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0004` supported 0.86, `clm_0005` supported 0.86, `clm_0006` supported 0.86, `clm_0007` 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）：这影响企业环境和个人环境的安装风险。 证据：`README.md`

### 继续会触碰什么

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

### 最小安全下一步

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

### 退出方式

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

## 哪些只能预览

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

## 哪些必须安装后验证

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

## 边界与风险判断卡

- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0015` inferred 0.45
- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0016` 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。

### 任务路由

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

### 上下文规模

- 文件总数：55
- 重要文件覆盖：40/55
- 证据索引条目：54
- 角色 / Skill 条目：8

### 证据不足时的处理

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

## Prompt Recipes

### 适配判断

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

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

### 安装前体验

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

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

请严格输出四段：
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
请基于 agentlock 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。
```

## 角色 / Skill 索引

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

- **The Problem**（project_doc）：AgentLock An adversarially benchmarked reference implementation for pre-action agent authorization Your AI agent needs a login screen. AgentLock is that login screen. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`
- **Contributing to AgentLock**（project_doc）：Thank you for your interest in contributing to AgentLock. This project aims to establish an open standard for authorization in AI agent systems. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CONTRIBUTING.md`
- **AgentLock Security Benchmark Report**（project_doc）：AgentLock Security Benchmark Report 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/benchmark.md`
- **Framework Integrations**（project_doc）：AgentLock is framework-agnostic. The core library has zero framework dependencies. Optional integrations wrap popular frameworks with AgentLock authorization. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/integrations.md`
- **Quick Start Guide**（project_doc）：Protect Your First Tool in 5 Minutes 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/quickstart.md`
- **AgentLock Specification v1.2**（project_doc）：AI agents are being deployed with direct access to tools that can read databases, send emails, execute financial transactions, and modify production systems. Yet these tools have no standardized permission model. Every major agent framework LangChain, CrewAI, AutoGen, and others treats tool calls as trusted function invocations with no identity verification, scope constraints, or access control. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/specification.md`
- **Changelog**（project_doc）：All notable changes to AgentLock will be documented in this file. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CHANGELOG.md`
- **Security Policy**（project_doc）：Version Supported --------- -------------------- 1.2.x Yes 1.1.x Yes 1.0.x Yes 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`SECURITY.md`

## 证据索引

- 共索引 54 条证据。

- **The Problem**（documentation）：AgentLock An adversarially benchmarked reference implementation for pre-action agent authorization Your AI agent needs a login screen. AgentLock is that login screen. 证据：`README.md`
- **Contributing to AgentLock**（documentation）：Thank you for your interest in contributing to AgentLock. This project aims to establish an open standard for authorization in AI agent systems. 证据：`CONTRIBUTING.md`
- **License**（source_file）：Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 证据：`LICENSE`
- **AgentLock Security Benchmark Report**（documentation）：AgentLock Security Benchmark Report 证据：`docs/benchmark.md`
- **Framework Integrations**（documentation）：AgentLock is framework-agnostic. The core library has zero framework dependencies. Optional integrations wrap popular frameworks with AgentLock authorization. 证据：`docs/integrations.md`
- **Quick Start Guide**（documentation）：Protect Your First Tool in 5 Minutes 证据：`docs/quickstart.md`
- **AgentLock Specification v1.2**（documentation）：AI agents are being deployed with direct access to tools that can read databases, send emails, execute financial transactions, and modify production systems. Yet these tools have no standardized permission model. Every major agent framework LangChain, CrewAI, AutoGen, and others treats tool calls as trusted function invocations with no identity verification, scope constraints, or access control. 证据：`docs/specification.md`
- **Changelog**（documentation）：All notable changes to AgentLock will be documented in this file. 证据：`CHANGELOG.md`
- **Security Policy**（documentation）：Version Supported --------- -------------------- 1.2.x Yes 1.1.x Yes 1.0.x Yes 证据：`SECURITY.md`
- **Agentlock V1.0**（structured_config）：{ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://agentlock.dev/schema/v1.0", "title": "AgentLock Tool Definition Schema v1.0", "description": "Authorization schema for AI agent tool calls. Defines the agentlock permissions block that extends standard tool definitions with access control, rate limiting, data policies, and audit requirements.", "type": "object", "properties": { "name": { "type": "string", "description": "Tool identifier" }, "description": { "type": "string", "description": "Human-readable tool description" }, "parameters": { "type": "object", "description": "Tool parameter schema" }, "agentlock": { "$ref": " /$defs/AgentLockPermissions" } }, "requi… 证据：`schema/agentlock-v1.0.json`
- **Agentlock V1.2**（structured_config）：{ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://agentlock.dev/schema/v1.2", "title": "AgentLock Tool Definition Schema v1.2", "description": "Authorization schema for AI agent tool calls. Defines the agentlock permissions block that extends standard tool definitions with access control, rate limiting, data policies, audit requirements, adaptive hardening, DEFER/STEP UP/MODIFY decision types, signed receipts, and hash-chained context.", "type": "object", "properties": { "name": { "type": "string", "description": "Tool identifier" }, "description": { "type": "string", "description": "Human-readable tool description" }, "parameters": { "type": "object", "descriptio… 证据：`schema/agentlock-v1.2.json`
- **.gitignore**（source_file）：pycache / .py cod $py.class .egg-info/ dist/ build/ .egg .eggs/ .mypy cache/ .pytest cache/ .ruff cache/ .coverage htmlcov/ .so .env .venv/ venv/ env/ .log .DS Store Thumbs.db 证据：`.gitignore`
- **Notice**（source_file）：AgentLock Copyright 2026 David Grice AgentLock — agentlock.dev 证据：`NOTICE`
- **Init**（source_file）：version = "1.2.1" ⋮---- all = 证据：`agentlock/__init__.py`
- **v1.1 additions**（source_file）：logger = logging.getLogger "agentlock.audit" ⋮---- all = "AuditRecord", "AuditLogger", "AuditBackend", "FileAuditBackend" ⋮---- def generate audit id - AuditId ⋮---- ts = time.strftime "%Y-%m-%d", time.gmtime seq = secrets.token hex 4 ⋮---- @dataclass slots=True class AuditRecord ⋮---- """A single audit entry.""" ⋮---- audit id: AuditId = field default factory= generate audit id timestamp: float = field default factory=time.time tool name: str = "" user id: str = "" role: str = "" action: str = "" "allowed", "denied", "error" reason: str = "" risk level: str = "" parameters: dict str, Any None = None response summary: str = "" token id: str = "" session id: str = "" duration ms: float = 0.0… 证据：`agentlock/audit.py`
- **Chain**（source_file）：all = ⋮---- GENESIS HASH = hashlib.sha256 b"" .hexdigest ⋮---- def generate entry id - str ⋮---- """Compute the deterministic hash of a chain entry.""" payload = ⋮---- @dataclass slots=True class ChainedContextEntry ⋮---- entry id: str = field default factory= generate entry id timestamp: float = field default factory=time.time source: str = "" ContextSource value authority: str = "" ContextAuthority value content hash: str = "" SHA-256 of actual content previous hash: str = "" hash of the previous ChainedContextEntry entry hash: str = "" SHA-256 previous hash + content hash + ... writer id: str = "" metadata: dict str, Any = field default factory=dict ⋮---- class ContextChain ⋮---- """Appe… 证据：`agentlock/chain.py`
- **If the file is a full tool definition**（source_file）：def validate args: argparse.Namespace - int ⋮---- path = Path args.file ⋮---- data = json.loads path.read text ⋮---- errors: list str = ⋮---- If the file is a full tool definition ⋮---- tool = ToolDefinition data perms = tool.agentlock ⋮---- perms = AgentLockPermissions data "agentlock" ⋮---- perms = AgentLockPermissions data ⋮---- thr = perms.human approval.threshold.value ch = perms.human approval.channel.value ⋮---- cp = perms.context policy td status = "enabled" if cp.trust degradation.enabled else "disabled" ⋮---- mp = perms.memory policy ⋮---- def schema args: argparse.Namespace - int ⋮---- """Print the AgentLock JSON schema.""" ⋮---- schema = AgentLockPermissions.model json schema ⋮-… 证据：`agentlock/cli.py`
- **Resolve authority from policy**（source_file）：all = "ContextProvenance", "ContextState", "ContextTracker" ⋮---- def generate provenance id - str ⋮---- @dataclass slots=True class ContextProvenance ⋮---- """Attribution for a single context entry.""" ⋮---- provenance id: str = field default factory= generate provenance id source: ContextSource = ContextSource.TOOL OUTPUT authority: ContextAuthority = ContextAuthority.DERIVED writer id: str = "" timestamp: float = field default factory=time.time tool name: str None = None token id: str None = None session id: str = "" content hash: str = "" previous hash: str = "" parent provenance id: str None = None metadata: dict str, Any = field default factory=dict ⋮---- @staticmethod def hash conten… 证据：`agentlock/context.py`
- **Decorators**（source_file）：F = TypeVar "F", bound=Callable ..., Any ⋮---- RESERVED KWARGS = {" user id", " role", " session id", " metadata"} ⋮---- def decorator func: F - F ⋮---- tool name = name or func. name ⋮---- perms = AgentLockPermissions permissions ⋮---- perms = permissions ⋮---- perms dict: dict str, Any = { ⋮---- perms = AgentLockPermissions perms dict ⋮---- @functools.wraps func async def async wrapper args: Any, kwargs: Any - Any ⋮---- user id = kwargs.pop " user id", "" role = kwargs.pop " role", "" ⋮---- meta = kwargs.pop " metadata", None ⋮---- auth result = gate.authorize ⋮---- captured result = await func args, kwargs ⋮---- redacted = gate.redact output tool name, captured result \ ⋮---- @functools.… 证据：`agentlock/decorators.py`
- **Defer**（source_file）：all = "DeferralManager", "DeferralRecord" ⋮---- def generate deferral id - str ⋮---- @dataclass class DeferralRecord ⋮---- """A suspended authorization decision.""" ⋮---- deferral id: str = field default factory= generate deferral id tool name: str = "" user id: str = "" role: str = "" reason: str = "" trigger: str = "" created at: float = field default factory=time.time timeout seconds: int = 60 resolution: str None = None "approved", "denied", "timeout" resolved at: float None = None resolved by: str None = None parameters: dict str, Any None = None ⋮---- @property def is resolved self - bool ⋮---- @property def is expired self - bool ⋮---- class DeferralManager ⋮---- def init self, sibli… 证据：`agentlock/defer.py`
- **Exceptions**（source_file）：class AgentLockError Exception ⋮---- class DeniedError AgentLockError ⋮---- def format self - str ⋮---- parts = f"denied: {self.reason}" ⋮---- def to dict self - dict str, Any ⋮---- """Serialize to the AgentLock denial response format.""" d: dict str, Any = { ⋮---- class AuthenticationRequiredError DeniedError ⋮---- def init self, auth methods: list str None = None, kwargs: Any - None ⋮---- class InsufficientRoleError DeniedError ⋮---- def init self, kwargs: Any - None ⋮---- class ScopeViolationError DeniedError ⋮---- class RateLimitedError DeniedError ⋮---- class SessionExpiredError DeniedError ⋮---- class ApprovalRequiredError DeniedError ⋮---- class TrustDegradedError DeniedError ⋮---- c… 证据：`agentlock/exceptions.py`
- **Adaptive prompt hardening off by default — pass HardeningConfig to enable**（source_file）：@dataclass class AuthResult ⋮---- allowed: bool decision: DecisionType = DecisionType.ALLOW token: ExecutionToken None = None denial: dict str, Any None = None audit id: str = "" hardening: HardeningDirective None = None modify output fn: Callable str , str None = None transformations applied: list str = field default factory=list deferral id: str = "" stepup request id: str = "" receipt: SignedReceipt None = None ⋮---- def raise if denied self - None ⋮---- """Raise DeniedError if the call was denied.""" ⋮---- class AuthorizationGate ⋮---- """Central authorization enforcement point. This is the primary interface for AgentLock. Register tools with their permissions, then call authorize on ev… 证据：`agentlock/gate.py`
- **Hardening**（source_file）：all = ⋮---- DEFAULT SIGNAL WEIGHTS: dict str, int = { ⋮---- SIGNAL INSTRUCTIONS: dict str, list str = { ⋮---- COMPOUND RULES: list dict str, Any = ⋮---- @dataclass slots=True class HardeningSignal ⋮---- signal type: str weight: int timestamp: float = field default factory=time.time details: str = "" source: str = "" ⋮---- @dataclass class HardeningDirective ⋮---- """Defensive instructions to inject into the agent's system prompt. The framework integration must check this after every authorize call and update the LLM's system prompt accordingly. """ ⋮---- active: bool = False severity: str = "none" instructions: list str = field default factory=list triggered by: list str = field default fac… 证据：`agentlock/hardening.py`
- **Built-in prohibited content patterns**（source_file）：all = ⋮---- def generate entry id - str ⋮---- @dataclass class MemoryEntry ⋮---- """A persisted memory item with provenance.""" ⋮---- entry id: str = field default factory= generate entry id user id: str = "" tool name: str = "" content: str = "" content hash: str = "" persistence: MemoryPersistence = MemoryPersistence.SESSION writer: MemoryWriter = MemoryWriter.SYSTEM created at: float = field default factory=time.time provenance: ContextProvenance None = None metadata: dict str, Any = field default factory=dict ⋮---- @property def is expired self - bool ⋮---- """Check if the entry has exceeded its max age. Note: max age is not stored on the entry — it's checked against the policy at read… 证据：`agentlock/memory_gate.py`
- **Track fields that were blocked not just modified**（source_file）：all = ⋮---- DEFAULT PII TYPES = "ssn", "email", "phone", "credit card", "api key" ⋮---- @dataclass class ModifyResult ⋮---- modified: bool = False original params: dict str, Any None = None modified params: dict str, Any None = None original output: str None = None modified output: str None = None transformations applied: list str = field default factory=list blocked fields: list str = field default factory=list ⋮---- class ModifyEngine ⋮---- def init self - None ⋮---- result = ModifyResult original output=output current = output ⋮---- t field = t.field if hasattr t, "field" else t.get "field", "" t action = t.action if hasattr t, "action" else t.get "action", "" t config = t.config if hasa… 证据：`agentlock/modify.py`
- **---------------------------------------------------------------------------**（source_file）：@dataclass slots=True class RequestContext ⋮---- user id: str = "" role: str = "" session id: str = "" data boundary: DataBoundary = DataBoundary.AUTHENTICATED USER ONLY record count: int = 1 recipient: str = "" is bulk: bool = False is external: bool = False is financial: bool = False amount: float = 0.0 max output classification: DataClassification None = None metadata: dict str, Any = field default factory=dict context state: ContextState None = None ⋮---- @property def is authenticated self - bool ⋮---- @dataclass slots=True class PolicyDecision ⋮---- """Result of policy evaluation.""" ⋮---- allowed: bool reason: DenialReason None = None detail: str = "" required role: str = "" suggesti… 证据：`agentlock/policy.py`
- **Rate Limit**（source_file）：@dataclass slots=True class Window ⋮---- calls: list float max calls: int window seconds: int ⋮---- class RateLimiter ⋮---- def init self - None ⋮---- key = tool name, user id now = time.time cutoff = now - window seconds ⋮---- window = self. windows key ⋮---- oldest = min window.calls if window.calls else now retry after = int oldest + window seconds - now + 1 ⋮---- def remaining self, tool name: str, user id: str - int None ⋮---- """Return remaining calls in the current window, or None if no limit set.""" ⋮---- window = self. windows.get key ⋮---- cutoff = now - window.window seconds active = t for t in window.calls if t cutoff ⋮---- def reset self, tool name: str None = None, user id: st… 证据：`agentlock/rate_limit.py`
- **Receipts**（source_file）：all = ⋮---- def generate receipt id - str ⋮---- @dataclass class SignedReceipt ⋮---- """A signed record of an authorization decision.""" ⋮---- receipt id: str = field default factory= generate receipt id timestamp: float = field default factory=time.time decision: str = "" allow/deny/defer/step up/modify tool name: str = "" user id: str = "" role: str = "" parameters hash: str = "" SHA-256 of parameters reason: str None = None policy version hash: str = "" context hash: str = "" trust ceiling: str None = None signing key id: str = "" signature: str = "" hex-encoded signature metadata: dict str, Any = field default factory=dict ⋮---- def canonical bytes self - bytes ⋮---- """Deterministic se… 证据：`agentlock/receipts.py`
- **International: +44 7700 900000, +91-9876543210, +1-555-123-4567**（source_file）：all = "RedactionEngine", "RedactionResult" ⋮---- BUILTIN PATTERNS: dict str, re.Pattern str = { ⋮---- International: +44 7700 900000, +91-9876543210, +1-555-123-4567 ⋮---- Local with leading zero: 07700 900000, 0800-123-456 ⋮---- @dataclass slots=True class RedactionResult ⋮---- original: str redacted: str redactions: list dict str, str ⋮---- @property def was redacted self - bool ⋮---- class RedactionEngine ⋮---- pattern = re.compile pattern ⋮---- def redact self, text: str - RedactionResult ⋮---- redactions: list dict str, str = result = text ⋮---- replacement = self. placeholder.format type=dtype ⋮---- def replacer match: re.Match str , dt: str = dtype, rep: str = replacement - str ⋮----… 证据：`agentlock/redaction.py`
- **Schema**（source_file）：all = ⋮---- SCHEMA VERSION = "1.2" ⋮---- class ScopeConfig BaseModel ⋮---- data boundary: DataBoundary = DataBoundary.AUTHENTICATED USER ONLY max records: int None = Field default=None, ge=1 allowed recipients: RecipientPolicy = RecipientPolicy.KNOWN CONTACTS ONLY ⋮---- model config = {"extra": "forbid"} ⋮---- class RateLimitConfig BaseModel ⋮---- max calls: int = Field ge=1 window seconds: int = Field ge=1 ⋮---- class DataPolicyConfig BaseModel ⋮---- input classification: DataClassification = DataClassification.PUBLIC output classification: DataClassification = DataClassification.PUBLIC prohibited in output: list str = Field default factory=list redaction: RedactionMode = RedactionMode.NON… 证据：`agentlock/schema.py`
- **Session**（source_file）：def generate session id - SessionId ⋮---- @dataclass class Session ⋮---- """An authenticated session. Attributes: session id: Unique session identifier. user id: Verified identity. role: Active role for this session. data boundary: Current scope of data access. created at: Unix timestamp. expires at: Unix timestamp. metadata: Arbitrary session metadata device info, IP, etc. . """ ⋮---- user id: str role: str data boundary: DataBoundary = DataBoundary.AUTHENTICATED USER ONLY created at: float = field default factory=time.time expires at: float = 0.0 session id: SessionId = field default factory= generate session id metadata: dict str, Any = field default factory=dict ⋮---- max duration: int… 证据：`agentlock/session.py`
- **Stepup**（source_file）：all = ⋮---- def generate request id - str ⋮---- @dataclass class StepUpRequest ⋮---- """A pending human approval request.""" ⋮---- request id: str = field default factory= generate request id tool name: str = "" user id: str = "" role: str = "" risk level: str = "" reason: str = "" trigger: str = "" hardening severity: str = "" created at: float = field default factory=time.time timeout seconds: int = 120 resolution: str None = None "approved", "denied", "timeout" resolved at: float None = None resolved by: str None = None ⋮---- @property def is resolved self - bool ⋮---- @property def is expired self - bool ⋮---- @runtime checkable class StepUpNotifier Protocol ⋮---- def notify self, reque… 证据：`agentlock/stepup.py`
- **Token**（source_file）：def generate token id - TokenId ⋮---- @dataclass slots=True class ExecutionToken ⋮---- """A single-use, time-limited, operation-bound execution token. Attributes: token id: Unique identifier. tool name: The specific tool this token authorizes. user id: Authenticated identity of the caller. role: The role under which this call is authorized. scope: Data boundary constraints snapshot. parameters hash: SHA-256 of the serialized call parameters. issued at: Unix timestamp of issuance. expires at: Unix timestamp after which the token is invalid. status: Current lifecycle state. """ ⋮---- tool name: str user id: str role: str scope: dict str, Any = field default factory=dict parameters hash: str =… 证据：`agentlock/token.py`
- **Types**（source_file）：all = ⋮---- class DecisionType str, Enum ⋮---- ALLOW = "allow" DENY = "deny" DEFER = "defer" STEP UP = "step up" MODIFY = "modify" ⋮---- class RiskLevel str, Enum ⋮---- NONE = "none" LOW = "low" MEDIUM = "medium" HIGH = "high" CRITICAL = "critical" ⋮---- class AuthMethod str, Enum ⋮---- OAUTH2 = "oauth2" MAGIC LINK = "magic link" MFA = "mfa" API KEY = "api key" ⋮---- class DataClassification str, Enum ⋮---- PUBLIC = "public" INTERNAL = "internal" CONFIDENTIAL = "confidential" MAY CONTAIN PII = "may contain pii" CONTAINS PII = "contains pii" CONTAINS PHI = "contains phi" CONTAINS FINANCIAL = "contains financial" ⋮---- class DataBoundary str, Enum ⋮---- AUTHENTICATED USER ONLY = "authenticate… 证据：`agentlock/types.py`
- **Now call through the gate -- output will be automatically redacted**（source_file）：gate = AuthorizationGate ⋮---- def lookup customer customer id: str - str ⋮---- raw output = lookup customer customer id="CUST-001" ⋮---- Now call through the gate -- output will be automatically redacted ⋮---- redacted output = gate.call ⋮---- --------------------------------------------------------------------------- You can also use the redaction engine directly for inspection ⋮---- result = gate.redact output "lookup customer", raw output ⋮---- Tool without redaction policy -- output passes through unchanged ⋮---- def get status - str ⋮---- output = gate.call 证据：`examples/data_redaction.py`
- **-- run report: viewer is denied, analyst is allowed ----------------------**（source_file）：gate = AuthorizationGate ⋮---- @agentlock gate, risk level="low", allowed roles= "viewer", "analyst", "admin" def search docs query: str - str ⋮---- @agentlock gate, risk level="medium", allowed roles= "analyst", "admin" def run report report name: str, date range: str - str ⋮---- def delete user username: str - str ⋮---- result = search docs query="agentlock setup", user id="bob", role="viewer" ⋮---- -- run report: viewer is denied, analyst is allowed ---------------------- ⋮---- result = run report ⋮---- -- delete user: only admin ----------------------------------------------- ⋮---- result = delete user username="eve", user id="carol", role="analyst" ⋮---- result = delete user username="… 证据：`examples/decorator_example.py`
- **Fastapi App**（source_file）：audit backend = InMemoryAuditBackend gate = AuthorizationGate audit backend=audit backend ⋮---- app = FastAPI title="AgentLock FastAPI Example" ⋮---- class AuthContext BaseModel ⋮---- user id: str role: str ⋮---- def get auth context request: Request - AuthContext ⋮---- user id = request.headers.get "X-User-Id", "" role = request.headers.get "X-User-Role", "" ⋮---- result = gate.authorize ⋮---- denial = result.denial or {} ⋮---- @app.get "/search" def search q: str, auth: AuthContext = Depends get auth context ⋮---- class ReportRequest BaseModel ⋮---- report name: str date range: str ⋮---- @app.post "/reports" def run report body: ReportRequest, auth: AuthContext = Depends get auth context… 证据：`examples/fastapi_app.py`
- **Test each user against each tool**（source_file）：audit backend = InMemoryAuditBackend gate = AuthorizationGate audit backend=audit backend ⋮---- tools = { ⋮---- users = { ⋮---- tool names = list tools.keys col width = max len t for t in tool names + 2 user col = 18 ⋮---- header = f"{'User role ':<{user col}}" ⋮---- Test each user against each tool ⋮---- row = f"{user id} {role} " row = f"{row:<{user col}}" ⋮---- result = gate.authorize tool name, user id=user id, role=role status = "ALLOW" if result.allowed else "DENY" ⋮---- --------------------------------------------------------------------------- Show per-user detail ⋮---- test cases = ⋮---- status = "ALLOWED" if result.allowed else "DENIED" reason = "" ⋮---- reason = f" {result.denial… 证据：`examples/multi_role.py`
- **---------------------------------------------------------------------------**（source_file）：audit backend = InMemoryAuditBackend gate = AuthorizationGate audit backend=audit backend ⋮---- perms = AgentLockPermissions ⋮---- --------------------------------------------------------------------------- Step 3: Denied case -- wrong role ⋮---- Alice is a "viewer". The tool requires "admin". Authorization will fail. ⋮---- result denied = gate.authorize ⋮---- You can also use raise if denied to turn denials into exceptions: ⋮---- Step 4: Allowed case -- correct role ⋮---- Now Alice authenticates as "admin". Authorization succeeds. ⋮---- result allowed = gate.authorize ⋮---- Step 5: Execute the tool using the token ⋮---- The token is single-use and time-limited. Pass it to gate.execute alon… 证据：`examples/quickstart.py`
- **gate.call combines authorize + execute in one step.**（source_file）：gate = AuthorizationGate ⋮---- def send notification channel: str, message: str - str ⋮---- gate.call combines authorize + execute in one step. It raises DeniedError including RateLimitedError on failure. ⋮---- RateLimitedError is a subclass of DeniedError with extra fields ⋮---- --------------------------------------------------------------------------- Check remaining quota ⋮---- Different users have independent limits ⋮---- output = gate.call 证据：`examples/rate_limiting.py`
- **Pyproject**（source_file）：build-system requires = "hatchling" build-backend = "hatchling.build" 证据：`pyproject.toml`
- **Init**（source_file）：@runtime checkable class AuthProvider Protocol ⋮---- def verify self, token or code: str - dict str, Any None ⋮---- class StaticAuthProvider ⋮---- def init self, users: dict str, str - None ⋮---- role = self. users.get token or code 证据：`agentlock/auth_providers/__init__.py`
- **Init**（source_file）：all = 证据：`agentlock/integrations/__init__.py`
- **No permissions -- leave the function as-is.**（source_file）：def check autogen available - None ⋮---- class AgentLockFunctionMap ⋮---- perms = permissions map func name ⋮---- perms = default permissions ⋮---- No permissions -- leave the function as-is. The gate will deny calls to unregistered tools. ⋮---- perms = AgentLockPermissions perms ⋮---- """Create an authorization-guarded wrapper for a single function.""" gate = self. gate default user = self. default user id default role = self. default role ⋮---- @functools.wraps func def guarded args: Any, kwargs: Any - Any ⋮---- user id = kwargs.pop " agentlock user id", default user role = kwargs.pop " agentlock role", default role ⋮---- auth = gate.authorize ⋮---- def exec params: Any - Any ⋮---- @prope… 证据：`agentlock/integrations/autogen.py`
- **Crewai**（source_file）：def import crewai - Any ⋮---- def import crewai crew - Any ⋮---- class AgentLockCrewTool ⋮---- crewai tools = import crewai ⋮---- permissions = AgentLockPermissions permissions ⋮---- wrapper ref = self inner = self. inner tool ⋮---- base = type inner ⋮---- class ProtectedCrewTool base ⋮---- name: str = inner.name description: str = inner.description ⋮---- def run self, args: Any, kwargs: Any - Any ⋮---- @property def tool self - Any ⋮---- @property def inner tool self - Any ⋮---- @property def tool name self - str ⋮---- def authorized run self, args: Any, kwargs: Any - Any ⋮---- user id = kwargs.pop " agentlock user id", self. default user id role = kwargs.pop " agentlock role", self. defau… 证据：`agentlock/integrations/crewai.py`
- **Fall back to JWT claims**（source_file）：def import fastapi - Any ⋮---- def import starlette - tuple Any, Any, Any ⋮---- HEADER USER ID = "X-AgentLock-User-Id" HEADER ROLE = "X-AgentLock-Role" HEADER TOOL = "X-AgentLock-Tool" HEADER SESSION ID = "X-AgentLock-Session-Id" ⋮---- def extract jwt claims authorization: str - dict str, Any ⋮---- token = authorization 7: parts = token.split "." ⋮---- payload b64 = parts 1 padding = 4 - len payload b64 % 4 ⋮---- payload bytes = base64.urlsafe b64decode payload b64 result: dict str, Any = json.loads payload bytes ⋮---- class AgentLockMiddleware ⋮---- async def call self, scope: dict str, Any , receive: Any, send: Any - None ⋮---- request = request cls scope, receive path = request.url.path… 证据：`agentlock/integrations/fastapi.py`
- **Fall back to JWT Authorization header best-effort decode**（source_file）：F = TypeVar "F", bound=Callable ..., Any ⋮---- def import flask - Any ⋮---- HEADER USER ID = "X-AgentLock-User-Id" HEADER ROLE = "X-AgentLock-Role" HEADER SESSION ID = "X-AgentLock-Session-Id" ⋮---- flask mod = import flask request = flask mod.request ⋮---- user id = request.headers.get user id header, "" role = request.headers.get role header, "" ⋮---- Fall back to JWT Authorization header best-effort decode ⋮---- auth header = request.headers.get "Authorization", "" claims = decode jwt claims auth header user id = user id or claims.get "sub", "" role = role or claims.get "role", "" ⋮---- def decode jwt claims authorization: str - dict str, Any ⋮---- """Best-effort JWT payload decode witho… 证据：`agentlock/integrations/flask.py`
- **Dynamically build a subclass of BaseTool that delegates to us.**（source_file）：def import langchain - Any ⋮---- def import callback manager - Any ⋮---- class AgentLockToolWrapper ⋮---- lc tools = import langchain ⋮---- permissions = AgentLockPermissions permissions ⋮---- Dynamically build a subclass of BaseTool that delegates to us. wrapper ref = self inner = self. inner tool ⋮---- base = lc tools.BaseTool ⋮---- class WrappedTool base : type: ignore misc,valid-type ⋮---- name: str = inner.name description: str = inner.description ⋮---- @property def args schema self - Any ⋮---- -- Public access to the LangChain tool object ------------------------- ⋮---- @property def tool self - Any ⋮---- """Return the wrapped LangChain BaseTool .""" ⋮---- @property def inner tool se… 证据：`agentlock/integrations/langchain.py`
- **Register all permissions with the gate**（source_file）：def import mcp - Any ⋮---- def import mcp types - Any ⋮---- class AgentLockMCPServer ⋮---- Register all permissions with the gate ⋮---- Hook into tool dispatch ⋮---- @property def server self - Any ⋮---- """Return the underlying MCP server.""" ⋮---- def install hook self - None ⋮---- """Monkey-patch the server's call tool handler to add authorization. MCP servers register tool handlers via @server.call tool . We wrap the registered handler or the dispatch method so that authorization runs first. """ server = self. server ⋮---- The MCP SDK uses a request-handler registry. We intercept by wrapping the call tool decorator so any handler registered through it gets an authorization check. origin… 证据：`agentlock/integrations/mcp.py`
- **Init**（source_file）：all = 证据：`agentlock/signals/__init__.py`
- **Check pairs order-independent within session**（source_file）：all = "ComboDetector", "ComboSignal", "ComboConfig" ⋮---- DEFAULT SUSPICIOUS PAIRS: dict tuple str, str , int = { ⋮---- DEFAULT SUSPICIOUS SEQUENCES: dict tuple str, ... , int = { ⋮---- @dataclass slots=True class ComboSignal ⋮---- signal type: str weight: int tools: list str details: str = "" ⋮---- @dataclass class ComboConfig ⋮---- """Configuration for combo detection. Both maps are configurable so deployers can add their own tool combinations without modifying the defaults. """ ⋮---- suspicious pairs: dict tuple str, str , int = field suspicious sequences: dict tuple str, ... , int = field ⋮---- class ComboDetector ⋮---- """Detects suspicious tool call combinations within a session. Call… 证据：`agentlock/signals/combos.py`
- **System prompt leakage**（source_file）：all = "EchoDetector", "EchoSignal", "EchoConfig" ⋮---- DEFAULT ECHO PATTERNS: list tuple str, re.Pattern str , int = ⋮---- System prompt leakage ⋮---- Tool enumeration in response ⋮---- Configuration disclosure ⋮---- Role confusion / persona hijacking echo ⋮---- Instruction-following language in suspicious contexts ⋮---- @dataclass slots=True class EchoSignal ⋮---- """Result from echo detection.""" ⋮---- pattern name: str weight: int matched text: str = "" details: str = "" ⋮---- @dataclass class EchoConfig ⋮---- """Configuration for echo detection.""" ⋮---- patterns: list tuple str, re.Pattern str , int = field Tool names to check for echoing set by the deployer known tool names: list str… 证据：`agentlock/signals/echo.py`
- **Prompt Scan**（source_file）：all = "PromptScanner", "PromptScanConfig" ⋮---- INJECTION PATTERNS: list tuple str, re.Pattern str = ⋮---- AUTHORITY PATTERNS: list tuple str, re.Pattern str = ⋮---- INSTRUCTION PLANTING PATTERNS: list tuple str, re.Pattern str = ⋮---- ENCODING PATTERNS: list tuple str, re.Pattern str = ⋮---- r" A-Za-z0-9+/ {40,}={0,2}" base64 string 40+ chars ⋮---- IMPERSONATION PATTERNS: list tuple str, re.Pattern str = ⋮---- FORMAT FORCING PATTERNS: list tuple str, re.Pattern str = ⋮---- RETRIEVAL PATTERNS: list tuple str, re.Pattern str = ⋮---- @dataclass class PromptScanConfig ⋮---- """Configuration for the prompt scanner.""" ⋮---- detect injection: bool = True detect authority: bool = True detect plan… 证据：`agentlock/signals/prompt_scan.py`
- **Risk level ordering for topic escalation detection**（source_file）：all = "VelocityDetector", "VelocitySignal", "VelocityConfig" ⋮---- @dataclass slots=True class VelocitySignal ⋮---- signal type: str weight: int details: str = "" ⋮---- Risk level ordering for topic escalation detection RISK ORDER: dict str, int = { ⋮---- @dataclass slots=True class CallRecord ⋮---- tool name: str risk level: str timestamp: float ⋮---- @dataclass class VelocityConfig ⋮---- rapid calls count: int = 3 rapid calls window: float = 60.0 rapid calls weight: int = 2 burst count: int = 3 burst window: float = 30.0 burst weight: int = 2 escalation weight: int = 3 ⋮---- class VelocityDetector ⋮---- def init self, config: VelocityConfig None = None - None ⋮---- ts = timestamp if times… 证据：`agentlock/signals/velocity.py`

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

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

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

- 你准备在哪个宿主 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.md, agentlock/__init__.py, agentlock/policy.py, agentlock/types.py
- **三层执行架构**：importance `high`
  - source_paths: agentlock/gate.py, agentlock/token.py, README.md
- **授权门与权限策略**：importance `high`
  - source_paths: agentlock/gate.py, agentlock/policy.py, agentlock/schema.py, schema/agentlock-v1.2.json, schema/agentlock-v1.0.json
- **五种决策类型**：importance `high`
  - source_paths: agentlock/modify.py, agentlock/defer.py, agentlock/stepup.py, agentlock/gate.py, agentlock/redaction.py
- **签名回执与哈希链上下文**：importance `high`
  - source_paths: agentlock/receipts.py, agentlock/context.py, agentlock/audit.py, agentlock/gate.py
- **上下文、内存与信任降级**：importance `high`
  - source_paths: agentlock/context.py, agentlock/memory_gate.py, agentlock/session.py, agentlock/policy.py
- **自适应硬化与信号检测**：importance `high`
  - source_paths: agentlock/hardening.py, agentlock/signals/__init__.py, agentlock/signals/velocity.py, agentlock/signals/combos.py, agentlock/signals/echo.py
- **框架与协议集成**：importance `high`
  - source_paths: agentlock/integrations/__init__.py, agentlock/integrations/langchain.py, agentlock/integrations/crewai.py, agentlock/integrations/autogen.py, agentlock/integrations/mcp.py

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

- repo_clone_verified: true
- repo_inspection_verified: true
- repo_commit: `38c22117f30979b6f115303a3319fb9668db7eee`
- inspected_files: `README.md`, `pyproject.toml`, `docs/benchmark.md`, `docs/integrations.md`, `docs/quickstart.md`, `docs/specification.md`, `examples/data_redaction.py`, `examples/decorator_example.py`, `examples/fastapi_app.py`, `examples/multi_role.py`, `examples/quickstart.py`, `examples/rate_limiting.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: 能力判断依赖假设

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

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

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

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

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

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

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

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

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

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