:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): add gh_stack tool so cloud runs can build stacked PRs (#87683)
Alessandro Pogliaghi1678f05ec8b4
diff --git a/.agents/skills/stacking-prs/SKILL.md b/.agents/skills/stacking-prs/SKILL.mdindex 3a14e7b2701b..60d893b92a4f 100644--- a/.agents/skills/stacking-prs/SKILL.md+++ b/.agents/skills/stacking-prs/SKILL.md@@ -24,6 +24,21 @@ gh extension install github/gh-stack # or: gh extension upgrade stackUpstream docs: [about stacked PRs](https://docs.github.com/en/pull-requests/get-started/about-stacked-prs), [CLI commands](https://docs.github.com/en/pull-requests/reference/stacked-prs-cli-commands).+## In a cloud task sandbox, use `gh_stack` instead++The rest of this skill assumes a developer machine.+Cloud task runs block `git commit` and `git push` so unsigned commits cannot leave the sandbox, which takes out every `gh stack` command that publishes a stack — `submit`, `sync`, `push`, and `link` with branch arguments all push, and `gh stack add -m` commits.++There, build the stack from the signed-commit tooling and link it with the `gh_stack` MCP tool, which drives GitHub's Stacks REST API and never pushes:++1. Commit each layer with `git_signed_commit`, passing a new `branch` — the checkout already sits on the layer below, so the branch starts there.+2. Open each layer's PR with `gh pr create --base <branch of the layer below>`.+3. Link them with `gh_stack`, operation `create`, passing `pull_requests` bottom to top.++To restack a layer: check that layer out, `git rebase <its parent branch>`, then republish it with `git_signed_rewrite` passing `onto` = the parent branch.+`gh stack rebase` still does the rebase itself, but nothing may publish the result — `gh stack push` and `gh stack sync` both push.+`git_signed_rewrite` replays whatever local HEAD points at and uses `branch` only to pick which remote ref moves, so the layer has to be the checked-out branch or you publish the wrong history to it.+## Create a stack```bashdiff --git a/products/desktop/packages/agent/src/adapters/local-tools/index.ts b/products/desktop/packages/agent/src/adapters/local-tools/index.tsindex a797c86cf1e3..d894bd5bdcc1 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/index.ts+++ b/products/desktop/packages/agent/src/adapters/local-tools/index.ts@@ -1,6 +1,7 @@import type { LocalTool, LocalToolCtx, LocalToolGateMeta } from "./registry";import { cloneRepoTool } from "./tools/clone-repo";import { finishTool } from "./tools/finish";+import { ghStackTool } from "./tools/gh-stack";import { listAgentsTool } from "./tools/list-agents";import { listReposTool } from "./tools/list-repos";import { reportInsightTool } from "./tools/report-insight";@@ -26,6 +27,7 @@ export const LOCAL_TOOLS: LocalTool[] = [signedCommitTool,signedMergeTool,signedRewriteTool,+ ghStackTool,listReposTool,cloneRepoTool,speakTool,diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/gh-stack.test.ts b/products/desktop/packages/agent/src/adapters/local-tools/tools/gh-stack.test.tsnew file mode 100644index 000000000000..ccacbfe3737e--- /dev/null+++ b/products/desktop/packages/agent/src/adapters/local-tools/tools/gh-stack.test.ts@@ -0,0 +1,126 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const createStack = vi.fn();+const extendStack = vi.fn();+const getStack = vi.fn();+const fetchPullRequestRefs = vi.fn();+const unstack = vi.fn();++vi.mock("@posthog/git/stacks", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@posthog/git/stacks")>();+ return {+ ...actual,+ createStack: (...args: unknown[]) => createStack(...args),+ extendStack: (...args: unknown[]) => extendStack(...args),+ getStack: (...args: unknown[]) => getStack(...args),+ fetchPullRequestRefs: (...args: unknown[]) => fetchPullRequestRefs(...args),+ unstack: (...args: unknown[]) => unstack(...args),+ };+});++const { ghStackTool } = await import("./gh-stack");++const CTX = { cwd: "/tmp/workspace/repos/posthog/posthog", token: "ghs_x" };++describe("gh_stack tool handler", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it.each([+ {+ name: "create with a single pull request",+ args: { operation: "create", pull_requests: [1] },+ expected: "at least 2 PR number(s)",+ },+ {+ name: "create with no pull requests at all",+ args: { operation: "create" },+ expected: "at least 2 PR number(s)",+ },+ {+ name: "create listing the same pull request twice",+ args: { operation: "create", pull_requests: [1, 1] },+ expected: "same PR twice",+ },+ {+ name: "extend without a stack number",+ args: { operation: "extend", pull_requests: [3] },+ expected: "needs `stack`",+ },+ {+ name: "unstack without a stack number",+ args: { operation: "unstack" },+ expected: "needs `stack`",+ },+ ])("refuses $name locally", async ({ args, expected }) => {+ const result = await ghStackTool.handler(CTX, args);++ expect(result.isError).toBe(true);+ expect(result.content[0].text).toContain(expected);+ expect(createStack).not.toHaveBeenCalled();+ expect(extendStack).not.toHaveBeenCalled();+ expect(unstack).not.toHaveBeenCalled();+ });++ it("refuses to link a chain whose layers do not target each other", async () => {+ fetchPullRequestRefs.mockResolvedValue([+ { number: 1, headRef: "posthog/db", baseRef: "master" },+ { number: 2, headRef: "posthog/api", baseRef: "master" },+ ]);++ const result = await ghStackTool.handler(CTX, {+ operation: "create",+ pull_requests: [1, 2],+ });++ expect(result.isError).toBe(true);+ expect(result.content[0].text).toContain("Retarget #2 onto that branch");+ expect(result.content[0].text).toContain("posthog/db");+ expect(createStack).not.toHaveBeenCalled();+ });++ it("validates an extension against the stack's current top layer", async () => {+ getStack.mockResolvedValue({+ pull_requests: [{ number: 1 }, { number: 2 }],+ });+ fetchPullRequestRefs.mockResolvedValue([+ { number: 2, headRef: "posthog/api", baseRef: "posthog/db" },+ { number: 3, headRef: "posthog/ui", baseRef: "posthog/api" },+ ]);+ extendStack.mockResolvedValue({+ number: 50,+ base: { ref: "master" },+ open: true,+ pull_requests: [],+ });++ await ghStackTool.handler(CTX, {+ operation: "extend",+ stack: 50,+ pull_requests: [3],+ });++ expect(fetchPullRequestRefs).toHaveBeenCalledWith(+ expect.anything(),+ [2, 3],+ );+ expect(extendStack).toHaveBeenCalledWith(expect.anything(), 50, [3]);+ });++ it("surfaces an API failure as a tool error rather than throwing", async () => {+ fetchPullRequestRefs.mockResolvedValue([+ { number: 1, headRef: "posthog/db", baseRef: "master" },+ { number: 2, headRef: "posthog/api", baseRef: "posthog/db" },+ ]);+ createStack.mockRejectedValue(new Error("Creating the stack failed: 403"));++ const result = await ghStackTool.handler(CTX, {+ operation: "create",+ pull_requests: [1, 2],+ });++ expect(result.isError).toBe(true);+ expect(result.content[0].text).toBe("Creating the stack failed: 403");+ });+});diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/gh-stack.ts b/products/desktop/packages/agent/src/adapters/local-tools/tools/gh-stack.tsnew file mode 100644index 000000000000..795a3949df83--- /dev/null+++ b/products/desktop/packages/agent/src/adapters/local-tools/tools/gh-stack.ts@@ -0,0 +1,189 @@+import {+ createStack,+ extendStack,+ fetchPullRequestRefs,+ formatStack,+ getStack,+ listStacks,+ MAX_STACK_PULL_REQUESTS,+ MIN_STACK_SIZE,+ type StackCtx,+ summarizeStackList,+ unstack,+ validateStackChain,+} from "@posthog/git/stacks";+import { z } from "zod";+import type {+ SignedCommitToolCtx,+ SignedCommitToolResult,+} from "../../signed-commit-shared";+import { qualifiedLocalToolName } from "../registry";+import { defineSignedGitTool } from "./signed-git-tool";++export const GH_STACK_TOOL_NAME = "gh_stack";+export const GH_STACK_QUALIFIED_TOOL_NAME =+ qualifiedLocalToolName(GH_STACK_TOOL_NAME);++export const GH_STACK_TOOL_DESCRIPTION =+ "Manage GitHub native stacked pull requests — an ordered chain where each PR targets the " ++ "branch of the PR below it. Use this instead of the `gh stack` CLI, whose publishing " ++ "commands (`submit`, `sync`, `push`, `link`) all run `git push` and are therefore blocked " ++ "here. Build the layers first: commit each one with `git_signed_commit` (passing `branch`), " ++ "then open its PR with `gh pr create --base <branch of the layer below>`. Then call this " ++ 'with operation "create" and the PR numbers ordered bottom to top to link them into a ' ++ 'stack. "extend" appends new layers to an existing stack, "view" reads stacks, and ' ++ '"unstack" detaches the unmerged layers. Never merges anything.';++export const ghStackToolSchema = {+ operation: z+ .enum(["view", "create", "extend", "unstack"])+ .describe(+ 'What to do: "view" reads a stack (or lists the repo\'s stacks), "create" links pull ' ++ 'requests into a new stack, "extend" appends to one, "unstack" dissolves one.',+ ),+ pull_requests: z+ .array(z.number().int().positive())+ .optional()+ .describe(+ 'PR numbers ordered bottom to top. Required for "create" (every layer, at least two) ' ++ 'and "extend" (only the new layers). For "view", a single number finds the stack ' ++ "containing that PR.",+ ),+ stack: z+ .number()+ .int()+ .positive()+ .optional()+ .describe(+ 'Stack number, as shown on the PR. Required for "extend" and "unstack"; optional for ' ++ '"view", which lists every stack in the repository without it.',+ ),+ cwd: z+ .string()+ .optional()+ .describe(+ "Path to the git checkout whose origin remote names the repository; defaults to the " ++ "session's working directory. Relative paths resolve against the session cwd.",+ ),+};++interface GhStackInput {+ operation: "view" | "create" | "extend" | "unstack";+ pull_requests?: number[];+ stack?: number;+}++function ok(text: string): SignedCommitToolResult {+ return { content: [{ type: "text", text }] };+}++function fail(text: string): SignedCommitToolResult {+ return { content: [{ type: "text", text }], isError: true };+}++function checkPayload(+ prs: readonly number[],+ minimum: number,+ operation: string,+): string | null {+ if (prs.length < minimum) {+ return (+ `${GH_STACK_TOOL_NAME} "${operation}" needs \`pull_requests\` with at least ` ++ `${minimum} PR number(s), ordered bottom to top.`+ );+ }+ if (prs.length > MAX_STACK_PULL_REQUESTS) {+ return `A stack takes at most ${MAX_STACK_PULL_REQUESTS} pull requests.`;+ }+ if (new Set(prs).size !== prs.length) {+ return "`pull_requests` contains the same PR twice; a stack is a linear chain.";+ }+ return null;+}++async function checkChain(+ ctx: StackCtx,+ chain: readonly number[],+): Promise<string | null> {+ const refs = await fetchPullRequestRefs(ctx, chain);+ return validateStackChain(refs);+}++async function runGhStack(+ ctx: SignedCommitToolCtx,+ input: GhStackInput,+): Promise<SignedCommitToolResult> {+ const stackCtx: StackCtx = { cwd: ctx.cwd, token: ctx.token };+ const prs = input.pull_requests ?? [];+ try {+ switch (input.operation) {+ case "view": {+ if (input.stack !== undefined) {+ return ok(formatStack(await getStack(stackCtx, input.stack)));+ }+ const stacks = await listStacks(stackCtx, prs[0]);+ if (prs[0] === undefined) return ok(summarizeStackList(stacks));+ return ok(+ stacks.length === 0+ ? `No stack contains #${prs[0]}.`+ : stacks.map(formatStack).join("\n\n"),+ );+ }+ case "create": {+ const problem =+ checkPayload(prs, MIN_STACK_SIZE, "create") ??+ (await checkChain(stackCtx, prs));+ if (problem) return fail(problem);+ return ok(+ `Created the stack.\n${formatStack(await createStack(stackCtx, prs))}`,+ );+ }+ case "extend": {+ if (input.stack === undefined) {+ return fail(+ `${GH_STACK_TOOL_NAME} "extend" needs \`stack\`, the number of the stack to append to.`,+ );+ }+ const payloadProblem = checkPayload(prs, 1, "extend");+ if (payloadProblem) return fail(payloadProblem);+ const top = (await getStack(stackCtx, input.stack)).pull_requests.at(+ -1,+ );+ const problem = await checkChain(+ stackCtx,+ top ? [top.number, ...prs] : prs,+ );+ if (problem) return fail(problem);+ return ok(+ `Extended the stack.\n${formatStack(+ await extendStack(stackCtx, input.stack, prs),+ )}`,+ );+ }+ case "unstack": {+ if (input.stack === undefined) {+ return fail(+ `${GH_STACK_TOOL_NAME} "unstack" needs \`stack\`, the number of the stack to dissolve.`,+ );+ }+ const remaining = await unstack(stackCtx, input.stack);+ return ok(+ remaining === null+ ? `Dissolved stack #${input.stack}.`+ : `Detached the unmerged layers; merged or queued ones stay.\n${formatStack(remaining)}`,+ );+ }+ }+ } catch (err) {+ return fail(err instanceof Error ? err.message : String(err));+ }+}++export const ghStackTool = defineSignedGitTool({+ name: GH_STACK_TOOL_NAME,+ description: GH_STACK_TOOL_DESCRIPTION,+ schema: ghStackToolSchema,+ // Few runs stack, so keep the schema out of every cloud run's context.+ alwaysLoad: false,+ run: runGhStack,+});diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-git-tool.ts b/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-git-tool.tsindex cdeae219d0ec..bffff228faa2 100644--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-git-tool.ts+++ b/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-git-tool.ts@@ -9,22 +9,23 @@ import type {import { defineLocalTool, type LocalTool } from "../registry";/**- * Factory for the cloud-only signed-git tools (git_signed_commit / git_signed_rewrite).- * Resolves the token lazily (live /tmp/agent-env first, so a mid-session credential- * refresh takes effect) and the optional `cwd` arg against the session cwd, then- * delegates to the tool's `run`. Kept past ToolSearch via alwaysLoad.+ * Factory for the cloud-only GitHub tools (git_signed_commit / git_signed_rewrite /+ * gh_stack). Resolves the token lazily (live /tmp/agent-env first, so a mid-session+ * credential refresh takes effect) and the optional `cwd` arg against the session cwd,+ * then delegates to the tool's `run`. Kept past ToolSearch via alwaysLoad by default.*/export function defineSignedGitTool<S extends z.ZodRawShape, R>(opts: {name: string;description: string;schema: S;+ alwaysLoad?: boolean;run: (ctx: SignedCommitToolCtx, input: R) => Promise<SignedCommitToolResult>;}): LocalTool {return defineLocalTool({name: opts.name,description: opts.description,schema: opts.schema,- alwaysLoad: true,+ alwaysLoad: opts.alwaysLoad ?? true,isEnabled: (_ctx, meta) => isCloudRun(meta),handler: (ctx, args) => {const token = resolveGithubToken() ?? ctx.token;diff --git a/products/desktop/packages/agent/src/adapters/signed-commit-shared.ts b/products/desktop/packages/agent/src/adapters/signed-commit-shared.tsindex 0988547e4bc3..8ae30fcde5c5 100644--- a/products/desktop/packages/agent/src/adapters/signed-commit-shared.ts+++ b/products/desktop/packages/agent/src/adapters/signed-commit-shared.ts@@ -69,14 +69,21 @@ export const SIGNED_REWRITE_TOOL_DESCRIPTION ="of `git push --force`. First rebase locally with normal `git` (resolving conflicts and " +"finishing with `git rebase --continue`, NOT `git commit`); then call this to republish the " +"branch's commits as Verified and atomically move the remote branch onto them. Use this to " +- "update an existing PR after a rebase or conflict fix. Rewrites the current branch by default. " ++ "update an existing PR after a rebase or conflict fix. The commits always come from your " ++ "local HEAD, so check out the branch you are rewriting first: `branch` only picks which " ++ "remote ref moves, and calling this from another checkout publishes that checkout's history " ++ "to `branch`. Defaults to the current branch. " +"Histories containing merge commits are refused — rebase (which flattens merges) first.";export const signedRewriteToolSchema = {branch: z.string().optional()- .describe("Branch to rewrite; defaults to the current branch."),+ .describe(+ "Remote branch to move; defaults to the current branch. This picks the ref to update, " ++ "NOT the history to publish — the commits come from your local HEAD either way, so " ++ "check the branch out before rewriting it.",+ ),onto: z.string().optional()diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.tsindex c794c2881378..6d3b48098917 100644--- a/products/desktop/packages/agent/src/server/agent-server.test.ts+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts@@ -4853,7 +4853,8 @@ describe("AgentServer HTTP Mode", () => {const s = createServer();const prompt = (s as unknown as TestableServer).buildCloudSystemPrompt();expect(prompt).toContain("gh pr create --draft`");- expect(prompt).not.toContain("--base");+ // Scoped to the create command; other sections mention the flag legitimately.+ expect(prompt).not.toContain("gh pr create --draft --base");delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;});diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex e7a8a01624b6..f0c9a16fa84b 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -60,6 +60,7 @@ import {classifyAgentError,isPromptTooLongError,} from "../adapters/error-classification";+import { GH_STACK_QUALIFIED_TOOL_NAME } from "../adapters/local-tools/tools/gh-stack";import { isSupportedReasoningEffort } from "../adapters/reasoning-effort";import { appendRtkGuidanceForCodex } from "../adapters/rtk-guidance";import {@@ -4087,6 +4088,30 @@ we want:Generated-By: PostHog DesktopTask-Id: ${taskId}`;+ // A stack is several PRs, so this would contradict the review-first modes.+ const stackInstructions = shouldAutoCreatePr+ ? `+## Stacked pull requests+Stack only when the layers are independently reviewable (schema, then backend, then UI) or the+user asked for a stack. Keep stacks shallow — 2 to 4 layers. One PR remains the default.+Do NOT use the \`gh stack\` CLI: its publishing commands (\`submit\`, \`sync\`, \`push\`, \`link\`)+all run \`git push\`, which is blocked here. Build the stack this way instead:+1. Commit the bottom layer with \`git_signed_commit\`, passing \`branch\`, then open its pull+ request based on the base branch.+2. For each layer above, commit with \`git_signed_commit\` and a new \`branch\` — your checkout+ already sits on the layer below, so the branch starts there — then open its pull request+ based on the branch of the layer below (\`--base <that branch>\`).+3. Link them with the \`gh_stack\` tool (full name \`${GH_STACK_QUALIFIED_TOOL_NAME}\`),+ operation "create", passing \`pull_requests\` bottom to top. Every layer must target the+ branch of the one below it, or the link is refused.+When a lower layer changes, restack the layers above it bottom-first. For each layer: check+that layer out, \`git rebase <its parent branch>\`, then republish it with+\`git_signed_rewrite\` passing \`onto\` = the parent branch. Check the layer out every time —+\`git_signed_rewrite\` replays whatever your local HEAD points at and uses \`branch\` only to+pick which remote ref moves, so rewriting from the wrong checkout publishes the wrong history+to that layer.`+ : "";+const prLinkInstructions = `## Referencing pull requestsWhen you mention a pull request in any reply or summary, always hyperlink it to its full URL@@ -4106,7 +4131,7 @@ Optimize for the fewest shell round trips.When you create a non-code file the user should be able to download (such as a report, chart, image, archive, or data file), call the \`upload_artifact\` tool with its path before your final reply. In your final reply, link to the download URL returned by the tool—never link to the file's local workspace path. Files left in the workspace don't reach the user. Don't upload source code or repository changes—those belong in a commit or PR.`;// Closes out every branch below, so a new section is added once rather than five times.- const commonInstructions = `${signedCommitInstructions}${prLinkInstructions}${shellEfficiencyInstructions}${artifactInstructions}${this.buildSlackDeliveryInstructions()}${this.buildSourceControlAccessInstructions()}`;+ const commonInstructions = `${signedCommitInstructions}${stackInstructions}${prLinkInstructions}${shellEfficiencyInstructions}${artifactInstructions}${this.buildSlackDeliveryInstructions()}${this.buildSourceControlAccessInstructions()}`;const whyContextInstruction = ` - Add a brief **Why** to the body — one or two sentences capturing the reason the user asked for this change (the motivation, not a restatement of the diff). Keep it short.`;const publicRepoSafetyInstruction = ` - **Public-repo safety.** Treat the target repository as public-readable unless you have verified otherwise. The PR title, description, and commit messages must not contain private operational scale (exact event counts, internal row volumes, customer-usage percentages), customer names / emails / companies, references to internal tickets or incidents, the contents of Slack threads (do not quote or paraphrase what was said), or unreleased roadmap details. Linking to the originating Slack thread is fine and encouraged — Slack links are auth-gated and useful as context — as are channel references like "raised in #team-foo". Describe findings qualitatively ("present on nearly all X events, absent from Y") rather than with quantitative figures pulled from analytics queries — the reasoning that uses those numbers can stay in the thread; the PR copy cannot.`;diff --git a/products/desktop/packages/git/src/gh.test.ts b/products/desktop/packages/git/src/gh.test.tsindex 901f624c86fe..458583744227 100644--- a/products/desktop/packages/git/src/gh.test.ts+++ b/products/desktop/packages/git/src/gh.test.ts@@ -76,4 +76,25 @@ describe("execGhWithRetry", () => {expect(res.exitCode).toBe(1);expect(exec).toHaveBeenCalledTimes(1);});++ // Dropping `options.input` on a retry would send an empty body, not fail.+ it("re-sends the same request body on a retried attempt", async () => {+ const exec = vi+ .fn()+ .mockResolvedValueOnce(result({ stderr: "gh: HTTP 502" }))+ .mockResolvedValueOnce(result({ stdout: "ok", exitCode: 0 }));+ const options = { input: JSON.stringify({ pull_requests: [1, 2] }) };++ await execGhWithRetry(+ ["api", "-X", "POST"],+ options,+ { backoffMs: 0 },+ exec,+ );++ expect(exec).toHaveBeenCalledTimes(2);+ for (const call of exec.mock.calls) {+ expect(call[1]).toMatchObject({ input: options.input });+ }+ });});diff --git a/products/desktop/packages/git/src/signed-commit.ts b/products/desktop/packages/git/src/signed-commit.tsindex 43b4f485ad7a..955f85f2a499 100644--- a/products/desktop/packages/git/src/signed-commit.ts+++ b/products/desktop/packages/git/src/signed-commit.ts@@ -188,8 +188,8 @@ export function operationInProgressError(op: GitOperationInProgress): string {);}-async function resolveRepoNameWithOwner(ctx: SignedCommitCtx): Promise<string> {- const url = await gitText(["remote", "get-url", "origin"], ctx.cwd);+export async function resolveRepoNameWithOwner(cwd: string): Promise<string> {+ const url = await gitText(["remote", "get-url", "origin"], cwd);const parsed = parseGithubUrl(url);if (!parsed) {throw new Error(`Could not parse owner/repo from origin remote: ${url}`);@@ -836,7 +836,7 @@ export async function createSignedCommit(// Repo (from origin remote) and branch (from HEAD) are independent reads.const [repo, branch] = await Promise.all([- resolveRepoNameWithOwner(ctx),+ resolveRepoNameWithOwner(ctx.cwd),resolveBranchName(ctx, input),]);@@ -941,7 +941,7 @@ export async function createSignedRewrite(input: SignedRewriteInput,): Promise<SignedCommitResult> {const [repo, branch] = await Promise.all([- resolveRepoNameWithOwner(ctx),+ resolveRepoNameWithOwner(ctx.cwd),resolveBranchName(ctx, { message: "", branch: input.branch }),]);@@ -1121,7 +1121,7 @@ export async function createSignedMerge(}const [repo, branch] = await Promise.all([- resolveRepoNameWithOwner(ctx),+ resolveRepoNameWithOwner(ctx.cwd),resolveBranchName(ctx, { message: "", branch: input.branch }),]);diff --git a/products/desktop/packages/git/src/stacks.test.ts b/products/desktop/packages/git/src/stacks.test.tsnew file mode 100644index 000000000000..f18c97ebf3b9--- /dev/null+++ b/products/desktop/packages/git/src/stacks.test.ts@@ -0,0 +1,182 @@+import { describe, expect, it } from "vitest";+import type { GhExecResult } from "./gh";+import {+ formatStack,+ type PullRequestRefs,+ type Stack,+ stacksApiError,+ summarizeStackList,+ validateStackChain,+} from "./stacks";++function refs(+ number: number,+ headRef: string,+ baseRef: string,+): PullRequestRefs {+ return { number, headRef, baseRef };+}++describe("validateStackChain", () => {+ it.each([+ {+ name: "accepts a chain where each layer targets the one below it",+ prs: [+ refs(1, "posthog/db", "master"),+ refs(2, "posthog/api", "posthog/db"),+ refs(3, "posthog/ui", "posthog/api"),+ ],+ expected: null,+ },+ {+ name: "accepts a single layer, which cannot break a chain",+ prs: [refs(1, "posthog/db", "master")],+ expected: null,+ },+ {+ name: "rejects a layer opened against the base branch instead of its parent",+ prs: [refs(1, "posthog/db", "master"), refs(2, "posthog/api", "master")],+ expected:+ "#2 targets 'master', but the layer below it (#1) is on 'posthog/db'. " ++ "Every layer must target the branch of the layer below it. " ++ "Retarget #2 onto that branch with `gh pr edit`, then retry.",+ },+ ])("$name", ({ prs, expected }) => {+ expect(validateStackChain(prs)).toBe(expected);+ });++ // Guards against someone restoring the convenient copy-pastable command.+ it("keeps a ref out of any runnable command", () => {+ const problem = validateStackChain([+ refs(1, "feat/x;whoami", "master"),+ refs(2, "posthog/api", "master"),+ ]);+ expect(problem).toContain("feat/x;whoami");+ expect(problem).not.toContain("--base feat/x;whoami");+ });++ it("reports the lowest break when several layers are misaligned", () => {+ const problem = validateStackChain([+ refs(1, "posthog/db", "master"),+ refs(2, "posthog/api", "master"),+ refs(3, "posthog/ui", "master"),+ ]);+ expect(problem).toContain("#2 targets 'master'");+ expect(problem).not.toContain("#3");+ });+});++describe("stacksApiError", () => {+ function result(partial: Partial<GhExecResult>): GhExecResult {+ return { stdout: "", stderr: "", exitCode: 1, ...partial };+ }++ it("explains that a 404 means stacks are off for the repo, not a bad URL", () => {+ const message = stacksApiError(+ result({ stderr: "gh: HTTP 404" }),+ "Creating the stack",+ );+ expect(message).toContain("Creating the stack failed");+ expect(message).toContain("not");+ expect(message).toContain("enabled for this repository");+ });++ it("passes other failures through verbatim so the API's reason survives", () => {+ expect(+ stacksApiError(+ result({ stderr: "gh: HTTP 422 - base ref mismatch" }),+ "Creating the stack",+ ),+ ).toBe("Creating the stack failed: gh: HTTP 422 - base ref mismatch");+ });+});++describe("formatStack", () => {+ const stack: Stack = {+ id: 9,+ number: 50,+ url: "https://api.github.com/repos/x/y/stacks/50",+ base: { ref: "master" },+ open: true,+ pull_requests: [+ {+ number: 11,+ state: "open",+ draft: false,+ merged_at: "2026-08-01T00:00:00Z",+ head: { ref: "posthog/db", sha: "a1" },+ },+ {+ number: 12,+ state: "open",+ draft: true,+ merged_at: null,+ head: { ref: "posthog/api", sha: "b2" },+ },+ ],+ };++ // The agent reads this order back to build the create/extend payload.+ it("numbers the layers bottom to top and marks merged and draft ones", () => {+ expect(formatStack(stack)).toBe(+ "Stack #50 onto master (open), bottom to top:\n" ++ " 1. #11 posthog/db — merged\n" ++ " 2. #12 posthog/api — draft",+ );+ });+});++describe("summarizeStackList", () => {+ function stacks(open: number, closed: number): Stack[] {+ return Array.from({ length: open + closed }, (_, i) => ({+ id: i,+ number: i + 1,+ url: "",+ base: { ref: "master" },+ open: i < open,+ pull_requests: [],+ }));+ }++ // A cut the agent cannot see reads as the whole repository.+ it.each([+ { name: "says nothing when everything is shown", list: stacks(3, 0) },+ {+ name: "names the closed stacks it dropped",+ list: stacks(3, 7),+ expected: "7 closed",+ },+ {+ name: "names the open stacks past the cap",+ list: stacks(25, 0),+ expected: "5 more open",+ },+ {+ name: "names both when it drops open and closed stacks",+ list: stacks(25, 7),+ expected: "5 more open, 7 closed",+ },+ ])("$name", ({ list, expected }) => {+ const text = summarizeStackList(list);+ if (expected === undefined) {+ expect(text).not.toContain("Not shown");+ return;+ }+ expect(text).toContain(`Not shown: ${expected}.`);+ });++ it.each([+ {+ name: "no stacks at all",+ list: [],+ expected: "No stacks in this repository.",+ },+ {+ name: "stacks exist but none are open",+ list: stacks(0, 4),+ expected: "No open stacks in this repository.",+ },+ ])("reports $name", ({ list, expected }) => {+ expect(summarizeStackList(list)).toContain(expected);+ });+});diff --git a/products/desktop/packages/git/src/stacks.ts b/products/desktop/packages/git/src/stacks.tsnew file mode 100644index 000000000000..bd863370cc94--- /dev/null+++ b/products/desktop/packages/git/src/stacks.ts@@ -0,0 +1,260 @@+import { mapWithConcurrency } from "./concurrency";+import { execGhWithRetry, type GhExecResult } from "./gh";+import { ghTokenEnv, resolveRepoNameWithOwner } from "./signed-commit";++/**+ * GitHub native stacked pull requests, driven through the Stacks REST API.+ * The `gh stack` CLI cannot drive one from the cloud sandbox: everything that+ * publishes a stack pushes, and pushing is blocked there. These endpoints only+ * link pull requests that already exist.+ */++const STACKS_API_TIMEOUT_MS = 30_000;++// Matches the staged-blob read limit in signed-commit.ts.+const PR_REF_CONCURRENCY = 16;++// An active repository holds hundreds of stacks — ~10k tokens unrendered.+const STACK_LIST_LIMIT = 20;++export const MIN_STACK_SIZE = 2;+export const MAX_STACK_PULL_REQUESTS = 100;++export interface StackCtx {+ cwd: string;+ token: string;+}++export interface StackPullRequest {+ number: number;+ state: string;+ draft: boolean;+ merged_at: string | null;+ head: { ref: string; sha: string };+}++export interface Stack {+ id: number;+ number: number;+ url: string;+ base: { ref: string };+ open: boolean;+ /** Ordered bottom to top. */+ pull_requests: StackPullRequest[];+}++export interface PullRequestRefs {+ number: number;+ headRef: string;+ baseRef: string;+}++/**+ * Every layer must target the head branch of the layer below it. Checked here+ * because GitHub answers a broken chain with an opaque 422. Layers come bottom+ * to top, with the existing top layer first when extending.+ */+export function validateStackChain(+ prs: readonly PullRequestRefs[],+): string | null {+ for (let i = 1; i < prs.length; i++) {+ const below = prs[i - 1];+ const above = prs[i];+ if (above.baseRef === below.headRef) continue;+ // Names the branch as data, not a runnable command: refs may legally hold+ // `;`, `$()`, and backticks, and an agent runs what it is handed.+ return (+ `#${above.number} targets '${above.baseRef}', but the layer below it (#${below.number}) ` ++ `is on '${below.headRef}'. Every layer must target the branch of the layer below it. ` ++ `Retarget #${above.number} onto that branch with \`gh pr edit\`, then retry.`+ );+ }+ return null;+}++/** A 404 means the repo has stacks turned off far more often than a bad URL. */+export function stacksApiError(res: GhExecResult, action: string): string {+ const detail = (res.stderr || res.error || res.stdout).trim();+ if (/HTTP 404/.test(detail)) {+ return (+ `${action} failed: the Stacks API returned 404. Either stacked pull requests are not ` ++ `enabled for this repository, or the stack number does not exist. Do not retry without ` ++ `checking which — \`gh_stack\` with operation "view" lists the repository's stacks.`+ );+ }+ return `${action} failed: ${detail}`;+}++export function formatStack(stack: Stack): string {+ const layers = stack.pull_requests+ .map((pr, i) => ` ${i + 1}. #${pr.number} ${pr.head.ref}${prState(pr)}`)+ .join("\n");+ return (+ `Stack #${stack.number} onto ${stack.base.ref} ` ++ `(${stack.open ? "open" : "closed"}), bottom to top:\n${layers}`+ );+}++/**+ * Renders the unfiltered browse: open stacks only, capped, and explicit about+ * what it dropped, since a silent cut reads as the whole set.+ */+export function summarizeStackList(stacks: readonly Stack[]): string {+ if (stacks.length === 0) return "No stacks in this repository.";++ const open = stacks.filter((s) => s.open);+ const shown = open.slice(0, STACK_LIST_LIMIT);+ const omitted: string[] = [];+ if (open.length > shown.length) {+ omitted.push(`${open.length - shown.length} more open`);+ }+ if (stacks.length > open.length) {+ omitted.push(`${stacks.length - open.length} closed`);+ }++ const body =+ shown.length === 0+ ? "No open stacks in this repository."+ : shown.map(formatStack).join("\n\n");+ if (omitted.length === 0) return body;+ return (+ `${body}\n\nNot shown: ${omitted.join(", ")}. ` ++ "Pass `stack` or `pull_requests` to read one directly."+ );+}++function prState(pr: StackPullRequest): string {+ if (pr.merged_at) return " — merged";+ if (pr.state !== "open") return ` — ${pr.state}`;+ return pr.draft ? " — draft" : "";+}++async function stacksApi(+ ctx: StackCtx,+ args: string[],+ action: string,+ body?: unknown,+): Promise<string> {+ const res = await execGhWithRetry(+ args,+ {+ cwd: ctx.cwd,+ env: ghTokenEnv(ctx.token),+ timeoutMs: STACKS_API_TIMEOUT_MS,+ // `pull_requests` is an array of integers, which `-f` would send as strings.+ ...(body === undefined ? {} : { input: JSON.stringify(body) }),+ },+ { maxAttempts: 3 },+ );+ if (res.exitCode !== 0) {+ throw new Error(stacksApiError(res, action));+ }+ return res.stdout;+}++export async function listStacks(+ ctx: StackCtx,+ pullRequest?: number,+): Promise<Stack[]> {+ const repo = await resolveRepoNameWithOwner(ctx.cwd);+ const filter =+ pullRequest === undefined ? "" : `&pull_request=${pullRequest}`;+ const stdout = await stacksApi(+ ctx,+ [+ "api",+ `/repos/${repo}/stacks?per_page=100${filter}`,+ "--paginate",+ "--slurp",+ ],+ "Listing stacks",+ );+ // --slurp collects one array per page, so the pages need flattening.+ return (JSON.parse(stdout) as Stack[][]).flat();+}++export async function getStack(+ ctx: StackCtx,+ stackNumber: number,+): Promise<Stack> {+ const repo = await resolveRepoNameWithOwner(ctx.cwd);+ const stdout = await stacksApi(+ ctx,+ ["api", `/repos/${repo}/stacks/${stackNumber}`],+ `Reading stack #${stackNumber}`,+ );+ return JSON.parse(stdout) as Stack;+}++export async function fetchPullRequestRefs(+ ctx: StackCtx,+ numbers: readonly number[],+): Promise<PullRequestRefs[]> {+ const repo = await resolveRepoNameWithOwner(ctx.cwd);+ return mapWithConcurrency(numbers, PR_REF_CONCURRENCY, async (number) => {+ const stdout = await stacksApi(+ ctx,+ [+ "api",+ `/repos/${repo}/pulls/${number}`,+ "--jq",+ "{headRef: .head.ref, baseRef: .base.ref}",+ ],+ `Reading pull request #${number}`,+ );+ return {+ number,+ ...(JSON.parse(stdout) as Omit<PullRequestRefs, "number">),+ };+ });+}++export async function createStack(+ ctx: StackCtx,+ pullRequests: readonly number[],+): Promise<Stack> {+ const repo = await resolveRepoNameWithOwner(ctx.cwd);+ const stdout = await stacksApi(+ ctx,+ ["api", "-X", "POST", `/repos/${repo}/stacks`, "--input", "-"],+ "Creating the stack",+ { pull_requests: pullRequests },+ );+ return JSON.parse(stdout) as Stack;+}++export async function extendStack(+ ctx: StackCtx,+ stackNumber: number,+ pullRequests: readonly number[],+): Promise<Stack> {+ const repo = await resolveRepoNameWithOwner(ctx.cwd);+ const stdout = await stacksApi(+ ctx,+ [+ "api",+ "-X",+ "POST",+ `/repos/${repo}/stacks/${stackNumber}/add`,+ "--input",+ "-",+ ],+ `Extending stack #${stackNumber}`,+ { pull_requests: pullRequests },+ );+ return JSON.parse(stdout) as Stack;+}++/** Resolves to null when the whole stack is gone; the API answers 204 for that. */+export async function unstack(+ ctx: StackCtx,+ stackNumber: number,+): Promise<Stack | null> {+ const repo = await resolveRepoNameWithOwner(ctx.cwd);+ const stdout = await stacksApi(+ ctx,+ ["api", "-X", "POST", `/repos/${repo}/stacks/${stackNumber}/unstack`],+ `Unstacking stack #${stackNumber}`,+ );+ return stdout.trim() ? (JSON.parse(stdout) as Stack) : null;+}diff --git a/products/desktop/packages/harness/src/extensions/auto-publish/extension.test.ts b/products/desktop/packages/harness/src/extensions/auto-publish/extension.test.tsindex abf720f0726f..c4b9d16c59a5 100644--- a/products/desktop/packages/harness/src/extensions/auto-publish/extension.test.ts+++ b/products/desktop/packages/harness/src/extensions/auto-publish/extension.test.ts@@ -19,5 +19,9 @@ describe("createAutoPublishExtension", () => {expect(result.systemPrompt).toContain("Base system prompt");expect(result.systemPrompt).toContain("gh pr create --draft");expect(result.systemPrompt).toContain("git_signed_commit");+ // Pi never sees buildCloudSystemPrompt; this is its only stacking guidance.+ expect(result.systemPrompt).toContain("gh_stack");+ expect(result.systemPrompt).toContain("Default to a single pull request");+ expect(result.systemPrompt).toContain("Do not use the `gh stack` CLI");});});diff --git a/products/desktop/packages/harness/src/extensions/auto-publish/extension.ts b/products/desktop/packages/harness/src/extensions/auto-publish/extension.tsindex 977f06ed14cf..929194ebf47b 100644--- a/products/desktop/packages/harness/src/extensions/auto-publish/extension.ts+++ b/products/desktop/packages/harness/src/extensions/auto-publish/extension.ts@@ -7,6 +7,7 @@ const AUTO_PUBLISH_SYSTEM_PROMPT = ["The user has auto-publish enabled for this cloud run.","After completing and verifying code changes, create a `posthog/` branch, stage the changes, use the `git_signed_commit` tool to create a signed commit, and open a draft pull request with `gh pr create --draft`. Do not stop with local changes waiting for review.","Do not use `git commit` or `git push`. If this task already has an open pull request for the same work, continue on that PR instead of opening another one.",+ "Default to a single pull request. When a change splits into independently reviewable layers, you may stack instead: commit each layer with `git_signed_commit` onto its own branch, open each pull request with `gh pr create --base <branch of the layer below>`, then link them with the `gh_stack` tool. Do not use the `gh stack` CLI, whose publishing commands push.",].join("\n");export function createAutoPublishExtension(): ExtensionFactory {