/** * ============================================================ * src/tools/bash/semantics.ts —— 命令退出码语义解释 * ------------------------------------------------------------ * 许多命令用 exit code 传递"信息"而不是"成功/失败"。 * 最典型的是 grep:没匹配返回 1,但这不算错误。 * * 这里对一小撮"退出码语义特殊"的命令做白名单化处理, * 让 Bash 工具能正确地把它们的"信息性退出码"识别成非错误, * 避免模型看到 ok=false 后无意义重试。 * * 纯函数模块,无 I/O,便于单测。 * ============================================================ */ export type CommandSemanticResult = { isError: boolean; message?: string }; export type CommandSemanticFn = ( exitCode: number, stdout: string, stderr: string, ) => CommandSemanticResult; /** Small conservative lexer, not a shell evaluator. Quoted regex operators are * data. Expansions, redirects and unsupported syntax remain non-read-only. */ function inspectionCommands(command: string, advisorInspection = false): string[][] | null { const commands: string[][] = []; let words: string[] = []; let word = ''; let started = false; let quote = ''; const flushWord = () => { if (started) words.push(word); word = ''; started = false; }; const flushCommand = () => { flushWord(); if (words.length) commands.push(words); words = []; }; for (let i = 0; i < command.length; i++) { const c = command[i]!; if (quote === "'") { if (c === "'") quote = ''; else word += c; continue; } if (c === '\\') { const next = command[++i]; if (next === undefined) return null; if (quote === '"' && !['$', '`', '"', '\\', '\n'].includes(next)) word += '\\'; if (next !== '\n') { word += next; started = true; } continue; } if (c === '`' || (c === '$' && /[({\w?'"*#@!$-]/.test(command[i + 1] ?? ''))) return null; if (quote === '"') { if (c === '"') quote = ''; else word += c; continue; } if (c === "'" || c === '"') { quote = c; started = true; continue; } // Only the Advisor's inspection hint may ignore discarding stderr. This // never changes lease/sandbox classification or permits arbitrary redirects. if (advisorInspection && !started && command.startsWith('2>/dev/null', i) && /^(?:\s|[;&|]|$)/.test(command.slice(i + '2>/dev/null'.length))) { i += '2>/dev/null'.length - 1; continue; } if (/[<>(){}]/.test(c)) return null; if (c === '#' && !started) { while (i + 1 < command.length && command[i + 1] !== '\n') i++; continue; } if (c === '&' && command[i + 1] !== '&') return null; if (c === '&' || c === '|' || c === ';' || c === '\n') { flushCommand(); if ((c === '&' || c === '|') && command[i + 1] === c) i++; continue; } if (/\s/.test(c)) { flushWord(); continue; } word += c; started = true; } if (quote) return null; flushCommand(); return commands; } /** Conservative shell side-effect classification used by Advisor gates. */ export function isReadOnlyShellCommand(command: string): boolean { if (!command.trim()) return true; // A conservative scheduling hint, not an OS sandbox. Strict read-only // consumers must reject shell execution rather than trust this heuristic. // Do not strip nested shell quoting: expansion may happen in the outer shell. const segments = inspectionCommands(command); if (!segments) return false; for (const tokens of segments) { let index = 0; if ( tokens[index] === 'command' && /^(?:-v|--verbose|-V)$/.test(tokens[index + 1] ?? '') ) continue; if (tokens[index] === 'sudo' || /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[index] ?? '')) return false; if (/[\\/]/.test(tokens[index] ?? '')) return false; const name = tokens[index]?.toLowerCase(); if ( !name || name === 'cd' || name === ':' || name === 'true' || name === 'pwd' ) continue; if (name === 'git') { const sub = tokens[index + 1]?.toLowerCase() ?? ''; const args = tokens.slice(index + 2); if ( args.some((token) => /^--(?:output|ext-diff|textconv)(?:=|$)/.test(token), ) ) return false; const readOnly = new Set([ 'status', 'diff', 'log', 'show', 'branch', 'rev-parse', 'remote', 'tag', 'ls-files', 'ls-tree', 'check-ignore', 'describe', 'reflog', 'version', 'help', 'cat-file', 'count-objects', ]); if (sub === 'config') { if (!/^--(?:get|list|get-all|get-regexp)$/.test(args[0] ?? '')) return false; } else if ( sub === 'reflog' && tokens .slice(index + 2) .some((token) => /^(?:expire|delete|drop)$/.test(token)) ) { return false; } else if (sub === 'branch') { const listing = args.length === 0 || args.some((token) => /^(?:--list|-a|--all|-r|--remotes|--show-current|--contains(?:=.*)?|--no-contains(?:=.*)?|--merged(?:=.*)?|--no-merged(?:=.*)?|--points-at(?:=.*)?|--sort(?:=.*)?|--format(?:=.*)?|--column(?:=.*)?|--color(?:=.*)?|--ignore-case)$/.test( token, ), ); const allowed = /^(?:--list|-a|--all|-r|--remotes|-v|-vv|--verbose|--show-current|--contains(?:=.*)?|--no-contains(?:=.*)?|--merged(?:=.*)?|--no-merged(?:=.*)?|--points-at(?:=.*)?|--sort(?:=.*)?|--format(?:=.*)?|--column(?:=.*)?|--color(?:=.*)?|--ignore-case)$/; if ( !listing || args.some((token) => token.startsWith('-') && !allowed.test(token)) ) return false; } else if (sub === 'tag') { const listing = args.length === 0 || args.some((token) => /^(?:-l|--list|-n\d*|--contains(?:=.*)?|--no-contains(?:=.*)?|--merged(?:=.*)?|--no-merged(?:=.*)?|--points-at(?:=.*)?|--sort(?:=.*)?|--format(?:=.*)?|--column(?:=.*)?|--color(?:=.*)?|--ignore-case)$/.test( token, ), ); const allowed = /^(?:-l|--list|-n\d*|--contains(?:=.*)?|--no-contains(?:=.*)?|--merged(?:=.*)?|--no-merged(?:=.*)?|--points-at(?:=.*)?|--sort(?:=.*)?|--format(?:=.*)?|--column(?:=.*)?|--color(?:=.*)?|--ignore-case)$/; if ( !listing || args.some((token) => token.startsWith('-') && !allowed.test(token)) ) return false; } else if (sub === 'remote') { if ( args.length && !( args.every((token) => token === '-v' || token === '--verbose') || /^(?:get-url|get-head|get-branches|get-tags)$/.test(args[0] ?? '') ) ) return false; } else if (!readOnly.has(sub)) return false; continue; } if ( name === 'find' && tokens.some((token) => /^-(?:delete|exec|execdir|ok|okdir|fprint|fprint0|fprintf|fls)$/.test( token, ), ) ) return false; if (name === 'rg' && tokens.some((token) => /^--pre(?:=|$)/.test(token))) return false; if ( /^(?:ls|dir|find|rg|grep|cat|head|tail|stat|file|which|where|type|printf|echo|uname|whoami|printenv|realpath|readlink|du|df|wc|diff|cmp|get-childitem|get-content|get-item|get-location|get-process|test-path|select-string)$/.test( name, ) ) continue; if ((name === 'env' || name === 'date') && tokens.length === index + 1) continue; if ( /^(?:node|bun|python|python3)$/.test(name) && tokens.length === index + 2 && /^(?:--version|-v|--help|-h)$/.test(tokens[index + 1]!) ) continue; return false; } return true; } /** * Advisor 专用信号,别处不要复用:命令是否只是"检查现状"(跑测试/构建/lint/ * 类型检查),而不是开始实施改动。跟 isReadOnlyShellCommand 是两个不同的问题—— * 后者要回答"能不能安全并行/算不算并发写",这类命令往往会写构建产物/缓存/ * 日志,答案本该是 false,改不得;但顾问提醒(advisorNudge)拿 isReadOnlyShellCommand * 的结果去判定"这是不是开始实施改动"时,会把纯验证型命令 * (如 `cd frontend && npm run build` 核对现状)误判成"开始写代码", * 于是过早提醒"动手前先咨询"。 * * 宁可漏判(仍照旧触发一次检查点,是现状,不算回退)也不误判(放过真正的写): * 每个分段要么落在 isReadOnlyShellCommand 的白名单里,要么命中下面这份 * 有意从紧的多生态"验证类"清单,否则整条命令按写处理。 */ export function isVerificationShellCommand(command: string): boolean { if (!command.trim()) return true; const segments = inspectionCommands(command); if (!segments) return false; if (!segments.length) return false; for (const tokens of segments) { // Re-quote tokens for the shared classifier without reinterpreting data. if (isReadOnlyShellCommand(tokens.map(token => `'${token.replace(/'/g, `'\\''`)}'`).join(' '))) continue; let index = 0; while (index < tokens.length && tokens[index] === 'sudo') index++; while ( index < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[index]!) ) index++; const name = tokens[index]?.replace(/^.*\//, '').toLowerCase(); const rest = tokens.slice(index + 1).map((token) => token.toLowerCase()); if (!isVerificationInvocation(name, rest)) return false; } return true; } /** Advisor-only diagnosis hint; not an authorization or concurrency predicate. */ export function isAdvisorInspectionCommand(command: string): boolean { const segments = inspectionCommands(command, true); if (!segments?.length) return false; return segments.every(original => { const tokens = [...original]; if (tokens[0] === 'git') { let i = 1; while (i < tokens.length) { if (tokens[i] === '-C' && tokens[i + 1] && !tokens[i + 1]!.startsWith('-')) { i += 2; continue; } if (['--no-pager', '--no-optional-locks'].includes(tokens[i]!)) { i++; continue; } break; } tokens.splice(1, i - 1); } return isReadOnlyShellCommand(tokens.map(token => `'${token.replace(/'/g, `'\\''`)}'`).join(' ')); }); } function isVerificationInvocation( name: string | undefined, rest: string[], ): boolean { if (!name) return false; if (/^(?:npm|yarn|pnpm|bun)$/.test(name)) { const sub = rest[0] ?? ''; const script = sub === 'run' || sub === 'run-script' ? (rest[1] ?? '') : sub; return /^(?:test|lint|typecheck|type-check|check|build|verify|ci)(?::|$)/.test( script, ); } if (name === 'tsc') return true; if ( /^(?:eslint|biome|tslint|ruff|flake8|pylint|mypy|stylelint|rustfmt|clippy)$/.test( name, ) ) return true; if (name === 'pytest') return true; if ( (name === 'python' || name === 'python3') && rest[0] === '-m' && ['pytest', 'mypy', 'pyflakes', 'unittest'].includes(rest[1] ?? '') ) return true; if (name === 'go') return /^(?:test|vet|build)$/.test(rest[0] ?? ''); if (name === 'cargo') return /^(?:test|check|build|clippy)$/.test(rest[0] ?? ''); if (['mvn', 'gradle', 'gradlew', './gradlew'].includes(name)) return /^(?:test|verify|check|build)$/.test(rest[0] ?? ''); if (name === 'make') return rest.length === 0 || /^(?:test|check|lint|build)$/.test(rest[0] ?? ''); if (/^(?:jest|vitest|mocha|rspec|phpunit|ava|karma)$/.test(name)) return true; if (name === 'dotnet') return /^(?:test|build)$/.test(rest[0] ?? ''); return false; } const DEFAULT_SEMANTIC: CommandSemanticFn = (exitCode) => ({ isError: exitCode !== 0, message: exitCode !== 0 ? `Command failed with exit code ${exitCode}` : undefined, }); export const COMMAND_SEMANTICS: Map = new Map([ // grep: 0=找到匹配, 1=无匹配(非错误), 2+=真错误 [ 'grep', (exitCode) => ({ isError: exitCode >= 2, message: exitCode === 1 ? 'No matches found' : undefined, }), ], // ripgrep 与 grep 同义 [ 'rg', (exitCode) => ({ isError: exitCode >= 2, message: exitCode === 1 ? 'No matches found' : undefined, }), ], // find: 1=部分目录不可达(仍有结果,非致命), 2+=错误 [ 'find', (exitCode) => ({ isError: exitCode >= 2, message: exitCode === 1 ? 'Some directories were inaccessible' : undefined, }), ], // diff: 0=相同, 1=有差异(非错误), 2+=错误 [ 'diff', (exitCode) => ({ isError: exitCode >= 2, message: exitCode === 1 ? 'Files differ' : undefined, }), ], // test: 0=真, 1=假(非错误), 2+=错误 [ 'test', (exitCode) => ({ isError: exitCode >= 2, message: exitCode === 1 ? 'Condition is false' : undefined, }), ], // [ 是 test 的别名 [ '[', (exitCode) => ({ isError: exitCode >= 2, message: exitCode === 1 ? 'Condition is false' : undefined, }), ], ]); /** * 从复合命令串里启发式抽出"最终决定 exit code 的那个命令"。 * * 规则(够用即可,不追求严谨 shell 解析): * 1. 去掉前缀 `bash -c "..."` / `sh -c '...'` * 2. 按 ` | `、`&&`、`||`、`;` 分段,取最后一段(决定退出码的是最后一个命令) * 3. 去掉前置 `env VAR=val` / `VAR=val` 形态的环境变量赋值 * 4. 取第一个 token 作为命令名 * * 不依赖 shell-quote,避免引新依赖。 */ function extractPrimaryCommand(command: string): string { let cmd = command.trim(); // 剥 bash -c "..." / sh -c '...' 外壳 const wrapMatch = cmd.match(/^(?:bash|sh|zsh|dash)\s+-c\s+(['"])(.+)\1\s*$/s); if (wrapMatch) cmd = wrapMatch[2]!.trim(); // 按 shell 控制操作符切,取最后一段 const segments = cmd .split(/\s*(?:\|\||&&|;|\|)\s*/) .filter((s) => s.length > 0); let last = segments[segments.length - 1] ?? cmd; last = last.trim(); // 去掉前置环境变量赋值:`FOO=bar BAZ=qux cmd ...` 或 `env FOO=bar cmd ...` const tokens = last.split(/\s+/); let i = 0; if (tokens[i] === 'env') i++; while (i < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[i]!)) i++; return tokens[i] ?? ''; } export function interpretCommandResult( command: string, exitCode: number, stdout: string, stderr: string, ): CommandSemanticResult { const base = extractPrimaryCommand(command); const fn = COMMAND_SEMANTICS.get(base) ?? DEFAULT_SEMANTIC; return fn(exitCode, stdout, stderr); }