diff --git a/server/src/__tests__/version.test.ts b/server/src/__tests__/version.test.ts index 9d8f9d8b1f4..cd660a39905 100644 --- a/server/src/__tests__/version.test.ts +++ b/server/src/__tests__/version.test.ts @@ -42,19 +42,98 @@ describe("resolveServerVersion", () => { it("falls back to package version without throwing when git is unavailable", () => { const debugLog = vi.fn(); + const cause = new Error("spawn git ENOENT"); + const err = Object.assign(new Error("fatal: not a git repository"), { + code: 128, + stderr: Buffer.from("fatal: not a git repository\n"), + stdout: "", + cause, + }); expect( resolveServerVersion({ packageVersion: "2026.706.0", gitDescribeCommand: () => { - throw new Error("fatal: not a git repository"); + throw err; }, debugLog, }), ).toBe("2026.706.0"); expect(debugLog).toHaveBeenCalledWith( - expect.objectContaining({ reason: "git_describe_unavailable" }), + expect.objectContaining({ + err: expect.objectContaining({ + cause: expect.objectContaining({ message: "spawn git ENOENT" }), + code: 128, + message: "fatal: not a git repository", + stderr: "fatal: not a git repository\n", + stdout: "", + stack: expect.any(String), + }), + reason: "git_describe_unavailable", + }), "falling back to package version for server version", ); }); + + it("skips git metadata probing for packaged installs under node_modules", () => { + const debugLog = vi.fn(); + + expect( + resolveServerVersion({ + packageVersion: "2026.707.0-canary.12", + debugLog, + packageRoot: "/tmp/npm/_npx/example/node_modules/@paperclipai/server", + }), + ).toBe("2026.707.0-canary.12"); + + expect(debugLog).toHaveBeenCalledWith( + { reason: "packaged_install" }, + "falling back to package version for server version", + ); + }); + + it("uses git metadata for source checkouts whose path contains node_modules", () => { + const debugLog = vi.fn(); + const gitDescribeCommand = vi.fn(() => "v2026.626.0-58-g518fc71ce\n"); + + expect( + resolveServerVersion({ + packageVersion: "2026.707.0-canary.12", + debugLog, + gitDescribeCommand, + packageRoot: "/tmp/node_modules/source/paperclip/server", + pathExists: (path) => path === "/tmp/node_modules/source/paperclip/.git", + realpath: (path) => path, + }), + ).toBe("2026.626.0+58.git.518fc71ce"); + + expect(gitDescribeCommand).toHaveBeenCalledOnce(); + expect(debugLog).not.toHaveBeenCalled(); + }); + + it("keeps fallback diagnostics quiet by default", () => { + const previousDebugFlag = process.env.PAPERCLIP_DEBUG_VERSION_RESOLUTION; + delete process.env.PAPERCLIP_DEBUG_VERSION_RESOLUTION; + const consoleDebug = vi.spyOn(console, "debug").mockImplementation(() => {}); + + try { + expect( + resolveServerVersion({ + packageVersion: "2026.706.0", + gitDescribeCommand: () => { + throw new Error("fatal: not a git repository"); + }, + }), + ).toBe("2026.706.0"); + + expect(consoleDebug).not.toHaveBeenCalled(); + } finally { + consoleDebug.mockRestore(); + if (previousDebugFlag === undefined) { + delete process.env.PAPERCLIP_DEBUG_VERSION_RESOLUTION; + } else { + process.env.PAPERCLIP_DEBUG_VERSION_RESOLUTION = previousDebugFlag; + } + } + }); }); diff --git a/server/src/version.ts b/server/src/version.ts index 1dfff0aa1a7..e543b79e1d5 100644 --- a/server/src/version.ts +++ b/server/src/version.ts @@ -1,5 +1,7 @@ import { createRequire } from "node:module"; import { execFileSync } from "node:child_process"; +import { existsSync, realpathSync } from "node:fs"; +import { basename, dirname, join } from "node:path"; type PackageJson = { version?: string; @@ -7,14 +9,19 @@ type PackageJson = { type GitDescribeCommand = () => string; type DebugLog = (fields: Record, message: string) => void; +type PathExists = (path: string) => boolean; +type Realpath = (path: string) => string; const requirePackage = createRequire(import.meta.url); +const packageRoot = dirname(requirePackage.resolve("../package.json")); const pkg = requirePackage("../package.json") as PackageJson; const GIT_DESCRIBE_RE = /^v(?\d+\.\d+\.\d+)-(?\d+)-g(?[0-9a-f]{7,40})(?-dirty)?$/i; function defaultDebugLog(fields: Record, message: string): void { + if (process.env.PAPERCLIP_DEBUG_VERSION_RESOLUTION !== "1") return; + console.debug(message, fields); } @@ -23,6 +30,7 @@ function defaultGitDescribeCommand(): string { "git", ["describe", "--tags", "--match", "v*", "--long", "--dirty"], { + cwd: packageRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 1500, @@ -30,6 +38,97 @@ function defaultGitDescribeCommand(): string { ); } +function hasPathSegment(path: string, segment: string): boolean { + return path.split(/[\\/]+/).includes(segment); +} + +function safeRealpath(path: string, realpath: Realpath): string { + try { + return realpath(path); + } catch { + return path; + } +} + +function hasGitMetadataBeforeNodeModulesBoundary( + path: string, + pathExists: PathExists, +): boolean { + let current = path; + + while (true) { + if (pathExists(join(current, ".git"))) return true; + + const parent = dirname(current); + if (parent === current || basename(current) === "node_modules") return false; + + current = parent; + } +} + +function isPackagedInstall( + path: string, + { + pathExists = existsSync, + realpath = realpathSync, + }: { pathExists?: PathExists; realpath?: Realpath } = {}, +): boolean { + const realPackageRoot = safeRealpath(path, realpath); + const candidateRoots = Array.from(new Set([path, realPackageRoot])); + const hasNodeModulesSegment = candidateRoots.some((candidate) => + hasPathSegment(candidate, "node_modules"), + ); + + if (!hasNodeModulesSegment) return false; + + return !candidateRoots.some((candidate) => + hasGitMetadataBeforeNodeModulesBoundary(candidate, pathExists), + ); +} + +function normalizeErrorField(value: unknown): unknown { + if (Buffer.isBuffer(value)) return value.toString("utf8"); + if (value instanceof Uint8Array) return Buffer.from(value).toString("utf8"); + return value; +} + +function compactRecord(fields: Record): Record { + return Object.fromEntries( + Object.entries(fields).filter(([, value]) => value !== undefined), + ); +} + +function summarizeError(err: unknown): Record { + if (err && typeof err === "object") { + const errorLike = err as { + name?: unknown; + message?: unknown; + status?: unknown; + signal?: unknown; + code?: unknown; + stdout?: unknown; + stderr?: unknown; + stack?: unknown; + cause?: unknown; + }; + + return compactRecord({ + name: errorLike.name, + message: errorLike.message, + status: errorLike.status, + signal: errorLike.signal, + code: errorLike.code, + stdout: normalizeErrorField(errorLike.stdout), + stderr: normalizeErrorField(errorLike.stderr), + stack: errorLike.stack, + cause: + errorLike.cause === undefined ? undefined : summarizeError(errorLike.cause), + }); + } + + return { message: String(err) }; +} + export function parseGitDescribeVersion(output: string): string | null { const match = output.trim().match(GIT_DESCRIBE_RE); if (!match?.groups) return null; @@ -51,11 +150,28 @@ export function resolveServerVersion( gitDescribeCommand?: GitDescribeCommand; packageVersion?: string; debugLog?: DebugLog; + packageRoot?: string; + pathExists?: PathExists; + realpath?: Realpath; } = {}, ): string { const packageVersion = opts.packageVersion ?? pkg.version ?? "0.0.0"; const gitDescribeCommand = opts.gitDescribeCommand ?? defaultGitDescribeCommand; const debugLog = opts.debugLog ?? defaultDebugLog; + const resolvedPackageRoot = opts.packageRoot ?? packageRoot; + + if ( + isPackagedInstall(resolvedPackageRoot, { + pathExists: opts.pathExists, + realpath: opts.realpath, + }) + ) { + debugLog( + { reason: "packaged_install" }, + "falling back to package version for server version", + ); + return packageVersion; + } try { const parsedVersion = parseGitDescribeVersion(gitDescribeCommand()); @@ -67,7 +183,7 @@ export function resolveServerVersion( ); } catch (err) { debugLog( - { err, reason: "git_describe_unavailable" }, + { err: summarizeError(err), reason: "git_describe_unavailable" }, "falling back to package version for server version", ); }