The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
feat(gateguard): ask code questions that fit the change
Jeffrey Montoya10f67715b177
diff --git a/docs/gateguard/design-notes.md b/docs/gateguard/design-notes.mdindex 7805b2909..58c2108bb 100644--- a/docs/gateguard/design-notes.md+++ b/docs/gateguard/design-notes.md@@ -81,8 +81,10 @@ their absolute path. A Windows-style path has no real location on a POSIX hostThe first matching class wins: instruction, test, prose, config, code (thefallback). Cursor `.mdc` rule files are instructions wherever they live. Abasename starting with `.env` is config unless it has a code extension-(`.env.example.ts` is source). Code targets keep the original four questions;-other classes get class-specific questions and a class-specific condensed hint.+(`.env.example.ts` is source). Code targets ask the original four questions,+narrowed by the change profile (see+[Questions from the change profile](#questions-from-the-change-profile)); other+classes get class-specific questions and a class-specific condensed hint.## Worktree prefix@@ -344,3 +346,32 @@ line inside a multi-line string that opens and closes outside the snippetreads as a comment; the trivial pass never marks the target checked and neverapplies to sensitive, instruction or config targets, so the next non-trivialchange still meets the full gate.++## Questions from the change profile++Every question has a stable id, and `questionIdsFor(class, isWrite, profile)`+returns the ids in the order asked, so later measurement can record which+questions were asked without storing text.++| Target | Profile | Question ids |+|---|---|---|+| code Edit/MultiEdit | unknown | `importers`, `public-api`, `data-schema`, `quote-instruction` |+| code Edit/MultiEdit | public surface | `importers`, `public-api`, [`data-schema`], `quote-instruction` |+| code Edit/MultiEdit | no public surface | `local-callers`, [`data-schema`], `quote-instruction` |+| code Write | unknown | `callers`, `no-duplicate`, `data-schema`, `quote-instruction` |+| code Write | known | `callers`, `no-duplicate`, [`data-schema`], `quote-instruction` |+| instruction | any | `loader`, `behaviour-change`, `no-duplicate-instruction`, `quote-instruction` |+| test | any | `under-test`, `existing-tests`, `quote-instruction` |+| prose Write | any | `supersedes`, `linked-from`, `why-new-file`, `quote-instruction` |+| prose Edit | any | `references`, `corrects-or-adds`, `quote-instruction` |+| config | any | `config-reader`, `config-effect`, `no-plaintext-secrets`, `quote-instruction` |++`[data-schema]` is asked only when `touchesData`. With an unknown profile the+code text is byte-identical to the fixed four questions. Sensitive targets are+never profiled, so they always get the full code questions. Instruction and+config questions carry no change-dependent item, and the test and prose items+do not depend on what the change touches, so the profile leaves those classes+alone. For a MultiEdit, the denied file's profile covers every entry for that+file (same canonical key); entries for other files do not count. The condensed+denial uses the local-callers hint when `local-callers` is asked, else the+original code hint.diff --git a/docs/ja-JP/skills/gateguard/SKILL.md b/docs/ja-JP/skills/gateguard/SKILL.mdindex fc336e8a2..996079758 100644--- a/docs/ja-JP/skills/gateguard/SKILL.md+++ b/docs/ja-JP/skills/gateguard/SKILL.md@@ -95,6 +95,8 @@ Before creating {file_path}, present these facts:| prose (Edit) | List other docs or code that reference the section being changed *(search)* · State what the change corrects or adds || config | Name which process/tool reads this file and when · Describe the effect of the change · Confirm no secrets or credentials are being written in plain text |+code クラスでは変更内容も読み、公開宣言に触れない Edit には importer/公開 API の代わりに「このファイルまたはモジュール内で変更された振る舞いに依存する呼び出し箇所」を尋ね、データを扱わない変更ではデータ形式の質問を省きます(未対応の拡張子、64 KiB 超などの判定不能な変更と機密対象では従来の 4 問のままです)。+メッセージの文面以外でクラスが影響するのは兄弟ファイル集約だけです(集約できるクラスと、同じクラス同士でのみ集約されること)。### Destructive Bash Gate (every destructive command)diff --git a/docs/zh-CN/skills/gateguard/SKILL.md b/docs/zh-CN/skills/gateguard/SKILL.mdindex 4d4badc0b..009b901af 100644--- a/docs/zh-CN/skills/gateguard/SKILL.md+++ b/docs/zh-CN/skills/gateguard/SKILL.md@@ -91,6 +91,7 @@ LLM 的自我评估不起作用。问"你是否违反了任何策略?"答案以上编辑/写入门控的问题适用于 **code** 类目标。完整规则见英文版 `skills/gateguard/SKILL.md`,要点如下:* **目标类别:** 首次编辑/写入按项目相对路径(去掉开头的 `.claude/worktrees/<name>/`)依次判定为 instruction(`CLAUDE.md`、`AGENTS.md`、`SKILL.md`、`.mdc`、`.cursorrules`、`.github/copilot-instructions.md` 等)、test、prose(`.md` 等)、config(`.json`、`.yaml`、`.env` / `.env.*` 等,`.env.example.ts` 仍属 code)或 code,并提出相应的问题。+* **按变更内容提问:** 对 code 类目标还会读取变更内容:未触及公开声明的编辑改问"本文件或其模块中依赖所改行为的调用点",不涉及数据的变更省略数据格式问题;无法可靠判断(不支持的扩展名、超过 64 KiB 等)以及敏感目标时仍问原来的四个问题。* **事先搜索抵免:** 若当前人类回合内已有成功完成(非错误结果)的 `Glob`、`Grep`、`LS` 或 `rg`/`grep`/`find` 等搜索命中该文件,则以附注代替拒绝。`Read` 从不计入;与被门控调用同批次的搜索、重复的 tool_use id、压缩(compaction)之前的搜索均不计入。文件名词干须按单词边界匹配,且目标须位于所搜索目录之内(shell 片段按其路径参数或 `cwd` 判定范围;参数前的输入重定向 `<` 视为读取 stdin)。仅"创建尚不存在的文件"的写入可按目录匹配,且 shell 参数须是真实存在的目录;回合内出现 `cd` 等切换目录命令时不再按 shell 目录匹配。相对路径按工具的 `cwd` 解析。排除规则从不计入:`Grep` 的 `glob` 中以 `!` 开头的项,以及 shell 中 `rg -g '!x'`、`grep --exclude`/`--exclude-dir`、`fd -E`、`ls -I`、`tree -I`、`git ls-files -x`、git `:!x` 路径规格、带 `-not`/`!` 或后接 `-prune` 的 `find -name`/`-path`、PowerShell `-Exclude` 都不作为词干来源;若排除项覆盖目标(文件名、路径上的目录或词干),该搜索完全不能为其抵免(`rg -g '!widget.py' TODO .` 不抵免 `widget.py`,`rg -g '!*.md' widget .` 仍抵免)。含 `--exclude-from`/`--ignore-file` 的片段不抵免;用 `*.py`、`--include`、`find -name` 等文件名 glob 限定的搜索,只有在其匹配目标文件名时词干才计入。* **同回合同级文件合并:** 同一目录、同一类别(仅 code、test、prose)的新文件在同一回合内(完全没有 transcript 路径时为 120 秒内)只拒绝第一个,其余以附注放行。config、instruction,以及任何以 `.` 开头的路径段(点文件和所有点目录)或 8.3 短文件名下的文件从不合并;目录按解析符号链接后的真实位置判定和记录;有 transcript 路径但文件缺失、无法读取或得不到回合 ID 时不合并;编辑从不合并。* **拒绝上限(可选):** 设置 `GATEGUARD_FACT_FORCE_MAX_DENIALS` 后,会话内首次触碰的拒绝次数达到该值后,新路径直接放行(计入 `cap_allows`)。`GATEGUARD_FACT_FORCE_FULL_DENIALS` 只决定消息详略(消息预算),而此变量决定是否拦截(拒绝预算)。事先搜索抵免和同级合并先于上限判定,不消耗上限;格式错误的值视为无上限,并在 stderr 警告一次。diff --git a/manifests/context-packs/[email protected] b/manifests/context-packs/[email protected]index f94cb5970..8f9f4e0e5 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":"836d4a2d0ab394c394599eee4387ffbc287f0d2d84e2158a5cc23b93750be60c","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":"ba200e80f4b96c71c8dd46029e2565769248955da20ccf849479f2e6613a4f92","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 1608ccfff..741cf144d 100644--- a/scripts/hooks/gateguard-fact-force.js+++ b/scripts/hooks/gateguard-fact-force.js@@ -30,9 +30,9 @@ const { classifyPowerShellDestructiveCommand } = require('../lib/powershell-destconst { stripHeredocBodies } = require('./gateguard-heredoc');const {WINDOWS_PATH_PATTERN,- CLASS_QUESTIONS,- CLASS_CONDENSED_HINTS,- QUOTE_INSTRUCTION,+ questionIdsFor,+ questionText,+ condensedHintFor,resolveTargetPath,canonicalPathKey,classifyTarget,@@ -42,6 +42,7 @@ const {} = require('../lib/gateguard-target-class');const { scanCurrentTurn, createTurnScanner, currentTurnId, transcriptPathFor } = require('../lib/gateguard-turn-scan');const { createSearchEvidence } = require('../lib/gateguard-search-evidence');+const { profileChange } = require('../lib/gateguard-change-profile');const {getDenialCount,getCreditedCount,@@ -1829,45 +1830,9 @@ function batchSiblingWarning(safePath) {);}-function editGateMsg(filePath) {+function firstTouchGateMsg(filePath, isWrite, cls, profile) {const safe = sanitizePath(filePath);- return [- '[Fact-Forcing Gate]',- '',- `Before editing ${safe}, present these facts:`,- '',- '1. List ALL files that import/require this file (search the tree — Glob/Grep, or find/grep via Bash)',- '2. List the public functions/classes affected by this change',- '3. If this file reads/writes data files, show field names, structure, and date format (use redacted or synthetic values, not raw production data)',- "4. Quote the user's current instruction verbatim",- '',- batchSiblingWarning(safe),- '',- 'Present the facts, then retry the same operation.'- ].join('\n');-}--function writeGateMsg(filePath) {- const safe = sanitizePath(filePath);- return [- '[Fact-Forcing Gate]',- '',- `Before creating ${safe}, present these facts:`,- '',- '1. Name the file(s) and line(s) that will call this new file',- '2. Confirm no existing file serves the same purpose (search the tree — Glob/Grep, or find/grep via Bash)',- '3. If this file reads/writes data files, show field names, structure, and date format (use redacted or synthetic values, not raw production data)',- "4. Quote the user's current instruction verbatim",- '',- batchSiblingWarning(safe),- '',- 'Present the facts, then retry the same operation.'- ].join('\n');-}--function classGateMsg(filePath, cls, isWrite) {- const safe = sanitizePath(filePath);- const questions = [...CLASS_QUESTIONS[cls](isWrite), QUOTE_INSTRUCTION];+ const questions = questionIdsFor(cls, isWrite, profile).map(questionText);return ['[Fact-Forcing Gate]','',@@ -1881,23 +1846,14 @@ function classGateMsg(filePath, cls, isWrite) {].join('\n');}-function firstTouchGateMsg(filePath, isWrite, cls) {- if (!CLASS_QUESTIONS[cls]) {- return isWrite ? writeGateMsg(filePath) : editGateMsg(filePath);- }- return classGateMsg(filePath, cls, isWrite);-}-/*** Condensed single-line denial used after the full-block budget is spent* (#2142). Carries the denial ordinal so consecutive denials differ* textually, and a one-line recovery hint instead of the multi-line block.*/-function condensedGateMsg(action, filePath, ordinal, cls = 'code', sensitive = false) {+function condensedGateMsg(action, filePath, ordinal, cls = 'code', sensitive = false, profile = null) {const safe = sanitizePath(filePath);- const hint = CLASS_CONDENSED_HINTS[cls]- ? CLASS_CONDENSED_HINTS[cls](action === 'creation')- : "briefly state importers/callers, affected API, data schemas if any, and the user's verbatim instruction, then retry.";+ const hint = condensedHintFor(cls, action === 'creation', profile);return (`[Fact-Forcing Gate] (denial #${ordinal} this session) First ${action} of ${safe}: ` +`${hint} ` +@@ -1916,12 +1872,12 @@ function withSensitiveNote(message) {return `${message.slice(0, at)}${SENSITIVE_TARGET_NOTE}\n\n${message.slice(at)}`;}-function firstTouchDenial(filePath, { isWrite, denials, cls, sensitive }) {+function firstTouchDenial(filePath, { isWrite, denials, cls, sensitive, profile }) {if (denials > getFullDenialBudget()) {const action = isWrite ? 'creation' : 'edit';- return denyResult(condensedGateMsg(action, filePath, denials, cls, sensitive), { includeRecoveryHint: false });+ return denyResult(condensedGateMsg(action, filePath, denials, cls, sensitive, profile), { includeRecoveryHint: false });}- const message = firstTouchGateMsg(filePath, isWrite, cls);+ const message = firstTouchGateMsg(filePath, isWrite, cls, profile);return denyResult(sensitive ? withSensitiveNote(message) : message, {narrowRecoveryHint: EDIT_WRITE_NARROW_RECOVERY_HINT});@@ -2052,6 +2008,16 @@ function siblingNote(gate) {);}+// --- Change profile ---++function changeProfileFor(toolName, filePath, edits, content) {+ return profileChange({ filePath, tool: toolName === 'Write' ? 'Write' : 'Edit', edits, content });+}++function entriesFor(edits, fileKey, data) {+ return edits.filter(edit => edit && typeof edit.file_path === 'string' && canonicalPathKey(edit.file_path, data) === fileKey);+}+// --- Core logic (exported for run-with-flags.js) ---function run(rawInput) {@@ -2120,7 +2086,8 @@ function run(rawInput) {// see docs/gateguard/design-notes.md#denial-capreturn rawInput;}- return firstTouchDenial(filePath, { isWrite: toolName === 'Write', denials, cls, sensitive });+ const profile = sensitive ? null : changeProfileFor(toolName, filePath, [toolInput], toolInput.content);+ return firstTouchDenial(filePath, { isWrite: toolName === 'Write', denials, cls, sensitive, profile });}return rawInput; // allow@@ -2157,7 +2124,8 @@ function run(rawInput) {// see docs/gateguard/design-notes.md#denial-capcontinue;}- return firstTouchDenial(filePath, { isWrite: false, denials, cls, sensitive });+ const profile = sensitive ? null : changeProfileFor('Edit', filePath, entriesFor(edits, fileKey, data));+ return firstTouchDenial(filePath, { isWrite: false, denials, cls, sensitive, profile });}}if (creditNotes.length > 0) {diff --git a/scripts/lib/gateguard-target-class.js b/scripts/lib/gateguard-target-class.jsindex f0d1df8f3..4940f9bfa 100644--- a/scripts/lib/gateguard-target-class.js+++ b/scripts/lib/gateguard-target-class.js@@ -148,34 +148,66 @@ function classifyTargetFor(filePath, data) {const SEARCH_THE_TREE = '(search the tree — Glob/Grep, or find/grep via Bash)';const QUOTE_INSTRUCTION = "Quote the user's current instruction verbatim";-const CLASS_QUESTIONS = {- instruction: () => [- 'Name the harness/loader that reads this file (Claude Code, Codex, Cursor, OpenCode, …) and when it loads it',- 'Describe what agent behaviour changes as a result',- `Confirm no existing instruction, skill, or agent file already covers this ${SEARCH_THE_TREE}`- ],- test: () => [- 'Name what behaviour is under test and which module/function it exercises',- `Name the existing test file(s) covering this module, or confirm none exist ${SEARCH_THE_TREE}`- ],- prose: isWrite =>- isWrite- ? [- `Name any existing doc this supersedes or duplicates ${SEARCH_THE_TREE}`,- 'State where it will be linked or referenced from',- 'Explain why a new file rather than editing an existing one'- ]- : [- `List other docs or code that reference the section being changed ${SEARCH_THE_TREE}`,- 'State what the change corrects or adds'- ],- config: () => [- 'Name which process/tool reads this file and when',- 'Describe the effect of the change',- 'Confirm no secrets or credentials are being written in plain text'- ]+const QUESTION_TEXT = Object.freeze({+ importers: `List ALL files that import/require this file ${SEARCH_THE_TREE}`,+ 'public-api': 'List the public functions/classes affected by this change',+ 'local-callers': `List the call sites in this file or its module that rely on the changed behaviour ${SEARCH_THE_TREE}`,+ callers: 'Name the file(s) and line(s) that will call this new file',+ 'no-duplicate': `Confirm no existing file serves the same purpose ${SEARCH_THE_TREE}`,+ 'data-schema':+ 'If this file reads/writes data files, show field names, structure, and date format (use redacted or synthetic values, not raw production data)',+ loader: 'Name the harness/loader that reads this file (Claude Code, Codex, Cursor, OpenCode, …) and when it loads it',+ 'behaviour-change': 'Describe what agent behaviour changes as a result',+ 'no-duplicate-instruction': `Confirm no existing instruction, skill, or agent file already covers this ${SEARCH_THE_TREE}`,+ 'under-test': 'Name what behaviour is under test and which module/function it exercises',+ 'existing-tests': `Name the existing test file(s) covering this module, or confirm none exist ${SEARCH_THE_TREE}`,+ supersedes: `Name any existing doc this supersedes or duplicates ${SEARCH_THE_TREE}`,+ 'linked-from': 'State where it will be linked or referenced from',+ 'why-new-file': 'Explain why a new file rather than editing an existing one',+ references: `List other docs or code that reference the section being changed ${SEARCH_THE_TREE}`,+ 'corrects-or-adds': 'State what the change corrects or adds',+ 'config-reader': 'Name which process/tool reads this file and when',+ 'config-effect': 'Describe the effect of the change',+ 'no-plaintext-secrets': 'Confirm no secrets or credentials are being written in plain text',+ 'quote-instruction': QUOTE_INSTRUCTION+});++const CLASS_QUESTION_IDS = {+ instruction: () => ['loader', 'behaviour-change', 'no-duplicate-instruction'],+ test: () => ['under-test', 'existing-tests'],+ prose: isWrite => (isWrite ? ['supersedes', 'linked-from', 'why-new-file'] : ['references', 'corrects-or-adds']),+ config: () => ['config-reader', 'config-effect', 'no-plaintext-secrets']};+const CLASS_QUESTIONS = Object.fromEntries(+ Object.entries(CLASS_QUESTION_IDS).map(([cls, ids]) => [cls, isWrite => ids(isWrite).map(id => QUESTION_TEXT[id])])+);++// see docs/gateguard/design-notes.md#questions-from-the-change-profile+function codeQuestionIds(isWrite, profile) {+ const known = Boolean(profile) && profile.known === true;+ const surface = !known || profile.touchesPublicSurface !== false;+ const data = !known || profile.touchesData !== false;+ const opening = isWrite ? ['callers', 'no-duplicate'] : surface ? ['importers', 'public-api'] : ['local-callers'];+ return data ? [...opening, 'data-schema'] : opening;+}++/** Stable ids of the first-touch questions for a class, action and change profile. */+function questionIdsFor(cls, isWrite, profile) {+ const ids = Object.hasOwn(CLASS_QUESTION_IDS, cls) ? CLASS_QUESTION_IDS[cls](Boolean(isWrite)) : codeQuestionIds(Boolean(isWrite), profile);+ return [...ids, 'quote-instruction'];+}++/** Question text for an id from `questionIdsFor`. */+function questionText(id) {+ return Object.hasOwn(QUESTION_TEXT, id) ? QUESTION_TEXT[id] : '';+}++const CODE_CONDENSED_HINT =+ "briefly state importers/callers, affected API, data schemas if any, and the user's verbatim instruction, then retry.";+const LOCAL_CODE_CONDENSED_HINT =+ "briefly state the call sites in this file or its module that rely on the change, data schemas if any, and the user's verbatim instruction, then retry.";+const CLASS_CONDENSED_HINTS = {instruction: () =>"briefly state which harness loads this file, the agent behaviour it changes, that no existing instruction file covers it, and the user's verbatim instruction, then retry.",@@ -189,6 +221,12 @@ const CLASS_CONDENSED_HINTS = {"briefly state which process reads this file, the effect of the change, that no secrets are written in plain text, and the user's verbatim instruction, then retry."};+/** One-line condensed hint matching `questionIdsFor`. */+function condensedHintFor(cls, isWrite, profile) {+ if (Object.hasOwn(CLASS_CONDENSED_HINTS, cls)) return CLASS_CONDENSED_HINTS[cls](Boolean(isWrite));+ return questionIdsFor(cls, isWrite, profile).includes('local-callers') ? LOCAL_CODE_CONDENSED_HINT : CODE_CONDENSED_HINT;+}+// --- Sensitive targets ---// see docs/gateguard/design-notes.md#sensitive-targets@@ -331,6 +369,9 @@ module.exports = {CLASS_QUESTIONS,CLASS_CONDENSED_HINTS,QUOTE_INSTRUCTION,+ questionIdsFor,+ questionText,+ condensedHintFor,resolveTargetPath,canonicalPathKey,classifyTarget,diff --git a/skills/gateguard/SKILL.md b/skills/gateguard/SKILL.mdindex ea305c013..7900f07b0 100644--- a/skills/gateguard/SKILL.md+++ b/skills/gateguard/SKILL.md@@ -64,6 +64,12 @@ Before editing {file_path}, present these facts:4. Quote the user's current instruction verbatim```+These four are the full set, asked whenever the change cannot be read with+confidence. When it can (see [Questions fit the change](#questions-fit-the-change)),+an edit that touches no public declaration asks instead for the call sites in+the file or its module that rely on the changed behaviour, and item 3 is+dropped when the change handles no data.+### Write Gate (first new file creation)For **code** targets the Write gate asks:@@ -78,6 +84,37 @@ Before creating {file_path}, present these facts:4. Quote the user's current instruction verbatim```+Item 3 is dropped when the new content handles no data.++### Questions fit the change++For **code** targets the gate reads the change it is about to allow (Edit+`old_string`/`new_string`, every MultiEdit entry for the file, Write+`content`) and decides two things:++- **Public surface:** a line on either side declares or exposes a public name.+ JS/TS: `export`, `exports`, `public`, `declare` (`.d.ts` files always); Python:+ `def`/`class` not starting with `_`, dunders, `__all__`, a module-level public+ assignment (`__init__.py` always); Go: capitalised `func`/`type`/`var`/`const`+ names, `package`, lines starting with a capital; Rust: `pub`, `impl`, `trait`,+ `#[macro_export]`. Java, Kotlin, C#, C and C++, and every Write, always count+ as touching it. Touching it keeps questions 1 and 2; otherwise both are+ replaced by "List the call sites in this file or its module that rely on the+ changed behaviour".+- **Data:** words for file I/O, formats (`json`, `csv`, `yaml`, …),+ serialisation, schemas, SQL and dates on either side. Without them the data+ question is dropped.++Supported extensions: `.js .mjs .cjs .jsx .ts .tsx .mts .cts .py .pyi .go .rs+.java .kt .kts .cs .c .h .cc .cpp .cxx .hpp .hh .hxx`. Any other extension, a+missing or non-string field, more than 64 MultiEdit entries, a side over+64 KiB, or 256 KiB in total means the full questions, word for word. Sensitive+targets always get the full questions. Other classes keep their class+questions. Each question has a stable id (`importers`, `public-api`,+`local-callers`, `callers`, `no-duplicate`, `data-schema`,+`quote-instruction`, and one per class question), listed in+`docs/gateguard/design-notes.md`.+### Questions by target classThe code questions carry no signal for a `SKILL.md`, a README, a test, or adiff --git a/tests/hooks/gateguard-fact-force.test.js b/tests/hooks/gateguard-fact-force.test.jsindex 9cd2945e5..f940f3aae 100644--- a/tests/hooks/gateguard-fact-force.test.js+++ b/tests/hooks/gateguard-fact-force.test.js@@ -744,7 +744,7 @@ function runTests() {test('denies first Edit per file with fact-forcing message', () => {const input = {tool_name: 'Edit',- tool_input: { file_path: '/src/app.js', old_string: 'foo', new_string: 'bar' }+ tool_input: { file_path: '/src/app.js', old_string: 'export function foo() {', new_string: 'export function bar() {' }};const result = runHook(input);assert.strictEqual(result.code, 0, 'exit code should be 0');@@ -4328,7 +4328,12 @@ function runTests() {clearState();if (test('src/a.py Write and Edit keep the code text byte-identical', () => {- const writeReason = c2Reason('Write', 'src/a.py');+ const fullReason = tool_input => {+ const output = parseOutput(runHook({ tool_name: tool_input.content === undefined ? 'Edit' : 'Write', tool_input }, C2_ENV).stdout);+ assert.ok(output && output.hookSpecificOutput, `${tool_input.file_path} should be denied`);+ return output.hookSpecificOutput.permissionDecisionReason;+ };+ const writeReason = fullReason({ file_path: 'src/a.py', content: 'import json\n' });const expectedWrite = ['[Fact-Forcing Gate]','',@@ -4345,7 +4350,7 @@ function runTests() {''].join('\n');assert.ok(writeReason.startsWith(expectedWrite), 'code Write block unchanged');- const editReason = c2Reason('Edit', 'src/b.py');+ const editReason = fullReason({ file_path: 'src/b.py', old_string: 'def load(path):', new_string: 'def load_json(path):' });const expectedEdit = ['[Fact-Forcing Gate]','',@@ -4400,6 +4405,161 @@ function runTests() {passed++;else failed++;+ // --- Questions from the change profile ---+ const B2_ENV = { CLAUDE_PROJECT_DIR: '/proj-b2' };+ const b2Reason = (toolName, tool_input, env = {}) => {+ const output = parseOutput(runHook({ tool_name: toolName, tool_input }, { ...B2_ENV, ...env }).stdout);+ assert.ok(output && output.hookSpecificOutput, `${toolName} ${JSON.stringify(tool_input).slice(0, 80)} should be denied`);+ assert.strictEqual(output.hookSpecificOutput.permissionDecision, 'deny');+ return output.hookSpecificOutput.permissionDecisionReason;+ };+ const b2Questions = reason => reason.split('\n').filter(line => /^\d+\. /.test(line)).map(line => line.replace(/^\d+\. /, ''));+ const B2_TEXT = {+ importers: 'List ALL files that import/require this file (search the tree — Glob/Grep, or find/grep via Bash)',+ publicApi: 'List the public functions/classes affected by this change',+ localCallers: 'List the call sites in this file or its module that rely on the changed behaviour (search the tree — Glob/Grep, or find/grep via Bash)',+ callers: 'Name the file(s) and line(s) that will call this new file',+ noDuplicate: 'Confirm no existing file serves the same purpose (search the tree — Glob/Grep, or find/grep via Bash)',+ dataSchema: 'If this file reads/writes data files, show field names, structure, and date format (use redacted or synthetic values, not raw production data)',+ quote: QUOTE_LINE+ };+ const B2_FULL_EDIT = [B2_TEXT.importers, B2_TEXT.publicApi, B2_TEXT.dataSchema, B2_TEXT.quote];+ const B2_FULL_WRITE = [B2_TEXT.callers, B2_TEXT.noDuplicate, B2_TEXT.dataSchema, B2_TEXT.quote];++ clearState();+ if (+ test('an Edit that changes an exported signature asks for importers and the affected public API', () => {+ const reason = b2Reason('Edit', { file_path: 'src/api.js', old_string: 'export function load(a) {', new_string: 'export function load(a, b) {' });+ assert.deepStrictEqual(b2Questions(reason), [B2_TEXT.importers, B2_TEXT.publicApi, B2_TEXT.quote]);+ assertFrame(reason, 'editing', 'src/api.js');+ })+ )+ passed++;+ else failed++;++ clearState();+ if (+ test('an Edit of a function body asks for call sites in the file or module instead of importers', () => {+ const reason = b2Reason('Edit', { file_path: 'src/calc.js', old_string: ' return a + 1;', new_string: ' return a * 2;' });+ assert.deepStrictEqual(b2Questions(reason), [B2_TEXT.localCallers, B2_TEXT.quote]);+ assertFrame(reason, 'editing', 'src/calc.js');+ })+ )+ passed++;+ else failed++;++ clearState();+ if (+ test('an Edit that handles data keeps the data-schema question', () => {+ const reason = b2Reason('Edit', { file_path: 'src/calc.py', old_string: ' x = 1', new_string: ' rows = json.load(fh)' });+ assert.deepStrictEqual(b2Questions(reason), [B2_TEXT.localCallers, B2_TEXT.dataSchema, B2_TEXT.quote]);+ })+ )+ passed++;+ else failed++;++ clearState();+ if (+ test('a Write of a new code file without data handling drops the data-schema question', () => {+ const reason = b2Reason('Write', { file_path: 'src/new_mod.js', content: 'export const x = 1;\n' });+ assert.deepStrictEqual(b2Questions(reason), [B2_TEXT.callers, B2_TEXT.noDuplicate, B2_TEXT.quote]);+ const withData = b2Reason('Write', { file_path: 'lib/new_io.js', content: "const fs = require('fs');\n" });+ assert.deepStrictEqual(b2Questions(withData), B2_FULL_WRITE);+ })+ )+ passed++;+ else failed++;++ clearState();+ if (+ test('an unknown or over-bound change keeps the full code questions byte-identical', () => {+ const cases = [+ ['Edit', { file_path: 'src/a.rb', old_string: 'a', new_string: 'b' }, B2_FULL_EDIT],+ ['Edit', { file_path: 'src/big.js', old_string: 'x'.repeat(70 * 1024), new_string: 'y' }, B2_FULL_EDIT],+ ['Edit', { file_path: 'src/shape.js' }, B2_FULL_EDIT],+ ['Edit', { file_path: 'src/shape2.js', old_string: 5, new_string: 'b' }, B2_FULL_EDIT],+ ['Write', { file_path: 'src/d.rb', content: 'x' }, B2_FULL_WRITE],+ ['Write', { file_path: 'src/e.js' }, B2_FULL_WRITE]+ ];+ for (const [tool, input, expected] of cases) {+ clearState();+ const reason = b2Reason(tool, input);+ assert.deepStrictEqual(b2Questions(reason), expected, `${input.file_path}`);+ const header = `Before ${tool === 'Write' ? 'creating' : 'editing'} ${input.file_path}, present these facts:`;+ const block = ['[Fact-Forcing Gate]', '', header, '', ...expected.map((q, i) => `${i + 1}. ${q}`), ''].join('\n');+ assert.ok(reason.startsWith(block), `${input.file_path}: block unchanged`);+ }+ })+ )+ passed++;+ else failed++;++ clearState();+ if (+ test('sensitive code targets always get the full code questions', () => {+ const reason = b2Reason('Edit', { file_path: 'src/auth/login.js', old_string: ' return a + 1;', new_string: ' return a * 2;' });+ assert.deepStrictEqual(b2Questions(reason), B2_FULL_EDIT);+ assert.ok(reason.includes('Sensitive target'), 'sensitive note');+ const write = b2Reason('Write', { file_path: 'src/billing/new.js', content: 'export const x = 1;\n' });+ assert.deepStrictEqual(b2Questions(write), B2_FULL_WRITE);+ })+ )+ passed++;+ else failed++;++ clearState();+ if (+ test('config, instruction and test targets keep their class questions whatever the change', () => {+ const config = b2Questions(b2Reason('Write', { file_path: 'config/app.yaml', content: 'a: 1\n' }));+ assert.strictEqual(config.length, 4, 'config keeps three questions and the quote');+ assert.ok(config[2].includes('no secrets or credentials'));+ const instruction = b2Questions(b2Reason('Edit', { file_path: 'CLAUDE.md', old_string: 'a', new_string: 'b' }));+ assert.strictEqual(instruction.length, 4, 'instruction keeps three questions and the quote');+ const testFile = b2Questions(b2Reason('Edit', { file_path: 'src/a.test.js', old_string: ' return 1;', new_string: ' return 2;' }));+ assert.ok(testFile[0].includes('behaviour is under test'), 'test questions');+ assert.strictEqual(testFile.length, 3);+ })+ )+ passed++;+ else failed++;++ clearState();+ if (+ test('MultiEdit questions follow every entry for the denied file', () => {+ const surface = b2Reason('MultiEdit', {+ edits: [+ { file_path: 'src/m.js', old_string: ' return 1;', new_string: ' return 2;' },+ { file_path: 'src/m.js', old_string: 'function f() {', new_string: 'export function f() {' }+ ]+ });+ assert.deepStrictEqual(b2Questions(surface), [B2_TEXT.importers, B2_TEXT.publicApi, B2_TEXT.quote]);+ clearState();+ const local = b2Reason('MultiEdit', {+ edits: [+ { file_path: 'src/n.js', old_string: ' return 1;', new_string: ' return 2;' },+ { file_path: 'src/other.js', old_string: 'export const y = 1;', new_string: 'export const y = 2;' }+ ]+ });+ assert.deepStrictEqual(b2Questions(local), [B2_TEXT.localCallers, B2_TEXT.quote], 'entries for other files do not count');+ })+ )+ passed++;+ else failed++;++ clearState();+ if (+ test('condensed denials follow the change profile', () => {+ const env = { GATEGUARD_FACT_FORCE_FULL_DENIALS: '0' };+ const local = b2Reason('Edit', { file_path: 'src/c1.js', old_string: ' return 1;', new_string: ' return 2;' }, env);+ assert.ok(local.includes('the call sites in this file or its module that rely on the change'), local);+ assert.ok(!local.includes('importers/callers'), 'no importer hint for a local change');+ const full = b2Reason('Edit', { file_path: 'src/c2.rb', old_string: 'a', new_string: 'b' }, env);+ assert.ok(full.includes('briefly state importers/callers, affected API, data schemas if any'), 'unknown profile keeps the hint');+ })+ )+ passed++;+ else failed++;+clearState();if (test('scripts/hooks/x.js is code, not instruction', () => {@@ -4437,7 +4597,7 @@ function runTests() {const editReason = c2Reason('Edit', 'docs/late-edit.md', env);assert.ok(editReason.includes('(denial #2 this session) First edit of docs/late-edit.md: '), 'ordinal advances');assert.ok(editReason.includes('what references the changed section'), 'prose Edit hint');- const codeReason = c2Reason('Edit', 'src/late.js', env);+ const codeReason = c2Reason('Edit', 'src/late.rb', env);assert.ok(codeReason.includes('briefly state importers/callers, affected API, data schemas if any'), 'code hint unchanged');}))@@ -5776,7 +5936,7 @@ function runTests() {const state = c3State();assert.deepStrictEqual(state.denials_by_class, { code: 1 }, 'counter uses the same class as the questions');assert.ok(state.dir_gates[f3GateKey('code', 'src')], `gate key uses the same class: ${JSON.stringify(Object.keys(state.dir_gates))}`);- assert.ok(f3Edit('lib/b.py', t).reason.includes('List ALL files that import/require this file'), 'Edit code questions');+ assert.ok(f3Edit('lib/b.py', t).reason.includes('List the call sites in this file or its module'), 'Edit code questions');// The prefix is stripped only for a real worktree (its .git file or dir exists).fs.mkdirSync(f3('.claude/worktrees/feat-x'), { recursive: true });fs.writeFileSync(f3('.claude/worktrees/feat-x/.git'), 'gitdir: ../../../.git/worktrees/feat-x\n');diff --git a/tests/lib/gateguard-target-class.test.js b/tests/lib/gateguard-target-class.test.jsindex db10de5ac..4132a9c82 100644--- a/tests/lib/gateguard-target-class.test.js+++ b/tests/lib/gateguard-target-class.test.js@@ -16,6 +16,10 @@ const hookPath = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'gateguardconst {CLASS_QUESTIONS,CLASS_CONDENSED_HINTS,+ QUOTE_INSTRUCTION,+ questionIdsFor,+ questionText,+ condensedHintFor,COLLAPSIBLE_CLASSES,canonicalPathKey,classifyTarget,@@ -314,6 +318,48 @@ test('every non-code class has questions and a condensed hint; code has neither'assert.notDeepStrictEqual(CLASS_QUESTIONS.prose(true), CLASS_QUESTIONS.prose(false), 'prose Write and Edit differ');});+test('questionIdsFor gives stable ids per class, action and change profile', () => {+ const known = (touchesPublicSurface, touchesData) => ({ known: true, language: 'js', touchesPublicSurface, touchesData, trivial: false });+ const table = [+ ['code', false, null, ['importers', 'public-api', 'data-schema', 'quote-instruction']],+ ['code', true, null, ['callers', 'no-duplicate', 'data-schema', 'quote-instruction']],+ ['code', false, { known: false, touchesPublicSurface: false, touchesData: false }, ['importers', 'public-api', 'data-schema', 'quote-instruction']],+ ['code', false, known(true, true), ['importers', 'public-api', 'data-schema', 'quote-instruction']],+ ['code', false, known(true, false), ['importers', 'public-api', 'quote-instruction']],+ ['code', false, known(false, true), ['local-callers', 'data-schema', 'quote-instruction']],+ ['code', false, known(false, false), ['local-callers', 'quote-instruction']],+ ['code', true, known(false, false), ['callers', 'no-duplicate', 'quote-instruction']],+ ['code', true, known(true, true), ['callers', 'no-duplicate', 'data-schema', 'quote-instruction']],+ ['instruction', false, known(false, false), ['loader', 'behaviour-change', 'no-duplicate-instruction', 'quote-instruction']],+ ['test', true, known(false, false), ['under-test', 'existing-tests', 'quote-instruction']],+ ['prose', true, null, ['supersedes', 'linked-from', 'why-new-file', 'quote-instruction']],+ ['prose', false, null, ['references', 'corrects-or-adds', 'quote-instruction']],+ ['config', false, known(false, false), ['config-reader', 'config-effect', 'no-plaintext-secrets', 'quote-instruction']],+ ['__proto__', false, null, ['importers', 'public-api', 'data-schema', 'quote-instruction']]+ ];+ for (const [cls, isWrite, profile, expected] of table) {+ const ids = questionIdsFor(cls, isWrite, profile);+ assert.deepStrictEqual(ids, expected, `${cls} ${isWrite ? 'Write' : 'Edit'} ${JSON.stringify(profile)}`);+ for (const id of ids) assert.ok(questionText(id), `${id} has text`);+ }+ assert.strictEqual(questionText('constructor'), '');+ assert.strictEqual(questionText('missing'), '');+});++test('class question texts are unchanged by the ids', () => {+ assert.deepStrictEqual(questionIdsFor('prose', true).slice(0, -1).map(questionText), CLASS_QUESTIONS.prose(true));+ assert.deepStrictEqual(questionIdsFor('config', false).slice(0, -1).map(questionText), CLASS_QUESTIONS.config(false));+ assert.strictEqual(questionText('quote-instruction'), QUOTE_INSTRUCTION);+});++test('condensedHintFor matches the question set', () => {+ const local = { known: true, touchesPublicSurface: false, touchesData: false };+ assert.ok(condensedHintFor('code', false, local).includes('call sites in this file or its module'));+ assert.ok(condensedHintFor('code', false, null).startsWith('briefly state importers/callers'));+ assert.ok(condensedHintFor('code', true, local).startsWith('briefly state importers/callers'));+ assert.strictEqual(condensedHintFor('test', false, local), CLASS_CONDENSED_HINTS.test(false));+});+// ── isSensitiveTarget ──test('isSensitiveTarget matches every listed basename, segment and prefix rule', () => {