The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
feat(gateguard): gate sensitive targets in subagents
Jeffrey Montoya15d4f169d34e
diff --git a/docs/gateguard/design-notes.md b/docs/gateguard/design-notes.mdindex 13265ff7f..127e9bdf2 100644--- a/docs/gateguard/design-notes.md+++ b/docs/gateguard/design-notes.md@@ -482,3 +482,21 @@ judged by file name: `state-proj-*` uses 30 minutes, any other key 8 hours.A session id that itself starts with `proj-` gets the short window for bothexpiry and pruning, which can only expire state sooner. Temporary files from interrupted writesare never loaded and always use the short window.++## Subagents++File gates skip subagent calls (a non-empty string `agent_id`, `agentId`,+`parent_tool_use_id` or `parentToolUseId`): the parent was already gated on+the work it delegated, and a subagent writing many files would otherwise draw+one denial per file. Shell gates were never skipped, so a subagent can+already receive a denial, present facts and retry.++Sensitive targets are the exception. A subagent Edit, Write or MultiEdit+entry on a sensitive target is denied once per path with the full sensitive+denial, unless the parent already gated that path. Prior-search credit, the+change profile, sibling collapse and the denial cap never apply, as at top+level. The subagent's denial marks a separate subagent key, not the file's+key, so a subagent's retry never unlocks the path for the parent, whose own+first touch is still gated. The keys share the parent's state file when the+subagent's call carries the parent's session id. Exempt globs and Claude+settings files are skipped first, as at top level.diff --git a/docs/ja-JP/skills/gateguard/SKILL.md b/docs/ja-JP/skills/gateguard/SKILL.mdindex 25844287d..ecccc9626 100644--- a/docs/ja-JP/skills/gateguard/SKILL.md+++ b/docs/ja-JP/skills/gateguard/SKILL.md@@ -116,7 +116,7 @@ Triggers on: `rm -rf`, `git reset --hard`, `git push --force`, `drop table`, etc2. What this specific command verifies or produces```-このゲートが発火するまでは、読み取り専用のコマンド(`ls`、`cat`、`rg`、`git status`/`log`/`diff`、`Get-ChildItem` など。リダイレクト、置換、`tee`、`xargs`、未知のコマンドを含まないもの)はゲートを消費せずに通過し `routine_readonly_passes` に数えます。セッション ID またはトランスクリプトパスで識別される状態は 8 時間、プロジェクトディレクトリによるフォールバックは 30 分の無操作で失効します。+このゲートが発火するまでは、読み取り専用のコマンド(`ls`、`cat`、`rg`、`git status`/`log`/`diff`、`Get-ChildItem` など。リダイレクト、置換、`tee`、`xargs`、未知のコマンドを含まないもの)はゲートを消費せずに通過し `routine_readonly_passes` に数えます。セッション ID またはトランスクリプトパスで識別される状態は 8 時間、プロジェクトディレクトリによるフォールバックは 30 分の無操作で失効し、サブエージェントでも機密対象はパスごとに 1 回拒否されます(親のゲートは解除されません)。## すでに済んでいるとみなされるものdiff --git a/docs/zh-CN/skills/gateguard/SKILL.md b/docs/zh-CN/skills/gateguard/SKILL.mdindex b75dccd21..5bb280454 100644--- a/docs/zh-CN/skills/gateguard/SKILL.md+++ b/docs/zh-CN/skills/gateguard/SKILL.md@@ -98,8 +98,8 @@ LLM 的自我评估不起作用。问"你是否违反了任何策略?"答案* **同回合同级文件合并:** 同一目录、同一类别(仅 code、test、prose)的新文件在同一回合内(完全没有 transcript 路径时为 120 秒内)只拒绝第一个,其余以附注放行。config、instruction,以及任何以 `.` 开头的路径段(点文件和所有点目录)或 8.3 短文件名下的文件从不合并;目录按解析符号链接后的真实位置判定和记录;有 transcript 路径但文件缺失、无法读取或得不到回合 ID 时不合并;编辑从不合并。* **拒绝上限(可选):** 设置 `GATEGUARD_FACT_FORCE_MAX_DENIALS` 后,会话内首次触碰的拒绝次数达到该值后,新路径直接放行(计入 `cap_allows`)。`GATEGUARD_FACT_FORCE_FULL_DENIALS` 只决定消息详略(消息预算),而此变量决定是否拦截(拒绝预算)。事先搜索抵免和同级合并先于上限判定,不消耗上限;格式错误的值视为无上限,并在 stderr 警告一次。* **敏感目标:** `.env`/`.env.*`、`*.pem`/`*.key`/`*.p12`/`*.pfx`、`id_rsa*`/`id_ed25519*`/`id_ecdsa*`/`id_dsa*`/`.netrc`/`.pgpass`/`credentials*`/`secrets.*`、任一路径段恰为 `auth`、`authn`、`authz`、`security`、`secrets`、`payment`、`payments`、`billing`、`migrations`,以及 `.github/workflows/` 下的文件,不适用抵免、合并和上限,首次触碰总是拒绝。按字面路径和解析符号链接后的真实位置同时判定(`src/tools -> ../auth` 时 `src/tools/login.py` 也是敏感目标),真实位置无法解析时视为敏感。判定顺序:exempt → subagent → checked → 敏感? → 抵免 → 同级合并 → 上限 → 拒绝。-* **例行 shell 门控与会话:** 门控触发前,只读命令(`ls`、`cat`、`rg`、`git status`/`log`/`diff`、`Get-ChildItem` 等,不含重定向、替换、`tee`、`xargs` 或未知命令)直接放行且不消耗门控,计入 `routine_readonly_passes`;以会话 ID 或 transcript 路径为键的状态空闲 8 小时失效,项目目录回退键仍为 30 分钟。-* **兼容性:** 唯一新增的环境变量是可选的 `GATEGUARD_FACT_FORCE_MAX_DENIALS`;以前允许的操作不会变为拒绝,且从不返回 `permissionDecision: "allow"`。+* **例行 shell 门控与会话:** 门控触发前,只读命令(`ls`、`cat`、`rg`、`git status`/`log`/`diff`、`Get-ChildItem` 等,不含重定向、替换、`tee`、`xargs` 或未知命令)直接放行且不消耗门控,计入 `routine_readonly_passes`;以会话 ID 或 transcript 路径为键的状态空闲 8 小时失效,项目目录回退键仍为 30 分钟;子代理对敏感目标每个路径拒绝一次(不会为父会话解锁)。+* **兼容性:** 唯一新增的环境变量是可选的 `GATEGUARD_FACT_FORCE_MAX_DENIALS`;除子代理首次触碰敏感目标外,以前允许的操作不会变为拒绝,且从不返回 `permissionDecision: "allow"`。## 快速开始diff --git a/manifests/context-packs/[email protected] b/manifests/context-packs/[email protected]index f6bd7d7a9..3693949af 100644--- a/manifests/context-packs/[email protected]+++ b/manifests/context-packs/[email protected]@@ -1 +1 @@-{"coverage":{"skills":293,"withTriggers":32},"generatedAt":"2026-09-24T23:51:22.784Z","id":"skill-triggers@1","model":{"effort":null,"id":"hand-seeded","source":"manual-curation-pending-regeneration"},"registryDigest":"672c16a07a04ec9eb343092c57aa05ec931bacd79fa94977fb572bef2fd816b4","schemaVersion":1,"triggers":{"skill:api-connector-builder":["add api integration","new provider connector","match existing integration pattern"],"skill:api-design":["rest endpoint design","pagination api","status codes","api versioning","rate limiting api","resource naming","filtering api","api error responses","offset pagination","limit query parameter","pagination defaults"],"skill:backend-patterns":["express api","node backend architecture","nextjs api routes","server side patterns","data access layer","static file server","url path handling","file server"],"skill:browser-qa":["deployed feature test","visual regression screenshots","core web vitals check","axe accessibility audit","ship do not ship","staging verification"],"skill:canary-watch":["post deploy monitoring","smoke test url","production url check","console errors production","sse stream check","after deploy verification"],"skill:code-tour":["onboarding walkthrough","explain subsystem","architecture tour","pr walkthrough","rca tour"],"skill:coding-standards":["code review standards","naming conventions","readability review","immutability conventions","fix naming typo","export naming","consistent exports"],"skill:content-hash-cache-pattern":["cache file processing","content addressed cache","sha256 hash cache"],"skill:database-migrations":["zero downtime migration","schema change production","add column large table","backfill data","expand contract","concurrent index","migration rollback","prisma migration","django migration"],"skill:deployment-patterns":["ci cd setup","dockerize app","health checks","rollback strategy","production readiness","deploy pipeline","containerize application"],"skill:design-system":["design tokens","visual consistency audit","css custom properties","ui audit","design system bootstrap"],"skill:django-patterns":["django orm","drf api","django rest framework","django caching","django signals","django middleware"],"skill:django-security":["django authentication","csrf protection","sql injection prevention","xss prevention","django deployment security","role based access control","authorization middleware","permissions checks"],"skill:docker-patterns":["dockerfile review","docker compose setup","container security","multi service orchestration"],"skill:error-handling":["error types","retry logic","circuit breaker","user facing errors","exception handling patterns","typed errors","error boundaries","go error handling","custom error class","error codes","config validation"],"skill:evm-token-decimals":["token decimals","wei conversion","erc20 balance off","bridge token precision"],"skill:frontend-a11y":["aria attributes","screen reader support","focus management","semantic html","form labeling","keyboard navigation react","a11y lint errors"],"skill:git-workflow":["merge vs rebase","commit conventions","resolve merge conflict","branching strategy","clean up commits","pull request cleanup","git history tidy"],"skill:hexagonal-architecture":["ports and adapters","dependency injection boundaries","decouple domain from io"],"skill:kubernetes-patterns":["kubernetes manifests","kubectl debugging","pod probes","k8s rbac","autoscaling config","configmap secrets"],"skill:orch-fix-defect":["fix a bug","broken behavior","regression fix","reproduce bug","defect repair"],"skill:postgres-patterns":["slow postgres query","query optimization","index design","rls policies","supabase schema","postgres indexing","database performance","schema design postgres","postgres driver","node postgres","query planner"],"skill:python-patterns":["pythonic code","pep 8","type hints python","python code review","idiomatic python"],"skill:python-testing":["pytest fixtures","mocking python","parametrized tests","coverage python","tdd python"],"skill:redis-patterns":["cache aside pattern","distributed lock","redis rate limiting","cache invalidation"],"skill:regex-vs-llm-structured-text":["parse invoice","extract receipt data","text extraction pipeline","parse form fields","cheap document parser","extract table data","parse log lines","parse access logs","common log format","log line parsing"],"skill:rust-patterns":["rust ownership","borrow checker","rust error handling","traits rust","rust concurrency","idiomatic rust"],"skill:search-first":["find existing library","npm package research","before writing custom code","evaluate existing tools","add dependency research"],"skill:security-review":["security audit","authentication review","sanitize user input","secrets handling","payment security checklist","prevent injection attacks","secure api endpoints","authn authz review","vulnerability checklist","input validation security","parameterized queries","sql injection"],"skill:security-scan":["audit claude config","claudemd security","mcp server audit","agentshield scan","hook configuration audit","settings json security"],"skill:tdd-workflow":["write test first","failing test","red green refactor","test driven development","regression test first","write a regression test"],"skill:verification-loop":["pre pr checks","verification report","quality gates","build lint test coverage","before creating a pr"]},"triggersDigest":"25b97a9e06fc336c7cf95ab854ed1a41033a54bcd6e1fb1cf69dc906332462aa"}+{"coverage":{"skills":293,"withTriggers":32},"generatedAt":"2026-09-24T23:51:22.784Z","id":"skill-triggers@1","model":{"effort":null,"id":"hand-seeded","source":"manual-curation-pending-regeneration"},"registryDigest":"8327457d64c59c71b4c2d699226e9782854d2512ead87e2e6a2b4a65741d1c22","schemaVersion":1,"triggers":{"skill:api-connector-builder":["add api integration","new provider connector","match existing integration pattern"],"skill:api-design":["rest endpoint design","pagination api","status codes","api versioning","rate limiting api","resource naming","filtering api","api error responses","offset pagination","limit query parameter","pagination defaults"],"skill:backend-patterns":["express api","node backend architecture","nextjs api routes","server side patterns","data access layer","static file server","url path handling","file server"],"skill:browser-qa":["deployed feature test","visual regression screenshots","core web vitals check","axe accessibility audit","ship do not ship","staging verification"],"skill:canary-watch":["post deploy monitoring","smoke test url","production url check","console errors production","sse stream check","after deploy verification"],"skill:code-tour":["onboarding walkthrough","explain subsystem","architecture tour","pr walkthrough","rca tour"],"skill:coding-standards":["code review standards","naming conventions","readability review","immutability conventions","fix naming typo","export naming","consistent exports"],"skill:content-hash-cache-pattern":["cache file processing","content addressed cache","sha256 hash cache"],"skill:database-migrations":["zero downtime migration","schema change production","add column large table","backfill data","expand contract","concurrent index","migration rollback","prisma migration","django migration"],"skill:deployment-patterns":["ci cd setup","dockerize app","health checks","rollback strategy","production readiness","deploy pipeline","containerize application"],"skill:design-system":["design tokens","visual consistency audit","css custom properties","ui audit","design system bootstrap"],"skill:django-patterns":["django orm","drf api","django rest framework","django caching","django signals","django middleware"],"skill:django-security":["django authentication","csrf protection","sql injection prevention","xss prevention","django deployment security","role based access control","authorization middleware","permissions checks"],"skill:docker-patterns":["dockerfile review","docker compose setup","container security","multi service orchestration"],"skill:error-handling":["error types","retry logic","circuit breaker","user facing errors","exception handling patterns","typed errors","error boundaries","go error handling","custom error class","error codes","config validation"],"skill:evm-token-decimals":["token decimals","wei conversion","erc20 balance off","bridge token precision"],"skill:frontend-a11y":["aria attributes","screen reader support","focus management","semantic html","form labeling","keyboard navigation react","a11y lint errors"],"skill:git-workflow":["merge vs rebase","commit conventions","resolve merge conflict","branching strategy","clean up commits","pull request cleanup","git history tidy"],"skill:hexagonal-architecture":["ports and adapters","dependency injection boundaries","decouple domain from io"],"skill:kubernetes-patterns":["kubernetes manifests","kubectl debugging","pod probes","k8s rbac","autoscaling config","configmap secrets"],"skill:orch-fix-defect":["fix a bug","broken behavior","regression fix","reproduce bug","defect repair"],"skill:postgres-patterns":["slow postgres query","query optimization","index design","rls policies","supabase schema","postgres indexing","database performance","schema design postgres","postgres driver","node postgres","query planner"],"skill:python-patterns":["pythonic code","pep 8","type hints python","python code review","idiomatic python"],"skill:python-testing":["pytest fixtures","mocking python","parametrized tests","coverage python","tdd python"],"skill:redis-patterns":["cache aside pattern","distributed lock","redis rate limiting","cache invalidation"],"skill:regex-vs-llm-structured-text":["parse invoice","extract receipt data","text extraction pipeline","parse form fields","cheap document parser","extract table data","parse log lines","parse access logs","common log format","log line parsing"],"skill:rust-patterns":["rust ownership","borrow checker","rust error handling","traits rust","rust concurrency","idiomatic rust"],"skill:search-first":["find existing library","npm package research","before writing custom code","evaluate existing tools","add dependency research"],"skill:security-review":["security audit","authentication review","sanitize user input","secrets handling","payment security checklist","prevent injection attacks","secure api endpoints","authn authz review","vulnerability checklist","input validation security","parameterized queries","sql injection"],"skill:security-scan":["audit claude config","claudemd security","mcp server audit","agentshield scan","hook configuration audit","settings json security"],"skill:tdd-workflow":["write test first","failing test","red green refactor","test driven development","regression test first","write a regression test"],"skill:verification-loop":["pre pr checks","verification report","quality gates","build lint test coverage","before creating a pr"]},"triggersDigest":"25b97a9e06fc336c7cf95ab854ed1a41033a54bcd6e1fb1cf69dc906332462aa"}diff --git a/scripts/hooks/gateguard-fact-force.js b/scripts/hooks/gateguard-fact-force.jsindex 5bec3df59..d6484dd7d 100644--- a/scripts/hooks/gateguard-fact-force.js+++ b/scripts/hooks/gateguard-fact-force.js@@ -2077,6 +2077,24 @@ function siblingNote(gate) {);}+// --- Subagents ---+// see docs/gateguard/design-notes.md#subagents++function subagentGateKey(fileKey) {+ return `__subagent__${crypto.createHash('sha256').update(fileKey).digest('hex').slice(0, 16)}`;+}++function subagentSensitiveDenial(filePath, data, isWrite) {+ if (!isSensitiveTargetFor(filePath, data)) return null;+ const fileKey = canonicalPathKey(filePath, data);+ const subKey = subagentGateKey(fileKey);+ if (isChecked([fileKey, filePath, subKey])) return null;+ const cls = classifyTargetFor(filePath, data);+ const { ok, denials } = markCheckedAndCountDenial(subKey, { cls });+ if (!ok) return allowWithStateWarning();+ return firstTouchDenial(filePath, { isWrite, denials, cls, sensitive: true, profile: null, miss: null });+}+// --- Change profile ---function changeProfileFor(toolName, filePath, edits, content) {@@ -2119,7 +2137,7 @@ function run(rawInput) {}if (inSubagent) {- return rawInput; // parent session already passed the first-touch file gate+ return subagentSensitiveDenial(filePath, data, toolName === 'Write') || rawInput;}const fileKey = canonicalPathKey(filePath, data);@@ -2170,12 +2188,17 @@ function run(rawInput) {}if (toolName === 'MultiEdit') {+ const edits = toolInput.edits || [];if (inSubagent) {- return rawInput; // parent session already passed the first-touch file gate+ for (const edit of edits) {+ const filePath = (edit && edit.file_path) || '';+ if (!filePath || isClaudeSettingsPath(filePath) || isExemptPath(filePath, data)) continue;+ const denial = subagentSensitiveDenial(filePath, data, false);+ if (denial) return denial;+ }+ return rawInput;}- const edits = toolInput.edits || [];-const notes = [];const trivialKeys = new Set();for (const edit of edits) {diff --git a/skills/gateguard/SKILL.md b/skills/gateguard/SKILL.mdindex aa14515a8..c23d5c50d 100644--- a/skills/gateguard/SKILL.md+++ b/skills/gateguard/SKILL.md@@ -233,7 +233,10 @@ For each Edit/Write target (and each MultiEdit entry) the gate decides inthis order; the first rule that applies wins:1. **Exempt** (`GATEGUARD_EXEMPT_GLOBS`, Claude settings files) — allowed.-2. **Subagent** call — allowed (the parent session was already gated).+2. **Subagent** call — allowed (the parent session was already gated),+ except a [sensitive target](#sensitive-targets): denied once per path+ unless the parent already gated it. A subagent's retry does not unlock+ the path for the parent.3. **Already checked** this session — allowed.4. **Sensitive target?** — if so, skip straight to the denial (step 9).5. **Prior-search credit** — allowed with a note.@@ -482,8 +485,8 @@ working.- **One new, opt-in environment variable:**`GATEGUARD_FACT_FORCE_MAX_DENIALS` (unset means no cap). The existingcontrols are unchanged.-- **Nothing previously allowed is now denied.** These rules only remove- denials, and never return `permissionDecision: "allow"`, so other hooks+- **Nothing previously allowed is now denied**, except a subagent's first+ touch of a sensitive target. The other rules only remove denials, and never return `permissionDecision: "allow"`, so other hooksand permission rules still apply.- **Trust limit:** prior-search credit reads the local transcript file,which the agent could in principle write to. The credit verifies observeddiff --git a/tests/hooks/gateguard-fact-force.test.js b/tests/hooks/gateguard-fact-force.test.jsindex e6e8a9e31..3e089c2a0 100644--- a/tests/hooks/gateguard-fact-force.test.js+++ b/tests/hooks/gateguard-fact-force.test.js@@ -6862,6 +6862,58 @@ function runTests() {assert.ok(!fs.existsSync(oldTmp), 'stale temp file is pruned on the short window');});+ // --- Sensitive targets in subagents ---+ const subRun = (tool, toolInput, extra = {}) =>+ runHook({ tool_name: tool, tool_input: toolInput, session_id: 'subagent-sensitive-session', ...extra }, { CLAUDE_SESSION_ID: '', ECC_SESSION_ID: '' });+ const subEdit = (file_path, extra) => subRun('Edit', { file_path, old_string: 'a', new_string: 'b' }, extra);+ const subAgent = { agent_id: 'agent-sens' };++ c3Case('a subagent Edit of a sensitive file is denied once, then its retry passes', () => {+ const first = subEdit('/src/.env', subAgent);+ assert.strictEqual(roDecision(first), 'deny', first.stdout);+ assert.ok(roReason(first).includes(sensLine));+ assert.strictEqual(roDecision(subEdit('/src/.env', subAgent)), undefined, 'subagent retry passes');+ });++ c3Case('a subagent pass on a sensitive file does not unlock it for the parent', () => {+ subEdit('/src/auth/login.js', subAgent);+ assert.strictEqual(roDecision(subEdit('/src/auth/login.js', subAgent)), undefined);+ const parent = subEdit('/src/auth/login.js');+ assert.strictEqual(roDecision(parent), 'deny', 'parent first touch is still gated');+ });++ c3Case('a sensitive file the parent already gated passes in a subagent', () => {+ assert.strictEqual(roDecision(subEdit('/src/secrets.json')), 'deny');+ assert.strictEqual(roDecision(subEdit('/src/secrets.json', { parent_tool_use_id: 'toolu_parent' })), undefined);+ });++ c3Case('subagent Write and MultiEdit of sensitive targets are denied; ordinary targets still pass', () => {+ const write = subRun('Write', { file_path: '/repo/.github/workflows/ci.yml', content: 'x' }, subAgent);+ assert.strictEqual(roDecision(write), 'deny');+ const multi = subRun('MultiEdit', {+ edits: [+ { file_path: '/src/plain.js', old_string: 'a', new_string: 'b' },+ { file_path: '/src/payments/charge.js', old_string: 'a', new_string: 'b' }+ ]+ }, subAgent);+ assert.strictEqual(roDecision(multi), 'deny');+ assert.ok(roReason(multi).includes('charge.js'));+ assert.strictEqual(roDecision(subEdit('/src/ordinary.js', subAgent)), undefined);+ assert.strictEqual(roDecision(subRun('Write', { file_path: '/src/new-file.js', content: 'x' }, subAgent)), undefined);+ });++ c3Case('subagent sensitive denials ignore prior-search credit and the denial cap', () => {+ const transcript = c3WriteTranscript([c3Human('fix it'), ...c3Search('toolu_sub1', 'Grep', { pattern: 'login', path: '/src' })]);+ const result = subRun('Edit', { file_path: '/src/auth/login.js', old_string: 'a', new_string: 'b' }, { ...subAgent, transcript_path: transcript });+ assert.strictEqual(roDecision(result), 'deny');+ clearState();+ const capped = runHook(+ { tool_name: 'Edit', tool_input: { file_path: '/src/.env.local', old_string: 'a', new_string: 'b' }, session_id: 'subagent-sensitive-session', ...subAgent },+ { CLAUDE_SESSION_ID: '', ECC_SESSION_ID: '', GATEGUARD_FACT_FORCE_MAX_DENIALS: '0' }+ );+ assert.strictEqual(roDecision(capped), 'deny');+ });+fs.rmSync(f3Base, { recursive: true, force: true });fs.rmSync(f2Root, { recursive: true, force: true });