Files
PaperClipAI/packages/adapters/cursor-local/src/server/test.test.ts
T
Devin FoleyandPaperclip 35a4448c02 fix(cursor): select failure diagnostics after trace notices (#14636)
## Thinking Path

> - Paperclip manages work performed by AI agents.
> - The Cursor CLI adapter turns process output into run results.
> - Cursor can print a trace-file notice before a real error.
> - The adapter used the first stderr line as the failure summary.
> - This could hide the error behind an informational file path.
> - This change selects the first diagnostic after that known notice and
preserves the full logs.

## Linked Issues or Issue Description

**What happened?**

When Cursor exits with a nonzero code, a leading `cursor-retrieval:
tracing to ...` notice can become the error summary. A later error
remains in stderr but is absent from the summary. If the notice is the
only output, the summary does not explain that the process exited
unsuccessfully.

**Expected behavior**

Prefer the structured error, then a stderr diagnostic, then the exit
code. Keep the run failed and preserve the original logs.

**Steps to reproduce**

1. Use a fixture Cursor executable that writes the trace-file notice to
stderr.
2. Write `Authentication failed` on the next line, then exit with code
7.
3. The old adapter reports the trace-file notice. This change reports
the authentication error.
4. Repeat with only the notice. This change reports `Cursor exited with
code 7`.

**Paperclip version or commit**

Reproduced against master commit
`17780751551b3bc1c2521f7694026c34534c46c9` with local process fixtures.

**Deployment mode**

Local CLI adapter. The diagnostic helper is also used by environment
probes.

Searched open Cursor PRs and issues. PRs #14631 and #14435 concern
native ACP support; #11106 concerns MCP configuration. None changes this
legacy CLI diagnostic selection.

## What Changed

- Skip only the exact trace-location notice when choosing a diagnostic
line.
- Remove terminal control codes from summary candidates.
- Use the same selection for execution and environment probes.
- Preserve structured-error priority, exit status, retry decisions, and
raw stdout/stderr.
- Add child-process regression tests and narrow parsing cases. Document
the behavior.

## Verification

- Two execution regression cases failed on the previous implementation;
structured-error priority already passed.
- `pnpm exec vitest run packages/adapters/cursor-local`: all 16 tests
passed across five files.
- `pnpm --filter @paperclipai/adapter-cursor-local typecheck` passed.
- `pnpm -r typecheck` passed.
- All GitHub CI checks passed on the PR head. One preview-runtime
readiness test failed on the first attempt; its full local suite passed
(28 tests, three skips) and the failed CI shard passed on retry. No
unrelated source change was needed.
- The broad local `pnpm test:run` command did not complete in the
available verification window and was stopped; no full local-suite pass
is claimed. The full sharded GitHub CI suite passed. `pnpm build`
passed.
- Tests use local fixture processes. They make no Cursor provider
requests.

## Risks

A future Cursor notice format may no longer match and will remain
visible. Retrieval error lines and unknown diagnostics remain visible.
This improves diagnosis; it does not claim to fix an unknown provider or
machine failure. There are no schema, authentication, cancellation, or
retry-policy changes.

## Model Used

OpenAI Codex (GPT-6), with reasoning, repository inspection, and command
execution. The session does not expose a more specific model revision or
context-window size.

## 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 described the issue in-PR following the relevant issue
template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
Paperclip ticket id or instance-derived details
- [x] I have run the targeted tests locally and they pass; full checks
are in progress
- [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>
2026-09-29 16:36:36 -07:00

157 lines
5.4 KiB
TypeScript

import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { runChildProcess } from "@paperclipai/adapter-utils/server-utils";
import { SANDBOX_INSTALL_COMMAND } from "../index.js";
import { testEnvironment } from "./test.js";
function buildFakeAgentScript(): string {
return `#!/bin/sh
if [ "$1" = "--version" ]; then
printf '%s\\n' 'Cursor Agent 1.2.3'
exit 0
fi
printf '%s\\n' '{"type":"system","subtype":"init","session_id":"cursor-session-envtest-1","model":"auto"}'
printf '%s\\n' '{"type":"assistant","message":{"content":[{"type":"output_text","text":"hello"}]}}'
printf '%s\\n' '{"type":"result","subtype":"success","session_id":"cursor-session-envtest-1","result":"ok"}'
`;
}
function buildInstallSimulationCommand(commandPath: string): string {
return [
`mkdir -p ${JSON.stringify(path.dirname(commandPath))}`,
`cat > ${JSON.stringify(commandPath)} <<'EOF'`,
buildFakeAgentScript(),
"EOF",
`chmod +x ${JSON.stringify(commandPath)}`,
].join("\n");
}
function createSandboxRunner(options: { homeDir: string; installCommandPath: string }) {
let counter = 0;
const installCommands: string[] = [];
const systemPath = "/usr/bin:/bin";
return {
installCommands,
execute: async (input: {
command: string;
args?: string[];
cwd?: string;
env?: Record<string, string>;
stdin?: string;
timeoutMs?: number;
onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise<void>;
onSpawn?: (meta: { pid: number; startedAt: string }) => Promise<void>;
}) => {
counter += 1;
const args = [...(input.args ?? [])];
if (args[1] === SANDBOX_INSTALL_COMMAND) {
installCommands.push(args[1]);
args[1] = buildInstallSimulationCommand(options.installCommandPath);
}
return await runChildProcess(`cursor-envtest-runner-${counter}`, input.command, args, {
cwd: input.cwd ?? process.cwd(),
env: {
...(input.env ?? {}),
HOME: input.env?.HOME ?? options.homeDir,
PATH: input.env?.PATH ?? systemPath,
},
stdin: input.stdin,
timeoutSec: Math.max(1, Math.ceil((input.timeoutMs ?? 30_000) / 1000)),
graceSec: 5,
onLog: input.onLog ?? (async () => {}),
onSpawn: input.onSpawn
? async (meta) => input.onSpawn?.({ pid: meta.pid, startedAt: meta.startedAt })
: undefined,
});
},
};
}
describe("cursor testEnvironment", () => {
it("shows the probe failure after an informational retrieval trace notice", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-cursor-probe-diagnostic-"));
const command = path.join(root, "agent");
await fs.writeFile(command, `#!/bin/sh
if [ "$1" = "--version" ]; then
printf '%s\\n' 'Cursor Agent 1.2.3'
exit 0
fi
printf '%s\\n' "cursor-retrieval: tracing to '/tmp/fixture.log'" 'Provider connection failed' >&2
exit 7
`, { mode: 0o755 });
try {
const result = await testEnvironment({
companyId: "company-1", adapterType: "cursor",
config: { command: "agent", cwd: root, env: { PATH: `${root}${path.delimiter}${process.env.PATH ?? ""}`, CURSOR_API_KEY: "fixture-cursor-key" } },
});
expect(result.checks).toEqual(expect.arrayContaining([
expect.objectContaining({ code: "cursor_hello_probe_failed", detail: "Provider connection failed" }),
]));
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("re-resolves the installed agent under ~/.cursor/bin and verifies --version before the hello probe", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-cursor-envtest-"));
const homeDir = path.join(root, "home");
const workspace = path.join(root, "workspace");
const remoteWorkspace = path.join(root, "remote-workspace");
const agentPath = path.join(homeDir, ".cursor", "bin", "agent");
await fs.mkdir(workspace, { recursive: true });
await fs.mkdir(remoteWorkspace, { recursive: true });
const runner = createSandboxRunner({
homeDir,
installCommandPath: agentPath,
});
try {
const result = await testEnvironment({
companyId: "company-1",
adapterType: "cursor",
config: {
command: "agent",
cwd: workspace,
env: {
PATH: "/usr/bin:/bin",
},
},
executionTarget: {
kind: "remote",
transport: "sandbox",
shellCommand: "bash",
remoteCwd: remoteWorkspace,
runner,
timeoutMs: 30_000,
},
});
expect(result.status).toBe("pass");
expect(runner.installCommands).toEqual([SANDBOX_INSTALL_COMMAND]);
expect(result.checks).toEqual(
expect.arrayContaining([
expect.objectContaining({
code: "cursor_command_resolvable",
level: "info",
message: `Command is executable: ${agentPath}`,
}),
expect.objectContaining({
code: "cursor_version_probe_passed",
level: "info",
detail: "Cursor Agent 1.2.3",
}),
expect.objectContaining({
code: "cursor_hello_probe_passed",
level: "info",
}),
]),
);
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
});