Files
PaperClipAI/server/src/services/workspace-runtime-ready-comment.test.ts
T
417336f8be fix(workspaces): attach PR preparation to existing branches (#11703)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Execution workspaces isolate an agent task from the primary
checkout.
> - Pull request preparation can need a branch that already contains
completed work.
> - The workspace policy could not require an exact existing branch.
> - Workspace cleanup also treated worktree creation as branch
ownership.
> - This pull request adds an exact existing-branch policy and separate
branch ownership metadata.
> - The benefit is safe pull request preparation that preserves every
existing commit and operator-owned branch.

## Linked Issues or Issue Description

**What happened?**

A pull request preparation run could not pin its execution workspace to
an exact existing branch. Workspace reuse and cleanup could also confuse
worktree creation with branch ownership.

**Expected behavior**

The run must attach only to the requested branch in an isolated Git
worktree. It must fail if the branch is missing, busy, or inconsistent.
Cleanup must not delete a branch that Paperclip does not own.

**Steps to reproduce**

1. Create a branch that contains completed work.
2. Configure a pull request preparation task to use that branch.
3. Start the task and observe that the prior policy cannot require the
exact branch.

**Paperclip version or commit**

This behavior reproduces on the base revision before this pull request.

**Deployment mode**

Local development with isolated Git worktrees.

## What Changed

- Add `existingBranch` to the execution workspace policy and shared
validation contracts.
- Require `existingBranch` to use an isolated Git worktree and reject
conflicting branch templates.
- Attach to the exact branch without creating, renaming, resetting, or
deleting it.
- Track branch ownership separately from worktree creation and use that
ownership during cleanup.
- Return HTTP 422 for invalid existing-branch settings on every
issue-producing route.
- Add a bounded repair script for existing pull request preparation
tasks.
- Add focused policy, route, heartbeat, runtime, and ready-comment
tests.
- Document the exact-branch behavior and safety rules.

## Verification

- `pnpm exec vitest run
server/src/__tests__/execution-workspace-policy.test.ts
server/src/__tests__/heartbeat-workspace-session.test.ts
server/src/__tests__/issue-existing-branch-validation-status.test.ts
server/src/__tests__/workspace-runtime.test.ts
server/src/services/workspace-runtime-exposure.test.ts
server/src/services/workspace-runtime-ready-comment.test.ts` passed 335
tests.
- `pnpm -r typecheck` passed for all workspace projects.
- `pnpm test:run` passed 4,431 tests. Two unrelated embedded-Postgres
setup hooks timed out under aggregate load. Their isolated rerun passed
74 tests.
- `pnpm build` passed for all workspace projects.
- The two review regressions passed with 139 unrelated tests skipped.
- All latest-head CI gates passed after one unrelated timing-sensitive
test passed on rerun.
- Greptile scored the latest head 5/5 with no unresolved review threads.

## Risks

- Invalid workspace settings now return HTTP 422 instead of a generic
validation response.
- The exact branch must already exist and must not be checked out by
another worktree.
- The new policy fails closed when it cannot prove branch identity or
ownership.
- This change has no database migration.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI Codex from the GPT-5 family assisted with this change. The
runtime did not expose its exact deployment ID or context window. The
agent used high-reasoning mode, repository tools, shell execution, and
code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 17:23:18 -05:00

195 lines
6.1 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
buildWorkspaceReadyComment,
buildWorkspaceReadyMetadata,
buildWorkspaceReadyPresentation,
type RealizedExecutionWorkspace,
type RuntimeServiceRef,
} from "./workspace-runtime.js";
function workspace(
overrides: Partial<RealizedExecutionWorkspace> = {},
): RealizedExecutionWorkspace {
return {
baseCwd: "/repo",
source: "project_primary",
projectId: "project-id",
workspaceId: "project-workspace-id",
repoUrl: null,
repoRef: "main",
strategy: "git_worktree",
cwd: "/repo/.paperclip/worktrees/PAP-16051",
branchName: "PAP-16051-workspace-ready-notice",
worktreePath: "/repo/.paperclip/worktrees/PAP-16051",
warnings: [],
created: true,
branchCreatedByRuntime: true,
...overrides,
};
}
function runtimeService(
overrides: Partial<RuntimeServiceRef> = {},
): RuntimeServiceRef {
return {
id: "service-id",
companyId: "company-id",
projectId: "project-id",
projectWorkspaceId: "project-workspace-id",
executionWorkspaceId: "execution-workspace-id",
issueId: "issue-id",
serviceName: "web",
status: "running",
lifecycle: "ephemeral",
scopeType: "run",
scopeId: "run-id",
reuseKey: null,
command: "pnpm dev",
cwd: "/repo/.paperclip/worktrees/PAP-16051",
port: 3100,
url: "http://localhost:3100",
provider: "local_process",
providerRef: null,
ownerAgentId: "agent-id",
startedByRunId: "run-id",
lastUsedAt: "2026-08-01T00:00:00.000Z",
startedAt: "2026-08-01T00:00:00.000Z",
stoppedAt: null,
stopPolicy: null,
healthStatus: "healthy",
exposure: null,
reused: false,
...overrides,
};
}
describe("workspace-ready comment builders", () => {
it("uses a compact info notice that is collapsed when the workspace has no warnings", () => {
const input = { workspace: workspace(), runtimeServices: [] };
expect(buildWorkspaceReadyPresentation(input)).toEqual({
kind: "system_notice",
tone: "info",
title: "Workspace ready · PAP-16051-workspace-ready-notice",
density: "compact",
detailsDefaultOpen: false,
});
});
it("uses a warning notice that is expanded when warnings are present", () => {
const input = {
workspace: workspace({ warnings: ["The worktree was restored from a stale reference."] }),
runtimeServices: [],
};
expect(buildWorkspaceReadyPresentation(input)).toMatchObject({
tone: "warning",
detailsDefaultOpen: true,
});
expect(buildWorkspaceReadyMetadata(input).sections.at(-1)).toEqual({
title: "Warnings",
rows: [{ type: "text", text: "The worktree was restored from a stale reference." }],
});
});
it("truncates the presentation title to 160 characters", () => {
const presentation = buildWorkspaceReadyPresentation({
workspace: workspace({ branchName: "b".repeat(200) }),
runtimeServices: [],
});
expect(presentation.title).toHaveLength(160);
expect(presentation.title).toBe(`${`Workspace ready · ${"b".repeat(200)}`.slice(0, 159)}…`);
});
it("falls back to the workspace strategy when no branch is available", () => {
const presentation = buildWorkspaceReadyPresentation({
workspace: workspace({ branchName: null, strategy: "project_primary" }),
runtimeServices: [],
});
expect(presentation.title).toBe("Workspace ready · project_primary");
});
it("builds structured workspace and service sections without an empty warnings section", () => {
const input = {
workspace: workspace(),
runtimeServices: [
runtimeService(),
runtimeService({
id: "worker-service-id",
serviceName: "worker",
url: null,
reused: true,
}),
],
};
expect(buildWorkspaceReadyMetadata(input)).toEqual({
version: 1,
sections: [
{
title: "Workspace",
rows: [
{ type: "key_value", label: "Strategy", value: "git_worktree" },
{ type: "key_value", label: "Branch", value: "PAP-16051-workspace-ready-notice" },
{ type: "key_value", label: "CWD", value: "/repo/.paperclip/worktrees/PAP-16051" },
],
},
{
title: "Services",
rows: [
{ type: "key_value", label: "web", value: "http://localhost:3100" },
{ type: "key_value", label: "worker", value: "running (reused)" },
],
},
],
});
});
it("keeps service labels within the comment metadata boundary", () => {
const metadata = buildWorkspaceReadyMetadata({
workspace: workspace(),
runtimeServices: [runtimeService({ serviceName: ` ${"s".repeat(150)} ` })],
});
const serviceLabel = metadata.sections[1]?.rows[0];
expect(serviceLabel).toEqual({
type: "key_value",
label: `${"s".repeat(119)}…`,
value: "http://localhost:3100",
});
});
it("includes a distinct worktree row and preserves the existing markdown body", () => {
const input = {
workspace: workspace({
cwd: "/repo/runtime",
worktreePath: "/repo/.paperclip/worktrees/PAP-16051",
warnings: ["Warning text"],
}),
runtimeServices: [runtimeService({ reused: true })],
};
expect(buildWorkspaceReadyMetadata(input).sections[0]).toEqual({
title: "Workspace",
rows: [
{ type: "key_value", label: "Strategy", value: "git_worktree" },
{ type: "key_value", label: "Branch", value: "PAP-16051-workspace-ready-notice" },
{ type: "key_value", label: "CWD", value: "/repo/runtime" },
{ type: "key_value", label: "Worktree", value: "/repo/.paperclip/worktrees/PAP-16051" },
],
});
expect(buildWorkspaceReadyComment(input)).toBe([
"## Workspace Ready",
"",
"- Strategy: `git_worktree`",
"- Branch: `PAP-16051-workspace-ready-notice`",
"- CWD: `/repo/runtime`",
"- Worktree: `/repo/.paperclip/worktrees/PAP-16051`",
"- Warning: Warning text",
"- Service: web: http://localhost:3100 (reused)",
].join("\n"));
});
});