From 883690e1284052adfa34b36e8b97de008d93fc32 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Fri, 11 Sep 2026 11:42:12 +0800 Subject: [PATCH] Add local dev binary override and Git-aware versioning --- AGENTS.md | 1 + package.json | 2 + scripts/build-binary.mjs | 100 +++++++++++++++++++-- scripts/dev-override.ts | 158 +++++++++++++++++++++++++++++++++ src/cli.test.ts | 19 ++++ src/cli/commands/update.ts | 24 +++-- src/cli/runner.ts | 7 +- src/version.test.ts | 124 ++++++++++++++++++++++++++ src/version.ts | 174 ++++++++++++++++++++++++++++++++++++- 9 files changed, 585 insertions(+), 24 deletions(-) create mode 100755 scripts/dev-override.ts create mode 100644 src/version.test.ts diff --git a/AGENTS.md b/AGENTS.md index 405dca8..159762c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,6 +21,7 @@ Tests are colocated as `*.test.ts` files in `src/`. OpenAPI source YAML lives in - `bun run openapi:bundle`: rebuild `dist/openapi.json`. - `bun run build:binary`: compile the standalone `seal-use` binary to `dist/bin/seal-use` (gitignored). - `bun run build:plugin`: bundle the MCP server to `dist/mcp/server.js` (tracked, used by `.mcp.json`). +- `bun run dev:override`: compile the host binary with Git dev version metadata, macOS sign, atomically override the Mac global command (`/opt/homebrew/bin/seal-use`), and sync the local Agent Skill. ## Coding Style & Naming Conventions diff --git a/package.json b/package.json index 9565517..87a1fe5 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,8 @@ "build:binary": "node scripts/build-binary.mjs", "build:plugin": "node scripts/build-plugin.mjs", "bump": "bun run scripts/bump-version.ts", + "dev:override": "bun run scripts/dev-override.ts", + "dev:link": "bun run scripts/dev-override.ts", "openapi:bundle": "bun run scripts/bundle-openapi.ts", "openapi:raw": "bun run scripts/generate-raw-openapi.ts", "test": "bun test" diff --git a/scripts/build-binary.mjs b/scripts/build-binary.mjs index 79eee7f..a159fcc 100644 --- a/scripts/build-binary.mjs +++ b/scripts/build-binary.mjs @@ -1,5 +1,5 @@ -import { mkdirSync } from "node:fs"; -import { spawn } from "node:child_process"; +import { mkdirSync, readFileSync } from "node:fs"; +import { spawn, spawnSync } from "node:child_process"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -18,14 +18,95 @@ const args = process.argv.slice(2); const isAll = args.includes("--all") || args.includes("--matrix"); const targetArg = args.find((arg) => arg.startsWith("--target="))?.replace("--target=", ""); const shouldMinify = !args.includes("--no-minify"); +const isRelease = args.includes("--release") || + process.env.SEAL_BUILD_RELEASE === "1" || + (Boolean(process.env.CI) && process.env.GITHUB_REF_TYPE === "tag"); + +function getBuildInfo(releaseMode) { + const pkg = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")); + if (releaseMode) { + return { + version: pkg.version, + channel: "release", + isRelease: true + }; + } + + try { + const res = spawnSync("git", ["describe", "--tags", "--long", "--dirty", "--always"], { + cwd: root, + encoding: "utf8" + }); + if (res.status === 0 && res.stdout) { + const trimmed = res.stdout.trim(); + const dirty = trimmed.endsWith("-dirty"); + const clean = dirty ? trimmed.slice(0, -6) : trimmed; + const longMatch = clean.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/); + let baseVersion = pkg.version; + let commitsAhead = 0; + let commit = ""; + + if (longMatch) { + baseVersion = longMatch[1]; + commitsAhead = Number.parseInt(longMatch[2], 10); + commit = longMatch[3]; + } else { + const rev = spawnSync("git", ["rev-parse", "--short", "HEAD"], { cwd: root, encoding: "utf8" }); + if (rev.status === 0 && rev.stdout) commit = rev.stdout.trim(); + } + + const dirtySuffix = dirty ? ".dirty" : ""; + const commitSuffix = commit ? `+g${commit}${dirtySuffix}` : dirty ? "+dirty" : ""; + const version = `${baseVersion}-dev.${commitsAhead}${commitSuffix}`; + + return { + version, + channel: "dev", + isRelease: false, + git: { + baseVersion, + commitsAhead, + commit, + dirty, + describe: trimmed + } + }; + } + } catch { + // fallback + } + + return { + version: `${pkg.version}-dev.0+local`, + channel: "dev", + isRelease: false + }; +} async function main() { const startTime = Date.now(); + const buildInfo = getBuildInfo(isRelease); + console.log(`[build:binary] version: ${buildInfo.version} (${buildInfo.channel}, isRelease: ${buildInfo.isRelease})`); + + const buildEnv = { + ...process.env, + SEAL_BUILD_VERSION: buildInfo.version, + SEAL_BUILD_CHANNEL: buildInfo.channel, + SEAL_BUILD_IS_RELEASE: String(buildInfo.isRelease), + ...(buildInfo.git ? { + SEAL_BUILD_GIT_BASE: buildInfo.git.baseVersion, + SEAL_BUILD_GIT_COMMITS_AHEAD: String(buildInfo.git.commitsAhead), + SEAL_BUILD_GIT_COMMIT: buildInfo.git.commit, + SEAL_BUILD_GIT_DIRTY: String(buildInfo.git.dirty), + SEAL_BUILD_GIT_DESCRIBE: buildInfo.git.describe + } : {}) + }; + if (isAll) { console.log(`[build:binary] compiling ${Object.keys(TARGET_MAP).length} targets in parallel (minify: ${shouldMinify})...`); await Promise.all( Object.entries(TARGET_MAP).map(([name, config]) => - buildTarget(name, config.bunTarget, resolve(root, config.outfile), shouldMinify) + buildTarget(name, config.bunTarget, resolve(root, config.outfile), shouldMinify, buildEnv) ) ); console.log(`[build:binary] all targets compiled in ${((Date.now() - startTime) / 1000).toFixed(2)}s`); @@ -34,16 +115,16 @@ async function main() { if (!config) { throw new Error(`Unknown target: ${targetArg}. Available targets: ${Object.keys(TARGET_MAP).join(", ")}`); } - await buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile), shouldMinify); + await buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile), shouldMinify, buildEnv); } else { const output = resolve(root, "dist/bin/seal-use"); - await buildTarget("host", null, output, shouldMinify); + await buildTarget("host", null, output, shouldMinify, buildEnv); } } -async function buildTarget(name, bunTarget, output, minify = true) { +async function buildTarget(name, bunTarget, output, minify = true, buildEnv = process.env) { mkdirSync(dirname(output), { recursive: true }); - const buildArgs = ["build", "--compile"]; + const buildArgs = ["build", "--compile", "--env=SEAL_BUILD_*"]; if (minify) { buildArgs.push("--minify"); } @@ -53,7 +134,7 @@ async function buildTarget(name, bunTarget, output, minify = true) { buildArgs.push("--outfile", output, "src/cli.ts"); console.log(`[build:binary] start compiling: ${name} -> ${output}`); - await runAsync(bun, buildArgs); + await runAsync(bun, buildArgs, { env: buildEnv }); if (process.platform === "darwin" && (name.startsWith("darwin") || name === "host")) { try { @@ -74,7 +155,8 @@ function runAsync(command, args, options = {}) { return new Promise((res, rej) => { const child = spawn(command, args, { cwd: root, - stdio: options.quiet ? ["ignore", "ignore", "ignore"] : "inherit" + stdio: options.quiet ? ["ignore", "ignore", "ignore"] : "inherit", + env: options.env ?? process.env }); child.on("error", rej); child.on("exit", (code) => { diff --git a/scripts/dev-override.ts b/scripts/dev-override.ts new file mode 100755 index 0000000..2d06f2c --- /dev/null +++ b/scripts/dev-override.ts @@ -0,0 +1,158 @@ +#!/usr/bin/env bun +import { chmodSync, copyFileSync, existsSync, mkdirSync, rmSync, symlinkSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { homedir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +function resolveTargetBinaryPath(): string { + // 1. Check which seal-use + try { + const whichRes = spawnSync("which", ["seal-use"], { encoding: "utf8" }); + if (whichRes.status === 0 && whichRes.stdout) { + const p = whichRes.stdout.trim(); + if (p && existsSync(p)) { + return p; + } + } + } catch { + // ignore + } + + // 2. Fallback candidate paths in order of preference + const candidates = [ + "/opt/homebrew/bin/seal-use", + "/usr/local/bin/seal-use", + join(homedir(), ".local", "bin", "seal-use"), + join(homedir(), "bin", "seal-use") + ]; + + for (const candidate of candidates) { + const dir = dirname(candidate); + if (existsSync(dir)) { + return candidate; + } + } + + const defaultDir = join(homedir(), ".local", "bin"); + mkdirSync(defaultDir, { recursive: true }); + return join(defaultDir, "seal-use"); +} + +async function main() { + console.error("==> [dev:override] Building latest host binary from local worktree..."); + + // 1. Compile host binary with dev metadata + const buildRes = spawnSync("node", ["scripts/build-binary.mjs"], { + cwd: root, + stdio: ["ignore", "inherit", "inherit"] + }); + + if (buildRes.status !== 0) { + console.error("❌ [dev:override] Build failed."); + process.exit(buildRes.status ?? 1); + } + + const localBinary = join(root, "dist", "bin", "seal-use"); + if (!existsSync(localBinary)) { + console.error(`❌ [dev:override] Expected binary at ${localBinary} not found.`); + process.exit(1); + } + + const targetPath = resolveTargetBinaryPath(); + const targetDir = dirname(targetPath); + mkdirSync(targetDir, { recursive: true }); + + console.error(`==> [dev:override] Installing to global path: ${targetPath}`); + + // 2. Check and stop background service if running + let serviceWasRunning = false; + try { + const statusRes = spawnSync(targetPath, ["service", "status"], { encoding: "utf8" }); + if (statusRes.status === 0 && statusRes.stdout) { + const parsed = JSON.parse(statusRes.stdout); + if (parsed.running) { + console.error("==> [dev:override] Stopping running background service daemon..."); + spawnSync(targetPath, ["service", "stop"], { stdio: "ignore" }); + serviceWasRunning = true; + } + } + } catch { + // ignore + } + + // 3. Atomically overwrite target binary + const tmpTarget = `${targetPath}.tmp.${Date.now()}`; + copyFileSync(localBinary, tmpTarget); + chmodSync(tmpTarget, 0o755); + + if (process.platform === "darwin") { + try { + spawnSync("/usr/bin/codesign", ["--remove-signature", tmpTarget], { stdio: "ignore" }); + spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", tmpTarget], { stdio: "ignore" }); + } catch { + // ignore + } + } + + copyFileSync(tmpTarget, targetPath); + chmodSync(targetPath, 0o755); + try { + rmSync(tmpTarget, { force: true }); + } catch { + // ignore + } + + // 4. Ensure legacy seal-home symlink exists + const legacyLink = join(targetDir, "seal-home"); + if (legacyLink !== targetPath) { + try { + if (existsSync(legacyLink)) rmSync(legacyLink, { force: true }); + symlinkSync(targetPath, legacyLink); + } catch { + // ignore + } + } + + // 5. Sync Agent Skill to ~/.agents/skills/seal-use + const skillSource = join(root, "skills", "seal-use"); + const skillTarget = join(homedir(), ".agents", "skills", "seal-use"); + const legacySkill = join(homedir(), ".agents", "skills", "seal-home"); + if (existsSync(legacySkill)) { + try { + rmSync(legacySkill, { recursive: true, force: true }); + } catch {} + } + if (existsSync(skillSource)) { + try { + const { cpSync } = await import("node:fs"); + mkdirSync(dirname(skillTarget), { recursive: true }); + cpSync(skillSource, skillTarget, { recursive: true }); + console.error(`✓ [dev:override] Synced agent skill to ${skillTarget}`); + } catch (err) { + console.error(`⚠️ [dev:override] Failed to sync agent skill: ${err}`); + } + } + + // 6. Restart service daemon if it was previously running + if (serviceWasRunning) { + console.error("==> [dev:override] Restarting background service daemon with new binary..."); + spawnSync(targetPath, ["service", "start"], { stdio: "ignore" }); + } + + // 7. Verify and output + console.error("✨ [dev:override] Success! Active global seal-use binary is now updated:"); + const testRes = spawnSync(targetPath, ["v"], { encoding: "utf8" }); + if (testRes.status === 0 && testRes.stdout) { + process.stdout.write(testRes.stdout); + } else { + console.error(testRes.stderr || "Failed to verify updated binary"); + } +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/src/cli.test.ts b/src/cli.test.ts index c4fbd18..777539d 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -37,6 +37,25 @@ describe("CLI version & help handling", () => { const parsed = JSON.parse(result.stdout.trim()); expect(parsed.name).toBe("seal-use"); expect(parsed.version).toBe(VERSION); + expect(parsed).toHaveProperty("channel"); + expect(parsed).toHaveProperty("isRelease"); + }); + + test("version output includes structured dev channel and git information", () => { + const result = runCli(["v"]); + expect(result.status).toBe(0); + const parsed = JSON.parse(result.stdout.trim()); + expect(parsed.name).toBe("seal-use"); + expect(typeof parsed.channel).toBe("string"); + expect(typeof parsed.isRelease).toBe("boolean"); + if (!parsed.isRelease) { + expect(parsed.channel).toBe("dev"); + if (parsed.git) { + expect(parsed.git).toHaveProperty("baseVersion"); + expect(parsed.git).toHaveProperty("commitsAhead"); + expect(parsed.git).toHaveProperty("commit"); + } + } }); test("help command prints standard help banner", () => { diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.ts index 467c02a..80ebc3a 100644 --- a/src/cli/commands/update.ts +++ b/src/cli/commands/update.ts @@ -3,7 +3,7 @@ import { dirname, join } from "node:path"; import { spawnSync } from "node:child_process"; import { isCompiledBinary } from "../../core/runtime.js"; import { syncGlobalSkillIfPresent } from "../../core/embedded-skill.js"; -import { VERSION } from "../../version.js"; +import { VERSION, IS_RELEASE } from "../../version.js"; import { runServiceCommand, serviceStatus } from "../service.js"; import { printJson } from "../printer.js"; import { STATE_DIR } from "./service.js"; @@ -46,14 +46,20 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp const cleanTarget = targetVersion.replace(/^v/, ""); const cmp = compareSemVer(cleanTarget, VERSION); if (cmp < 0) { - printJson({ - updated: false, - currentVersion: VERSION, - targetVersion: cleanTarget, - mode: isCompiledBinary() ? "binary" : "source", - message: `Cannot downgrade seal-use from v${VERSION} to older version v${cleanTarget}. Updates must be forward-only.` - }); - return; + if (!IS_RELEASE && options.force) { + // Allow force reinstall/switch from dev build to target release + } else { + printJson({ + updated: false, + currentVersion: VERSION, + targetVersion: cleanTarget, + mode: isCompiledBinary() ? "binary" : "source", + message: !IS_RELEASE + ? `Cannot downgrade seal-use from dev build v${VERSION} to release v${cleanTarget}. Use --force to overwrite.` + : `Cannot downgrade seal-use from v${VERSION} to older version v${cleanTarget}. Updates must be forward-only.` + }); + return; + } } if (cmp === 0 && !options.force) { printJson({ diff --git a/src/cli/runner.ts b/src/cli/runner.ts index bb4d242..3986548 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -4,7 +4,7 @@ import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { createSealClient } from "../core/http/factory.js"; import type { CorpConfig } from "../core/config/types.js"; -import { VERSION } from "../version.js"; +import { VERSION, VERSION_INFO } from "../version.js"; import { handleApprovalRunsCommand } from "./commands/approval-runs.js"; import { handleAnalyticsCommand } from "./commands/analytics.js"; import { handleAuthCommand } from "./commands/auth.js"; @@ -174,10 +174,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) { Boolean(args.options.v) || Boolean(args.options.V) ) { - printJson({ - name: "seal-use", - version: VERSION - }); + printJson(VERSION_INFO); return; } diff --git a/src/version.test.ts b/src/version.test.ts new file mode 100644 index 0000000..b0bfcd1 --- /dev/null +++ b/src/version.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, test } from "bun:test"; +import { formatDevVersion, parseGitDescribe, resolveVersionInfo } from "./version.js"; +import { compareSemVer, isNewerVersion } from "./cli/commands/update.js"; + +describe("Git version parsing and formatting", () => { + test("parses full git describe string with commits ahead and dirty state", () => { + const parsed = parseGitDescribe("v0.10.15-2-ga521a24-dirty"); + expect(parsed).toEqual({ + baseVersion: "0.10.15", + commitsAhead: 2, + commit: "a521a24", + dirty: true, + describe: "v0.10.15-2-ga521a24-dirty" + }); + }); + + test("parses clean git describe string without dirty suffix", () => { + const parsed = parseGitDescribe("v0.10.15-0-g83ade4d"); + expect(parsed).toEqual({ + baseVersion: "0.10.15", + commitsAhead: 0, + commit: "83ade4d", + dirty: false, + describe: "v0.10.15-0-g83ade4d" + }); + }); + + test("parses tag-only git describe with dirty status", () => { + const parsed = parseGitDescribe("v0.10.15-dirty"); + expect(parsed).toEqual({ + baseVersion: "0.10.15", + commitsAhead: 0, + commit: "", + dirty: true, + describe: "v0.10.15-dirty" + }); + }); + + test("parses raw commit hash fallback", () => { + const parsed = parseGitDescribe("83ade4d-dirty", "0.10.15"); + expect(parsed).toEqual({ + baseVersion: "0.10.15", + commitsAhead: 0, + commit: "83ade4d", + dirty: true, + describe: "83ade4d-dirty" + }); + }); + + test("returns null for empty or invalid describe strings", () => { + expect(parseGitDescribe("")).toBeNull(); + expect(parseGitDescribe(" ")).toBeNull(); + expect(parseGitDescribe("invalid/string/without/semver")).toBeNull(); + }); + + test("formats dev version according to standard SemVer 2.0 rules", () => { + expect(formatDevVersion("0.10.15", 2, "a521a24", false)).toBe("0.10.15-dev.2+ga521a24"); + expect(formatDevVersion("0.10.15", 2, "a521a24", true)).toBe("0.10.15-dev.2+ga521a24.dirty"); + expect(formatDevVersion("0.10.15", 0, "83ade4d", false)).toBe("0.10.15-dev.0+g83ade4d"); + expect(formatDevVersion("0.10.15", 0, "83ade4d", true)).toBe("0.10.15-dev.0+g83ade4d.dirty"); + }); +}); + +describe("resolveVersionInfo configuration modes", () => { + test("resolves inlined environment variables when preset", () => { + const info = resolveVersionInfo({ + env: { + SEAL_BUILD_VERSION: "0.10.15-dev.3+g9a7be16", + SEAL_BUILD_CHANNEL: "dev", + SEAL_BUILD_IS_RELEASE: "false", + SEAL_BUILD_GIT_BASE: "0.10.15", + SEAL_BUILD_GIT_COMMITS_AHEAD: "3", + SEAL_BUILD_GIT_COMMIT: "9a7be16", + SEAL_BUILD_GIT_DIRTY: "false", + SEAL_BUILD_GIT_DESCRIBE: "v0.10.15-3-g9a7be16" + } + }); + + expect(info.name).toBe("seal-use"); + expect(info.version).toBe("0.10.15-dev.3+g9a7be16"); + expect(info.channel).toBe("dev"); + expect(info.isRelease).toBe(false); + expect(info.git).toBeDefined(); + expect(info.git?.baseVersion).toBe("0.10.15"); + expect(info.git?.commitsAhead).toBe(3); + expect(info.git?.commit).toBe("9a7be16"); + expect(info.git?.dirty).toBe(false); + }); + + test("resolves release mode when SEAL_FORCE_RELEASE is set", () => { + const info = resolveVersionInfo({ + env: { + SEAL_FORCE_RELEASE: "1" + } + }); + + expect(info.name).toBe("seal-use"); + expect(info.channel).toBe("release"); + expect(info.isRelease).toBe(true); + expect(info.git).toBeUndefined(); + }); +}); + +describe("compareSemVer dev version handling", () => { + test("recognizes future release as newer than dev build", () => { + expect(isNewerVersion("0.10.16", "0.10.15-dev.2+ga521a24")).toBe(true); + expect(isNewerVersion("0.11.0", "0.10.15-dev.2+ga521a24")).toBe(true); + expect(isNewerVersion("1.0.0", "0.10.15-dev.2+ga521a24")).toBe(true); + }); + + test("recognizes base release as older than ahead dev build", () => { + expect(compareSemVer("0.10.15", "0.10.15-dev.2+ga521a24")).toBe(-1); + expect(isNewerVersion("0.10.15", "0.10.15-dev.2+ga521a24")).toBe(false); + }); + + test("correctly compares dev builds by commits ahead", () => { + expect(compareSemVer("0.10.15-dev.3", "0.10.15-dev.2")).toBe(1); + expect(compareSemVer("0.10.15-dev.1", "0.10.15-dev.2")).toBe(-1); + }); + + test("identifies older legacy release as downgrade", () => { + expect(compareSemVer("0.3.3", "0.10.15-dev.2+ga521a24")).toBe(-1); + }); +}); diff --git a/src/version.ts b/src/version.ts index 1a27327..bafa692 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,3 +1,175 @@ +import { spawnSync } from "node:child_process"; import packageJson from "../package.json" with { type: "json" }; -export const VERSION = packageJson.version; +export interface GitBuildInfo { + baseVersion: string; + commitsAhead: number; + commit: string; + dirty: boolean; + describe: string; +} + +export interface VersionInfo { + name: "seal-use"; + version: string; + channel: "release" | "dev"; + isRelease: boolean; + git?: GitBuildInfo; +} + +export function parseGitDescribe(output: string, fallbackVersion = packageJson.version): GitBuildInfo | null { + const trimmed = output.trim(); + if (!trimmed) return null; + + const dirty = trimmed.endsWith("-dirty"); + const clean = dirty ? trimmed.slice(0, -6) : trimmed; + + // Format 1: v0.10.15-2-ga521a24 + const longMatch = clean.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/); + if (longMatch && longMatch[1] && longMatch[2] && longMatch[3]) { + return { + baseVersion: longMatch[1], + commitsAhead: Number.parseInt(longMatch[2], 10), + commit: longMatch[3], + dirty, + describe: trimmed + }; + } + + // Format 2: v0.10.15 + const tagMatch = clean.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)$/); + if (tagMatch && tagMatch[1]) { + return { + baseVersion: tagMatch[1], + commitsAhead: 0, + commit: "", + dirty, + describe: trimmed + }; + } + + // Format 3: 83ade4d + const commitMatch = clean.match(/^([0-9a-f]{7,40})$/); + if (commitMatch && commitMatch[1]) { + return { + baseVersion: fallbackVersion, + commitsAhead: 0, + commit: commitMatch[1], + dirty, + describe: trimmed + }; + } + + return null; +} + +export function formatDevVersion(baseVersion: string, commitsAhead: number, commit: string, dirty: boolean): string { + const dirtySuffix = dirty ? ".dirty" : ""; + const commitSuffix = commit ? `+g${commit}${dirtySuffix}` : dirty ? "+dirty" : ""; + return `${baseVersion}-dev.${commitsAhead}${commitSuffix}`; +} + +export function resolveVersionInfo(options?: { + env?: Record; + cwd?: string; +}): VersionInfo { + const customEnv = options?.env; + const buildVersion = customEnv?.SEAL_BUILD_VERSION ?? process.env.SEAL_BUILD_VERSION; + const buildIsRelease = customEnv?.SEAL_BUILD_IS_RELEASE ?? process.env.SEAL_BUILD_IS_RELEASE; + const buildChannel = customEnv?.SEAL_BUILD_CHANNEL ?? process.env.SEAL_BUILD_CHANNEL; + const buildGitBase = customEnv?.SEAL_BUILD_GIT_BASE ?? process.env.SEAL_BUILD_GIT_BASE; + const buildGitCommitsAhead = customEnv?.SEAL_BUILD_GIT_COMMITS_AHEAD ?? process.env.SEAL_BUILD_GIT_COMMITS_AHEAD; + const buildGitCommit = customEnv?.SEAL_BUILD_GIT_COMMIT ?? process.env.SEAL_BUILD_GIT_COMMIT; + const buildGitDirty = customEnv?.SEAL_BUILD_GIT_DIRTY ?? process.env.SEAL_BUILD_GIT_DIRTY; + const buildGitDescribe = customEnv?.SEAL_BUILD_GIT_DESCRIBE ?? process.env.SEAL_BUILD_GIT_DESCRIBE; + const forceRelease = customEnv?.SEAL_FORCE_RELEASE ?? process.env.SEAL_FORCE_RELEASE; + const cwd = options?.cwd; + + // 1. Check compile-time inlined environment variables + if (buildVersion) { + const isRelease = buildIsRelease === "true"; + const channel = (buildChannel as "release" | "dev") || (isRelease ? "release" : "dev"); + const result: VersionInfo = { + name: "seal-use", + version: buildVersion, + channel, + isRelease + }; + + if (buildGitBase) { + result.git = { + baseVersion: buildGitBase, + commitsAhead: Number.parseInt(buildGitCommitsAhead || "0", 10), + commit: buildGitCommit || "", + dirty: buildGitDirty === "true", + describe: buildGitDescribe || buildVersion + }; + } + return result; + } + + // 2. Explicit force release via environment + if (buildIsRelease === "true" || forceRelease === "1") { + return { + name: "seal-use", + version: packageJson.version, + channel: "release", + isRelease: true + }; + } + + // 3. Dynamic resolution from git repository in dev mode + try { + const res = spawnSync("git", ["describe", "--tags", "--long", "--dirty", "--always"], { + cwd, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"] + }); + + if (res.status === 0 && res.stdout) { + const gitInfo = parseGitDescribe(res.stdout.trim(), packageJson.version); + if (gitInfo) { + if (!gitInfo.commit) { + const revRes = spawnSync("git", ["rev-parse", "--short", "HEAD"], { + cwd, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"] + }); + if (revRes.status === 0 && revRes.stdout) { + gitInfo.commit = revRes.stdout.trim(); + } + } + + const devVersion = formatDevVersion( + gitInfo.baseVersion, + gitInfo.commitsAhead, + gitInfo.commit, + gitInfo.dirty + ); + + return { + name: "seal-use", + version: devVersion, + channel: "dev", + isRelease: false, + git: gitInfo + }; + } + } + } catch { + // Fall back below if git is not installed or error occurs + } + + // 4. Default fallback when git is not available + return { + name: "seal-use", + version: `${packageJson.version}-dev.0+local`, + channel: "dev", + isRelease: false + }; +} + +export const VERSION_INFO = resolveVersionInfo(); +export const VERSION = VERSION_INFO.version; +export const IS_RELEASE = VERSION_INFO.isRelease; +export const CHANNEL = VERSION_INFO.channel;