Skip to content
TypeScript

feat(server): link pull requests agents create from the shell (#24813)

Theo Brownedca46e2b2424
diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts
index b978f211589..028e74b06a2 100644
--- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts
+++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts
@@ -332,17 +332,22 @@ function runUpdated(
};
}
-function commandRan(threadId: ThreadId, input: string): OrchestrationV2DomainEvent {
+function commandRan(
+ threadId: ThreadId,
+ input: string,
+ output?: string,
+ name = "command",
+): OrchestrationV2DomainEvent {
const runId = RunId.make(`run:${threadId}:1`);
const at = DateTime.makeUnsafe(NOW);
return {
type: "turn-item.updated",
- id: EventId.make(`event:${threadId}:command`),
+ id: EventId.make(`event:${threadId}:${name}`),
threadId,
runId,
occurredAt: at,
payload: {
- id: TurnItemId.make(`item:${threadId}:command`),
+ id: TurnItemId.make(`item:${threadId}:${name}`),
threadId,
runId,
nodeId: null,
@@ -358,6 +363,7 @@ function commandRan(threadId: ThreadId, input: string): OrchestrationV2DomainEve
updatedAt: at,
type: "command_execution",
input,
+ ...(output === undefined ? {} : { output }),
},
};
}
@@ -466,6 +472,29 @@ const requestAndApply = Effect.fn("requestPullRequestSyncHarness")(function* (
yield* applyRecordedSyncs(fixture);
});
+/** A thread with an open pull request whose merge command marks the end of earlier events. */
+const MERGING_THREAD = ThreadId.make("merging");
+
+/** The link commands `events` dispatch, read once the reactor has handled them all. */
+const linksFrom = Effect.fn("linksFrom")(function* (
+ fixture: Harness,
+ reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"],
+ events: ReadonlyArray<OrchestrationV2DomainEvent>,
+) {
+ yield* Ref.set(fixture.linkCommands, []);
+ yield* Queue.offerAll(fixture.domainEvents, [
+ ...events,
+ commandRan(MERGING_THREAD, "gh pr merge 7", undefined, "merge"),
+ ]);
+ yield* Queue.take(fixture.snapshotReads);
+ yield* Queue.take(fixture.snapshotReads);
+ yield* reactor.drain;
+ return yield* Ref.get(fixture.linkCommands);
+});
+
+const mergingSnapshot = () =>
+ makeSnapshot([makeThread(MERGING_THREAD, { pullRequests: [makeLink(7, { state: "open" })] })]);
+
describe("PullRequestSyncReactor", () => {
it.effect("retries a failed stack read after the summary becomes terminal", () =>
Effect.scoped(
@@ -1480,4 +1509,183 @@ describe("PullRequestSyncReactor", () => {
}),
),
);
+
+ it.effect.each([
+ {
+ name: "a plain create",
+ input:
+ 'gh pr create --base main --head feature --title "fix: 7 things" --body-file /tmp/body.md',
+ output: "https://github.com/owner/repository/pull/124\n",
+ linked: [124],
+ },
+ {
+ name: "a Codex shell wrapper after a push",
+ input: '/bin/zsh -lc "git push -u origin feature 2>&1 | tail -2 && gh pr create --fill"',
+ output: [
+ "remote: Create a pull request for 'feature' on GitHub by visiting:",
+ "remote: https://github.com/owner/repository/pull/new/feature",
+ "https://github.com/owner/repository/pull/124",
+ ].join("\n"),
+ linked: [124],
+ },
+ {
+ name: "a Codex script quoted in pieces around a heredoc",
+ input:
+ "/bin/zsh -lc \"cat > /tmp/body.md <<'EOF'\nSet the \"'`hidden`'\" flag.\nEOF\ngh pr create --fill --body-file /tmp/body.md\"",
+ output: "https://github.com/owner/repository/pull/62\n",
+ linked: [62],
+ },
+ {
+ name: "an older pull request read in the same command",
+ input: "gh pr view 120 --json url --jq .url && gh pr create --fill",
+ output:
+ "https://github.com/owner/repository/pull/120\nhttps://github.com/owner/repository/pull/124",
+ linked: [124],
+ },
+ {
+ name: "both layers of a stack",
+ input: "gh pr create --base main --head a --fill && gh pr create --base a --head b --fill",
+ output:
+ "https://github.com/owner/repository/pull/124\nhttps://github.com/owner/repository/pull/125",
+ linked: [124, 125],
+ },
+ {
+ name: "the first pull request of a new repository",
+ input: "cargo test 2>&1 | tail -1 && timeout 60 gh pr create -R owner/repository --fill",
+ output: "test result: ok\nhttps://github.com/owner/repository/pull/1",
+ linked: [1],
+ },
+ {
+ name: "a GitLab merge request",
+ input: "glab mr create --fill --yes",
+ output:
+ "!3 Fix the thing (feature)\n https://gitlab.com/owner/repository/-/merge_requests/3\n",
+ linked: [3],
+ },
+ {
+ name: "a new pull request whose number appears in the create command",
+ input: "timeout 60 gh pr create --fill",
+ output: "https://github.com/owner/repository/pull/60",
+ linked: [60],
+ },
+ {
+ name: "a create subcommand that does not end its shell word",
+ input: "gh pr create#typo; gh pr view --json url --jq .url",
+ output: "https://github.com/owner/repository/pull/124",
+ linked: [],
+ },
+ {
+ name: "a create after an empty heredoc",
+ input: "cat > /tmp/notes.md <<'EOF'\nEOF\ngh pr create --fill",
+ output: "https://github.com/owner/repository/pull/124",
+ linked: [124],
+ },
+ {
+ name: "a read with no create",
+ input: "gh pr view 124 --json url --jq .url",
+ output: "https://github.com/owner/repository/pull/124",
+ linked: [],
+ },
+ {
+ name: "a create command quoted in another program's query",
+ input: `sqlite3 audit.db "select output from items where input like '%gh pr create%'"`,
+ output: "https://github.com/owner/repository/pull/124",
+ linked: [],
+ },
+ {
+ name: "a create command with a separator inside quotes",
+ input: "echo 'example: gh pr create; gh pr create --fill' && gh pr view --json url --jq .url",
+ output: "https://github.com/owner/repository/pull/124",
+ linked: [],
+ },
+ {
+ name: "more URLs than create commands",
+ input: "gh pr view --json url --jq .url && gh pr create --fill",
+ output:
+ "https://github.com/owner/repository/pull/120\nhttps://github.com/owner/repository/pull/124",
+ linked: [],
+ },
+ {
+ name: "a create command only in heredoc text",
+ input:
+ "cat > notes.md <<'EOF'\nOpen it with gh pr create.\nEOF\ngh pr list --json url --jq '.[].url'",
+ output: "https://github.com/owner/repository/pull/124",
+ linked: [],
+ },
+ {
+ name: "a create command after a comment that starts at a separator",
+ input: "gh pr view --json url --jq .url;# note; gh pr create --fill",
+ output: "https://github.com/owner/repository/pull/124",
+ linked: [],
+ },
+ {
+ name: "a create beside a command that lists other pull requests",
+ input: "gh pr list --json url --jq '.[].url' && gh pr create --fill > /dev/null",
+ output: "https://github.com/owner/repository/pull/120",
+ linked: [],
+ },
+ {
+ name: "another host's URL beside a create command",
+ input: "gh pr create --fill",
+ output: "https://gitlab.com/owner/repository/-/merge_requests/3",
+ linked: [],
+ },
+ {
+ name: "an existing pull request quoted in another command",
+ input:
+ "printf '%s\\n' 'https://github.com/owner/repository/pull/120'; gh pr create --fill > /dev/null",
+ output: "https://github.com/owner/repository/pull/120",
+ linked: [],
+ },
+ ])("links what the command created: $name", ({ input, output, linked }) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ yield* TestClock.setTime(Date.parse(NOW));
+ const fixture = yield* makeHarness({ snapshot: mergingSnapshot() });
+
+ yield* Effect.gen(function* () {
+ const reactor = yield* startAndSweep(fixture);
+ const child = ThreadId.make("delegated-child");
+ const links = yield* linksFrom(fixture, reactor, [commandRan(child, input, output)]);
+
+ assert.deepStrictEqual(
+ links.map((command) => [command.threadId, command.number, command.source]),
+ linked.map((number) => [child, number, "created"]),
+ );
+ }).pipe(Effect.provide(fixture.layer));
+ }),
+ ),
+ );
+
+ it.effect("links a created pull request once its command settles, with one command id", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ yield* TestClock.setTime(Date.parse(NOW));
+ const fixture = yield* makeHarness({ snapshot: mergingSnapshot() });
+
+ yield* Effect.gen(function* () {
+ const reactor = yield* startAndSweep(fixture);
+ const settled = commandRan(
+ ThreadId.make("agent"),
+ "gh pr create --fill",
+ "https://github.com/owner/repository/pull/124",
+ );
+ assert.strictEqual(settled.type, "turn-item.updated");
+ if (settled.type !== "turn-item.updated") return;
+
+ const links = yield* linksFrom(fixture, reactor, [
+ { ...settled, payload: { ...settled.payload, status: "running" } },
+ settled,
+ settled,
+ ]);
+
+ assert.deepStrictEqual(
+ links.map((command) => command.number),
+ [124, 124],
+ );
+ assert.strictEqual(links[0]!.commandId, links[1]!.commandId);
+ }).pipe(Effect.provide(fixture.layer));
+ }),
+ ),
+ );
});
diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts
index fb9fa25c6e1..cc322531562 100644
--- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts
+++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts
@@ -1,6 +1,7 @@
import {
CommandId,
isOrchestrationV2WorkActive,
+ type OrchestrationV2TurnItem,
type PullRequestSummary,
type ThreadId,
type ThreadPullRequestKey,
@@ -49,6 +50,127 @@ const isChangeRequestCloseCommand = (command: string) =>
(definition) => definition.changeRequestCloseCommand?.test(command) === true,
);
+// Where a shell starts a command, past `NAME=value` assignments and wrappers like `timeout 60`.
+// A create command anywhere else, as in `echo "gh pr create"`, is text, not a command that runs.
+const COMMAND_START =
+ "(?:^|[;&|({`\\n]|\\b(?:do|then|else)\\s)\\s*(?:(?:\\w+=\\S*|env|time|nohup|timeout\\s+\\S+)\\s+)*";
+const CREATE_COMMANDS = sourceControlDefinitions.definitions.flatMap(
+ ({ kind, changeRequestCreateCommand: command }) =>
+ command === undefined
+ ? []
+ : // The subcommand must end its shell word: `gh pr create#x` runs another one.
+ [
+ {
+ kind,
+ command,
+ run: new RegExp(`${COMMAND_START}${command.source}(?=$|[\\s;&|)])`, "gu"),
+ },
+ ],
+);
+const createCommandCount = (code: string) =>
+ CREATE_COMMANDS.reduce((count, { run }) => count + [...code.matchAll(run)].length, 0);
+
+// Codex runs each command as `/bin/zsh -lc <script>`, quoting the script in pieces such as
+// `"a "'`b`'" c"`.
+const SHELL_WRAPPER = /^\s*(?:\S*\/)?(?:ba|z|da|k)?sh\s+-l?c\s+(?=["'])([\s\S]*)$/u;
+const SHELL_WORD_PIECE = /"((?:\\[\s\S]|[^"\\])*)"|'([^']*)'|\\([\s\S])|(\S)/gu;
+// Heredoc bodies, quoted strings and comments are text a command carries, not commands it runs.
+const HEREDOC_BODY =
+ /<<-?[ \t]*(['"]?)(\w+)\1[^\n]*\n(?:(?:[\s\S]*?\n)?[ \t]*\2[ \t]*(?=\n|$)|[\s\S]*$)/gu;
+const QUOTED_OR_COMMENT = /'[^']*'|"(?:\\[\s\S]|[^"\\])*"|(?<=^|[\s;&|(])#[^\n]*/gmu;
+const COMMAND_SEPARATOR = /&&|\|\||[;|\n]/u;
+// Commands that print other change requests' URLs, so output beside them proves nothing.
+const LISTS_CHANGE_REQUESTS =
+ /\b(?:gh\s+(?:pr\s+(?:list|status)|search\s+prs|api)|glab\s+(?:mr\s+list|api))\b/u;
+const URL_LINE = /^[ \t]*(https?:\/\/\S+)[ \t]*$/gmu;
+
+/** The script a shell input runs, unwrapped from Codex's `sh -lc`. */
+function shellScript(input: string): string {
+ const [, wrapped] = SHELL_WRAPPER.exec(input) ?? [];
+ return wrapped === undefined
+ ? input
+ : Array.from(
+ wrapped.matchAll(SHELL_WORD_PIECE),
+ ([, double, single, escaped, bare]) =>
+ double?.replace(/\\(["\\$`])/gu, "$1") ?? single ?? escaped ?? bare,
+ ).join("");
+}
+
+/** A script split at command separators that sit outside quotes. */
+function shellSegments(script: string): ReadonlyArray<string> {
+ const segments: Array<string> = [];
+ let current = "";
+ let quote: string | null = null;
+ for (let index = 0; index < script.length; index++) {
+ const char = script[index] ?? "";
+ if (quote !== null) {
+ current += char;
+ if (char === "\\" && quote === '"') current += script[++index] ?? "";
+ else if (char === quote) quote = null;
+ continue;
+ }
+ if (char === "'" || char === '"') quote = char;
+ if (char === "\\") {
+ current += char + (script[++index] ?? "");
+ continue;
+ }
+ const pair = script.slice(index, index + 2);
+ if (pair === "&&" || pair === "||" || char === ";" || char === "|" || char === "\n") {
+ segments.push(current);
+ current = "";
+ if (pair === "&&" || pair === "||") index++;
+ continue;
+ }
+ current += char;
+ }
+ segments.push(current);
+ return segments;
+}
+
+/** The commands a script runs, without the text it carries. */
+const shellCode = (script: string) =>
+ script.replace(HEREDOC_BODY, "<<").replace(QUOTED_OR_COMMENT, "''");
+
+type CommandExecution = Extract<OrchestrationV2TurnItem, { readonly type: "command_execution" }>;
+
+/**
+ * The change requests a shell command opened: URLs on lines of their own in the output of a
+ * command that runs a host's create command. One the command also names, as `gh pr view 12`
+ * does, existed before it ran. More URLs than create commands means something else printed
+ * some, such as `gh pr list`, so none are taken.
+ */
+function changeRequestsCreatedBy(input: string, output: string) {
+ if (!CREATE_COMMANDS.some(({ command }) => command.test(input))) return [];
+ const script = shellScript(input);
+ const code = shellCode(script);
+ const creates = createCommandCount(code);
+ if (creates === 0) return [];
+ const otherCommands = code
+ .split(COMMAND_SEPARATOR)
+ .filter((part) => createCommandCount(part) === 0)
+ .join("\n");
+ if (LISTS_CHANGE_REQUESTS.test(otherCommands)) return [];
+ const otherScript = shellSegments(script)
+ .filter((segment) => createCommandCount(shellCode(segment)) === 0)
+ .join("\n");
+ const creators = new Set(
+ CREATE_COMMANDS.filter(({ run }) => code.match(run) !== null).map(({ kind }) => kind),
+ );
+ const created = new Map<string, ThreadPullRequestKey & { readonly url: string }>();
+ for (const [, url = ""] of output.matchAll(URL_LINE)) {
+ const parsed = sourceControlDefinitions.parseChangeRequestUrl(url);
+ // Only the host whose create command ran can have printed a new change request.
+ if (parsed === null || !creators.has(parsed.definition.kind)) continue;
+ const { link } = parsed;
+ const named = new RegExp(`(?:^|(?<=[\\s#/=("']))${link.number}(?=$|[\\s);&|/"'])`, "u");
+ // Quoted text in the other commands counts, as in `printf '.../pull/12'`.
+ if (named.test(otherScript)) continue;
+ const key = normalizeThreadPullRequestKey(link);
+ created.set(threadPullRequestKeyOf(key), { ...key, url });
+ }
+ return created.size > creates ? [] : [...created.values()];
+}
+
const isPullRequestProviderError = Schema.is(PullRequestProviderError);
type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
@@ -500,6 +622,34 @@ export const make = Effect.gen(function* () {
Effect.catchCause(logSkipped("pull request refresh after run skipped", { threadId })),
);
+ // An agent that opens a pull request from a shell gets it linked as link_pull_request would.
+ const linkCreatedChangeRequests = Effect.fn("PullRequestSyncReactor.linkCreatedChangeRequests")(
+ function* (threadId: ThreadId, item: CommandExecution) {
+ if (isOrchestrationV2WorkActive(item.status)) return;
+ yield* Effect.forEach(
+ changeRequestsCreatedBy(item.input, item.output ?? ""),
+ (created) =>
+ engine
+ .dispatch({
+ type: "thread.pull-request.link",
+ // Stable per command, so a repeated settlement cannot relink one the user unlinked.
+ commandId: CommandId.make(
+ `server:pr-created-link:${threadId}:${item.id}:${threadPullRequestKeyOf(created)}`,
+ ),
+ threadId,
+ ...created,
+ source: "created",
+ })
+ .pipe(
+ Effect.catchCause(
+ logSkipped("linking a pull request a command created failed", { threadId }),
+ ),
+ ),
+ { discard: true },
+ );
+ },
+ );
+
const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
"PullRequestSyncReactor.start",
)(function* () {
@@ -532,14 +682,14 @@ export const make = Effect.gen(function* () {
// ends. Read again when the run ends, since `merge --auto` returns before it merges.
case "turn-item.updated": {
const item = event.payload;
- if (item.type !== "command_execution" || !isChangeRequestCloseCommand(item.input)) {
- return Effect.void;
- }
+ if (item.type !== "command_execution") return Effect.void;
+ const linked = linkCreatedChangeRequests(event.threadId, item);
+ if (!isChangeRequestCloseCommand(item.input)) return linked;
const ended = closeCommands.get(event.threadId) ?? new Set<string>();
closeCommands.set(event.threadId, ended);
- if (isOrchestrationV2WorkActive(item.status) || ended.has(item.id)) return Effect.void;
+ if (isOrchestrationV2WorkActive(item.status) || ended.has(item.id)) return linked;
ended.add(item.id);
- return refreshOpenLinks(event.threadId);
+ return Effect.andThen(linked, refreshOpenLinks(event.threadId));
}
case "run.updated":
return isTerminalRunStatus(event.payload.status) && closeCommands.delete(event.threadId)
diff --git a/docs/user/source-control.md b/docs/user/source-control.md
index de63202c51e..57d512dcb3b 100644
--- a/docs/user/source-control.md
+++ b/docs/user/source-control.md
@@ -266,8 +266,9 @@ and their marks follow the same rules as on web and desktop.
A thread can hold several pull requests, including reviews from another repository on the same host.
Use **Link pull request** in the command palette or **Linked pull requests** panel, or right-click a
-pull request link in the conversation. Creating a pull request from Git actions links it automatically.
-Agents can link their pull requests with the `link_pull_request` tool.
+pull request link in the conversation. Creating a pull request from Git actions links it automatically,
+and so does an agent creating one with `gh pr create` or `glab mr create`. Agents can link other
+pull requests with the `link_pull_request` tool.
Use **Link this PR** in a branch-detected badge's tooltip to keep it with the thread. From a review
on the Pull Requests page, **Link to thread** lets you search for an active thread. The review header
diff --git a/packages/source-control-core/src/shared/definition.ts b/packages/source-control-core/src/shared/definition.ts
index 5be147af6b4..6a9f3d23bc6 100644
--- a/packages/source-control-core/src/shared/definition.ts
+++ b/packages/source-control-core/src/shared/definition.ts
@@ -234,6 +234,11 @@ export interface SourceControlDefinition {
* sends T3 no notification of its own. Absent for a host with no such CLI.
*/
readonly changeRequestCloseCommand?: RegExp;
+ /**
+ * Matches a shell command that opens a change request with this host's CLI and prints its URL
+ * on a line of its own. Absent for a host with no such CLI.
+ */
+ readonly changeRequestCreateCommand?: RegExp;
readonly authorProfileUrl: (login: string, repositoryUrl: string) => string | null;
/**
* The references this host's own renderer links in plain text, such as `#12` or a commit SHA,
diff --git a/packages/source-control-github/src/shared/definition.ts b/packages/source-control-github/src/shared/definition.ts
index 5d93895315e..170395bb7ee 100644
--- a/packages/source-control-github/src/shared/definition.ts
+++ b/packages/source-control-github/src/shared/definition.ts
@@ -105,6 +105,7 @@ export const definition = defineSourceControl({
] as const),
checkoutCommand: ({ number }) => `gh pr checkout ${number}`,
changeRequestCloseCommand: /\bgh\s+(?:pr\s+(?:merge|close)|stack\s+merge)\b/u,
+ changeRequestCreateCommand: /\bgh\s+pr\s+create\b/u,
authorProfileUrl: (login, repositoryUrl) =>
login.endsWith("[bot]")
? null
diff --git a/packages/source-control-gitlab/src/shared/definition.ts b/packages/source-control-gitlab/src/shared/definition.ts
index 14ef165f03b..1a3c417641c 100644
--- a/packages/source-control-gitlab/src/shared/definition.ts
+++ b/packages/source-control-gitlab/src/shared/definition.ts
@@ -53,6 +53,7 @@ export const definition = defineSourceControl({
] as const),
checkoutCommand: ({ number }) => `glab mr checkout ${number}`,
changeRequestCloseCommand: /\bglab\s+mr\s+(?:merge|close)\b/u,
+ changeRequestCreateCommand: /\bglab\s+mr\s+create\b/u,
authorProfileUrl: () => null,
reviewSummaryRequired: () => false,
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,