feat(server): link pull requests agents create from the shell #24813
Mergedt3dotgg(GitHub profile, opens in a new tab)merged 7 commits into
main fromrefs/pull/24813/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/orchestration-v2/PullRequestSyncReactor.ts line 146Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -51,0 +81,21 @@81+ ? input82+ : Array.from(83+ wrapped.matchAll(SHELL_WORD_PIECE),84+ ([, double, single, escaped, bare]) =>85+ double?.replace(/\\(["\\$`])/gu, "$1") ?? single ?? escaped ?? bare,86+ ).join("");87+ return script.replace(HEREDOC_BODY, "<<").replace(QUOTED_OR_COMMENT, "''");88+}89+90+type CommandExecution = Extract<OrchestrationV2TurnItem, { readonly type: "command_execution" }>;91+92+/**93+ * The change requests a shell command opened: URLs on lines of their own in the output of a94+ * command that runs a host's create command. One the command also names, as `gh pr view 12`95+ * does, existed before it ran. More URLs than create commands means something else printed96+ * some, such as `gh pr list`, so none are taken.97+ */98+function changeRequestsCreatedBy(input: string, output: string) {99+ if (!CREATE_COMMANDS.some(({ command }) => command.test(input))) return [];100+ const code = shellCode(input);101+ const creates = createCommandCount(code);apps/server/src/orchestration-v2/PullRequestSyncReactor.ts line 87OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -51,0 +67,21 @@67+// `"a "'`b`'" c"`.68+const SHELL_WRAPPER = /^\s*(?:\S*\/)?(?:ba|z|da|k)?sh\s+-l?c\s+(?=["'])([\s\S]*)$/u;69+const SHELL_WORD_PIECE = /"((?:\\[\s\S]|[^"\\])*)"|'([^']*)'|\\([\s\S])|(\S)/gu;70+// Heredoc bodies, quoted strings and comments are text a command carries, not commands it runs.71+const HEREDOC_BODY = /<<-?[ \t]*(['"]?)(\w+)\1[^\n]*\n[\s\S]*?(?:\n[ \t]*\2[ \t]*(?=\n|$)|$)/gu;72+const QUOTED_OR_COMMENT = /'[^']*'|"(?:\\[\s\S]|[^"\\])*"|(?<=^|\s)#[^\n]*/gmu;73+const COMMAND_SEPARATOR = /&&|\|\||[;|\n]/u;74+const URL_LINE = /^[ \t]*(https?:\/\/\S+)[ \t]*$/gmu;75+76+/** The commands a shell input runs, without the text it carries. */77+function shellCode(input: string): string {78+ const [, wrapped] = SHELL_WRAPPER.exec(input) ?? [];79+ const script =80+ wrapped === undefined81+ ? input82+ : Array.from(83+ wrapped.matchAll(SHELL_WORD_PIECE),84+ ([, double, single, escaped, bare]) =>85+ double?.replace(/\\(["\\$`])/gu, "$1") ?? single ?? escaped ?? bare,86+ ).join("");87+ return script.replace(HEREDOC_BODY, "<<").replace(QUOTED_OR_COMMENT, "''");
- apps/server/src/orchestration-v2/PullRequestSyncReactor.ts line 72OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -51 +52,21 @@515253+// Where a shell starts a command, past `NAME=value` assignments and wrappers like `timeout 60`.54+// A create command anywhere else, as in `echo "gh pr create"`, is text, not a command that runs.55+const COMMAND_START =56+ "(?:^|[;&|({`\\n]|\\b(?:do|then|else)\\s)\\s*(?:(?:\\w+=\\S*|env|time|nohup|timeout\\s+\\S+)\\s+)*";57+const CREATE_COMMANDS = sourceControlDefinitions.definitions.flatMap(58+ ({ changeRequestCreateCommand: command }) =>59+ command === undefined60+ ? []61+ : [{ command, run: new RegExp(COMMAND_START + command.source, "gu") }],62+);63+const createCommandCount = (code: string) =>64+ CREATE_COMMANDS.reduce((count, { run }) => count + [...code.matchAll(run)].length, 0);65+66+// Codex runs each command as `/bin/zsh -lc <script>`, quoting the script in pieces such as67+// `"a "'`b`'" c"`.68+const SHELL_WRAPPER = /^\s*(?:\S*\/)?(?:ba|z|da|k)?sh\s+-l?c\s+(?=["'])([\s\S]*)$/u;69+const SHELL_WORD_PIECE = /"((?:\\[\s\S]|[^"\\])*)"|'([^']*)'|\\([\s\S])|(\S)/gu;70+// Heredoc bodies, quoted strings and comments are text a command carries, not commands it runs.71+const HEREDOC_BODY = /<<-?[ \t]*(['"]?)(\w+)\1[^\n]*\n[\s\S]*?(?:\n[ \t]*\2[ \t]*(?=\n|$)|$)/gu;72+const QUOTED_OR_COMMENT = /'[^']*'|"(?:\\[\s\S]|[^"\\])*"|(?<=^|\s)#[^\n]*/gmu;apps/server/src/orchestration-v2/PullRequestSyncReactor.ts lines 160 to 171Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -51,0 +96,21 @@96+ * some, such as `gh pr list`, so none are taken.97+ */98+function changeRequestsCreatedBy(input: string, output: string) {99+ if (!CREATE_COMMANDS.some(({ command }) => command.test(input))) return [];100+ const code = shellCode(input);101+ const creates = createCommandCount(code);102+ if (creates === 0) return [];103+ const otherCommands = code104+ .split(COMMAND_SEPARATOR)105+ .filter((part) => createCommandCount(part) === 0)106+ .join("\n");107+ const created = new Map<string, ThreadPullRequestKey & { readonly url: string }>();108+ for (const [, url = ""] of output.matchAll(URL_LINE)) {109+ const link = sourceControlDefinitions.parseChangeRequestUrl(url)?.link;110+ if (link === undefined) continue;111+ const named = new RegExp(`(?:^|(?<=[\\s#/=(]))${link.number}(?=$|[\\s);&|/])`, "u");112+ if (named.test(otherCommands)) continue;113+ const key = normalizeThreadPullRequestKey(link);114+ created.set(threadPullRequestKeyOf(key), { ...key, url });115+ }116+ return created.size > creates ? [] : [...created.values()];
- apps/server/src/orchestration-v2/PullRequestSyncReactor.ts line 120OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -51,0 +100,21 @@100+ */101+function changeRequestsCreatedBy(input: string, output: string) {102+ if (!CREATE_COMMANDS.some(({ command }) => command.test(input))) return [];103+ const code = shellCode(input);104+ const creates = createCommandCount(code);105+ if (creates === 0) return [];106+ const otherCommands = code107+ .split(COMMAND_SEPARATOR)108+ .filter((part) => createCommandCount(part) === 0)109+ .join("\n");110+ if (LISTS_CHANGE_REQUESTS.test(otherCommands)) return [];111+ const creators = new Set(112+ CREATE_COMMANDS.filter(({ run }) => code.match(run) !== null).map(({ kind }) => kind),113+ );114+ const created = new Map<string, ThreadPullRequestKey & { readonly url: string }>();115+ for (const [, url = ""] of output.matchAll(URL_LINE)) {116+ const parsed = sourceControlDefinitions.parseChangeRequestUrl(url);117+ // Only the host whose create command ran can have printed a new change request.118+ if (parsed === null || !creators.has(parsed.definition.kind)) continue;119+ const { link } = parsed;120+ const named = new RegExp(`(?:^|(?<=[\\s#/=(]))${link.number}(?=$|[\\s);&|/])`, "u");
- apps/server/src/orchestration-v2/PullRequestSyncReactor.ts line 125OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -51,0 +105,21 @@105+ const script = shellScript(input);106+ const code = shellCode(script);107+ const creates = createCommandCount(code);108+ if (creates === 0) return [];109+ const otherCommands = code110+ .split(COMMAND_SEPARATOR)111+ .filter((part) => createCommandCount(part) === 0)112+ .join("\n");113+ if (LISTS_CHANGE_REQUESTS.test(otherCommands)) return [];114+ const creators = new Set(115+ CREATE_COMMANDS.filter(({ run }) => code.match(run) !== null).map(({ kind }) => kind),116+ );117+ const created = new Map<string, ThreadPullRequestKey & { readonly url: string }>();118+ for (const [, url = ""] of output.matchAll(URL_LINE)) {119+ const parsed = sourceControlDefinitions.parseChangeRequestUrl(url);120+ // Only the host whose create command ran can have printed a new change request.121+ if (parsed === null || !creators.has(parsed.definition.kind)) continue;122+ const { link } = parsed;123+ const named = new RegExp(`(?:^|(?<=[\\s#/=("']))${link.number}(?=$|[\\s);&|/"'])`, "u");124+ // Quoted text counts here: the command that creates a change request cannot name its number.125+ if (named.test(script)) continue;
- apps/server/src/orchestration-v2/PullRequestSyncReactor.ts line 61OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -49,3 +50,12 @@4950 (definition) => definition.changeRequestCloseCommand?.test(command) === true,5051 );515253+// Where a shell starts a command, past `NAME=value` assignments and wrappers like `timeout 60`.54+// A create command anywhere else, as in `echo "gh pr create"`, is text, not a command that runs.55+const COMMAND_START =56+ "(?:^|[;&|({`\\n]|\\b(?:do|then|else)\\s)\\s*(?:(?:\\w+=\\S*|env|time|nohup|timeout\\s+\\S+)\\s+)*";57+const CREATE_COMMANDS = sourceControlDefinitions.definitions.flatMap(58+ ({ kind, changeRequestCreateCommand: command }) =>59+ command === undefined60+ ? []61+ : [{ kind, command, run: new RegExp(COMMAND_START + command.source, "gu") }],
- apps/server/src/orchestration-v2/PullRequestSyncReactor.ts lines 71 to 71Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -50,2 +51,21 @@5051 );515253+// Where a shell starts a command, past `NAME=value` assignments and wrappers like `timeout 60`.54+// A create command anywhere else, as in `echo "gh pr create"`, is text, not a command that runs.55+const COMMAND_START =56+ "(?:^|[;&|({`\\n]|\\b(?:do|then|else)\\s)\\s*(?:(?:\\w+=\\S*|env|time|nohup|timeout\\s+\\S+)\\s+)*";57+const CREATE_COMMANDS = sourceControlDefinitions.definitions.flatMap(58+ ({ kind, changeRequestCreateCommand: command }) =>59+ command === undefined60+ ? []61+ : // The subcommand must end its shell word: `gh pr create#x` runs another one.62+ [63+ {64+ kind,65+ command,66+ run: new RegExp(`${COMMAND_START}${command.source}(?=$|[\\s;&|)])`, "gu"),67+ },68+ ],69+);70+const createCommandCount = (code: string) =>71+ CREATE_COMMANDS.reduce((count, { run }) => count + [...code.matchAll(run)].length, 0);
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed