The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
fix(gateguard): judge comment-only edits against the file they change
Jeffrey Montoya6e677b008c80
diff --git a/docs/gateguard/design-notes.md b/docs/gateguard/design-notes.mdindex cfbb9812f..682d43a3b 100644--- a/docs/gateguard/design-notes.md+++ b/docs/gateguard/design-notes.md@@ -291,8 +291,10 @@ state write, so an event is never half-recorded.`scripts/lib/gateguard-change-profile.js` reads the change the hook alreadyreceives (Edit `old_string`/`new_string`, each MultiEdit entry for the target,Write `content`) and derives three booleans: `touchesPublicSurface`,-`touchesData` and `trivial`. It is pure string analysis: no file or transcript-reads, no `RegExp` built from input, and every loop is a single linear pass.+`touchesData` and `trivial`. It is string analysis of those texts and, for+`trivial`, of the current file text the hook passes in (see+[File context](#file-context)): no reads of its own, no `RegExp` built from+input, and every loop is a single linear pass.The profile only ever removes questions, so anything uncertain yields theunknown profile (every question asked, never trivial): an unsupported@@ -456,11 +458,56 @@ target passes with an `additionalContext` note after prior-search credit andbefore sibling collapse and the denial cap. It is not marked checked and doesnot touch the denial count or ordinal, so the next change that alters code isgated as a first touch; `trivial_allows` counts the passes (merged by maximum-like the other counters). The profile sees only the snippet, so a comment-looking-line inside a multi-line string that opens and closes outside the snippet-reads as a comment; the trivial pass never marks the target checked and never-applies to sensitive, instruction or config targets, so the next non-trivial-change still meets the full gate.+like the other counters). The trivial pass never marks the target checked and+never applies to sensitive, instruction or config targets, so the next+non-trivial change still meets the full gate.++## File context++A snippet alone cannot show whether a comment-looking line is a comment: it+may sit inside a template literal, a docstring, a raw string or a heredoc+that opens above it, follow a line that continues onto it, or lose its line+break so the next line joins it. So an Edit is trivial only when checked+against the file it applies to.++- The hook reads the current target (never a sensitive one) itself: the path+ is resolved like every other target, opened read-only and non-blocking,+ and used only if `fstat` says it is a regular file of at most 1 MiB; CRLF+ is folded to LF, as the Edit tool does. A missing, unreadable, larger or+ special file (directory, FIFO, device) gives no file text and the edit is+ not trivial. The text is never logged, stored or put in a message.+- Each entry is applied in order, as the tool applies it, to the evolving+ text. `old_string` must be non-empty and occur exactly once, or at least+ once with `replace_all`; otherwise the tool would fail and the entry is not+ trivial. Over 1 MiB of text after an edit, more than 8 MiB of scanning for+ one call, or an edit window over 128 KiB is not trivial. A `new_string`+ holding a `String.prototype.replace` pattern (`$$`, `$&`, `` $` ``, `$'`,+ `$<`, `$` and a digit) is not trivial, in case the tool expands it.+- The edit window runs from the start of the line before the first+ occurrence to the end of the line holding the last occurrence's end+ (through the next line when `old_string` ends in a line break), so a line+ that loses or gains a break is compared joined. The window before and+ after the replacement is compared with the lexer rules above.+- The text before the window must end in plain code: not inside a comment,+ string, template literal (including `${...}`), text block, raw string,+ heredoc or here-string, and not after a line continuation (`\` in C-family,+ Python and POSIX shells, a backtick in PowerShell, `^` in batch). A+ per-language scanner decides; anything it cannot follow makes the edit not+ trivial: a JS `/` after `}` with another `/` or quote later on the line+ (regex or division), JSX in `.js`/`.jsx`/`.tsx` (`.ts`, `.mts` and `.cts`+ allow `<` generics), `<!--` and `-->`, a Python f-string whose+ replacement field holds its own quote, a comment or a line break, C#+ raw strings and interpolation holes with quotes or braces, Kotlin `${`+ inside strings, shell command substitution holding `case`, a heredoc or+ a comment, a heredoc whose terminator never comes, and nesting deeper than+ eight levels.+- Go files that import `"C"` are never trivial: the comment before the import+ is C code.++The scanner was checked against real tokenizers over this repository: every+line start it calls plain code in 801 JS files (espree) and 146 Python files+(`tokenize`) is outside strings, templates, regex literals and comments and+not a backslash continuation.## Questions from the change profilediff --git a/manifests/context-packs/[email protected] b/manifests/context-packs/[email protected]index 56fb553b4..a7f77f398 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":"2c34de198272f96fd120fdb1131f87a63bd74c0a5c88275538a9404a0e534575","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":"c1f2f63cbefb96bbd3dafea59dc752c88c207d68ae86ade02dfd70510e826396","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 4e73a39b2..93c83dfda 100644--- a/scripts/hooks/gateguard-fact-force.js+++ b/scripts/hooks/gateguard-fact-force.js@@ -2112,9 +2112,43 @@ function subagentSensitiveDenial(filePath, data, isWrite) {}// --- Change profile ---+// see docs/gateguard/design-notes.md#file-context-function changeProfileFor(toolName, filePath, edits, content) {- return profileChange({ filePath, tool: toolName === 'Write' ? 'Write' : 'Edit', edits, content });+const MAX_CONTEXT_FILE_BYTES = 1024 * 1024;++function readTargetText(filePath, data) {+ let fd = null;+ try {+ const target = resolveTargetPath(filePath, data);+ if (!target) return null;+ fd = fs.openSync(target.resolved, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK || 0));+ const stat = fs.fstatSync(fd);+ if (!stat.isFile() || stat.size > MAX_CONTEXT_FILE_BYTES) return null;+ const buffer = Buffer.alloc(stat.size);+ let read = 0;+ while (read < buffer.length) {+ const n = fs.readSync(fd, buffer, read, buffer.length - read, read);+ if (n === 0) break;+ read += n;+ }+ return buffer.toString('utf8', 0, read).replace(/\r\n/g, '\n');+ } catch (_) {+ return null;+ } finally {+ if (fd !== null) {+ try {+ fs.closeSync(fd);+ } catch (_) {+ /* ignore */+ }+ }+ }+}++function changeProfileFor(toolName, filePath, edits, content, data) {+ const tool = toolName === 'Write' ? 'Write' : 'Edit';+ const fileText = tool === 'Edit' ? readTargetText(filePath, data) : null;+ return profileChange({ filePath, tool, edits, content, fileText });}function entriesFor(edits, fileKey, data) {@@ -2248,7 +2282,7 @@ function gate(rawInput) {recordDecision('credit', 'prior-search', { target: filePath, cls, sensitive });return { additionalContext: creditNote(credit, filePath), exitCode: 0 };}- const profile = sensitive ? null : changeProfileFor(toolName, filePath, [toolInput], toolInput.content);+ const profile = sensitive ? null : changeProfileFor(toolName, filePath, [toolInput], toolInput.content, data);if (toolName === 'Edit' && isTrivialChange(cls, sensitive, profile)) {if (!countTrivialAllow()) {return allowWithStateWarning();@@ -2322,7 +2356,7 @@ function gate(rawInput) {notes.push(creditNote(credit, filePath));continue;}- const profile = sensitive ? null : changeProfileFor('Edit', filePath, entriesFor(edits, fileKey, data));+ const profile = sensitive ? null : changeProfileFor('Edit', filePath, entriesFor(edits, fileKey, data), undefined, data);if (isTrivialChange(cls, sensitive, profile)) {if (!countTrivialAllow()) {return allowWithStateWarning();diff --git a/scripts/lib/gateguard-change-profile.js b/scripts/lib/gateguard-change-profile.jsindex ddc0b8337..711f0d5ee 100644--- a/scripts/lib/gateguard-change-profile.js+++ b/scripts/lib/gateguard-change-profile.js@@ -28,20 +28,30 @@ const LANGUAGE_BY_EXT = new Map([const C_FAMILY = { lineComment: '//', blockComment: true, quotes: '"\'', indentSensitive: false };+const C_CONTEXT = { ...C_FAMILY, startsFresh: cFamilyStartsFresh };+const LEX_SPECS = {- js: { ...C_FAMILY, forbiddenCode: '`/', jsx: true },- go: { ...C_FAMILY, forbiddenCode: '`' },- rust: { ...C_FAMILY, quotes: '"', rustChars: true, rawPrefixes: 'r#', rustDocs: true },- java: { ...C_FAMILY, tripleQuotes: true },- kotlin: { ...C_FAMILY, tripleQuotes: true, noDollarInStrings: true },- csharp: { ...C_FAMILY, tripleQuotes: true, rawPrefixes: '@$' },- c: { ...C_FAMILY, rawPrefixes: 'R' },- cpp: { ...C_FAMILY, rawPrefixes: 'R' },- python: { lineComment: '#', blockComment: false, quotes: '"\'', indentSensitive: true, tripleQuotes: true, fStrings: true },- shell: { lexer: shCodeLines, normalize: line => normalizeShellLine(line, '\\') },- powershell: { lexer: psCodeLines, normalize: line => normalizeShellLine(line, '`') },- batch: { lexer: batchCodeLines, normalize: line => line }+ js: { ...C_CONTEXT, flavor: 'js', forbiddenCode: '`/', jsx: true },+ go: { ...C_CONTEXT, flavor: 'go', forbiddenCode: '`' },+ rust: { ...C_CONTEXT, flavor: 'rust', quotes: '"', rustChars: true, rawPrefixes: 'r#', rustDocs: true },+ java: { ...C_CONTEXT, flavor: 'java', tripleQuotes: true },+ kotlin: { ...C_CONTEXT, flavor: 'kotlin', tripleQuotes: true, noDollarInStrings: true },+ csharp: { ...C_CONTEXT, flavor: 'csharp', tripleQuotes: true, rawPrefixes: '@$' },+ c: { ...C_CONTEXT, flavor: 'c', rawPrefixes: 'R' },+ cpp: { ...C_CONTEXT, flavor: 'c', rawPrefixes: 'R' },+ python: { lineComment: '#', blockComment: false, quotes: '"\'', indentSensitive: true, tripleQuotes: true, fStrings: true, startsFresh: pythonStartsFresh },+ shell: { lexer: shCodeLines, normalize: line => normalizeShellLine(line, '\\'), startsFresh: shStartsFresh },+ powershell: { lexer: psCodeLines, normalize: line => normalizeShellLine(line, '`'), startsFresh: psStartsFresh },+ batch: { lexer: batchCodeLines, normalize: line => line, startsFresh: batchStartsFresh }};+const TS_EXTS = new Set(['.ts', '.mts', '.cts']);+const TS_SPEC = { ...LEX_SPECS.js, jsx: false };++function lexSpecFor(filePath, language) {+ if (language !== 'js') return LEX_SPECS[language];+ const base = baseName(filePath);+ return TS_EXTS.has(base.slice(base.lastIndexOf('.'))) ? TS_SPEC : LEX_SPECS.js;+}function isSpace(ch) {return ch === ' ' || ch === '\t' || ch === '\f' || ch === '\v';@@ -122,14 +132,20 @@ function lexCodeLines(text, spec) {let quote = '';let stringBody = '';let commentStart = 0;+ let tail = '';+ const append = piece => {+ code += piece;+ tail = (tail + piece).slice(-2);+ };const endComment = end => {const marker = directiveMarker(text.slice(commentStart, end), spec);- if (marker) code += marker;+ if (marker) append(marker);};const endLine = () => {if (endsWithContinuation(code)) return false;lines.push(code);code = '';+ tail = '';return true;};if (spec.jsx !== undefined && text.startsWith('#!')) state = 'line';@@ -145,6 +161,7 @@ function lexCodeLines(text, spec) {if (state === 'block') {lines.push(code);code = '';+ tail = '';} else if (!endLine()) {return null;}@@ -156,7 +173,7 @@ function lexCodeLines(text, spec) {if (ch === '*' && text[i + 1] === '/') {endComment(i);state = 'code';- code += ' ';+ append(' ');i++;} else if (ch === '/' && text[i + 1] === '*') {return null;@@ -164,11 +181,11 @@ function lexCodeLines(text, spec) {continue;}if (state === 'string') {- code += ch;+ append(ch);if (ch === '\\') {const next = text[i + 1];if (next === undefined || next === '\n' || next === '\r') return null;- code += next;+ append(next);i++;} else if (ch === quote) {if (spec.noDollarInStrings && stringBody.includes('$')) return null;@@ -200,20 +217,20 @@ function lexCodeLines(text, spec) {if (spec.jsx !== undefined && ch === '-' && text[i + 1] === '-' && text[i + 2] === '>') return null;if (ch === "'" && spec.rustChars) {const end = rustCharEnd(text, i);- code += end === -1 ? ch : text.slice(i, end + 1);+ append(end === -1 ? ch : text.slice(i, end + 1));if (end !== -1) i = end;continue;}if (spec.quotes.includes(ch)) {if (spec.tripleQuotes && text[i + 1] === ch && text[i + 2] === ch) return null;- if (stringPrefixIsUnsafe(code, spec)) return null;+ if (stringPrefixIsUnsafe(tail, spec)) return null;state = 'string';quote = ch;stringBody = '';- code += ch;+ append(ch);continue;}- code += ch;+ append(ch);}if (state === 'string' || state === 'block') return null;if (state === 'line') {@@ -286,6 +303,724 @@ function isTrivialEdit(oldString, newString, spec) {return before.every((line, index) => line === after[index]);}+// --- File context ---+// see docs/gateguard/design-notes.md#file-context++const REPLACEMENT_PATTERN = /\$[$&'`<0-9]/;+const MAX_FILE_CHARS = 1024 * 1024;+const MAX_WINDOW_CHARS = 128 * 1024;+const MAX_CONTEXT_WORK = 8 * 1024 * 1024;+const JS_REGEX_KEYWORDS = new Set(['return', 'typeof', 'instanceof', 'in', 'of', 'new', 'delete', 'void', 'throw', 'case', 'do', 'else', 'yield', 'await']);+const JS_CONTROL_HEADERS = new Set(['if', 'while', 'for', 'with']);+const CPP_RAW_PREFIXES = new Set(['R', 'u8R', 'uR', 'UR', 'LR']);++function isNewline(ch) {+ return ch === '\n' || ch === '\r';+}++function lineEndAt(text, i) {+ let j = i;+ while (j < text.length && !isNewline(text[j])) j++;+ return j;+}++function quotedEnd(text, i, quote, multiline) {+ for (let j = i + 1; j < text.length; j++) {+ const ch = text[j];+ if (ch === '\\') {+ j++;+ if (text[j] === '\r' && text[j + 1] === '\n') j++;+ } else if (ch === quote) {+ return j + 1;+ } else if (isNewline(ch) && !multiline) {+ return -1;+ }+ }+ return -1;+}++function regexEnd(text, i) {+ let inClass = false;+ for (let j = i + 1; j < text.length; j++) {+ const ch = text[j];+ if (isNewline(ch)) return -1;+ if (ch === '\\') {+ if (j + 1 >= text.length || isNewline(text[j + 1])) return -1;+ j++;+ } else if (inClass) {+ if (ch === ']') inClass = false;+ } else if (ch === '[') {+ inClass = true;+ } else if (ch === '/') {+ let k = j + 1;+ while (isIdentChar(text[k])) k++;+ return k;+ }+ }+ return -1;+}++function nestedBlockEnd(text, i) {+ let depth = 0;+ for (let j = i; j + 1 < text.length; j++) {+ if (text[j] === '/' && text[j + 1] === '*') {+ depth++;+ j++;+ } else if (text[j] === '*' && text[j + 1] === '/') {+ depth--;+ j++;+ if (depth === 0) return j + 1;+ }+ }+ return -1;+}++function textBlockEnd(text, i, escapes) {+ for (let j = i + 3; j < text.length; j++) {+ if (escapes && text[j] === '\\') {+ j++;+ } else if (!escapes && text[j] === '$' && text[j + 1] === '{') {+ return -1;+ } else if (text.startsWith('"""', j)) {+ let end = j + 3;+ while (text[end] === '"') end++;+ return end;+ }+ }+ return -1;+}++function kotlinStringEnd(text, i) {+ for (let j = i + 1; j < text.length; j++) {+ const ch = text[j];+ if (ch === '\\') j++;+ else if (ch === '$' && text[j + 1] === '{') return -1;+ else if (ch === '"') return j + 1;+ else if (isNewline(ch)) return -1;+ }+ return -1;+}++function csharpStringEnd(text, i) {+ let j = i;+ let verbatim = false;+ let interpolated = false;+ while (text[j] === '@' || text[j] === '$') {+ if (text[j] === '@') verbatim = true;+ else interpolated = true;+ j++;+ }+ if (text.startsWith('"""', j)) return -1;+ for (let k = j + 1; k < text.length; k++) {+ const ch = text[k];+ if (ch === '"') {+ if (verbatim && text[k + 1] === '"') {+ k++;+ continue;+ }+ return k + 1;+ }+ if (!verbatim && ch === '\\') {+ k++;+ } else if (!verbatim && isNewline(ch)) {+ return -1;+ } else if (interpolated && ch === '{') {+ if (text[k + 1] === '{') {+ k++;+ continue;+ }+ let m = k + 1;+ while (m < text.length && text[m] !== '}') {+ if ('"\'{/\n\r'.includes(text[m])) return -1;+ m++;+ }+ if (m >= text.length) return -1;+ k = m;+ }+ }+ return -1;+}++function cppRawEnd(text, quote) {+ const open = text.indexOf('(', quote + 1);+ if (open === -1 || open - quote - 1 > 16) return -1;+ const delimiter = text.slice(quote + 1, open);+ for (const ch of delimiter) {+ if (isSpace(ch) || isNewline(ch) || '()\\"'.includes(ch)) return -1;+ }+ const end = text.indexOf(`)${delimiter}"`, open + 1);+ return end === -1 ? -1 : end + delimiter.length + 2;+}++function rustRawEnd(text, i) {+ let j = i + (text[i] === 'r' ? 1 : 2);+ let hashes = '';+ while (text[j] === '#') {+ hashes += '#';+ j++;+ }+ if (text[j] !== '"') return null;+ const end = text.indexOf(`"${hashes}`, j + 1);+ return end === -1 ? -1 : end + 1 + hashes.length;+}++function wordStart(text, i) {+ let start = i;+ while (start > 0 && isIdentChar(text[start - 1])) start--;+ return start;+}++function cFamilyStringEnd(text, i, spec) {+ const ch = text[i];+ const flavor = spec.flavor;+ if (ch === '`') {+ if (flavor === 'kotlin') return quotedEnd(text, i, '`', false);+ if (flavor !== 'go') return -1;+ const end = text.indexOf('`', i + 1);+ return end === -1 ? -1 : end + 1;+ }+ if (ch === "'") {+ if (flavor === 'rust') {+ const end = rustCharEnd(text, i);+ return end === -1 ? null : end + 1;+ }+ if (flavor === 'c' && isIdentChar(text[i - 1]) && isIdentChar(text[i + 1])) {+ const first = text[wordStart(text, i)];+ if (first >= '0' && first <= '9') return null;+ }+ return quotedEnd(text, i, "'", false);+ }+ if (flavor === 'c') {+ const start = wordStart(text, i);+ const prefix = text.slice(start, i);+ if (CPP_RAW_PREFIXES.has(prefix)) return cppRawEnd(text, i);+ if (prefix.endsWith('R')) return -1;+ }+ if (flavor === 'java' && text.startsWith('"""', i)) return textBlockEnd(text, i, true);+ if (flavor === 'kotlin') return text.startsWith('"""', i) ? textBlockEnd(text, i, false) : kotlinStringEnd(text, i);+ if (flavor === 'csharp' && text.startsWith('"""', i)) return -1;+ return quotedEnd(text, i, '"', flavor === 'rust');+}++function cFamilyStartsFresh(text, spec) {+ const js = spec.flavor === 'js';+ const frames = [{ template: false, depth: 0 }];+ const parens = [];+ let lastWord = '';+ let lastSig = 'op';+ let lineEnd = '';+ let continued = false;+ let i = js && text.startsWith('#!') ? lineEndAt(text, 0) : 0;+ while (i < text.length) {+ const frame = frames[frames.length - 1];+ const ch = text[i];+ const next = text[i + 1];+ if (frame.template) {+ if (ch === '\\') {+ i += 2;+ } else if (ch === '`') {+ frames.pop();+ lastSig = 'value';+ i++;+ } else if (ch === '$' && next === '{') {+ frames.push({ template: false, depth: 0 });+ lastSig = 'op';+ i += 2;+ } else {+ i++;+ }+ continue;+ }+ if (isNewline(ch)) {+ continued = lineEnd === '\\';+ lineEnd = '';+ i++;+ continue;+ }+ if (isSpace(ch)) {+ i++;+ continue;+ }+ if (ch === '/' && next === '/') {+ const end = lineEndAt(text, i);+ if (text.slice(i, end).trimEnd().endsWith('\\')) return false;+ i = end;+ continue;+ }+ if (ch === '/' && next === '*') {+ const end = spec.rustDocs ? nestedBlockEnd(text, i) : text.indexOf('*/', i + 2);+ if (end === -1) return false;+ i = spec.rustDocs ? end : end + 2;+ lineEnd = '';+ continue;+ }+ lineEnd = ch;+ if (js) {+ if (ch === '`') {+ frames.push({ template: true, depth: 0 });+ i++;+ continue;+ }+ if (ch === '/') {+ if (lastSig === 'op') {+ const end = regexEnd(text, i);+ if (end === -1) return false;+ lineEnd = text[end - 1];+ lastSig = 'value';+ i = end;+ continue;+ }+ if (lastSig === 'close' && /[/'"`]/.test(text.slice(i + 1, lineEndAt(text, i)))) return false;+ lastSig = 'op';+ i++;+ continue;+ }+ if (ch === '<' && (next === '!' || (spec.jsx && (isLetter(next) || next === '/' || next === '>')))) return false;+ if (ch === '-' && next === '-' && text[i + 2] === '>') return false;+ if (frames.length > 1 && ch === '{') frame.depth++;+ if (frames.length > 1 && ch === '}') {+ if (frame.depth === 0) {+ frames.pop();+ i++;+ continue;+ }+ frame.depth--;+ }+ }+ if (spec.flavor === 'csharp' && (ch === '@' || ch === '$') && /^[@$]{1,3}"/.test(text.slice(i, i + 4))) {+ const end = csharpStringEnd(text, i);+ if (end === -1) return false;+ lineEnd = '"';+ i = end;+ continue;+ }+ if (spec.flavor === 'rust' && (ch === 'r' || ((ch === 'b' || ch === 'c') && next === 'r')) && !isIdentChar(text[i - 1])) {+ const end = rustRawEnd(text, i);+ if (end === -1) return false;+ if (end !== null) {+ lineEnd = text[end - 1];+ lastSig = 'value';+ i = end;+ continue;+ }+ }+ if (ch === '"' || ch === "'" || ch === '`') {+ const end = cFamilyStringEnd(text, i, spec);+ if (end === -1) return false;+ if (end !== null) {+ lineEnd = text[end - 1];+ lastSig = 'value';+ i = end;+ continue;+ }+ i++;+ continue;+ }+ if (isIdentChar(ch)) {+ let end = i;+ while (end < text.length && isIdentChar(text[end])) end++;+ lastWord = text.slice(i, end);+ lastSig = js && JS_REGEX_KEYWORDS.has(lastWord) ? 'op' : 'value';+ lineEnd = text[end - 1];+ i = end;+ continue;+ }+ if (ch === '(') {+ parens.push(lastSig === 'value' && JS_CONTROL_HEADERS.has(lastWord));+ lastSig = 'op';+ } else if (ch === ')') {+ lastSig = parens.pop() ? 'op' : 'value';+ } else {+ lastSig = ch === '}' ? 'close' : ch === ']' ? 'value' : 'op';+ }+ lastWord = '';+ i++;+ }+ return frames.length === 1 && !continued;+}++function pythonStringEnd(text, i, prefix) {+ const quote = text[i];+ const triple = text[i + 1] === quote && text[i + 2] === quote;+ const fString = prefix.toLowerCase().includes('f');+ let depth = 0;+ for (let j = i + (triple ? 3 : 1); j < text.length; j++) {+ const ch = text[j];+ if (fString && depth > 0) {+ if (ch === '{') {+ depth++;+ } else if (ch === '}') {+ depth--;+ } else if ((ch === '"' || ch === "'") && ch !== quote) {+ let k = j + 1;+ while (k < text.length && text[k] !== ch) {+ if (text[k] === quote || text[k] === '\\' || isNewline(text[k])) return -1;+ k++;+ }+ if (k >= text.length) return -1;+ j = k;+ } else if (ch === quote || ch === '#' || ch === '\\' || isNewline(ch)) {+ return -1;+ }+ continue;+ }+ if (ch === '\\') {+ j++;+ if (text[j] === '\r' && text[j + 1] === '\n') j++;+ } else if (fString && ch === '{') {+ if (text[j + 1] === '{') j++;+ else depth = 1;+ } else if (isNewline(ch) && !triple) {+ return -1;+ } else if (ch === quote && (!triple || (text[j + 1] === quote && text[j + 2] === quote))) {+ return j + (triple ? 3 : 1);+ }+ }+ return -1;+}++function pythonStartsFresh(text) {+ let lineEnd = '';+ let continued = false;+ let i = 0;+ while (i < text.length) {+ const ch = text[i];+ if (isNewline(ch)) {+ continued = lineEnd === '\\';+ lineEnd = '';+ i++;+ } else if (isSpace(ch)) {+ i++;+ } else if (ch === '#') {+ i = lineEndAt(text, i);+ } else if (ch === '"' || ch === "'") {+ const start = wordStart(text, i);+ const prefix = text.slice(start, i);+ if (prefix.length > 2 || /[^rbuf]/i.test(prefix)) return false;+ const end = pythonStringEnd(text, i, prefix);+ if (end === -1) return false;+ lineEnd = ch;+ i = end;+ } else {+ lineEnd = ch;+ i++;+ }+ }+ return !continued;+}++function heredocDelimiter(text, i) {+ let j = i + 2;+ const stripTabs = text[j] === '-';+ if (stripTabs) j++;+ while (isBlank(text[j])) j++;+ let word = '';+ while (j < text.length && !isBlank(text[j]) && !isNewline(text[j]) && !';|&<>()'.includes(text[j])) {+ if (!'\'"\\'.includes(text[j])) word += text[j];+ j++;+ }+ return word ? { word, stripTabs, end: j } : null;+}++function skipHeredocs(text, i, pending) {+ let at = i;+ for (const doc of pending) {+ for (;;) {+ if (at >= text.length) return -1;+ const end = lineEndAt(text, at);+ let line = text.slice(at, end);+ if (doc.stripTabs) line = line.replace(/^\t+/, '');+ at = end + (text[end] === '\r' && text[end + 1] === '\n' ? 2 : 1);+ if (line === doc.word) break;+ }+ }+ return at;+}++const MAX_NESTING = 8;++function shSingleQuoteEnd(text, i) {+ if (text[i - 1] === '$') return quotedEnd(text, i, "'", true);+ return text.indexOf("'", i + 1) + 1 || -1;+}++function shSubstitutionEnd(text, i, level) {+ if (level > MAX_NESTING) return -1;+ let depth = 0;+ for (let j = i + 1; j < text.length; j++) {+ const ch = text[j];+ if (ch === '\\') {+ j++;+ } else if (ch === '(') {+ depth++;+ } else if (ch === ')') {+ depth--;+ if (depth === 0) return j + 1;+ } else if (ch === "'" || ch === '"') {+ const end = ch === "'" ? shSingleQuoteEnd(text, j) : shDoubleQuoteScan(text, j, level + 1);+ if (end === -1) return -1;+ j = end - 1;+ } else if (ch === '`' || (ch === '<' && text[j + 1] === '<') || (ch === '#' && hashStartsComment(text, j) !== false)) {+ return -1;+ } else if (ch === 'c' && text.startsWith('case', j) && !isIdentChar(text[j - 1]) && !isIdentChar(text[j + 4])) {+ return -1;+ }+ }+ return -1;+}++function shDoubleQuoteScan(text, i, level) {+ for (let j = i + 1; j < text.length; j++) {+ const ch = text[j];+ if (ch === '"') return j + 1;+ if (ch === '\\') {+ j++;+ } else if (ch === '`') {+ return -1;+ } else if (ch === '$' && text[j + 1] === '(') {+ const end = shSubstitutionEnd(text, j, level);+ if (end === -1) return -1;+ j = end - 1;+ } else if (ch === '$' && text[j + 1] === '{') {+ const close = text.indexOf('}', j + 2);+ if (close === -1 || /["'\n\r]/.test(text.slice(j + 2, close))) return -1;+ j = close;+ }+ }+ return -1;+}++function shStartsFresh(text) {+ if (hasLoneCarriageReturn(text)) return false;+ const pending = [];+ let lineEnd = '';+ let continued = false;+ let i = 0;+ while (i < text.length) {+ const ch = text[i];+ if (isNewline(ch)) {+ continued = lineEnd === '\\';+ lineEnd = '';+ i += ch === '\r' && text[i + 1] === '\n' ? 2 : 1;+ if (pending.length > 0) {+ i = skipHeredocs(text, i, pending);+ if (i === -1) return false;+ pending.length = 0;+ }+ continue;+ }+ if (isBlank(ch)) {+ i++;+ continue;+ }+ lineEnd = ch;+ if (ch === '\\') {+ i += isNewline(text[i + 1]) ? 1 : 2;+ } else if (ch === "'") {+ const end = shSingleQuoteEnd(text, i);+ if (end === -1) return false;+ i = end;+ } else if (ch === '"') {+ const end = shDoubleQuoteScan(text, i, 0);+ if (end === -1) return false;+ i = end;+ } else if (ch === '`') {+ const end = text.indexOf('`', i + 1);+ if (end === -1 || /['"\\#\n\r]/.test(text.slice(i + 1, end))) return false;+ i = end + 1;+ } else if (ch === '#') {+ const starts = hashStartsComment(text, i);+ if (starts === null) return false;+ i = starts ? lineEndAt(text, i) : i + 1;+ if (starts) lineEnd = '';+ } else if (ch === '<' && text[i + 1] === '<') {+ if (text[i + 2] === '<') {+ i += 3;+ continue;+ }+ const doc = heredocDelimiter(text, i);+ if (!doc) return false;+ pending.push(doc);+ i = doc.end;+ } else {+ i++;+ }+ }+ return !continued && pending.length === 0;+}++function psSingleQuoteEnd(text, i) {+ for (let j = i + 1; j < text.length; j++) {+ if (text[j] !== "'") continue;+ if (text[j + 1] !== "'") return j + 1;+ j++;+ }+ return -1;+}++function psSubexpressionEnd(text, i, level) {+ if (level > MAX_NESTING) return -1;+ let depth = 0;+ for (let j = i + 1; j < text.length; j++) {+ const ch = text[j];+ if (ch === '`') {+ j++;+ } else if (ch === '(') {+ depth++;+ } else if (ch === ')') {+ depth--;+ if (depth === 0) return j + 1;+ } else if (ch === "'" || ch === '"') {+ const end = ch === "'" ? psSingleQuoteEnd(text, j) : psDoubleQuoteScan(text, j, level + 1);+ if (end === -1) return -1;+ j = end - 1;+ } else if (ch === '#' || (ch === '@' && (text[j + 1] === '"' || text[j + 1] === "'"))) {+ return -1;+ }+ }+ return -1;+}++function psDoubleQuoteScan(text, i, level) {+ for (let j = i + 1; j < text.length; j++) {+ const ch = text[j];+ if (ch === '`') {+ j++;+ } else if (ch === '$' && text[j + 1] === '(') {+ const end = psSubexpressionEnd(text, j, level);+ if (end === -1) return -1;+ j = end - 1;+ } else if (ch === '"') {+ if (text[j + 1] !== '"') return j + 1;+ j++;+ }+ }+ return -1;+}++function psStartsFresh(text) {+ if (PS_SMART_QUOTES.test(text)) return false;+ let lineEnd = '';+ let continued = false;+ let i = 0;+ while (i < text.length) {+ const ch = text[i];+ const next = text[i + 1];+ if (isNewline(ch)) {+ continued = lineEnd === '`';+ lineEnd = '';+ i++;+ continue;+ }+ if (isBlank(ch)) {+ i++;+ continue;+ }+ lineEnd = ch;+ if (ch === '`') {+ i += isNewline(next) ? 1 : 2;+ } else if (ch === '@' && (next === '"' || next === "'")) {+ const open = lineEndAt(text, i);+ if (text.slice(i + 2, open).trim() !== '') return false;+ let at = open;+ let found = -1;+ while (at < text.length) {+ at += text[at] === '\r' && text[at + 1] === '\n' ? 2 : 1;+ if (text.startsWith(`${next}@`, at)) {+ found = at + 2;+ break;+ }+ at = lineEndAt(text, at);+ }+ if (found === -1) return false;+ i = found;+ } else if (ch === "'" || ch === '"') {+ const end = ch === "'" ? psSingleQuoteEnd(text, i) : psDoubleQuoteScan(text, i, 0);+ if (end === -1) return false;+ i = end;+ } else if (ch === '<' && next === '#') {+ if (!psHashStartsComment(text, i)) return false;+ const end = text.indexOf('#>', i + 2);+ if (end === -1) return false;+ i = end + 2;+ lineEnd = '';+ } else if (ch === '#') {+ if (psHashStartsComment(text, i)) {+ i = lineEndAt(text, i);+ lineEnd = '';+ } else if (isIdentChar(text[i - 1]) || '-.:'.includes(text[i - 1])) {+ i++;+ } else {+ return false;+ }+ } else {+ i++;+ }+ }+ return !continued;+}++function batchStartsFresh(text) {+ const lines = text.split(/\r\n|\r|\n/);+ const last = lines.length > 1 ? lines[lines.length - 2] : '';+ return !last.endsWith('^');+}++function lineStartOf(text, i) {+ let start = i;+ while (start > 0 && !isNewline(text[start - 1])) start--;+ return start;+}++function windowStart(text, at) {+ const start = lineStartOf(text, at);+ if (start === 0) return 0;+ let end = start - 1;+ if (text[end] === '\n' && text[end - 1] === '\r') end--;+ return lineStartOf(text, end);+}++function windowEnd(text, at) {+ const end = lineEndAt(text, at);+ if (end >= text.length) return text.length;+ return end + (text[end] === '\r' && text[end + 1] === '\n' ? 2 : 1);+}++function occurrences(text, needle, replaceAll) {+ const first = text.indexOf(needle);+ if (first === -1) return null;+ let last = first;+ for (let at = text.indexOf(needle, first + needle.length); at !== -1; at = text.indexOf(needle, at + needle.length)) {+ if (!replaceAll) return null;+ last = at;+ }+ return { first, last };+}++function trivialInFile(pairs, fileText, spec) {+ if (typeof fileText !== 'string' || fileText.length > MAX_FILE_CHARS || !spec.startsFresh) return false;+ if (spec.flavor === 'go' && fileText.includes('"C"')) return false;+ let text = fileText;+ let work = 0;+ for (const [oldString, newString, replaceAll] of pairs) {+ if (!oldString || REPLACEMENT_PATTERN.test(newString)) return false;+ const found = occurrences(text, oldString, replaceAll);+ if (!found) return false;+ const start = windowStart(text, found.first);+ const end = windowEnd(text, found.last + oldString.length);+ work += start + 2 * (end - start);+ if (end - start > MAX_WINDOW_CHARS || work > MAX_CONTEXT_WORK || !spec.startsFresh(text.slice(0, start), spec)) return false;+ const before = text.slice(start, end);+ const after = replaceAll+ ? before.split(oldString).join(newString)+ : `${text.slice(start, found.first)}${newString}${text.slice(found.first + oldString.length, end)}`;+ if (!isTrivialEdit(before, after, spec)) return false;+ text = `${text.slice(0, start)}${after}${text.slice(end)}`;+ if (text.length > MAX_FILE_CHARS) return false;+ }+ return true;+}+// --- Shell lexing ---// see docs/gateguard/design-notes.md#shell-scripts@@ -762,9 +1497,9 @@ function changeTexts(input) {const oldString = entry.old_string;const newString = entry.new_string;if (typeof oldString !== 'string' || typeof newString !== 'string') return null;- pairs.push([oldString, newString]);+ pairs.push([oldString, newString, entry.replace_all === true]);}- return { sides: pairs.flat(), pairs };+ return { sides: pairs.flatMap(([oldString, newString]) => [oldString, newString]), pairs };}function withinBounds(sides) {@@ -779,7 +1514,7 @@ function withinBounds(sides) {return true;}-/** Profile of one target's change from Edit/MultiEdit entries or Write content; unknown on any doubt. */+/** Profile of one target's change from Edit/MultiEdit entries or Write content, judged against `fileText` when given; unknown on any doubt. */function profileChange(input) {try {if (!input || typeof input !== 'object') return UNKNOWN_PROFILE;@@ -791,8 +1526,7 @@ function profileChange(input) {const touchesPublicSurface = input.tool === 'Write' || !lineIsSurface || wholeFileIsSurface(input.filePath, language) ||texts.sides.some(side => textTouchesSurface(side, lineIsSurface));const touchesData = texts.sides.some(side => textTouchesData(side, language));- const spec = LEX_SPECS[language];- const trivial = input.tool === 'Edit' && texts.pairs.every(([oldString, newString]) => isTrivialEdit(oldString, newString, spec));+ const trivial = input.tool === 'Edit' && trivialInFile(texts.pairs, input.fileText, lexSpecFor(input.filePath, language));return Object.freeze({ known: true, language, touchesPublicSurface, touchesData, trivial });} catch (_) {return UNKNOWN_PROFILE;diff --git a/skills/gateguard/SKILL.md b/skills/gateguard/SKILL.mdindex 562a3c260..6952ff3bb 100644--- a/skills/gateguard/SKILL.md+++ b/skills/gateguard/SKILL.md@@ -414,24 +414,31 @@ It applies only to the extensions listed inentry reads cleanly:- comments are `//` and `/* */` (C family), `#` (Python), `#` at the start of- a word (shell), `#` and `<# #>` (PowerShell, not `#Requires`), or `REM`- lines (batch); C preprocessor lines, shebang lines and batch `::` labels- are code; whitespace inside strings, line breaks between code, and+ a word (shell), `#` and `<# #>` (PowerShell), or `REM` lines (batch);+ C preprocessor lines and batch `::` labels are code; directive comments are+ code too (shebangs, encoding cookies, `# type:`, `# noqa`, `# nosec`,+ `// @ts-...`, `eslint-...`, `//go:build`, `// +build`, `//go:embed`, Rust+ doc comments, `#Requires`, `shellcheck`, `NOLINT`, `NOSONAR`, fallthrough+ markers and similar); whitespace inside strings, line breaks between code, andthe presence of whitespace between tokens are code (`a+b` → `a + b` is nottrivial);- Python indentation of code lines is code;- never trivial: a Write; any multi-line or raw string form (backticks, triplequotes, `r"`, `R"`, `@"`, `$"`, f-strings, Kotlin `$`), a string running to- the end of a line, a line comment ending in `\`, `??/`, a nested or- unterminated block comment; in JS/TS any `/` outside a comment (regex versus+ the end of a line, a line comment or code line ending in `\`, `??/`, a+ nested or unterminated block comment; in JS/TS any `/` outside a comment (regex versusdivision), JSX-like tags, and `-->`; in shell scripts heredocs, backticks,`$(` inside double quotes, `$'...'`, line continuations and here-strings(see the design notes for the full list);- config, instruction, and sensitive targets never pass this way.-Only the snippet is read, so a comment-looking line inside a multi-line string-that opens and closes outside the snippet reads as a comment; because the-file stays unchecked, the next real change is still gated.+The edit is also checked against the current file (a regular file of at+most 1 MiB, read by the hook and never stored): `old_string` must be found as+the Edit tool would apply it, the lines around the change must compare equal+as above, and the text before them must end in plain code, not inside a+template literal, docstring, raw string, heredoc or here-string and not after+a line continuation. A missing, unreadable or larger file, or a Go file that+imports `"C"`, never passes this way.### Same-turn sibling creation collapsediff --git a/tests/hooks/gateguard-fact-force.test.js b/tests/hooks/gateguard-fact-force.test.jsindex b6b514022..8e61f73b7 100644--- a/tests/hooks/gateguard-fact-force.test.js+++ b/tests/hooks/gateguard-fact-force.test.js@@ -4611,15 +4611,32 @@ function runTests() {else failed++;// --- Comment and whitespace-only edits ---+ const b3Root = fs.mkdtempSync(path.join(tmpRoot, 'gateguard-b3-'));+ const b3Seed = tool_input => {+ const entries = Array.isArray(tool_input.edits) ? tool_input.edits : [tool_input];+ const byFile = new Map();+ for (const entry of entries) {+ const rel = entry.file_path || tool_input.file_path;+ if (typeof rel !== 'string' || typeof entry.old_string !== 'string') continue;+ byFile.set(rel, [...(byFile.get(rel) || []), entry.old_string]);+ }+ for (const [rel, parts] of byFile) {+ const file = path.join(b3Root, rel);+ if (fs.existsSync(file)) continue;+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, `${parts.join('\n')}\n`);+ }+ };const b3Run = (toolName, tool_input, env = {}) => {- const result = runHook({ tool_name: toolName, tool_input }, { ...B2_ENV, ...env });+ b3Seed(tool_input);+ const result = runHook({ tool_name: toolName, tool_input }, { CLAUDE_PROJECT_DIR: b3Root, ...env });const output = parseOutput(result.stdout);const hso = output && output.hookSpecificOutput ? output.hookSpecificOutput : {};const context = Array.isArray(hso.additionalContext) ? hso.additionalContext.join('\n') : String(hso.additionalContext || '');return { result, decision: hso.permissionDecision, context, reason: hso.permissionDecisionReason || '' };};const b3State = () => (fs.existsSync(stateFile) ? JSON.parse(fs.readFileSync(stateFile, 'utf8')) : {});- const b3Key = rel => `/proj-b2/${rel}`;+ const b3Key = rel => `${b3Root}/${rel}`;const B3_NOTE = 'Comment or whitespace-only change to';clearState();@@ -4718,6 +4735,77 @@ function runTests() {passed++;else failed++;+ clearState();+ if (+ test('comment-looking edits that change code in their file context are denied', () => {+ const cases = [+ ['macro continuation', 'src/ctx/a.c', '#define A 1 \\\n// c\nint x;\n', { old_string: '// c\n', new_string: '' }],+ ['joined next line', 'src/ctx/b.js', 'a();\n// c\nb();\n', { old_string: '// c\n', new_string: '// c ' }],+ ['template literal', 'src/ctx/c.js', 'const q = `\n // hint\n SELECT 1\n`;\n', { old_string: ' // hint', new_string: ' // other' }],+ ['docstring', 'src/ctx/d.py', 'Q = """\n# limit 10\nSELECT 1\n"""\n', { old_string: '# limit 10', new_string: '# limit 99' }],+ ['heredoc body', 'scripts/ctx/e.sh', 'cat > colors.txt <<EOF\n#ff0000\n#00ff00\nEOF\n', { old_string: '#00ff00', new_string: '#0000ff' }],+ ['inside a string', 'src/ctx/f.js', 'const s = "abc // q";\n', { old_string: '// q"', new_string: '// r"' }],+ ['replace_all into a string', 'src/ctx/g.js', 'x = "// a"; // a\n', { old_string: '// a', new_string: '// b', replace_all: true }],+ ['type directive', 'src/ctx/h.py', 'x = f() # type: ignore\n', { old_string: '# type: ignore', new_string: '# ok' }],+ ['suppression marker', 'src/ctx/i.py', 'call(cmd, shell=True) # nosec\n', { old_string: '# nosec', new_string: '# reviewed' }],+ ['build constraint', 'src/ctx/j.go', '//go:build linux\n\npackage j\n', { old_string: '//go:build linux', new_string: '//go:build ignore' }],+ ['cgo preamble', 'src/ctx/k.go', 'package k\n\n// int add(int a) { return a; }\nimport "C"\n', { old_string: 'return a;', new_string: 'return a + 1;' }]+ ];+ for (const [label, rel, content, input] of cases) {+ clearState();+ const file = path.join(b3Root, rel);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, content);+ const out = b3Run('Edit', { file_path: rel, ...input });+ assert.strictEqual(out.decision, 'deny', `${label}: ${out.result.stdout}`);+ assert.strictEqual(b3State().trivial_allows || 0, 0, `${label}: no trivial count`);+ }+ })+ )+ passed++;+ else failed++;++ clearState();+ if (+ test('the trivial pass needs a readable regular file under the size bound', () => {+ const input = { old_string: '// old', new_string: '// new' };+ const cases = [['missing file', 'src/nf/missing.js']];+ const big = path.join(b3Root, 'src/nf/big.js');+ fs.mkdirSync(path.dirname(big), { recursive: true });+ fs.writeFileSync(big, `// old\n${'x();\n'.repeat(300 * 1024)}`);+ cases.push(['file over 1 MiB', 'src/nf/big.js']);+ fs.mkdirSync(path.join(b3Root, 'src/nf/dir.js'), { recursive: true });+ cases.push(['directory', 'src/nf/dir.js']);+ if (process.platform !== 'win32' && spawnSync('mkfifo', [path.join(b3Root, 'src/nf/pipe.js')]).status === 0) {+ cases.push(['named pipe', 'src/nf/pipe.js']);+ }+ for (const [label, rel] of cases) {+ clearState();+ const started = Date.now();+ const result = runHook({ tool_name: 'Edit', tool_input: { file_path: rel, ...input } }, { CLAUDE_PROJECT_DIR: b3Root });+ const hso = (parseOutput(result.stdout) || {}).hookSpecificOutput || {};+ assert.strictEqual(hso.permissionDecision, 'deny', `${label}: ${result.stdout}`);+ assert.ok(Date.now() - started < 10000, `${label}: returned promptly`);+ }+ })+ )+ passed++;+ else failed++;++ clearState();+ if (+ test('a comment edit next to closed multi-line constructs still passes', () => {+ const rel = 'src/ctx/ok.js';+ const file = path.join(b3Root, rel);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, 'const q = `a\n${b}\n`;\nconst r = /[/"]+/g;\n\n// old\nfoo();\n');+ const out = b3Run('Edit', { file_path: rel, old_string: '// old', new_string: '// new' });+ assert.ok(out.context.includes(`${B3_NOTE} ${rel}`), out.result.stdout);+ })+ )+ passed++;+ else failed++;+clearState();if (test('a Write is never a trivial edit', () => {diff --git a/tests/hooks/gateguard-metrics.test.js b/tests/hooks/gateguard-metrics.test.jsindex 93801303a..1e58caa39 100644--- a/tests/hooks/gateguard-metrics.test.js+++ b/tests/hooks/gateguard-metrics.test.js@@ -155,6 +155,11 @@ function writeTranscript(searches) {const src = name => path.join(projectRoot, 'src', name);+function seed(file, content) {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, content);+}+console.log('\n=== Testing GateGuard decision metrics ===\n');test('writes no metrics file when GATEGUARD_METRICS is unset', () => {@@ -222,6 +227,7 @@ test('records a sensitive denial with the full question set', () => {test('records a comment-only edit as trivial', () => {resetState();+ seed(src('quiet-helper-beta.js'), 'run(); // COMMENT-BODY-RHO old\n');const result = edit(src('quiet-helper-beta.js'), 'run(); // COMMENT-BODY-RHO old', 'run(); // COMMENT-BODY-RHO new');assert.strictEqual(result.decision, 'pass');const event = lastEvent();@@ -292,6 +298,7 @@ test('records a subagent denial on a sensitive target', () => {test('records one line per file decided by a MultiEdit call', () => {resetState();+ seed(src('multi-kappa.js'), 'x(); // a\ny(); // a\n');const result = runHook('pre:edit-write:gateguard-fact-force', {tool_name: 'MultiEdit',tool_input: {diff --git a/tests/lib/gateguard-change-profile.test.js b/tests/lib/gateguard-change-profile.test.jsindex 0fbc0ea3e..2e08720d7 100644--- a/tests/lib/gateguard-change-profile.test.js+++ b/tests/lib/gateguard-change-profile.test.js@@ -28,7 +28,10 @@ function test(desc, fn) {}}-const edit = (filePath, oldString, newString) => profileChange({ filePath, tool: 'Edit', edits: [{ old_string: oldString, new_string: newString }] });+const edit = (filePath, oldString, newString) =>+ profileChange({ filePath, tool: 'Edit', edits: [{ old_string: oldString, new_string: newString }], fileText: oldString });+const inFile = (filePath, fileText, oldString, newString, replaceAll = false) =>+ profileChange({ filePath, tool: 'Edit', edits: [{ old_string: oldString, new_string: newString, replace_all: replaceAll }], fileText }).trivial;const write = (filePath, content) => profileChange({ filePath, tool: 'Write', content });const surface = (filePath, oldString, newString) => edit(filePath, oldString, newString).touchesPublicSurface;const data = (filePath, oldString, newString) => edit(filePath, oldString, newString).touchesData;@@ -533,11 +536,119 @@ test('Write, unknown languages and MultiEdit with any non-trivial entry are notassert.strictEqual(write('a.js', '// only a comment\n').trivial, false);assert.strictEqual(trivial('a.rb', '# a', '# b'), false);assert.strictEqual(trivial('a.fish', '# a', '# b'), false);- const multi = edits => profileChange({ filePath: 'a.js', tool: 'Edit', edits });+ const multi = edits => profileChange({ filePath: 'a.js', tool: 'Edit', edits, fileText: '// a\nfoo();\n// c\nf(1);\n' });assert.strictEqual(multi([{ old_string: '// a', new_string: '// b' }, { old_string: '// c', new_string: '// d' }]).trivial, true);assert.strictEqual(multi([{ old_string: '// a', new_string: '// b' }, { old_string: 'f(1)', new_string: 'f(2)' }]).trivial, false);});+// ── file context ──+console.log('\nfile context:');++test('an edit is trivial only against the file it applies to', () => {+ const change = { filePath: 'a.js', tool: 'Edit', edits: [{ old_string: '// a', new_string: '// b' }] };+ assert.strictEqual(profileChange(change).trivial, false, 'no file text');+ assert.strictEqual(profileChange({ ...change, fileText: null }).trivial, false, 'unreadable file');+ assert.strictEqual(profileChange({ ...change, fileText: 'x();\n' }).trivial, false, 'old_string not in the file');+ assert.strictEqual(profileChange({ ...change, fileText: '// a\n// a\n' }).trivial, false, 'ambiguous without replace_all');+ assert.strictEqual(profileChange({ ...change, fileText: 'x();\n// a\ny();\n' }).trivial, true);+ assert.strictEqual(inFile('a.js', 'x();\n', '', '// a'), false, 'empty old_string');+ assert.strictEqual(inFile('a.js', '// a\n// a\n', '// a', '// b', true), true, 'replace_all over comments');+ assert.strictEqual(inFile('a.js', `// a\n${'x();\n'.repeat(10)}`, '// a', '// b'), true);+ assert.strictEqual(inFile('a.js', `// a\n${'x'.repeat(2 * 1024 * 1024)}`, '// a', '// b'), false, 'file over the bound');+ for (const pattern of ["$'", '$`', '$&', '$$', '$1', '$<a>']) {+ assert.strictEqual(inFile('a.js', 'x();\n// a\ny();\n', '// a', `// b ${pattern}`), false, `replacement pattern ${pattern}`);+ }+ assert.strictEqual(inFile('a.js', 'x();\n// a\ny();\n', '// a', '// costs $5 or $x'), false, 'a dollar digit reads as a pattern');+ assert.strictEqual(inFile('a.js', 'x();\n// a\ny();\n', '// a', '// costs $ x'), true);+});++test('comment-looking text inside a multi-line construct of the file is not trivial', () => {+ const cases = [+ ['a.js', 'const q = `\n // hint\n SELECT 1\n`;\n', ' // hint', ' // other'],+ ['a.js', 'const q = html`\n <p>${x}</p>\n // a\n`;\n', ' // a', ' // b'],+ ['a.js', "const s = 'a\\\n// a';\n", "// a';", "// b';"],+ ['a.js', 'const s = "abc // q";\n', '// q"', '// r"'],+ ['a.js', 'x = "// a"; // a\n', '// a', '// b', true],+ ['a.js', '/* start\nmiddle\n// a */ x(1);\n', 'x(1)', 'x(2)'],+ ['a.ts', 'const t = `\n${a}\n// a\n`;\n', '// a', '// b'],+ ['a.py', 'Q = """\n# limit 10\nSELECT 1\n"""\n', '# limit 10', '# limit 99'],+ ['a.py', "Q = f'''\n{x}\n# a\n'''\n", '# a', '# b'],+ ['a.py', 'Q = (\n "a"\n)\nS = """x\ny\n# a\n"""\n', '# a', '# b'],+ ['a.go', 'var q = `\nfirst\n// a\n`\n', '// a', '// b'],+ ['a.rs', 'let s = "line\nnext\n// a";\n', '// a";', '// b";'],+ ['a.rs', 'let s = r#"\nx\n// a\n"#;\n', '// a', '// b'],+ ['a.rs', '/* a /* b */\nx\n// c */ y(1);\n', 'y(1)', 'y(2)'],+ ['a.cpp', 'auto s = R"x(\nfirst\n// a\n)x";\n', '// a', '// b'],+ ['a.cs', 'var s = @"\nfirst\n// a";\n', '// a";', '// b";'],+ ['a.java', 'String s = """\nfirst\n// a\n""";\n', '// a', '// b'],+ ['a.kt', 'val s = """\nfirst\n// a\n"""\n', '// a', '// b'],+ ['a.sh', 'cat > colors.txt <<EOF\n#ff0000\n#00ff00\nEOF\n', '#00ff00', '#0000ff'],+ ['a.sh', "echo 'multi\nline\n# a'\n", "# a'", "# b'"],+ ['a.sh', 'x="\nfirst\n# a"\n', '# a"', '# b"'],+ ['a.ps1', '$s = @"\nfirst\n# a\n"@\n', '# a', '# b'],+ ['a.ps1', "$s = 'multi\nline\n# a'\n", "# a'", "# b'"],+ ['a.ps1', '<# help\nfirst\n# a #> Get-Item a\n', 'Get-Item a', 'Remove-Item a']+ ];+ for (const [file, text, before, after, all] of cases) {+ assert.strictEqual(inFile(file, text, before, after, all), false, `${file}: ${JSON.stringify(text)}`);+ }+});++test('an edit next to a continued line is not trivial', () => {+ const cases = [+ ['a.c', '#define A 1 \\\n// c\nint x;\n', '// c\n', ''],+ ['a.c', '#define A(x) \\\n (x) + \\\n 1\n// c\n', '// c', '// d'],+ ['a.py', 'y = 1 + \\\n 2\n# c\nz()\n', '# c\n', ''],+ ['a.sh', 'make \\\n all\n# c\nrm x\n', '# c\n', ''],+ ['a.ps1', 'Get-Item `\n a\n# c\nRemove-Item b\n', '# c\n', ''],+ ['a.bat', 'echo a ^\nb\nREM c\necho d\n', 'REM c\n', '']+ ];+ for (const [file, text, before, after] of cases) {+ assert.strictEqual(inFile(file, text, before, after), false, `${file}: ${JSON.stringify(text)}`);+ }+});++test('an edit that joins or splits a line across the snippet boundary is not trivial', () => {+ assert.strictEqual(inFile('a.js', 'a();\n// c\nb();\n', '// c\n', '// c '), false, 'next line joins the comment');+ assert.strictEqual(inFile('a.js', 'a(); // x\nb();\n', '\nb();', ' b();'), false, 'line joins the previous comment');+ assert.strictEqual(inFile('a.py', 'x = 1\n# c\nimport os\n', '# c\n', '# c'), false);+ assert.strictEqual(inFile('a.sh', 'echo a\n# c\nrm -rf b\n', '# c\n', '# c '), false);+});++test('comment edits after closed multi-line constructs stay trivial', () => {+ const cases = [+ ['a.js', 'const q = `a\n${b}\nc`;\nconst r = /[/"]+/g;\nconst d = x / 2;\n\n// old\nfoo();\n', '// old', '// new'],+ ['a.js', '#!/usr/bin/env node\nconst s = "a // b";\n\n// old\nfoo();\n', '// old', '// new'],+ ['a.ts', 'function f<T>(x: Array<T>): T {\n return x[0];\n}\n\n// old\nfoo();\n', '// old', '// new'],+ ['a.py', 'def f():\n """Doc with # hash\n and more.\n """\n return f"{x!r}"\n\n# old\nfoo()\n', '# old', '# new'],+ ['a.go', 'var q = `raw\nstring`\n\n// old\nfunc f() {}\n', '// old', '// new'],+ ['a.rs', "fn f<'a>(s: &'a str) -> char {\n let r = r#\"raw \" quote\"#;\n '\"'\n}\n\n// old\nfn g() {}\n", '// old', '// new'],+ ['a.cpp', 'auto s = R"x(\nraw )" still\n)x";\n\n// old\nint y;\n', '// old', '// new'],+ ['a.cs', 'var s = @"a\n""b""";\nvar t = $"{name} is {age:D2}";\n\n// old\nint y;\n', '// old', '// new'],+ ['a.java', 'String s = """\ntext\n""";\n\n// old\nint y;\n', '// old', '// new'],+ ['a.sh', "cat <<'EOF'\n# body\nEOF\necho 'a\nb'\n\n# old\nmake\n", '# old', '# new'],+ ['a.ps1', '$s = @"\nbody # x\n"@\n<# help\n#>\n\n# old\nGet-Item a\n', '# old', '# new'],+ ['a.bat', 'echo a ^\nb\n\nREM old\necho c\n', 'REM old', 'REM new']+ ];+ for (const [file, text, before, after] of cases) {+ assert.strictEqual(inFile(file, text, before, after), true, `${file}: ${JSON.stringify(text)}`);+ }+});++test('file context work stays linear on hostile files', () => {+ const size = 512 * 1024;+ const texts = ['`'.repeat(size), '/*'.repeat(size / 2), '"\\'.repeat(size / 2), '<<a\n'.repeat(size / 4), "r#'".repeat(size / 3), '${'.repeat(size / 2), '\\\n'.repeat(size / 2)];+ for (const [index, text] of texts.entries()) {+ for (const file of ['a.js', 'a.py', 'a.rs', 'a.cpp', 'a.cs', 'a.sh', 'a.ps1', 'a.bat']) {+ const start = process.hrtime.bigint();+ inFile(file, `${text}\n// a\n`, '// a', '// b');+ inFile(file, `${'// a\n'.repeat(1000)}${text}`, '// a', '// b', true);+ const ms = Number(process.hrtime.bigint() - start) / 1e6;+ assert.ok(ms < 500, `text ${index} in ${file} took ${ms.toFixed(1)} ms`);+ }+ }+});+test('comments that mention exports or data do not stop an edit from being trivial', () => {const profile = edit('a.js', '// export JSON later\nfoo();', '// export JSON soon\nfoo();');assert.strictEqual(profile.trivial, true);