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,46 @@
1
+ // search (find/f/s) — 本地优先两级检索;--remote 走 skills.sh 官方 API
2
+ import { scanAll } from '../lib/scanner.js';
3
+ import { searchRemote } from '../lib/registries/skillssh.js';
4
+ import { table, info, warn } from '../lib/render.js';
5
+
6
+ export async function run(ctx) {
7
+ const query = ctx.args.join(' ').trim();
8
+ if (!query) { warn('usage: skillmkt search <query> [--local|--remote] [--json]'); return 1; }
9
+ const flags = ctx.flags.raw;
10
+ const q = query.toLowerCase();
11
+
12
+ // LOCAL:已装+external
13
+ const rows = scanAll(ctx.hub, ctx.harnesses, ctx.library, ctx.project?.root);
14
+ const local = rows.filter((r) => r.name.toLowerCase().includes(q) || (r.meta?.description || '').toLowerCase().includes(q));
15
+
16
+ // REMOTE:默认 TTY 附带;--remote 强制;--local 禁用
17
+ let remote = { skills: [], base: null }, remoteErr = null;
18
+ const wantRemote = flags.remote || (!flags.local && ctx.tty);
19
+ if (wantRemote) {
20
+ try { remote = await searchRemote(query, ctx); }
21
+ catch (e) { remoteErr = e.message; }
22
+ }
23
+
24
+ if (ctx.flags.json) {
25
+ console.log(JSON.stringify({ local: local.map((r) => ({ name: r.name, where: r.where, state: r.state, path: r.path })), remote: remote.skills }, null, 2));
26
+ return 0;
27
+ }
28
+
29
+ info('LOCAL');
30
+ if (local.length) {
31
+ table(local.map((r) => ({ name: r.name, where: `${r.where}${r.state === 'external' ? ' (external)' : ''}`, ver: r.version })),
32
+ [{ key: 'name', title: 'skill' }, { key: 'where', title: 'where' }, { key: 'ver', title: 'ver' }]);
33
+ } else info(' (no local match)');
34
+
35
+ if (wantRemote) {
36
+ info('');
37
+ info(`REMOTE ${remote.base || ''}`);
38
+ if (remoteErr) warn(`remote search failed: ${remoteErr}(本地结果可用)`);
39
+ else if (remote.skills.length) {
40
+ table(remote.skills.slice(0, 15).map((s) => ({ name: s.name, id: s.slug, installs: s.installs })),
41
+ [{ key: 'name', title: 'skill' }, { key: 'id', title: 'id' }, { key: 'installs', title: 'installs' }]);
42
+ info(`→ skillmkt install ${remote.skills[0].slug.split('/').slice(0, 2).join('/')} --path ${remote.skills[0].slug.split('/').slice(2).join('/')}`);
43
+ } else info(' (no remote match)');
44
+ }
45
+ return 0;
46
+ }
@@ -0,0 +1,99 @@
1
+ // serve — 本地 daemon:node:http + token + SSE + 静态 SPA;--daemon 内部模式 / --stop / --wait
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import http from 'node:http';
5
+ import crypto from 'node:crypto';
6
+ import { daemonFile, readDaemon } from '../lib/daemon.js';
7
+ import { loadConflicts } from '../lib/conflicts.js';
8
+ import { loadDecisions, decide } from '../lib/decide.js';
9
+ import { readLibrary, readLock } from '../lib/hub.js';
10
+ import { readUpstream } from '../lib/state.js';
11
+ import { readYAML } from '../../pipeline/lib/util.js';
12
+ import { scanAll } from '../lib/scanner.js';
13
+ import { ok, info, fail } from '../lib/render.js';
14
+
15
+ const PUB = path.join(new URL('.', import.meta.url).pathname, '../public');
16
+ const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.png': 'image/png', '.svg': 'image/svg+xml' };
17
+
18
+ export async function run(ctx) {
19
+ const flags = ctx.flags.raw;
20
+ if (flags.stop) {
21
+ const d = readDaemon(ctx.hub);
22
+ if (d) { try { process.kill(d.pid); } catch { /* dead */ } fs.rmSync(daemonFile(ctx.hub), { force: true }); ok('daemon stopped'); }
23
+ else info('no daemon');
24
+ return 0;
25
+ }
26
+
27
+ const token = crypto.randomBytes(16).toString('hex');
28
+ const sse = new Set();
29
+ const emit = (type, data) => { for (const res of sse) res.write(`event: ${type}\ndata: ${JSON.stringify(data)}\n\n`); };
30
+ let lastActive = Date.now();
31
+ const idleMs = (ctx.config.daemon?.idle_minutes ?? 30) * 60e3;
32
+
33
+ const state = () => ({
34
+ hub: ctx.hub, library: readLibrary(ctx.hub), lock: readLock(ctx.hub),
35
+ upstream: readUpstream(ctx.hub), conflicts: loadConflicts(ctx.hub),
36
+ decisions: loadDecisions(ctx.hub), harnesses: ctx.harnesses,
37
+ scans: fs.existsSync(path.join(ctx.hub, 'scans')) ? fs.readdirSync(path.join(ctx.hub, 'scans')).map((f) => readYAML(path.join(ctx.hub, 'scans', f))).filter(Boolean) : [],
38
+ scans_all: scanAll(ctx.hub, ctx.harnesses, readLibrary(ctx.hub), ctx.cwd),
39
+ });
40
+
41
+ const routes = {
42
+ 'GET /api/state': () => state(),
43
+ 'GET /api/conflicts': () => loadConflicts(ctx.hub),
44
+ 'GET /api/decisions': () => loadDecisions(ctx.hub),
45
+ };
46
+
47
+ const server = http.createServer(async (req, res) => {
48
+ lastActive = Date.now();
49
+ const u = new URL(req.url, 'http://x');
50
+ // auth:Bearer header 或 ?token=(SSE/img 用 query,服务端不下发 cookie)
51
+ const authed = req.headers.authorization === `Bearer ${token}` || u.searchParams.get('token') === token;
52
+ if (u.pathname === '/api/events') { // SSE
53
+ if (!authed) { res.writeHead(401); return res.end(); }
54
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
55
+ res.write('retry: 2000\n\n');
56
+ sse.add(res);
57
+ req.on('close', () => sse.delete(res));
58
+ return;
59
+ }
60
+ if (u.pathname.startsWith('/api/')) {
61
+ if (!authed) { res.writeHead(401, { 'content-type': 'application/json' }); return res.end('{"error":"unauthorized"}'); }
62
+ res.setHeader('content-type', 'application/json');
63
+ if (req.method === 'POST' && u.pathname === '/api/decide') {
64
+ const body = JSON.parse(await new Promise((r) => { let b = ''; req.on('data', (c) => b += c); req.on('end', () => r(b || '{}')); }));
65
+ const c = loadConflicts(ctx.hub).find((x) => x.id === body.id);
66
+ if (!c) { res.writeHead(404); return res.end('{"error":"not found"}'); }
67
+ try {
68
+ decide(ctx.hub, c, { resolution: body.resolution, custom: body.custom || null, reason: body.reason || 'web decision', by: 'web-ui' });
69
+ c.status = 'resolved';
70
+ const { writeConflict } = await import('../lib/conflicts.js');
71
+ writeConflict(ctx.hub, c);
72
+ emit('decide', { id: c.id });
73
+ return res.end('{"ok":true}');
74
+ } catch (e) { res.writeHead(400); return res.end(JSON.stringify({ error: e.message })); }
75
+ }
76
+ const h = routes[`${req.method} ${u.pathname}`];
77
+ if (h) return res.end(JSON.stringify(h()));
78
+ res.writeHead(404); return res.end('{"error":"not found"}');
79
+ }
80
+ // 静态:public/ + evidence 文件(冲突截图)
81
+ let p = u.pathname === '/' ? '/index.html' : u.pathname;
82
+ let file = path.join(PUB, p);
83
+ if (p.startsWith('/evidence/')) file = path.join(ctx.hub, p);
84
+ if (!file.startsWith(PUB) && !file.startsWith(ctx.hub)) { res.writeHead(403); return res.end(); }
85
+ if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) { res.writeHead(404); return res.end('nf'); }
86
+ res.setHeader('content-type', MIME[path.extname(file)] || 'application/octet-stream');
87
+ fs.createReadStream(file).pipe(res);
88
+ });
89
+
90
+ await new Promise((r) => server.listen(flags.port || 0, '127.0.0.1', r));
91
+ const port = server.address().port;
92
+ fs.writeFileSync(daemonFile(ctx.hub), JSON.stringify({ pid: process.pid, port, token, started: new Date().toISOString() }));
93
+ const idle = setInterval(() => { if (Date.now() - lastActive > idleMs) { server.close(); process.exit(0); } }, 60e3);
94
+ idle.unref();
95
+ if (flags.daemon) { console.log(`daemon ready :${port}`); await new Promise(() => {}); }
96
+ console.log(`serve: http://127.0.0.1:${port}?token=${token}(idle ${ctx.config.daemon?.idle_minutes ?? 30}m 自退;--stop 停止)`);
97
+ if (flags.wait !== false && !flags.daemon) await new Promise(() => {});
98
+ return 0;
99
+ }
@@ -0,0 +1,52 @@
1
+ // show (view/info) — skill 详情卡:frontmatter+版本+审核+目标;--raw/--files/--audit
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { readSkillDir, parseFrontmatter } from '../lib/package.js';
5
+ import { scanAll } from '../lib/scanner.js';
6
+ import { readYAMLFile } from '../lib/hub.js';
7
+ import { info, fail } from '../lib/render.js';
8
+
9
+ export async function run(ctx) {
10
+ const name = ctx.args[0];
11
+ if (!name) { fail('usage: skillmkt show <name> [--raw|--files|--audit]'); return 1; }
12
+ const flags = ctx.flags.raw;
13
+
14
+ // 受管 → hub;否则 external 中找
15
+ let dir = path.join(ctx.hub, 'skills', name);
16
+ let entry = ctx.library.skills?.[name] ?? null;
17
+ let where = 'hub';
18
+ if (!fs.existsSync(path.join(dir, 'SKILL.md'))) {
19
+ const ext = scanAll(ctx.hub, ctx.harnesses, ctx.library, ctx.project?.root)
20
+ .find((r) => r.name === name && r.state === 'external');
21
+ if (!ext) { fail(`not found: ${name}`); return 1; }
22
+ dir = ext.path; where = `${ext.where} (external)`;
23
+ }
24
+ const pkg = readSkillDir(dir);
25
+
26
+ if (flags.raw) { console.log(fs.readFileSync(path.join(dir, 'SKILL.md'), 'utf8')); return 0; }
27
+ if (flags.files) { pkg.files.forEach((f) => console.log(f)); return 0; }
28
+ if (flags.audit) {
29
+ const scan = readYAMLFile(path.join(ctx.hub, 'scans', `${name}.yml`), null);
30
+ if (ctx.flags.json) { console.log(JSON.stringify(scan)); return 0; }
31
+ if (!scan) { info('no scan record'); return 0; }
32
+ info(`verdict: ${scan.verdict} @ ${scan.scanned_at}`);
33
+ (scan.static?.findings || []).forEach((f) => info(` ${f.rule} ${f.file}:${f.line}`));
34
+ return 0;
35
+ }
36
+
37
+ const card = {
38
+ name: pkg.name, version: pkg.version, description: pkg.meta.description || '',
39
+ where, path: dir, files: pkg.fileCount,
40
+ ...(entry ? { source: entry.source, targets: entry.targets, audit: entry.audit, installed_at: entry.installed_at } : {}),
41
+ };
42
+ if (ctx.flags.json) { console.log(JSON.stringify(card, null, 2)); return 0; }
43
+ info(`${card.name} v${card.version}`);
44
+ info(`${card.description}`);
45
+ info(`where: ${card.where} · ${card.path}`);
46
+ info(`files: ${card.files}`);
47
+ if (entry) {
48
+ info(`source: ${entry.source?.registry} ${entry.source?.ref || ''}${entry.source?.path ? ` (${entry.source.path})` : ''}${entry.source?.adopted_from ? ` adopted_from ${entry.source.adopted_from}` : ''}`);
49
+ info(`targets: ${(entry.targets || []).join(', ') || 'hub only'} · audit: ${entry.audit}`);
50
+ }
51
+ return 0;
52
+ }
@@ -0,0 +1,54 @@
1
+ // sync — 按 library+lock 重放全部投影;--dry-run 只报漂移 exit4;新 harness 交互询问
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { projectSkill, checkDrift, targetDirFor } from '../lib/project.js';
5
+ import { updateLock } from '../lib/hub.js';
6
+ import { confirm } from '../lib/prompt.js';
7
+ import { ok, warn, info } from '../lib/render.js';
8
+
9
+ export async function run(ctx) {
10
+ const { library, lock } = ctx;
11
+
12
+ if (ctx.flags.dryRun) {
13
+ const drift = checkDrift(ctx);
14
+ if (drift.length) {
15
+ for (const d of drift) info(`${d.name} @ ${d.target}: ${d.issue}`);
16
+ warn(`${drift.length} drift — run 'skillmkt sync' to repair`);
17
+ return 4;
18
+ }
19
+ ok('projections in sync');
20
+ return 0;
21
+ }
22
+
23
+ // 新 available harness:交互询问纳入(非 TTY 不扩面)
24
+ const avail = ctx.harnesses.filter((h) => h.state === 'available' && !h.detectOnly
25
+ && !ctx.config.default_targets.includes(h.id));
26
+ for (const h of avail) {
27
+ if (await confirm(`检测到新 harness ${h.id}(available)——纳入默认投影目标?`, { defaultYes: false })) {
28
+ const raw = ctx.config._raw;
29
+ raw.default_targets = [...new Set([...(raw.default_targets || []), h.id])];
30
+ const { writeConfig } = await import('../lib/hub.js');
31
+ writeConfig(ctx.hub, raw);
32
+ info(`${h.id} → default_targets`);
33
+ }
34
+ }
35
+
36
+ let n = 0, repaired = 0;
37
+ for (const [name, s] of Object.entries(library.skills || {})) {
38
+ const src = path.join(ctx.hub, 'skills', name);
39
+ if (!fs.existsSync(src)) { warn(`${name}: hub 副本缺失`); continue; }
40
+ const lockTargets = {};
41
+ for (const t of s.targets || []) {
42
+ const dir = targetDirFor(ctx, t, name);
43
+ if (!dir) { warn(`${name}: unknown target ${t}`); continue; }
44
+ const r = projectSkill(src, name, dir, { mode: s.transport?.[t] === 'link' ? 'link' : 'copy', force: !!ctx.flags.raw.force });
45
+ if (r.action === 'conflict') warn(`${name} @ ${t}: ${r.detail}(手动改过的内容不覆盖——--force 强制重建,或改回后 sync)`);
46
+ else if (r.action !== 'skipped') { repaired++; info(`${name} → ${r.action} ${r.target}`); }
47
+ lockTargets[t] = { hash: r.hash, projected_at: new Date().toISOString(), mode: r.mode };
48
+ n++;
49
+ }
50
+ if (Object.keys(lockTargets).length) updateLock(ctx.hub, name, lock.skills?.[name]?.content_hash ?? 'sha256:', lockTargets);
51
+ }
52
+ ok(`sync done: ${n} targets checked, ${repaired} (re)projected`);
53
+ return 0;
54
+ }
@@ -0,0 +1,75 @@
1
+ // targets — list / add <harness> / add --path <dir> <name> / remove <id>
2
+ import path from 'node:path';
3
+ import { table, ok, fail, info } from '../lib/render.js';
4
+ import { readConfig, writeConfig, expandHome } from '../lib/hub.js';
5
+ import { projectSkill } from '../lib/project.js';
6
+ import { updateLock } from '../lib/hub.js';
7
+ import { readSkillDir } from '../lib/package.js';
8
+ import fs from 'node:fs';
9
+
10
+ export async function run(ctx) {
11
+ const [sub, ...rest] = ctx.args;
12
+ const flags = ctx.flags.raw;
13
+
14
+ if (!sub || sub === 'list') {
15
+ const rows = ctx.harnesses.map((h) => ({
16
+ id: h.id, state: h.state,
17
+ dir: h.dirs.map((d) => d.path).join(', '),
18
+ default: ctx.config.default_targets.includes(h.id) ? '●' : '',
19
+ }));
20
+ const customs = Object.entries(ctx.config.targets).map(([n, t]) => ({ id: n, state: 'custom', dir: expandHome(t.path), default: ctx.config.default_targets.includes(n) ? '●' : '' }));
21
+ if (ctx.flags.json) { console.log(JSON.stringify({ harnesses: rows, custom: customs }, null, 2)); return 0; }
22
+ table([...rows, ...customs], [
23
+ { key: 'id', title: 'target' }, { key: 'state', title: 'state' },
24
+ { key: 'dir', title: 'dir' }, { key: 'default', title: 'def' },
25
+ ]);
26
+ return 0;
27
+ }
28
+
29
+ if (sub === 'add') {
30
+ const raw = readConfig(ctx.hub)._raw;
31
+ // targets add --path <dir> <name>
32
+ if (flags.path) {
33
+ const name = rest[0];
34
+ if (!name) { fail('usage: targets add --path <dir> <name>'); return 1; }
35
+ raw.targets = raw.targets || {};
36
+ raw.targets[name] = { path: flags.path, transport: 'copy' };
37
+ writeConfig(ctx.hub, raw);
38
+ ok(`custom target registered: ${name} → ${flags.path}`);
39
+ return 0;
40
+ }
41
+ // targets add <harness-id|custom-name>:写 default_targets + 立即投影全部
42
+ const id = rest[0];
43
+ if (!id) { fail('usage: targets add <id>'); return 1; }
44
+ const h = ctx.harnesses.find((x) => x.id === id);
45
+ const custom = ctx.config.targets[id];
46
+ if (!h && !custom) { fail(`unknown target: ${id}`); return 1; }
47
+ raw.default_targets = [...new Set([...(raw.default_targets || []), id])];
48
+ writeConfig(ctx.hub, raw);
49
+ ok(`${id} → default_targets`);
50
+
51
+ const dirs = h ? h.dirs.map((d) => ({ dir: d.path, id })) : [{ dir: expandHome(custom.path), id: `custom:${expandHome(custom.path)}` }];
52
+ for (const [name] of Object.entries(ctx.library.skills || {})) {
53
+ const src = path.join(ctx.hub, 'skills', name);
54
+ if (!fs.existsSync(src)) continue;
55
+ for (const { dir, id: tid } of dirs) {
56
+ const r = projectSkill(src, name, dir, { mode: 'copy', dryRun: ctx.flags.dryRun });
57
+ info(`${name} → ${r.action} ${r.target}`);
58
+ }
59
+ }
60
+ return 0;
61
+ }
62
+
63
+ if (sub === 'remove' || sub === 'rm') {
64
+ const id = rest[0];
65
+ const raw = readConfig(ctx.hub)._raw;
66
+ if (raw.targets?.[id]) { delete raw.targets[id]; writeConfig(ctx.hub, raw); ok(`custom target removed: ${id}`); return 0; }
67
+ raw.default_targets = (raw.default_targets || []).filter((t) => t !== id);
68
+ writeConfig(ctx.hub, raw);
69
+ ok(`${id} removed from default_targets(已投影副本保留——skillmkt sync 可清)`);
70
+ return 0;
71
+ }
72
+
73
+ fail('usage: skillmkt targets [list] | add <id> | add --path <dir> <name> | remove <id>');
74
+ return 1;
75
+ }
@@ -0,0 +1,39 @@
1
+ // update — apt update 语义:只刷新上游元数据入 state/upstream.yml,不碰已装
2
+ import path from 'node:path';
3
+ import fs from 'node:fs';
4
+ import { remoteTree } from '../lib/registries/github.js';
5
+ import { setUpstream, readUpstream, writeUpstream } from '../lib/state.js';
6
+ import { gitTreeHash } from '../lib/githash.js';
7
+ import { ok, warn, info } from '../lib/render.js';
8
+
9
+ export async function run(ctx) {
10
+ const skills = ctx.library.skills || {};
11
+ const names = ctx.args[0] === '--all' || !ctx.args[0] ? Object.keys(skills) : ctx.args;
12
+ let n = 0, na = 0, errs = 0;
13
+ for (const name of names) {
14
+ const s = skills[name];
15
+ if (!s) { warn(`未受管: ${name}`); continue; }
16
+ const src = s.source || {};
17
+ if (src.registry !== 'github' || !src.ref) { na++; continue; } // adopted/local/rfc 无远端可查(rfc 走 registry 适配后续)
18
+ try {
19
+ const [owner, repo] = src.ref.split('/');
20
+ const remote = await remoteTree(owner, repo, src.pin, src.path || null);
21
+ const localDir = path.join(ctx.hub, 'skills', name);
22
+ const localTree = fs.existsSync(localDir) ? gitTreeHash(localDir) : null;
23
+ setUpstream(ctx.hub, name, {
24
+ ref: remote.sha, tree_hash: remote.tree_hash,
25
+ outdated: localTree !== null && localTree !== remote.tree_hash,
26
+ });
27
+ n++;
28
+ if (localTree !== remote.tree_hash) info(`${name}: upstream changed`);
29
+ } catch (e) {
30
+ errs++;
31
+ warn(`${name}: ${e.message.slice(0, 80)}`);
32
+ }
33
+ }
34
+ const u = readUpstream(ctx.hub);
35
+ u.refreshed_at = new Date().toISOString();
36
+ writeUpstream(ctx.hub, u);
37
+ ok(`update done: ${n} refreshed${na ? `, ${na} n/a(adopted/local)` : ''}${errs ? `, ${errs} errors` : ''}`);
38
+ return errs ? 1 : 0;
39
+ }
@@ -0,0 +1,75 @@
1
+ // upgrade — apt upgrade:拉新→diff 摘要→重审→快照→重投影→改 lock;--dry-run 只演示
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fetchSkill } from '../lib/registries/github.js';
5
+ import { readUpstream, setUpstream, historySnapshot } from '../lib/state.js';
6
+ import { auditDir, stripFilter, writeScan } from '../lib/audit.js';
7
+ import { readSkillDir, walk, rmDir, treeHash } from '../lib/package.js';
8
+ import { projectSkill, targetDirFor } from '../lib/project.js';
9
+ import { registerSkill, updateLock } from '../lib/hub.js';
10
+ import { fetchMirror } from '../lib/registries/index.js';
11
+ import { ok, warn, fail, info } from '../lib/render.js';
12
+
13
+ function copyFiltered(src, dst, keep) {
14
+ fs.mkdirSync(dst, { recursive: true });
15
+ for (const p of walk(src)) {
16
+ const rel = path.relative(src, p).split(path.sep).join('/');
17
+ if (!keep(rel)) continue;
18
+ const d = path.join(dst, rel);
19
+ fs.mkdirSync(path.dirname(d), { recursive: true });
20
+ fs.copyFileSync(p, d);
21
+ }
22
+ }
23
+
24
+ export async function run(ctx) {
25
+ const flags = ctx.flags.raw;
26
+ const up = readUpstream(ctx.hub);
27
+ const skills = ctx.library.skills || {};
28
+ const names = flags.all ? Object.keys(skills) : ctx.args;
29
+ if (!names.length) { fail('usage: skillmkt upgrade <name|--all>'); return 1; }
30
+
31
+ let upgraded = 0;
32
+ for (const name of names) {
33
+ const s = skills[name];
34
+ if (!s) { warn(`未受管: ${name}`); continue; }
35
+ const u = up.skills?.[name];
36
+ if (!u?.outdated && !flags.force) { info(`${name}: clean(update 先刷新)`); continue; }
37
+ const src = s.source || {};
38
+ if (src.registry !== 'github' || !src.ref) { warn(`${name}: 无上游可升级`); continue; }
39
+
40
+ const [owner, repo] = src.ref.split('/');
41
+ info(`${name}: fetching ${src.ref} …`);
42
+ try {
43
+ const got = await fetchSkill({ owner, repo, ref: null, path: src.path || null, mirror: fetchMirror(ctx) });
44
+ const pkg = readSkillDir(got.dir);
45
+ const audit = auditDir(got.dir, { strip: !flags.keepScripts });
46
+ if (audit.verdict === 'malicious') { warn(`${name}: 新版审核 malicious——保留旧版(quarantine 不收新版)`); continue; }
47
+ if (ctx.flags.dryRun) {
48
+ info(`[dry-run] ${name}: ${pkg?.fileCount ?? '?'} files, audit:${audit.verdict}${audit.stripped.length ? `,strip ${audit.stripped.length}` : ''}`);
49
+ continue;
50
+ }
51
+ historySnapshot(ctx.hub, name);
52
+ const dest = path.join(ctx.hub, 'skills', name);
53
+ rmDir(dest);
54
+ copyFiltered(got.dir, dest, stripFilter(flags.keepScripts ? [] : audit.stripped));
55
+ writeScan(ctx.hub, name, audit);
56
+ // 重投影
57
+ const lockTargets = {};
58
+ for (const t of s.targets || []) {
59
+ const dir = targetDirFor(ctx, t, name);
60
+ if (!dir) continue;
61
+ const r = projectSkill(dest, name, dir, { mode: 'copy' });
62
+ lockTargets[t] = { hash: r.hash, projected_at: new Date().toISOString(), mode: 'copy' };
63
+ }
64
+ registerSkill(ctx.hub, name, { ...s, source: { ...src, pin: got.sha }, version: pkg?.version || s.version, installed_at: new Date().toISOString(), audit: audit.stripped.length ? 'stripped' : audit.verdict });
65
+ updateLock(ctx.hub, name, treeHash(dest), lockTargets);
66
+ setUpstream(ctx.hub, name, { ref: got.sha, outdated: false });
67
+ upgraded++;
68
+ ok(`${name} → ${got.sha.slice(0, 7)} audit:${audit.verdict}`);
69
+ } catch (e) {
70
+ warn(`${name}: upgrade failed — ${e.message.slice(0, 100)}`);
71
+ }
72
+ }
73
+ ok(`upgrade done: ${upgraded} applied`);
74
+ return 0;
75
+ }
@@ -0,0 +1,67 @@
1
+ // ai.js — LLM 语义层:全部 additive/降级安全(llm=null 或异常→回静态)
2
+ // fresh-context 仲裁 / LLM 审核 / 语义 diff / 自由域抽取
3
+ import { chat } from './llm.js';
4
+
5
+ const J = (s) => { const m = String(s).match(/```(?:json)?\s*([\s\S]*?)```/) || [null, s]; try { return JSON.parse(m[1].trim()); } catch { return null; } };
6
+
7
+ // ── 仲裁:fresh-context 判冲突是否真实 + 给建议(简单冲突独立裁决,难的留人)
8
+ // → {real: bool, verdict: keep-a|keep-b|merge|human, confidence, explanation, merged?}
9
+ export async function arbitrate(llm, conflict) {
10
+ const [a, b] = conflict.sides;
11
+ const r = J(await chat(llm, {
12
+ system: 'You arbitrate conflicting rules from different agent skills. Reply ONLY JSON.',
13
+ user: `Two rules may conflict:\nA [${a.source}]: ${a.text}\nB [${b.source}]: ${b.text}\n\nJSON: {"real":bool,"verdict":"keep-a|keep-b|merge|human","confidence":0-1,"explanation":"one sentence","merged":"only if verdict=merge"}\n- real=false if not actually contradictory\n- verdict=human when it's a genuine value tradeoff (aesthetics/philosophy) needing human choice`,
14
+ maxTokens: 1600,
15
+ }));
16
+ if (!r || typeof r.real !== 'boolean') return null;
17
+ return r;
18
+ }
19
+
20
+ // ── LLM 审核(additive:静态 findings 之外补充语义判断)
21
+ // → {verdict: clean|suspicious|malicious, reasons[]}
22
+ export async function llmAudit(llm, { name, files }) {
23
+ const preview = files.map((f) => `### ${f.path}\n${f.content.slice(0, 1500)}`).join('\n\n').slice(0, 12000);
24
+ const r = J(await chat(llm, {
25
+ system: 'You audit agent skill packages for supply-chain risk. Reply ONLY JSON.',
26
+ user: `Skill "${name}" files:\n${preview}\n\nJSON: {"verdict":"clean|suspicious|malicious","reasons":["…"]}\nmalicious=data exfiltration/credential theft/persistence; suspicious=network+secret reads, obfuscation, instruction smuggling`,
27
+ maxTokens: 800,
28
+ }));
29
+ return r?.verdict ? r : null;
30
+ }
31
+
32
+ // ── 语义 diff:文件增删+节变化 → 意图变化摘要
33
+ export async function semanticDiff(llm, { name, added, removed, changed, secAdded, secRemoved }) {
34
+ const t = await chat(llm, {
35
+ system: 'Summarize upstream changes to an agent skill for a user deciding whether to upgrade. 2-4 sentences, direct.',
36
+ user: `Skill "${name}": files +${added.length} -${removed.length} ~${changed.length}\nadded: ${added.slice(0, 10).join(', ')}\nremoved: ${removed.slice(0, 10).join(', ')}\nsections added: ${secAdded.join(' | ')}\nsections removed: ${secRemoved.join(' | ')}`,
37
+ maxTokens: 600,
38
+ });
39
+ return t?.trim() || null;
40
+ }
41
+
42
+ // ── LLM 抽规则:自由 domain 标签(≤12 字符),静态兜底见 lib/rules.js
43
+ export async function extractRulesLLM(llm, skillMd, sourceName) {
44
+ const r = J(await chat(llm, {
45
+ system: 'Extract rules from an agent skill document. Reply ONLY JSON array.',
46
+ user: `From this skill doc extract normative rules (dos/donts/specs). JSON: [{"text":"≤160 chars","domain":"≤12-char slug","severity":"floor|standard|reflex"}]\n\n${skillMd.slice(0, 14000)}`,
47
+ maxTokens: 8000,
48
+ }));
49
+ if (!Array.isArray(r)) return null;
50
+ const { ruleHash } = await import('../../pipeline/lib/util.js');
51
+ return r.filter((x) => x?.text?.length > 10).map((x, i) => ({
52
+ id: `${sourceName.slice(0, 6)}-l${String(i + 1).padStart(3, '0')}`, source: sourceName,
53
+ domain: String(x.domain || 'misc').slice(0, 12), severity: ['floor', 'standard', 'reflex'].includes(x.severity) ? x.severity : 'standard',
54
+ text: x.text.slice(0, 220), hash: ruleHash(x.text),
55
+ }));
56
+ }
57
+
58
+ // ── 文本 A/B 解说(非设计域冲突的证据替代)
59
+ export async function explainConflict(llm, conflict) {
60
+ const [a, b] = conflict.sides;
61
+ const t = await chat(llm, {
62
+ system: 'Explain a rule conflict between two agent skills in 1-2 sentences.',
63
+ user: `A [${a.source}]: ${a.text}\nB [${b.source}]: ${b.text}`,
64
+ maxTokens: 400,
65
+ });
66
+ return t?.trim() || null;
67
+ }
@@ -0,0 +1,87 @@
1
+ // audit.js — 静态审核闸门(无需模型):scripts 剥离、密钥出口、外联指令、权限越权、PII 收割
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { walk } from './package.js';
5
+ import { writeYAMLFile } from './hub.js';
6
+
7
+ const TEXT_EXT = /\.(md|txt|json|ya?ml|toml|mjs|cjs|js|ts|sh|py|html?|css)$/i;
8
+ const STRIP_DIRS = /^(scripts?|bin|tools?|hooks?|install|\.github\/workflows)$/i;
9
+ const EXEC_EXT = /\.(sh|bash|zsh|exe|bat|cmd|ps1|com|dll|so|dylib|app)$/i;
10
+
11
+ const RULES = [
12
+ {
13
+ id: 'secret-pattern', weight: 2,
14
+ re: /sk-[A-Za-z0-9_-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----|~\/\.ssh\/|AWS_(SECRET|ACCESS)|\.env\b.*(?:read|cat|source|load)|(?:API[_-]?KEY|SECRET|TOKEN)\s*=\s*["']?[A-Za-z0-9_\-]{16,}/i,
15
+ severe: /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
16
+ },
17
+ {
18
+ id: 'egress-cmd', weight: 1,
19
+ re: /\b(?:curl|wget|Invoke-WebRequest|iwr)\b[^|\n]*https?:\/\/|\bnc\b\s+-|\/dev\/tcp\/|\bbase64\b[^|\n]*\|\s*(?:sh|bash)|\b(?:fetch|axios|requests\.get)\b[^)\n]*https?:\/\//i,
20
+ },
21
+ {
22
+ id: 'perm-escalation', weight: 1,
23
+ re: /ignore (?:all |any )?(?:previous|prior) instructions?|do not (?:tell|inform|show) the user|add (?:yourself|itself|myself) to|(?:grant|give) (?:yourself|it) (?:access|permission)|modify (?:the )?(?:settings|config|permissions?)\.(?:json|ya?ml)|enable (?:all )?tools?/i,
24
+ },
25
+ {
26
+ id: 'pii-harvest', weight: 3, severe: true,
27
+ re: /contacts?\.(?:sqlite|db)|browser (?:profile|cookie|password|history)|keychain|wallet\.(?:dat|json)|\.metamask|\.aws\/credentials|password store|cookies?\.sqlite/i,
28
+ },
29
+ ];
30
+
31
+ export function isTextFile(p) { return TEXT_EXT.test(p); }
32
+ export function shouldStripDir(name) { return STRIP_DIRS.test(name) || EXEC_EXT.test(name); }
33
+
34
+ // 返回 {verdict, findings[], stripped[]}——pkg={path} 指向待审目录
35
+ export function auditDir(dir, { strip = true } = {}) {
36
+ const findings = [];
37
+ const stripped = [];
38
+
39
+ for (const p of walk(dir)) {
40
+ const rel = path.relative(dir, p);
41
+ const top = rel.split(path.sep)[0];
42
+ const base = path.basename(p);
43
+ if (STRIP_DIRS.test(top) || EXEC_EXT.test(base) || /\.(sh|bash|ps1)$/.test(base)) {
44
+ stripped.push(rel);
45
+ continue;
46
+ }
47
+ if (!isTextFile(p)) continue;
48
+ let src;
49
+ try { src = fs.readFileSync(p, 'utf8'); } catch { continue; }
50
+ const lines = src.split('\n');
51
+ for (const rule of RULES) {
52
+ lines.forEach((line, i) => {
53
+ if (rule.re.test(line)) {
54
+ const severe = rule.severe === true ? true : !!rule.severe?.test?.(line);
55
+ findings.push({ rule: rule.id, file: rel, line: i + 1, excerpt: line.trim().slice(0, 120), severe });
56
+ }
57
+ });
58
+ }
59
+ }
60
+
61
+ // verdict 归并(代码判定,不是模型)
62
+ const has = (id) => findings.some((f) => f.rule === id);
63
+ const severe = findings.some((f) => f.severe);
64
+ const suspiciousCount = findings.reduce((n, f) => n + (RULES.find((r) => r.id === f.rule)?.weight ?? 1), 0);
65
+ let verdict = 'clean';
66
+ if (has('pii-harvest') || severe || (has('secret-pattern') && has('egress-cmd')) || suspiciousCount >= 5) verdict = 'malicious';
67
+ else if (findings.length || stripped.length) verdict = 'suspicious';
68
+
69
+ return { verdict, findings, stripped: strip ? stripped : [] };
70
+ }
71
+
72
+ // 剥离:copy 时排除 stripped 相对路径
73
+ export function stripFilter(stripped) {
74
+ const set = new Set(stripped);
75
+ const tops = new Set(stripped.map((r) => r.split('/')[0].split('\\')[0]));
76
+ return (rel) => !set.has(rel) && !tops.has(rel.split('/')[0]);
77
+ }
78
+
79
+ export function writeScan(hub, name, result, { llm = null } = {}) {
80
+ writeYAMLFile(path.join(hub, 'scans', `${name}.yml`), {
81
+ name,
82
+ scanned_at: new Date().toISOString(),
83
+ static: { findings: result.findings, stripped: result.stripped },
84
+ verdict: result.verdict,
85
+ ...(llm ? { llm } : {}),
86
+ });
87
+ }
@@ -0,0 +1,26 @@
1
+ // autoarb.js — fresh-context 自动仲裁:confidence≥阈值 且 verdict≠human → 自动落 decision
2
+ // 返回 {auto, human, errors};LLM 异常→errors(不阻塞,pending 原样留队)
3
+ import { arbitrate } from './ai.js';
4
+ import { decide } from './decide.js';
5
+ import { writeConflict } from './conflicts.js';
6
+ import { mapPool } from '../../pipeline/lib/util.js';
7
+
8
+ export async function autoArbitrate(hub, llm, conflicts, { minConfidence = 0.85, onProgress = null } = {}) {
9
+ const out = { auto: 0, human: 0, errors: 0 };
10
+ await mapPool(conflicts, async (c) => {
11
+ let r;
12
+ try { r = await arbitrate(llm, c); } catch { out.errors++; return; }
13
+ onProgress?.(c, r);
14
+ if (!r || !r.real) { // 误判/解析失败→留 pending 给人
15
+ if (r && !r.real) { c.status = 'dismissed'; c.dismiss_reason = r.explanation || 'llm: not a real conflict'; writeConflict(hub, c); out.auto++; }
16
+ return;
17
+ }
18
+ if (r.verdict === 'human' || (Number(r.confidence) || 0) < minConfidence) { out.human++; return; }
19
+ decide(hub, c, { resolution: r.verdict, custom: r.merged || null, reason: `auto-arbiter: ${r.explanation || r.verdict}`, by: 'auto-arbiter' });
20
+ c.status = 'resolved';
21
+ if (r.explanation) c.ai_explanation = r.explanation;
22
+ writeConflict(hub, c);
23
+ out.auto++;
24
+ }, 2);
25
+ return out;
26
+ }