diff --git a/README.md b/README.md index a424e7c..4eca36a 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ Because `npm link` makes the global command a symlink into your checkout, **upda Enterprise configs live only in the global directory `~/.config/seal-use/enterprises` (legacy fallback `~/.config/seal-home/enterprises`); the project tree carries none. -The canonical plugin skill lives at `skills/seal-use`. There is no in-repo `.agents/skills/seal-use` symlink; run `seal-use skill install` (or copy that folder yourself) to place it in a Codex skills directory such as `~/.agents/skills/seal-use` when you want Codex to invoke the workflow as `$seal-use`. +The canonical plugin skill lives at `skills/seal-use`. There is no in-repo `.agents/skills/seal-use` symlink; run `seal-use skill install` (or `seal-use skill install --dir `) to place it in a Codex skills directory such as `~/.agents/skills/seal-use` when you want Codex to invoke the workflow as `$seal-use`. The installer includes the full embedded manifest, including report references sourced outside that folder; manually copying only the skill folder omits those references. ## ZCode Plugin diff --git a/SECURITY.md b/SECURITY.md index 6168042..e146a9e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -41,7 +41,8 @@ than described here. full API access, so "read-only" is guaranteed only by this client (it exposes `GET` only — see `src/domains/langfuse/client.ts`), and anyone with the binary can extract the key pair. The repository and its Releases are private, which is what bounds distribution. Treat Langfuse traces - and `.cache/langfuse/` as sensitive (they can contain enterprise approval data); rotate the key + and `~/.cache/seal-use/langfuse/` (plus legacy `.cache/langfuse/` entries) as sensitive + (they can contain enterprise approval data); rotate the key pair in Langfuse and update the four `LANGFUSE_*` repository secrets to re-key. - **Self-update and the install script do not verify signatures.** `seal-use update` downloads a release binary and replaces the running executable; `scripts/install.sh` compares diff --git a/scripts/bump-version.ts b/scripts/bump-version.ts index b17893c..6707a62 100644 --- a/scripts/bump-version.ts +++ b/scripts/bump-version.ts @@ -1,7 +1,8 @@ #!/usr/bin/env bun -import { readFileSync, writeFileSync } from "node:fs"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; import { join } from "node:path"; -import { execSync } from "node:child_process"; +import { execSync, spawnSync } from "node:child_process"; const ROOT = join(import.meta.dirname, ".."); const pkgPath = join(ROOT, "package.json"); @@ -87,14 +88,14 @@ console.log("✓ Updated skills/seal-use/SKILL.md"); // 5. Sync to global ~/.agents/skills/seal-use/ if present -const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "seal-use"); -const legacyGlobalSkillDir = join(process.env.HOME || "", ".agents", "skills", "seal-home"); -const { existsSync, cpSync, rmSync } = await import("node:fs"); -if (existsSync(legacyGlobalSkillDir)) { - rmSync(legacyGlobalSkillDir, { recursive: true, force: true }); -} -if (existsSync(globalSkillDir)) { - cpSync(join(ROOT, "skills", "seal-use"), globalSkillDir, { recursive: true }); +const globalSkillDir = join(homedir(), ".agents", "skills", "seal-use"); +const legacyGlobalSkillDir = join(homedir(), ".agents", "skills", "seal-home"); +if (existsSync(globalSkillDir) || existsSync(legacyGlobalSkillDir)) { + // A fresh source process reads the bumped skill, including the full embedded resource manifest. + const sync = spawnSync(process.execPath, [join(ROOT, "src", "cli.ts"), "skill", "install", "--dir", globalSkillDir], { + cwd: ROOT, stdio: "inherit", env: { ...process.env, SEAL_DISABLE_BG_UPDATE: "1" } + }); + if (sync.status !== 0) throw new Error(`Failed to sync bumped Agent Skill: ${sync.error || sync.status}`); console.log("✓ Synchronized ~/.agents/skills/seal-use/"); } diff --git a/scripts/dev-override.ts b/scripts/dev-override.ts index 85ee21a..a84f23c 100755 --- a/scripts/dev-override.ts +++ b/scripts/dev-override.ts @@ -1,5 +1,5 @@ #!/usr/bin/env bun -import { chmodSync, copyFileSync, existsSync, mkdirSync, rmSync } from "node:fs"; +import { chmodSync, 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"; @@ -7,14 +7,16 @@ import { fileURLToPath } from "node:url"; const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); -function resolveTargetBinaryPath(): string { +export function resolveTargetBinaryPath(): string { // 1. Check which seal-use try { - const whichRes = spawnSync("which", ["seal-use"], { encoding: "utf8" }); + 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)) { - return p; + // Preserve native binary symlinks (Homebrew), but never overwrite an npm-linked source entry. + const target = realpathSync(p); + return /\.(?:[cm]?[jt]sx?|sh)$/i.test(target) ? p : target; } } } catch { @@ -97,8 +99,7 @@ async function main() { } } - copyFileSync(tmpTarget, targetPath); - chmodSync(targetPath, 0o755); + renameSync(tmpTarget, targetPath); try { rmSync(tmpTarget, { force: true }); } catch { @@ -106,24 +107,14 @@ async function main() { } // 4. 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}`); - } + // Install the binary's manifest, including references sourced outside skills/seal-use. + // A custom destination avoids changing unrelated agent host settings during development. + const skillRes = spawnSync(targetPath, ["skill", "install", "--dir", skillTarget], { encoding: "utf8" }); + if (skillRes.status !== 0) { + throw new Error(`[dev:override] Failed to sync agent skill: ${skillRes.stderr || skillRes.error || "unknown error"}`); } + console.error(`✓ [dev:override] Synced agent skill to ${skillTarget}`); // 5. Restart service daemon if it was previously running if (serviceWasRunning) { @@ -132,16 +123,21 @@ async function main() { } // 6. 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"); + if (testRes.status !== 0 || !testRes.stdout) { + throw new Error(testRes.stderr || "Failed to verify updated binary"); } + const installed = JSON.parse(testRes.stdout); + if (installed.name !== "seal-use" || typeof installed.version !== "string") { + throw new Error("Updated binary returned an invalid version payload"); + } + console.error("✨ [dev:override] Success! Active global seal-use binary is now updated:"); + process.stdout.write(testRes.stdout); } -main().catch((err) => { - console.error(err); - process.exit(1); -}); +if (import.meta.main) { + main().catch((err) => { + console.error(err); + process.exit(1); + }); +} diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index 295676b..646f116 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -99,7 +99,7 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr | Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` | | 附件、发票、收据、OCR 或界面高亮结论争议 | `references/approval-attachment-trace.md` | 先完成追踪和归因后,才读 `approval-bad-cases.md` 做案例对照 | | 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 | -| 月度审核准确率报告、月报生成、accuracy report | 本文「月度审核准确率报告」一节 | 需要结构校验或 PDF 渲染时,再读 `report-templates/README.md` | +| 月度审核准确率报告、月报生成、accuracy report | 本文「月度审核准确率报告」一节 | 校验/渲染参数先查 `seal-use report render --help`;CLI 安装的 Skill 另附 `report-templates/README.md` | 冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。 diff --git a/skills/seal-use/references/approval-attachment-trace.md b/skills/seal-use/references/approval-attachment-trace.md index 7bb8c8b..f3d6377 100644 --- a/skills/seal-use/references/approval-attachment-trace.md +++ b/skills/seal-use/references/approval-attachment-trace.md @@ -50,7 +50,7 @@ If `seal-use langfuse search` does not find Chinese terms reliably, grep the cac ```bash rg -n "发票未上传至发票栏位|附件中存在定额发票|检查该附件(定额发票)|" \ - .cache/langfuse/traces/default/.json + ~/.cache/seal-use/langfuse/traces/default/.json ``` Read focused IO for the relevant observations. @@ -103,7 +103,7 @@ jq -r ' or contains("附件中存在定额发票") or contains("检查该附件(定额发票)")) | [.id,.name,.type,.startTime,((.output|tostring)|gsub("\n";" ")|.[0:500])] | @tsv -' .cache/langfuse/traces/default/.json +' ~/.cache/seal-use/langfuse/traces/default/.json ``` Then inspect the earliest matching observation. Typical interpretation: @@ -125,7 +125,7 @@ jq -r ' .trace.observations[] | walkobs(.; 0) | select(.name? | test("pre_analysis")) | [.startTime,.id,.name,.type,.parentObservationId,((.input|tostring|length)//0),((.output|tostring|length)//0)] | @tsv -' .cache/langfuse/traces/default/.json +' ~/.cache/seal-use/langfuse/traces/default/.json ``` Then inspect its output for the disputed file and rule: @@ -136,7 +136,7 @@ jq -r ' .trace.observations[] | walkobs(.) | select(.name? == "pre_analysis:ai.streamText") | .output -' .cache/langfuse/traces/default/.json | rg -n "fileId|fileName||付款截图金额|收款金额|金额合计" +' ~/.cache/seal-use/langfuse/traces/default/.json | rg -n "fileId|fileName||付款截图金额|收款金额|金额合计" ``` Look for these failure patterns: diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 46344d3..9b637d5 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -373,7 +373,7 @@ Approval runs, simulations, and Langfuse bridge: Langfuse trace inspection (built-in, read-only, credentials injected at compile time; no `--corp` and no user config required; all verbs are `seal_use` MCP-read-only): - `seal-use langfuse check` verifies connectivity of the embedded read-only credentials (missing credentials → exit 11). -- `seal-use langfuse cache-refresh ` fetches one full trace into `/.cache/langfuse/traces/default/.json` (shared format with langfuse-home); other cache-first verbs answer from it and point here (exit 13) when it is missing, unless `--refresh-if-missing`. +- `seal-use langfuse cache-refresh ` fetches one full trace into `~/.cache/seal-use/langfuse/traces/default/.json` (shared format with langfuse-home); other cache-first verbs answer from it across working directories and point here (exit 13) when it is missing, unless `--refresh-if-missing`. `SEAL_USE_LANGFUSE_CACHE_DIR` overrides the cache root. Matching legacy cwd caches are copied on first read, preserving their original files and timestamps. - `seal-use langfuse outline [--include-io-preview] [--max-preview-chars ] [--full]` returns the compact observation tree with sizes, usage, cost, and `warnings[]` for >20k-char fields. - `seal-use langfuse search --query ` is the ranked single-trace keyword search (qrep): hierarchy paths, `observationId`, before/match/after context; `--metadata ` and `--observation-types` narrow it. - `seal-use langfuse observation [--max-chars ] [--json-path ]` reads focused IO last (middle-truncated to 8000 chars by default, 30000 max, 500000 with `--full`). diff --git a/skills/seal-use/references/langfuse-trace.md b/skills/seal-use/references/langfuse-trace.md index 2b2f9eb..ccdafe8 100644 --- a/skills/seal-use/references/langfuse-trace.md +++ b/skills/seal-use/references/langfuse-trace.md @@ -2,7 +2,7 @@ `seal-use langfuse` 是内建的只读 Langfuse trace 检索域:凭据在编译期注入,最终用户**零配置**,无需 `langfuse-home` 或任何本地 `.env`。命令不需要 `--corp`,MCP `seal_use` 网关全部可达。 -只读边界:client 只发 `GET`,本地只写 `.cache/langfuse/` 缓存。凭据缺失(源码直跑未注入)→ exit 11;Langfuse 401/403 → exit 11;其它上游失败 → exit 1;参数缺失/越界 → exit 13。 +只读边界:client 只发 `GET`,本地只写用户目录 `~/.cache/seal-use/langfuse/` 缓存。凭据缺失(源码直跑未注入)→ exit 11;Langfuse 401/403 → exit 11;其它上游失败 → exit 1;参数缺失/越界 → exit 13。 ## IO-last 工作流 @@ -14,7 +14,7 @@ seal-use langfuse cache-refresh ``` -缓存写入 `/.cache/langfuse/traces/default/.json`(与 langfuse-home 同格式,可共享)。后续命令缺缓存时报 exit 13 并提示补缓存,或加 `--refresh-if-missing` 现场拉取。 +缓存写入 `~/.cache/seal-use/langfuse/traces/default/.json`,换目录后仍可读;可用 `SEAL_USE_LANGFUSE_CACHE_DIR` 显式指定缓存根目录。与 langfuse-home 的 JSON 格式保持兼容:从旧工作目录读取时,会将匹配当前项目的 `/.cache/langfuse/traces/default/.json` 复制到用户缓存,保留原文件和原缓存时间。后续命令缺缓存时报 exit 13 并提示补缓存,或加 `--refresh-if-missing` 现场拉取。 ### 2. 读大纲(不打印原始 IO) @@ -33,7 +33,7 @@ seal-use langfuse search --query "关键词" --fields input,output --o seal-use langfuse search --query "关键词" --metadata '{"stage":"review"}' ``` -返回带 `path` 层级、`observationId`、`context{before,match,after}` 的排序片段。output 命中权重最高,`approval_review`/`审核` 观测加成。中文分词不理想时直接 grep 缓存:`rg -n "<原文>" .cache/langfuse/traces/default/.json`。 +返回带 `path` 层级、`observationId`、`context{before,match,after}` 的排序片段。output 命中权重最高,`approval_review`/`审核` 观测加成。中文分词不理想时直接 grep 缓存:`rg -n "<原文>" ~/.cache/seal-use/langfuse/traces/default/.json`。 ### 4. 焦点 observation IO diff --git a/src/cli/commands/homebrew-skill.test.ts b/src/cli/commands/homebrew-skill.test.ts new file mode 100644 index 0000000..475011c --- /dev/null +++ b/src/cli/commands/homebrew-skill.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { handleUpdateCommand, homebrewFormulaPrefix, installHomebrewSkill } from "./update.js"; + +describe("Homebrew skill refresh", () => { + test("a copied source package cannot update its parent application's Git repository", async () => { + const dir = mkdtempSync(join(tmpdir(), "seal-source-update-test-")); + try { + await expect(handleUpdateCommand({ appRoot: dir, entryFile: join(dir, "src", "cli.ts") })) + .rejects.toMatchObject({ exitCode: 13 }); + expect(existsSync(join(dir, "bun.lock"))).toBe(false); + } finally { rmSync(dir, { recursive: true, force: true }); } + }); + + test("uses the upgraded formula executable even when PATH contains an older standalone CLI", () => { + const dir = mkdtempSync(join(tmpdir(), "seal-brew-skill-test-")); + const originalPath = process.env.PATH; + try { + const prefix = join(dir, "formula"); + const bin = join(prefix, "bin"); + const skill = join(dir, "skill"); + mkdirSync(bin, { recursive: true }); + mkdirSync(skill); + writeFileSync(join(skill, "SKILL.md"), "---\nmetadata:\n version: 1.2.3\n---\n"); + // Shell fixtures touch only this temp directory; no real brew upgrade or global skill installation. + writeFileSync(join(dir, "brew"), `#!/bin/sh\nprintf '%s\\n' '${prefix}'\n`, { mode: 0o755 }); + writeFileSync(join(dir, "seal-use"), `#!/bin/sh\ntouch '${join(dir, "wrong-cli")}'\nexit 1\n`, { mode: 0o755 }); + writeFileSync(join(bin, "seal-use"), `#!/bin/sh\ntouch '${join(dir, "right-cli")}'\nprintf '%s\\n' '{"targetDir":"${skill}"}'\n`, { mode: 0o755 }); + process.env.PATH = `${dir}:${originalPath ?? ""}`; + // Fail before any install call if child-process PATH isolation is ever broken. + expect(homebrewFormulaPrefix()).toBe(prefix); + expect(installHomebrewSkill("1.2.3")).toEqual({ targetDir: skill, version: "1.2.3" }); + expect(existsSync(join(dir, "right-cli"))).toBe(true); + expect(existsSync(join(dir, "wrong-cli"))).toBe(false); + writeFileSync(join(skill, "SKILL.md"), "---\nmetadata:\n version: 1.2.2\n---\n"); + expect(() => installHomebrewSkill("1.2.3")).toThrow("1.2.2"); + try { installHomebrewSkill("1.2.3"); } catch (error) { expect(error).toMatchObject({ exitCode: 13 }); } + } finally { + if (originalPath === undefined) delete process.env.PATH; else process.env.PATH = originalPath; + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.ts index 4bf5527..025c1bf 100644 --- a/src/cli/commands/update.ts +++ b/src/cli/commands/update.ts @@ -1,4 +1,4 @@ -import { chmodSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs"; import { basename, dirname, isAbsolute, join, relative } from "node:path"; import { spawn, spawnSync } from "node:child_process"; import { isCompiledBinary } from "../../core/runtime.js"; @@ -7,6 +7,7 @@ import { readInstalledSkillVersion } from "../../core/embedded-skill.js"; import { saveUpdateCache } from "../../core/update-cache.js"; import { VERSION, IS_RELEASE } from "../../version.js"; import { printJson } from "../printer.js"; +import { CliError, validationError } from "../../core/errors.js"; import type { CliRuntime } from "../types.js"; const DEFAULT_GITHUB_REPO = "yunyingk/seal-use"; @@ -130,6 +131,10 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp return; } + // Source updates must operate on this package's checkout, never a parent app's repository. + if (!existsSync(join(runtime.appRoot, ".git"))) { + throw validationError("当前源码安装目录不是 seal-use 的 Git 工作区。请使用发行版二进制,或从 seal-use 仓库通过 npm link 安装。"); + } try { runCommand("git", ["-C", runtime.appRoot, "pull", "--ff-only"]); } catch (err) { @@ -151,6 +156,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp await handleHomebrewUpdate(options, repo, targetVersion); return; } catch (err) { + if (err instanceof CliError) throw err; console.error( `⚠️ Homebrew 自动更新失败,回退至原生二进制更新: ${err instanceof Error ? err.message : String(err)}` ); @@ -430,6 +436,18 @@ function installSkillFromInstalledBinary( return { targetDir, version }; } +/** Homebrew may change the formula prefix; PATH can still contain an older standalone command. */ +export function installHomebrewSkill(targetVersion: string): { targetDir?: string; version?: string } { + const prefix = homebrewFormulaPrefix(); + if (!prefix) throw validationError("Cannot resolve the updated Homebrew seal-use formula prefix."); + try { + return installSkillFromInstalledBinary(join(prefix, "bin", "seal-use"), targetVersion); + } catch (error) { + // The formula was already upgraded. Do not fall back to replacing the old running Cellar image. + throw validationError(error instanceof Error ? error.message : String(error)); + } +} + function detectPlatform(): "darwin" | "linux" | "windows" { if (process.platform === "darwin") return "darwin"; if (process.platform === "win32") return "windows"; @@ -440,11 +458,12 @@ function detectArch(): "arm64" | "x64" { return process.arch === "arm64" ? "arm64" : "x64"; } -function homebrewFormulaPrefix(): string | undefined { +export function homebrewFormulaPrefix(): string | undefined { try { const result = spawnSync("brew", ["--prefix", "seal-use"], { stdio: ["ignore", "pipe", "ignore"], - encoding: "utf-8" + encoding: "utf-8", + env: { ...process.env } }); if (result.status !== 0 || typeof result.stdout !== "string") return undefined; const prefix = result.stdout.trim(); @@ -596,11 +615,7 @@ async function handleHomebrewUpdate( alreadyLatest = alreadyLatestBeforeUpdate; // Refresh installed skill through new binary - try { - spawnSync("seal-use", ["skill", "install"], { stdio: "ignore" }); - } catch { - // best-effort - } + installHomebrewSkill(latestVersion); console.error( alreadyLatest diff --git a/src/core/dev-override.test.ts b/src/core/dev-override.test.ts new file mode 100644 index 0000000..300807e --- /dev/null +++ b/src/core/dev-override.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, test } from "bun:test"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { resolveTargetBinaryPath } from "../../scripts/dev-override.js"; + +describe("development CLI install target", () => { + test("npm-linked source is never selected as the binary replacement target", () => { + const dir = mkdtempSync(join(tmpdir(), "seal-dev-target-test-")); + const originalPath = process.env.PATH; + try { + const command = join(dir, "seal-use"); + const source = join(dir, "cli.ts"); + writeFileSync(source, "#!/usr/bin/env bun\nconsole.log('source fixture')\n"); + chmodSync(source, 0o755); + symlinkSync(source, command); + process.env.PATH = `${dir}${process.platform === "win32" ? ";" : ":"}${originalPath ?? ""}`; + expect(resolveTargetBinaryPath()).toBe(command); + expect(readFileSync(source, "utf8")).toContain("source fixture"); + } finally { + if (originalPath === undefined) delete process.env.PATH; else process.env.PATH = originalPath; + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("native command symlinks continue to replace the installed target", () => { + const dir = mkdtempSync(join(tmpdir(), "seal-dev-target-test-")); + const originalPath = process.env.PATH; + try { + const command = join(dir, "seal-use"); + mkdirSync(join(dir, "formula")); + const target = join(dir, "formula", "seal-use"); + writeFileSync(target, "native binary fixture"); + chmodSync(target, 0o755); + symlinkSync(target, command); + process.env.PATH = `${dir}${process.platform === "win32" ? ";" : ":"}${originalPath ?? ""}`; + expect(resolveTargetBinaryPath()).toBe(realpathSync(target)); + } finally { + if (originalPath === undefined) delete process.env.PATH; else process.env.PATH = originalPath; + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/src/domains/langfuse/cache.test.ts b/src/domains/langfuse/cache.test.ts new file mode 100644 index 0000000..71dd2db --- /dev/null +++ b/src/domains/langfuse/cache.test.ts @@ -0,0 +1,80 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DEFAULT_LANGFUSE_CACHE_DIR, LANGFUSE_CACHE_DIR_ENV, TraceCache } from "./cache.js"; +import type { CachedTrace } from "./types.js"; + +const project = { baseUrl: "https://langfuse.test", projectId: "test-project" }; +const originalCwd = process.cwd(); +const originalCacheDir = process.env[LANGFUSE_CACHE_DIR_ENV]; +let dir: string; +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "seal-trace-cache-test-")); + process.env[LANGFUSE_CACHE_DIR_ENV] = join(dir, "user-cache"); +}); +afterEach(() => { + process.chdir(originalCwd); + if (originalCacheDir === undefined) delete process.env[LANGFUSE_CACHE_DIR_ENV]; + else process.env[LANGFUSE_CACHE_DIR_ENV] = originalCacheDir; + rmSync(dir, { recursive: true, force: true }); +}); + +function legacyEntry(overrides: Record = {}): string { + const cached: CachedTrace = { + cacheVersion: 1, cachedAt: "2026-10-01T00:00:00Z", + project: { key: "default", ...project }, trace: { id: "trace", projectId: project.projectId, observations: [] } + }; + const file = join(dir, ".cache", "langfuse", "traces", "default", "trace.json"); + mkdirSync(join(dir, ".cache", "langfuse", "traces", "default"), { recursive: true }); + writeFileSync(file, JSON.stringify({ ...cached, ...overrides })); + process.chdir(dir); + return file; +} + +describe("portable Langfuse cache", () => { + test("the default path is independent of cwd without writing to the real user's cache", () => { + delete process.env[LANGFUSE_CACHE_DIR_ENV]; + const first = new TraceCache(project).path("trace"); + process.chdir(dir); + const second = new TraceCache(project).path("trace"); + expect(first).toBe(join(DEFAULT_LANGFUSE_CACHE_DIR, "default", "trace.json")); + expect(second).toBe(first); + }); + + test("a newly created service can read a trace after changing directories", async () => { + const first = new TraceCache(project); + await first.write("trace", { id: "trace", projectId: project.projectId, observations: [] }); + const elsewhere = join(dir, "elsewhere"); + mkdirSync(elsewhere); + process.chdir(elsewhere); + const second = new TraceCache(project); + expect(second.path("trace")).toBe(first.path("trace")); + expect((await second.read("trace"))?.trace.id).toBe("trace"); + expect(statSync(first.path("trace")).mode & 0o777).toBe(0o600); + }); + + test("legacy cache is copied once with its timestamp and original file retained", async () => { + const legacy = legacyEntry(); + const original = readFileSync(legacy, "utf8"); + const imported = await new TraceCache(project).read("trace"); + expect(imported?.cachedAt).toBe("2026-10-01T00:00:00Z"); + expect(readFileSync(legacy, "utf8")).toBe(original); + process.chdir(originalCwd); + expect(await new TraceCache(project).read("trace")).toEqual(imported); + }); + + test("a different project's legacy trace is not imported", async () => { + legacyEntry({ project: { key: "default", baseUrl: project.baseUrl, projectId: "other-project" } }); + const cache = new TraceCache(project); + expect(await cache.read("trace")).toBeUndefined(); + expect(existsSync(cache.path("trace"))).toBe(false); + }); + + test("wrong trace IDs and unsupported cache versions are not accepted", async () => { + for (const entry of [{ cacheVersion: 2 }, { trace: { id: "another-trace", projectId: project.projectId } }]) { + legacyEntry(entry); + expect(await new TraceCache(project).read("trace")).toBeUndefined(); + } + }); +}); diff --git a/src/domains/langfuse/cache.ts b/src/domains/langfuse/cache.ts index 7f402c8..d4d4503 100644 --- a/src/domains/langfuse/cache.ts +++ b/src/domains/langfuse/cache.ts @@ -1,12 +1,16 @@ -import { mkdir, readFile, stat, writeFile } from "node:fs/promises"; -import { dirname, resolve } from "node:path"; +import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; +import { randomUUID } from "node:crypto"; +import { homedir } from "node:os"; +import { dirname, join, resolve } from "node:path"; import type { CachedTrace, LangfuseTraceSummary } from "./types.js"; const CACHE_VERSION = 1; -const CACHE_ROOT = ".cache/langfuse/traces"; +const LEGACY_CACHE_ROOT = ".cache/langfuse/traces"; +export const LANGFUSE_CACHE_DIR_ENV = "SEAL_USE_LANGFUSE_CACHE_DIR"; +export const DEFAULT_LANGFUSE_CACHE_DIR = join(homedir(), ".cache", "seal-use", "langfuse", "traces"); // Single-project domain: the cache segment stays "default", which keeps this -// cache byte-compatible with `langfuse-home` (same cwd-relative layout), so the -// two tools share cached traces instead of re-fetching them. +// cache byte-compatible with `langfuse-home`, so old cwd-relative entries can +// be imported without re-fetching or removing their original files. const PROJECT_SEGMENT = "default"; export type TraceCacheProject = { @@ -15,18 +19,21 @@ export type TraceCacheProject = { }; /** - * Single-trace JSON cache keyed by traceId, written under `/.cache` - * (gitignored). Holds the FULL raw trace (including observation IO) so outline, + * Single-trace JSON cache keyed by traceId, written under the user's cache + * directory. Holds the FULL raw trace (including observation IO) so outline, * search, observation and flow tools can answer without touching the network. * No TTL: `cache-refresh` overwrites explicitly. */ export class TraceCache { - constructor(private readonly project: TraceCacheProject) {} + private readonly root: string; + + constructor(private readonly project: TraceCacheProject) { + this.root = resolve(process.env[LANGFUSE_CACHE_DIR_ENV]?.trim() || DEFAULT_LANGFUSE_CACHE_DIR); + } path(traceId: string): string { return resolve( - process.cwd(), - CACHE_ROOT, + this.root, PROJECT_SEGMENT, `${sanitizeSegment(traceId)}.json` ); @@ -42,10 +49,25 @@ export class TraceCache { } async read(traceId: string): Promise { + const cached = await this.readEntry(this.path(traceId), traceId); + if (cached) return cached; + const legacyPath = resolve(process.cwd(), LEGACY_CACHE_ROOT, PROJECT_SEGMENT, `${sanitizeSegment(traceId)}.json`); + if (legacyPath === this.path(traceId)) return undefined; + const legacy = await this.readEntry(legacyPath, traceId); + if (!legacy) return undefined; + // Preserve cachedAt and the original legacy entry; only copy a matching project's trace. + await this.persist(traceId, legacy); + return legacy; + } + + private async readEntry(path: string, traceId: string): Promise { try { - const content = await readFile(this.path(traceId), "utf8"); + const content = await readFile(path, "utf8"); const parsed = JSON.parse(content) as CachedTrace; - return parsed.cacheVersion === CACHE_VERSION ? parsed : undefined; + if (parsed.cacheVersion !== CACHE_VERSION || parsed.trace?.id !== traceId) return undefined; + if (parsed.project?.baseUrl?.replace(/\/+$/, "") !== this.project.baseUrl.replace(/\/+$/, "")) return undefined; + if (this.project.projectId && parsed.project.projectId !== this.project.projectId) return undefined; + return parsed; } catch { return undefined; } @@ -63,11 +85,17 @@ export class TraceCache { trace }; - const path = this.path(traceId); - await mkdir(dirname(path), { recursive: true }); - await writeFile(path, `${JSON.stringify(cached, null, 2)}\n`, "utf8"); + await this.persist(traceId, cached); return cached; } + + private async persist(traceId: string, cached: CachedTrace): Promise { + const path = this.path(traceId); + await mkdir(dirname(path), { recursive: true, mode: 0o700 }); + const temp = `${path}.${randomUUID()}.tmp`; + await writeFile(temp, `${JSON.stringify(cached, null, 2)}\n`, { encoding: "utf8", mode: 0o600 }); + await rename(temp, path); + } } function sanitizeSegment(value: string): string { diff --git a/src/domains/langfuse/service.test.ts b/src/domains/langfuse/service.test.ts index 1cfcefe..753e5c6 100644 --- a/src/domains/langfuse/service.test.ts +++ b/src/domains/langfuse/service.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { CliError } from "../../core/errors.js"; @@ -52,16 +52,21 @@ function sampleTrace(): LangfuseTraceSummary { } let originalCwd: string; +let originalCacheDir: string | undefined; let workdir: string; beforeEach(() => { originalCwd = process.cwd(); + originalCacheDir = process.env.SEAL_USE_LANGFUSE_CACHE_DIR; workdir = mkdtempSync(join(tmpdir(), "seal-langfuse-test-")); + process.env.SEAL_USE_LANGFUSE_CACHE_DIR = join(workdir, "cache"); process.chdir(workdir); }); afterEach(() => { process.chdir(originalCwd); + if (originalCacheDir === undefined) delete process.env.SEAL_USE_LANGFUSE_CACHE_DIR; + else process.env.SEAL_USE_LANGFUSE_CACHE_DIR = originalCacheDir; rmSync(workdir, { recursive: true, force: true }); }); @@ -72,13 +77,11 @@ async function seedCache(trace: LangfuseTraceSummary = sampleTrace()) { } describe("trace cache", () => { - test("writes the langfuse-home compatible path and round-trips", async () => { + test("writes the langfuse-home compatible format in the configured cache directory and round-trips", async () => { const cache = await seedCache(); - // process.cwd() resolves symlinks, so compare against the physical tmpdir - // (macOS /var -> /private/var). - const physicalWorkdir = realpathSync(workdir); + // The cache root is explicit and independent of cwd, including macOS /var symlinks. expect(cache.path("trace-1")).toBe( - join(physicalWorkdir, ".cache", "langfuse", "traces", "default", "trace-1.json") + join(workdir, "cache", "default", "trace-1.json") ); const read = await new TraceCache({ baseUrl: CONFIG.baseUrl }).read("trace-1"); diff --git a/src/server.test.ts b/src/server.test.ts index da2f3c4..e69012f 100644 --- a/src/server.test.ts +++ b/src/server.test.ts @@ -1,8 +1,12 @@ import { describe, expect, test } from "bun:test"; import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import { spawnSync } from "node:child_process"; +import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; import { createServer, resolveMcpEnabled, + resolveServerCliLauncher, SEAL_USE_MCP_TOOL_NAME, SEAL_USE_MCP_WRITE_TOOL_NAME, SEAL_MCP_ENABLED_ENV, @@ -10,6 +14,20 @@ import { } from "./server.js"; describe("seal-use MCP server", () => { + test("the source MCP launcher executes the CLI without relying on the caller's cwd", () => { + const launcher = resolveServerCliLauncher(fileURLToPath(import.meta.resolve("./server.ts")), false); + const result = spawnSync(launcher.command, [...launcher.args!, "version"], { + cwd: tmpdir(), encoding: "utf8", env: { ...process.env, SEAL_DISABLE_BG_UPDATE: "1" } + }); + expect(result.status).toBe(0); + expect(JSON.parse(result.stdout).name).toBe("seal-use"); + }); + + test("the compiled MCP launcher never forwards a virtual source file to the executable", () => { + const launcher = resolveServerCliLauncher("/$bunfs/root/src/server.ts", true, "/usr/local/bin/seal-use"); + expect(launcher).toEqual({ command: "/usr/local/bin/seal-use", args: [] }); + }); + test("tokenizes quoted JSON without invoking a shell", () => { expect(tokenizeCommand( `seal-use rules search "差旅 发票" --corp corp-a` diff --git a/src/server.ts b/src/server.ts index 3b97ab5..6fa5d75 100644 --- a/src/server.ts +++ b/src/server.ts @@ -8,17 +8,23 @@ import { isReadOnlyCliCommand } from "./cli/read-only.js"; import { normalizeCliArgs, tokenizeCommand } from "./cli/tokenize.js"; import { classifyCliError } from "./cli/errors.js"; import { VERSION } from "./version.js"; +import { isCompiledBinary, resolveAppRoot, resolveDefaultLauncher } from "./core/runtime.js"; const serverEntryFile = fileURLToPath(import.meta.url); -// Repo/checkout root when running from src/server.ts (`seal-use mcp`); there is -// no packaged bundle anymore, so two levels up is always the app root. -const pluginRoot = dirname(dirname(serverEntryFile)); +// Source servers and compiled CLI servers share the launcher rules. In a binary, +// $bunfs paths identify bundled modules, not files a child process can execute. +const cliEntryFile = resolve(dirname(serverEntryFile), "cli.ts"); +const pluginRoot = resolveAppRoot(cliEntryFile); export const SEAL_USE_MCP_TOOL_NAME = "seal_use"; export const SEAL_USE_MCP_WRITE_TOOL_NAME = "seal_use_write"; export const SEAL_MCP_ENABLED_ENV = "SEAL_USE_MCP_ENABLED"; export const LEGACY_SEAL_MCP_ENABLED_ENV = "SEAL_HOME_MCP_ENABLED"; +export function resolveServerCliLauncher(entryFile = serverEntryFile, compiled = isCompiledBinary(), execPath = process.execPath) { + return resolveDefaultLauncher(resolve(dirname(entryFile), "cli.ts"), compiled, execPath); +} + export function resolveMcpEnabled( value = process.env[SEAL_MCP_ENABLED_ENV] ?? process.env[LEGACY_SEAL_MCP_ENABLED_ENV] ): boolean { @@ -138,11 +144,8 @@ async function executeCliCommand( try { return cliResult(await runCli(cliArgs, { appRoot: pluginRoot, - entryFile: serverEntryFile, - launcher: { - command: process.execPath, - args: [serverEntryFile, "--seal-use-cli"] - } + entryFile: cliEntryFile, + launcher: resolveServerCliLauncher() })); } catch (error) { const classification = classifyCliError(error); @@ -184,11 +187,8 @@ function cliResult(result: { stdout: string; stderr: string; isError: boolean; e async function runEmbeddedCli() { const result = await runCli(process.argv.slice(3), { appRoot: pluginRoot, - entryFile: serverEntryFile, - launcher: { - command: process.execPath, - args: [serverEntryFile, "--seal-use-cli"] - } + entryFile: cliEntryFile, + launcher: resolveServerCliLauncher() }); if (result.stdout) process.stdout.write(result.stdout); if (result.stderr) process.stderr.write(`${result.stderr}${result.stderr.endsWith("\n") ? "" : "\n"}`); diff --git a/src/version.test.ts b/src/version.test.ts index b0bfcd1..0f575b8 100644 --- a/src/version.test.ts +++ b/src/version.test.ts @@ -1,4 +1,8 @@ import { describe, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; import { formatDevVersion, parseGitDescribe, resolveVersionInfo } from "./version.js"; import { compareSemVer, isNewerVersion } from "./cli/commands/update.js"; @@ -62,6 +66,40 @@ describe("Git version parsing and formatting", () => { }); describe("resolveVersionInfo configuration modes", () => { + test("source version uses its own checkout even when launched inside another Git repository", () => { + const dir = mkdtempSync(join(tmpdir(), "seal-version-cwd-test-")); + const originalCwd = process.cwd(); + const emptyBuildEnv = { SEAL_BUILD_VERSION: "", SEAL_BUILD_IS_RELEASE: "", SEAL_FORCE_RELEASE: "" }; + try { + const repoRoot = resolve(import.meta.dirname, ".."); + const expected = resolveVersionInfo({ env: emptyBuildEnv, cwd: repoRoot }); + for (const args of [["init"], ["config", "user.name", "Fixture"], ["config", "user.email", "fixture@example.test"]]) { + expect(spawnSync("git", args, { cwd: dir }).status).toBe(0); + } + writeFileSync(join(dir, "fixture.txt"), "foreign repository"); + expect(spawnSync("git", ["add", "fixture.txt"], { cwd: dir }).status).toBe(0); + expect(spawnSync("git", ["commit", "-m", "Fixture"], { cwd: dir }).status).toBe(0); + expect(spawnSync("git", ["tag", "v99.99.99"], { cwd: dir }).status).toBe(0); + process.chdir(dir); + expect(resolveVersionInfo({ env: emptyBuildEnv })).toEqual(expected); + // Explicit cwd remains available for callers/tests that intentionally inspect another checkout. + expect(resolveVersionInfo({ env: emptyBuildEnv, cwd: dir }).git?.baseVersion).toBe("99.99.99"); + const copy = join(dir, "node_modules", "seal-use"); + mkdirSync(join(copy, "src"), { recursive: true }); + copyFileSync(join(repoRoot, "src", "version.ts"), join(copy, "src", "version.ts")); + copyFileSync(join(repoRoot, "package.json"), join(copy, "package.json")); + const child = spawnSync(process.execPath, ["-e", `import { VERSION_INFO } from ${JSON.stringify(join(copy, "src", "version.ts"))}; console.log(JSON.stringify(VERSION_INFO))`], { + cwd: dir, encoding: "utf8", env: { ...process.env, ...emptyBuildEnv } + }); + expect(child.status).toBe(0); + expect(JSON.parse(child.stdout)).toMatchObject({ version: expect.stringContaining("+local"), channel: "dev" }); + expect(JSON.parse(child.stdout).git).toBeUndefined(); + } finally { + process.chdir(originalCwd); + rmSync(dir, { recursive: true, force: true }); + } + }); + test("resolves inlined environment variables when preset", () => { const info = resolveVersionInfo({ env: { diff --git a/src/version.ts b/src/version.ts index bafa692..7d3b442 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,4 +1,7 @@ import { spawnSync } from "node:child_process"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { existsSync } from "node:fs"; import packageJson from "../package.json" with { type: "json" }; export interface GitBuildInfo { @@ -83,7 +86,9 @@ export function resolveVersionInfo(options?: { 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; + // Source invocations may be launched from any directory, including another Git repository. + // Compiled builds use the injected metadata above; their virtual source root is not a checkout. + const cwd = options?.cwd ?? resolve(dirname(fileURLToPath(import.meta.url)), ".."); // 1. Check compile-time inlined environment variables if (buildVersion) { @@ -120,6 +125,11 @@ export function resolveVersionInfo(options?: { // 3. Dynamic resolution from git repository in dev mode try { + // A copied npm package has no checkout. Git would otherwise walk up into + // the consuming application's repository and report its version as ours. + if (options?.cwd === undefined && !existsSync(join(cwd, ".git"))) { + return { name: "seal-use", version: `${packageJson.version}-dev.0+local`, channel: "dev", isRelease: false }; + } const res = spawnSync("git", ["describe", "--tags", "--long", "--dirty", "--always"], { cwd, encoding: "utf8",