Files
PaperClipAI/cli/src/__tests__/install-command.test.ts
T
fc5a30805e feat(cli): add managed install, update, and service lifecycle (#10045)
## Thinking Path

> - Paperclip is the open source control plane people use to manage
AI-agent companies
> - Operators need a predictable installation path that survives beyond
an ephemeral `npx` process
> - A durable installation needs an owned per-user payload store, stable
command shim, safe shell integration, and supported service lifecycle
> - Updates must preserve recoverability by backing up data, installing
side-by-side, verifying the new payload, and retaining rollback state
> - Bootstrap scripts and privileged service operations must fail closed
across download, filesystem, ownership, and consent boundaries
> - This pull request integrates managed install, update, rollback,
service, uninstall, doctor, bootstrap-installer, and runtime-serving
support into one workflow
> - The benefit is a recoverable, inspectable, and documented
installation lifecycle with explicit safety boundaries across Linux,
macOS, containers, WSL, npm, npx, and source checkouts

## Linked Issues or Issue Description

### Problem

Paperclip lacks a first-class durable installation and lifecycle
workflow. Operators currently have to assemble npm/npx installation,
PATH setup, background-service management, updates, rollback,
diagnostics, and uninstall behavior themselves. That makes upgrades
harder to recover, creates inconsistent behavior across platforms, and
leaves shell/download/service trust boundaries without one documented
implementation.

### Proposed Solution

Add a managed per-user install store and stable shim, a verified shell
bootstrap installer, service lifecycle commands, install-mode-aware
update/rollback behavior, doctor checks, and documentation. Managed
updates back up the database, install and smoke-test a side-by-side
payload, atomically switch `current`, and retain prior payloads. The
shell installer pins registry/download trust boundaries and requires
explicit consent for non-interactive privileged actions.

### Alternatives Considered

- Keep recommending `npx`: simple for evaluation, but ephemeral and
unsuitable for stable services, atomic updates, or rollback.
- Require global npm installation only: familiar, but cannot provide the
owned side-by-side payload store and retained rollback semantics.
- Split the capability across multiple PRs: rejected because install,
update, service, uninstall, bootstrap, and serving behavior share
contracts and security boundaries that need review together.

### Related Pull Requests

- Supersedes #10042 and #10044 with one integrated final diff.
- Incorporates and replaces the closed preparatory work in #10032 and
#10034.

## What Changed

- Added `paperclipai install`, `update`/`upgrade`, rollback, uninstall,
service lifecycle, onboarding integration, and managed-install doctor
checks.
- Added a private managed payload store, verified manifest/marker
ownership, exclusive mutation locks, atomic manifest/current/shim
writes, retained previous payloads, and provenance validation.
- Added npm and GitHub-ref install sources with exact target resolution,
registry isolation, database backup, side-by-side verification, atomic
activation, service restart coordination, and failure rollback.
- Made managed-update backups report actionable service-start and
`--no-backup` recovery guidance for unreachable databases, while clean
never-onboarded instances skip an empty backup.
- Added systemd user and launchd service definitions, status/health/log
commands, single-instance coordination, stale-port recovery, and
explicit sudo/lingering consent handling.
- Added the `scripts/install.sh` bootstrap path with checked two-stage
downloads, pinned public npm registry usage, platform checks,
dry-run/non-interactive controls, and Docker fixtures.
- Added embedded Postgres/native bootstrap integration,
hot-restart/systemd-notify serving support, passive update notices,
configuration contracts, README/CLI/install documentation, and focused
regression tests.
- Security re-review should explicitly re-verify: (1)
`addManagedPathBlock`/`removeManagedPathBlock` reject symlinked or
non-regular rc files, assert current-user ownership, preserve
restrictive modes, and replace atomically; (2) managed shim replacement
rejects unsafe parents, foreign-owned or multiply linked files, and uses
checked atomic replacement; (3) the shell installer and sudo path
preserve explicit consent and checked downloads; and (4) installed
service/runtime serving remains bound to the validated managed shim and
instance configuration.

## Verification

- `bash -n scripts/install.sh scripts/clean-install-git.sh
scripts/clean-install-npm.sh scripts/test-install-sh-docker.sh`
- `pnpm exec vitest run cli/src/__tests__/install-store.test.ts
cli/src/__tests__/install-command.test.ts
cli/src/__tests__/managed-install-check.test.ts
cli/src/__tests__/onboard-service.test.ts
cli/src/__tests__/service-health-check.test.ts
cli/src/__tests__/service-manager.test.ts
cli/src/__tests__/update-command.test.ts
cli/src/__tests__/update-notice.test.ts
packages/db/src/embedded-postgres-native.test.ts` — 9 files, 66 tests
passed
- `pnpm --dir cli typecheck`
- `pnpm --dir cli build`
- Follow-up verification: `pnpm exec vitest run
cli/src/__tests__/update-command.test.ts` (14/14), `pnpm --dir cli
typecheck`, `pnpm --dir cli build`, and `pnpm --filter
@paperclipai/server typecheck`.
- `pnpm -r typecheck`
- `pnpm build`
- Full `pnpm test:run` exercised all suites; an injected static AWS
credential changed one unrelated doctor expectation, which passed when
those credentials were removed. A second run cleared that case and
exposed stale pre-existing adapter-utils `dist` output; rebuilding
`@paperclipai/adapter-utils` made the isolated test pass. The updated PR
CI is the authoritative clean-workspace full-suite run.

## Risks

- Installer/update code writes executable shims, symlinks, shell rc
blocks, service definitions, and managed payloads; ownership,
regular-file, symlink, hard-link, marker, and path-containment checks
fail closed before destructive changes.
- The bootstrap installer executes downloaded tooling; downloads are
staged and checked before execution, npm traffic is pinned to the public
registry, and non-interactive privileged behavior requires explicit
consent.
- Linux lingering may invoke `sudo`; the command is surfaced and
confirmed before execution, and unsupported service managers fall back
to foreground-run guidance.
- Database migrations remain forward-only; payload rollback does not
reverse migrations, so managed updates create a backup before activation
unless explicitly disabled.
- Service restart and runtime serving touch process/port ownership;
lifecycle locks, health/version checks, and stable-shim service
definitions reduce split-brain and stale-process risk.

> 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 coding agents using GPT-5.5 and GPT-5.6-sol, with
reasoning, repository/API access, shell execution, and test tooling. The
runtime did not expose a reliable 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 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-07-31 18:52:23 -07:00

377 lines
19 KiB
TypeScript

import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
type CommandRunner,
installCommand,
installGitPayload,
resolveGitHubRef,
resolveGitInstallRequest,
resolveGitInstallWorkspacePackages,
resolveNpmInstallRequest,
runCommandWithDiagnostics,
} from "../commands/install.js";
import { uninstallCommand } from "../commands/uninstall.js";
import { resolvePaperclipInstanceId } from "../config/home.js";
import {
INSTALL_MANIFEST_VERSION,
flipCurrentAtomic,
initializeInstallStore,
payloadPathFor,
readInstallManifest,
resolveInstallStorePaths,
withInstallStoreLock,
writeInstallManifestAtomic,
} from "../install-store.js";
import { resolveCliVersion } from "../version.js";
import { systemdServiceName } from "../services/service-manager.js";
const ORIGINAL_ENV = { ...process.env };
describe("managed install commands", () => {
let root: string;
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-install-command-"));
process.env = {
...ORIGINAL_ENV,
HOME: path.join(root, "home"),
PAPERCLIP_HOME: path.join(root, "home", ".paperclip"),
PATH: "/usr/bin:/bin",
SHELL: "/bin/bash",
};
fs.mkdirSync(process.env.HOME!, { recursive: true });
vi.spyOn(console, "log").mockImplementation(() => undefined);
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...ORIGINAL_ENV };
fs.rmSync(root, { recursive: true, force: true });
});
it("selects stable, canary, and exact-version npm sources", () => {
expect(resolveNpmInstallRequest({})).toEqual({ spec: "latest", channel: "latest" });
expect(resolveNpmInstallRequest({ canary: true })).toEqual({ spec: "canary", channel: "canary" });
expect(resolveNpmInstallRequest({ version: "2026.720.0" })).toEqual({
spec: "2026.720.0",
channel: "pinned",
});
expect(() => resolveNpmInstallRequest({ canary: true, version: "1.2.3" })).toThrow();
expect(() => resolveNpmInstallRequest({ version: "latest" })).toThrow();
});
it("resolves branch, tag, full SHA, and short SHA refs through GitHub", async () => {
const sha = "a".repeat(40);
const runCommand = vi.fn(async (_file: string, _args: string[]) => ({ stdout: JSON.stringify({ sha }), stderr: "" }));
for (const ref of ["master", "v1.2.3", sha, sha.slice(0, 12)]) {
await expect(resolveGitHubRef("paperclipai/paperclip", ref, runCommand)).resolves.toBe(sha);
}
expect(runCommand.mock.calls.map((call) => call[1].at(-1))).toEqual([
"https://api.github.com/repos/paperclipai/paperclip/commits/master",
"https://api.github.com/repos/paperclipai/paperclip/commits/v1.2.3",
`https://api.github.com/repos/paperclipai/paperclip/commits/${sha}`,
`https://api.github.com/repos/paperclipai/paperclip/commits/${sha.slice(0, 12)}`,
]);
});
it("supports fork overrides and classifies SHA refs as pinned", () => {
expect(resolveGitInstallRequest({ ref: "feature/test", repo: "HenkDz/paperclip" })).toEqual({ repo: "HenkDz/paperclip", ref: "feature/test", pinned: false });
expect(resolveGitInstallRequest({ ref: "abcdef1" })).toEqual({ repo: "paperclipai/paperclip", ref: "abcdef1", pinned: true });
expect(() => resolveGitInstallRequest({ repo: "HenkDz/paperclip" })).toThrow("requires --ref");
});
it("requires explicit non-interactive consent before resolving git refs", async () => {
const runCommand = vi.fn();
await expect(installCommand({ ref: "master", repo: "HenkDz/paperclip" }, { runCommand }))
.rejects.toThrow("Re-run with --yes");
expect(runCommand).not.toHaveBeenCalled();
});
it("reuses a SHA-keyed git payload without downloading or rebuilding", async () => {
const sha = "b".repeat(40);
const paths = resolveInstallStorePaths();
const payloadPath = payloadPathFor(paths, "git", sha.slice(0, 12));
const packageRoot = path.join(payloadPath, "node_modules", "paperclipai");
fs.mkdirSync(path.join(packageRoot, "dist"), { recursive: true });
fs.writeFileSync(path.join(packageRoot, "package.json"), JSON.stringify({ version: "0.3.1" }));
fs.writeFileSync(path.join(packageRoot, "dist", "index.js"), "#!/usr/bin/env node\n");
const runCommand = vi.fn(async (_file: string, _args: string[]) => ({ stdout: "0.3.1\n", stderr: "" }));
await expect(installGitPayload("paperclipai/paperclip", sha, runCommand, paths)).resolves.toEqual({ payloadPath, reused: true, version: "0.3.1" });
expect(runCommand).toHaveBeenCalledOnce();
expect(runCommand.mock.calls[0]?.[0]).toBe(process.execPath);
});
const createGitCheckoutRunCommand = (sha: string) =>
vi.fn(async (file: string, args: string[], _options?: Parameters<CommandRunner>[2]) => {
if (file === "curl" && !args.includes("--output")) return { stdout: JSON.stringify({ sha }), stderr: "" };
if (file === "curl") { fs.writeFileSync(args[args.indexOf("--output") + 1], "archive"); return { stdout: "", stderr: "" }; }
if (file === "tar") {
const checkout = args[args.indexOf("-C") + 1];
const packages = [
{ dir: "packages/shared", name: "@paperclipai/shared", packageJson: { name: "@paperclipai/shared", version: "0.3.1" } },
{ dir: "packages/db", name: "@paperclipai/db", packageJson: { name: "@paperclipai/db", version: "0.3.1", dependencies: { "@paperclipai/shared": "workspace:*" }, bundleDependencies: ["embedded-postgres"] } },
{ dir: "server", name: "@paperclipai/server", packageJson: { name: "@paperclipai/server", version: "0.3.1", dependencies: { "@paperclipai/db": "workspace:*" } } },
];
fs.mkdirSync(path.join(checkout, "cli"), { recursive: true });
fs.writeFileSync(path.join(checkout, "cli", "package.json"), JSON.stringify({ version: "0.3.1" }));
fs.mkdirSync(path.join(checkout, "scripts"), { recursive: true });
fs.writeFileSync(path.join(checkout, "scripts", "release-package-manifest.json"), JSON.stringify(packages.map(({ dir, name }) => ({ dir, name }))));
for (const workspacePackage of packages) {
fs.mkdirSync(path.join(checkout, workspacePackage.dir), { recursive: true });
fs.writeFileSync(path.join(checkout, workspacePackage.dir, "package.json"), JSON.stringify(workspacePackage.packageJson));
}
return { stdout: "", stderr: "" };
}
if (file === "corepack") {
if (args.includes("pack")) {
const destination = args[args.indexOf("--pack-destination") + 1];
const packageDir = args[args.indexOf("--dir") + 1];
const packageName = packageDir === "server" ? "paperclipai-server" : "paperclipai-shared";
fs.writeFileSync(path.join(destination, `${packageName}-0.3.1.tgz`), "package");
}
return { stdout: "", stderr: "" };
}
if (file === "bash") return { stdout: "", stderr: "" };
if (file === "npm" && args[0] === "pack") {
const packageName = args[1]?.includes("workspace-package-") ? "paperclipai-db" : "paperclipai";
fs.writeFileSync(path.join(args[args.indexOf("--pack-destination") + 1], `${packageName}-0.3.1.tgz`), "package");
return { stdout: "", stderr: "" };
}
if (file === "npm" && args[0] === "install") { const prefix = args[args.indexOf("--prefix") + 1]; const packageRoot = path.join(prefix, "node_modules", "paperclipai"); fs.mkdirSync(path.join(packageRoot, "dist"), { recursive: true }); fs.writeFileSync(path.join(packageRoot, "package.json"), JSON.stringify({ version: "0.3.1" })); fs.writeFileSync(path.join(packageRoot, "dist", "index.js"), "#!/usr/bin/env node\n"); return { stdout: "", stderr: "" }; }
if (file === process.execPath && args[0]?.endsWith("prepare-bundled-package.mjs")) {
fs.mkdirSync(args[2], { recursive: true });
fs.writeFileSync(path.join(args[2], "package.json"), JSON.stringify({ name: "@paperclipai/db", version: "0.3.1" }));
return { stdout: "", stderr: "" };
}
if (file === process.execPath) return { stdout: "0.3.1\n", stderr: "" };
throw new Error(`Unexpected command: ${file} ${args.join(" ")}`);
});
it("installs a GitHub branch through codeload and reuses the resolved SHA", async () => {
const sha = "c".repeat(40);
const runCommand = createGitCheckoutRunCommand(sha);
await installCommand({ ref: "master", repo: "HenkDz/paperclip", yes: true }, { runCommand });
await installCommand({ ref: "master", repo: "HenkDz/paperclip", yes: true }, { runCommand });
const manifest = readInstallManifest(resolveInstallStorePaths());
expect(manifest).toMatchObject({ source: "git", repo: "HenkDz/paperclip", ref: "master", sha });
expect(manifest?.payloadPath).toContain(path.join("git", sha.slice(0, 12)));
expect(runCommand.mock.calls.filter(([command, args]) => command === "curl" && args.includes("--output"))).toHaveLength(1);
expect(runCommand.mock.calls.filter(([command, args]) => command === "corepack" && args[1] === "install")).toHaveLength(1);
expect(runCommand.mock.calls.filter(([command, args]) => command === "corepack" && args.includes("pack"))).toHaveLength(2);
expect(runCommand.mock.calls.filter(([command, args]) => command === process.execPath && args[0]?.endsWith("prepare-bundled-package.mjs"))).toHaveLength(1);
expect(runCommand.mock.calls.filter(([command, args]) => command === "npm" && args[0] === "pack")).toHaveLength(2);
const installCall = runCommand.mock.calls.find(([command, args]) => command === "npm" && args[0] === "install");
expect(installCall?.[1].filter((arg) => arg.endsWith(".tgz"))).toHaveLength(4);
});
it("builds git checkouts with NODE_ENV cleared so ambient production mode keeps devDependencies", async () => {
process.env.NODE_ENV = "production";
const sha = "d".repeat(40);
const runCommand = createGitCheckoutRunCommand(sha);
await expect(installGitPayload("paperclipai/paperclip", sha, runCommand, resolveInstallStorePaths())).resolves.toMatchObject({ version: "0.3.1", reused: false });
const buildCalls = runCommand.mock.calls.filter(([file, args]) =>
file === "bash" ||
file === "corepack" ||
(file === "npm" && args[0] === "pack") ||
(file === process.execPath && args[0]?.endsWith("prepare-bundled-package.mjs")));
expect(buildCalls).toHaveLength(9);
for (const call of buildCalls) {
const env = call[2]?.env;
expect(env, `${call[0]} ${call[1].join(" ")} must run with an explicit env`).toBeDefined();
expect(env, `${call[0]} ${call[1].join(" ")} must not inherit NODE_ENV`).not.toHaveProperty("NODE_ENV");
}
const uiPackCall = buildCalls.find(([file, , options]) => file === "corepack" && options?.env?.PAPERCLIP_RELEASE_REUSE_UI_DIST === "1");
expect(uiPackCall).toBeDefined();
});
it("resolves the complete server workspace dependency closure in dependency order", () => {
const checkout = path.join(root, "checkout");
const packages = [
{ dir: "packages/shared", name: "@paperclipai/shared", dependencies: {} },
{ dir: "packages/db", name: "@paperclipai/db", dependencies: { "@paperclipai/shared": "workspace:*" } },
{ dir: "server", name: "@paperclipai/server", dependencies: { "@paperclipai/db": "workspace:*" } },
];
fs.mkdirSync(path.join(checkout, "scripts"), { recursive: true });
fs.writeFileSync(path.join(checkout, "scripts", "release-package-manifest.json"), JSON.stringify(packages.map(({ dir, name }) => ({ dir, name }))));
for (const workspacePackage of packages) {
fs.mkdirSync(path.join(checkout, workspacePackage.dir), { recursive: true });
fs.writeFileSync(path.join(checkout, workspacePackage.dir, "package.json"), JSON.stringify({ name: workspacePackage.name, dependencies: workspacePackage.dependencies }));
}
expect(resolveGitInstallWorkspacePackages(checkout).map(({ name }) => name)).toEqual([
"@paperclipai/shared",
"@paperclipai/db",
"@paperclipai/server",
]);
});
it("includes child-process stderr in command failures", async () => {
await expect(runCommandWithDiagnostics(process.execPath, ["-e", "process.stderr.write('unsupported workspace dependency\\n'); process.exit(1)"]))
.rejects.toThrow("unsupported workspace dependency");
});
it("installs through the shim, reports provenance, and uninstalls without deleting user data", async () => {
const version = "2026.720.0";
const runCommand = vi.fn(async (file: string, args: string[], _options?: unknown) => {
if (file === "npm" && args[0] === "view") return { stdout: JSON.stringify(version), stderr: "" };
if (file === "npm" && args[0] === "install") {
const prefix = args[args.indexOf("--prefix") + 1];
const entrypoint = path.join(prefix, "node_modules", "paperclipai", "dist", "index.js");
fs.mkdirSync(path.dirname(entrypoint), { recursive: true });
fs.writeFileSync(entrypoint, "#!/usr/bin/env node\n");
return { stdout: "", stderr: "" };
}
if (file === process.execPath && args.at(-1) === "--version") {
return { stdout: `${version}\n`, stderr: "" };
}
throw new Error(`Unexpected command: ${file} ${args.join(" ")}`);
});
await installCommand({}, { runCommand, now: () => new Date("2026-07-22T18:00:00.000Z") });
const paths = resolveInstallStorePaths();
const manifest = readInstallManifest(paths);
expect(manifest?.version).toBe(version);
expect(manifest?.channel).toBe("latest");
expect(fs.realpathSync(paths.currentPath)).toBe(fs.realpathSync(manifest!.payloadPath));
expect(fs.existsSync(paths.shimPath)).toBe(true);
const installCall = runCommand.mock.calls.find(
([file, args]) => file === "npm" && args[0] === "install",
);
expect(installCall?.[1]).toContain("--@paperclipai:registry=https://registry.npmjs.org");
const installOptions = installCall?.[2] as { env?: NodeJS.ProcessEnv } | undefined;
expect(installOptions?.env?.npm_config_userconfig).toContain(".npmrc-");
const entrypoint = path.join(manifest!.payloadPath, "node_modules", "paperclipai", "dist", "index.js");
expect(resolveCliVersion(entrypoint)).toContain(`managed npm latest; payload ${manifest!.payloadPath}`);
const userData = path.join(process.env.PAPERCLIP_HOME!, "instances", "default", "keep.txt");
fs.mkdirSync(path.dirname(userData), { recursive: true });
fs.writeFileSync(userData, "keep");
const uninstallService = vi.fn(async () => {
expect(fs.existsSync(paths.shimPath)).toBe(true);
});
await uninstallCommand({
detectServiceManager: vi.fn(async () => ({
supported: true as const,
manager: {
status: vi.fn(async () => ({ installed: true, active: true })),
uninstall: uninstallService,
} as never,
})),
});
expect(uninstallService).toHaveBeenCalledOnce();
expect(fs.existsSync(paths.cliRoot)).toBe(false);
expect(fs.existsSync(paths.shimPath)).toBe(false);
expect(fs.readFileSync(userData, "utf8")).toBe("keep");
});
it("refuses to remove the shared CLI while another instance service is installed", async () => {
const paths = resolveInstallStorePaths();
const otherUnitPath = path.join(process.env.HOME!, ".config", "systemd", "user", systemdServiceName("team-a"));
fs.mkdirSync(path.dirname(otherUnitPath), { recursive: true });
fs.writeFileSync(otherUnitPath, "unit");
await expect(uninstallCommand({
detectServiceManager: vi.fn(async () => ({
supported: true as const,
manager: { status: vi.fn(async () => ({ installed: false, active: false })) } as never,
})),
platform: "linux",
userHomeDir: process.env.HOME!,
})).rejects.toThrow("other instance services are installed");
expect(fs.existsSync(paths.cliRoot)).toBe(false);
expect(fs.existsSync(otherUnitPath)).toBe(true);
});
it("preserves the managed install when an existing systemd unit cannot be checked", async () => {
const paths = resolveInstallStorePaths();
fs.mkdirSync(path.dirname(paths.shimPath), { recursive: true });
fs.writeFileSync(paths.shimPath, "managed shim");
const unitPath = path.join(
process.env.HOME!,
".config",
"systemd",
"user",
systemdServiceName(resolvePaperclipInstanceId()),
);
fs.mkdirSync(path.dirname(unitPath), { recursive: true });
fs.writeFileSync(unitPath, "unit");
await expect(uninstallCommand({
detectServiceManager: vi.fn(async () => ({
supported: false as const,
reason: "No usable systemd user manager was detected",
})),
platform: "linux",
userHomeDir: process.env.HOME!,
})).rejects.toThrow("Cannot verify or remove the background service");
expect(fs.existsSync(paths.shimPath)).toBe(true);
expect(fs.existsSync(unitPath)).toBe(true);
});
it("rejects a symlinked installs root before npm writes outside the store", async () => {
const paths = resolveInstallStorePaths();
const outside = path.join(root, "outside");
fs.mkdirSync(paths.cliRoot, { recursive: true });
fs.mkdirSync(outside);
fs.symlinkSync(outside, paths.installsRoot, "dir");
const runCommand = vi.fn(async () => ({ stdout: JSON.stringify("2026.720.0"), stderr: "" }));
await expect(installCommand({}, { runCommand })).rejects.toThrow("non-directory install-store path");
expect(runCommand).toHaveBeenCalledTimes(1);
expect(fs.readdirSync(outside)).toEqual([]);
});
it("refuses to uninstall an unverified cli directory", async () => {
const paths = resolveInstallStorePaths();
const unrelatedFile = path.join(paths.cliRoot, "keep.txt");
fs.mkdirSync(paths.cliRoot, { recursive: true });
fs.writeFileSync(unrelatedFile, "keep");
await expect(uninstallCommand()).rejects.toThrow("unverified install store");
expect(fs.readFileSync(unrelatedFile, "utf8")).toBe("keep");
});
it("refuses to uninstall while another store mutation holds the lock", async () => {
const paths = resolveInstallStorePaths();
const payloadPath = payloadPathFor(paths, "npm", "2026.720.0");
initializeInstallStore(paths);
fs.mkdirSync(payloadPath, { recursive: true });
flipCurrentAtomic(payloadPath, paths);
writeInstallManifestAtomic({
schemaVersion: INSTALL_MANIFEST_VERSION,
source: "npm",
version: "2026.720.0",
channel: "latest",
payloadPath,
installedAt: "2026-07-22T18:00:00.000Z",
previous: [],
}, paths);
await withInstallStoreLock(
async () => {
await expect(uninstallCommand()).rejects.toThrow("already running");
},
paths,
);
expect(fs.existsSync(paths.lockPath)).toBe(false);
});
it("refuses a symlinked git payload root before downloading", async () => {
const paths = resolveInstallStorePaths(); initializeInstallStore(paths);
const outside = path.join(root, "outside-git"); fs.mkdirSync(outside);
fs.symlinkSync(outside, path.join(paths.installsRoot, "git"));
const runCommand = vi.fn(async () => ({ stdout: "", stderr: "" }));
await expect(installGitPayload("paperclipai/paperclip", "4".repeat(40), runCommand, paths)).rejects.toThrow("unsafe payload root");
expect(runCommand).not.toHaveBeenCalled();
});
});