@matrixfu/skill-set-manager 0.0.0-stage → 1.1.2
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/client.js +1618 -0
- package/cordis.patch.yml +5 -0
- package/icon.svg +7 -0
- package/index.js +1091 -0
- package/lib/core/atomic.js +16 -0
- package/lib/core/backup.js +123 -0
- package/lib/core/binding.js +22 -0
- package/lib/core/commandLine.js +31 -0
- package/lib/core/dataPlane.js +81 -0
- package/lib/core/diagnose.js +167 -0
- package/lib/core/effective.js +237 -0
- package/lib/core/giterr.js +22 -0
- package/lib/core/github.js +256 -0
- package/lib/core/gitignore.js +35 -0
- package/lib/core/gitnet.js +112 -0
- package/lib/core/lifecycle.js +88 -0
- package/lib/core/linkx.js +92 -0
- package/lib/core/managed.js +24 -0
- package/lib/core/manifest.js +169 -0
- package/lib/core/migrate.js +145 -0
- package/lib/core/opgate.js +62 -0
- package/lib/core/paths.js +52 -0
- package/lib/core/pending.js +210 -0
- package/lib/core/plan.js +33 -0
- package/lib/core/projectRoot.js +20 -0
- package/lib/core/providerSkills.js +26 -0
- package/lib/core/provision.js +32 -0
- package/lib/core/resident.js +98 -0
- package/lib/core/resolver.js +136 -0
- package/lib/core/search.js +28 -0
- package/lib/core/sets.js +250 -0
- package/lib/core/source.js +64 -0
- package/lib/core/storage.js +87 -0
- package/lib/core/translateExec.js +122 -0
- package/lib/core/translations.js +62 -0
- package/lib/core/updates.js +181 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +63 -4
- package/README.md +0 -3
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 技能扫描与解析(§7.1/§7.3)。
|
|
3
|
+
* 陷阱照抄取证:条目性质判定只用 stat/lstat,禁 readdir Dirent(junction 会报成 symlink);
|
|
4
|
+
* 只扫一层(嵌套 SKILL.md 不被发现);`.managed.json`/`.system`/点开头条目一律跳过。
|
|
5
|
+
*/
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { SKILL_NAME_RE, ZONE_RANKS } from './paths.js';
|
|
9
|
+
|
|
10
|
+
const MAX_SKILL_BYTES = 64 * 1024;
|
|
11
|
+
|
|
12
|
+
function unquote(v) {
|
|
13
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) return v.slice(1, -1);
|
|
14
|
+
return v;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** 极简 frontmatter:`key: value` 与 `key: >-`/`key: |` 折叠块(足够读 name/description 等标量)。 */
|
|
18
|
+
export function parseFrontmatter(text) {
|
|
19
|
+
const m = /^---\r?\n([\s\S]*?)(?:\r?\n---|$)/.exec(text);
|
|
20
|
+
if (!m) return null;
|
|
21
|
+
const out = {};
|
|
22
|
+
const lines = m[1].split(/\r?\n/);
|
|
23
|
+
for (let i = 0; i < lines.length; i++) {
|
|
24
|
+
const kv = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/.exec(lines[i]);
|
|
25
|
+
if (!kv) continue;
|
|
26
|
+
const key = kv[1];
|
|
27
|
+
let val = kv[2].trim();
|
|
28
|
+
if (val === '' || val.startsWith('>') || val.startsWith('|') || val.startsWith('&')) {
|
|
29
|
+
const cont = [];
|
|
30
|
+
while (i + 1 < lines.length && /^\s+\S/.test(lines[i + 1])) cont.push(lines[++i].trim());
|
|
31
|
+
val = cont.join(' ');
|
|
32
|
+
}
|
|
33
|
+
out[key] = unquote(val);
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function truthy(v) { return v === true || v === 'true' || v === 'yes'; }
|
|
39
|
+
function falsy(v) { return v === false || v === 'false' || v === 'no'; }
|
|
40
|
+
|
|
41
|
+
function readEntry(dir, name, zone, rank, fsImpl) {
|
|
42
|
+
const entryPath = path.join(dir, name);
|
|
43
|
+
let st;
|
|
44
|
+
try { st = fsImpl.statSync(entryPath); } catch { return null; } // stat 跟随 junction
|
|
45
|
+
if (name.endsWith('.md')) {
|
|
46
|
+
if (!st.isFile()) return null;
|
|
47
|
+
return finalize(entryPath.slice(0, -3), entryPath, dir, zone, rank, 'flat', fsImpl);
|
|
48
|
+
}
|
|
49
|
+
if (!st.isDirectory()) return null;
|
|
50
|
+
const skillPath = path.join(entryPath, 'SKILL.md');
|
|
51
|
+
try { if (!fsImpl.statSync(skillPath).isFile()) return null; } catch { return null; }
|
|
52
|
+
return finalize(name, skillPath, entryPath, zone, rank, 'dir', fsImpl);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function finalize(baseName, skillPath, dirPath, zone, rank, kind, fsImpl) {
|
|
56
|
+
let text = '';
|
|
57
|
+
try { text = fsImpl.readFileSync(skillPath, 'utf8').slice(0, MAX_SKILL_BYTES); } catch {}
|
|
58
|
+
const fm = parseFrontmatter(text);
|
|
59
|
+
const name = (fm && fm.name) ? String(fm.name).trim() : baseName;
|
|
60
|
+
const problems = [];
|
|
61
|
+
if (!fm) problems.push('missing-frontmatter');
|
|
62
|
+
if (!SKILL_NAME_RE.test(name)) problems.push('not-kebab-case');
|
|
63
|
+
if (!fm || !fm.description) problems.push('missing-description');
|
|
64
|
+
return {
|
|
65
|
+
name,
|
|
66
|
+
path: skillPath,
|
|
67
|
+
dirPath,
|
|
68
|
+
zone,
|
|
69
|
+
rank,
|
|
70
|
+
kind,
|
|
71
|
+
frontmatter: fm,
|
|
72
|
+
valid: problems.length === 0,
|
|
73
|
+
problems,
|
|
74
|
+
invocation: {
|
|
75
|
+
modelInvocable: !truthy(fm && fm['disable-model-invocation']),
|
|
76
|
+
userInvocable: !falsy(fm && fm['user-invocable']),
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function scanDir(dir, zone, rank, fsImpl) {
|
|
82
|
+
const out = [];
|
|
83
|
+
let names;
|
|
84
|
+
try { names = fsImpl.readdirSync(dir); } catch { return out; } // 目录不存在 = 该层缺席
|
|
85
|
+
for (const name of names) {
|
|
86
|
+
if (name.startsWith('.')) continue; // 含 .managed.json 与 .system
|
|
87
|
+
const e = readEntry(dir, name, zone, rank, fsImpl);
|
|
88
|
+
if (e) out.push(e);
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** 按 rank 优先级扫描全部生效层(技能库不在其中——§4.2)。 */
|
|
94
|
+
export async function scanSkills(roots, projectRoot, { fs: fsImpl = fs } = {}) {
|
|
95
|
+
const zones = [
|
|
96
|
+
['project-dsh', path.join(projectRoot, '.dsh', 'skills')],
|
|
97
|
+
['project-agents', path.join(projectRoot, '.agents', 'skills')],
|
|
98
|
+
...roots.customDirs.map((d) => ['custom', d]),
|
|
99
|
+
['user-dsh', roots.userDshRoot],
|
|
100
|
+
['user-agents', roots.userAgentsRoot],
|
|
101
|
+
];
|
|
102
|
+
const entries = [];
|
|
103
|
+
for (const [zone, dir] of zones) entries.push(...scanDir(dir, zone, ZONE_RANKS[zone], fsImpl));
|
|
104
|
+
return entries;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 同名冲突:rank 小者胜(上层整体优先),同层先到者胜。 */
|
|
108
|
+
export function dedupeWinners(entries) {
|
|
109
|
+
const sorted = [...entries].sort((a, b) => a.rank - b.rank);
|
|
110
|
+
const winners = new Map();
|
|
111
|
+
for (const e of sorted) if (!winners.has(e.name)) winners.set(e.name, e);
|
|
112
|
+
return winners;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* 技能名 → 链接本体(§7.4 存在性检查 + T4 的 junction 目标):
|
|
117
|
+
* 库内本体优先(技能集引用库技能,junction 指向库);否则取生效层 rank 胜者;都没有 → missing。
|
|
118
|
+
*/
|
|
119
|
+
export async function resolveSkillTargets(roots, projectRoot, names, { fs: fsImpl = fs } = {}) {
|
|
120
|
+
const entries = await scanSkills(roots, projectRoot, { fs: fsImpl });
|
|
121
|
+
const winners = dedupeWinners(entries);
|
|
122
|
+
const targets = new Map();
|
|
123
|
+
const missing = [];
|
|
124
|
+
for (const name of names) {
|
|
125
|
+
const libBody = path.join(roots.libraryRoot, name);
|
|
126
|
+
let lib = false;
|
|
127
|
+
try { lib = fsImpl.statSync(path.join(libBody, 'SKILL.md')).isFile(); } catch {}
|
|
128
|
+
if (lib) targets.set(name, { path: libBody, origin: 'library', kind: 'dir' });
|
|
129
|
+
else if (winners.has(name) && winners.get(name).valid) {
|
|
130
|
+
const w = winners.get(name);
|
|
131
|
+
// flat <name>.md 没有可链接目录:effective 对 flat 用文件复制(junction 只用于目录)
|
|
132
|
+
targets.set(name, { path: w.kind === 'flat' ? w.path : w.dirPath, origin: w.zone, kind: w.kind });
|
|
133
|
+
} else missing.push(name);
|
|
134
|
+
}
|
|
135
|
+
return { targets, missing };
|
|
136
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* P3 搜索匹配器(设计 §6.2):纯函数零依赖,host CASES 与 client(web bundle)共用同一实现。
|
|
3
|
+
* 口径:归一化(小写 + 全半角折叠)→ 空白分 token,token 间 AND、字段间 OR(每 token 须命中同一行的任一字段);
|
|
4
|
+
* 排序 = 名称前缀 > 名称包含 > 其余,同级按名称字典序。
|
|
5
|
+
*/
|
|
6
|
+
export function normalize(s) {
|
|
7
|
+
if (typeof s !== 'string') return '';
|
|
8
|
+
return s
|
|
9
|
+
.toLowerCase()
|
|
10
|
+
.replace(/[\uFF01-\uFF5E]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) - 0xFEE0)) // 全角 ASCII → 半角
|
|
11
|
+
.replace(/\u3000/g, ' '); // 全角空格
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function searchRows(rows, query, fields = ['name', 'source', 'description', 'descriptionZh']) {
|
|
15
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
16
|
+
const tokens = normalize(query).split(/\s+/).filter(Boolean);
|
|
17
|
+
if (!tokens.length) return list.slice();
|
|
18
|
+
const scored = [];
|
|
19
|
+
for (const row of list) {
|
|
20
|
+
const vals = fields.map((f) => normalize(row?.[f]));
|
|
21
|
+
if (!tokens.every((t) => vals.some((v) => v.includes(t)))) continue; // token AND、字段 OR
|
|
22
|
+
const name = vals[0];
|
|
23
|
+
const rank = tokens.every((t) => name.startsWith(t)) ? 0 : tokens.every((t) => name.includes(t)) ? 1 : 2;
|
|
24
|
+
scored.push({ row, rank });
|
|
25
|
+
}
|
|
26
|
+
scored.sort((a, b) => a.rank - b.rank || String(a.row?.name ?? '').localeCompare(String(b.row?.name ?? '')));
|
|
27
|
+
return scored.map((s) => s.row);
|
|
28
|
+
}
|
package/lib/core/sets.js
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 技能集数据模型(§5/§11):setsDir 下每集一个用户可见 JSON 文件;
|
|
3
|
+
* slug = ASCII kebab 稳定文件名(binding 引用它,重命名只改文件内显示名);
|
|
4
|
+
* 常驻 = 保留文件 _resident.json(§5.3:插件级全局唯一一份)。
|
|
5
|
+
*/
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { SKILL_NAME_RE } from './paths.js';
|
|
9
|
+
import { writeTextAtomic } from './atomic.js';
|
|
10
|
+
import { writeSkillManifest } from './manifest.js';
|
|
11
|
+
|
|
12
|
+
export const RESIDENT_SLUG = '_resident';
|
|
13
|
+
|
|
14
|
+
export function slugify(name) {
|
|
15
|
+
const s = String(name || '').toLowerCase()
|
|
16
|
+
.normalize('NFKD')
|
|
17
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
18
|
+
.replace(/^-+|-+$/g, '');
|
|
19
|
+
return s;
|
|
20
|
+
}
|
|
21
|
+
function uniqueSlug(roots, base) {
|
|
22
|
+
let slug = base || 'set';
|
|
23
|
+
for (let n = 2; fs.existsSync(path.join(roots.setsDir, `${slug}.json`)); n++) slug = `${base}-${n}`;
|
|
24
|
+
return slug;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function setPath(roots, slug) { return path.join(roots.setsDir, `${slug}.json`); }
|
|
28
|
+
function readJson(file) {
|
|
29
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) {
|
|
30
|
+
if (e.code === 'ENOENT') return null;
|
|
31
|
+
throw new Error(`${file}: 解析失败(文件被手改坏?请人工修复,插件不覆盖): ${e.message}`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function loadSet(roots, slug) {
|
|
36
|
+
if (slug === RESIDENT_SLUG) return null;
|
|
37
|
+
return readJson(setPath(roots, slug));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function listSets(roots) {
|
|
41
|
+
let names;
|
|
42
|
+
try { names = fs.readdirSync(roots.setsDir); } catch { return []; }
|
|
43
|
+
return names
|
|
44
|
+
.filter((n) => n.endsWith('.json') && n !== `${RESIDENT_SLUG}.json`)
|
|
45
|
+
.map((n) => readJson(path.join(roots.setsDir, n)))
|
|
46
|
+
.filter(Boolean)
|
|
47
|
+
.map((s) => ({ slug: s.slug, name: s.name, description: s.description, skills: s.skills, updatedAt: s.updatedAt }));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function saveSet(roots, set) {
|
|
51
|
+
const { slug, name, description = '', skills = [] } = set;
|
|
52
|
+
if (!slug || slug === RESIDENT_SLUG || !SKILL_NAME_RE.test(slug)) throw new Error(`非法 slug: ${JSON.stringify(slug)}(须 ASCII kebab-case,且不用保留名 _resident)`);
|
|
53
|
+
if (!name || String(name).trim() === '') throw new Error('技能集显示名不能为空');
|
|
54
|
+
for (const s of skills) if (!SKILL_NAME_RE.test(s)) throw new Error(`技能名不合法(非 kebab-case): ${s}`);
|
|
55
|
+
for (const other of listSets(roots)) {
|
|
56
|
+
if (other.slug !== slug && other.name === name) throw new Error(`显示名已被技能集「${other.slug}」占用,导入/新建不覆盖`);
|
|
57
|
+
}
|
|
58
|
+
const prev = readJson(setPath(roots, slug));
|
|
59
|
+
const doc = { slug, name, description, skills: [...skills], createdAt: prev?.createdAt ?? new Date().toISOString(), updatedAt: new Date().toISOString() };
|
|
60
|
+
writeTextAtomic(setPath(roots, slug), JSON.stringify(doc, null, 2) + '\n');
|
|
61
|
+
return doc;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function deleteSet(roots, slug) {
|
|
65
|
+
if (slug === RESIDENT_SLUG) throw new Error('常驻技能不是技能集,不能按技能集删除');
|
|
66
|
+
try { fs.unlinkSync(setPath(roots, slug)); return true; } catch (e) { if (e.code === 'ENOENT') return false; throw e; }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 只改显示名;slug 稳定(binding 引用不断,§11)。 */
|
|
70
|
+
export function renameSet(roots, slug, newName) {
|
|
71
|
+
const set = loadSet(roots, slug);
|
|
72
|
+
if (!set) throw new Error(`技能集不存在: ${slug}`);
|
|
73
|
+
const old = set.name;
|
|
74
|
+
set.name = String(newName).trim();
|
|
75
|
+
set.updatedAt = new Date().toISOString();
|
|
76
|
+
return (saveSet(roots, set), { old, new: set.name });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function copySet(roots, slug, name) {
|
|
80
|
+
const set = loadSet(roots, slug);
|
|
81
|
+
if (!set) throw new Error(`技能集不存在: ${slug}`);
|
|
82
|
+
const newSlug = uniqueSlug(roots, slugify(name || `${set.name}-copy`) || `${slug}-copy`);
|
|
83
|
+
return saveSet(roots, { slug: newSlug, name: name || `${set.name} 副本`, description: set.description, skills: set.skills });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ---------- 常驻技能(§5.3) ----------
|
|
87
|
+
export function loadResident(roots) {
|
|
88
|
+
return readJson(path.join(roots.setsDir, `${RESIDENT_SLUG}.json`)) ?? { slug: RESIDENT_SLUG, name: '常驻技能', skills: [] };
|
|
89
|
+
}
|
|
90
|
+
export function saveResident(roots, skills, { links } = {}) {
|
|
91
|
+
for (const s of skills) if (!SKILL_NAME_RE.test(s)) throw new Error(`技能名不合法: ${s}`);
|
|
92
|
+
const prev = readJson(path.join(roots.setsDir, `${RESIDENT_SLUG}.json`));
|
|
93
|
+
const doc = {
|
|
94
|
+
slug: RESIDENT_SLUG, name: '常驻技能', skills: [...skills],
|
|
95
|
+
links: links ?? prev?.links ?? {}, // 全局区自建链接台账(退常驻精确回收)
|
|
96
|
+
updatedAt: new Date().toISOString(),
|
|
97
|
+
};
|
|
98
|
+
writeTextAtomic(path.join(roots.setsDir, `${RESIDENT_SLUG}.json`), JSON.stringify(doc, null, 2) + '\n');
|
|
99
|
+
return doc;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 名字存在性(库 + 全局层;项目层由 T4 的 resolveSkillTargets 按项目补全)。 */
|
|
103
|
+
function skillExists(roots, name) {
|
|
104
|
+
const dirs = [roots.libraryRoot, roots.userDshRoot, roots.userAgentsRoot, ...roots.customDirs];
|
|
105
|
+
for (const d of dirs) {
|
|
106
|
+
for (const cand of [path.join(d, name, 'SKILL.md'), path.join(d, `${name}.md`)]) {
|
|
107
|
+
try { if (fs.statSync(cand).isFile()) return true; } catch {}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 生效名单 = 常驻 ∪ 集(§7.4 存在性检查在此给出 missing 警告)。 */
|
|
114
|
+
export function effectiveNames(roots, setSlug) {
|
|
115
|
+
const set = setSlug ? loadSet(roots, setSlug) : null;
|
|
116
|
+
const names = [...new Set([...loadResident(roots).skills, ...(set?.skills ?? [])])];
|
|
117
|
+
return { names, missing: names.filter((n) => !skillExists(roots, n)) };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** 从当前生效清单另存为(§5.4:第一次建集的主路径)。
|
|
121
|
+
* excludeResident(用户 2026-10-26):常驻 = 全局生效,不该进项目集合
|
|
122
|
+
* (否则另存后绑定会把全局技能再写一份进项目 .agents/skills)。 */
|
|
123
|
+
export function saveAsSet(roots, { name, names, excludeResident = false }) {
|
|
124
|
+
const slug = uniqueSlug(roots, slugify(name) || 'set');
|
|
125
|
+
let skills = names ?? [];
|
|
126
|
+
if (excludeResident) {
|
|
127
|
+
const resident = new Set(loadResident(roots).skills);
|
|
128
|
+
skills = skills.filter((n) => !resident.has(n));
|
|
129
|
+
}
|
|
130
|
+
return saveSet(roots, { slug, name, description: '', skills });
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 导出 = 名字列表 + 可选来源 pin(§5.6)。 */
|
|
134
|
+
export function exportSet(roots, slug) {
|
|
135
|
+
const set = loadSet(roots, slug);
|
|
136
|
+
if (!set) throw new Error(`技能集不存在: ${slug}`);
|
|
137
|
+
const pins = {};
|
|
138
|
+
for (const n of set.skills) {
|
|
139
|
+
const mf = readJson(path.join(roots.libraryRoot, n, '.manifest.json'));
|
|
140
|
+
if (mf && mf.source && mf.source !== 'unknown' && mf.source !== 'placeholder') pins[n] = { source: mf.source, commit: mf.commit };
|
|
141
|
+
}
|
|
142
|
+
return { sets: [{ slug: set.slug, name: set.name, description: set.description ?? '', skills: set.skills, ...(Object.keys(pins).length ? { pins } : {}) }] };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ---------- 导入(§5.6:预览 → 三选一「按 pin 安装 / 忽略 / 先占位」,插件不自动联网) ----------
|
|
146
|
+
|
|
147
|
+
/** pin 归一:无 source、source=unknown 或 placeholder 一律视为无 pin(按 pin 安装按钮随之禁用,评审 M2)。 */
|
|
148
|
+
function pinOf(pins, name) {
|
|
149
|
+
const p = pins && typeof pins === 'object' ? pins[name] : null;
|
|
150
|
+
const source = typeof p?.source === 'string' ? p.source.trim() : '';
|
|
151
|
+
if (!source || source === 'unknown' || source === 'placeholder') return null;
|
|
152
|
+
return { source, commit: typeof p.commit === 'string' ? p.commit : null };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** payload 校验(用户粘的 JSON 不可信):一个坏集只报一条错、整集不参与写入,绝不半写。 */
|
|
156
|
+
function validatePayload(payload) {
|
|
157
|
+
if (!payload || !Array.isArray(payload.sets) || !payload.sets.length)
|
|
158
|
+
return { errors: ['payload 须为 { sets: [{ name, skills, pins? }] }'], items: [] };
|
|
159
|
+
const errors = [];
|
|
160
|
+
const items = [];
|
|
161
|
+
for (const item of payload.sets) {
|
|
162
|
+
const label = item?.name ?? item?.slug ?? '(无名)';
|
|
163
|
+
if (!item || typeof item !== 'object' || !String(item.name ?? '').trim()) { errors.push(`技能集缺少显示名:${JSON.stringify(label)}`); continue; }
|
|
164
|
+
if (!Array.isArray(item.skills)) { errors.push(`技能集「${label}」的 skills 须为数组`); continue; }
|
|
165
|
+
const bad = item.skills.filter((n) => typeof n !== 'string' || !SKILL_NAME_RE.test(n));
|
|
166
|
+
if (bad.length) { errors.push(`技能集「${label}」含非法技能名:${bad.join('、')}`); continue; }
|
|
167
|
+
items.push(item);
|
|
168
|
+
}
|
|
169
|
+
return { errors, items };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** 只读预览:本机上哪些技能缺、有没有 pin 可装、显示名会不会撞车。 */
|
|
173
|
+
export function importPreview(roots, payload) {
|
|
174
|
+
const { errors, items } = validatePayload(payload);
|
|
175
|
+
const known = listSets(roots);
|
|
176
|
+
const out = items.map((item) => {
|
|
177
|
+
const skills = [...new Set(item.skills)];
|
|
178
|
+
return {
|
|
179
|
+
name: String(item.name).trim(),
|
|
180
|
+
slug: uniqueSlug(roots, slugify(item.slug || item.name) || 'set'),
|
|
181
|
+
skills,
|
|
182
|
+
conflict: known.some((s) => s.name === String(item.name).trim()),
|
|
183
|
+
missing: skills.filter((n) => !skillExists(roots, n)).map((n) => ({ name: n, pin: pinOf(item.pins, n) })),
|
|
184
|
+
};
|
|
185
|
+
});
|
|
186
|
+
return { items: out, errors };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 占位技能体(§5.6「先占位」):让名字先存在、集不悬空,manifest 标 source=placeholder。 */
|
|
190
|
+
function makePlaceholder(roots, name) {
|
|
191
|
+
const dir = path.join(roots.libraryRoot, name);
|
|
192
|
+
const md = path.join(dir, 'SKILL.md');
|
|
193
|
+
if (fs.existsSync(md)) return false; // 已有技能体就不覆盖(空壳目录仍补写,评审 M3)
|
|
194
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
195
|
+
writeTextAtomic(md,
|
|
196
|
+
`---\nname: ${name}\ndescription: 占位:导入时选「先占位」,技能体尚未安装\n---\n\n# ${name}\n\n占位技能:技能体尚未安装。装上真身后请删除本目录(或从 GitHub 安装覆盖)。\n`);
|
|
197
|
+
writeSkillManifest(dir, { source: 'placeholder' });
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* 落盘导入:`choices[技能名] = 'install' | 'placeholder' | 'ignore'`,缺省 ignore
|
|
203
|
+
* (插件不自动联网安装——§5.6 硬约束);install 由调用方注入(host 走同一条稀疏拉取路径)。
|
|
204
|
+
*/
|
|
205
|
+
export async function importApply(roots, payload, { choices = {}, install = null } = {}) {
|
|
206
|
+
const { errors, items } = validatePayload(payload);
|
|
207
|
+
const created = [], nameConflicts = [], installed = [], placeholders = [], ignored = [], warnings = [];
|
|
208
|
+
for (const item of items) {
|
|
209
|
+
const name = String(item.name).trim();
|
|
210
|
+
const exists = listSets(roots).find((s) => s.name === name);
|
|
211
|
+
if (exists) { nameConflicts.push({ name, slug: exists.slug }); continue; } // 显示名冲突不覆盖(§5.10)
|
|
212
|
+
const slug = uniqueSlug(roots, slugify(item.slug || name) || 'set');
|
|
213
|
+
const skills = [...new Set(item.skills)];
|
|
214
|
+
saveSet(roots, { slug, name, description: typeof item.description === 'string' ? item.description : '', skills });
|
|
215
|
+
created.push({ slug, name });
|
|
216
|
+
for (const n of skills) {
|
|
217
|
+
if (skillExists(roots, n)) continue;
|
|
218
|
+
const choice = choices[n] ?? 'ignore';
|
|
219
|
+
if (choice === 'install') {
|
|
220
|
+
const pin = pinOf(item.pins, n);
|
|
221
|
+
if (!pin) { warnings.push(`${n}: 无来源 pin,无法按 pin 安装(改判忽略)`); ignored.push(n); continue; }
|
|
222
|
+
if (!install) { warnings.push(`${n}: 本环境无安装通道(改判忽略)`); ignored.push(n); continue; }
|
|
223
|
+
try { await install(n, pin); installed.push(n); }
|
|
224
|
+
catch (e) { warnings.push(`${n}: 按 pin 安装失败(${e?.message ?? e})`); ignored.push(n); }
|
|
225
|
+
} else if (choice === 'placeholder') {
|
|
226
|
+
try {
|
|
227
|
+
if (makePlaceholder(roots, n)) placeholders.push(n);
|
|
228
|
+
else warnings.push(`${n}: 库内已有 SKILL.md,占位未写(保留现有技能体)`);
|
|
229
|
+
} catch (e) { warnings.push(`${n}: 占位失败(${e?.message ?? e})`); }
|
|
230
|
+
} else ignored.push(n);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return { created, nameConflicts, installed, placeholders, ignored, warnings, errors };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** 导入:显示名冲突不覆盖;缺失技能只列清单,插件不自动联网安装(§5.6)。 */
|
|
237
|
+
export function importSets(roots, payload) {
|
|
238
|
+
const created = [];
|
|
239
|
+
const nameConflicts = [];
|
|
240
|
+
const missingSkills = [];
|
|
241
|
+
for (const item of payload?.sets ?? []) {
|
|
242
|
+
const exists = listSets(roots).find((s) => s.name === item.name);
|
|
243
|
+
if (exists) { nameConflicts.push({ name: item.name, slug: exists.slug }); continue; }
|
|
244
|
+
const slug = uniqueSlug(roots, slugify(item.slug || item.name) || 'set');
|
|
245
|
+
saveSet(roots, { slug, name: item.name, description: item.description ?? '', skills: item.skills ?? [] });
|
|
246
|
+
created.push({ slug, name: item.name });
|
|
247
|
+
for (const n of item.skills ?? []) if (!skillExists(roots, n) && !missingSkills.includes(n)) missingSkills.push(n);
|
|
248
|
+
}
|
|
249
|
+
return { created, nameConflicts, missingSkills };
|
|
250
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 技能来源规格(§8.3 格式,仿 dsh-skills-marketplace「仓库+分支+稀疏路径」)。
|
|
3
|
+
* 独立叶子模块:github(拉取)与 manifest(认领来源)都要解析来源,放这里避免 ESM 环。
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* owner/repo[@ref][/subpath] → {owner, repo, ref|null, subpath|null};非法 throw 业务错。
|
|
8
|
+
* 容忍三种粘贴形态(都是真实用户输入,用户报告 2026-10-26):整条 `https://github.com/…` 地址、
|
|
9
|
+
* clone 地址尾部的 `.git`、网页地址路由残留 `tree/<ref>/`(或 `blob/<ref>/`——无显式 @ref 时当 ref)。
|
|
10
|
+
*/
|
|
11
|
+
export function parseRepoSpec(spec) {
|
|
12
|
+
if (typeof spec !== 'string' || !spec.trim()) throw new Error('技能来源须为非空字符串');
|
|
13
|
+
const rest = spec.trim().replace(/^(https?:\/\/(?:www\.)?github\.com\/|github\.com\/)/, '');
|
|
14
|
+
const at = rest.indexOf('@');
|
|
15
|
+
const repoPart = at >= 0 ? rest.slice(0, at) : rest;
|
|
16
|
+
const refPart = at >= 0 ? rest.slice(at + 1) : null;
|
|
17
|
+
const segs = repoPart.split('/').filter(Boolean);
|
|
18
|
+
if (segs.length < 2) throw new Error(`技能来源格式错误 "${spec}":期望 owner/repo[@ref][/subpath]`);
|
|
19
|
+
const [owner, rawRepo] = segs;
|
|
20
|
+
// 尾部 `.git` 是 clone 地址的后缀,不是仓库名(GitHub 网页地址不带它):不剥就拼出
|
|
21
|
+
// `owner/repo.git.git` → 远端「Repository not found」(用户报告 2026-10-26:
|
|
22
|
+
// manifest 存了 github:vercel-labs/skills.git,库「检查更新」exit 128)
|
|
23
|
+
const repo = rawRepo.length > 4 && rawRepo.endsWith('.git') ? rawRepo.slice(0, -4) : rawRepo;
|
|
24
|
+
let subpath = segs.length > 2 ? segs.slice(2).join('/') : null;
|
|
25
|
+
// 浏览器地址的残留路由段 owner/repo/{tree|blob}/<ref>/<path>:GitHub 网页地址就是这个形状,
|
|
26
|
+
// 粘贴它是常态(用户报告 2026-10-26:diagram-design、ask-matt 的认领来源都粘成
|
|
27
|
+
// …/tree/main/skills、…/blob/main/skills/engineering → tree/main 被当成稀疏路径 →
|
|
28
|
+
// 稀疏检出空目录 → 检查更新报「上游不含技能」)。仅在没写显式 @ref 时认它,不与 @ 语法打架。
|
|
29
|
+
let webRef = null;
|
|
30
|
+
if (refPart === null && subpath) {
|
|
31
|
+
const ps = subpath.split('/');
|
|
32
|
+
if ((ps[0] === 'tree' || ps[0] === 'blob') && ps.length >= 2) { webRef = ps[1] || null; subpath = ps.slice(2).join('/') || null; }
|
|
33
|
+
}
|
|
34
|
+
if (refPart === null) return { owner, repo, ref: webRef, subpath };
|
|
35
|
+
const rs = refPart.split('/');
|
|
36
|
+
const ref = rs[0];
|
|
37
|
+
if (!ref) throw new Error(`技能来源格式错误 "${spec}":ref 为空`);
|
|
38
|
+
const tail = rs.slice(1).join('/');
|
|
39
|
+
if (subpath && tail) throw new Error(`技能来源格式错误 "${spec}":@ 前后不得同时带路径`);
|
|
40
|
+
if (!subpath) subpath = tail || null;
|
|
41
|
+
return { owner, repo, ref, subpath };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 来源归一(P2 单一口径):`github:` 前缀写法(manifest 规范形)、`github.com/…`、
|
|
46
|
+
* `https://github.com/…` 与裸 `owner/repo[/subpath]` 一律解析后写回规范形
|
|
47
|
+
* `github:owner/repo[/subpath]`(@ref 丢弃——commit 另存于 manifest)。
|
|
48
|
+
* 认领来源(§8.1)与按 pin 安装(§5.6)都先过这里。
|
|
49
|
+
*/
|
|
50
|
+
/**
|
|
51
|
+
* 一次解析、两种口径同时出(评审 C1 修复):`canonical` 写 manifest / 参与比较,
|
|
52
|
+
* `spec` 直接喂 fetchRepo(owner 绝不能带 `github:` 前缀,否则拼出的 remote URL 必 404)。
|
|
53
|
+
* 「归一化输出再当输入解析」= 双重前缀;解析只做一次即从根上断掉。
|
|
54
|
+
*/
|
|
55
|
+
export function resolveRepoSource(source) {
|
|
56
|
+
// parseRepoSpec 只认 URL/裸写法,`github:` 前缀(manifest 规范形)在此剥掉
|
|
57
|
+
const spec = parseRepoSpec(String(source ?? '').trim().replace(/^github:/, ''));
|
|
58
|
+
const canonical = `github:${spec.owner}/${spec.repo}${spec.subpath ? `/${spec.subpath}` : ''}`;
|
|
59
|
+
return { canonical, spec: { owner: spec.owner, repo: spec.repo, ref: null, subpath: spec.subpath } };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function normalizeRepoSource(source) {
|
|
63
|
+
return resolveRepoSource(source).canonical;
|
|
64
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 状态存储(§11):首选 ctx.storageDomain 自声明(探针已证可用),
|
|
3
|
+
* 失败回退 `<dshHome>/skill-set-manager/<table>/<key>.json`。
|
|
4
|
+
* 两者暴露同一 StateStore 接口 {get,put,delete,keys},core 其余部分不感知差异。
|
|
5
|
+
* key 必须 path-safe:项目键用会话目录同款编码(--C-AI-...--),天然满足 [a-zA-Z0-9_-]+。
|
|
6
|
+
*/
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
|
|
10
|
+
export const DOMAIN_NAME = 'skill_set_manager'; // 下划线:UNIT_NAME_RE 拒绝连字符(探针取证)
|
|
11
|
+
export const KEY_RE = /^[a-zA-Z0-9_.-]+$/; // 点允许:projectKey 可含点目录段(如 .dsh,无会话 state 路径活体实锤 2026-10-26);'.'/'..' 单独拒绝防穿越
|
|
12
|
+
|
|
13
|
+
export function projectKey(p) {
|
|
14
|
+
return '--' + String(p).replace(/[\\/:]+/g, '-') + '--';
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function makeFallbackStore(dir) {
|
|
18
|
+
const tableDir = (t) => {
|
|
19
|
+
if (!/^[a-z][a-z0-9_]*$/.test(t)) throw new Error(`非法表名: ${t}`);
|
|
20
|
+
return path.join(dir, t);
|
|
21
|
+
};
|
|
22
|
+
const file = (t, k) => {
|
|
23
|
+
if (!KEY_RE.test(k) || k === '.' || k === '..') throw new Error(`非法记录 key(须 path-safe): ${k}`);
|
|
24
|
+
return path.join(tableDir(t), `${k}.json`);
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
kind: 'fallback',
|
|
28
|
+
async get(t, k) {
|
|
29
|
+
try { return JSON.parse(fs.readFileSync(file(t, k), 'utf8')); } catch (e) { if (e.code === 'ENOENT') return null; throw e; }
|
|
30
|
+
},
|
|
31
|
+
async put(t, k, v) {
|
|
32
|
+
fs.mkdirSync(tableDir(t), { recursive: true });
|
|
33
|
+
const tmp = file(t, k) + '.tmp';
|
|
34
|
+
fs.writeFileSync(tmp, JSON.stringify(v, null, 2) + '\n');
|
|
35
|
+
fs.renameSync(tmp, file(t, k)); // 半写不落正式文件
|
|
36
|
+
},
|
|
37
|
+
async delete(t, k) {
|
|
38
|
+
try { fs.unlinkSync(file(t, k)); return true; } catch (e) { if (e.code === 'ENOENT') return false; throw e; }
|
|
39
|
+
},
|
|
40
|
+
async keys(t) {
|
|
41
|
+
let names;
|
|
42
|
+
try { names = fs.readdirSync(tableDir(t)); } catch { return []; }
|
|
43
|
+
return names.filter((n) => n.endsWith('.json')).map((n) => n.slice(0, -5));
|
|
44
|
+
},
|
|
45
|
+
async close() {},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 打开 domain(tables: pending/undo/oplog),失败回退。
|
|
51
|
+
* @param ctx - 插件 Context(storageDomain 访问器)。
|
|
52
|
+
* @param fallbackDir - 回退目录根(生产传 roots.dshHome)。
|
|
53
|
+
*/
|
|
54
|
+
export async function openDomain(ctx, { fallbackDir } = {}) {
|
|
55
|
+
try {
|
|
56
|
+
const mod = await import('zod');
|
|
57
|
+
const z = mod.default ?? mod;
|
|
58
|
+
const domain = await ctx.storageDomain.open({
|
|
59
|
+
name: DOMAIN_NAME,
|
|
60
|
+
version: 1,
|
|
61
|
+
layout: 'per-record',
|
|
62
|
+
tables: {
|
|
63
|
+
pending: { valueSchema: z.object({ projectRoot: z.string(), setSlug: z.string().nullable(), sessionId: z.string().nullable().optional(), previousManaged: z.unknown(), added: z.array(z.string()), removed: z.array(z.string()) }) },
|
|
64
|
+
undo: { valueSchema: z.object({ projectRoot: z.string(), setSlug: z.string().nullable(), managed: z.unknown(), pushedAt: z.string() }) },
|
|
65
|
+
oplog: { valueSchema: z.object({ at: z.string(), kind: z.string(), detail: z.unknown() }) },
|
|
66
|
+
bindings: { valueSchema: z.object({ projectRoot: z.string() }) },
|
|
67
|
+
migration: { valueSchema: z.object({ moved: z.array(z.object({ name: z.string(), from: z.string(), to: z.string() })) }) },
|
|
68
|
+
// P3 新表(domain kind 也须在场:table() 只认白名单,活体复盘 2026-10-26)
|
|
69
|
+
translations: { valueSchema: z.record(z.object({ srcHash: z.string(), en: z.string().nullable().optional(), zh: z.string().nullable().optional(), status: z.string(), updatedAt: z.string().optional() })) },
|
|
70
|
+
migrate_agents: { valueSchema: z.object({ moved: z.array(z.object({ name: z.string(), from: z.string(), to: z.string(), claimed: z.boolean().optional() })) }) },
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
return {
|
|
74
|
+
kind: 'domain',
|
|
75
|
+
domain,
|
|
76
|
+
async get(t, k) { return domain.table(t).get(k) ?? null; },
|
|
77
|
+
async put(t, k, v) { return domain.table(t).put(k, v); },
|
|
78
|
+
async delete(t, k) { return domain.table(t).delete(k); },
|
|
79
|
+
async keys(t) { return [...domain.table(t).keys()]; },
|
|
80
|
+
async close() { return domain.close(); },
|
|
81
|
+
};
|
|
82
|
+
} catch (e) {
|
|
83
|
+
ctx?.logger?.warn?.(`skill-set-manager: storageDomain.open 失败(${e?.message}),回退 JSON 目录 ${fallbackDir}`);
|
|
84
|
+
if (!fallbackDir) throw e;
|
|
85
|
+
return makeFallbackStore(path.join(fallbackDir, 'skill-set-manager'));
|
|
86
|
+
}
|
|
87
|
+
}
|