From 87bb10f5278512034a5ffee25df1a16b0d712a29 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Thu, 29 Oct 2026 15:10:40 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(install):=20=E6=94=AF=E6=8C=81=20--sys?= =?UTF-8?q?tem=20=E4=B8=8E=20--user=20=E6=A8=A1=E5=BC=8F=E5=88=87=E6=8D=A2?= =?UTF-8?q?=E5=B9=B6=E8=87=AA=E5=8A=A8=E6=B8=85=E7=90=86=E6=AE=8B=E7=95=99?= =?UTF-8?q?=E4=BA=8C=E8=BF=9B=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在 scripts/install.sh 中默认安装至用户目录 ~/.local/bin,并自动清理历史遗留的 /opt/homebrew/bin/seal-use - 在 scripts/dev-override.ts 中优先命中 ~/.local/bin/seal-use,忽略 Homebrew 路径并自动清理残留 - 在 seal-use update 中支持 --system(提权迁移至 /usr/local/bin)与 --user(降权回归至 ~/.local/bin)选项,添加 seal-use migrate 别名 - 迁移与更新时自动清理另一端的非活动实体二进制(恪守 Single Binary Invariant) - 自更新权限预检:当目标位于系统目录且缺少写权限时,友好提示 sudo seal-use update 而非底层报错 - 在 seal-use doctor 中增加执行模式识别与多份二进制(PATH 阴影)检测告警 --- scripts/dev-override.ts | 18 +++- scripts/install.sh | 20 ++++- skills/seal-use/references/cli.md | 5 +- src/cli.test.ts | 13 +++ src/cli/area-aliases.ts | 2 +- src/cli/commands/update.test.ts | 60 ++++++++++++- src/cli/commands/update.ts | 142 ++++++++++++++++++++++++++---- src/cli/help.ts | 16 +++- src/cli/parser.ts | 2 +- src/cli/runner.ts | 19 +++- src/core/doctor/diagnose.test.ts | 3 + src/core/doctor/diagnose.ts | 28 +++++- 12 files changed, 294 insertions(+), 34 deletions(-) diff --git a/scripts/dev-override.ts b/scripts/dev-override.ts index 762308a..9a83daa 100755 --- a/scripts/dev-override.ts +++ b/scripts/dev-override.ts @@ -13,8 +13,8 @@ export function resolveTargetBinaryPath(): string { const whichRes = spawnSync("which", ["seal-use"], { encoding: "utf8", env: { ...process.env } }); if (whichRes.status === 0 && whichRes.stdout) { const p = whichRes.stdout.trim(); - if (p && existsSync(p)) { - // Preserve native binary symlinks, but never overwrite an npm-linked source entry. + if (p && existsSync(p) && !p.startsWith("/opt/homebrew")) { + // Preserve native binary symlinks, but never overwrite an npm-linked source entry or stale Homebrew. const target = realpathSync(p); return /\.(?:[cm]?[jt]sx?|sh)$/i.test(target) ? p : target; } @@ -25,8 +25,8 @@ export function resolveTargetBinaryPath(): string { // 2. Fallback candidate paths in order of preference const candidates = [ - "/usr/local/bin/seal-use", join(homedir(), ".local", "bin", "seal-use"), + "/usr/local/bin/seal-use", join(homedir(), "bin", "seal-use") ]; @@ -105,6 +105,18 @@ async function main() { // ignore } + // Clean up stale /opt/homebrew/bin/seal-use if present + for (const stale of ["/opt/homebrew/bin/seal-use", "/opt/homebrew/bin/seal-home"]) { + if (existsSync(stale) && stale !== targetPath) { + try { + rmSync(stale, { force: true }); + console.error(`✓ [dev:override] Cleaned stale Homebrew binary at ${stale}`); + } catch { + // ignore + } + } + } + // 4. Sync Agent Skill to ~/.agents/skills/seal-use const skillTarget = join(homedir(), ".agents", "skills", "seal-use"); // Install the binary's manifest, including references sourced outside skills/seal-use. diff --git a/scripts/install.sh b/scripts/install.sh index a6f726d..a3abe86 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -44,12 +44,12 @@ TARGET_DIR="${SEAL_USE_INSTALL_DIR:-${SEAL_HOME_INSTALL_DIR:-}}" if [ -n "$TARGET_DIR" ]; then mkdir -p "$TARGET_DIR" else - # Reuse an existing command's directory so a second installation does not get shadowed on PATH. + # Default to user directory (~/.local/bin) unless an active writable system command is already in use. EXISTING_COMMAND="$(command -v seal-use || true)" - if [ -n "$EXISTING_COMMAND" ] && [ -f "$EXISTING_COMMAND" ] && [ -w "$(dirname "$EXISTING_COMMAND")" ]; then + if [ -n "$EXISTING_COMMAND" ] && [ -f "$EXISTING_COMMAND" ] && [ -w "$(dirname "$EXISTING_COMMAND")" ] && [ "$(dirname "$EXISTING_COMMAND")" != "/opt/homebrew/bin" ]; then TARGET_DIR="$(dirname "$EXISTING_COMMAND")" else - for candidate in "/usr/local/bin" "$HOME/.local/bin" "$HOME/bin"; do + for candidate in "$HOME/.local/bin" "$HOME/bin" "/usr/local/bin"; do if [ -d "$candidate" ] && [ -w "$candidate" ]; then TARGET_DIR="$candidate" break @@ -263,6 +263,20 @@ if [ "$PLATFORM" = "darwin" ] && command -v codesign >/dev/null 2>&1; then codesign --force --sign - "$TARGET_PATH" 2>/dev/null || true fi +# Clean up stale/shadowed Homebrew binaries +for stale in "/opt/homebrew/bin/seal-use" "/opt/homebrew/bin/seal-home"; do + if [ -e "$stale" ] || [ -L "$stale" ]; then + if [ "$stale" != "$TARGET_PATH" ]; then + if [ -w "$stale" ] || [ -w "$(dirname "$stale")" ]; then + echo "==> Cleaning up legacy/shadowed Homebrew binary at ${stale}..." + rm -f "$stale" 2>/dev/null || true + else + echo "::warning::Legacy binary found at ${stale}. Remove it with: rm -f ${stale}" + fi + fi + fi +done + # Clean legacy skill to avoid model routing collisions, then install new seal-use skill LEGACY_SKILL_DIR="$HOME/.agents/skills/seal-home" if [ -e "$LEGACY_SKILL_DIR" ]; then diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index c6240cc..b64a3bc 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -212,10 +212,13 @@ seal-use documents search [--max-results 20] [--corp ] seal-use documents create --title --purpose <purpose> [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>] seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>] seal-use documents delete <documentId> [--dry-run|--yes|--confirm] [--corp <corpId>] -seal-use update [--check] [--force] [--version <v>] +seal-use update [--system|--user] [--check] [--force] [--version <v>] +seal-use update --system +seal-use update --user seal-use update check seal-use update changelog [--limit <n>] seal-use changelog [--limit <n>] +seal-use migrate --system|--user seal-use probe [<corpId>] seal-use langfuse check seal-use langfuse cache-refresh <traceId> [--trace-id <traceId>] diff --git a/src/cli.test.ts b/src/cli.test.ts index 2496cfe..58c9e3b 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -161,6 +161,19 @@ describe("CLI version & help handling", () => { expect(parsed.version).toBe(VERSION); }, 20000); + test("migrate command without target flags shows usage error", () => { + const result = runCli(["migrate"]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("Usage: seal-use migrate --system | --user"); + }); + + test("update help shows system and user migration options", () => { + const result = runCli(["update", "--help"]); + expect(result.status).toBe(0); + expect(result.stdout).toContain("--system"); + expect(result.stdout).toContain("--user"); + }); + test("mcp-config outputs valid mcp configuration json", () => { const result = runCli(["mcp-config"]); expect(result.status).toBe(0); diff --git a/src/cli/area-aliases.ts b/src/cli/area-aliases.ts index afed5e2..5d92177 100644 --- a/src/cli/area-aliases.ts +++ b/src/cli/area-aliases.ts @@ -9,7 +9,7 @@ export const AREA_ALIASES: Readonly<Record<string, string>> = { } export const UPDATE_ALIASES = new Set([ - "update", "upgrade", "up", "self-update", "selfupdate" + "update", "upgrade", "up", "self-update", "selfupdate", "migrate" ]) export function normalizeCliArea(area: string): string { diff --git a/src/cli/commands/update.test.ts b/src/cli/commands/update.test.ts index d10663d..7c6d6ab 100644 --- a/src/cli/commands/update.test.ts +++ b/src/cli/commands/update.test.ts @@ -2,7 +2,18 @@ import { describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { compareSemVer, getMirrorMode, handleUpdateCommand, isNewerVersion, matchAssetForPlatform, pruneUpdateLeftovers } from "./update.js"; +import { + SYSTEM_BINARY_PATH, + cleanStaleBinaries, + compareSemVer, + getMirrorMode, + getUserBinaryPath, + handleUpdateCommand, + isNewerVersion, + isPathWritable, + matchAssetForPlatform, + pruneUpdateLeftovers +} from "./update.js"; type Asset = { name: string; downloadUrl: string; size: number }; @@ -295,4 +306,51 @@ describe("update installation modes", () => { rmSync(dir, { recursive: true, force: true }); } }); + + test("rejects conflicting --system and --user flags", async () => { + const dir = mkdtempSync(join(tmpdir(), "seal-conflicting-flags-")); + try { + await expect(handleUpdateCommand({ appRoot: dir, entryFile: join(dir, "src", "cli.ts") }, { system: true, user: true })) + .rejects.toMatchObject({ exitCode: 13, message: "Cannot specify both --system and --user." }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("rejects --system and --user in source development mode", async () => { + const dir = mkdtempSync(join(tmpdir(), "seal-source-mode-flags-")); + try { + await expect(handleUpdateCommand({ appRoot: dir, entryFile: join(dir, "src", "cli.ts") }, { system: true })) + .rejects.toMatchObject({ exitCode: 13 }); + await expect(handleUpdateCommand({ appRoot: dir, entryFile: join(dir, "src", "cli.ts") }, { user: true })) + .rejects.toMatchObject({ exitCode: 13 }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("isPathWritable verifies path and parent directory writability", () => { + const dir = mkdtempSync(join(tmpdir(), "seal-writable-test-")); + try { + expect(isPathWritable(dir)).toBe(true); + expect(isPathWritable(join(dir, "sub", "target"))).toBe(true); + const testFile = join(dir, "file"); + writeFileSync(testFile, "test"); + expect(isPathWritable(testFile)).toBe(true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("getUserBinaryPath returns user home directory path", () => { + const userPath = getUserBinaryPath(); + expect(userPath).toContain(".local"); + expect(userPath).toContain("seal-use"); + expect(SYSTEM_BINARY_PATH).toBe("/usr/local/bin/seal-use"); + }); + + test("cleanStaleBinaries ignores activePath and returns list of cleaned files", () => { + const cleaned = cleanStaleBinaries(SYSTEM_BINARY_PATH); + expect(Array.isArray(cleaned)).toBe(true); + }); }); diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.ts index b8151c5..97889c2 100644 --- a/src/cli/commands/update.ts +++ b/src/cli/commands/update.ts @@ -1,4 +1,5 @@ -import { chmodSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs"; +import { accessSync, chmodSync, constants, existsSync, lstatSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; import { basename, dirname, join } from "node:path"; import { spawnSync } from "node:child_process"; import { isCompiledBinary } from "../../core/runtime.js"; @@ -15,6 +16,61 @@ const LEGACY_GITHUB_REPO = "yunyingk/seal-home"; const GITHUB_REPO_ENV = "SEAL_USE_GITHUB_REPO"; const LEGACY_GITHUB_REPO_ENV = "SEAL_HOME_GITHUB_REPO"; +export const SYSTEM_BINARY_PATH = "/usr/local/bin/seal-use"; + +export function getUserBinaryPath(): string { + return join(homedir(), ".local", "bin", "seal-use"); +} + +export function isPathWritable(targetPath: string): boolean { + try { + if (!existsSync(targetPath)) { + const parent = dirname(targetPath); + return isPathWritable(parent); + } + accessSync(targetPath, constants.W_OK); + const stat = statSync(targetPath); + if (!stat.isDirectory()) { + accessSync(dirname(targetPath), constants.W_OK); + } + return true; + } catch { + return false; + } +} + +export function cleanStaleBinaries(activePath: string): string[] { + const cleaned: string[] = []; + const home = homedir(); + const userBinary = getUserBinaryPath(); + const userAlias = join(home, ".local", "bin", "seal-home"); + const systemBinary = SYSTEM_BINARY_PATH; + const systemAlias = "/usr/local/bin/seal-home"; + const homebrewBinary = "/opt/homebrew/bin/seal-use"; + const homebrewAlias = "/opt/homebrew/bin/seal-home"; + + const candidates = [homebrewBinary, homebrewAlias]; + if (activePath === systemBinary) { + candidates.push(userBinary, userAlias); + } else if (activePath === userBinary) { + candidates.push(systemBinary, systemAlias); + } + + for (const candidate of candidates) { + if (candidate === activePath) continue; + try { + lstatSync(candidate); + rmSync(candidate, { force: true }); + cleaned.push(candidate); + console.error(`✓ [update] Cleaned stale/shadowed binary at ${candidate}`); + } catch { + // ignore if non-existent or permission denied + } + } + + return cleaned; +} + export type UpdateOptions = { checkOnly?: boolean; changelogOnly?: boolean; @@ -23,9 +79,15 @@ export type UpdateOptions = { targetVersion?: string; repo?: string; bgSave?: boolean; + system?: boolean; + user?: boolean; }; export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOptions = {}) { + if (options.system && options.user) { + throw validationError("Cannot specify both --system and --user."); + } + const repo = options.repo || process.env[GITHUB_REPO_ENV]?.trim() || process.env[LEGACY_GITHUB_REPO_ENV]?.trim() @@ -53,7 +115,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp return; } } - if (cmp === 0 && !options.force) { + if (cmp === 0 && !options.force && !options.system && !options.user) { printJson({ updated: false, currentVersion: VERSION, @@ -87,6 +149,13 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp // 2. Source development mode (running via bun/node) if (!isCompiledBinary()) { + if (options.system || options.user) { + throw validationError( + "Source development mode does not install binaries into system or user directories. Use 'bun run dev:override' for local testing.", + "bun run dev:override" + ); + } + if (options.checkOnly) { const releases = await fetchGitHubReleases(repo, 30); const latestRelease = releases[0]; @@ -154,11 +223,33 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp const platform = detectPlatform(); const arch = detectArch(); - // Every binary-mode invocation sweeps here, not just real updates: the SWR - // background check (`update check --bg-save`) is the only command many users - // ever run after their last update, so it is what reclaims that update's - // `.old.<timestamp>` backup (undeletable while its image was executing). - pruneUpdateLeftovers(process.execPath); + const execPath = process.execPath; + const targetExecPath = options.system + ? SYSTEM_BINARY_PATH + : options.user + ? getUserBinaryPath() + : execPath; + const isMigration = targetExecPath !== execPath; + + // Pre-flight permission checks + if (options.system && !isPathWritable(targetExecPath)) { + throw validationError( + `Target location ${targetExecPath} requires elevated (root) privileges to install.`, + `sudo seal-use update --system` + ); + } + + if (!options.user && !isPathWritable(targetExecPath)) { + throw validationError( + `Active binary at ${targetExecPath} requires root privileges to update. Run with sudo, or migrate to user directory using 'seal-use update --user'.`, + `sudo seal-use update` + ); + } + + pruneUpdateLeftovers(targetExecPath); + if (targetExecPath !== execPath) { + pruneUpdateLeftovers(execPath); + } const { releases, source } = await fetchReleasesWithSource(repo, 30); const release = targetVersion @@ -193,7 +284,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp const latestVersion = release.version; const currentRelease = releases.find((r) => r.version === VERSION); const isUpgrade = isNewerVersion(latestVersion, VERSION); - const shouldUpdate = isUpgrade || Boolean(options.force); + const shouldUpdate = isUpgrade || Boolean(options.force) || isMigration; const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION)); if (release?.version) { @@ -209,6 +300,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp } if (options.checkOnly) { + const installMode = targetExecPath === SYSTEM_BINARY_PATH ? "system" : targetExecPath.includes(".local/bin") ? "user" : "custom"; printJson({ updated: false, updateAvailable: isUpgrade, @@ -216,6 +308,8 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp currentVersionPublishedAt: currentRelease?.publishedAt, latestVersion, latestVersionPublishedAt: release.publishedAt, + installMode, + activePath: targetExecPath, behindCount: pendingReleases.length, pendingReleases: pendingReleases.map((r) => ({ version: r.version, @@ -233,12 +327,15 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp } if (!shouldUpdate) { + const cleaned = cleanStaleBinaries(targetExecPath); printJson({ updated: false, currentVersion: VERSION, currentVersionPublishedAt: currentRelease?.publishedAt, latestVersion, latestVersionPublishedAt: release.publishedAt, + targetPath: targetExecPath, + cleanedPaths: cleaned.length ? cleaned : undefined, mode: "binary", message: `seal-use is already up to date (v${VERSION})` }); @@ -255,9 +352,9 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp } // Download binary or archive - const execPath = process.execPath; - const execDir = dirname(execPath); - const tmpDir = join(execDir, `.tmp-update-${Date.now()}`); + const targetDir = dirname(targetExecPath); + mkdirSync(targetDir, { recursive: true }); + const tmpDir = join(targetDir, `.tmp-update-${Date.now()}`); mkdirSync(tmpDir, { recursive: true }); try { @@ -283,19 +380,22 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp } } - // Atomic replace + // Atomic replace at targetExecPath if (process.platform === "win32") { - const oldBinary = `${execPath}.old.${Date.now()}`; + const oldBinary = `${targetExecPath}.old.${Date.now()}`; try { - renameSync(execPath, oldBinary); + renameSync(targetExecPath, oldBinary); } catch { // ignore } - renameSync(newBinaryPath, execPath); + renameSync(newBinaryPath, targetExecPath); } else { - renameSync(newBinaryPath, execPath); + renameSync(newBinaryPath, targetExecPath); } + // Single binary invariant: clean stale/shadowed binaries + const cleaned = cleanStaleBinaries(targetExecPath); + // Refresh the Agent Skill from the binary that is now on disk — never from this process. // // `renameSync` above advanced the file at `execPath`, but this process keeps executing the @@ -304,7 +404,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp // new one, leaving the agent a full release behind (and `skillSynced: <dir>` reported success // either way). One synchronous child reads the new image's embedded copy; it exits before this // function returns, and nothing is left running. - const skillSync = installSkillFromInstalledBinary(execPath, latestVersion); + const skillSync = installSkillFromInstalledBinary(targetExecPath, latestVersion); saveUpdateCache({ latestVersion, @@ -312,10 +412,18 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp releaseUrl: release.htmlUrl }); + if (isMigration) { + console.error(`✨ [update] Successfully migrated seal-use to ${targetExecPath}`); + } + printJson({ updated: true, fromVersion: VERSION, toVersion: latestVersion, + targetPath: targetExecPath, + migrated: isMigration, + fromPath: isMigration ? execPath : undefined, + cleanedPaths: cleaned.length ? cleaned : undefined, skillSynced: skillSync.targetDir ?? false, skillVersion: skillSync.version ?? false, mode: "binary" diff --git a/src/cli/help.ts b/src/cli/help.ts index 235a480..48ffb21 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -1416,12 +1416,22 @@ export const HELP_REGISTRY: AreaHelp[] = [ commands: [ { name: "", - summary: "Update seal-use to latest or target version", + summary: "Update seal-use to latest or target version, or migrate installation mode", usage: [ - "seal-use update [--check] [--force] [--version <v>]", + "seal-use update [--system|--user] [--check] [--force] [--version <v>]", + "seal-use update --system", + "seal-use update --user", "seal-use update check", "seal-use update changelog [--limit <n>]", - "seal-use changelog [--limit <n>]" + "seal-use changelog [--limit <n>]", + "seal-use migrate --system|--user" + ], + options: [ + { flag: "--system", description: "Migrate and update to system directory (/usr/local/bin, requires root)" }, + { flag: "--user", description: "Migrate and update to user directory (~/.local/bin, sudo-free)" }, + { flag: "--check", description: "Check whether updates are available without installing" }, + { flag: "--force", description: "Force reinstall even if already at latest version" }, + { flag: "--version <v>", description: "Target specific release version" } ] } ] diff --git a/src/cli/parser.ts b/src/cli/parser.ts index 1f30825..c60a864 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -35,7 +35,7 @@ export const BOOLEAN_FLAGS = new Set([ "r", "raw-json", "rawJson", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret", "save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation", "skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict", - "summary", "to-downloads", "toDownloads", "v", "wait", "with-expense-extraction", "withExpenseExtraction", "with-flow", + "summary", "system", "to-downloads", "toDownloads", "user", "v", "wait", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workspace", "yes" ]); diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 22ba08d..4e6b905 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url"; import type { CorpConfig } from "../core/config/types.js"; import { VERSION_INFO } from "../version.js"; import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../core/update-cache.js"; -import { classifyCliError, usageError } from "../core/errors.js"; +import { classifyCliError, usageError, validationError } from "../core/errors.js"; import { booleanOption, materialPackFilePolicyOptions, @@ -185,10 +185,21 @@ async function dispatchUpdate(args: ParsedArgs, runtime: CliRuntime): Promise<vo booleanOption(args.options["bg-save"]) === true || booleanOption(args.options["silent-save"]) === true; + const isSystem = booleanOption(args.options.system) === true || lowerAction === "system"; + const isUser = booleanOption(args.options.user) === true || lowerAction === "user"; + + if (isSystem && isUser) { + throw validationError("Cannot specify both --system and --user."); + } + + if (rawArea === "migrate" && !isSystem && !isUser) { + throw usageError("Usage: seal-use migrate --system | --user", "seal-use migrate --user"); + } + const targetVersion = stringOption(args.options.version) ?? stringOption(args.options.tag) ?? - (!isChangelog && !isCheck && !isBgSave && action && !action.startsWith("-") ? action : undefined); + (!isChangelog && !isCheck && !isBgSave && !isSystem && !isUser && action && !action.startsWith("-") ? action : undefined); await (await import("./commands/update.js")).handleUpdateCommand(runtime, { checkOnly: isCheck || isBgSave, @@ -197,7 +208,9 @@ async function dispatchUpdate(args: ParsedArgs, runtime: CliRuntime): Promise<vo force: booleanOption(args.options.force), targetVersion, repo: stringOption(args.options.repo), - bgSave: isBgSave + bgSave: isBgSave, + system: isSystem, + user: isUser }); return; } diff --git a/src/core/doctor/diagnose.test.ts b/src/core/doctor/diagnose.test.ts index 1ff2d26..62b4b7b 100644 --- a/src/core/doctor/diagnose.test.ts +++ b/src/core/doctor/diagnose.test.ts @@ -58,6 +58,9 @@ describe("Doctor Diagnosis Engine", () => { expect(diagnosis.directories.agentSkillDir).toBeDefined(); expect(diagnosis.checks.length).toBeGreaterThanOrEqual(3); + const execCheck = diagnosis.checks.find((c) => c.id === "executable"); + expect(execCheck).toBeDefined(); + expect(execCheck?.message).toMatch(/模式/); expect(diagnosis.knowledge.directorySpecsCount).toBe(EMBEDDED_DIRECTORY_SPECS.length); }); diff --git a/src/core/doctor/diagnose.ts b/src/core/doctor/diagnose.ts index 0e2e688..f4c64a6 100644 --- a/src/core/doctor/diagnose.ts +++ b/src/core/doctor/diagnose.ts @@ -224,13 +224,39 @@ export function diagnoseSystem(): DoctorDiagnosis { const checks: HealthCheckItem[] = []; // Check 1: Executable + const isSystem = process.execPath === "/usr/local/bin/seal-use" || process.execPath.startsWith("/usr/local/"); + const isUser = process.execPath.includes(".local/bin"); + const modeLabel = isSystem ? "系统全局模式 (/usr/local/bin)" : isUser ? "普通用户模式 (~/.local/bin)" : "独立模式"; + checks.push({ id: "executable", title: "命令行二进制", status: "ok", - message: `当前执行路径: ${process.execPath}` + message: `${process.execPath} [${modeLabel}]` }); + // Check 1b: Duplicate / Shadowed Binaries + const knownBinaryLocations = [ + join(home, ".local", "bin", "seal-use"), + "/usr/local/bin/seal-use", + "/opt/homebrew/bin/seal-use", + join(home, "bin", "seal-use") + ]; + const detectedBunWhich = Bun.which("seal-use"); + const existingBinaries = Array.from(new Set( + [detectedBunWhich, ...knownBinaryLocations, process.execPath] + .filter((p): p is string => Boolean(p && existsSync(p))) + )); + + if (existingBinaries.length > 1) { + checks.push({ + id: "binary_integrity", + title: "多份二进制检测 (PATH 阴影风险)", + status: "warn", + message: `检测到多份 seal-use 实体: ${existingBinaries.join(", ")} (当前生效: ${detectedBunWhich ?? process.execPath})` + }); + } + // Check 2: Config Directory if (directories.configDir?.exists && directories.configDir.writable) { checks.push({ From 0ab524a2aaedbc76f2ab0556826e7099ec50a32f Mon Sep 17 00:00:00 2001 From: yunyingk <haoda2195176187@gmail.com> Date: Thu, 29 Oct 2026 15:12:01 +0800 Subject: [PATCH 2/2] =?UTF-8?q?feat(dev):=20dev:override=20=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E7=B3=BB=E7=BB=9F=E7=9B=AE=E5=BD=95=E6=9D=83=E9=99=90?= =?UTF-8?q?=E9=A2=84=E6=A3=80=E4=B8=8E=E5=8F=8B=E5=A5=BD=E7=9A=84=20sudo/?= =?UTF-8?q?=E8=BF=81=E7=A7=BB=E5=BC=95=E5=AF=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/dev-override.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/scripts/dev-override.ts b/scripts/dev-override.ts index 9a83daa..b8a7f41 100755 --- a/scripts/dev-override.ts +++ b/scripts/dev-override.ts @@ -1,5 +1,5 @@ #!/usr/bin/env bun -import { chmodSync, copyFileSync, existsSync, mkdirSync, realpathSync, renameSync, rmSync } from "node:fs"; +import { accessSync, chmodSync, constants, copyFileSync, existsSync, mkdirSync, realpathSync, renameSync, rmSync } from "node:fs"; import { spawnSync } from "node:child_process"; import { homedir } from "node:os"; import { dirname, join, resolve } from "node:path"; @@ -64,7 +64,19 @@ async function main() { const targetPath = resolveTargetBinaryPath(); const targetDir = dirname(targetPath); - mkdirSync(targetDir, { recursive: true }); + + try { + mkdirSync(targetDir, { recursive: true }); + accessSync(targetDir, constants.W_OK); + if (existsSync(targetPath)) { + accessSync(targetPath, constants.W_OK); + } + } catch { + console.error(`❌ [dev:override] Permission denied: Target path '${targetPath}' requires root privileges.`); + console.error(`👉 Next action: run with sudo: 'sudo bun run dev:override'`); + console.error(`💡 Tip: To develop without sudo, migrate to user directory first: 'seal-use update --user'`); + process.exit(1); + } console.error(`==> [dev:override] Installing to global path: ${targetPath}`);