mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 20:29:18 +01:00
fix(grok): stage the environment test from a host directory, and survive an absent workspace (#13416)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - An agent runs through an adapter. Before you use an environment, the
adapter's environment test probes it and reports structured checks
> - The grok adapter's environment test stages the managed account into
a remote environment first. It gave the runtime its resolved `cwd` as
the host workspace directory
> - For a remote target that `cwd` is a path inside the sandbox. It does
not exist on the host that runs the test
> - A new workspace ignore scan reads that host directory. The scan
failed on the missing directory, and the error escaped the environment
test
> - The user got a server error instead of a result with checks
> - This pull request stages from a host temporary directory, sends the
remote path separately, and reports a staging failure as a check
> - The benefit is that the grok environment test always answers with
checks, and a workspace directory that does not exist no longer stops a
runtime preparation
## Linked Issues or Issue Description
No existing issue. The problem, in the bug report format:
**What happened**
The grok environment test failed with `Error: Workspace ignore scan
failed: git-ignore-scan-failed`. The route returned a server error, so
the user saw no checks at all.
**Expected behavior**
The environment test always returns `{status, checks}`. Every other
problem it finds (an invalid working directory, a command it cannot
resolve, a probe that times out) becomes a check with a level. A
credential staging problem must do the same.
**Steps to reproduce**
1. Configure a grok agent with a managed AI connection.
2. Point the agent at a remote (sandbox) environment.
3. Run the environment test for that environment.
**Paperclip version or commit**
Present on master. Both halves landed on 2026-09-12: the call site in
#13247, and the scan that it trips in #13353.
## What Changed
- `packages/adapters/grok-local/src/server/test.ts` stages the managed
account through a fresh host temporary directory and passes the remote
path as `workspaceRemoteDir`. This is the split `codex-local` and
`opencode-local` already use.
- A failure while staging becomes a `grok_environment_unprepared` check
with level `error`, instead of an exception that escapes the function.
The probe does not run after it, because there is no prepared
environment to probe.
- The temporary directory is removed in the existing `finally` block.
- `packages/adapter-utils/src/sandbox-managed-runtime.ts` treats a
`workspaceLocalDir` that does not exist as "nothing to sync". A
directory that is not there has no files for ignore rules to govern,
nothing to stage, and nothing to restore.
- Tests: the grok environment test now covers the managed-connection
remote branch, which had no coverage. `sandbox-file-sync.test.ts` covers
a preparation whose workspace directory does not exist.
## Verification
```
npx vitest run packages/adapters/grok-local/src/server/test.test.ts # 9 passed
npx vitest run packages/adapter-utils/src/sandbox-file-sync.test.ts \
packages/adapter-utils/src/sandbox-managed-runtime.test.ts # 90 passed
cd packages/adapter-utils && npx tsc --noEmit # clean
cd packages/adapters/grok-local && npx tsc --noEmit # clean
```
The two new grok tests fail against the old call site: the first asserts
the runtime never receives the remote path as its host workspace
directory, and the second asserts a staging failure becomes a check
instead of an exception.
## Risks
Low risk, and limited to environment preparation.
- The adapter change only affects the managed-connection remote branch
of one adapter's environment test.
- The `adapter-utils` change makes a preparation that used to throw now
continue with no workspace sync. A real workspace is unaffected, because
the directory exists in that case and the scan runs exactly as before.
- No migration. No API change.
## Model Used
- Claude Fable 5 (`claude-fable-5`), 1M context, extended thinking, run
through Claude Code with tool use 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
- [ ] I have updated relevant documentation to reflect my changes — no
documented behavior changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green — pending first run
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups —
pending first review
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
1 parent
46bcc0863c
commit
5054c9ef9b
4 files changed
+167
-17
No files matched your search
@@ -126,6 +126,45 @@ describe("sandbox native file sync", () => {
|
||||
expect(await readFile(path.join(repo, "outside.txt"), "utf8")).toBe("outside boundary\n");
|
||||
});
|
||||
|
||||
it("prepares a runtime whose workspace directory does not exist without failing the ignore scan", async () => {
|
||||
// An env test staging only credential assets can hand the runtime a
|
||||
// workspace path that never existed on this host. A directory with no
|
||||
// files has nothing for ignore rules to govern, so the scan is skipped
|
||||
// rather than failed (git-ignore-scan-failed took down the whole
|
||||
// preparation in production).
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-native-absent-workspace-"));
|
||||
cleanupDirs.push(rootDir);
|
||||
const remoteDir = path.join(rootDir, "remote");
|
||||
|
||||
const { client } = makeNativeClient();
|
||||
const prepared = await prepareSandboxManagedRuntime({
|
||||
spec: { transport: "sandbox", provider: "test", sandboxId: "s1", remoteCwd: remoteDir, timeoutMs: 30_000, apiKey: null },
|
||||
adapterKey: "test-adapter",
|
||||
client,
|
||||
workspaceLocalDir: path.join(rootDir, "never-created"),
|
||||
});
|
||||
await prepared.restoreWorkspace();
|
||||
});
|
||||
|
||||
it("fails preparation when the workspace cannot be read for a reason other than absence", async () => {
|
||||
// Only absence means "nothing to sync". A workspace that is there but
|
||||
// unreadable must not quietly become an empty remote workspace, so any
|
||||
// other access error still fails the preparation. A path whose parent is
|
||||
// a file gives a deterministic non-ENOENT error on every platform.
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-native-unreadable-workspace-"));
|
||||
cleanupDirs.push(rootDir);
|
||||
const notADirectory = path.join(rootDir, "a-file");
|
||||
await writeFile(notADirectory, "not a directory\n");
|
||||
|
||||
const { client } = makeNativeClient();
|
||||
await expect(prepareSandboxManagedRuntime({
|
||||
spec: { transport: "sandbox", provider: "test", sandboxId: "s1", remoteCwd: path.join(rootDir, "remote"), timeoutMs: 30_000, apiKey: null },
|
||||
adapterKey: "test-adapter",
|
||||
client,
|
||||
workspaceLocalDir: path.join(notADirectory, "workspace"),
|
||||
})).rejects.toMatchObject({ code: "ENOTDIR" });
|
||||
});
|
||||
|
||||
it("prefers the native path for default-provision asset inbound and workspace outbound", async () => {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-native-sync-"));
|
||||
cleanupDirs.push(rootDir);
|
||||
|
||||
@@ -1084,7 +1084,21 @@ export async function prepareSandboxManagedRuntime(input: {
|
||||
}): Promise<PreparedSandboxManagedRuntime> {
|
||||
const workspaceRemoteDir = input.workspaceRemoteDir ?? input.spec.remoteCwd;
|
||||
const runtimeRootDir = path.posix.join(workspaceRemoteDir, ".paperclip-runtime", input.adapterKey);
|
||||
const syncWorkspace = input.syncWorkspace !== false;
|
||||
// A workspace directory that does not exist on this host has nothing to
|
||||
// stage, no files for ignore rules to govern, and nothing to restore into —
|
||||
// callers that only stage credential assets (the adapter env tests) hand
|
||||
// the runtime a fresh path. Treat that one case as "do not sync" rather
|
||||
// than letting the ignore scan or the staging walk die on ENOENT. Any other
|
||||
// access failure still fails the preparation: a workspace that exists but
|
||||
// cannot be read must not silently become an empty remote workspace.
|
||||
const syncWorkspace = input.syncWorkspace !== false &&
|
||||
(await fs.access(input.workspaceLocalDir).then(
|
||||
() => true,
|
||||
(error: NodeJS.ErrnoException) => {
|
||||
if (error.code === "ENOENT") return false;
|
||||
throw error;
|
||||
},
|
||||
));
|
||||
const workspaceInboundMode = input.workspaceInboundMode ?? "host_current";
|
||||
const stageWorkspace =
|
||||
syncWorkspace && workspaceInboundMode !== "adopt_remote";
|
||||
|
||||
@@ -3,16 +3,23 @@ import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
const ensureDirectoryMock = vi.hoisted(() => vi.fn(async () => {}));
|
||||
const ensureCommandMock = vi.hoisted(() => vi.fn(async () => {}));
|
||||
const runProcessMock = vi.hoisted(() => vi.fn());
|
||||
const prepareRuntimeMock = vi.hoisted(() => vi.fn());
|
||||
const stageGrokHomeMock = vi.hoisted(() => vi.fn(async () => "/tmp/staged-grok-home"));
|
||||
|
||||
vi.mock("@paperclipai/adapter-utils/execution-target", () => ({
|
||||
describeAdapterExecutionTarget: () => "local",
|
||||
ensureAdapterExecutionTargetCommandResolvable: ensureCommandMock,
|
||||
ensureAdapterExecutionTargetDirectory: ensureDirectoryMock,
|
||||
prepareAdapterExecutionTargetRuntime: prepareRuntimeMock,
|
||||
resolveAdapterExecutionTargetCwd: (_target: unknown, configuredCwd: string, fallbackCwd: string) =>
|
||||
configuredCwd || fallbackCwd,
|
||||
runAdapterExecutionTargetProcess: runProcessMock,
|
||||
}));
|
||||
|
||||
vi.mock("./grok-home.js", () => ({ stageGrokHomeForSync: stageGrokHomeMock }));
|
||||
vi.mock("./grok-auth-copyback.js", () => ({ copyBackGrokAuth: vi.fn(async () => {}) }));
|
||||
|
||||
import { existsSync } from "node:fs";
|
||||
import { parseGrokModelsOutput, testEnvironment } from "./test.js";
|
||||
|
||||
describe("parseGrokModelsOutput", () => {
|
||||
@@ -38,6 +45,8 @@ describe("grok_local testEnvironment", () => {
|
||||
ensureDirectoryMock.mockClear();
|
||||
ensureCommandMock.mockClear();
|
||||
runProcessMock.mockReset();
|
||||
prepareRuntimeMock.mockReset();
|
||||
stageGrokHomeMock.mockClear();
|
||||
});
|
||||
|
||||
it("reports a healthy authenticated host with a working hello probe", async () => {
|
||||
@@ -249,6 +258,58 @@ describe("grok_local testEnvironment", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("stages the managed account through a host temp workspace, never the remote cwd", async () => {
|
||||
// The remote cwd is a path inside the sandbox. Handing it to the runtime
|
||||
// as `workspaceLocalDir` made the host-side ignore scan fail on a
|
||||
// directory that does not exist (git-ignore-scan-failed in production).
|
||||
let workspaceLocalDirAtCall: string | undefined;
|
||||
let workspaceExistedAtCall: boolean | undefined;
|
||||
prepareRuntimeMock.mockImplementationOnce(async (input: { workspaceLocalDir: string }) => {
|
||||
workspaceLocalDirAtCall = input.workspaceLocalDir;
|
||||
workspaceExistedAtCall = existsSync(input.workspaceLocalDir);
|
||||
return { assetDirs: { home: "/sandbox/assets/home" }, restoreWorkspace: async () => {} };
|
||||
});
|
||||
runProcessMock
|
||||
.mockResolvedValueOnce({ exitCode: 0, signal: null, timedOut: false, stdout: "You are logged in with grok.com.\n\nDefault model: grok-4\n\nAvailable models:\n * grok-4", stderr: "" })
|
||||
.mockResolvedValueOnce({ exitCode: 0, signal: null, timedOut: false, stdout: [JSON.stringify({ type: "text", data: "hello" }), JSON.stringify({ type: "end", stopReason: "EndTurn", sessionId: "s", requestId: "r" })].join("\n"), stderr: "" });
|
||||
|
||||
const result = await testEnvironment({
|
||||
companyId: "company-1",
|
||||
adapterType: "grok_local",
|
||||
config: { command: "grok", cwd: "/sandbox/workspace", managedAiConnection: { provider: "xai" } },
|
||||
executionTarget: { kind: "remote", transport: "sandbox" } as never,
|
||||
});
|
||||
|
||||
expect(prepareRuntimeMock).toHaveBeenCalledOnce();
|
||||
expect(prepareRuntimeMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ workspaceRemoteDir: "/sandbox/workspace" }),
|
||||
);
|
||||
expect(workspaceLocalDirAtCall).not.toBe("/sandbox/workspace");
|
||||
expect(workspaceExistedAtCall).toBe(true);
|
||||
// The staged home dir the runtime uploaded is what the probe must use.
|
||||
expect(runProcessMock.mock.calls[0]?.[4]).toMatchObject({ env: expect.objectContaining({ GROK_HOME: "/sandbox/assets/home" }) });
|
||||
expect(result.status).toBe("pass");
|
||||
});
|
||||
|
||||
it("reports a failed runtime preparation as a check instead of crashing", async () => {
|
||||
prepareRuntimeMock.mockRejectedValueOnce(
|
||||
new Error("Workspace ignore scan failed: git-ignore-scan-failed"),
|
||||
);
|
||||
|
||||
const result = await testEnvironment({
|
||||
companyId: "company-1",
|
||||
adapterType: "grok_local",
|
||||
config: { command: "grok", cwd: "/sandbox/workspace", managedAiConnection: { provider: "xai" } },
|
||||
executionTarget: { kind: "remote", transport: "sandbox" } as never,
|
||||
});
|
||||
|
||||
expect(result.status).toBe("fail");
|
||||
const unprepared = result.checks.find((check: { code: string }) => check.code === "grok_environment_unprepared");
|
||||
expect(unprepared).toMatchObject({ level: "error" });
|
||||
// A failed staging means there is no environment worth probing.
|
||||
expect(runProcessMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("emits no adapter_auth_missing check for a local target with missing authentication", async () => {
|
||||
// The canonical check gates sandbox login eligibility only. A local target
|
||||
// has no sandbox login to offer, so the check must not appear.
|
||||
|
||||
@@ -18,7 +18,8 @@ import {
|
||||
resolveAdapterExecutionTargetCwd,
|
||||
runAdapterExecutionTargetProcess,
|
||||
} from "@paperclipai/adapter-utils/execution-target";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { stageGrokHomeForSync } from "./grok-home.js";
|
||||
import { copyBackGrokAuth } from "./grok-auth-copyback.js";
|
||||
@@ -151,22 +152,43 @@ export async function testEnvironment(
|
||||
|
||||
const env = normalizeEnv(config.env);
|
||||
let stagedHome: string | undefined;
|
||||
let runtimeWorkspaceLocalDir: string | undefined;
|
||||
let restore: (() => Promise<void>) | undefined;
|
||||
try {
|
||||
if (config.managedAiConnection && targetIsRemote) {
|
||||
const hostHome = env.GROK_HOME;
|
||||
stagedHome = await stageGrokHomeForSync(hostHome, { runId });
|
||||
const prepared = await prepareAdapterExecutionTargetRuntime({
|
||||
runId, target, adapterKey: "grok", workspaceLocalDir: cwd,
|
||||
assets: [{ key: "home", localDir: stagedHome, followSymlinks: true,
|
||||
restore: async ({ assetDir, readFile }) => { await copyBackGrokAuth({
|
||||
readSandboxAuth: () => readFile(path.posix.join(assetDir, "auth.json")),
|
||||
hostHomeDir: hostHome, log: () => {},
|
||||
}); },
|
||||
}],
|
||||
});
|
||||
env.GROK_HOME = prepared.assetDirs.home;
|
||||
restore = () => prepared.restoreWorkspace(() => {});
|
||||
try {
|
||||
const hostHome = env.GROK_HOME;
|
||||
stagedHome = await stageGrokHomeForSync(hostHome, { runId });
|
||||
// `cwd` is the remote target path here, never a host directory, so the
|
||||
// runtime gets an empty host workspace to stage from and the remote
|
||||
// path separately — the same split codex-local and opencode-local
|
||||
// draw. Handing it the remote path as `workspaceLocalDir` made the
|
||||
// host-side ignore scan fail on a directory that does not exist.
|
||||
runtimeWorkspaceLocalDir = await mkdtemp(
|
||||
path.join(os.tmpdir(), `paperclip-grok-envtest-${runId}-`),
|
||||
);
|
||||
const prepared = await prepareAdapterExecutionTargetRuntime({
|
||||
runId, target, adapterKey: "grok",
|
||||
workspaceLocalDir: runtimeWorkspaceLocalDir,
|
||||
workspaceRemoteDir: cwd,
|
||||
assets: [{ key: "home", localDir: stagedHome, followSymlinks: true,
|
||||
restore: async ({ assetDir, readFile }) => { await copyBackGrokAuth({
|
||||
readSandboxAuth: () => readFile(path.posix.join(assetDir, "auth.json")),
|
||||
hostHomeDir: hostHome, log: () => {},
|
||||
}); },
|
||||
}],
|
||||
});
|
||||
env.GROK_HOME = prepared.assetDirs.home;
|
||||
restore = () => prepared.restoreWorkspace(() => {});
|
||||
} catch (err) {
|
||||
// The environment test reports what is wrong with the environment; a
|
||||
// credential-staging failure is a finding, not a crash.
|
||||
checks.push({
|
||||
code: "grok_environment_unprepared",
|
||||
level: "error",
|
||||
message: err instanceof Error ? err.message : "Could not stage the managed account into the environment",
|
||||
});
|
||||
}
|
||||
}
|
||||
const runtimeEnv = ensurePathInEnv({ ...process.env, ...env });
|
||||
|
||||
@@ -187,7 +209,10 @@ export async function testEnvironment(
|
||||
}
|
||||
|
||||
const canRunProbe =
|
||||
checks.every((check) => check.code !== "grok_cwd_invalid" && check.code !== "grok_command_unresolvable");
|
||||
checks.every((check) =>
|
||||
check.code !== "grok_cwd_invalid" &&
|
||||
check.code !== "grok_command_unresolvable" &&
|
||||
check.code !== "grok_environment_unprepared");
|
||||
|
||||
const configuredModel = asString(config.model, DEFAULT_GROK_LOCAL_MODEL).trim();
|
||||
|
||||
@@ -366,5 +391,16 @@ export async function testEnvironment(
|
||||
checks,
|
||||
testedAt: new Date().toISOString(),
|
||||
};
|
||||
} finally { try { await restore?.(); } finally { if (stagedHome) await rm(stagedHome, { recursive: true, force: true }); } }
|
||||
} finally {
|
||||
try { await restore?.(); } finally {
|
||||
// Both temporary directories are removed even when one removal fails,
|
||||
// and neither failure turns an answered environment test into a thrown
|
||||
// error: these are best-effort temp directories, and the caller asked
|
||||
// for checks.
|
||||
await Promise.allSettled([
|
||||
stagedHome ? rm(stagedHome, { recursive: true, force: true }) : undefined,
|
||||
runtimeWorkspaceLocalDir ? rm(runtimeWorkspaceLocalDir, { recursive: true, force: true }) : undefined,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user