Skip to main content

教程 09: Custom Legal Skills, Hooks & Agents

Build custom legal skills, compliance hooks, subagents and plugins for Claude Code or Codex, with the same playbook packaged for either tool.

覆盖Claude: 已验证ChatGPT / Codex: 草稿Grok Bot: 已验证

撰写以来的变化最近核查: 2026年6月27日 · 23
  1. Claude hook 与 plugin 控制

    Claude Code 2.1.195 添加 CLAUDE_CODE_DISABLE_MOUSE_CLICKS,修复带连字符 identifiers 的 hook matchers 使其 exact-match,改进 macOS 和 CJK voice dictation,对仅由 project settings 启用的 external plugins 在所有 loader paths 上要求 explicit install consent,修复 package 与 marketplace names 不一致时的 /plugin enable/disable,并改进 background-agent persistence、 restart behavior、Linux voice diagnostics、claude agents completed lists 和 remote-session provisioning checklist。Allowlisted Claude Code Action 现在 bundled Claude Code 2.1.195 和 Agent SDK 0.3.195。

    建议操作: 在无人值守 legal repositories 处理客户数据前,请重新测试 hyphenated hook 和 MCP matcher rules、external plugin consent、/plugin enablement、background-agent restart and persistence、remote-session provisioning、terminal mouse policy、voice dictation assumptions 和 pinned Claude Code Action versions。

    来源: Claude Code changelog · Claude Code Action 2.1.195 bump commit

  2. Codex Remote GA 与 Claude 控制

    OpenAI 6 月 25 日 Codex changelog 表示,Codex Remote 已 generally available, 可从 ChatGPT mobile app 在连接的 Mac 或 Windows host 上启动或继续工作,并为每个 mobile device 和 host 使用 authenticated one-to-one QR pairing。Codex CLI 0.142.2 还让 MCP tools 在支持时默认使用 tool search,启用时为 macOS authentication clients 增加 system-proxy support,加入 dark-mode plugin logos,改进 safety-buffering UI,并修复 remote plugin catalogs、expired Bedrock credential guidance 和 remote stdio MCP working directories。Claude Code 2.1.193 增加 autoMode.classifyAllShell、transcripts 和 UI 中的 auto-mode denial reasons、 assistant-response OpenTelemetry event、MCP-auth startup notices、 background-shell memory-pressure reaping、background-agent fixes、401/403 后的 MCP headersHelper automatic reconnect,以及 plugin auto-rename handling。 Allowlisted Claude Code Action 现在 bundled Claude Code 2.1.193 和 Agent SDK 0.3.193。

    建议操作: 在无人值守 legal repositories 处理客户数据前,请重新测试 mobile remote pairing、connected-host approval policy、DigitalOcean workspace provisioning、MCP tool-search behavior、macOS proxy authentication、plugin catalog 和 logo metadata、Bedrock credential recovery、remote stdio MCP path handling、Claude auto-mode shell classification、denial logging、OpenTelemetry export scope、MCP auth reconnects、background-agent cleanup 和 pinned Claude Code Action versions。

    来源: OpenAI Codex changelog · Claude Code changelog · Claude Code Action 2.1.193 bump commit

  3. Claude Code 凭据与 MCP 控制

    Claude Code 2.1.187 增加 sandbox.credentials,用于阻止 sandboxed commands 读取 credential files 和 secret environment variables;在模型选择界面加入组织配置的 model restrictions;修复 structured-output loops;中止无响应的 remote MCP calls; 改进 subagent depth tracking 和 leaked worktree cleanup;并让 /install-github-app 中的 GitHub Actions workflow setup 变为可选。Allowlisted Claude Code Action 现在 bundled Claude Code 2.1.187 和 Agent SDK 0.3.187。

    建议操作: 在无人值守 workflows 处理客户数据 repositories 前,请重新测试 credential-file 与 secret-environment blocking、organization model restrictions、structured-output schemas、remote MCP idle timeouts、subagent depth caps、worktree cleanup、GitHub App installation choices 和 pinned Claude Code Action versions。

    来源: Claude Code changelog · Claude Code Action 2.1.187 bump commit

  4. Claude 改进 MCP 和 managed settings

    Claude Code 2.1.191 修复了 managed settings refresh 行为,记住当前 session 允许的 sandbox network hosts,重试 transient MCP capability-discovery 和 OAuth requests,改进 MCP 404 diagnostics,并防止 stopped background agents 重新启动。Allowlisted 的 Claude Code Action 现在默认捆绑 Claude Code 2.1.191 和 Agent SDK 0.3.191。

    建议操作: 对 legal automation,请 pin 包含 2.1.191 的 Claude Code Action version, 重新测试 MDM 或 file-policy refresh,记录每个 session 可批准的 sandbox network hosts,并在 agents 处理 client-data repositories 前验证 MCP health checks 和 OAuth recovery。

    来源: Claude Code changelog · Claude Code Action 2.1.190 bump commit · Claude Code Action 2.1.191 bump commit

  5. Claude Action 过滤后续 review

    一个 allowlisted Claude Code Action commit 现在会按 authorized trigger time 过滤 pull-request reviews 和 inline review comments,与现有 issue/PR comments 和 bodies 的过滤保持一致。该 fix 关闭了一个 TOCTOU gap:trigger 之后提交或编辑的 reviews 或 inline comments 可能被渲染进 Claude 的 prompt。

    建议操作: 对 legal PR agents,请 pin 包含该 fix 的 action version,把 trigger 之后新增的 review threads 视为 untrusted reference material,保持 checkout credentials non-persistent,并在 agent-authored changes 应用于 client-data repositories 前要求 human merge gate。

    来源: Claude Code Action trigger-time review filtering commit

  6. Codex 远程执行与 Claude 可靠性控制

    OpenAI 6 月 18 日的 Codex CLI 0.141.0 changelog 增加了用于 remote executors 的 authenticated end-to-end encrypted Noise relay channels,保留 executor-native working directories 和 shells,按 thread 激活 selected plugin stdio MCP servers, 改进 app-server child-thread 与 rate-limit-credit APIs,增加 TUI prompt auto-resolution, 并修复 hooks、plugin routing、Windows sandbox、SQLite WAL-reset 和 TLS enterprise proxy reliability。Claude Code 2.1.181 增加 /config key=value、opt-in sandbox.allowAppleEvents、更强 API retries、更安全的 network/cloud-synced folder writes、MCP tools/list failure visibility,Claude Code Action 现在默认安装 2.1.181。

    建议操作: 对法律团队,请在无人值守 agents 处理客户数据 repositories 前,重新检查 remote executor trust、working-directory boundaries、shell policy、plugin-selected MCP servers、hook bypass decisions、Windows sandbox credentials、SQLite-backed session stores、enterprise TLS inspection、Claude Apple Events permissions、cloud-folder file-write behavior、MCP health reporting 和 GitHub Action version pins。

    来源: OpenAI Codex changelog · OpenAI Codex Record & Replay documentation · Claude Code changelog · Claude Code Action 2.1.181 bump commit · Claude Code Action 2.1.183 bump commit

  7. Codex 区域推出与 Claude 可靠性修复

    OpenAI 6 月 16 日的 Codex changelog 表示,Computer Use、Codex Chrome extension、Memories 和 Chronicle research preview 正在 EEA、UK 和 Switzerland 推出,且 Memories 在这些地区默认关闭。Claude Code 2.1.179 修复了 mid-stream connection drops、大型 Linux sandbox read-rule glob expansion、remote-session background-task status、subagent transcript/focus issues,以及 remote plugin-loading performance;allowlisted Claude Code Action 也升至 2.1.179。

    建议操作: 对这些地区的法律团队,请在客户数据 workflow 前确认 user consent、device policy、Chrome signed-in context、memory defaults、Chronicle opt-in scope、sandbox file-rule behavior、partial-output audit trails、background-task status、subagent transcript review 和固定的 Claude Action version。

    来源: OpenAI Codex changelog · Claude Code changelog · Claude Code Action 2.1.179 bump commit

  8. Codex 使用控制与 Claude 权限规则

    OpenAI 6 月 15 日的 Codex CLI 0.140.0 changelog 增加了 /usage token-activity views、永久删除 session、Claude Code import、统一的 file/plugin/skill mentions、managed Bedrock API-key authentication、加密的 CLI/MCP OAuth credential storage、MCP startup 和 OAuth reliability fixes,以及 remote plugin installation fixes。Claude Code 2.1.178 增加了 parameter-scoped permission rules、nested .claude/skills loading、closest-directory project settings precedence、针对 subagent spawns 的 auto-mode review,并修复 MCP subagent disallowedTools

    建议操作: 对法律团队,请在让 repository agents 运行于客户数据系统前,重新检查 token usage audit evidence、session-retention 和 deletion policy、导入的 Claude Code project settings、Bedrock/API credentials、OAuth storage、plugin provenance、nested skill precedence、parameter-scoped tool rules、subagent auto-mode review 和 MCP deny rules。

    来源: OpenAI Codex changelog · Claude Code changelog · Claude Code Action 2.1.178 bump commit

  9. Claude Action 收紧 allowed-tools 解析

    Allowlisted Claude Code Action commits 修复了两个 claude_args 解析缺口:未加引号的 scoped Bash 规则如 Bash(gh:*) 可能变成更宽的 Bash access;当存在多个值或注释行时,MCP server 安装也可能偏离 SDK 解析出的 --allowedTools grant。

    建议操作: 对法律仓库自动化,请为 scoped tool rules 加引号,避免在 --allowedTools blocks 中保留注释掉的 grants,固定 action 版本,并在 workflow 接触客户数据仓库前,将 MCP server 安装与实际授予的工具逐项核对。

    来源: Claude Code Action scoped Bash permission parser fix · Claude Code Action MCP allowed-tools parser alignment

  10. Codex 浏览器调试与 Claude Action 可靠性

    OpenAI 6 月 11 日的 Codex app 26.609 changelog 增加了通过 Chrome DevTools Protocol access 使用 Browser use 的 Developer mode、app composer 中的 /init、Computer Use 扩展和 Windows per-app access controls、usage-limit guidance、plugin management improvements,并修复 scheduled automations 以遵守所选 approval mode。Allowlisted Claude Code Action commits 还将 Claude Code 升至 2.1.175,在 inputs 为空时保留继承的 auth environment variables,并防止 SDK workflows 在 terminal result message 后挂起。

    建议操作: 对法律团队,请在让 agents 运行于客户数据仓库前,重新检查 Browser Developer mode 授权、捕获的 console/network data、Computer Use app 范围、scheduled automation approval modes、plugin provenance、Claude Action credential precedence 和 workflow timeout handling。

    来源: OpenAI Codex changelog · Claude Code Action auth fallback commit · Claude Code Action SDK iterator commit · Claude Code Action 2.1.175 bump commit

  11. Guardrail 与 Claude workflow 控制已更新

    OpenAI 6 月 4 日 API changelog 为 Responses 和 Chat Completions 生成请求增加 moderation scores;Claude Code 2.1.163 增加 managed minimum/maximum version settings、/plugin list、hook continuation context、MCP session ID continuity,并修复多项 permission、background-session 和 Windows 可靠性问题;Claude Code 2.1.165 是可靠性版本。

    建议操作: 对法律 workflow,请记录 inline moderation results 但不要存储敏感 prompt text,法律结论仍保留律师审查,通过 managed settings 固定 Claude Code 版本,用 /plugin list 审计 enabled plugins,并在无人值守处理客户数据前重新测试 hook/MCP 行为。

    来源: OpenAI API changelog · OpenAI Moderation guide · Claude Code changelog · Claude Code Action dependency update

  12. Codex Sites 与 Claude workflow 身份控制

    OpenAI 6 月 2 日的 Codex changelog 在 Codex app 中加入 Sites preview、iOS Codex 的 Face ID 或 passcode lock 控制、Queue/Steer follow-up 默认设置、Windows SSH 连接、/side <prompt>,并修复 host/task 可靠性问题。OpenAI API changelog 还将符合条件的 container sessions 改为按分钟计费并设置 5 分钟最低用量;一个 allowlisted Claude Code Action commit 则向 base action 添加 workload identity federation 输入,并要求 GitHub OIDC write permission 用于 OIDC token exchange。

    建议操作: 对法律 workflow,请在面向客户数据系统使用 Codex Sites 或 Claude Actions 前,审查 hosted-site 范围、environment variables 和 secrets、移动设备策略、Windows SSH 信任、container-session 成本控制、GitHub OIDC 权限、federation rule 归属以及静态凭据 fallback。

    来源: OpenAI Codex changelog · OpenAI API changelog · Claude Code Action workload identity federation commit

  13. Codex 与 Claude agent 运维已更新

    Codex CLI 0.131.0 增加了更丰富的 TUI 控制、统一的文件/plugin/skill mentions、plugin marketplace 命令、remote-control 支持、openai-codex Python SDK 包和 codex doctor;Claude Code 2.1.144 增加后台 session resume,并修复 plugin、MCP、headless、remote-login 和后台 agent 可靠性问题。

    建议操作: 对法律仓库,在 rollout 前请 pin 并测试 agent CLI 版本;在无人值守或涉及客户数据的 workflow 前,验证 plugin 依赖链、MCP 分页/tool list、remote-login policy、后台 session 隔离、Python SDK 包名和诊断输出。

    来源: OpenAI Codex changelog · Claude Code changelog

  14. 法律工作流的远程 Codex 与 Claude agent 控制

    OpenAI Codex changelog 增加了通过连接的 Mac 进行移动端远程访问,并补充 hooks、access token 和 enterprise setup 指南;Claude Code 2.1.143 收紧了 plugin、worktree、hook、后台 session 和 Windows 行为。

    建议操作: 在远程或后台法律 agent 工作前,请确认可信主机、token 范围、plugin 依赖链、worktree 隔离模式、MCP 设置、hook stop 策略和人工审查关卡。

    来源: OpenAI Codex changelog · Claude Code release notes

  15. Claude Code 2.1.141 的 hook、plugin 和 agent 控制

    Claude Code 2.1.141 增加 hook terminal-sequence 输出、HTTPS plugin 克隆、workspace 级 federation、按目录列出 agent、包含近期 session 的反馈 bundle,以及 background agent 权限修复。

    建议操作: 对法律 workflow,请重新测试会发送通知或设置终端标题的 hooks;没有 SSH key 时优先使用 HTTPS plugin 安装;用 claude agents --cwd 限定 agent 审计范围;并确认 background agent 保留预期 permission mode。

    来源: Claude Code changelog · Claude Code Action 2.1.141 dependency update

  16. Claude Code 2.1.139 更新 agent、hook 和 MCP 控制

    Claude Code 2.1.139 增加 agent view、/goal、hook 参数直接执行、PostToolUse 继续、MCP 项目目录环境支持和 subagent 遥测 headers。

    建议操作: 在客户或特权工作流中使用 Claude Code 前,请在带审计日志和人工审查的沙盒中重新测试 hooks、MCP 配置和目标驱动会话。

    来源: Claude Code changelog · Claude Code action bump

  17. 面向法律仓库的 Codex Auto-review 与 repair-loop 指南

    OpenAI 扩展了 Codex Auto-review 文档,并发布了使用 traces 和 evals 的 Codex 迭代修复与 agent 改进循环 cookbook 示例。

    建议操作: 请将 Auto-review 视为额外批准信号,而非法律签批;明确 sandbox 边界、eval 标准、来源检查和人工 diff 审查。

    来源: Codex changelog · Codex Auto-review · Codex agent improvement loop cookbook · Codex iterative repair loop cookbook

  18. OpenAI 模型、计划与 Responses API 文档更新

    OpenAI 文档现在强调当前 GPT-5.5/GPT-5.4 时代模型、更新后的 ChatGPT 计划命名,以及用于新 API 工作流的 Responses API 和内置工具。

    建议操作: 对法律工作流,避免陈旧的 GPT-4 或固定价格建议;面向客户试点前请核查当前模型、计划、工具、保留设置和审核控制。

    来源: OpenAI models · ChatGPT pricing · GPT-5.5 in ChatGPT · Responses API migration · OpenAI tools guide · Code Interpreter tool

  19. Claude Code 2.1.133 自动化可靠性更新

    Claude Code 增加了 worktree 基准控制、感知 effort 的 hooks、托管 sandbox 设置,并修复 MCP OAuth、subagent skill 发现和并发会话问题。

    建议操作: 对法律自动化 agent,请明确固定 worktree 行为,并在生产运行前复测 hooks、MCP 认证和 subagent skill 发现。

    来源: Claude Code changelog

  20. 法律工作流的 Codex 应用自动化回补

    Codex 文档现在强调周期性应用自动化、关联仓库 worktree、浏览器权限、subagent、plugin,以及 CLI sandbox 或 approval profile 控制。

    建议操作: 运行无人值守法律 agent 前,请固定 sandbox 和 approval 设置,明确来源 allowlist,并通过可审查 PR 处理 Codex 自动化变更。

    来源: Codex changelog · Codex Automations · Codex worktrees · Codex browser extension · Codex subagents · Codex plugins · Codex sandboxing

  21. OpenAI Realtime 与 Codex 插件更新

    OpenAI 发布了 Realtime 2、流式翻译和转录更新,以及面向 Codex 的 OpenAI Developers 插件。

    建议操作: 对法律接待或多语言语音流程,请先核查 realtime 模型和 API 指南,再做面向客户的试点。

    来源: OpenAI API changelog

  22. 面向法律内容工作流的 Claude Code 自动化模式

    Claude Code GitHub Actions 支持定时和事件驱动的编码工作流,包括 skills 和提示词驱动的自动化,可帮助维护教程质量。

    建议操作: 在翻译批次运行前,让 Claude 教程与当前 GitHub Action 和 skill 行为保持一致。

    来源: Claude Code GitHub Actions · Claude Code overview

  23. 面向法律 AI 教程的每日 Codex 自动化流程

    我们正在加入基于可信来源的自动化流程,用于跟踪 Codex 和 Claude 变化、提出教程更新,并把已批准的更改交给翻译 agent。

    建议操作: 使用更新页面查看变化内容、已核查来源以及需要刷新的教程。

    来源: Codex Automations · Codex Skills · Codex internet access

你将学到什么

本教程将向你展示如何构建自定义法律技能、添加安全检查(hooks),以及运行多代理工作流。需要具备一定的技术基础。

专家级

建议具备开发者技能。预计时间:120 分钟。

学习目标

完成本教程后,你将能够:

  • 理解 Claude Code 和 Codex 中的编码代理栈(skills、hooks、subagents、plugins)
  • 为你所在律所的工作流构建自定义法律技能
  • 创建用于质量控制和合规的 hooks
  • 部署用于复杂法律任务的多代理系统

第 1 部分:理解编码代理栈

Claude Code 和 Codex 共享相同的五个构建模块。文件格式不同;法律设计并无不同。

Official Claude Code screenshot showing Claude in a code editor workflow

Claude Code 的官方 Claude 截图。对于法律工作流仓库,建议将 Claude Code 任务与权限边界、hook 检查以及可审查的差异对比配合使用。

CLAUDE CODE STACK (docs checked 2026-09-02)

├── SKILLS        SKILL.md folders in ~/.claude/skills/ or .claude/skills/;
│                 Claude loads them when relevant or you run /skill-name
├── HOOKS         Commands, HTTP endpoints, MCP tools or prompts that run at
│                 lifecycle events, configured in settings.json
├── SUBAGENTS     Markdown agents in .claude/agents/ or ~/.claude/agents/
│                 with their own tools, model and permission mode
├── MCP SERVERS   External tool connections (Tutorial 07)
└── PLUGINS       .claude-plugin/plugin.json + skills/, agents/, hooks/, .mcp.json

为什么这对法律工作很重要

ComponentLegal Application
Skills编码操作手册、审查流程和起草标准
Hooks强制合规、防止未授权操作、审计日志记录
Subagents并行处理文档审查和研究任务
Plugins打包律所工作流以便分发

第 2 部分:构建自定义法律技能

Skills 是什么?

Skills 是存储在 SKILL.md 文件中的专门化指令,并可附带支持资源。与一次性 prompt 不同,skill 会持续存在,并在任务与其描述匹配时激活。Claude Code 和 Codex 都使用相同的 SKILL.md 布局(Codex 遵循 Agent Skills 开放标准),因此一个 skill 文件夹即可同时服务于这两种工具。

Skill 文件结构

your-skill/
├── SKILL.md          # Main instructions (required)
├── examples/         # Example inputs/outputs
│   ├── good-review.md
│   └── bad-review.md
├── templates/        # Document templates
│   ├── nda-template.docx
│   └── redline-template.docx
└── resources/        # Reference materials
    ├── playbook.json
    └── clause-library.md

创建合同审查 Skill

步骤 1:创建 Skill 目录

mkdir -p ~/.claude/skills/contract-review   # personal; use .claude/skills/ in a repo to share
cd ~/.claude/skills/contract-review

步骤 2:编写 SKILL.md

# Contract Review Skill
 
## Purpose
此 skill 提供全面的合同审查能力,
并与 [Firm Name] 的标准实践保持一致。
 
## Activation
在以下情况下激活此 skill:
- 用户上传合同文件
- 用户提到“合同审查”或类似表述
- 用户提及特定合同类型(NDA、MSA、SaaS 等)
 
## Process
 
### Step 1: Classification
在分析前,识别以下内容:
1. **Contract Type**: NDA、MSA、SaaS、License、Services 等
2. **Our Role**: 我们代表哪一方?
3. **Counterparty Profile**: 企业、中端市场公司、初创公司?
4. **Deal Tier**: 预计金额及战略重要性
 
### Step 2: Document Processing
- 在提供分析前通读整份合同
- 记录所有定义术语及其定义
- 识别 governing law 和 dispute resolution
- 梳理条款结构和交叉引用
 
### Step 3: Playbook Application
应用 `resources/playbook.json` 中的立场:
- 将每项条款与标准立场进行比较
- 识别偏离之处并评估严重程度
- 标明缺失的必备条款
 
### Step 4: Risk Assessment
对于每个问题:
- 分配严重等级:RED | YELLOW | GREEN
- 解释实际业务影响
- 考虑与其他条款的相互作用
 
### Step 5: Redline Generation
对于 RED 和 YELLOW 问题:
- 提供具体的替代措辞
- 在适用时引用条款库
- 解释修改理由
 
### Step 6: Output Generation
按以下结构输出回复:
1. Executive Summary(3-5 句)
2. Deal Parameters Table
3. Clause-by-Clause Analysis
4. Risk Score and Escalation Recommendation
5. Negotiation Priorities
6. Questions for Business Team
 
## Clause Library
参考 `resources/clause-library.md` 中的批准措辞。
 
## Examples
请参见 `examples/` 目录中的良好和不良审查示例。
 
## Calibration Notes
- Liability cap thresholds 已于 2026 年 1 月更新
- 根据 GDPR 变更更新了新的数据处理要求
- 需要使用更新后的 AI/ML 条款措辞
 
## Quality Requirements
- 未作适当限定时,绝不提供法律建议
- 标记任何需要进行法域核验的条款
- 当 playbook 未涵盖特定条款时予以说明
- 对于金额超过 $500K 的交易,建议升级处理

步骤 3:创建 Playbook 资源

resources/playbook.json:

{
  "contract_types": {
    "SaaS_Customer": {
      "liability": {
        "standard": "12 months fees",
        "minimum": "total contract value",
        "carve_outs": ["indemnification", "data_breach", "confidentiality", "IP", "gross_negligence", "willful_misconduct"]
      },
      "indemnification": {
        "required_vendor": ["IP_infringement", "data_breach", "security_failure"],
        "acceptable_exclusions": ["customer_modifications", "third_party_components_with_notice"]
      },
      "data": {
        "ownership": "customer",
        "vendor_rights": "service_delivery_only",
        "prohibited_uses": ["AI_training", "analytics", "marketing", "sale"],
        "retention_limit": "30_days_post_termination"
      }
    }
  },
  "severity_matrix": {
    "RED": [
      "unlimited_customer_liability",
      "no_vendor_indemnity",
      "data_used_for_AI_training",
      "no_termination_for_convenience"
    ],
    "YELLOW": [
      "liability_cap_below_12_months",
      "narrow_indemnity_carveouts",
      "60_plus_day_termination_notice"
    ]
  }
}

步骤 4:创建条款库

resources/clause-library.md:

# Approved Clause Language Library
 
## Limitation of Liability
 
### Standard Mutual Cap
“因本协议产生或与本协议相关的各方全部责任总额,
不得超过客户在提出索赔前十二(12)个月内
已支付或应支付的费用。”
 
### Uncapped Carve-Outs Addition
“前述责任限制不适用于: (A) 任一方的
赔偿义务;(B) 违反第 [DATA SECURITY] 条;
(C) 违反保密义务;(D) 任一方的
重大过失或故意不当行为;或 (E) 客户的付款义务。”
 
## Data Ownership
 
### Customer Ownership Clause
“在双方之间,客户保留对客户数据的一切权利、所有权和
利益。除本协议项下授予的有限许可外,供应商
不取得客户数据的任何权利。”
 
### No AI Training Clause
“供应商不得使用客户数据或其任何衍生物
来训练、开发或改进任何机器学习模型、
人工智能系统或类似技术。”
 
[Continue with additional clauses...]

步骤 5:安装并测试

# Discovered from ~/.claude/skills/ (personal) and .claude/skills/ (project).
# Add a `description` line to the SKILL.md frontmatter so Claude knows when to use it.
# Start a new session, then test:
claude "I need to review a software agreement"
# or invoke it explicitly:
/contract-review

第 3 部分:构建合规 Hooks

Hooks 是什么?

Hooks 是在代理生命周期特定节点运行的脚本(或 MCP 工具)。Claude Code 和 Codex 使用相同的核心事件名称:

生产环境提示: Hooks 可以阻止或改变工作流。在将其用于客户事项或特权文档之前,请先在具备真实权限、effort levels 和 MCP servers 的沙箱中进行测试。

Claude Code 2.1.139 为 hook 增加了 exec-form 的 args 字段以及用于 PostToolUsecontinueOnBlock。对于接收文件路径或事项标识符的 hooks,优先使用 exec-form 参数,因为这样可以避免 shell 引号问题。仅当 hook 的拒绝理由可以安全地反馈给模型,且不会泄露特权或机密事实时,才使用 continueOnBlock

Hook TypeTrigger PointUse Case
PreToolUse在任何工具运行之前阻止危险操作
PostToolUse工具完成之后审计日志记录
SessionStart会话开始时加载上下文
UserPromptSubmit在 prompt 处理之前过滤内容
Stop代理完成响应时质量检查

法律合规 Hook 示例

目的:防止代理对特权文档进行未授权更改。

步骤 1:创建 Hook 目录

mkdir -p ~/.claude/hooks

步骤 2:创建 Hook 脚本

~/.claude/hooks/pretool-privileged-guard.sh:

#!/usr/bin/env bash
set -euo pipefail
 
input="$(cat)"
tool_name="$(jq -r '.tool_name // ""' <<<"$input")"
path_value="$(jq -r '.tool_input.file_path // .tool_input.path // ""' <<<"$input")"
 
if [[ "$tool_name" =~ ^(Read|Write|Edit)$ ]] && \
   ([[ "$path_value" == *"/Privileged/"* ]] || [[ "$path_value" == *"/Attorney-Client/"* ]]); then
  jq -n '{
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason: "Privileged folder access requires explicit user approval."
    }
  }'
  exit 0
fi
 
exit 0

~/.claude/hooks/posttool-audit-log.sh:

#!/usr/bin/env bash
set -euo pipefail
 
mkdir -p "$HOME/.claude/logs"
input="$(cat)"
echo "$input" >> "$HOME/.claude/logs/legal-hooks-audit.jsonl"
exit 0

步骤 3:配置 Hook

~/.claude/settings.json(用户范围)或 .claude/settings.json(项目级,可共享):

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Read|Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "\"$HOME/.claude/hooks/pretool-privileged-guard.sh\""
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Read|Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "\"$HOME/.claude/hooks/posttool-audit-log.sh\""
          }
        ]
      }
    ]
  }
}

其他 Hook 用例

Citation Verification Hook (Stop)

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "\"$HOME/.claude/hooks/stop-citation-warning.sh\""
          }
        ]
      }
    ]
  }
}

Confidentiality Check Hook

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "WebSearch|WebFetch",
        "hooks": [
          {
            "type": "command",
            "command": "\"$HOME/.claude/hooks/pretool-confidentiality-check.sh\""
          }
        ]
      }
    ]
  }
}

第 4 部分:多代理法律工作流

理解 Sub-Agents

两种代理都可以生成 subagents 来处理特定任务:

  • 并行化:同时审查多份文件
  • 专门化:不同代理处理不同任务
  • 隔离:不同分析使用独立上下文

可将 subagent 定义为带有 frontmatter(namedescription,可选 toolsmodelpermissionMode)的 Markdown 文件,放在项目的 .claude/agents/ 或所有项目共用的 ~/.claude/agents/ 中,然后在 prompt 中写出其名称或使用 @ 提及(subagents docs,检查日期为 2026-09-02)。Claude Code 2.1.141 增加了 claude agents --cwd <path>,可将会话列表范围限定到某个目录;通过 /bg 启动的后台代理会保留当前权限模式。在分配特权文档或仓库写入任务前,请核实后台会话保持了预期的权限状态。

示例:并行尽职调查审查

// Due Diligence Multi-Agent Workflow
 
const agents = [
  {
    name: 'contract-reviewer',
    task: 'Review all customer agreements',
    folder: '/DD/Contracts/Customers',
    instructions: 'Apply customer agreement playbook'
  },
  {
    name: 'ip-reviewer',
    task: 'Review all IP agreements',
    folder: '/DD/Contracts/IP',
    instructions: 'Apply IP agreement playbook'
  },
  {
    name: 'employment-reviewer',
    task: 'Review all employment agreements',
    folder: '/DD/Contracts/Employment',
    instructions: 'Apply employment agreement playbook'
  },
  {
    name: 'litigation-reviewer',
    task: 'Analyze all pending litigation',
    folder: '/DD/Litigation',
    instructions: 'Assess litigation exposure and reserves'
  }
];
 
// Spawn all agents in parallel
const results = await Promise.all(
  agents.map(agent =>
    claude.spawnAgent({
      name: agent.name,
      prompt: `${agent.task} in ${agent.folder}. ${agent.instructions}.
               Output findings in structured JSON format.`,
      timeout: 30 * 60 * 1000 // 30 minute timeout
    })
  )
);
 
// Synthesize results
const synthesis = await claude.prompt(`
  I've received due diligence findings from ${agents.length} specialized reviewers.
 
  ${results.map((r, i) => `
  ## ${agents[i].name} Findings:
  ${r.output}
  `).join('\n')}
 
  Please synthesize into:
  1. Executive Summary of DD findings
  2. Critical issues requiring immediate attention
  3. Risk matrix by category
  4. Recommended deal adjustments
  5. Items requiring seller disclosure
`);

示例:研究 + 起草工作流

// Legal Research + Drafting Multi-Agent Workflow
 
async function researchAndDraft(topic, jurisdiction, outputType) {
  // Stage 1: Research Agent
  const research = await claude.spawnAgent({
    name: 'legal-researcher',
    prompt: `Research ${topic} under ${jurisdiction} law.
             Use available legal research tools (Midpage, CourtListener).
             Provide comprehensive analysis with citations.
             Format as structured legal memorandum outline.`,
    tools: ['midpage', 'courtlistener', 'webSearch']
  });
 
  // Stage 2: Draft Agent (uses research output)
  const draft = await claude.spawnAgent({
    name: 'legal-drafter',
    prompt: `Based on this research:
             ${research.output}
 
             Draft a ${outputType} addressing ${topic}.
             Include all relevant citations.
             Follow firm style guide.`,
    context: research.output
  });
 
  // Stage 3: Review Agent
  const review = await claude.spawnAgent({
    name: 'quality-reviewer',
    prompt: `Review this draft for:
             1. Legal accuracy
             2. Citation completeness
             3. Style compliance
             4. Missing analysis
 
             Draft:
             ${draft.output}`,
    context: draft.output
  });
 
  return {
    research: research.output,
    draft: draft.output,
    review: review.output
  };
}

第 5 部分:将 Skills 打包为 Plugins

Plugin 结构

legal-contract-plugin/
├── .claude-plugin/
│   └── plugin.json       # Manifest: name, description, version
├── skills/
│   └── contract-review/
│       └── SKILL.md      # Skills become /legal-contract-plugin:contract-review
├── agents/               # Subagent definitions
├── hooks/
│   └── hooks.json        # Event handlers
├── .mcp.json             # MCP server config
└── README.md

只有 plugin.json 放在 .claude-plugin/ 内;其他所有内容都位于 plugin 根目录(plugins docs,检查日期为 2026-09-02)。

Plugin Manifest 和 Hooks

Manifest schema 会演进;请使用官方参考文档确认当前字段。一个最小化的 hooks/hooks.json 可同时用于两种工具:

{
  "description": "Legal compliance checks",
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Read|Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/hooks/pretool-privileged-guard.sh"
          }
        ]
      }
    ]
  }
}

安装与分发

# Local development (session-scoped); /reload-plugins picks up edits
claude --plugin-dir /absolute/path/to/legal-contract-plugin
claude plugin validate ./legal-contract-plugin
 
# Marketplace install (recommended for team rollout)
/plugin marketplace add your-org/your-marketplace
claude plugin install legal-contract-review@your-marketplace --scope project
 
# Lifecycle operations
claude plugin enable legal-contract-review@your-marketplace --scope project
claude plugin update legal-contract-review@your-marketplace --scope project

对于没有 GitHub SSH key 的环境,Claude Code 2.1.141 增加了 CLAUDE_CODE_PLUGIN_PREFER_HTTPS,以便通过 HTTPS 克隆 GitHub plugin 源。使用 workload identity federation 的企业团队还可以设置 ANTHROPIC_WORKSPACE_ID,当 federation 规则覆盖多个 workspace 时,将铸造的 tokens 限定到特定 workspace。


第 6 部分:安全注意事项

Skill 安全

  • 来源验证:仅从可信来源安装 skills
  • 代码审查:部署前审查所有 hook 代码
  • 不得包含客户数据:切勿在 skill 文件中包含客户数据
  • 版本控制:跟踪 skills 的变更
  • 访问控制:限制可修改律所 skills 的人员

数据保护

// Example: UserPromptSubmit sanitization hook (conceptual)
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "\"$HOME/.claude/hooks/userprompt-sanitize.sh\""
          }
        ]
      }
    ]
  }
}

合规要求

  • Skills 已由 IT 安全团队审查
  • Hooks 已在沙箱环境中测试
  • 已启用审计日志记录
  • 已验证客户数据隔离
  • 已配置访问控制
  • 已记录备份流程

现在就做

  • 为你所在律所的某个审查流程创建一个自定义 skill
  • 至少添加一个用于合规或审计日志记录的安全检查(hook)
  • 测试一个用于并行文档处理的多代理工作流
  • 记录你的 skill,以便团队使用
  • 考虑将其打包为 plugin 以便分发

相关内容


导航


Quick Reference: Claude Code Commands

Official Claude Code terminal screenshot showing Claude running in a command-line workflow

Official Claude screenshot from Claude Code. Terminal workflows should be paired with scoped folders, explicit permission modes, and a reviewable diff before legal workflow changes are accepted.

# Skills (filesystem locations)
~/.claude/skills/           # Personal custom skills
.claude/skills/             # Project custom skills
 
# Hooks
/hooks                      # Open hooks manager in Claude Code
 
# Plugin hooks
${CLAUDE_PLUGIN_ROOT}/hooks/hooks.json
 
# Debugging
claude --help

来源

延伸阅读