The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
feat(gateguard): add change profile for first-touch edits
Jeffrey Montoyaa7fd960b202c
diff --git a/docs/gateguard/design-notes.md b/docs/gateguard/design-notes.mdindex 025ded3ee..7805b2909 100644--- a/docs/gateguard/design-notes.md+++ b/docs/gateguard/design-notes.md@@ -27,6 +27,9 @@ headings stable, since they are the anchors.- `scripts/lib/gateguard-state.js`: pure helpers for the session-state fields(counters, per-class counts, sibling dir gates). Reading and writing thestate file, and the one-write event helpers built on it, stay in the hook.+- `scripts/lib/gateguard-change-profile.js`: pure analysis of the change text+ of an Edit/Write/MultiEdit into a bounded change profile (see+ [Change profile](#change-profile)).## Fail to deny@@ -254,3 +257,90 @@ old-shape entries are dropped. `dir_gates` maps `<class>\u0000<canonicalDir>` towriters are merged on save (checked keys by union, counts by maximum, gates bynewest `at`). Marking a target checked and recording its event happen in onestate write, so an event is never half-recorded.++## Change profile++`scripts/lib/gateguard-change-profile.js` reads the change the hook already+receives (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.++The profile only ever removes questions, so anything uncertain yields the+unknown profile (every question asked, never trivial): an unsupported+extension, a non-string side, no entries or more than 64, a side over 64 KiB+(UTF-8), more than 256 KiB in total, or any exception. Supported languages, by+extension: JS/TS (`.js .mjs .cjs .jsx .ts .tsx .mts .cts`), Python+(`.py .pyi`), Go, Rust, Java, Kotlin (`.kt .kts`), C# and C/C++ (`.c .h .cc+.cpp .cxx .hpp .hh .hxx`). Shell, Ruby, Makefiles, Swift and everything else+are unknown.++## Public surface++A Write always touches the public surface (a new or rewritten module's+surface is all new). For an Edit, any line on either side that declares or+exposes a public name counts, whether it changed or is only context: context+around a public declaration means the edit is inside that symbol.++- JS/TS: a line starting with the word `export`, `public` or `declare`, or+ containing the word `exports` (`module.exports`, `exports.x`). `.d.ts`,+ `.d.mts` and `.d.cts` files are all surface.+- Python: `def`, `async def` or `class` whose name does not start with `_`+ (dunders such as `__init__` are public), any `__all__`, and a column-0+ assignment or annotation of a public name on a line after the first (the+ first line of a snippet may start mid-line). `__init__.py` is all surface.+- 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`.+- Java, Kotlin, C#, C and C++ always touch the surface: package-private Java,+ Kotlin's public default, C# partial classes and C linkage make a lexical+ answer unreliable.++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.++## Data handling++`touchesData` looks at every side (both sides of an Edit) as words: identifiers+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`,+`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.++## Trivial edits++An Edit is trivial when, for every entry, old and new have the same code once+comments are removed, blank and comment-only lines are dropped, and runs of+whitespace between tokens are folded to one space. Line structure, whitespace+inside strings, and the presence of whitespace between tokens stay code+(`a+b` to `a + b` is not trivial). For Python, leading whitespace of each code+line is code; comment-only lines carry no indentation.++Comments are `//` and non-nesting `/* */` in the C family and `#` in Python;+C preprocessor lines are code. Strings are single-line `"..."` and `'...'`+(Rust: `"..."` only, with `'x'` char literals told apart from lifetimes).+Anything the lexer cannot read with confidence makes the entry non-trivial:++- any multi-line string form: JS/Go backticks, Python/Java/Kotlin/C# triple+ quotes, Rust raw strings (`r"`, `r#"`), C++ raw strings (`R"`), C# verbatim+ and interpolated strings (`@"`, `$"`), Kotlin strings containing `$`, Python+ f-strings, and any string that runs to the end of a line;+- in JS/TS, any `/` outside a comment (division and regex literals cannot be+ told apart), JSX-like `<x`, `</`, `<>`, `<!`, and `-->`;+- a line comment ending in `\` (it continues onto the next line in C and+ Make), the trigraph `??/`, whitespace after a line-continuation `\`, a `/*`+ inside a block comment, and an unterminated block comment or string.++Write is never trivial. 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.diff --git a/scripts/lib/gateguard-change-profile.js b/scripts/lib/gateguard-change-profile.jsnew file mode 100644index 000000000..6396d13ae--- /dev/null+++ b/scripts/lib/gateguard-change-profile.js@@ -0,0 +1,450 @@+'use strict';++// see docs/gateguard/design-notes.md#change-profile++const MAX_SIDE_BYTES = 64 * 1024;+const MAX_TOTAL_BYTES = 256 * 1024;+const MAX_EDITS = 64;++const UNKNOWN_PROFILE = Object.freeze({ known: false, language: null, touchesPublicSurface: true, touchesData: true, trivial: false });++const LANGUAGE_BY_EXT = new Map([+ ['.js', 'js'], ['.mjs', 'js'], ['.cjs', 'js'], ['.jsx', 'js'], ['.ts', 'js'], ['.tsx', 'js'], ['.mts', 'js'], ['.cts', 'js'],+ ['.py', 'python'], ['.pyi', 'python'],+ ['.go', 'go'],+ ['.rs', 'rust'],+ ['.java', 'java'],+ ['.kt', 'kotlin'], ['.kts', 'kotlin'],+ ['.cs', 'csharp'],+ ['.c', 'c'], ['.h', 'c'],+ ['.cc', 'cpp'], ['.cpp', 'cpp'], ['.cxx', 'cpp'], ['.hpp', 'cpp'], ['.hh', 'cpp'], ['.hxx', 'cpp']+]);++// --- Lexing ---+// see docs/gateguard/design-notes.md#trivial-edits++const C_FAMILY = { lineComment: '//', blockComment: true, quotes: '"\'', indentSensitive: false };++const LEX_SPECS = {+ js: { ...C_FAMILY, forbiddenCode: '`/', jsx: true },+ go: { ...C_FAMILY, forbiddenCode: '`' },+ rust: { ...C_FAMILY, quotes: '"', rustChars: true, rawPrefixes: 'r#' },+ 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 }+};++function isSpace(ch) {+ return ch === ' ' || ch === '\t' || ch === '\f' || ch === '\v';+}++function isIdentChar(ch) {+ return ch !== undefined && ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch === '_' || ch === '$');+}++function isLetter(ch) {+ return ch !== undefined && ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'));+}++function rustCharEnd(text, i) {+ if (text[i + 1] === '\\') {+ if (text[i + 2] === "'") return text[i + 3] === "'" ? i + 3 : -1;+ const end = text.indexOf("'", i + 3);+ return end !== -1 && end <= i + 12 ? end : -1;+ }+ const cp = text.codePointAt(i + 1);+ if (cp === undefined || text[i + 1] === '\n' || text[i + 1] === '\r' || text[i + 1] === "'") return -1;+ const end = i + (cp > 0xffff ? 3 : 2);+ return text[end] === "'" ? end : -1;+}++function stringPrefixIsUnsafe(code, spec) {+ const last = code[code.length - 1];+ if (spec.rawPrefixes && last !== undefined && spec.rawPrefixes.includes(last)) return true;+ if (!spec.fStrings || !isLetter(last)) return false;+ const prefix = isLetter(code[code.length - 2]) ? code.slice(-2) : last;+ return prefix.toLowerCase().includes('f');+}++function lexCodeLines(text, spec) {+ const lines = [];+ let code = '';+ let state = 'code';+ let quote = '';+ let stringBody = '';+ let commentTail = '';+ const endLine = () => {+ lines.push(code);+ code = '';+ };+ for (let i = 0; i < text.length; i++) {+ const ch = text[i];+ if (ch === '\n' || ch === '\r') {+ if (state === 'string') return null;+ if (state === 'line') {+ if (commentTail.endsWith('\\')) return null;+ state = 'code';+ }+ endLine();+ if (ch === '\r' && text[i + 1] === '\n') i++;+ continue;+ }+ if (state === 'line') {+ if (!isSpace(ch)) commentTail = commentTail.length > 8 ? commentTail.slice(-4) + ch : commentTail + ch;+ continue;+ }+ if (state === 'block') {+ if (ch === '*' && text[i + 1] === '/') {+ state = 'code';+ code += ' ';+ i++;+ } else if (ch === '/' && text[i + 1] === '*') {+ return null;+ }+ continue;+ }+ if (state === 'string') {+ code += ch;+ if (ch === '\\') {+ const next = text[i + 1];+ if (next === undefined || next === '\n' || next === '\r') return null;+ code += next;+ i++;+ } else if (ch === quote) {+ if (spec.noDollarInStrings && stringBody.includes('$')) return null;+ state = 'code';+ } else {+ stringBody += ch;+ }+ continue;+ }+ if (spec.lineComment === '//' && ch === '/' && text[i + 1] === '/') {+ state = 'line';+ commentTail = '';+ i++;+ continue;+ }+ if (spec.lineComment === '#' && ch === '#') {+ state = 'line';+ commentTail = '';+ continue;+ }+ if (spec.blockComment && ch === '/' && text[i + 1] === '*') {+ state = 'block';+ i++;+ continue;+ }+ if (spec.forbiddenCode && spec.forbiddenCode.includes(ch)) return null;+ if (spec.jsx && ch === '<' && (isLetter(text[i + 1]) || text[i + 1] === '/' || text[i + 1] === '>' || text[i + 1] === '!')) return null;+ if (spec.jsx && 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);+ 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;+ state = 'string';+ quote = ch;+ stringBody = '';+ code += ch;+ continue;+ }+ code += ch;+ }+ if (state === 'string' || state === 'block') return null;+ if (state === 'line' && commentTail.endsWith('\\')) return null;+ endLine();+ return lines;+}++function normalizeCodeLine(line, spec) {+ let out = '';+ let pendingSpace = false;+ let quote = '';+ let indent = '';+ let leading = true;+ for (let i = 0; i < line.length; i++) {+ const ch = line[i];+ if (quote) {+ out += ch;+ if (ch === '\\' && i + 1 < line.length) out += line[++i];+ else if (ch === quote) quote = '';+ continue;+ }+ if (isSpace(ch)) {+ if (leading) indent += ch;+ else pendingSpace = true;+ continue;+ }+ leading = false;+ if (pendingSpace && out) out += ' ';+ pendingSpace = false;+ if (ch === "'" && spec.rustChars) {+ const end = rustCharEnd(line, i);+ out += end === -1 ? ch : line.slice(i, end + 1);+ if (end !== -1) i = end;+ continue;+ }+ if (spec.quotes.includes(ch)) quote = ch;+ out += ch;+ }+ if (!out) return '';+ return spec.indentSensitive ? `${indent}\u0000${out}` : out;+}++function hasSpaceAfterContinuation(line) {+ let end = line.length;+ while (end > 0 && isSpace(line[end - 1])) end--;+ return end < line.length && line[end - 1] === '\\';+}++function codeSignature(text, spec) {+ const lines = lexCodeLines(text, spec);+ if (lines === null) return null;+ const signature = [];+ for (const line of lines) {+ if (hasSpaceAfterContinuation(line)) return null;+ const normalized = normalizeCodeLine(line, spec);+ if (normalized) signature.push(normalized);+ }+ return signature;+}++function isTrivialEdit(oldString, newString, spec) {+ if (spec.lineComment === '//' && (oldString.includes('??/') || newString.includes('??/'))) return false;+ const before = codeSignature(oldString, spec);+ if (before === null) return false;+ const after = codeSignature(newString, spec);+ if (after === null || before.length !== after.length) return false;+ return before.every((line, index) => line === after[index]);+}++// --- Public surface ---++function leadingWord(text, word) {+ return text.startsWith(word) && !isIdentChar(text[word.length]);+}++function containsWord(text, word) {+ for (let at = text.indexOf(word); at !== -1; at = text.indexOf(word, at + 1)) {+ if (!isIdentChar(text[at - 1]) && !isIdentChar(text[at + word.length])) return true;+ }+ return false;+}++function identifierAt(text, start) {+ let end = start;+ while (end < text.length && isIdentChar(text[end])) end++;+ return text.slice(start, end);+}++function skipSpaces(text, at) {+ while (at < text.length && isSpace(text[at])) at++;+ return at;+}++function isUpper(ch) {+ return ch !== undefined && ch >= 'A' && ch <= 'Z';+}++function jsLineIsSurface(line) {+ const t = line.slice(skipSpaces(line, 0));+ return leadingWord(t, 'export') || containsWord(t, 'exports') || leadingWord(t, 'public') || leadingWord(t, 'declare');+}++function pythonNameIsPublic(name) {+ if (!name) return false;+ return !name.startsWith('_') || (name.length > 4 && name.startsWith('__') && name.endsWith('__'));+}++function pythonLineIsSurface(line, index) {+ const start = skipSpaces(line, 0);+ const t = line.slice(start);+ if (t.includes('__all__')) return true;+ for (const keyword of ['def', 'class']) {+ if (leadingWord(t, keyword)) return pythonNameIsPublic(identifierAt(t, skipSpaces(t, keyword.length)));+ }+ if (leadingWord(t, 'async')) {+ const rest = t.slice(skipSpaces(t, 5));+ if (leadingWord(rest, 'def')) return pythonNameIsPublic(identifierAt(rest, skipSpaces(rest, 3)));+ }+ if (index > 0 && start === 0) {+ const name = identifierAt(t, 0);+ const after = t[skipSpaces(t, name.length)];+ const rest = skipSpaces(t, name.length);+ const assigned = (after === '=' && t[rest + 1] !== '=') || (after === ':' && skipSpaces(t, rest + 1) < t.length);+ return Boolean(name) && isLetter(name[0]) && assigned && pythonNameIsPublic(name);+ }+ return false;+}++function goLineIsSurface(line) {+ const t = line.slice(skipSpaces(line, 0));+ if (isUpper(t[0])) return true;+ if (leadingWord(t, 'package')) return true;+ for (const keyword of ['type', 'var', 'const']) {+ if (leadingWord(t, keyword)) return isUpper(t[skipSpaces(t, keyword.length)]);+ }+ if (!leadingWord(t, 'func')) return false;+ let at = skipSpaces(t, 4);+ if (t[at] === '(') {+ const close = t.indexOf(')', at);+ if (close === -1) return true;+ at = skipSpaces(t, close + 1);+ }+ return isUpper(t[at]);+}++function rustLineIsSurface(line) {+ const t = line.slice(skipSpaces(line, 0));+ return leadingWord(t, 'pub') || leadingWord(t, 'impl') || leadingWord(t, 'trait') || t.startsWith('#[macro_export');+}++const SURFACE_BY_LANGUAGE = {+ js: jsLineIsSurface,+ python: pythonLineIsSurface,+ go: goLineIsSurface,+ rust: rustLineIsSurface+};++function baseName(filePath) {+ return String(filePath).replace(/\\/g, '/').split('/').pop().toLowerCase();+}++function wholeFileIsSurface(filePath, language) {+ const base = baseName(filePath);+ return (language === 'js' && (base.endsWith('.d.ts') || base.endsWith('.d.mts') || base.endsWith('.d.cts'))) ||+ (language === 'python' && base === '__init__.py');+}++function textTouchesSurface(text, lineIsSurface) {+ let index = 0;+ let start = 0;+ for (let i = 0; i <= text.length; i++) {+ if (i === text.length || text[i] === '\n' || text[i] === '\r') {+ if (lineIsSurface(text.slice(start, i), index)) return true;+ index++;+ start = i + 1;+ }+ }+ return false;+}++// --- Data handling ---++const DATA_WORDS = new Set([+ 'json', 'jsonl', 'ndjson', 'yaml', 'yml', 'csv', 'tsv', 'xml', 'toml', 'ini', 'parquet', 'avro', 'arrow', 'pickle', 'protobuf',+ 'serde', 'serialize', 'serializer', 'serialise', 'deserialize', 'deserializer', 'deserialise', 'marshal', 'unmarshal',+ 'schema', 'schemas', 'sql', 'sqlite', 'sqlite3', 'postgres', 'mysql', 'mongo', 'mongodb', 'database', 'db', 'cursor',+ 'migration', 'migrations', 'orm', 'dataframe', 'pandas',+ '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'+]);+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']+];+const SQL_PAIRS = [['select', 'from'], ['insert', 'into'], ['delete', 'from'], ['create', 'table'], ['alter', 'table'], ['drop', 'table'], ['update', 'set']];++function* words(text) {+ let word = '';+ let prev = '';+ for (let i = 0; i <= text.length; i++) {+ const ch = text[i];+ const alnum = ch !== undefined && ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'));+ const boundary = alnum && word && (+ (isUpper(ch) && !isUpper(prev) && !(prev >= '0' && prev <= '9')) ||+ (isUpper(ch) && isUpper(prev) && text[i + 1] >= 'a' && text[i + 1] <= 'z')+ );+ if (!alnum || boundary) {+ if (word) yield { word: word.toLowerCase(), call: !alnum && text[skipSpaces(text, i)] === '(' };+ word = alnum ? ch : '';+ } else {+ word += ch;+ }+ prev = ch;+ }+}++function textTouchesData(text) {+ const seen = new Set();+ let previous = '';+ for (const { word, call } of words(text)) {+ if (DATA_WORDS.has(word)) return true;+ if (word === 'open' && call) return true;+ if (DATA_PAIRS.some(([a, b]) => previous === a && word === b)) return true;+ seen.add(word);+ previous = word;+ }+ return SQL_PAIRS.some(([a, b]) => seen.has(a) && seen.has(b));+}++// --- Profile ---++/** Language of a target by extension, or null when unsupported. */+function languageFor(filePath) {+ if (typeof filePath !== 'string' || !filePath) return null;+ const base = baseName(filePath);+ const dot = base.lastIndexOf('.');+ if (dot <= 0) return null;+ return LANGUAGE_BY_EXT.get(base.slice(dot)) || null;+}++function changeTexts(input) {+ if (input.tool === 'Write') {+ return typeof input.content === 'string' ? { sides: [input.content], pairs: [] } : null;+ }+ if (input.tool !== 'Edit' || !Array.isArray(input.edits) || input.edits.length === 0 || input.edits.length > MAX_EDITS) return null;+ const pairs = [];+ for (const entry of input.edits) {+ if (!entry || typeof entry !== 'object') return null;+ const oldString = entry.old_string;+ const newString = entry.new_string;+ if (typeof oldString !== 'string' || typeof newString !== 'string') return null;+ pairs.push([oldString, newString]);+ }+ return { sides: pairs.flat(), pairs };+}++function withinBounds(sides) {+ let total = 0;+ for (const side of sides) {+ if (side.length > MAX_SIDE_BYTES) return false;+ const bytes = Buffer.byteLength(side, 'utf8');+ if (bytes > MAX_SIDE_BYTES) return false;+ total += bytes;+ if (total > MAX_TOTAL_BYTES) return false;+ }+ return true;+}++/** Profile of one target's change from Edit/MultiEdit entries or Write content; unknown on any doubt. */+function profileChange(input) {+ try {+ if (!input || typeof input !== 'object') return UNKNOWN_PROFILE;+ const language = languageFor(input.filePath);+ if (!language) return UNKNOWN_PROFILE;+ const texts = changeTexts(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));+ const touchesData = texts.sides.some(textTouchesData);+ const spec = LEX_SPECS[language];+ const trivial = input.tool === 'Edit' && texts.pairs.every(([oldString, newString]) => isTrivialEdit(oldString, newString, spec));+ return Object.freeze({ known: true, language, touchesPublicSurface, touchesData, trivial });+ } catch (_) {+ return UNKNOWN_PROFILE;+ }+}++module.exports = { MAX_SIDE_BYTES, MAX_TOTAL_BYTES, MAX_EDITS, UNKNOWN_PROFILE, languageFor, profileChange };diff --git a/tests/lib/gateguard-change-profile.test.js b/tests/lib/gateguard-change-profile.test.jsnew file mode 100644index 000000000..6c8608773--- /dev/null+++ b/tests/lib/gateguard-change-profile.test.js@@ -0,0 +1,357 @@+'use strict';+/**+ * Tests for scripts/lib/gateguard-change-profile.js.+ *+ * Run with: node tests/lib/gateguard-change-profile.test.js+ */++const assert = require('assert');+const path = require('path');++const { profileChange, languageFor, UNKNOWN_PROFILE, MAX_SIDE_BYTES } = require(+ path.join(__dirname, '..', '..', 'scripts', 'lib', 'gateguard-change-profile.js')+);++console.log('=== Testing gateguard-change-profile.js ===\n');++let passed = 0;+let failed = 0;++function test(desc, fn) {+ try {+ fn();+ console.log(` ✓ ${desc}`);+ passed++;+ } catch (e) {+ console.log(` ✗ ${desc}: ${e.message}`);+ failed++;+ }+}++const edit = (filePath, oldString, newString) => profileChange({ filePath, tool: 'Edit', edits: [{ old_string: oldString, new_string: newString }] });+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;+const trivial = (filePath, oldString, newString) => edit(filePath, oldString, newString).trivial;++// ── languages and bounds ──+console.log('languages and bounds:');++test('supported extensions map to a language; others do not', () => {+ const expected = {+ 'a.js': 'js', 'a.mjs': 'js', 'a.cjs': 'js', 'a.jsx': 'js', 'a.ts': 'js', 'a.tsx': 'js', 'a.mts': 'js', 'a.cts': 'js',+ 'a.py': 'python', 'a.pyi': 'python', 'a.go': 'go', 'a.rs': 'rust', 'a.java': 'java', 'a.kt': 'kotlin', 'a.kts': 'kotlin',+ 'a.cs': 'csharp', 'a.c': 'c', 'a.h': 'c', 'a.cc': 'cpp', 'a.cpp': 'cpp', 'a.cxx': 'cpp', 'a.hpp': 'cpp', 'a.hh': 'cpp',+ 'SRC\\A.PY': 'python'+ };+ for (const [file, lang] of Object.entries(expected)) assert.strictEqual(languageFor(file), lang, file);+ for (const file of ['a.rb', 'a.sh', 'Makefile', 'a.mk', 'a.yaml', 'a.md', 'a', 'a.swift', '', null]) {+ assert.strictEqual(languageFor(file), null, String(file));+ }+});++test('unknown language, bad shapes, and over-bound input give the unknown profile', () => {+ const big = 'x'.repeat(MAX_SIDE_BYTES + 1);+ const cases = [+ edit('a.rb', '# a', '# b'),+ edit('Makefile', '# a', '# b'),+ profileChange({ filePath: 'a.js', tool: 'Edit', edits: [] }),+ profileChange({ filePath: 'a.js', tool: 'Edit', edits: [{ old_string: 1, new_string: 'x' }] }),+ profileChange({ filePath: 'a.js', tool: 'Edit', edits: 'nope' }),+ profileChange({ filePath: 'a.js', tool: 'Write', content: 42 }),+ profileChange({ filePath: 'a.js', tool: 'Read', content: 'x' }),+ profileChange(null),+ profileChange({ filePath: 'a.js', tool: 'Edit', edits: Array.from({ length: 65 }, () => ({ old_string: 'a', new_string: 'b' })) }),+ edit('a.js', big, '// x'),+ edit('a.js', '// x', big),+ write('a.js', big),+ edit('a.js', 'é'.repeat(MAX_SIDE_BYTES / 2 + 1), 'x')+ ];+ for (const [index, profile] of cases.entries()) {+ assert.deepStrictEqual(profile, UNKNOWN_PROFILE, `case ${index}`);+ }+ assert.deepStrictEqual(UNKNOWN_PROFILE, { known: false, language: null, touchesPublicSurface: true, touchesData: true, trivial: false });+ assert.ok(Object.isFrozen(UNKNOWN_PROFILE));+});++test('a combined MultiEdit over the total bound is unknown', () => {+ const chunk = 'y'.repeat(MAX_SIDE_BYTES - 16);+ const edits = Array.from({ length: 5 }, () => ({ old_string: chunk, new_string: chunk }));+ assert.deepStrictEqual(profileChange({ filePath: 'a.js', tool: 'Edit', edits }), UNKNOWN_PROFILE);+});++// ── public surface ──+console.log('\npublic surface:');++test('JS/TS: export, module.exports, exports., and public members touch the surface', () => {+ assert.strictEqual(surface('a.js', 'export function f(a) {', 'export function f(a, b) {'), true);+ assert.strictEqual(surface('a.ts', 'const x = 1;', 'export const x = 1;'), true);+ assert.strictEqual(surface('a.js', 'module.exports = { a };', 'module.exports = { a, b };'), true);+ assert.strictEqual(surface('a.js', 'exports.a = a;', 'exports.a = b;'), true);+ assert.strictEqual(surface('a.ts', ' public run(): void {', ' public run(x: number): void {'), true);+ assert.strictEqual(surface('a.ts', 'export default class A {}', 'export default class B {}'), true);+ assert.strictEqual(surface('types.d.ts', 'type A = string;', 'type A = number;'), true, 'declaration files are all surface');+});++test('JS/TS: body-only changes and look-alike words do not touch the surface', () => {+ assert.strictEqual(surface('a.js', ' return a + 1;', ' return a + 2;'), false);+ assert.strictEqual(surface('a.js', 'const exported = 1;', 'const exported = 2;'), false);+ assert.strictEqual(surface('a.js', 'function exporter() {}', 'function exporter(a) {}'), false);+ assert.strictEqual(surface('a.js', 'const publicKey = k;', 'const publicKey = j;'), false);+});++test('Python: public def/class, dunders, __all__ and __init__.py touch the surface', () => {+ assert.strictEqual(surface('a.py', 'def load(path):', 'def load(path, strict):'), true);+ assert.strictEqual(surface('a.py', ' async def fetch(self):', ' async def fetch(self, x):'), true);+ assert.strictEqual(surface('a.py', 'class Loader:', 'class Loader(Base):'), true);+ assert.strictEqual(surface('a.py', ' def __init__(self):', ' def __init__(self, x):'), true);+ assert.strictEqual(surface('a.py', "__all__ = ['a']", "__all__ = ['a', 'b']"), true);+ assert.strictEqual(surface('pkg/__init__.py', 'x = 1', 'x = 2'), true, '__init__.py is all surface');+ assert.strictEqual(surface('a.py', 'x = 1\nLIMIT = 3', 'x = 1\nLIMIT = 4'), true, 'module-level public name');+});++test('Python: private definitions and bodies do not touch the surface', () => {+ assert.strictEqual(surface('a.py', 'def _helper(a):', 'def _helper(a, b):'), false);+ assert.strictEqual(surface('a.py', ' return a + 1', ' return a + 2'), false);+ assert.strictEqual(surface('a.py', ' x = 1', ' x = 2'), false, 'indented assignment');+ assert.strictEqual(surface('a.py', 'x = 1\n_limit = 3', 'x = 1\n_limit = 4'), false, 'module-level private name');+});++test('Go: capitalised declarations touch the surface; lowercase ones do not', () => {+ assert.strictEqual(surface('a.go', 'func Load(p string) error {', 'func Load(p string, s bool) error {'), true);+ assert.strictEqual(surface('a.go', 'func (s *Store) Get(k string) {', 'func (s *Store) Get(k int) {'), true);+ assert.strictEqual(surface('a.go', 'type Config struct {', 'type Config struct { // x'), true);+ assert.strictEqual(surface('a.go', '\tName string', '\tName int'), true, 'exported field');+ assert.strictEqual(surface('a.go', 'func load(p string) {', 'func load(p int) {'), false);+ assert.strictEqual(surface('a.go', 'func (s *store) get() {', 'func (s *store) get(k int) {'), false);+ assert.strictEqual(surface('a.go', '\treturn x + 1', '\treturn x + 2'), false);+});++test('Rust: pub items, impl/trait blocks and macro exports touch the surface', () => {+ assert.strictEqual(surface('a.rs', 'pub fn load() {', 'pub fn load(x: u8) {'), true);+ assert.strictEqual(surface('a.rs', 'pub(crate) fn load() {', 'pub(crate) fn load(x: u8) {'), true);+ assert.strictEqual(surface('a.rs', 'impl Display for A {', 'impl Debug for A {'), true);+ assert.strictEqual(surface('a.rs', '#[macro_export]\nmacro_rules! m {', '#[macro_export]\nmacro_rules! n {'), true);+ assert.strictEqual(surface('a.rs', 'fn load() {', 'fn load(x: u8) {'), false);+ assert.strictEqual(surface('a.rs', ' x + 1', ' x + 2'), false);+ assert.strictEqual(surface('a.rs', 'let publish = 1;', 'let publish = 2;'), false);+});++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;');+ assert.strictEqual(profile.known, true, file);+ assert.strictEqual(profile.touchesPublicSurface, true, file);+ }+});++test('Write always touches the surface', () => {+ const profile = write('a.js', 'const x = 1;\n');+ assert.strictEqual(profile.known, true);+ assert.strictEqual(profile.touchesPublicSurface, true);+ assert.strictEqual(profile.trivial, false);+});++// ── data ──+console.log('\ndata:');++test('file I/O, serialisation, SQL, schema and date handling touch data', () => {+ const hits = [+ ['a.js', 'const cfg = JSON.parse(raw);'],+ ['a.js', "const text = fs.readFileSync(p, 'utf8');"],+ ['a.ts', 'await writeFile(out, body);'],+ ['a.py', "with open(path) as fh:"],+ ['a.py', 'rows = csv.reader(fh)'],+ ['a.py', 'doc = yaml.safe_load(fh)'],+ ['a.py', "stamp = datetime.now().strftime('%Y')"],+ ['a.js', 'const when = new Date(ts).toISOString();'],+ ['a.go', 'err := json.Unmarshal(b, &v)'],+ ['a.go', 'f, err := os.Open(p)'],+ ['a.rs', 'let s = std::fs::read_to_string(p)?;'],+ ['a.rs', 'let v: T = serde_json::from_str(&s)?;'],+ ['a.java', 'rs = stmt.executeQuery("select id from users");'],+ ['a.py', 'cur.execute("INSERT INTO t VALUES (1)")'],+ ['a.ts', 'const schema = z.object({});'],+ ['a.py', 'df = pd.read_parquet(p)'],+ ['a.cs', 'var created = DateTime.UtcNow;'],+ ['a.kt', 'val ts = Instant.now().toEpochMilli() // timestamp']+ ];+ for (const [file, text] of hits) {+ assert.strictEqual(edit(file, 'x = 1', `${text}\n`).touchesData, true, `${file}: ${text}`);+ }+});++test('ordinary logic and look-alike words do not touch data', () => {+ const misses = [+ ['a.js', 'return a + b;'],+ ['a.js', 'const updated = validate(candidate);'],+ ['a.py', 'total = sum(values) / count'],+ ['a.go', 'if n > limit { return errTooMany }'],+ ['a.rs', 'let reopened = retry(opener);'],+ ['a.js', 'button.opened = true;']+ ];+ for (const [file, text] of misses) {+ assert.strictEqual(data(file, 'x = 1', text), false, `${file}: ${text}`);+ }+});++test('data is judged on both sides of an Edit and on Write content', () => {+ assert.strictEqual(data('a.js', 'JSON.parse(x)', 'parse(x)'), true, 'removed data handling still counts');+ assert.strictEqual(write('a.py', 'import json\n').touchesData, true);+ assert.strictEqual(write('a.py', 'def f():\n return 1\n').touchesData, false);+});++// ── trivial ──+console.log('\ntrivial:');++test('comment-only and whitespace-only edits are trivial in every supported language', () => {+ const cases = [+ ['a.js', '// old note\nfoo();', '// new note\nfoo();'],+ ['a.js', 'foo(); // old', 'foo(); // new'],+ ['a.js', '/* a\n * b\n */\nfoo();', '/* a\n * c\n */\nfoo();'],+ ['a.js', 'if (x) {\n foo();\n}', 'if (x) {\n foo();\n}'],+ ['a.js', 'foo(a, b);', 'foo(a, b); '],+ ['a.js', 'foo();\n\nbar();', 'foo();\nbar();'],+ ['a.js', 'foo();', '// added\nfoo();'],+ ['a.ts', "const s = 'x'; // why", "const s = 'x'; // because"],+ ['a.py', '# old\nx = 1', '# new\nx = 1'],+ ['a.py', 'x = 1 # old', 'x = 1 # new'],+ ['a.py', "s = 'a#b' # old", "s = 'a#b' # new"],+ ['a.go', '\t// Load loads.\n\treturn nil', '\t// Load reads.\n\treturn nil'],+ ['a.rs', "fn f<'a>(x: &'a str) {} // old", "fn f<'a>(x: &'a str) {} // new"],+ ['a.rs', "let c = '\"'; // old", "let c = '\"'; // new"],+ ['a.java', 'int x = 1; // old', 'int x = 1; // new'],+ ['a.kt', 'val x = "a" // old', 'val x = "a" // new'],+ ['a.cs', 'var x = "a"; // old', 'var x = "a"; // new'],+ ['a.c', '#include <stdio.h>\n/* old */', '#include <stdio.h>\n/* new */'],+ ['a.cpp', "char c = 'x'; // old", "char c = 'x'; // new"]+ ];+ for (const [file, before, after] of cases) {+ assert.strictEqual(trivial(file, before, after), true, `${file}: ${JSON.stringify(before)} -> ${JSON.stringify(after)}`);+ }+});++test('a comment change that also edits code is not trivial', () => {+ assert.strictEqual(trivial('a.js', '// old\nfoo(1);', '// new\nfoo(2);'), false);+ assert.strictEqual(trivial('a.py', 'x = 1 # old', 'x = 2 # new'), false);+ assert.strictEqual(trivial('a.js', 'foo();', 'foo();\nbar();'), false);+ assert.strictEqual(trivial('a.js', 'foo(); bar();', 'foo();\nbar();'), false, 'line structure is code');+});++test('whitespace inside strings and between tokens is code', () => {+ assert.strictEqual(trivial('a.js', "s = 'a b';", "s = 'a b';"), false);+ assert.strictEqual(trivial('a.js', 'x = a+b;', 'x = a + b;'), false);+ assert.strictEqual(trivial('a.py', 'x = f"a"', 'x = f "a"'), false);+ assert.strictEqual(trivial('a.c', 'int x;', 'intx;'), false);+ assert.strictEqual(trivial('a.c', 'a/* c */b', 'ab'), false);+});++test('indentation changes are never trivial in Python', () => {+ assert.strictEqual(trivial('a.py', 'if x:\n y()', 'if x:\n y()'), false);+ assert.strictEqual(trivial('a.py', 'if x:\n y()', 'if x:\n\ty()'), false);+ assert.strictEqual(trivial('a.py', 'if x:\n y()\n # note', 'if x:\n y()\n # note moved'), true, 'comment lines carry no indentation');+});++test('C preprocessor lines are code', () => {+ assert.strictEqual(trivial('a.c', '#define LIMIT 1', '#define LIMIT 2'), false);+ assert.strictEqual(trivial('a.h', '#include "a.h"', '#include "b.h"'), false);+ assert.strictEqual(trivial('a.c', '#if 0\nx();\n#endif', '#if 1\nx();\n#endif'), false);+});++test('multi-line strings, templates and raw strings are never trivial', () => {+ const cases = [+ ['a.js', 'const s = `\n// a\n`;', 'const s = `\n// b\n`;'],+ ['a.js', '// a\n`;', '// b\n`;'],+ ['a.go', 'q := `\n// a\n`', 'q := `\n// b\n`'],+ ['a.py', 'x = """\n# a\n"""', 'x = """\n# b\n"""'],+ ['a.py', "x = '''# a'''", "x = '''# b'''"],+ ['a.py', 'x = f"{d["#"]}" # old', 'x = f"{d["#"]}" # new'],+ ['a.java', 'String s = """\n// a\n""";', 'String s = """\n// b\n""";'],+ ['a.kt', 'val s = "${m["//"]}" // a', 'val s = "${m["//"]}" // b'],+ ['a.cs', 'var s = @"a\n// a";', 'var s = @"a\n// b";'],+ ['a.cs', 'var s = $"{d["//"]}"; // a', 'var s = $"{d["//"]}"; // b'],+ ['a.rs', 'let s = r#"// a"#;', 'let s = r#"// b"#;'],+ ['a.rs', 'let s = "line\n// a";', 'let s = "line\n// b";'],+ ['a.cpp', 'auto s = R"(// a)";', 'auto s = R"(// b)";'],+ ['a.c', 'char *s = "a\\\n// a";', 'char *s = "a\\\n// b";']+ ];+ for (const [file, before, after] of cases) {+ assert.strictEqual(trivial(file, before, after), false, `${file}: ${JSON.stringify(before)}`);+ }+});++test('ambiguous JS syntax is never trivial', () => {+ assert.strictEqual(trivial('a.js', "x = /'/; y = '//'", "x = /'/; y = '//x'"), false, 'regex literal');+ assert.strictEqual(trivial('a.js', 'x = a / b; // old', 'x = a / b; // new'), false, 'division');+ assert.strictEqual(trivial('a.jsx', '<p>// old</p>', '<p>// new</p>'), false, 'JSX text');+ assert.strictEqual(trivial('a.js', 'x = 1;\n--> old', 'x = 1;\n--> new'), false, 'HTML close comment');+});++test('comment tricks that can hide code are never trivial', () => {+ assert.strictEqual(trivial('a.c', '// note\nx();', '// note \\\nx();'), false, 'backslash continues a C line comment');+ assert.strictEqual(trivial('a.c', '// note\nx();', '// note ??/\nx();'), false, 'trigraph continuation');+ assert.strictEqual(trivial('a.rs', '/* a /* b */ */', '/* a /* c */ */'), false, 'nested block comment');+ assert.strictEqual(trivial('a.js', '/* open', '/* still open'), false, 'unterminated block comment');+ assert.strictEqual(trivial('a.js', "s = 'open", "s = 'open2"), false, 'unterminated string');+ assert.strictEqual(trivial('a.py', 'x = a \\\n + b', 'x = a \\ \n + b'), false, 'whitespace after a line continuation');+});++test('Write, unknown languages and MultiEdit with any non-trivial entry are not trivial', () => {+ assert.strictEqual(write('a.js', '// only a comment\n').trivial, false);+ assert.strictEqual(trivial('a.rb', '# a', '# b'), false);+ assert.strictEqual(trivial('a.sh', '# a', '# b'), false);+ const multi = edits => profileChange({ filePath: 'a.js', tool: 'Edit', edits });+ 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);+});++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);+ assert.strictEqual(profile.known, true);+});++// ── bounded work ──+console.log('\nbounded work:');++test('64 KiB adversarial inputs profile in linear time', () => {+ const size = MAX_SIDE_BYTES;+ const inputs = [+ '/*'.repeat(size / 2),+ '//'.repeat(size / 2),+ "'".repeat(size),+ '"\\'.repeat(size / 2),+ '\\\n'.repeat(size / 2),+ 'a'.repeat(size),+ ' '.repeat(size - 1) + 'x',+ '\n'.repeat(size),+ 'export '.repeat(Math.floor(size / 7)),+ 'def _'.repeat(Math.floor(size / 5)),+ 'aA'.repeat(size / 2),+ '# \\'.repeat(Math.floor(size / 3)),+ 'func ('.repeat(Math.floor(size / 6)),+ 'select from '.repeat(Math.floor(size / 12))+ ];+ for (const [index, input] of inputs.entries()) {+ for (const file of ['a.js', 'a.py', 'a.go', 'a.rs', 'a.c']) {+ const start = process.hrtime.bigint();+ edit(file, input, `${input} `);+ write(file, input);+ const ms = Number(process.hrtime.bigint() - start) / 1e6;+ assert.ok(ms < 250, `input ${index} in ${file} took ${ms.toFixed(1)} ms`);+ }+ }+});++test('never throws on hostile shapes', () => {+ const hostile = [+ { filePath: 'a.js', tool: 'Edit', edits: [null, { old_string: 'a', new_string: 'b' }] },+ { filePath: 'a.js', tool: 'Edit', edits: [{ get old_string() { throw new Error('boom'); }, new_string: 'b' }] },+ { filePath: { toString() { throw new Error('boom'); } }, tool: 'Edit', edits: [] },+ { filePath: 'a.js', tool: 'Write', get content() { throw new Error('boom'); } }+ ];+ for (const input of hostile) assert.deepStrictEqual(profileChange(input), UNKNOWN_PROFILE);+});++console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);+process.exit(failed > 0 ? 1 : 0);