luminae-helper 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.0
4
+
5
+ - 新增 runSkillOperation 单次公共安装/卸载入口,供包装器组织统一主菜单;复用现有保护和租约释放,独立菜单与版本命令保持兼容。
6
+
7
+ - 缓存只长期保留最近一次成功获取的正式版本,自动清理临时数据和闲置历史快照;通过跨进程占用保护并发安装,并在退出后回收,保留本地修改。
8
+
9
+ - 公共技能改为安装 / 更新时拉取 ai-skills 最新正式 Tag,显示版本及提交;不再随 npm 包内置或在构建时下载。
10
+ - 使用专用缓存与独立提交快照;下载失败必须明确选择才使用有效旧缓存,无缓存则停止安装。
11
+ - 从已安装受管内容发现离线卸载条目,不依赖源码缓存;保留现有覆盖保护。
12
+ - 包装器迁移:packageRoot 仅用于包身份和版本查询,移除公共内容打包与 sync-skills 钩子。
13
+
3
14
  ## 1.1.2
4
15
 
5
16
  - 安装时目标已存在且非本工具安装(缺 `managed-by`)→ 跳过并在结果表标「已跳过」,不再覆盖用户自建技能目录。
package/README.md CHANGED
@@ -2,11 +2,12 @@
2
2
 
3
3
  AI 编程工具的 skills/commands 管理 CLI。一键将公共 AI agent 技能安装到 Claude Code、Cursor、Codex、Hermes Agent、OpenCode、Trae 等工具中。
4
4
 
5
- npm 包在构建时将所有内容打包,运行时纯本地操作文件系统,不访问网络。
5
+ 公共内容不内置在 npm 包中。选择「安装 / 更新」时从 `ai-skills` 拉取最新正式 Git Tag,再复制到目标工具。首次需要网络与 Git;卸载和 `--version` 不需要拉取技能。
6
6
 
7
7
  ## 前置条件
8
8
 
9
9
  - Node.js >= 18.0.0
10
+ - Git(公共技能安装 / 更新需要访问 GitHub)
10
11
  - 至少一个目标 AI 工具已安装
11
12
 
12
13
  ## 安装
@@ -124,42 +125,28 @@ npm uninstall -g luminae-helper
124
125
 
125
126
  ## 开发
126
127
 
127
- ### 同步公共技能
128
+ ### 公共技能来源与缓存
128
129
 
129
- `commands/` 和 `skills/` 是构建产物(gitignored)。本地开发时,保持 `ai-skills` 为同级目录或设置环境变量:
130
+ 源仓库为 `https://github.com/evenweiss/ai-skills.git`。每次选择「安装 / 更新」都会检查最大正式版本 Tag(`X.Y.Z` 或 `vX.Y.Z`,不含预发布版本),不跟随未发布的 main。界面显示实际 Tag 和提交。
130
131
 
131
- ```bash
132
- git clone https://github.com/evenweiss/ai-skills.git ../ai-skills
133
- LUMINAE_SKILLS_SOURCE=../ai-skills npm run sync-skills
134
- ```
132
+ 缓存位于 `~/.cache/luminae-helper/public-skills/`:首次 clone,后续 fetch。只长期保留最近一次成功获取的正式版本;临时目录和无人使用的历史快照会自动清理。并发安装登记独立占用,旧快照在最后一个使用者退出后才回收,下载与清理不会中断其他安装。正常完成、返回、取消或失败都会释放占用;异常退出的遗留占用与临时数据在下次缓存操作时回收。
133
+
134
+ 不要编辑缓存;工作树或 HEAD 被修改的快照会被保留并提示,不会自动覆盖或删除,因此这类快照需要自行保留改动后处理。
135
+
136
+ 更新失败时,CLI 显示有效旧缓存的 Tag/提交,默认返回;只有明确选择才使用旧缓存安装,且提示未确认是最新版本。没有有效缓存时停止本次安装。删除缓存后,下次安装会重新下载;已安装的受管内容仍可离线卸载,包括新版本中已移除的条目。
135
137
 
136
- 脚本会扫描 `ai-skills/commands/` 和 `ai-skills/skills/`,将包含 `SKILL.md` 的子目录复制到本项目的对应目录。
138
+ 安装继续采用复制方式;更新缓存不会自动修改已安装技能,需要再次选择安装 / 更新。公共技能保留覆盖保护,公司内部技能不属于本工具。
137
139
 
138
- ### 发布
140
+ ### 测试与发布
139
141
 
140
142
  ```bash
141
- npm publish
143
+ npm test
144
+ npm pack
142
145
  ```
143
146
 
144
- 发布前 `prepublishOnly` 钩子以 `--strict` 模式运行同步脚本,确保至少有一个 command 或 skill 被打包。
147
+ 测试使用临时源码、Git 仓库和目标目录,不依赖本地公共技能副本。打包和 npm 安装不再触发技能下载。`commands/`、`skills/` 的旧生成目录仍被忽略,但不会进入 npm 包;旧 `sync-skills` 脚本已移除。
145
148
 
146
- ### 项目结构
147
-
148
- ```
149
- luminae-helper/
150
- ├── src/
151
- │ ├── cli.js # 入口
152
- │ ├── index.js # runCli() 导出
153
- │ └── lib/
154
- │ ├── constants.js # 工具定义、技能发现、安装目标生成
155
- │ ├── installer.js # 安装/卸载逻辑
156
- │ ├── ui.js # 交互式 TUI(inquirer)
157
- │ └── checkbox-with-action-rows.js # 带功能行的多选组件
158
- ├── scripts/fetch-skills.js # 构建时技能同步脚本
159
- ├── commands/ # 构建产物(gitignored)
160
- ├── skills/ # 构建产物(gitignored)
161
- └── package.json
162
- ```
149
+ 需要正式发布 CLI 时再执行 `npm publish`,公共技能的新 Tag 不要求 CLI 同步发版。
163
150
 
164
151
  ## Library API
165
152
 
@@ -170,9 +157,23 @@ import { runCli } from "luminae-helper";
170
157
 
171
158
  const code = await runCli({
172
159
  argv: process.argv.slice(2),
173
- packageRoot: import.meta.dirname, // 指向你自己的 commands/ skills/
160
+ packageRoot: import.meta.dirname, // 包装器的 package.json 所在目录
174
161
  });
175
162
  process.exit(code);
176
163
  ```
177
164
 
178
- `packageRoot` 让包装器提供自己的 `commands/` 和 `skills/`,复用相同的交互式安装引擎。
165
+ `packageRoot` 用于包装器名称、版本和 registry 查询;公共技能统一使用运行时仓库缓存。
166
+
167
+ 迁移注意:`packageRoot` 不再作为公共技能分发源,包装器无需打包自己的 `commands/`、`skills/` 或执行同步钩子。已安装技能的管理标识保持兼容。
168
+
169
+
170
+ 包装器需要自行组织主菜单时,复用单次操作入口:
171
+
172
+ ```js
173
+ import { runSkillOperation } from "luminae-helper";
174
+
175
+ const code = await runSkillOperation("install", { packageRoot: wrapperRoot });
176
+ // 或 runSkillOperation("uninstall", { packageRoot: wrapperRoot })
177
+ ```
178
+
179
+ 只接受 `install` / `uninstall`,非法操作会拒绝。入口不展示引擎自己的主菜单,完成或取消后返回控制权;嵌入流程的操作结束提示为返回主菜单。操作异常返回 `1`,正常或取消返回 `0`。缓存、覆盖保护、复制安装、离线卸载和快照占用释放继续由共享实现负责。独立运行 `luminae-helper` 仍使用原菜单,`runCli()` 的版本命令保持不变。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "luminae-helper",
3
- "version": "1.1.2",
3
+ "version": "1.2.0",
4
4
  "description": "Install public AI agent skills to coding tools",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -12,20 +12,13 @@
12
12
  "src/index.js",
13
13
  "src/lib/*.js",
14
14
  "src/utils/*.js",
15
- "scripts/fetch-skills.js",
16
- "commands/",
17
- "skills/",
18
15
  "README.md",
19
16
  "CHANGELOG.md"
20
17
  ],
21
18
  "scripts": {
22
19
  "start": "node src/cli.js",
23
20
  "dev": "node --watch src/cli.js",
24
- "test": "vitest run",
25
- "sync-skills": "node scripts/fetch-skills.js",
26
- "prepare": "node scripts/fetch-skills.js",
27
- "prepack": "node scripts/fetch-skills.js --strict",
28
- "prepublishOnly": "node scripts/fetch-skills.js --strict"
21
+ "test": "vitest run"
29
22
  },
30
23
  "keywords": [
31
24
  "claude",
package/src/index.js CHANGED
@@ -4,7 +4,6 @@ export async function runCli(options = {}) {
4
4
  globalThis.__LUMINAE_PACKAGE_ROOT__ = options.packageRoot;
5
5
  }
6
6
 
7
- const { runInteractive, TERM_GUTTER } = await import("./lib/ui.js");
8
7
  const { printVersion, checkOutdated } = await import("./utils/version.js");
9
8
 
10
9
  if (argv.includes("--version") || argv.includes("-v")) {
@@ -17,15 +16,23 @@ export async function runCli(options = {}) {
17
16
  return 0;
18
17
  }
19
18
 
19
+ const { runInteractive, runOperation, TERM_GUTTER } = await import("./lib/ui.js");
20
20
  try {
21
- await runInteractive();
21
+ if (options.operation) await runOperation(options.operation);
22
+ else await runInteractive();
22
23
  return 0;
23
24
  } catch (error) {
24
25
  if (error?.name === "ExitPromptError") {
25
- console.log("\n" + TERM_GUTTER + "👋 Bye!\n");
26
+ if (!options.operation) console.log("\n" + TERM_GUTTER + "👋 Bye!\n");
26
27
  return 0;
27
28
  }
28
29
  console.error("\n" + TERM_GUTTER + "Error:", error.message ?? String(error));
29
30
  return 1;
30
31
  }
31
32
  }
33
+
34
+ /** Execute one shared public-skill flow, then return control to a wrapper. */
35
+ export async function runSkillOperation(action, options = {}) {
36
+ if (!["install", "uninstall"].includes(action)) throw new TypeError(`Unknown skill operation: ${action}`);
37
+ return runCli({ ...options, argv: [], operation: action });
38
+ }
@@ -0,0 +1,112 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+
7
+ function isAlive(pid) {
8
+ if (!Number.isSafeInteger(pid) || pid < 1) return true;
9
+ try { process.kill(pid, 0); return true; }
10
+ catch (error) { return error.code !== "ESRCH"; }
11
+ }
12
+ function ownerPid(name) {
13
+ const match = name.match(/^([1-9]\d*)-[a-f0-9-]{36}\.owner$/);
14
+ return match ? Number(match[1]) : null;
15
+ }
16
+ function removeOwner(directory, name) {
17
+ try { unlinkSync(join(directory, name)); } catch (error) { if (error.code !== "ENOENT") throw error; }
18
+ // Never recursively delete a shared lock: a new owner may already be here.
19
+ try { rmdirSync(directory); } catch (error) { if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code)) throw error; }
20
+ }
21
+ function reapDeadLock(directory) {
22
+ try {
23
+ for (const name of readdirSync(directory)) {
24
+ const pid = ownerPid(name);
25
+ if (pid !== null && !isAlive(pid)) removeOwner(directory, name);
26
+ }
27
+ try { rmdirSync(directory); } catch (error) { if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code)) throw error; }
28
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
29
+ }
30
+ export async function withCacheLock(cacheDir, action) {
31
+ mkdirSync(cacheDir, { recursive: true });
32
+ const identity = `${process.pid}-${randomUUID()}`;
33
+ const waiting = join(cacheDir, `lock-${identity}`);
34
+ mkdirSync(waiting);
35
+ const owner = `${identity}.owner`;
36
+ const lock = join(cacheDir, "operation.lock");
37
+ try {
38
+ writeFileSync(join(waiting, owner), "");
39
+ const deadline = Date.now() + 120000;
40
+ while (true) {
41
+ try { renameSync(waiting, lock); break; }
42
+ catch (error) {
43
+ if (!["EEXIST", "ENOTEMPTY"].includes(error.code)) throw error;
44
+ reapDeadLock(lock);
45
+ if (Date.now() >= deadline) throw new Error("公共技能缓存正在更新,请稍后重试");
46
+ await delay(50);
47
+ }
48
+ }
49
+ try { return await action(); }
50
+ finally { removeOwner(lock, owner); }
51
+ } finally { rmSync(waiting, { recursive: true, force: true }); }
52
+ }
53
+ function activeCommits(cacheDir) {
54
+ const directory = join(cacheDir, "leases");
55
+ mkdirSync(directory, { recursive: true });
56
+ const active = new Set();
57
+ for (const name of readdirSync(directory)) {
58
+ if (!/^[a-f0-9-]{36}\.json$/.test(name)) continue;
59
+ const path = join(directory, name);
60
+ let lease;
61
+ try { lease = JSON.parse(readFileSync(path, "utf8")); } catch { rmSync(path, { force: true }); continue; }
62
+ if (isAlive(lease.pid)) {
63
+ if (/^[a-f0-9]{40,64}$/.test(lease.commit)) active.add(lease.commit);
64
+ } else { rmSync(path, { force: true }); }
65
+ }
66
+ return active;
67
+ }
68
+ // All lifecycle mutations, including lease registration, run under the same short lock.
69
+ export function cleanupCache(cacheDir) {
70
+ const active = activeCommits(cacheDir);
71
+ for (const name of readdirSync(cacheDir)) {
72
+ if (/^clone-[\w-]+$/.test(name) || /^current-[\w-]+\.json$/.test(name)) rmSync(join(cacheDir, name), { recursive: true, force: true });
73
+ const waiting = name.match(/^lock-([1-9]\d*)-[a-f0-9-]{36}$/);
74
+ if (waiting && !isAlive(Number(waiting[1]))) rmSync(join(cacheDir, name), { recursive: true, force: true });
75
+ }
76
+ let current;
77
+ try { current = JSON.parse(readFileSync(join(cacheDir, "current.json"), "utf8")).commit; } catch { /* Keep snapshots if the pointer cannot be read. */ }
78
+ const directory = join(cacheDir, "snapshots");
79
+ if (!existsSync(directory)) return;
80
+ for (const name of readdirSync(directory)) {
81
+ const path = join(directory, name);
82
+ if (/^checkout-[\w-]+$/.test(name)) { rmSync(path, { recursive: true, force: true }); continue; }
83
+ if (!/^[a-f0-9]{40,64}$/.test(current || "") || !/^[a-f0-9]{40,64}$/.test(name) || name === current || active.has(name)) continue;
84
+ if (!lstatSync(path).isDirectory()) continue;
85
+ try {
86
+ const run = args => execFileSync("git", args, { cwd: path, encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "pipe"] }).trim();
87
+ if (run(["rev-parse", "HEAD"]) !== name || run(["status", "--porcelain", "--untracked-files=all", "--ignored"])) {
88
+ console.warn(`公共技能旧快照包含本地修改,已保留:${path}`);
89
+ continue;
90
+ }
91
+ } catch { console.warn(`公共技能旧快照无法验证,已保留:${path}`); continue; }
92
+ rmSync(path, { recursive: true, force: true });
93
+ }
94
+ }
95
+ export function leaseSource(cacheDir, source) {
96
+ const directory = join(cacheDir, "leases");
97
+ mkdirSync(directory, { recursive: true });
98
+ const path = join(directory, `${randomUUID()}.json`);
99
+ writeFileSync(path, JSON.stringify({ pid: process.pid, commit: source.commit }));
100
+ let released = false;
101
+ return {
102
+ ...source,
103
+ async release() {
104
+ if (released) return;
105
+ await withCacheLock(cacheDir, () => {
106
+ rmSync(path, { force: true });
107
+ cleanupCache(cacheDir);
108
+ released = true;
109
+ });
110
+ },
111
+ };
112
+ }
@@ -1,6 +1,6 @@
1
1
  import { homedir } from "os";
2
2
  import { join } from "path";
3
- import { existsSync, readdirSync, readFileSync, statSync } from "fs";
3
+ import { existsSync, readdirSync, readFileSync, lstatSync } from "fs";
4
4
  import { commandExists } from "../utils/platform.js";
5
5
 
6
6
  // ── Tools ──
@@ -147,8 +147,9 @@ function generateInstallTargets(skillId, skillType) {
147
147
  return targets;
148
148
  }
149
149
 
150
- export function discoverSkills() {
151
- const packageDir = getPackageDir();
150
+ let skillsRoot = null;
151
+
152
+ export function discoverSkills(packageDir = skillsRoot || getPackageDir()) {
152
153
  const skills = [];
153
154
 
154
155
  const typeDirs = [
@@ -160,14 +161,14 @@ export function discoverSkills() {
160
161
 
161
162
  for (const { dir, type } of typeDirs) {
162
163
  const typePath = join(packageDir, dir);
163
- if (!existsSync(typePath)) continue;
164
+ if (!existsSync(typePath) || !lstatSync(typePath).isDirectory()) continue;
164
165
 
165
166
  for (const entry of readdirSync(typePath)) {
166
167
  const skillPath = join(typePath, entry);
167
- if (!statSync(skillPath).isDirectory()) continue;
168
+ if (!lstatSync(skillPath).isDirectory()) continue;
168
169
 
169
170
  const skillFile = join(skillPath, "SKILL.md");
170
- if (!existsSync(skillFile)) continue;
171
+ if (!existsSync(skillFile) || !lstatSync(skillFile).isFile()) continue;
171
172
 
172
173
  const skillId = entry;
173
174
 
@@ -195,6 +196,40 @@ export function discoverSkills() {
195
196
 
196
197
  export const SKILLS = discoverSkills();
197
198
 
199
+ export function setSkillsSource(root) {
200
+ const skills = discoverSkills(root);
201
+ skillsRoot = root;
202
+ SKILLS.splice(0, SKILLS.length, ...skills);
203
+ }
204
+
205
+ export function discoverInstalledSkills(tools = TOOLS) {
206
+ const found = new Map();
207
+ for (const tool of tools) {
208
+ for (const mode of ["file", "dir"]) {
209
+ const parent = mode === "file" ? tool.commandDir?.() : tool.skillDir?.();
210
+ if (!parent || !existsSync(parent)) continue;
211
+ for (const entry of readdirSync(parent)) {
212
+ const dest = join(parent, entry);
213
+ if (mode === "file" ? !entry.endsWith(".md") || !lstatSync(dest).isFile() : !lstatSync(dest).isDirectory()) continue;
214
+ const file = mode === "file" ? dest : join(dest, "SKILL.md");
215
+ if (!existsSync(file) || !lstatSync(file).isFile()) continue;
216
+ const content = readFileSync(file, "utf8");
217
+ if (!content.includes("managed-by: luminae-helper")) continue;
218
+ const id = mode === "file" ? entry.slice(0, -3) : entry;
219
+ // A command and a skill with the same id may both be installed in one tool.
220
+ const key = `${mode}:${id}`;
221
+ if (!found.has(key)) found.set(key, { id: key, ...parseSkillMeta(id, content), type: mode === "file" ? "command" : "skill", installTargets: [] });
222
+ found.get(key).installTargets.push({ toolId: tool.id, installMode: mode, conversion: null, destPath: () => dest });
223
+ }
224
+ }
225
+ }
226
+ return [...found.values()];
227
+ }
228
+
229
+ export function useInstalledSkills() {
230
+ SKILLS.splice(0, SKILLS.length, ...discoverInstalledSkills());
231
+ }
232
+
198
233
  export function detectInstalledTools() {
199
234
  return TOOLS.map((tool) => ({
200
235
  ...tool,
@@ -208,5 +243,5 @@ export function getSkillSourcePath(skillId) {
208
243
  throw new Error(`Unknown skillId: "${skillId}" — not found in discovered skills`);
209
244
  }
210
245
  const subDir = skill.type === "command" ? "commands" : "skills";
211
- return join(getPackageDir(), subDir, skillId);
246
+ return join(skillsRoot || getPackageDir(), subDir, skillId);
212
247
  }
@@ -0,0 +1,126 @@
1
+ import { execFile, execFileSync } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join, resolve } from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+ import { randomUUID } from "node:crypto";
8
+ import { cleanupCache, leaseSource, withCacheLock } from "./cache-lifecycle.js";
9
+ import { discoverSkills } from "./constants.js";
10
+
11
+ const exec = promisify(execFile);
12
+ const DEFAULT_REPO = "https://github.com/evenweiss/ai-skills.git";
13
+ export function publicSourceOptions() {
14
+ return { repo: DEFAULT_REPO, cacheDir: join(homedir(), ".cache", "luminae-helper", "public-skills") };
15
+ }
16
+ function optionsWithDefaults(options) {
17
+ return { ...publicSourceOptions(), ...options };
18
+ }
19
+ async function git(args, cwd) {
20
+ const { stdout } = await exec("git", args, {
21
+ cwd, encoding: "utf8", timeout: 30000, maxBuffer: 8 * 1024 * 1024,
22
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never", LC_ALL: "C" },
23
+ });
24
+ return stdout.trim();
25
+ }
26
+ function publishDirectory(temp, destination) {
27
+ try { renameSync(temp, destination); }
28
+ catch (error) {
29
+ // Another installer may have published this complete directory first.
30
+ if (!["EEXIST", "ENOTEMPTY"].includes(error.code) || !existsSync(destination)) throw error;
31
+ }
32
+ }
33
+ async function fetchTags(mirror) {
34
+ for (let attempt = 0; ; attempt++) {
35
+ try { return await git(["fetch", "--prune", "--no-tags", "origin", "refs/tags/*:refs/tags/*"], mirror); }
36
+ catch (error) {
37
+ if (attempt >= 2 || !/cannot lock ref|Unable to create .*\.lock/.test(error.stderr || "")) throw error;
38
+ await delay(200);
39
+ }
40
+ }
41
+ }
42
+ function stableTags(text) {
43
+ return text.split("\n").filter(tag => /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(tag))
44
+ .sort((a, b) => {
45
+ const av = a.replace(/^v/, "").split(".").map(BigInt);
46
+ const bv = b.replace(/^v/, "").split(".").map(BigInt);
47
+ for (let i = 0; i < 3; i++) if (av[i] !== bv[i]) return av[i] > bv[i] ? -1 : 1;
48
+ return a.localeCompare(b);
49
+ });
50
+ }
51
+ // Offline checks are synchronous so uninstall never needs a source fetch.
52
+ export function readCachedSource(options = {}) {
53
+ const { repo, cacheDir } = optionsWithDefaults(options);
54
+ try {
55
+ const info = JSON.parse(readFileSync(join(cacheDir, "current.json"), "utf8"));
56
+ if (info.repo !== repo || !/^[a-f0-9]{40,64}$/.test(info.commit) || stableTags(info.tag)[0] !== info.tag) return null;
57
+ const root = join(resolve(cacheDir), "snapshots", info.commit);
58
+ const run = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "pipe"] }).trim();
59
+ if (run("rev-parse", "HEAD") !== info.commit || run("status", "--porcelain", "--untracked-files=all", "--ignored")) return null;
60
+ if (discoverSkills(root).length === 0) return null;
61
+ return { root, tag: info.tag, commit: info.commit };
62
+ } catch { return null; }
63
+ }
64
+
65
+ export async function acquireCachedSource(options = {}) {
66
+ const resolved = optionsWithDefaults(options);
67
+ return withCacheLock(resolved.cacheDir, () => {
68
+ const source = readCachedSource(resolved);
69
+ const held = source ? leaseSource(resolved.cacheDir, source) : null;
70
+ cleanupCache(resolved.cacheDir);
71
+ return held;
72
+ });
73
+ }
74
+
75
+ export async function refreshPublicSource(options = {}) {
76
+ const resolved = optionsWithDefaults(options);
77
+ return withCacheLock(resolved.cacheDir, async () => {
78
+ cleanupCache(resolved.cacheDir);
79
+ try {
80
+ const source = await refreshUnlocked(resolved);
81
+ return leaseSource(resolved.cacheDir, source);
82
+ } finally { cleanupCache(resolved.cacheDir); }
83
+ });
84
+ }
85
+
86
+ async function refreshUnlocked(options) {
87
+ const { repo, cacheDir } = optionsWithDefaults(options);
88
+ mkdirSync(cacheDir, { recursive: true });
89
+ const mirror = join(cacheDir, "repository.git");
90
+ if (!existsSync(mirror)) {
91
+ const temp = mkdtempSync(join(cacheDir, "clone-"));
92
+ try {
93
+ await git(["clone", "--bare", "--", repo, temp]);
94
+ publishDirectory(temp, mirror);
95
+ } finally { rmSync(temp, { recursive: true, force: true }); }
96
+ } else {
97
+ if (await git(["remote", "get-url", "origin"], mirror) !== repo) throw new Error("公共技能缓存来源不匹配");
98
+ await fetchTags(mirror);
99
+ }
100
+ if (await git(["remote", "get-url", "origin"], mirror) !== repo) throw new Error("公共技能缓存来源不匹配");
101
+ const tag = stableTags(await git(["tag", "--list"], mirror))[0];
102
+ if (!tag) throw new Error("公共技能仓库没有正式版本 Tag");
103
+ const commit = await git(["rev-parse", `refs/tags/${tag}^{commit}`], mirror);
104
+ const snapshots = join(resolve(cacheDir), "snapshots");
105
+ mkdirSync(snapshots, { recursive: true });
106
+ const root = join(snapshots, commit);
107
+ if (!existsSync(root)) {
108
+ const temp = mkdtempSync(join(snapshots, "checkout-"));
109
+ try {
110
+ await git(["clone", "--no-checkout", "--no-hardlinks", "--", resolve(mirror), temp]);
111
+ await git(["checkout", "--detach", commit], temp);
112
+ if (discoverSkills(temp).length === 0) throw new Error("正式版本没有可安装的公共技能");
113
+ publishDirectory(temp, root);
114
+ } finally { rmSync(temp, { recursive: true, force: true }); }
115
+ }
116
+ if (await git(["rev-parse", "HEAD"], root) !== commit || await git(["status", "--porcelain", "--untracked-files=all", "--ignored"], root)) {
117
+ throw new Error("公共技能快照已被修改,请保留本地改动并移走该快照后重试");
118
+ }
119
+ if (discoverSkills(root).length === 0) throw new Error("正式版本没有可安装的公共技能");
120
+ const pointer = join(cacheDir, `current-${randomUUID()}.json`);
121
+ try {
122
+ writeFileSync(pointer, JSON.stringify({ repo, tag, commit }) + "\n");
123
+ renameSync(pointer, join(cacheDir, "current.json"));
124
+ } finally { rmSync(pointer, { force: true }); }
125
+ return { root, tag, commit };
126
+ }