Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA
TypeScript
skill contract: Bash writes to repo files count as edits for check_after_last_edit (GST-1633) (#4078)
Garry Tan89e9a994d8d0
diff --git a/changelog.d/capy-gst-1633-bash-writes.md b/changelog.d/capy-gst-1633-bash-writes.mdnew file mode 100644index 000000000..8201bd123--- /dev/null+++ b/changelog.d/capy-gst-1633-bash-writes.md@@ -0,0 +1 @@+- **/investigate's check-after-last-edit item sees fixes written through Bash.** A Bash command that writes a file inside the session directory (a heredoc into python or cat, `sed -i`, `tee`, a `>` or `>>` redirect, `patch`, `git apply`) now counts as an edit, so a run that tests, then fixes the code through the shell and never tests again reads `missing` instead of `met`. Before, only Edit, Write, MultiEdit and NotebookEdit counted, and 5 of 7 probe-I fixes in GEVA-2's L1 run were heredoc writes. The parser (`lib/shell-writes.ts`) is conservative: reads, output to stdout, `2>&1`, and writes under `/tmp`, `~`, another directory or a variable path do not count. (GST-1633)diff --git a/docs/skill-routing-and-contracts.md b/docs/skill-routing-and-contracts.mdindex a5da45f1e..6d2c1f58d 100644--- a/docs/skill-routing-and-contracts.md+++ b/docs/skill-routing-and-contracts.md@@ -73,7 +73,7 @@ Every item has an `id` (lowercase letters, digits, `.`, `_`, `-`) and a `kind`,| kind | Fields | Met when ||---|---|---|| `report_labels` | `heading`, `labels[]` | The last assistant message containing the heading has a `Label: value` line for every label, and no value is empty or a placeholder (`[...]`, `<...>`, TBD, TODO, `...`, or a template like `DONE \| BLOCKED`) |-| `check_after_last_edit` | optional `match` (regular expression) | No Edit, Write, MultiEdit or NotebookEdit happened, or a Bash test or repro command ran after the last one. By default a command counts when, with quoted text removed, one of its parts (split on `&&`, `\|\|`, `;`, `\|`) runs a test runner (pytest, jest, vitest, rspec, tsc, ...), a test or check verb (`npm test`, `go test`, `cargo run`, `make check`, `bun run lint`), code through an interpreter (`node repro.js`, `python -c ...`, `bun scripts/repro.ts`), `curl` against a URL, or a script whose name says test, spec, repro, check, verify or lint, directly or behind a wrapper (`bundle exec rspec`, `uv run pytest`, `docker compose run app pytest`, `xvfb-run npm test`, `bash scripts/test.sh`). Installs, builds, cleans and version probes (`bun install`, `npm install`, `go build`, `make clean`, `node --version`), `git commit --no-verify`, `cat test/a.test.ts` and the shell's `test -f` do not count |+| `check_after_last_edit` | optional `match` (regular expression) | No edit happened, or a Bash test or repro command ran after the last one. An edit is an Edit, Write, MultiEdit or NotebookEdit call, or a Bash command that writes a file inside the session directory (the transcript's first `cwd`): a `>`, `>>` or `&>` redirect, `tee`, `sed -i` or `perl -i`, `patch` or `git apply`, or an inline or heredoc python, node, ruby, bun or deno script that opens a literal path for writing (directly or through a variable assigned one, as in `python3 - <<'EOF'`), including a script the same command wrote first. A check later in the same Bash command counts (`sed -i ... && bun test`), and so does the command whose output the write captures (`bun test > out.log`, `bun test \| tee test.log`). Reads, output to stdout, fd duplications (`2>&1`), `/dev` paths, targets outside the session directory (`/tmp`, `~`, `../`) and targets named by a variable (`"$f"`) are not edits; `lib/shell-writes.ts` holds the parser (GST-1633). By default a command counts when, with quoted text removed, one of its parts (split on `&&`, `\|\|`, `;`, `\|`) runs a test runner (pytest, jest, vitest, rspec, tsc, ...), a test or check verb (`npm test`, `go test`, `cargo run`, `make check`, `bun run lint`), code through an interpreter (`node repro.js`, `python -c ...`, `bun scripts/repro.ts`), `curl` against a URL, or a script whose name says test, spec, repro, check, verify or lint, directly or behind a wrapper (`bundle exec rspec`, `uv run pytest`, `docker compose run app pytest`, `xvfb-run npm test`, `bash scripts/test.sh`). Installs, builds, cleans and version probes (`bun install`, `npm install`, `go build`, `make clean`, `node --version`), `git commit --no-verify`, `cat test/a.test.ts` and the shell's `test -f` do not count || `selected_specialists_dispatched` | optional `marker`, `empty_marker` | The selection line was printed in an assistant message or a Bash result (never a fetched page or file), its names are plain (letters, digits, spaces, `_`, `.`, `-`, at most 40 characters), and each specialist it names has an Agent dispatch that mentions it. The marker is literal text in which a whole-word N stands for a number; the default is `Dispatching N specialists:`. N = 0 (`Dispatching 0 specialists: (small diff)`) or a "specialists skipped" line means zero specialists were selected, which passes. Text in parentheses is not a name (`Dispatching 1 specialists: State Machines (small diff)` selects State Machines) || `agent_dispatch` | `match` (regular expression, case-insensitive) | An Agent dispatch's description or prompt matches `match`. A `marker` is rejected until the checker can bind it to the dispatch it names (GST-1242) |diff --git a/lib/shell-writes.ts b/lib/shell-writes.tsnew file mode 100644index 000000000..4502f77db--- /dev/null+++ b/lib/shell-writes.ts@@ -0,0 +1,341 @@+/**+ * shell-writes — the repo files a Bash command writes, for the skill contract's+ * check_after_last_edit item (GST-1633). A fix written through the shell (a+ * heredoc into python or cat, sed -i, tee, a > or >> redirect, patch, git apply)+ * is an edit just like an Edit call, so a test run before it does not count.+ *+ * Conservative: a write counts only when its target resolves inside the session+ * directory. Reads, output to stdout, fd duplications (2>&1), /dev paths, targets+ * under another directory (/tmp, ~, ../) and targets named by a variable never+ * count. patch, git apply and xargs sed -i with no visible target count when they+ * run inside the session directory, since they only write the tree they run in.+ */+import * as path from 'path';++const posix = path.posix;+/** Stands in for the session directory when the transcript does not name one. */+const UNKNOWN_DIR = '/\0session';++type Tok = { kind: 'word'; raw: string; value: string } | { kind: 'op'; value: string } | { kind: 'redir'; op: string } | { kind: 'heredoc'; body: string };+export interface ShellCommand { words: string[]; text: string; redirects: { op: string; target: string }[]; heredocs: string[]; cwd: string | null; pipeline: number }++/** The index just past the bracket that closes the one at src[from] (quotes are not tracked). */+function closing(src: string, from: number, open: string, close: string): number {+ let depth = 0;+ for (let j = from; j < src.length; j++) {+ if (src[j] === open) depth++;+ else if (src[j] === close && --depth === 0) return j + 1;+ }+ return src.length;+}++function tokenize(src: string): Tok[] {+ const toks: Tok[] = [];+ const pending: { delim: string; strip: boolean; at: number }[] = [];+ let raw = '';+ let value = '';+ let inWord = false;+ let i = 0;+ const flush = () => { if (inWord) toks.push({ kind: 'word', raw, value }); raw = ''; value = ''; inWord = false; };+ const take = (end: number, v = src.slice(i, end)) => { raw += src.slice(i, end); value += v; inWord = true; i = end; };+ const bodies = () => {+ const due = pending.splice(0);+ due.forEach((h, n) => {+ const lines: string[] = [];+ while (i < src.length) {+ const nl = src.indexOf('\n', i);+ const end = nl < 0 ? src.length : nl;+ const line = src.slice(i, end);+ i = end + 1;+ if ((h.strip ? line.replace(/^\t+/, '') : line) === h.delim) break;+ lines.push(line);+ }+ toks.splice(h.at, 0, { kind: 'heredoc', body: lines.join('\n') });+ for (const later of due.slice(n + 1)) later.at++;+ });+ };+ while (i < src.length) {+ const c = src[i];+ const rest = src.slice(i);+ if (c === '\\') {+ if (src[i + 1] === '\n') i += 2;+ else take(Math.min(i + 2, src.length), src[i + 1] ?? '');+ } else if (c === "'") {+ const end = src.indexOf("'", i + 1);+ take(end < 0 ? src.length : end + 1, src.slice(i + 1, end < 0 ? src.length : end));+ } else if (c === '"') {+ let j = i + 1;+ let v = '';+ for (; j < src.length && src[j] !== '"'; j++) {+ if (src[j] === '\\' && '"\\$`'.includes(src[j + 1] ?? '')) j++;+ v += src[j];+ }+ take(Math.min(j + 1, src.length), v);+ } else if (rest.startsWith('$(') || rest.startsWith('${')) {+ take(closing(src, i + 1, src[i + 1], src[i + 1] === '(' ? ')' : '}'));+ } else if (c === '`') {+ const end = src.indexOf('`', i + 1);+ take(end < 0 ? src.length : end + 1);+ } else if (rest.startsWith('((') && !inWord) {+ take(closing(src, i, '(', ')'));+ flush();+ } else if (c === '#' && !inWord) {+ while (i < src.length && src[i] !== '\n') i++;+ } else if (c === '\n') {+ flush();+ toks.push({ kind: 'op', value: '\n' });+ i++;+ bodies();+ } else if (c === ' ' || c === '\t') {+ flush();+ i++;+ } else {+ const redir = /^(?:&>>|&>|\d*>>|\d*>&|\d*>\||\d*>|<<<|<<-|<<|\d*<&|\d*<>|\d*<)/.exec(rest);+ const op = /^(?:\|\||&&|\|&|;;|[;|&()])/.exec(rest);+ if (redir && !(inWord && /^\d/.test(redir[0]))) {+ flush();+ i += redir[0].length;+ if (redir[0] === '<<' || redir[0] === '<<-') {+ while (src[i] === ' ' || src[i] === '\t') i++;+ const m = /^(['"])(.*?)\1|^[^\s;&|<>()]+/.exec(src.slice(i));+ pending.push({ delim: m ? (m[2] ?? m[0]).replace(/\\/g, '') : '', strip: redir[0] === '<<-', at: toks.length });+ i += m ? m[0].length : 0;+ continue;+ }+ const dup = /[<>]&$/.test(redir[0]) ? /^\s*(?:\d+|-)/.exec(src.slice(i)) : null;+ if (dup) i += dup[0].length;+ else toks.push({ kind: 'redir', op: redir[0].replace(/^(\d*)>&$/, '&>') });+ } else if (op) {+ flush();+ toks.push({ kind: 'op', value: op[0] });+ i += op[0].length;+ } else {+ take(i + 1);+ }+ }+ }+ flush();+ bodies();+ return toks;+}++const ASSIGN = /^[A-Za-z_][A-Za-z0-9_]*=/;+const RESERVED = new Set(['!', 'if', 'then', 'else', 'elif', 'fi', 'do', 'done', 'while', 'until', 'time', '{', '}']);+/** Words that run the command after them, with the options of each that take a value. */+const PREFIXES: Record<string, Set<string>> = {+ env: new Set(['-u', '--unset', '-C', '--chdir', '-S']), sudo: new Set(['-u', '-g', '-C', '-D', '-h', '-p', '-U']), command: new Set(), exec: new Set(['-a']),+ nice: new Set(['-n']), nohup: new Set(), time: new Set(), timeout: new Set(['-s', '-k', '--signal', '--kill-after']), xargs: new Set(['-I', '-n', '-P', '-L', '-d', '-E', '-s', '-a']),+};+const SHELLS = /^(?:bash|sh|zsh|dash)$/;+const base = (word: string) => word.split('/').pop() ?? '';++/** The words that run: assignments, reserved words and prefix commands (with their options) removed. */+function program(words: string[]): string[] {+ let w = words;+ for (let guard = 0; guard < 8 && w.length; guard++) {+ while (w.length && (ASSIGN.test(w[0]) || RESERVED.has(w[0]))) w = w.slice(1);+ const valued = PREFIXES[base(w[0] ?? '')];+ if (!valued) break;+ const name = base(w[0]);+ let k = 1;+ while (k < w.length && (w[k].startsWith('-') || ASSIGN.test(w[k]))) k += valued.has(w[k]) ? 2 : 1;+ if (name === 'timeout' && k < w.length) k++;+ w = w.slice(k);+ }+ return w;+}++/** A cd target resolved against the current directory; null when it cannot be known (cd, cd ~, cd -, cd $DIR). */+function changeDir(here: string | null, target: string | undefined): string | null {+ if (!target || /^[~$-]|\$|`/.test(target)) return null;+ if (posix.isAbsolute(target)) return posix.normalize(target);+ return here === null ? null : posix.resolve(here, target);+}++/** The simple commands of a Bash line in order, with heredoc bodies attached, cd tracked and bash -c unwrapped. */+export function shellCommands(line: string, cwd: string | null, depth = 0): ShellCommand[] {+ const out: ShellCommand[] = [];+ const scopes: (string | null)[] = [];+ let here = cwd;+ let pipeline = 0;+ let cur = { words: [] as string[], raws: [] as string[], redirects: [] as ShellCommand['redirects'], heredocs: [] as string[] };+ const end = () => {+ const words = program(cur.words);+ const redirects = words[0] === '[[' ? [] : cur.redirects;+ const cmd: ShellCommand = { words, text: cur.raws.join(' '), redirects, heredocs: cur.heredocs, cwd: here, pipeline };+ cur = { words: [], raws: [], redirects: [], heredocs: [] };+ if (!cmd.words.length && !redirects.length && !cmd.heredocs.length) return;+ const shell = SHELLS.test(base(words[0] ?? '')) && words[1] === '-c' && typeof words[2] === 'string' && depth < 3;+ if (shell) {+ out.push(...shellCommands(words[2], here, depth + 1).map(c => ({ ...c, pipeline })));+ if (redirects.length) out.push({ ...cmd, words: [], text: '' });+ return;+ }+ out.push(cmd);+ if (words[0] === 'cd' || words[0] === 'pushd') here = changeDir(here, words.slice(1).find(w => !w.startsWith('-')) ?? '~');+ else if (words[0] === 'popd') here = null;+ };+ const toks = tokenize(line);+ for (let k = 0; k < toks.length; k++) {+ const t = toks[k];+ if (t.kind === 'op') {+ end();+ if (t.value !== '|' && t.value !== '|&') pipeline++;+ if (t.value === '(') scopes.push(here);+ else if (t.value === ')' && scopes.length) here = scopes.pop() ?? null;+ } else if (t.kind === 'heredoc') cur.heredocs.push(t.body);+ else if (t.kind === 'redir') {+ const next = toks[k + 1];+ if (next?.kind === 'word') { cur.redirects.push({ op: t.op, target: next.value }); cur.raws.push(`${t.op}${next.raw}`); k++; }+ } else {+ cur.words.push(t.value);+ cur.raws.push(t.raw);+ }+ }+ end();+ return out;+}++/** A path relative to the session directory when it resolves inside it, else null. '' is the directory itself. */+function inside(p: string, cwd: string | null, root: string): string | null {+ if (!p || /^[~$&]|\$|`|^\/dev\/|^[A-Za-z]:[\\/]|^\\/.test(p)) return null;+ const abs = posix.isAbsolute(p) ? posix.normalize(p) : cwd === null ? null : posix.resolve(cwd, p);+ if (abs === null) return null;+ if (abs === root) return '';+ return abs.startsWith(`${root.replace(/\/+$/, '')}/`) ? abs.slice(root.replace(/\/+$/, '').length + 1) : null;+}++const WRITE_REDIRECT = /^(?:\d*>>?|\d*>\||&>>?)$/;+const INTERPRETER = /^(?:python[\d.]*|node|nodejs|ruby|bun|deno)$/;+const CODE_FLAG = /^(?:-c|-e|--eval|eval)$/;+const VALUE_FLAG = /^(?:-m|-W|-X|-r|--require|-I)$/;+const PATH_EXPR = String.raw`((?:pathlib\.)?Path\(\s*[rbuRBU]{0,2}(?:'[^'\n]*'|"[^"\n]*")\s*\)|[rbuRBU]{0,2}(?:'[^'\n]*'|"[^"\n]*")|[A-Za-z_$][\w$]*)`;+const MODE = String.raw`\s*(?:mode\s*=\s*)?[rbuRBU]?['"]([^'"]*)['"]`;+/** Calls that write a file named by their first path argument; the second group, when present, is an open mode. */+const WRITE_CALLS = [+ new RegExp(String.raw`\bopen\(\s*${PATH_EXPR}\s*,${MODE}`, 'g'),+ new RegExp(String.raw`${PATH_EXPR}\s*\.\s*open\(${MODE}`, 'g'),+ new RegExp(String.raw`${PATH_EXPR}\s*\.\s*write_(?:text|bytes)\s*\(`, 'g'),+ new RegExp(String.raw`\b(?:writeFileSync|writeFile|appendFileSync|appendFile|Bun\.write|File\.write|File\.binwrite|Deno\.writeTextFile(?:Sync)?|Deno\.writeFile(?:Sync)?)\s*\(\s*${PATH_EXPR}\s*,`, 'g'),+];+const ASSIGNMENT = new RegExp(String.raw`(?:^|[\s;(])(?:const\s+|let\s+|var\s+)?([A-Za-z_$][\w$]*)\s*=\s*${PATH_EXPR}\s*(?:;|$)`, 'gm');++/** The string literals a path expression can name: a literal, Path(literal), or a variable assigned one of those. */+function literals(expr: string, assigned: Map<string, string[]>): string[] {+ const m = /^(?:(?:pathlib\.)?Path\(\s*)?[rbuRBU]{0,2}(['"])(.*)\1\s*\)?$/.exec(expr.trim());+ if (m) return m[2].includes('{') ? [] : [m[2]];+ return assigned.get(expr.trim()) ?? [];+}++/** The files a script's code writes, by literal path or a variable holding one. */+function codeWrites(code: string): string[] {+ const assigned = new Map<string, string[]>();+ for (const m of code.matchAll(ASSIGNMENT)) {+ const lits = literals(m[2], new Map());+ if (lits.length) assigned.set(m[1], [...(assigned.get(m[1]) ?? []), ...lits]);+ }+ return WRITE_CALLS.flatMap(re => [...code.matchAll(re)].filter(m => m[2] === undefined || /[wax+]/.test(m[2])).flatMap(m => literals(m[1], assigned)));+}++/** The code an interpreter command runs, when the line shows it: an inline -c/-e script, its stdin, or a script this line wrote. */+function interpreterCode(c: ShellCommand, scripts: Map<string, string>): string[] {+ const [, ...args] = c.words;+ let script: string | undefined;+ for (let k = 0; k < args.length; k++) {+ if (CODE_FLAG.test(args[k])) return [args[k + 1] ?? ''];+ if (VALUE_FLAG.test(args[k])) { if (args[k] === '-m') return []; k++; continue; }+ if (!args[k].startsWith('-') || args[k] === '-') { script = args[k]; break; }+ }+ const file = (p: string) => scripts.get(c.cwd === null && !posix.isAbsolute(p) ? '' : posix.resolve(c.cwd ?? '/', p)) ?? '';+ if (script !== undefined && script !== '-') return [file(script)];+ return [...c.heredocs, ...c.redirects.filter(r => r.op === '<<<').map(r => r.target), ...c.redirects.filter(r => r.op === '<').map(r => file(r.target))];+}++/** The +++ paths of a unified diff, with git's a/ b/ prefixes removed. */+const diffTargets = (diff: string) => [...diff.matchAll(/^\+\+\+ (\S+)/gm)].map(m => m[1].replace(/^[ab]\//, '')).filter(p => p !== '/dev/null');++/**+ * The repo files one simple command writes, or null when it writes none. self is false when every write is the+ * command's own output (a redirect or tee), so the command itself can still be the check that follows the write.+ */+export function writeTargets(c: ShellCommand, root: string, scripts: Map<string, string> = new Map()): { files: string[]; self: boolean } | null {+ const files: string[] = [];+ const add = (p: string, cwd = c.cwd) => { const f = inside(p, cwd, root); if (f !== null) files.push(f || '.'); };+ for (const r of c.redirects) if (WRITE_REDIRECT.test(r.op)) add(r.target);+ const [first = '', ...args] = c.words;+ const name = base(first);+ const positional = args.filter(a => !a.startsWith('-'));+ if (name === 'tee') positional.forEach(f => add(f));+ const output = files.length;+ if (name === 'sed' || name === 'gsed' || name === 'perl') {+ let inPlace = false;+ let script = false;+ const rest: string[] = [];+ for (let k = 0; k < args.length; k++) {+ const a = args[k];+ if (/^(?:-e|--expression|-f|--file)$/.test(a)) { script = true; k++; }+ else if (a === '-i' && args[k + 1] === '') { inPlace = true; k++; }+ else if (a.startsWith('--in-place')) inPlace = true;+ else if (/^-[A-Za-z0-9]/.test(a)) {+ const letters = a.slice(1);+ const flags = letters.slice(0, letters.search(name === 'perl' ? /[CdDFImMx]|$/ : /[ef]|$/));+ const at = flags.indexOf('i');+ if (at >= 0 && (name !== 'perl' || !flags.slice(0, at).includes('e'))) inPlace = true;+ if (name === 'perl' && letters.endsWith('e')) { script = true; k++; }+ } else rest.push(a);+ }+ const targets = (script ? rest : rest.slice(1)).filter(f => f !== '{}');+ if (inPlace) targets.length ? targets.forEach(f => add(f)) : add('.');+ } else if (name === 'git') {+ let k = 0;+ let cwd = c.cwd;+ for (; k < args.length && args[k].startsWith('-'); k++) {+ if (args[k] === '-C') cwd = changeDir(cwd, args[++k]);+ else if (args[k] === '-c') k++;+ }+ const sub = args.slice(k + 1);+ const readOnly = sub.includes('--cached') || (sub.some(a => /^--(?:check|stat|numstat|summary)$/.test(a)) && !sub.includes('--apply'));+ if (args[k] === 'apply' && !readOnly) {+ const targets = c.heredocs.flatMap(diffTargets);+ targets.length ? targets.forEach(f => add(f, cwd)) : add('.', cwd);+ }+ } else if (name === 'patch' && !args.some(a => a === '--dry-run' || a === '-C' || a === '--check')) {+ let cwd = c.cwd;+ const named: string[] = [];+ for (let k = 0; k < args.length; k++) {+ if (args[k] === '-d' || args[k] === '--directory') cwd = changeDir(cwd, args[++k]);+ else if (args[k] === '-o' || args[k] === '--output') named.push(args[++k] ?? '');+ else if (/^(?:-i|--input|-B|--prefix|-r|--reject-file|-z|--suffix|-D|--ifdef|-F|--fuzz|-V)$/.test(args[k])) k++;+ else if (!args[k].startsWith('-')) { named.push(args[k]); break; }+ }+ const targets = [...named, ...c.heredocs.flatMap(diffTargets)];+ targets.length ? targets.forEach(f => add(f, cwd)) : add('.', cwd);+ } else if (INTERPRETER.test(name)) {+ interpreterCode(c, scripts).flatMap(codeWrites).forEach(f => add(f));+ }+ return files.length ? { files: [...new Set(files)], self: files.length > output } : null;+}++/**+ * The last repo write in a Bash line: the files it writes and the text of the commands that ran after it, which+ * includes the writer's own pipeline when the write is only its output (`bun test | tee test.log`). Null when the+ * line writes no file inside the session directory. cwd is where the line ran, root the session directory; both+ * null when the transcript does not say, and then only relative targets count.+ */+export function lastBashWrite(line: string, cwd: string | null, root: string | null): { files: string[]; after: string } | null {+ const top = root !== null && posix.isAbsolute(root) ? posix.normalize(root) : UNKNOWN_DIR;+ const here = cwd !== null && posix.isAbsolute(cwd) ? posix.normalize(cwd) : top;+ const cmds = shellCommands(line, here);+ const scripts = new Map<string, string>();+ let last: { at: number; files: string[]; self: boolean } | null = null;+ for (const [at, c] of cmds.entries()) {+ const w = writeTargets(c, top, scripts);+ if (w) last = { at, ...w };+ const body = c.heredocs.join('\n');+ for (const r of c.redirects) if (WRITE_REDIRECT.test(r.op) && c.cwd !== null) scripts.set(posix.resolve(c.cwd, r.target), body);+ }+ if (!last) return null;+ const { at, files, self } = last;+ const start = self ? at + 1 : cmds.findIndex(c => c.pipeline === cmds[at].pipeline);+ return { files, after: cmds.slice(start).map(c => c.text).join('\n') };+}diff --git a/lib/skill-contract.ts b/lib/skill-contract.tsindex aa5a0f5db..d10da8dae 100644--- a/lib/skill-contract.ts+++ b/lib/skill-contract.ts@@ -18,6 +18,7 @@import * as fs from 'fs';import * as path from 'path';import { atomicWriteSync } from './fs-atomic';+import { lastBashWrite } from './shell-writes';import { readFrontmatter, scanInstalledSkills } from './skill-route';import { resolveStateRoot } from './state-root';@@ -157,9 +158,10 @@ export function itemSummary(item: ContractItem): string {export type TranscriptEvent =| { kind: 'prompt' | 'meta' | 'text'; line: number; text: string }- | { kind: 'tool_use'; line: number; id: string; name: string; input: Record<string, any> }+ | { kind: 'tool_use'; line: number; id: string; name: string; input: Record<string, any>; cwd?: string }| { kind: 'tool_result'; line: number; id: string; text: string; isError: boolean };-export interface Transcript { events: TranscriptEvent[]; sessionId: string | null }+/** cwd is the session directory: the first record's working directory, when the transcript names one. */+export interface Transcript { events: TranscriptEvent[]; sessionId: string | null; cwd?: string | null }const META_PREFIX = /^\s*<(?:local-command-stdout|local-command-stderr|system-reminder|task-notification|user-prompt-submit-hook|bash-input|bash-stdout|bash-stderr)\b/;@@ -177,6 +179,7 @@ function blockText(content: unknown): string {export function parseTranscript(text: string, opts: { includeSidechain?: boolean } = {}): Transcript {const events: TranscriptEvent[] = [];let sessionId: string | null = null;+ let cwd: string | null = null;let lines = 0;let objects = 0;let messages = 0;@@ -195,13 +198,14 @@ export function parseTranscript(text: string, opts: { includeSidechain?: booleanmessages++;if (rec.isSidechain === true && !opts.includeSidechain) continue;if (typeof rec.sessionId === 'string') sessionId = rec.sessionId;+ if (cwd === null && typeof rec.cwd === 'string') cwd = rec.cwd;const blocks = typeof content === 'string' ? [{ type: 'text', text: content }] : content;for (const block of blocks) {if (!isObject(block)) continue;if (rec.type === 'assistant') {if (block.type === 'text' && typeof block.text === 'string') events.push({ kind: 'text', line, text: block.text });if (block.type === 'tool_use' && typeof block.name === 'string') {- events.push({ kind: 'tool_use', line, id: String(block.id ?? ''), name: block.name, input: isObject(block.input) ? block.input : {} });+ events.push({ kind: 'tool_use', line, id: String(block.id ?? ''), name: block.name, input: isObject(block.input) ? block.input : {}, ...(typeof rec.cwd === 'string' ? { cwd: rec.cwd } : {}) });}} else if (block.type === 'tool_result') {events.push({ kind: 'tool_result', line, id: String(block.tool_use_id ?? ''), text: blockText(block.content), isError: block.is_error === true });@@ -212,7 +216,7 @@ export function parseTranscript(text: string, opts: { includeSidechain?: boolean}if (lines > 0 && objects === 0) throw new UnknownShape('no line is a JSON object');if (objects > 0 && messages === 0) throw new UnknownShape('no user or assistant message records');- return { events, sessionId };+ return { events, sessionId, cwd };}/**@@ -359,7 +363,7 @@ function parseNames(raw: string): string[] {interface ItemCheck { met: boolean; detail: string; fix: string }-function checkItem(item: ContractItem, run: TranscriptEvent[]): ItemCheck {+function checkItem(item: ContractItem, run: TranscriptEvent[], root: string | null): ItemCheck {const texts = run.filter(e => e.kind === 'text').map(e => (e as { text: string }).text);const agents = run.filter((e): e is ToolUse => isToolUse(e) && AGENT_TOOLS.test(e.name));switch (item.kind) {@@ -377,17 +381,25 @@ function checkItem(item: ContractItem, run: TranscriptEvent[]): ItemCheck {}case 'check_after_last_edit': {let lastEdit = -1;- run.forEach((e, i) => { if (isToolUse(e) && EDIT_TOOLS.test(e.name)) lastEdit = i; });+ let edit = '';+ let sameCall = '';+ run.forEach((e, i) => {+ if (!isToolUse(e)) return;+ const cmd = bashCommand(e);+ const write = cmd === null ? null : lastBashWrite(cmd, e.cwd ?? root, root);+ if (write) [lastEdit, edit, sameCall] = [i, `Bash write (${cut(write.files.join(', '), 60)})`, write.after];+ else if (EDIT_TOOLS.test(e.name)) [lastEdit, edit, sameCall] = [i, e.name, ''];+ });if (lastEdit < 0) return { met: true, detail: 'no edits since the skill loaded', fix: '' };const re = item.match ? new RegExp(item.match, 'i') : null;- const check = run.slice(lastEdit + 1).map(bashCommand).find(cmd => {- if (cmd === null || /gstack-skill-contract/.test(cmd)) return false;+ const check = [sameCall || null, ...run.slice(lastEdit + 1).map(bashCommand)].find(cmd => {+ if (!cmd || /gstack-skill-contract/.test(cmd)) return false;const bare = cmd.replace(/"(?:[^"\\]|\\.)*"|'[^']*'/g, '""');return re ? re.test(bare) : isCheckCommand(bare);});return check? { met: true, detail: `ran "${cut(check)}" after the last edit`, fix: '' }- : { met: false, detail: `no test or repro command after the last ${(run[lastEdit] as ToolUse).name}`, fix: item.fix ?? 'run the test or repro again after your last edit and show its result' };+ : { met: false, detail: `no test or repro command after the last ${edit}`, fix: item.fix ?? 'run the test or repro again after your last edit and show its result' };}case 'selected_specialists_dispatched': {const marker = markerPattern(item.marker ?? DEFAULT_MATCHERS.specialistSelection);@@ -473,7 +485,7 @@ export function checkContract(t: Transcript, skill: string, contract: Contract,const earlyExit = !load ? null : statusLine === 'BLOCKED' ? 'STATUS: BLOCKED' : endedEarly ? DEFAULT_MATCHERS.earlyExit : null;const items: ItemResult[] = load ? contract.items.map(item => {if (earlyExit) return { id: item.id, kind: item.kind, status: 'met', detail: `the skill ended the run early (${earlyExit})`, fix: '' };- const r = checkItem(item, run);+ const r = checkItem(item, run, t.cwd ?? null);if (r.met) return { id: item.id, kind: item.kind, status: 'met', detail: r.detail, fix: '' };const reason = waived.get(item.id);return reason ? { id: item.id, kind: item.kind, status: 'waived', detail: r.detail, fix: r.fix, reason } : { id: item.id, kind: item.kind, status: 'missing', detail: r.detail, fix: r.fix };diff --git a/test/skill-contract.test.ts b/test/skill-contract.test.tsindex 19ae5dd72..9d0fcb00e 100644--- a/test/skill-contract.test.ts+++ b/test/skill-contract.test.ts@@ -12,6 +12,7 @@ import {type CheckResult,type Contract,} from '../lib/skill-contract';+import { lastBashWrite } from '../lib/shell-writes';import { readFrontmatter } from '../lib/skill-route';import {CONTRACT_HOOK, DEBUG_REPORT, INTERACTIVE_TURNS, J1_TRANSCRIPT, ROOT, SKILLS, hookEnv, meta, result, runHook, say, skillsDir, slash, tmpDir, tool, user,@@ -206,6 +207,73 @@ describe('checkContract is a pure function of the transcript', () => {expect([cmd, isCheckCommand(cmd)]).toEqual([cmd, false]);});+ test('check_after_last_edit: a Bash write to a repo file is an edit, so a fix written through the shell needs a check after it (GST-1633)', () => {+ const loaded = J1_TRANSCRIPT.slice(0, 4);+ const bash = (id: string, command: string) => [tool(id, 'Bash', { command }), result(id, 'ok')];+ const after = (...commands: string[]) => check([...loaded, ...bash('t0', 'bun test'), ...commands.flatMap((c, i) => bash(`b${i}`, c))]).items[1];+ const writes = [+ "python3 - <<'EOF'\np = 'src/auth.ts'\ns = open(p).read()\nopen(p, 'w').write(s.replace('a', 'b'))\nEOF",+ "sed -i 's/session.user/session?.user/' src/auth.ts",+ "echo 'export const x = 1' | tee src/auth.ts",+ "printf 'fixed\\n' >> src/auth.ts",+ "cat > src/auth.ts <<'EOF'\nexport function login() {}\nEOF",+ "git apply <<'EOF'\n--- a/src/auth.ts\n+++ b/src/auth.ts\n@@ -1 +1 @@\n-a\n+b\nEOF",+ 'patch -p1 < fix.diff',+ "cd src && perl -pi -e 's/a/b/' auth.ts",+ 'python3 -c "from pathlib import Path; Path(\'src/auth.ts\').write_text(\'x\')"',+ 'node -e "require(\'fs\').writeFileSync(\'/repo/src/auth.ts\', \'x\')"',+ "cat > /tmp/fix.py <<'EOF'\nwith open('src/auth.ts', 'w') as f:\n f.write('x')\nEOF\npython3 /tmp/fix.py",+ 'grep -rl session.user src | xargs sed -i s/session.user/session?.user/',+ ];+ for (const w of writes) {+ expect([w, after(w).status]).toEqual([w, 'missing']);+ expect([w, after(w, 'bun test test/auth.test.ts').status]).toEqual([w, 'met']);+ expect([w, after(`${w}\nbun test`).status]).toEqual([w, 'met']);+ expect([w, after(`bun test\n${w}`).status]).toEqual([w, 'missing']);+ }+ expect(after(writes[1]).detail).toBe('no test or repro command after the last Bash write (src/auth.ts)');+ expect(after(writes[0], 'git diff src/auth.ts').status).toBe('missing');+ });++ test('check_after_last_edit: reads, stdout, writes outside the repo and fd redirects are not edits (GST-1633)', () => {+ const edited = [...J1_TRANSCRIPT.slice(0, -1), tool('t0', 'Bash', { command: 'bun test' }), result('t0', 'ok')];+ const after = (command: string) => check([...edited, tool('b', 'Bash', { command }), result('b', 'ok')]).items[1].status;+ const controls = [+ 'cat src/auth.ts', 'grep -n user src/auth.ts', 'sed -n 1,20p src/auth.ts', 'echo done', 'echo "a > src/auth.ts"', "grep '>' src/auth.ts",+ "python3 - <<'EOF'\nprint(open('src/auth.ts').read())\nEOF", 'python3 -c "open(\'/tmp/x\', \'w\').write(\'y\')"',+ 'echo x > /tmp/out.txt', "cat > /tmp/fix.py <<'EOF'\nx = 1\nEOF", 'cd /tmp && echo x > notes.txt', 'echo x | tee /tmp/log', 'sed -i s/a/b/ /tmp/a.txt',+ 'echo x > ../elsewhere/a.txt', 'echo x > /home/u/notes.txt', 'echo x > ~/notes.txt', 'echo x > "$OUT"',+ 'bun test 2>&1 | tail -5', 'ls >/dev/null 2>&1', 'git status 2>&1', '[[ 2 > 1 ]] && echo ok', '(( 2 > 1 )) && echo ok',+ 'git apply --check fix.diff', 'patch --dry-run -p1 < fix.diff', "cat <<'EOF'\necho x > src/auth.ts\nEOF",+ ];+ for (const c of controls) expect([c, after(c)]).toEqual([c, 'met']);+ expect(after('bun test > test-output.log')).toBe('met');+ expect(after('bun test 2>&1 | tee test-output.log')).toBe('met');+ const noCwd = (lines: string[]) => lines.map(l => { const o = JSON.parse(l); delete o.cwd; return JSON.stringify(o); });+ const bare = (command: string) => check(noCwd([...edited, tool('b', 'Bash', { command }), result('b', 'ok')])).items[1].status;+ expect(bare('sed -i s/a/b/ src/auth.ts')).toBe('missing');+ expect(bare('echo x > /repo/src/auth.ts')).toBe('met');+ expect(bare('cd /tmp && sed -i s/a/b/ a.txt')).toBe('met');+ });++ test('lastBashWrite: the files a Bash line writes and the commands that ran after the last one (GST-1633)', () => {+ const w = (line: string, cwd = '/repo') => lastBashWrite(line, cwd, '/repo');+ expect(w('bash -c "sed -i s/a/b/ src/a.py && bun test"')).toEqual({ files: ['src/a.py'], after: 'bun test' });+ expect(w('(cd /tmp && echo x > a) && echo y > b.txt')).toEqual({ files: ['b.txt'], after: 'echo y >b.txt' });+ expect(w("sed -i '' 's/a/b/' src/a.py")).toEqual({ files: ['src/a.py'], after: '' });+ expect(w('echo x1>src/a.py')?.files).toEqual(['src/a.py']);+ expect(w("cat <<A > x.txt; cat <<B > /tmp/y\na\nA\nb\nB\npytest")).toEqual({ files: ['x.txt'], after: 'cat >x.txt\ncat >/tmp/y\npytest' });+ expect(w("python3 - <<'PY'\nimport pathlib\np = pathlib.Path('src/a.py')\np.write_text('x')\nPY")?.files).toEqual(['src/a.py']);+ expect(w('git apply fix.diff')?.files).toEqual(['.']);+ expect(w('git -C /tmp/other apply fix.diff')).toBeNull();+ expect(w('sed -i s/a/b/ a.py', '/repo/src')?.files).toEqual(['src/a.py']);+ expect(w("for f in src/*.py; do sed -i 's/a/b/' \"$f\"; done")).toBeNull();+ expect(w("node -e \"fs.writeFileSync(path.join('src', 'a'), 'x')\"")).toBeNull();+ for (const read of ['perl -Ilib t/basic.t', "perl -MList::Util=sum -le 'print sum(1, 2)'", 'sed -fscript.sed src/a.py', "sed -es/i/j/ src/a.py"]) expect([read, w(read)]).toEqual([read, null]);+ expect(w("perl -Ilib -pi -e 's/a/b/' src/a.pm")?.files).toEqual(['src/a.pm']);+ expect(w("perl -i.bak -pe 's/a/b/' src/a.pm")?.files).toEqual(['src/a.pm']);+ });+test('check_after_last_edit: an option value is never the verb, and a long chain of wrapper words stays fast', () => {for (const cmd of ['make -C web test', 'npm --prefix web test', 'pnpm --filter app test', 'bun --cwd app test', 'yarn workspace app test','xcodebuild -scheme App test', 'cargo +nightly test', 'mvn clean test', 'bun run typecheck', 'node --test'])