Skip to content

armgit / ECC

Public Imported from GitHub
0

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

fix(gateguard): gate MultiEdit by its file_path and widen surface checks

Jeffrey Montoya20eb2395e909
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 738126ea7..672efd7f5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@
### Fixed
- GateGuard keys checked files by canonical path, resolving relative targets against the tool `cwd`, so `a.py`, `./a.py`, and the absolute path (or differently cased and separated Windows spellings) share one first touch. Keys from earlier state files are still honoured.
+- GateGuard gates a MultiEdit call as its `tool_input.file_path` when its entries do not name their own path, which is the tool's own shape; such calls were never gated before, including on sensitive files and from subagents.
## 2.2.2 - 2026-09-15
diff --git a/docs/gateguard/design-notes.md b/docs/gateguard/design-notes.md
index 682d43a3b..4f525b43c 100644
--- a/docs/gateguard/design-notes.md
+++ b/docs/gateguard/design-notes.md
@@ -286,6 +286,16 @@ writers are merged on save (checked keys by union, counts by maximum, gates by
newest `at`). Marking a target checked and recording its event happen in one
state write, so an event is never half-recorded.
+## MultiEdit paths
+
+A MultiEdit call names its file once, in `tool_input.file_path`, and its
+`edits` entries carry only `old_string`, `new_string` and `replace_all`. An
+entry without a `file_path` of its own is gated as the call's `file_path`
+(at top level and in subagents), so the call meets the same first-touch,
+sensitive-target and trivial-edit rules as an Edit of that file. Entries that
+name their own path keep it. Non-object entries are skipped; a non-array
+`edits` is treated as empty.
+
## Change profile
`scripts/lib/gateguard-change-profile.js` reads the change the hook already
@@ -326,8 +336,10 @@ around a public declaration means the edit is inside that symbol.
- Go: `func` (after an optional receiver), `type`, `var` or `const` with a
capitalised name, a `package` line, and any line that starts with a
capital letter (exported fields, interface methods, grouped declarations).
-- Rust: lines starting with `pub` (any `pub(...)`), `impl`, `trait`, or
- `#[macro_export`.
+- Rust: lines starting with `pub` (any `pub(...)`), `impl`, `trait`,
+ `extern`, or an ABI or trait attribute (`#[macro_export`, `#[derive`,
+ `#[repr`, `#[no_mangle`, `#[export_name`, and their `#[unsafe(...)]`
+ forms).
- POSIX shells: a function definition (`name() {`, `function name`), an
`export`, or `declare -x`/`typeset -x`, at any indentation. A sourced
script's functions and exported variables are what other scripts use.
@@ -343,6 +355,31 @@ An Edit that changes a function body without its declaration line in the
snippet reads as not touching the surface; the local question still asks for
the call sites that rely on the behaviour.
+A member line can be public surface even though its container's declaration
+is not in the snippet: a property of an exported interface, a variant of a
+public enum, a name in an export list. So, when the hook passes the file text,
+the nearest line above the first occurrence that starts at column 0 (skipping
+blank lines, comments and decorators; a closing `}`, `]` or `)` there means
+the edit is at top level) is read as the enclosing opener:
+
+- JS/TS: `module.exports`/`exports` assigned an object, array or call, and
+ `export` (or `export default`) of an interface, enum, type, namespace,
+ module, `declare`, `{ ... }` list, or `const`/`let`/`var` that is not a
+ function or arrow: every line inside is surface. An exported class: lines
+ at the class's member indentation (the first non-blank line after the
+ opener) are surface; method bodies are not. An exported `function` or
+ `async function` is a body, as before.
+- Python: `__all__` makes every line surface; a public `class` makes an
+ assignment or annotation of a public name at member indentation (class
+ attributes, dataclass fields) surface.
+- Rust: a `pub` enum, struct, union, trait or `use` makes lines at member
+ indentation surface.
+
+The upward scan stops after 4 MiB in total and then counts as surface. The
+opener is found by indentation, not by parsing, so it can over-match (a method
+body inside an exported object literal counts), which only keeps the importer
+question.
+
## Data handling
`touchesData` looks at every side (both sides of an Edit) as words: identifiers
@@ -350,8 +387,11 @@ are split on non-alphanumerics, `_` and camelCase boundaries and lowercased,
so `validate` and `updated` never match `date`. It is true for a data word
(formats such as `json`, `csv`, `yaml`, `parquet`; serialisation; `schema`;
SQL and database words; date/time words such as `date`, `datetime`,
-`timestamp`, `strftime`, `utc`; file I/O such as `fs`, `fopen`, `pathlib`),
-for `open(`, for adjacent pairs such as `read file`,
+`timestamp`, `strftime`, `utc`, `chrono`, `zoneinfo`; encodings such as
+`base64`, `encoding`, `msgpack`; browser storage and cookies; data-store
+clients such as `redis`, `prisma`, `sqlalchemy`; file I/O such as `fs`,
+`fopen`, `pathlib`), for `open(`, for adjacent pairs such as `read file`,
+`time now`, `time parse`, `system time`,
`write text`, `read to`, and for SQL keyword pairs anywhere in the text
(`select`+`from`, `insert`+`into`, `create`+`table`, ...). Over-matching only
keeps the data question.
@@ -609,7 +649,9 @@ question still comes before the first command that can change something.
rejects.
- Options that execute or write reject: `find -exec*`/`-ok*`/`-delete`/
`-fprint*`/`-fls`, `fd -x`/`-X`/`--exec*` (also inside a short cluster),
- `rg --pre*`/`--hostname-bin`, `tree -o`/`-R` (also inside a short cluster).
+ `rg --pre*`/`--hostname-bin`/`--search-zip`/`-z` (`-z` runs decompressors
+ found on `PATH`, which older ripgrep on Windows also looked up in the
+ working directory), `tree -o`/`-R` (also inside a short cluster).
- `git` takes no global options. The subcommand must be `status`, `log`,
`diff`, `show`, `ls-files`, `rev-parse` or `branch`, and every option must
be in that subcommand's allowlist, so `--output` (and its abbreviations),
@@ -679,6 +721,10 @@ and how often a denial followed a search that nearly counted.
- **Never changes a decision.** Every metrics error (unwritable directory,
a directory in place of the file, a failed rotation) is ignored, and the
gate's result is returned unchanged.
+- **No symlinks.** The file is checked with `lstat` and opened with
+ `O_NOFOLLOW`; a symlink or other non-regular file in its place is left
+ alone and nothing is written, so a shared state directory cannot redirect
+ the append or the rotation onto another file.
- **Bounded.** When an append would take `metrics.jsonl` past 1 MiB it is
renamed to `metrics.jsonl.1`, replacing the previous rotation, so the two
files together stay near 2 MiB. Concurrent hooks may interleave lines or
diff --git a/manifests/context-packs/[email protected] b/manifests/context-packs/[email protected]
index a7f77f398..f5e93a3c5 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":"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"}
+{"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":"aeceb8c5bc18354a1ebb30aff8d03800b188765f445d1ebe06969c4d2ff0da34","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.js
index 93c83dfda..510301cb0 100644
--- a/scripts/hooks/gateguard-fact-force.js
+++ b/scripts/hooks/gateguard-fact-force.js
@@ -2151,6 +2151,13 @@ function changeProfileFor(toolName, filePath, edits, content, data) {
return profileChange({ filePath, tool, edits, content, fileText });
}
+// see docs/gateguard/design-notes.md#multiedit-paths
+function multiEditEntries(toolInput) {
+ const edits = Array.isArray(toolInput.edits) ? toolInput.edits : [];
+ const shared = typeof toolInput.file_path === 'string' ? toolInput.file_path : '';
+ return edits.map(edit => (edit && typeof edit === 'object' && !edit.file_path && shared ? { ...edit, file_path: shared } : edit));
+}
+
function entriesFor(edits, fileKey, data) {
return edits.filter(edit => edit && typeof edit.file_path === 'string' && canonicalPathKey(edit.file_path, data) === fileKey);
}
@@ -2321,7 +2328,7 @@ function gate(rawInput) {
}
if (toolName === 'MultiEdit') {
- const edits = toolInput.edits || [];
+ const edits = multiEditEntries(toolInput);
if (inSubagent) {
for (const edit of edits) {
const filePath = (edit && edit.file_path) || '';
@@ -2336,7 +2343,7 @@ function gate(rawInput) {
const notes = [];
const trivialKeys = new Set();
for (const edit of edits) {
- const filePath = edit.file_path || '';
+ const filePath = (edit && edit.file_path) || '';
const exempt = exemptReason(filePath, data);
if (exempt) {
recordDecision('pass-exempt', exempt, { target: filePath, key: `exempt:${filePath}` });
diff --git a/scripts/lib/gateguard-change-profile.js b/scripts/lib/gateguard-change-profile.js
index 711f0d5ee..716088c03 100644
--- a/scripts/lib/gateguard-change-profile.js
+++ b/scripts/lib/gateguard-change-profile.js
@@ -1326,9 +1326,12 @@ function goLineIsSurface(line) {
return isUpper(t[at]);
}
+const RUST_SURFACE_ATTRIBUTES = ['#[macro_export', '#[derive', '#[repr', '#[no_mangle', '#[unsafe(no_mangle', '#[export_name', '#[unsafe(export_name'];
+
function rustLineIsSurface(line) {
const t = line.slice(skipSpaces(line, 0));
- return leadingWord(t, 'pub') || leadingWord(t, 'impl') || leadingWord(t, 'trait') || t.startsWith('#[macro_export');
+ return leadingWord(t, 'pub') || leadingWord(t, 'impl') || leadingWord(t, 'trait') || leadingWord(t, 'extern') ||
+ RUST_SURFACE_ATTRIBUTES.some(attribute => t.startsWith(attribute));
}
function shellFunctionName(t) {
@@ -1388,6 +1391,114 @@ function textTouchesSurface(text, lineIsSurface) {
return false;
}
+// --- Container members ---
+// see docs/gateguard/design-notes.md#public-surface
+
+const MAX_OPENER_SCAN = 4 * 1024 * 1024;
+const JS_BODY_KINDS = ['function', 'async'];
+const JS_MEMBER_KINDS = ['class', 'abstract'];
+const JS_CONTAINER_KINDS = ['interface', 'enum', 'type', 'namespace', 'module', 'const', 'let', 'var', 'declare', '{'];
+const RUST_CONTAINER_KINDS = ['enum', 'struct', 'union', 'trait', 'use'];
+
+function indentOf(line) {
+ return line.slice(0, skipSpaces(line, 0));
+}
+
+function lineAt(text, start) {
+ const end = lineEndAt(text, start);
+ return { text: text.slice(start, end), next: end + (text[end] === '\r' && text[end + 1] === '\n' ? 2 : 1) };
+}
+
+function isCommentLine(t) {
+ return t.startsWith('//') || t.startsWith('/*') || t.startsWith('*') || t.startsWith('#') || t.startsWith('@');
+}
+
+function enclosingOpener(text, at, budget) {
+ let end = lineStartOf(text, at);
+ while (end > 0) {
+ let last = end - 1;
+ if (text[last] === '\n' && text[last - 1] === '\r') last--;
+ const start = lineStartOf(text, last);
+ budget.left -= end - start;
+ if (budget.left < 0) return null;
+ const line = text.slice(start, last);
+ end = start;
+ if (!line.trim() || isSpace(line[0])) continue;
+ if ('}])'.includes(line[0])) return null;
+ if (isCommentLine(line)) continue;
+ return { line, start };
+ }
+ return null;
+}
+
+function jsContainerKind(opener) {
+ const t = opener.trimEnd();
+ const bodyLike = t.includes('=>') || containsWord(t, 'function');
+ if (containsWord(t, 'exports')) return !bodyLike && /[{[(]$/.test(t) ? 'all' : null;
+ if (!leadingWord(t, 'export')) return null;
+ let rest = t.slice(skipSpaces(t, 6));
+ if (leadingWord(rest, 'default')) rest = rest.slice(skipSpaces(rest, 7));
+ if (JS_BODY_KINDS.some(word => leadingWord(rest, word))) return null;
+ if (JS_MEMBER_KINDS.some(word => leadingWord(rest, word))) return 'members';
+ if (rest.startsWith('{')) return 'all';
+ if (!JS_CONTAINER_KINDS.some(word => leadingWord(rest, word))) return null;
+ return bodyLike ? null : 'all';
+}
+
+function containerKind(opener, language) {
+ if (language === 'js') return jsContainerKind(opener);
+ if (language === 'python') {
+ if (opener.includes('__all__')) return 'all';
+ return leadingWord(opener, 'class') && pythonNameIsPublic(identifierAt(opener, skipSpaces(opener, 5))) ? 'fields' : null;
+ }
+ if (language === 'rust' && leadingWord(opener, 'pub')) {
+ const words = opener.split(/[^A-Za-z0-9_]+/);
+ return RUST_CONTAINER_KINDS.some(word => words.includes(word)) ? 'members' : null;
+ }
+ return null;
+}
+
+function memberIndent(text, opener) {
+ let at = lineAt(text, opener.start).next;
+ while (at < text.length) {
+ const line = lineAt(text, at);
+ if (line.text.trim()) return indentOf(line.text);
+ at = line.next;
+ }
+ return null;
+}
+
+function isMemberLine(line, indent, kind) {
+ if (!indent || indentOf(line) !== indent) return false;
+ const t = line.slice(indent.length);
+ if (!t || '}])'.includes(t[0]) || isCommentLine(t)) return false;
+ if (kind !== 'fields') return true;
+ const name = identifierAt(t, 0);
+ const after = t[skipSpaces(t, name.length)];
+ return pythonNameIsPublic(name) && isLetter(name[0]) && (after === ':' || (after === '=' && t[skipSpaces(t, name.length) + 1] !== '='));
+}
+
+function containerTouchesSurface(pairs, fileText, language) {
+ if (typeof fileText !== 'string' || fileText.length > MAX_FILE_CHARS) return false;
+ const budget = { left: MAX_OPENER_SCAN };
+ for (const [oldString, newString] of pairs) {
+ const at = oldString ? fileText.indexOf(oldString) : -1;
+ if (at === -1) continue;
+ const opener = enclosingOpener(fileText, at, budget);
+ if (budget.left < 0) return true;
+ const kind = opener ? containerKind(opener.line, language) : null;
+ if (!kind) continue;
+ if (kind === 'all') return true;
+ const indent = memberIndent(fileText, opener);
+ const start = lineStartOf(fileText, at);
+ const end = lineEndAt(fileText, at + oldString.length);
+ const before = fileText.slice(start, end);
+ const after = `${fileText.slice(start, at)}${newString}${fileText.slice(at + oldString.length, end)}`;
+ if (`${before}\n${after}`.split(/\r\n|\r|\n/).some(line => isMemberLine(line, indent, kind))) return true;
+ }
+ return false;
+}
+
// --- Data handling ---
const DATA_WORDS = new Set([
@@ -1398,12 +1509,17 @@ const DATA_WORDS = new Set([
'date', 'dates', 'datetime', 'timestamp', 'timestamps', 'strftime', 'strptime', 'isoformat', 'iso', 'iso8601', 'timezone',
'tz', 'utc', 'epoch', 'dayjs', 'moment', 'luxon', 'instant',
'fs', 'fopen', 'fread', 'fwrite', 'fgets', 'ioutil', 'bufio', 'pathlib', 'shutil', 'readfile', 'writefile', 'fstream',
- 'ifstream', 'ofstream'
+ 'ifstream', 'ofstream',
+ 'chrono', 'zoneinfo', 'pytz', 'tzinfo', 'temporal', 'base64', 'encoding', 'charset', 'codec', 'msgpack', 'bson', 'cbor',
+ 'xlsx', 'storage', 'cookie', 'cookies', 'redis', 'prisma', 'knex', 'sequelize', 'mongoose', 'typeorm', 'drizzle',
+ 'sqlalchemy', 'jdbc', 'firestore', 'dynamodb'
]);
const DATA_PAIRS = [
['read', 'file'], ['write', 'file'], ['append', 'file'], ['open', 'file'], ['read', 'text'], ['write', 'text'],
['read', 'bytes'], ['write', 'bytes'], ['read', 'to'], ['read', 'lines'], ['write', 'lines'], ['read', 'all'],
- ['file', 'reader'], ['file', 'writer'], ['file', 'stream'], ['read', 'csv'], ['to', 'csv']
+ ['file', 'reader'], ['file', 'writer'], ['file', 'stream'], ['read', 'csv'], ['to', 'csv'],
+ ['time', 'now'], ['time', 'parse'], ['time', 'unix'], ['time', 'since'], ['time', 'format'], ['time', 'time'],
+ ['time', 'duration'], ['time', 'zone'], ['time', 'stamp'], ['system', 'time']
];
const SQL_PAIRS = [['select', 'from'], ['insert', 'into'], ['delete', 'from'], ['create', 'table'], ['alter', 'table'], ['drop', 'table'], ['update', 'set']];
@@ -1524,7 +1640,7 @@ function profileChange(input) {
if (!texts || !withinBounds(texts.sides)) return UNKNOWN_PROFILE;
const lineIsSurface = SURFACE_BY_LANGUAGE[language];
const touchesPublicSurface = input.tool === 'Write' || !lineIsSurface || wholeFileIsSurface(input.filePath, language) ||
- texts.sides.some(side => textTouchesSurface(side, lineIsSurface));
+ texts.sides.some(side => textTouchesSurface(side, lineIsSurface)) || containerTouchesSurface(texts.pairs, input.fileText, language);
const touchesData = texts.sides.some(side => textTouchesData(side, language));
const trivial = input.tool === 'Edit' && trivialInFile(texts.pairs, input.fileText, lexSpecFor(input.filePath, language));
return Object.freeze({ known: true, language, touchesPublicSurface, touchesData, trivial });
diff --git a/scripts/lib/gateguard-metrics.js b/scripts/lib/gateguard-metrics.js
index c8ac0651f..61e0182a6 100644
--- a/scripts/lib/gateguard-metrics.js
+++ b/scripts/lib/gateguard-metrics.js
@@ -11,6 +11,7 @@ const SESSION_DIGEST_LENGTH = 12;
const CODE_MAX_LENGTH = 48;
const CODE_PATTERN = /^[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*)?$/;
const SESSION_PATTERN = /^[0-9a-f]{12}$/;
+const APPEND_FLAGS = fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | (fs.constants.O_NOFOLLOW || 0);
const DECISIONS = Object.freeze([
'deny',
@@ -83,6 +84,7 @@ function isMetricsEvent(value) {
/** Append events to `<dir>/metrics.jsonl` in one write, rotating to `.1` past the size cap; never throws. */
function appendMetrics(dir, events) {
+ let fd = null;
try {
const lines = events
.filter(Boolean)
@@ -93,18 +95,29 @@ function appendMetrics(dir, events) {
fs.mkdirSync(dir, { recursive: true });
let size = 0;
try {
- const stat = fs.statSync(file);
- size = stat.isFile() ? stat.size : 0;
+ const stat = fs.lstatSync(file);
+ if (!stat.isFile()) return false;
+ size = stat.size;
} catch (_) {
size = 0;
}
if (size > 0 && size + Buffer.byteLength(lines) > METRICS_MAX_BYTES) {
fs.renameSync(file, `${file}.1`);
}
- fs.appendFileSync(file, lines, { encoding: 'utf8', mode: 0o600 });
+ fd = fs.openSync(file, APPEND_FLAGS, 0o600);
+ if (!fs.fstatSync(fd).isFile()) return false;
+ fs.writeSync(fd, lines);
return true;
} catch (_) {
return false;
+ } finally {
+ if (fd !== null) {
+ try {
+ fs.closeSync(fd);
+ } catch (_) {
+ /* ignore */
+ }
+ }
}
}
diff --git a/scripts/lib/gateguard-readonly-shell.js b/scripts/lib/gateguard-readonly-shell.js
index b667f1f2c..ac9ed51a7 100644
--- a/scripts/lib/gateguard-readonly-shell.js
+++ b/scripts/lib/gateguard-readonly-shell.js
@@ -57,7 +57,7 @@ const noArg = pattern => args => !args.some(arg => pattern.test(arg));
const FIND_ACTIONS = /^-(exec|ok|delete|fprint|fls)/;
const FD_EXEC = /^(--exec|-[^-]*[xX])/;
-const RG_EXEC = /^--(pre|hostname-bin)/;
+const RG_EXEC = /^(--(pre|hostname-bin|search-zip)|-[^-]*z)/;
const TREE_WRITE = /^(-[^-]*[oR]|--o)/;
const BASH_COMMANDS = new Map([
diff --git a/skills/gateguard/SKILL.md b/skills/gateguard/SKILL.md
index 6952ff3bb..8e56950cd 100644
--- a/skills/gateguard/SKILL.md
+++ b/skills/gateguard/SKILL.md
@@ -48,7 +48,8 @@ Both agents produce code that runs and passes tests. The difference is design de
### Edit / MultiEdit Gate (first edit per file)
-MultiEdit is handled identically — each file in the batch is gated individually.
+MultiEdit is handled identically — each file in the batch is gated individually;
+entries without their own `file_path` are gated as the call's `file_path`.
The questions depend on the target's class (see
[Questions by target class](#questions-by-target-class)). For **code**
@@ -97,14 +98,20 @@ For **code** targets the gate reads the change it is about to allow (Edit
`def`/`class` not starting with `_`, dunders, `__all__`, a module-level public
assignment such as `BASE_URL = ...` (`__init__.py` always); Go: capitalised
`func`/`type`/`var`/`const` names, `package`, lines starting with a capital;
- Rust: `pub`, `impl`, `trait`, `#[macro_export]`; shell: function definitions,
+ Rust: `pub`, `impl`, `trait`, `extern`, `#[macro_export]`, `#[derive]`,
+ `#[repr]`, `#[no_mangle]`; shell: function definitions,
`export`, `declare -x`; PowerShell: `function`, `filter`, `param`,
- `Export-ModuleMember`, `[CmdletBinding`. Java, Kotlin, C#, C, C++ and batch
+ `Export-ModuleMember`, `[CmdletBinding`. A member of an exported container
+ counts too, judged from the file: lines inside an exported interface, enum,
+ type, object or export list, member declarations of an exported class,
+ `__all__` entries, public class attributes and dataclass fields, and members
+ of a `pub` enum, struct, trait or `use` list. Java, Kotlin, C#, C, C++ and batch
files, 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; in shell scripts also
+ serialisation, encodings, schemas, SQL, data stores, browser storage, dates
+ and clock reads on either side; in shell scripts also
redirection to a file, `curl`, `wget`, `jq` and PowerShell file and web
cmdlets. Without them the data
question is dropped.
@@ -199,7 +206,7 @@ their aliases, `rg`, `git`) passes and is counted in
`routine_readonly_passes`. The first other command is still gated. Any
redirection, `tee`, substitution, backtick, variable, environment
assignment, wrapper (`env`, `sudo`, `xargs`, `sh -c`), unknown command,
-`find -exec`/`-delete`, `fd -x`, `rg --pre`, `tree -o`, `git` global option or
+`find -exec`/`-delete`, `fd -x`, `rg --pre`/`-z`, `tree -o`, `git` global option or
write/execute option, or PowerShell `$`, `@`, `(`, `{` or `--%` makes the
command ordinary. Destructive detection runs first, unchanged.
diff --git a/tests/hooks/gateguard-fact-force.test.js b/tests/hooks/gateguard-fact-force.test.js
index 8e61f73b7..68e145af5 100644
--- a/tests/hooks/gateguard-fact-force.test.js
+++ b/tests/hooks/gateguard-fact-force.test.js
@@ -4616,6 +4616,7 @@ function runTests() {
const entries = Array.isArray(tool_input.edits) ? tool_input.edits : [tool_input];
const byFile = new Map();
for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
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]);
@@ -4852,6 +4853,33 @@ function runTests() {
passed++;
else failed++;
+ clearState();
+ if (
+ test('MultiEdit entries without their own path are gated as the call file_path', () => {
+ const sensitive = b3Run('MultiEdit', { file_path: '.env', edits: [{ old_string: 'A=1', new_string: 'A=2' }] });
+ assert.strictEqual(sensitive.decision, 'deny', sensitive.result.stdout);
+ assert.ok(sensitive.reason.includes('.env'), sensitive.reason);
+ clearState();
+ const code = b3Run('MultiEdit', { file_path: 'src/mt1.js', edits: [{ old_string: 'f(1);', new_string: 'f(2);' }] });
+ assert.strictEqual(code.decision, 'deny', code.result.stdout);
+ assert.ok(code.reason.includes('src/mt1.js'), code.reason);
+ clearState();
+ const trivial = b3Run('MultiEdit', { file_path: 'src/mt2.js', edits: [{ old_string: 'f(); // a', new_string: 'f(); // b' }] });
+ assert.ok(trivial.context.includes(`${B3_NOTE} src/mt2.js`), trivial.result.stdout);
+ clearState();
+ const input = { file_path: 'config/.env.local', edits: [{ old_string: 'A=1', new_string: 'A=2' }] };
+ b3Seed(input);
+ const result = runHook({ tool_name: 'MultiEdit', tool_input: input, agent_id: 'sub-1' }, { CLAUDE_PROJECT_DIR: b3Root });
+ const hso = (parseOutput(result.stdout) || {}).hookSpecificOutput || {};
+ assert.strictEqual(hso.permissionDecision, 'deny', `subagent: ${result.stdout}`);
+ clearState();
+ const odd = b3Run('MultiEdit', { file_path: 'src/mt3.js', edits: [null, 7, { old_string: 'g(1);', new_string: 'g(2);' }] });
+ assert.strictEqual(odd.decision, 'deny', `malformed entries: ${odd.result.stdout}`);
+ })
+ )
+ passed++;
+ else failed++;
+
clearState();
if (
test('the trivial pass comes before the denial cap and never consumes it', () => {
diff --git a/tests/lib/gateguard-change-profile.test.js b/tests/lib/gateguard-change-profile.test.js
index 2e08720d7..dc19cbf08 100644
--- a/tests/lib/gateguard-change-profile.test.js
+++ b/tests/lib/gateguard-change-profile.test.js
@@ -156,6 +156,52 @@ test('Rust: pub items, impl/trait blocks and macro exports touch the surface', (
assert.strictEqual(surface('a.rs', 'let publish = 1;', 'let publish = 2;'), false);
});
+test('Rust: derive, repr, no_mangle and extern items touch the surface', () => {
+ assert.strictEqual(surface('a.rs', '#[derive(Clone)]', '#[derive(Clone, Copy)]'), true);
+ assert.strictEqual(surface('a.rs', '#[repr(C)]', '#[repr(packed)]'), true);
+ assert.strictEqual(surface('a.rs', '#[no_mangle]', '#[export_name = "f"]'), true);
+ assert.strictEqual(surface('a.rs', 'extern "C" fn f() {}', 'extern "C" fn f(x: i32) {}'), true);
+ assert.strictEqual(surface('a.rs', '#[inline]', '#[inline(always)]'), false);
+});
+
+test('members of exported containers touch the surface when the file shows the container', () => {
+ const inside = (filePath, fileText, oldString, newString) =>
+ profileChange({ filePath, tool: 'Edit', edits: [{ old_string: oldString, new_string: newString }], fileText }).touchesPublicSurface;
+ const hits = [
+ ['a.js', 'module.exports = {\n parse,\n format,\n};\n', ' format,\n', ''],
+ ['a.js', 'exports.defaults = {\n retries: 3,\n};\n', ' retries: 3,', ' retries: 5,'],
+ ['a.ts', 'export interface Options {\n timeout: number;\n}\n', ' timeout: number;', ' timeout?: number;'],
+ ['a.ts', 'export enum Color {\n Red,\n Green,\n}\n', ' Green,\n', ''],
+ ['a.ts', 'export type Mode =\n | "a"\n | "b";\n', ' | "b";', ' | "c";'],
+ ['a.ts', 'export declare namespace N {\n const x: number;\n}\n', ' const x: number;', ' const x: string;'],
+ ['a.js', 'export const defaults = {\n retries: 3,\n};\n', ' retries: 3,', ' retries: 5,'],
+ ['a.js', 'export {\n parse,\n format,\n};\n', ' format,\n', ''],
+ ['a.ts', 'export class Client {\n constructor(private url: string) {}\n\n get(path: string) {\n return 1;\n }\n}\n', ' get(path: string) {', ' get(path: string, opts?: object) {'],
+ ['a.ts', 'export default class Client {\n static retries = 3;\n}\n', ' static retries = 3;', ' static retries = 5;'],
+ ['a.py', '__all__ = [\n "a",\n "b",\n]\n', ' "b",\n', ''],
+ ['a.py', '@dataclass\nclass Options:\n timeout: int = 5\n', ' timeout: int = 5', ' timeout: float = 5.0'],
+ ['a.py', 'class Options:\n """Doc."""\n retries = 3\n', ' retries = 3', ' retries = 5'],
+ ['a.rs', 'pub enum E {\n A,\n B,\n}\n', ' B,\n', ''],
+ ['a.rs', 'pub struct S {\n a: u8,\n}\n', ' a: u8,', ' a: u16,'],
+ ['a.rs', 'pub trait T {\n fn f(&self);\n}\n', ' fn f(&self);', ' fn f(&self, x: u8);'],
+ ['a.rs', 'pub use crate::{\n a,\n b,\n};\n', ' b,\n', '']
+ ];
+ for (const [file, text, before, after] of hits) assert.strictEqual(inside(file, text, before, after), true, `${file}: ${JSON.stringify(before)}`);
+ const misses = [
+ ['a.js', 'export function f() {\n return 1;\n}\n', ' return 1;', ' return 2;'],
+ ['a.js', 'export const handler = async (req) => {\n return 1;\n};\n', ' return 1;', ' return 2;'],
+ ['a.js', 'module.exports = function (x) {\n return x;\n};\n', ' return x;', ' return x + 1;'],
+ ['a.ts', 'export class Client {\n get(path: string) {\n return 1;\n }\n}\n', ' return 1;', ' return 2;'],
+ ['a.js', 'function local() {\n return 1;\n}\nmodule.exports = { local };\n', ' return 1;', ' return 2;'],
+ ['a.py', 'class Options:\n def run(self):\n x = 1\n', ' x = 1', ' x = 2'],
+ ['a.py', 'class _Private:\n x = 1\n', ' x = 1', ' x = 2'],
+ ['a.py', 'def f():\n x = 1\n', ' x = 1', ' x = 2'],
+ ['a.rs', 'pub struct S {\n a: u8,\n}\n\nfn f() {\n x();\n}\n', ' x();', ' y();'],
+ ['a.rs', 'impl S {\n fn helper(&self) {\n x();\n }\n}\n', ' x();', ' y();']
+ ];
+ for (const [file, text, before, after] of misses) assert.strictEqual(inside(file, text, before, after), false, `${file}: ${JSON.stringify(before)}`);
+});
+
test('Java, Kotlin, C#, C and C++ always count as touching the surface', () => {
for (const file of ['a.java', 'a.kt', 'a.cs', 'a.c', 'a.cpp']) {
const profile = edit(file, 'x = 1;', 'x = 2;');
@@ -344,6 +390,27 @@ test('file I/O, serialisation, SQL, schema and date handling touch data', () =>
}
});
+test('clock reads, encodings, browser storage and data stores touch data', () => {
+ const hits = [
+ ['a.go', 't := time.Now()'],
+ ['a.go', 'd, err := time.ParseDuration(s)'],
+ ['a.py', 'started = time.time()'],
+ ['a.rs', 'let now = SystemTime::now();'],
+ ['a.rs', 'let t = chrono::Local::now();'],
+ ['a.py', 'zone = ZoneInfo("UTC")'],
+ ['a.js', 'const raw = Buffer.from(s, "base64");'],
+ ['a.js', 'localStorage.setItem("k", v);'],
+ ['a.js', 'document.cookie = v;'],
+ ['a.py', 'packed = msgpack.packb(v)'],
+ ['a.js', 'await prisma.user.findMany();'],
+ ['a.py', 'engine = sqlalchemy.create_engine(url)'],
+ ['a.js', 'const text = new TextDecoder(encoding).decode(bytes);']
+ ];
+ for (const [file, text] of hits) assert.strictEqual(data(file, 'x = 1', text), true, `${file}: ${text}`);
+ const misses = [['a.js', 'setTimeout(run, 10);'], ['a.go', 'ctx, cancel := context.WithTimeout(ctx, d)'], ['a.py', 'runtime = compute()']];
+ for (const [file, text] of misses) assert.strictEqual(data(file, 'x = 1', text), false, `${file}: ${text}`);
+});
+
test('ordinary logic and look-alike words do not touch data', () => {
const misses = [
['a.js', 'return a + b;'],
diff --git a/tests/lib/gateguard-metrics.test.js b/tests/lib/gateguard-metrics.test.js
index 12b204067..4f30007d4 100644
--- a/tests/lib/gateguard-metrics.test.js
+++ b/tests/lib/gateguard-metrics.test.js
@@ -149,5 +149,22 @@ test('reports failure instead of throwing when the file cannot be written', () =
}
});
+test('never writes through a symlink in place of the metrics file', () => {
+ if (process.platform === 'win32') return;
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gateguard-metrics-lib-'));
+ try {
+ const victim = path.join(dir, 'victim.txt');
+ fs.writeFileSync(victim, 'keep\n');
+ fs.symlinkSync(victim, path.join(dir, METRICS_FILE_NAME));
+ assert.strictEqual(appendMetrics(dir, [metricsEvent(base)]), false);
+ assert.strictEqual(fs.readFileSync(victim, 'utf8'), 'keep\n');
+ fs.writeFileSync(victim, 'x'.repeat(METRICS_MAX_BYTES));
+ assert.strictEqual(appendMetrics(dir, [metricsEvent(base)]), false);
+ assert.strictEqual(fs.statSync(victim).size, METRICS_MAX_BYTES, 'a symlink is not rotated onto');
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
console.log(`\n ${passed} passed, ${failed} failed\n`);
process.exit(failed > 0 ? 1 : 0);
diff --git a/tests/lib/gateguard-readonly-shell.test.js b/tests/lib/gateguard-readonly-shell.test.js
index dee17f78b..5ff77a26c 100644
--- a/tests/lib/gateguard-readonly-shell.test.js
+++ b/tests/lib/gateguard-readonly-shell.test.js
@@ -143,6 +143,9 @@ test('fd, rg and tree options that execute or write are not read-only', () => {
'rg --pre ./script foo',
'rg --pre=cat foo',
'rg --hostname-bin=./x foo',
+ 'rg -z foo',
+ 'rg -iz foo',
+ 'rg --search-zip foo',
'tree -o out.txt',
'tree -ao out.txt',
'tree -R'