diff --git a/README.md b/README.md index cf9e63e..51f27de 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,7 @@ hose-use mcp # 启动 MCP Server (默认暴露 ### 模块化 Agent Skill 与 IDE 插件规范 - **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装到统一的 `~/.agents/skills/hose-use`;如需安装到其他位置,必须显式使用 `--dir`; +- **开发环境检查**:Git 工作树、分支、无引用提交、canonical Skill 与全局开发版可通过 `bun run dev:status`、`bun run dev:check` 检查;清理必须先 `bun run dev:clean --dry-run`,再追加 `--yes`; - **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `.mcp.json` 清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关; - **MCP 单文件产物**:支持通过 `bun run build:plugin` 快速编译 Node.js 兼容的轻量单文件 `dist/mcp/server.js`。 diff --git a/package.json b/package.json index ca73d12..08d024d 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,9 @@ "build:plugin": "node scripts/build-plugin.mjs", "dev:override": "bun run scripts/dev-override.ts", "dev:link": "bun run scripts/dev-override.ts", + "dev:status": "bun run scripts/dev-hygiene.ts status", + "dev:check": "bun run scripts/dev-hygiene.ts check", + "dev:clean": "bun run scripts/dev-hygiene.ts clean", "dev": "bun run --watch src/server.ts", "start": "bun run src/server.ts", "export:workflow-schema": "bun run scripts/export-workflow-schema.ts" diff --git a/scripts/dev-hygiene.test.ts b/scripts/dev-hygiene.test.ts new file mode 100644 index 0000000..db78466 --- /dev/null +++ b/scripts/dev-hygiene.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, test } from "bun:test"; +import { buildCleanupPlan, classifyExitCode, parseDevHygieneArgs, type Finding } from "./dev-hygiene.ts"; + +describe("dev hygiene tooling", () => { + test("only accepts development-scoped modes and confirmation flags", () => { + expect(parseDevHygieneArgs(["status"])).toEqual({ mode: "status", dryRun: false, yes: false, pruneUnreachable: false, help: false }); + expect(parseDevHygieneArgs(["clean", "--dry-run"])).toEqual({ mode: "clean", dryRun: true, yes: false, pruneUnreachable: false, help: false }); + expect(parseDevHygieneArgs(["clean", "--yes", "--prune-unreachable"])).toEqual({ mode: "clean", dryRun: false, yes: true, pruneUnreachable: true, help: false }); + }); + + test("uses semantic exit codes for clean, warning, and blocked states", () => { + const finding = (level: Finding["level"]): Finding => ({ id: level, level, message: level }); + expect(classifyExitCode([])).toBe(0); + expect(classifyExitCode([finding("info")])).toBe(0); + expect(classifyExitCode([finding("warning")])).toBe(2); + expect(classifyExitCode([finding("blocked")])).toBe(3); + }); + + test("only plans deletion for clean merged worktrees and local branches", () => { + const snapshot = { + repository: {} as any, + worktrees: [ + { path: "/tmp/merged", head: "a", branch: "feat/merged", current: false, exists: true, clean: true }, + { path: "/tmp/dirty", head: "b", branch: "feat/dirty", current: false, exists: true, clean: false }, + ], + branches: [ + { name: "main", sha: "m", merged: true, gone: false }, + { name: "feat/merged", sha: "a", merged: true, gone: false }, + { name: "feat/dirty", sha: "b", merged: true, gone: false }, + { name: "feat/live", sha: "c", merged: false, gone: false }, + ], + unreachableCommits: ["deadbeef"], + skill: {} as any, + binaries: [], + legacyConfig: {} as any, + }; + const plan = buildCleanupPlan(snapshot, false); + expect(plan.map((action) => action.target)).toEqual(["/tmp/merged", "feat/merged"]); + expect(plan[1]?.kind).toBe("branch-delete"); + expect(plan.some((action) => action.kind === "git-prune")).toBe(false); + }); +}); diff --git a/scripts/dev-hygiene.ts b/scripts/dev-hygiene.ts new file mode 100644 index 0000000..07e80e9 --- /dev/null +++ b/scripts/dev-hygiene.ts @@ -0,0 +1,510 @@ +#!/usr/bin/env bun + +import { createHash } from "node:crypto"; +import { execFileSync, spawnSync } from "node:child_process"; +import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join, relative, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const PACKAGE = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as { version: string }; +const CANONICAL_SKILL_DIR = join(homedir(), ".agents", "skills", "hose-use"); +const NON_CANONICAL_SKILL_DIRS = [ + join(homedir(), ".gemini", "antigravity", "skills", "hose-use"), + join(homedir(), ".codex", "skills", "hose-use"), +]; + +export type FindingLevel = "info" | "warning" | "blocked"; +export type HygieneMode = "status" | "check" | "clean"; + +export interface Finding { + id: string; + level: FindingLevel; + message: string; + details?: Record; + nextAction?: string; +} + +export interface HygieneArgs { + mode: HygieneMode; + dryRun: boolean; + yes: boolean; + pruneUnreachable: boolean; + help: boolean; +} + +export interface CleanupAction { + kind: "worktree-remove" | "worktree-prune" | "branch-delete" | "git-prune"; + target: string; + command: string; + reason: string; +} + +interface GitBranch { + name: string; + sha: string; + upstream?: string; + gone: boolean; + merged: boolean; +} + +interface GitWorktree { + path: string; + head: string; + branch?: string; + current: boolean; + exists: boolean; + clean?: boolean; +} + +interface HygieneSnapshot { + repository: { + root: string; + branch: string; + head: string; + upstream?: string; + ahead: number; + behind: number; + clean: boolean; + stagedChanges: number; + unstagedChanges: number; + untrackedFiles: number; + }; + worktrees: GitWorktree[]; + branches: GitBranch[]; + unreachableCommits: string[]; + skill: { + canonicalDir: string; + canonicalExists: boolean; + canonicalIsSymlink: boolean; + missingFiles: string[]; + mismatchedFiles: string[]; + nonCanonicalCopies: Array<{ dir: string; exists: boolean; isSymlink: boolean }>; + }; + binaries: Array<{ + name: string; + path?: string; + version?: string; + expectedVersion: string; + matches: boolean; + error?: string; + }>; + legacyConfig: { + enterprisesDir: string; + configFile: string; + enterprisesDirExists: boolean; + configFileExists: boolean; + }; +} + +export interface HygieneReport { + schemaVersion: 1; + mode: HygieneMode; + generatedAt: string; + repository: string; + snapshot: HygieneSnapshot; + findings: Finding[]; + counts: Record; + nextActions: string[]; + exitCode: number; +} + +export function parseDevHygieneArgs(argv: string[]): HygieneArgs { + const requestedMode = argv.find((arg) => !arg.startsWith("--")) || "check"; + const mode: HygieneMode = requestedMode === "status" || requestedMode === "clean" ? requestedMode : "check"; + return { + mode, + dryRun: argv.includes("--dry-run") || argv.includes("--dryRun"), + yes: argv.includes("--yes") || argv.includes("--confirm"), + pruneUnreachable: argv.includes("--prune-unreachable"), + help: argv.includes("--help") || argv.includes("-h"), + }; +} + +export function classifyExitCode(findings: Finding[]): number { + if (findings.some((finding) => finding.level === "blocked")) return 3; + if (findings.some((finding) => finding.level === "warning")) return 2; + return 0; +} + +function git(args: string[], cwd = ROOT): string { + try { + return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new Error(`git ${args.join(" ")} 失败: ${detail}`); + } +} + +function gitMaybe(args: string[], cwd = ROOT): string | undefined { + try { + return git(args, cwd).trim() || undefined; + } catch { + return undefined; + } +} + +function parseRepository(): HygieneSnapshot["repository"] { + const status = git(["status", "--porcelain=v1", "-b"]); + const lines = status.split("\n").filter(Boolean); + const branchLine = lines.shift() || "## HEAD"; + const branch = branchLine.replace(/^##\s+/, "").split("...")[0] || "HEAD"; + const changes = lines.filter((line) => !line.startsWith("##")); + const stagedChanges = changes.filter((line) => line !== "??" && line[0] !== " " && line[0] !== "?").length; + const unstagedChanges = changes.filter((line) => line !== "??" && line[1] !== " " && line.slice(0, 2) !== "??").length; + const untrackedFiles = changes.filter((line) => line.startsWith("??")).length; + const upstream = gitMaybe(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]); + const divergence = upstream ? gitMaybe(["rev-list", "--left-right", "--count", "HEAD...@{upstream}"]) : undefined; + const [ahead, behind] = (divergence || "0 0").split(/\s+/).map((value) => Number(value) || 0); + return { + root: ROOT, + branch, + head: git(["rev-parse", "--short", "HEAD"]).trim(), + ...(upstream ? { upstream } : {}), + ahead, + behind, + clean: changes.length === 0, + stagedChanges, + unstagedChanges, + untrackedFiles, + }; +} + +function parseWorktrees(): GitWorktree[] { + const records: GitWorktree[] = []; + let current: Partial = {}; + const flush = () => { + if (!current.path) return; + const path = resolve(current.path); + const exists = existsSync(path); + let clean: boolean | undefined; + if (exists) { + try { + clean = git(["status", "--porcelain=v1"], path).trim() === ""; + } catch { + clean = undefined; + } + } + records.push({ + path, + head: current.head || "", + ...(current.branch ? { branch: current.branch } : {}), + current: path === ROOT, + exists, + ...(clean === undefined ? {} : { clean }), + }); + current = {}; + }; + + for (const line of git(["worktree", "list", "--porcelain"]).split("\n")) { + if (!line) { + flush(); + continue; + } + const [key, ...rest] = line.split(" "); + const value = rest.join(" "); + if (key === "worktree") current.path = value; + if (key === "HEAD") current.head = value; + if (key === "branch") current.branch = value.replace(/^refs\/heads\//, ""); + } + flush(); + return records; +} + +function parseBranches(): GitBranch[] { + const merged = new Set(git(["branch", "--merged", "main", "--format=%(refname:short)"]).split("\n").filter(Boolean)); + return git(["for-each-ref", "--format=%(refname:short)%09%(objectname:short)%09%(upstream:short)%09%(upstream:track)", "refs/heads"]) + .split("\n") + .filter(Boolean) + .map((line) => { + const [name, sha, upstream, track] = line.split("\t"); + return { name, sha, ...(upstream ? { upstream } : {}), gone: track === "[gone]", merged: merged.has(name) }; + }); +} + +function parseUnreachableCommits(): string[] { + return git(["fsck", "--full", "--no-reflogs", "--unreachable"]) + .split("\n") + .filter((line) => line.includes(" commit ")) + .map((line) => line.trim().split(/\s+/)[2]) + .filter(Boolean); +} + +function listFiles(dir: string, base = dir): string[] { + if (!existsSync(dir)) return []; + const files: string[] = []; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const fullPath = join(dir, entry.name); + if (entry.isDirectory() && !entry.isSymbolicLink()) files.push(...listFiles(fullPath, base)); + else files.push(relative(base, fullPath)); + } + return files.sort(); +} + +function fileHash(path: string): string | undefined { + try { + return createHash("sha256").update(readFileSync(path)).digest("hex"); + } catch { + return undefined; + } +} + +function parseSkill(): HygieneSnapshot["skill"] { + const expectedFiles = git(["ls-files", "skills/hose-use"]).split("\n").filter(Boolean).map((path) => path.slice("skills/hose-use/".length)); + const missingFiles = expectedFiles.filter((file) => !existsSync(join(CANONICAL_SKILL_DIR, file))); + const mismatchedFiles = expectedFiles.filter((file) => { + const sourceHash = fileHash(join(ROOT, "skills", "hose-use", file)); + const targetHash = fileHash(join(CANONICAL_SKILL_DIR, file)); + return sourceHash !== undefined && targetHash !== undefined && sourceHash !== targetHash; + }); + return { + canonicalDir: CANONICAL_SKILL_DIR, + canonicalExists: existsSync(CANONICAL_SKILL_DIR), + canonicalIsSymlink: existsSync(CANONICAL_SKILL_DIR) && lstatSync(CANONICAL_SKILL_DIR).isSymbolicLink(), + missingFiles, + mismatchedFiles, + nonCanonicalCopies: NON_CANONICAL_SKILL_DIRS.map((dir) => ({ + dir, + exists: existsSync(dir), + isSymlink: existsSync(dir) && lstatSync(dir).isSymbolicLink(), + })), + }; +} + +function resolveCommand(name: string): string | undefined { + const result = spawnSync("which", [name], { encoding: "utf8" }); + if (result.status === 0 && result.stdout?.trim()) return result.stdout.trim(); + return undefined; +} + +function inspectBinary(name: string): HygieneSnapshot["binaries"][number] { + const path = resolveCommand(name); + if (!path) return { name, expectedVersion: PACKAGE.version, matches: false, error: "PATH 中未找到" }; + const result = spawnSync(path, ["version", "--json"], { cwd: ROOT, encoding: "utf8", timeout: 5000 }); + if (result.status !== 0) { + return { name, path, expectedVersion: PACKAGE.version, matches: false, error: result.stderr?.trim() || `退出码 ${result.status ?? 1}` }; + } + try { + const version = (JSON.parse(result.stdout) as { version?: string }).version; + return { name, path, version, expectedVersion: PACKAGE.version, matches: version === PACKAGE.version }; + } catch { + return { name, path, expectedVersion: PACKAGE.version, matches: false, error: "版本输出不是 JSON" }; + } +} + +function parseLegacyConfig(): HygieneSnapshot["legacyConfig"] { + const home = homedir(); + const enterprisesDir = join(home, ".cache", "ekb-mcp", "enterprises"); + const configFile = join(home, ".cache", "ekb-mcp", "config.json"); + return { enterprisesDir, configFile, enterprisesDirExists: existsSync(enterprisesDir), configFileExists: existsSync(configFile) }; +} + +function collectSnapshot(): HygieneSnapshot { + return { + repository: parseRepository(), + worktrees: parseWorktrees(), + branches: parseBranches(), + unreachableCommits: parseUnreachableCommits(), + skill: parseSkill(), + binaries: [inspectBinary("hose-use"), inspectBinary("hose-aipro")], + legacyConfig: parseLegacyConfig(), + }; +} + +function buildFindings(snapshot: HygieneSnapshot): Finding[] { + const findings: Finding[] = []; + const repo = snapshot.repository; + if (!repo.clean) { + findings.push({ id: "repo.dirty", level: "warning", message: "当前开发工作树存在未提交修改", details: { stagedChanges: repo.stagedChanges, unstagedChanges: repo.unstagedChanges, untrackedFiles: repo.untrackedFiles }, nextAction: "先确认这些修改属于当前工作,必要时提交或单独保存" }); + } + if (repo.branch === "HEAD") findings.push({ id: "repo.detached", level: "blocked", message: "当前处于 detached HEAD", nextAction: "切换到明确的开发分支后再进行清理" }); + if (repo.behind > 0) findings.push({ id: "repo.behind", level: "warning", message: "当前分支落后于上游分支", details: { upstream: repo.upstream, behind: repo.behind }, nextAction: "确认远程变化后再执行开发清理" }); + + for (const worktree of snapshot.worktrees) { + if (!worktree.exists) { + findings.push({ id: "worktree.missing", level: "blocked", message: "Git 记录了不存在的工作树路径", details: { path: worktree.path, branch: worktree.branch }, nextAction: "先用 git worktree prune 清理失效记录" }); + } else if (!worktree.current && worktree.clean === false) { + findings.push({ id: "worktree.dirty", level: "warning", message: "额外工作树存在未提交修改", details: { path: worktree.path, branch: worktree.branch }, nextAction: "不要自动删除;先进入该工作树确认修改归属" }); + } else if (!worktree.current) { + findings.push({ id: "worktree.extra", level: "info", message: "存在额外工作树,需人工确认是否仍有用途", details: { path: worktree.path, branch: worktree.branch } }); + } + } + + for (const branch of snapshot.branches) { + if (branch.name === snapshot.repository.branch) continue; + if (branch.name !== "main" && branch.merged) { + const linked = snapshot.worktrees.some((worktree) => worktree.branch === branch.name); + findings.push({ id: "branch.merged", level: linked ? "warning" : "info", message: linked ? "已合并分支仍被工作树占用" : "发现已合并的本地分支", details: { branch: branch.name, sha: branch.sha, linkedWorktree: linked } }); + } else if (branch.gone) { + findings.push({ id: "branch.gone", level: "warning", message: "本地分支的上游远程分支已不存在", details: { branch: branch.name, upstream: branch.upstream }, nextAction: "确认本地分支不再需要后再删除" }); + } + } + if (snapshot.unreachableCommits.length) { + findings.push({ id: "git.unreachable", level: "warning", message: "发现无分支或标签引用的 Git commit", details: { count: snapshot.unreachableCommits.length, commits: snapshot.unreachableCommits }, nextAction: "先检查内容,确认后使用 dev:clean --yes --prune-unreachable" }); + } + + const skill = snapshot.skill; + if (!skill.canonicalExists || skill.missingFiles.length || skill.mismatchedFiles.length) { + findings.push({ id: "skill.canonical-drift", level: "warning", message: "canonical Skill 缺失或与当前源码不一致", details: { dir: skill.canonicalDir, missingFiles: skill.missingFiles, mismatchedFiles: skill.mismatchedFiles }, nextAction: "运行 bun run dev:override 同步开发版 Skill" }); + } + for (const copy of skill.nonCanonicalCopies.filter((item) => item.exists)) { + findings.push({ id: "skill.noncanonical-copy", level: "warning", message: "发现非 canonical Skill 副本;检查不会删除它", details: copy, nextAction: "确认外部工具不再使用后,再单独设计迁移或软链接" }); + } + + for (const binary of snapshot.binaries) { + if (!binary.path) { + findings.push({ id: "binary.missing", level: "info", message: `${binary.name} 未安装到 PATH`, details: binary, nextAction: "如需全局开发版,运行 bun run dev:override" }); + } else if (!binary.matches) { + findings.push({ id: "binary.drift", level: "warning", message: `${binary.name} 全局版本与当前源码不一致`, details: binary, nextAction: "运行 bun run dev:override 同步全局开发版" }); + } + } + const legacy = snapshot.legacyConfig; + if (legacy.enterprisesDirExists || legacy.configFileExists) { + findings.push({ id: "config.legacy", level: "warning", message: "发现旧版 ekb-mcp 配置路径;检查不会删除配置", details: legacy, nextAction: "先确认迁移结果,再按配置迁移策略清理" }); + } + return findings; +} + +export function buildCleanupPlan(snapshot: HygieneSnapshot, pruneUnreachable: boolean): CleanupAction[] { + const actions: CleanupAction[] = []; + if (snapshot.worktrees.some((worktree) => !worktree.exists)) { + actions.push({ kind: "worktree-prune", target: "stale-worktree-records", command: "git worktree prune", reason: "移除 Git 记录中已经不存在的工作树" }); + } + const removableWorktreeBranches = new Set( + snapshot.worktrees + .filter((worktree) => !worktree.current && worktree.exists && worktree.clean && worktree.branch && snapshot.branches.some((branch) => branch.name === worktree.branch && branch.merged)) + .map((worktree) => worktree.branch) + .filter((branch): branch is string => Boolean(branch)) + ); + const linkedPaths = new Set( + snapshot.worktrees + .filter((worktree) => !removableWorktreeBranches.has(worktree.branch || "")) + .map((worktree) => worktree.branch) + .filter((branch): branch is string => Boolean(branch)) + ); + for (const worktree of snapshot.worktrees) { + if (!worktree.current && worktree.exists && worktree.clean && worktree.branch && snapshot.branches.some((branch) => branch.name === worktree.branch && branch.merged)) { + actions.push({ kind: "worktree-remove", target: worktree.path, command: `git worktree remove ${JSON.stringify(worktree.path)}`, reason: `工作树干净且分支 ${worktree.branch} 已合并` }); + } + } + for (const branch of snapshot.branches) { + if (branch.name !== "main" && branch.merged && !linkedPaths.has(branch.name)) { + actions.push({ kind: "branch-delete", target: branch.name, command: `git branch -d ${branch.name}`, reason: "本地分支已合并且没有关联工作树" }); + } + } + if (pruneUnreachable && snapshot.unreachableCommits.length) { + actions.push({ kind: "git-prune", target: "unreachable-objects", command: "git reflog expire --expire=now --all && git gc --prune=now", reason: "明确启用 unreachable 对象清理" }); + } + return actions; +} + +function applyCleanup(actions: CleanupAction[]): Array<{ action: CleanupAction; ok: boolean; error?: string }> { + return actions.map((action) => { + try { + if (action.kind === "worktree-remove") git(["worktree", "remove", action.target]); + else if (action.kind === "worktree-prune") git(["worktree", "prune"]); + else if (action.kind === "branch-delete") git(["branch", "-d", action.target]); + else { + git(["reflog", "expire", "--expire=now", "--all"]); + git(["gc", "--prune=now"]); + } + return { action, ok: true }; + } catch (error) { + return { action, ok: false, error: error instanceof Error ? error.message : String(error) }; + } + }); +} + +function createReport(mode: HygieneMode): HygieneReport { + const snapshot = collectSnapshot(); + const findings = buildFindings(snapshot); + const counts = { + info: findings.filter((finding) => finding.level === "info").length, + warning: findings.filter((finding) => finding.level === "warning").length, + blocked: findings.filter((finding) => finding.level === "blocked").length, + }; + const exitCode = classifyExitCode(findings); + return { + schemaVersion: 1, + mode, + generatedAt: new Date().toISOString(), + repository: ROOT, + snapshot, + findings, + counts, + nextActions: findings.map((finding) => finding.nextAction).filter((action): action is string => Boolean(action)), + exitCode, + }; +} + +function emit(value: unknown): void { + process.stdout.write(`${JSON.stringify(value, null, 2)}\n`); +} + +function emitSummary(report: HygieneReport): void { + console.error(`[dev:${report.mode}] ${report.repository}`); + console.error(`发现 ${report.counts.info} 条提示、${report.counts.warning} 条警告、${report.counts.blocked} 条阻塞项;退出码 ${report.exitCode}`); + for (const finding of report.findings) console.error(`- [${finding.level}] ${finding.message}`); +} + +function usage(): string { + return [ + "开发环境检查(不会进入 hose-use 用户命令):", + " bun run dev:status 输出当前开发环境快照", + " bun run dev:check 只读检查并返回语义化退出码", + " bun run dev:clean --dry-run 预览安全清理动作", + " bun run dev:clean --yes 执行干净且已合并的本地清理", + " bun run dev:clean --yes --prune-unreachable 额外清理无引用 Git 对象", + "", + "stdout 始终为 JSON;人类提示和进度写入 stderr。远程分支和非 canonical Skill 目录不会被自动删除。", + ].join("\n"); +} + +export async function main(argv = process.argv.slice(2)): Promise { + const args = parseDevHygieneArgs(argv); + if (args.help) { + emit({ ok: true, usage: usage().split("\n") }); + console.error(usage()); + return 0; + } + + try { + if (args.mode !== "clean") { + const report = createReport(args.mode); + emit(report); + emitSummary(report); + return args.mode === "status" ? 0 : report.exitCode; + } + + const report = createReport("clean"); + const plan = buildCleanupPlan(report.snapshot, args.pruneUnreachable); + if (args.dryRun || !args.yes) { + emit({ ...report, plan, dryRun: true, nextAction: "bun run dev:clean --yes" }); + emitSummary(report); + console.error(plan.length ? "[dev:clean] 当前仅预览,追加 --yes 才会执行。" : "[dev:clean] 没有满足安全条件的本地清理动作。"); + return report.exitCode; + } + + if (report.snapshot.repository.branch === "HEAD") { + emit({ ...report, plan, applied: false, error: "detached HEAD 下拒绝清理" }); + return 3; + } + const results = applyCleanup(plan); + const failed = results.filter((result) => !result.ok); + emit({ ...report, plan, applied: true, results, failed: failed.length }); + console.error(`[dev:clean] 已执行 ${results.length - failed.length} 项,失败 ${failed.length} 项。`); + return failed.length ? 4 : 0; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + emit({ ok: false, error: message }); + console.error(`[dev:hygiene] ${message}`); + return 4; + } +} + +if (import.meta.main) { + main().then((exitCode) => { + process.exitCode = exitCode; + }); +}