skillmkt 0.0.0-stage → 0.1.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.
Files changed (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +213 -2
  3. package/client/bin/skillmkt.js +84 -0
  4. package/client/commands/audit.js +34 -0
  5. package/client/commands/build.js +61 -0
  6. package/client/commands/config.js +34 -0
  7. package/client/commands/conflicts.js +14 -0
  8. package/client/commands/decide.js +19 -0
  9. package/client/commands/diff.js +52 -0
  10. package/client/commands/doctor.js +109 -0
  11. package/client/commands/download.js +35 -0
  12. package/client/commands/init.js +82 -0
  13. package/client/commands/install.js +169 -0
  14. package/client/commands/list.js +56 -0
  15. package/client/commands/merge.js +49 -0
  16. package/client/commands/outdated.js +34 -0
  17. package/client/commands/registry.js +42 -0
  18. package/client/commands/remove.js +48 -0
  19. package/client/commands/resolve.js +76 -0
  20. package/client/commands/rollback.js +30 -0
  21. package/client/commands/search.js +46 -0
  22. package/client/commands/serve.js +99 -0
  23. package/client/commands/show.js +52 -0
  24. package/client/commands/sync.js +54 -0
  25. package/client/commands/targets.js +75 -0
  26. package/client/commands/update.js +39 -0
  27. package/client/commands/upgrade.js +75 -0
  28. package/client/lib/ai.js +67 -0
  29. package/client/lib/audit.js +87 -0
  30. package/client/lib/autoarb.js +26 -0
  31. package/client/lib/conflicts.js +65 -0
  32. package/client/lib/ctx.js +68 -0
  33. package/client/lib/daemon.js +47 -0
  34. package/client/lib/dashboard.js +29 -0
  35. package/client/lib/decide.js +43 -0
  36. package/client/lib/evidence.js +56 -0
  37. package/client/lib/githash.js +36 -0
  38. package/client/lib/hub.js +125 -0
  39. package/client/lib/llm.js +85 -0
  40. package/client/lib/package.js +73 -0
  41. package/client/lib/project.js +97 -0
  42. package/client/lib/prompt.js +22 -0
  43. package/client/lib/ref.js +37 -0
  44. package/client/lib/registries/github.js +106 -0
  45. package/client/lib/registries/index.js +37 -0
  46. package/client/lib/registries/rfc.js +42 -0
  47. package/client/lib/registries/skillssh.js +59 -0
  48. package/client/lib/render.js +53 -0
  49. package/client/lib/rules.js +36 -0
  50. package/client/lib/scanner.js +158 -0
  51. package/client/lib/state.js +50 -0
  52. package/client/lib/yamlls.js +14 -0
  53. package/client/public/app.js +63 -0
  54. package/client/public/index.html +21 -0
  55. package/package.json +44 -4
  56. package/pipeline/lib/env.js +40 -0
  57. package/pipeline/lib/gh.js +53 -0
  58. package/pipeline/lib/llm.js +108 -0
  59. package/pipeline/lib/util.js +103 -0
  60. package/skill/SKILL.md +270 -0
  61. package/skill/references/a11y.md +82 -0
  62. package/skill/references/code.md +415 -0
  63. package/skill/references/color.md +84 -0
  64. package/skill/references/copy.md +197 -0
  65. package/skill/references/imagery.md +157 -0
  66. package/skill/references/layout.md +404 -0
  67. package/skill/references/motion.md +104 -0
  68. package/skill/references/process.md +303 -0
  69. package/skill/references/type.md +84 -0
  70. package/skill/rules-manifest.yml +13092 -0
@@ -0,0 +1,35 @@
1
+ // download — apt download 语义:fetch+审核→cache/ 不装不投影;install 命中缓存复用
2
+ import path from 'node:path';
3
+ import { parseRef } from '../lib/ref.js';
4
+ import { fetchRef } from '../lib/registries/index.js';
5
+ import { auditDir, writeScan } from '../lib/audit.js';
6
+ import { readSkillDir, copyDir, rmDir } from '../lib/package.js';
7
+ import { ensureHub, cacheDir, quarantinePath } from '../lib/hub.js';
8
+ import { ok, warn, fail } from '../lib/render.js';
9
+
10
+ export async function run(ctx) {
11
+ const input = ctx.args[0];
12
+ if (!input) { fail('usage: skillmkt download <ref>'); return 1; }
13
+ const ref = parseRef(input, ctx.flags.raw, { harnesses: ctx.harnesses, registries: ctx.config.registries });
14
+ ensureHub(ctx.hub);
15
+
16
+ const got = ref.kind === 'local' || ref.kind === 'harness'
17
+ ? { dir: ref.absPath, provenance: { registry: 'local', adopted_from: ref.absPath }, sha: null }
18
+ : await fetchRef(ref, ctx);
19
+ const pkg = readSkillDir(got.dir);
20
+ if (!pkg) { fail(`不是合法 skill: ${input}`); return 1; }
21
+ const audit = auditDir(got.dir, { strip: !ctx.flags.raw.keepScripts });
22
+ if (audit.verdict === 'malicious') {
23
+ if (!ctx.flags.dryRun) { rmDir(quarantinePath(ctx.hub, pkg.name)); copyDir(got.dir, quarantinePath(ctx.hub, pkg.name)); writeScan(ctx.hub, pkg.name, audit); }
24
+ warn(`malicious — quarantined: ${pkg.name}`);
25
+ return 2;
26
+ }
27
+ const dest = cacheDir(ctx.hub, pkg.name, got.sha || pkg.contentHash);
28
+ if (!ctx.flags.dryRun) {
29
+ rmDir(dest);
30
+ copyDir(got.dir, dest);
31
+ writeScan(ctx.hub, pkg.name, audit);
32
+ }
33
+ ok(`${ctx.flags.dryRun ? '[dry-run] ' : ''}downloaded ${pkg.name} → cache (${pkg.fileCount} files, audit:${audit.verdict})`);
34
+ return 0;
35
+ }
@@ -0,0 +1,82 @@
1
+ // init — 交互式初始化:形态选择(Web/终端)→ LLM 探测→选模型→冒烟→写配置→harness 默认目标
2
+ import fs from 'node:fs';
3
+ import { ensureHub, writeConfig, readConfig } from '../lib/hub.js';
4
+ import { probeEndpoints, chat } from '../lib/llm.js';
5
+ import { choose, confirm } from '../lib/prompt.js';
6
+ import { ok, warn, fail, info } from '../lib/render.js';
7
+
8
+ export async function run(ctx) {
9
+ ensureHub(ctx.hub);
10
+ if (!ctx.tty) {
11
+ info('non-interactive: hub 骨架已建,LLM 配置请用 skillmkt config set llm.*');
12
+ return 0;
13
+ }
14
+
15
+ // 首问:初始化形态(写 ui.enabled——§3.11 自动接管与裸跑形态听它的)
16
+ const mode = ctx.flags.ui === 'force' ? 'web' : ctx.flags.ui === 'off' ? 'cli'
17
+ : (await choose('初始化方式?', [
18
+ { label: 'Web 面板(推荐——探测结果、模型列表、harness 勾选可视化)', v: 'web' },
19
+ { label: '终端向导(纯键盘,SSH/无浏览器环境)', v: 'cli' },
20
+ ])).v;
21
+
22
+ const raw = readConfig(ctx.hub)._raw;
23
+ raw.ui = { ...(raw.ui || {}), enabled: mode === 'web' ? 'always' : 'auto' };
24
+
25
+ if (mode === 'web') {
26
+ // M5 daemon 就绪前:标记偏好,走终端向导完成本次
27
+ warn('Web 初始化依赖 daemon(M5 提供)——本次先用终端向导完成,偏好已记录');
28
+ }
29
+
30
+ // LLM 端点探测(只在用户进入配置步骤时探测——铁律)
31
+ info('探测本地 LLM 服务…');
32
+ const found = await probeEndpoints();
33
+ let base_url = null, model = null;
34
+
35
+ if (found.length) {
36
+ const opts = [
37
+ ...found.flatMap((f) => f.models.slice(0, 6).map((m) => ({
38
+ label: `${f.name}:${f.port} — ${m}`, v: { base_url: f.base_url, model: m },
39
+ }))),
40
+ { label: '手动输入端点', v: 'manual' },
41
+ { label: '跳过(确定性功能照常用)', v: 'skip' },
42
+ ];
43
+ const sel = await choose('选择模型端点:', opts);
44
+ if (sel.v === 'manual') {
45
+ // 手动输入交给 config set 提示
46
+ info('→ skillmkt config set llm.base_url <url> && skillmkt config set llm.model <id>');
47
+ } else if (sel.v !== 'skip') {
48
+ ({ base_url, model } = sel.v);
49
+ }
50
+ } else {
51
+ info('未发现本地 LLM 服务(8001/11434/1234/8000/8080/1337/5000)');
52
+ info('→ 手动:skillmkt config set llm.base_url http://host:port/v1');
53
+ }
54
+
55
+ // API key 环境变量引用(不存真值)
56
+ if (base_url) {
57
+ const keyEnv = await choose('API key 来源?', [
58
+ { label: '无需 key(本地端点常见)', v: null },
59
+ { label: 'SKILLMKT_API_KEY', v: 'env:SKILLMKT_API_KEY' },
60
+ { label: 'OMLX_API_KEY', v: 'env:OMLX_API_KEY' },
61
+ ]);
62
+ raw.llm = { base_url, model, ...(keyEnv.v ? { api_key: keyEnv.v } : {}), concurrency: 2, timeout_ms: 60000 };
63
+
64
+ // 冒烟:真实 chat 调用
65
+ try {
66
+ const probe = { base_url, model, api_key: keyEnv.v ? process.env[keyEnv.v.slice(4)] ?? '' : '', timeout_ms: 15000 };
67
+ const reply = await chat(probe, { user: 'Reply with exactly: OK', maxTokens: 8 });
68
+ ok(`llm smoke: ${reply.trim().slice(0, 40) || '(empty reply)'}`);
69
+ } catch (e) {
70
+ warn(`llm smoke failed: ${e.message}(配置已写入,功能将降级)`);
71
+ }
72
+ }
73
+
74
+ // harness 默认目标 = installed 态
75
+ const installed = ctx.harnesses.filter((h) => h.state === 'installed' && !h.detectOnly).map((h) => h.id);
76
+ raw.default_targets = [...new Set([...(raw.default_targets || []), ...installed])];
77
+ writeConfig(ctx.hub, raw);
78
+
79
+ ok(`init done — default_targets: ${raw.default_targets.join(', ') || '(无 installed harness,装好后 targets add)'}`);
80
+ info(`llm: ${model ? `${model} @ ${base_url}` : '未配置(skillmkt init 随时重跑)'}`);
81
+ return 0;
82
+ }
@@ -0,0 +1,169 @@
1
+ // install (alias: i, add) — fetch→审核闸门→strip→hub→投影→lock;harness 路径=收编
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { execFileSync } from 'node:child_process';
5
+ import { ensureHub, registerSkill, updateLock, quarantinePath, cacheDir } from '../lib/hub.js';
6
+ import { parseRef } from '../lib/ref.js';
7
+ import { fetchRef } from '../lib/registries/index.js';
8
+ import { auditDir, stripFilter, writeScan } from '../lib/audit.js';
9
+ import { readSkillDir, copyDir, rmDir, walk, treeHash } from '../lib/package.js';
10
+ import { projectSkill, resolveTargets } from '../lib/project.js';
11
+ import { cacheLookup } from '../lib/state.js';
12
+ import { confirm } from '../lib/prompt.js';
13
+ import { ok, warn, fail, info } from '../lib/render.js';
14
+
15
+ // 来源取证:.git remote → skills-lock.json → .market-skills.json → frontmatter
16
+ function recoverProvenance(dir, meta) {
17
+ try {
18
+ const remote = execFileSync('git', ['-C', dir, 'config', '--get', 'remote.origin.url'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
19
+ const m = remote.match(/github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?$/);
20
+ if (m) {
21
+ const sha = execFileSync('git', ['-C', dir, 'rev-parse', 'HEAD'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
22
+ return { registry: 'github', ref: `${m[1]}/${m[2]}`, pin: sha };
23
+ }
24
+ } catch { /* no .git */ }
25
+ for (const f of ['skills-lock.json', '.market-skills.json']) {
26
+ try {
27
+ const lock = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'));
28
+ const hit = lock.skills?.[path.basename(dir)] || lock[path.basename(dir)] || Object.values(lock.skills || lock)[0];
29
+ const src = hit?.source || hit?.repo || hit?.id;
30
+ if (src && src.includes('/')) {
31
+ const [owner, repo, ...rest] = src.replace(/^https?:\/\/github\.com\//, '').split('/');
32
+ return { registry: 'github', ref: `${owner}/${repo}`, path: rest.join('/') || null, pin: hit?.ref || hit?.version || null };
33
+ }
34
+ } catch { /* next file */ }
35
+ }
36
+ const home = meta?.homepage || meta?.repository;
37
+ if (home?.includes('github.com')) {
38
+ const m = home.match(/github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git|\/|$)/);
39
+ if (m) return { registry: 'github', ref: `${m[1]}/${m[2]}`, pin: null };
40
+ }
41
+ return null;
42
+ }
43
+
44
+ // copy 目录但排除 stripped 相对路径
45
+ function copyFiltered(src, dst, keep) {
46
+ fs.mkdirSync(dst, { recursive: true });
47
+ for (const p of walk(src)) {
48
+ const rel = path.relative(src, p).split(path.sep).join('/');
49
+ if (!keep(rel)) continue;
50
+ const d = path.join(dst, rel);
51
+ fs.mkdirSync(path.dirname(d), { recursive: true });
52
+ fs.copyFileSync(p, d);
53
+ }
54
+ }
55
+
56
+ export async function run(ctx) {
57
+ const input = ctx.args[0];
58
+ if (!input) { fail('usage: skillmkt install <ref|path|owner/repo>'); return 1; }
59
+ const flags = ctx.flags.raw;
60
+
61
+ const ref = parseRef(input, flags, { harnesses: ctx.harnesses, registries: ctx.config.registries });
62
+ if (!ctx.flags.dryRun) ensureHub(ctx.hub);
63
+
64
+ // ① 取得源目录
65
+ let srcDir, provenance, tmp = null, adopted = null;
66
+ if (ref.kind === 'local' || ref.kind === 'harness') {
67
+ srcDir = ref.absPath;
68
+ if (ref.kind === 'harness') {
69
+ adopted = { from: ref.absPath, harnessId: ref.harnessId };
70
+ provenance = recoverProvenance(ref.absPath, readSkillDir(ref.absPath)?.meta || {});
71
+ }
72
+ provenance = provenance || { registry: ref.kind === 'harness' ? 'adopted' : 'local', adopted_from: ref.absPath };
73
+ } else {
74
+ // download 缓存命中:cache/<name>-*/ 存在即复用不重复拉
75
+ const cached = ref.kind === 'named' ? cacheLookup(ctx.hub, ref.name) : null;
76
+ if (cached) {
77
+ info(`cache hit: ${cached}`);
78
+ srcDir = cached;
79
+ provenance = { registry: 'cache', adopted_from: cached };
80
+ } else {
81
+ info(`fetching ${input} …`);
82
+ const got = await fetchRef(ref, ctx);
83
+ srcDir = got.dir; tmp = got.tmp;
84
+ provenance = got.provenance;
85
+ }
86
+ }
87
+
88
+ const pkg = readSkillDir(srcDir);
89
+ if (!pkg) { fail(`不是合法 skill(缺 SKILL.md): ${srcDir}`); return 1; }
90
+ const name = pkg.name;
91
+
92
+ // ② 审核闸门
93
+ const audit = auditDir(srcDir, { strip: !flags.keepScripts });
94
+ if (audit.verdict === 'malicious') {
95
+ if (!ctx.flags.dryRun) {
96
+ rmDir(quarantinePath(ctx.hub, name));
97
+ copyDir(srcDir, quarantinePath(ctx.hub, name));
98
+ writeScan(ctx.hub, name, audit);
99
+ }
100
+ fail(`malicious — quarantined: ${name}(${audit.findings.length} findings)`);
101
+ return 2;
102
+ }
103
+ if (audit.verdict === 'suspicious' && ctx.config.policy !== 'permissive') {
104
+ warn(`suspicious: ${audit.findings.length} findings${audit.stripped.length ? `, stripping ${audit.stripped.length} files` : ''}`);
105
+ audit.findings.slice(0, 5).forEach((f) => info(`${f.rule} ${f.file}:${f.line} — ${f.excerpt.slice(0, 80)}`));
106
+ // --yes 不放大 suspicious(安全默认);strict 直接拒
107
+ const proceed = ctx.config.policy === 'strict' ? false : await confirm(`继续安装 ${name}?`, { defaultYes: false });
108
+ if (!proceed) { fail('install aborted'); return 2; }
109
+ }
110
+
111
+ // ③ 落 hub(stripped 过滤)
112
+ const dest = path.join(ctx.hub, 'skills', name);
113
+ const freshHash = () => treeHash(dest);
114
+ const alreadyManaged = ctx.library.skills?.[name] && fs.existsSync(dest);
115
+ if (alreadyManaged) {
116
+ const keep = stripFilter(audit.stripped);
117
+ // 与现有 hub 副本内容对比:相同则跳过 copy
118
+ const srcFilteredHash = (() => { const t = path.join(ctx.hub, 'cache', `__probe_${process.pid}`); rmDir(t); copyFiltered(srcDir, t, keep); const h = treeHash(t); rmDir(t); return h; })();
119
+ if (srcFilteredHash !== freshHash() && !flags.force) {
120
+ warn(`${name} 已受管且内容不同——--force 覆盖,或 upgrade 流程`);
121
+ return 1;
122
+ }
123
+ }
124
+ if (!ctx.flags.dryRun) {
125
+ rmDir(dest);
126
+ copyFiltered(srcDir, dest, stripFilter(flags.keepScripts ? [] : audit.stripped));
127
+ writeScan(ctx.hub, name, audit);
128
+ }
129
+
130
+ // ④ 投影目标:收编默认仅原 harness;其余 --to/--target/default_targets(空则全部 installed)
131
+ const targets = adopted && !flags.target
132
+ ? [{ id: adopted.harnessId, dir: path.dirname(adopted.from), mode: 'copy' }]
133
+ : resolveTargets(ctx, { allowAdopted: ctx.harnesses.filter((h) => h.state === 'installed').map((h) => h.id) });
134
+
135
+ // ⑤ 投影 + lock
136
+ const results = [];
137
+ const lockTargets = {};
138
+ for (const t of targets) {
139
+ const lockT = ctx.lock.skills?.[name]?.targets?.[t.id];
140
+ const r = projectSkill(dest, name, t.dir, {
141
+ mode: t.mode, dryRun: ctx.flags.dryRun, force: !!flags.force,
142
+ lockEntry: lockT ? { hash: lockT.hash } : null,
143
+ });
144
+ results.push({ ...r, id: t.id });
145
+ if (r.action === 'conflict') warn(`${name} → ${t.dir}: ${r.detail}`);
146
+ else lockTargets[t.id] = { hash: r.hash, projected_at: new Date().toISOString(), mode: r.mode };
147
+ }
148
+
149
+ if (!ctx.flags.dryRun) {
150
+ registerSkill(ctx.hub, name, {
151
+ source: {
152
+ ...provenance,
153
+ ...(adopted ? { registry: provenance?.registry === 'github' ? 'github' : 'adopted', adopted_from: adopted.from, adopted_at: new Date().toISOString() } : {}),
154
+ },
155
+ version: pkg.version,
156
+ installed_at: new Date().toISOString(),
157
+ targets: Object.keys(lockTargets),
158
+ scope: flags.scope === 'project' ? 'project' : 'global',
159
+ project_root: flags.scope === 'project' ? ctx.project?.root ?? null : null,
160
+ audit: audit.stripped.length ? 'stripped' : audit.verdict === 'suspicious' ? 'suspicious' : 'clean',
161
+ transport: Object.fromEntries(Object.keys(lockTargets).map((k) => [k, lockTargets[k].mode])),
162
+ });
163
+ if (Object.keys(lockTargets).length) updateLock(ctx.hub, name, treeHash(dest), lockTargets);
164
+ }
165
+
166
+ const mark = results.map((r) => `${r.id.split(':')[0]}(${r.action === 'copied' ? 'copy' : r.action === 'linked' ? 'sym' : r.action})`).join(' ');
167
+ ok(`${ctx.flags.dryRun ? '[dry-run] ' : ''}installed ${name} → ${mark || 'hub only'} · audit:${audit.stripped.length ? 'stripped' : audit.verdict} · locked ${treeHash(dest).slice(7, 15)}`);
168
+ return 0;
169
+ }
@@ -0,0 +1,56 @@
1
+ // list (alias: ls) — 安装矩阵:skills×targets + external + pending 冲突数
2
+ import path from 'node:path';
3
+ import { table, out, info } from '../lib/render.js';
4
+ import { scanAll } from '../lib/scanner.js';
5
+ import { listYAML } from '../lib/yamlls.js';
6
+
7
+ export async function run(ctx) {
8
+ const { hub, library, harnesses, project } = ctx;
9
+ const skills = library.skills || {};
10
+ const rows = scanAll(hub, harnesses, library, project?.root);
11
+ const externals = rows.filter((r) => r.state === 'external');
12
+ const conflicts = listYAML(path.join(hub, 'conflicts'));
13
+ const pendingBySide = new Map();
14
+ for (const c of conflicts.filter((x) => x.status === 'pending')) {
15
+ for (const s of c.sides || []) pendingBySide.set(s.source, (pendingBySide.get(s.source) || 0) + 1);
16
+ }
17
+
18
+ // 列:name + 每个出现过为 target 的 harness + audit + conflicts + source
19
+ const allTargets = [...new Set(Object.values(skills).flatMap((s) => s.targets || []))];
20
+ const tableRows = Object.entries(skills).map(([name, s]) => {
21
+ const row = { name, version: s.version || '-', audit: s.audit || '-', conflicts: pendingBySide.get(name) || 0, source: s.source?.registry || '?' };
22
+ for (const t of allTargets) row[`t_${t}`] = (s.targets || []).includes(t) ? `●${(s.transport?.[t] || 'copy').slice(0, 4)}` : '—';
23
+ return row;
24
+ });
25
+ const cols = [
26
+ { key: 'name', title: 'skill' }, { key: 'version', title: 'ver' },
27
+ ...allTargets.map((t) => ({ key: `t_${t}`, title: t.slice(0, 8) })),
28
+ { key: 'audit', title: 'audit' }, { key: 'conflicts', title: 'conf' }, { key: 'source', title: 'src' },
29
+ ];
30
+
31
+ const extRows = externals.map((e) => ({ name: `◌${e.name}`, dir: e.targetDir || e.where, ver: e.version }));
32
+ const data = { managed: tableRows, external: extRows, targets: allTargets };
33
+
34
+ out(data, {
35
+ json: ctx.flags.json,
36
+ human: () => {
37
+ if (tableRows.length) table(tableRows, cols);
38
+ else info('(empty — skillmkt search / install 开始)');
39
+ if (extRows.length) {
40
+ info('');
41
+ info('external(未收编):');
42
+ for (const e of extRows) info(` ${e.name.padEnd(30)} ${e.dir}`);
43
+ info(`→ skillmkt install <path> 收编`);
44
+ }
45
+ if (ctx.project) {
46
+ const projRows = rows.filter((r) => r.where === 'project');
47
+ if (projRows.length) {
48
+ info('');
49
+ info(`project ${ctx.project.root}:`);
50
+ for (const r of projRows) info(` ${r.state === 'managed' ? '●' : '◌'} ${r.name} ${r.targetDir}`);
51
+ }
52
+ }
53
+ },
54
+ });
55
+ return 0;
56
+ }
@@ -0,0 +1,49 @@
1
+ // merge <a> <b> [more…] [--name n] — 抽规则→去重→检冲突→merged/rules.yml 中间态
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { extractRules } from '../lib/rules.js';
5
+ import { extractRulesLLM } from '../lib/ai.js';
6
+ import { detectConflicts } from '../lib/conflicts.js';
7
+ import { autoArbitrate } from '../lib/autoarb.js';
8
+ import { tokens, jaccard, writeYAML } from '../../pipeline/lib/util.js';
9
+ import { ok, warn, fail, info } from '../lib/render.js';
10
+
11
+ export const mergedDir = (hub) => path.join(hub, 'merged');
12
+
13
+ export async function run(ctx) {
14
+ const names = ctx.args.filter((a) => !a.startsWith('--'));
15
+ if (names.length < 2) { fail('usage: skillmkt merge <a> <b> [more…] [--name n]'); return 1; }
16
+ const outName = ctx.flags.raw.name || `merged-${names.length}skills`;
17
+
18
+ const useLlm = ctx.flags.raw.llm && ctx.llm;
19
+ const rules = [];
20
+ for (const name of names) {
21
+ const dir = path.join(ctx.hub, 'skills', name);
22
+ const f = path.join(dir, 'SKILL.md');
23
+ if (!fs.existsSync(f)) { fail(`未受管: ${name}`); return 1; }
24
+ let rs = null;
25
+ if (useLlm) {
26
+ try { rs = await extractRulesLLM(ctx.llm, fs.readFileSync(f, 'utf8'), name); } catch { /* 降级静态 */ }
27
+ }
28
+ rules.push(...(rs || extractRules(dir, name)));
29
+ }
30
+ // 去重(jaccard≥0.9 保留 first-seen)
31
+ const dedup = [];
32
+ for (const r of rules) {
33
+ const t = tokens(r.text);
34
+ if (dedup.some((d) => jaccard(tokens(d.text), t) >= 0.9)) continue;
35
+ dedup.push(r);
36
+ }
37
+ const news = detectConflicts(ctx.hub, dedup);
38
+ // --auto:仲裁直接吃确定项(fresh-context per conflict)
39
+ if (ctx.flags.raw.auto && ctx.llm && news.length) {
40
+ const r = await autoArbitrate(ctx.hub, ctx.llm, news, { onProgress: (c, x) => info(`${c.id}: ${x?.verdict ?? '?'}@${x?.confidence ?? '?'}`) });
41
+ info(`auto-arbiter: ${r.auto} 已决,${r.human} 留人`);
42
+ }
43
+ const dir = mergedDir(ctx.hub);
44
+ fs.mkdirSync(dir, { recursive: true });
45
+ writeYAML(path.join(dir, 'rules.yml'), { name: outName, sources: names, merged_at: new Date().toISOString(), rules: dedup });
46
+ ok(`merged: ${dedup.length} rules(原始 ${rules.length},去重 -${rules.length - dedup.length})· 新冲突 ${news.length}`);
47
+ if (news.length) info(`skillmkt conflicts 查看队列;decide/resolve 裁决后 build`);
48
+ return news.length ? 3 : 0;
49
+ }
@@ -0,0 +1,34 @@
1
+ // outdated — 离线对比 state/upstream.yml vs 本地,只读报告;有更新 exit4
2
+ import path from 'node:path';
3
+ import fs from 'node:fs';
4
+ import { readUpstream } from '../lib/state.js';
5
+ import { gitTreeHash } from '../lib/githash.js';
6
+ import { table, info, warn } from '../lib/render.js';
7
+
8
+ export async function run(ctx) {
9
+ const up = readUpstream(ctx.hub);
10
+ const rows = [];
11
+ let outdated = 0;
12
+ for (const [name, s] of Object.entries(ctx.library.skills || {})) {
13
+ const u = up.skills?.[name];
14
+ const localDir = path.join(ctx.hub, 'skills', name);
15
+ if (!u) {
16
+ rows.push({ name, status: s.source?.registry === 'adopted' || s.source?.registry === 'local' ? 'n/a (无上游)' : 'never checked — run update' });
17
+ continue;
18
+ }
19
+ const localTree = fs.existsSync(localDir) ? gitTreeHash(localDir) : null;
20
+ if (localTree && u.tree_hash && localTree !== u.tree_hash) {
21
+ outdated++;
22
+ rows.push({ name, status: `upstream changed (${u.ref?.slice(0, 6)}) — upgrade 应用` });
23
+ } else {
24
+ rows.push({ name, status: 'clean' });
25
+ }
26
+ }
27
+ if (ctx.flags.json) { console.log(JSON.stringify({ outdated, rows })); }
28
+ else {
29
+ if (rows.length) table(rows, [{ key: 'name', title: 'skill' }, { key: 'status', title: 'status' }]);
30
+ if (!Object.keys(up.skills || {}).length) warn('state/upstream.yml 为空——先跑 skillmkt update');
31
+ else info(`last refresh: ${up.refreshed_at ?? 'unknown'}(skillmkt update 刷新)`);
32
+ }
33
+ return outdated ? 4 : 0;
34
+ }
@@ -0,0 +1,42 @@
1
+ // registry — list / add --type <t> --url <u> [--token env:X] [--name n] / remove <name>
2
+ import { readConfig, writeConfig } from '../lib/hub.js';
3
+ import { table, ok, fail } from '../lib/render.js';
4
+
5
+ export async function run(ctx) {
6
+ const [sub, ...rest] = ctx.args;
7
+ const flags = ctx.flags.raw;
8
+ const raw = readConfig(ctx.hub)._raw;
9
+ raw.registries = raw.registries || [{ type: 'github', default: true }];
10
+
11
+ if (!sub || sub === 'list') {
12
+ if (ctx.flags.json) { console.log(JSON.stringify(raw.registries, null, 2)); return 0; }
13
+ table(raw.registries.map((r) => ({ type: r.type, name: r.name || '-', url: r.url || '-', default: r.default ? '●' : '', auth: r.token ? '●' : '' })),
14
+ [{ key: 'type', title: 'type' }, { key: 'name', title: 'name' }, { key: 'url', title: 'url' }, { key: 'default', title: 'def' }, { key: 'auth', title: 'auth' }]);
15
+ return 0;
16
+ }
17
+
18
+ if (sub === 'add') {
19
+ if (!flags.type) { fail('usage: registry add --type <github|rfc|clawhub|skillssh> [--url u] [--name n] [--token env:X]'); return 1; }
20
+ const entry = { type: flags.type };
21
+ if (flags.url) entry.url = flags.url;
22
+ if (flags.name) entry.name = flags.name;
23
+ if (flags.token) entry.token = flags.token.startsWith('env:') ? flags.token : `env:${flags.token}`;
24
+ raw.registries.push(entry);
25
+ writeConfig(ctx.hub, raw);
26
+ ok(`registry added: ${flags.type}${flags.url ? ` ${flags.url}` : ''}${flags.name ? ` (${flags.name})` : ''}`);
27
+ return 0;
28
+ }
29
+
30
+ if (sub === 'remove' || sub === 'rm') {
31
+ const id = rest[0];
32
+ const before = raw.registries.length;
33
+ raw.registries = raw.registries.filter((r) => (r.name || r.type) !== id);
34
+ if (raw.registries.length === before) { fail(`not found: ${id}`); return 1; }
35
+ writeConfig(ctx.hub, raw);
36
+ ok(`registry removed: ${id}`);
37
+ return 0;
38
+ }
39
+
40
+ fail('usage: registry [list] | add --type … | remove <name>');
41
+ return 1;
42
+ }
@@ -0,0 +1,48 @@
1
+ // remove (uninstall/un/rm) — 删投影→.trash(--purge 直删)→除名;--scope project 仅删项目副本
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { unregisterSkill, trashPath } from '../lib/hub.js';
5
+ import { unproject, targetDirFor } from '../lib/project.js';
6
+ import { confirm } from '../lib/prompt.js';
7
+ import { ok, warn, fail, info } from '../lib/render.js';
8
+ import { rmDir } from '../lib/package.js';
9
+
10
+ export async function run(ctx) {
11
+ const name = ctx.args[0];
12
+ if (!name) { fail('usage: skillmkt remove <name> [--purge] [--scope project]'); return 1; }
13
+ const flags = ctx.flags.raw;
14
+ const entry = ctx.library.skills?.[name];
15
+ if (!entry) { fail(`未受管: ${name}`); return 1; }
16
+
17
+ const projectOnly = flags.scope === 'project';
18
+ const targets = Object.entries(ctx.lock.skills?.[name]?.targets || {})
19
+ .filter(([t]) => (projectOnly ? t.startsWith('project:') : true));
20
+
21
+ for (const [t, lockT] of targets) {
22
+ const dir = targetDirFor(ctx, t, name);
23
+ if (!dir) continue;
24
+ const r = unproject(name, dir, { dryRun: ctx.flags.dryRun });
25
+ if (r.action !== 'absent') info(`${r.action} ${r.target}`);
26
+ }
27
+
28
+ if (projectOnly) {
29
+ info('project copy removed; hub 不动');
30
+ return 0;
31
+ }
32
+
33
+ if (!ctx.flags.dryRun) {
34
+ const hubDir = path.join(ctx.hub, 'skills', name);
35
+ if (fs.existsSync(hubDir)) {
36
+ if (flags.purge) { rmDir(hubDir); info(`purged ${hubDir}`); }
37
+ else {
38
+ const trash = trashPath(ctx.hub, name);
39
+ rmDir(trash);
40
+ fs.renameSync(hubDir, trash);
41
+ info(`→ .trash(恢复: mv 回 skills/ 或 skillmkt install <path>)`);
42
+ }
43
+ }
44
+ unregisterSkill(ctx.hub, name);
45
+ }
46
+ ok(`${ctx.flags.dryRun ? '[dry-run] ' : ''}removed ${name}${flags.purge ? ' (purged)' : ''}`);
47
+ return 0;
48
+ }
@@ -0,0 +1,76 @@
1
+ // resolve [id] — 交互裁决队列:[a][b][m 合并][e $EDITOR 编合并][d 误报][s 跳过][q]
2
+ // 非 TTY → 只列出队列退出 3(安全默认不裁决)
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import readline from 'node:readline';
7
+ import { execFileSync } from 'node:child_process';
8
+ import { loadConflicts, writeConflict } from '../lib/conflicts.js';
9
+ import { decide } from '../lib/decide.js';
10
+ import { autoArbitrate } from '../lib/autoarb.js';
11
+ import { maybeHandoff } from '../lib/daemon.js';
12
+ import { ok, fail, info, warn } from '../lib/render.js';
13
+
14
+ const edit = (seed) => {
15
+ const f = path.join(os.tmpdir(), `skillmkt-merge-${Date.now()}.md`);
16
+ fs.writeFileSync(f, seed);
17
+ execFileSync(process.env.EDITOR || 'vi', [f], { stdio: 'inherit' });
18
+ return fs.readFileSync(f, 'utf8').trim();
19
+ };
20
+
21
+ export async function run(ctx) {
22
+ // TTY 默认接管到 Web 裁决(--cli 留在终端;--auto/--evidence 先跑 CLI 部分)
23
+ if (!ctx.flags.raw.auto && !ctx.flags.raw.evidence && !ctx.flags.raw.cli && await maybeHandoff(ctx, '/#conflicts')) return 0;
24
+ let queue = loadConflicts(ctx.hub, { pendingOnly: true });
25
+ // --auto:fresh-context 仲裁先吃掉确定项,剩余真价值权衡留人
26
+ if (ctx.flags.raw.auto) {
27
+ if (!ctx.llm) { fail('--auto 需要 LLM(config.llm 或 OMLX_*)'); return 1; }
28
+ const r = await autoArbitrate(ctx.hub, ctx.llm, queue, { onProgress: (c, x) => info(`${c.id}: ${x ? `${x.verdict}@${x.confidence}` : 'parse-fail'}`) });
29
+ ok(`auto-arbiter: ${r.auto} 已决,${r.human} 留人,${r.errors} 错误`);
30
+ queue = loadConflicts(ctx.hub, { pendingOnly: true });
31
+ if (!queue.length) return 0;
32
+ }
33
+ // --evidence:设计域 pending 生成 A/B 截图(playwright 缺失降级 text)
34
+ if (ctx.flags.raw.evidence) {
35
+ const { makeEvidence, isDesignDomain } = await import('../lib/evidence.js');
36
+ for (const c of queue.filter((x) => isDesignDomain(x.domain))) {
37
+ if (!ctx.llm) { warn('--evidence 需要 LLM'); break; }
38
+ try { await makeEvidence(ctx.llm, ctx.hub, c); info(`${c.id}: evidence ${c.evidence}`); }
39
+ catch (e) { warn(`${c.id}: evidence failed — ${e.message.slice(0, 60)}`); }
40
+ }
41
+ }
42
+ const target = ctx.args[0] ? queue.filter((c) => c.id === ctx.args[0]) : queue;
43
+ if (!target.length) { info('无 pending 冲突'); return 0; }
44
+ if (!process.stdin.isTTY || ctx.flags.raw.cli === false) { info(`${target.length} pending(非 TTY 不裁决)— skillmkt resolve 终端交互 / --ui 网页(M5)`); return 3; }
45
+
46
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
47
+ const ask = (q) => new Promise((r) => rl.question(q, r));
48
+ let resolved = 0;
49
+ for (const c of target) {
50
+ console.log(`\n━━ ${c.id} [${c.domain}]`);
51
+ console.log(` A(${c.sides[0].source}): ${c.sides[0].text}`);
52
+ console.log(` B(${c.sides[1].source}): ${c.sides[1].text}`);
53
+ for (;;) {
54
+ const a = (await ask(' [a][b][m][e 编辑合并][d 误报][s 跳过][q] > ')).trim().toLowerCase();
55
+ if (a === 'q') { rl.close(); return resolved ? 0 : 3; }
56
+ if (a === 's') break;
57
+ const res = { a: 'keep-a', b: 'keep-b', m: 'merge', e: 'merge', d: 'dismissed' }[a];
58
+ if (!res) continue;
59
+ let custom = null;
60
+ if (a === 'm' || a === 'e') {
61
+ custom = a === 'e' ? edit(`${c.sides[0].text}\n---\n${c.sides[1].text}\n`) : (await ask(' 合并文本 > ')).trim();
62
+ if (!custom) { info('空文本,跳过'); break; }
63
+ }
64
+ const reason = (await ask(' reason > ')).trim();
65
+ if (!reason) { info('reason 必填'); continue; }
66
+ decide(ctx.hub, c, { resolution: res, custom, reason, by: process.env.USER || 'cli' });
67
+ c.status = 'resolved';
68
+ writeConflict(ctx.hub, c);
69
+ resolved++;
70
+ break;
71
+ }
72
+ }
73
+ rl.close();
74
+ ok(`resolved ${resolved}/${target.length}`);
75
+ return 0;
76
+ }
@@ -0,0 +1,30 @@
1
+ // rollback — .history/<name>/ 换回 hub 副本 → 重投影 → 改 lock(一版深度)
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { historyRestore } from '../lib/state.js';
5
+ import { historyDir } from '../lib/hub.js';
6
+ import { projectSkill, targetDirFor } from '../lib/project.js';
7
+ import { updateLock } from '../lib/hub.js';
8
+ import { treeHash } from '../lib/package.js';
9
+ import { ok, fail } from '../lib/render.js';
10
+
11
+ export async function run(ctx) {
12
+ const name = ctx.args[0];
13
+ const s = ctx.library.skills?.[name];
14
+ if (!s) { fail(`未受管: ${name}`); return 1; }
15
+ if (!fs.existsSync(historyDir(ctx.hub, name))) { fail(`${name}: 无历史副本(upgrade 后才有一版深度)`); return 1; }
16
+ if (!ctx.flags.dryRun) {
17
+ historyRestore(ctx.hub, name);
18
+ const dest = path.join(ctx.hub, 'skills', name);
19
+ const lockTargets = {};
20
+ for (const t of s.targets || []) {
21
+ const dir = targetDirFor(ctx, t, name);
22
+ if (!dir) continue;
23
+ const r = projectSkill(dest, name, dir, { mode: 'copy', force: true });
24
+ lockTargets[t] = { hash: r.hash, projected_at: new Date().toISOString(), mode: 'copy' };
25
+ }
26
+ updateLock(ctx.hub, name, treeHash(dest), lockTargets);
27
+ }
28
+ ok(`${ctx.flags.dryRun ? '[dry-run] ' : ''}rolled back ${name}`);
29
+ return 0;
30
+ }