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.
- package/LICENSE +21 -0
- package/README.md +213 -2
- package/client/bin/skillmkt.js +84 -0
- package/client/commands/audit.js +34 -0
- package/client/commands/build.js +61 -0
- package/client/commands/config.js +34 -0
- package/client/commands/conflicts.js +14 -0
- package/client/commands/decide.js +19 -0
- package/client/commands/diff.js +52 -0
- package/client/commands/doctor.js +109 -0
- package/client/commands/download.js +35 -0
- package/client/commands/init.js +82 -0
- package/client/commands/install.js +169 -0
- package/client/commands/list.js +56 -0
- package/client/commands/merge.js +49 -0
- package/client/commands/outdated.js +34 -0
- package/client/commands/registry.js +42 -0
- package/client/commands/remove.js +48 -0
- package/client/commands/resolve.js +76 -0
- package/client/commands/rollback.js +30 -0
- package/client/commands/search.js +46 -0
- package/client/commands/serve.js +99 -0
- package/client/commands/show.js +52 -0
- package/client/commands/sync.js +54 -0
- package/client/commands/targets.js +75 -0
- package/client/commands/update.js +39 -0
- package/client/commands/upgrade.js +75 -0
- package/client/lib/ai.js +67 -0
- package/client/lib/audit.js +87 -0
- package/client/lib/autoarb.js +26 -0
- package/client/lib/conflicts.js +65 -0
- package/client/lib/ctx.js +68 -0
- package/client/lib/daemon.js +47 -0
- package/client/lib/dashboard.js +29 -0
- package/client/lib/decide.js +43 -0
- package/client/lib/evidence.js +56 -0
- package/client/lib/githash.js +36 -0
- package/client/lib/hub.js +125 -0
- package/client/lib/llm.js +85 -0
- package/client/lib/package.js +73 -0
- package/client/lib/project.js +97 -0
- package/client/lib/prompt.js +22 -0
- package/client/lib/ref.js +37 -0
- package/client/lib/registries/github.js +106 -0
- package/client/lib/registries/index.js +37 -0
- package/client/lib/registries/rfc.js +42 -0
- package/client/lib/registries/skillssh.js +59 -0
- package/client/lib/render.js +53 -0
- package/client/lib/rules.js +36 -0
- package/client/lib/scanner.js +158 -0
- package/client/lib/state.js +50 -0
- package/client/lib/yamlls.js +14 -0
- package/client/public/app.js +63 -0
- package/client/public/index.html +21 -0
- package/package.json +44 -4
- package/pipeline/lib/env.js +40 -0
- package/pipeline/lib/gh.js +53 -0
- package/pipeline/lib/llm.js +108 -0
- package/pipeline/lib/util.js +103 -0
- package/skill/SKILL.md +270 -0
- package/skill/references/a11y.md +82 -0
- package/skill/references/code.md +415 -0
- package/skill/references/color.md +84 -0
- package/skill/references/copy.md +197 -0
- package/skill/references/imagery.md +157 -0
- package/skill/references/layout.md +404 -0
- package/skill/references/motion.md +104 -0
- package/skill/references/process.md +303 -0
- package/skill/references/type.md +84 -0
- package/skill/rules-manifest.yml +13092 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// state.js — state/upstream.yml 读写 + cache 索引 + history 快照
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { readYAMLFile, writeYAMLFile, historyDir } from './hub.js';
|
|
5
|
+
import { rmDir } from './package.js';
|
|
6
|
+
|
|
7
|
+
export const readUpstream = (hub) => readYAMLFile(path.join(hub, 'state', 'upstream.yml'), { skills: {} });
|
|
8
|
+
export const writeUpstream = (hub, d) => writeYAMLFile(path.join(hub, 'state', 'upstream.yml'), d);
|
|
9
|
+
|
|
10
|
+
export function setUpstream(hub, name, entry) {
|
|
11
|
+
const u = readUpstream(hub);
|
|
12
|
+
u.skills[name] = { ...u.skills[name], ...entry, checked_at: new Date().toISOString() };
|
|
13
|
+
writeUpstream(hub, u);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// download 缓存命中:cache/<name>-*/ 存在即返回
|
|
17
|
+
export function cacheLookup(hub, name) {
|
|
18
|
+
const dir = path.join(hub, 'cache');
|
|
19
|
+
try {
|
|
20
|
+
const hit = fs.readdirSync(dir).find((d) => d.startsWith(`${name}-`) || d === name);
|
|
21
|
+
return hit ? path.join(dir, hit) : null;
|
|
22
|
+
} catch { return null; }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function historySnapshot(hub, name) {
|
|
26
|
+
const src = path.join(hub, 'skills', name);
|
|
27
|
+
const dst = historyDir(hub, name);
|
|
28
|
+
if (!fs.existsSync(src)) return false;
|
|
29
|
+
rmDir(dst);
|
|
30
|
+
fs.mkdirSync(path.dirname(dst), { recursive: true });
|
|
31
|
+
copyDirFs(src, dst);
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function historyRestore(hub, name) {
|
|
36
|
+
const dst = historyDir(hub, name);
|
|
37
|
+
const src = path.join(hub, 'skills', name);
|
|
38
|
+
if (!fs.existsSync(dst)) return false;
|
|
39
|
+
rmDir(src);
|
|
40
|
+
copyDirFs(dst, src);
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function copyDirFs(src, dst) {
|
|
45
|
+
fs.mkdirSync(dst, { recursive: true });
|
|
46
|
+
for (const e of fs.readdirSync(src, { withFileTypes: true })) {
|
|
47
|
+
const s = path.join(src, e.name), d = path.join(dst, e.name);
|
|
48
|
+
if (e.isDirectory()) copyDirFs(s, d); else fs.copyFileSync(s, d);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// yamlls.js — 目录下所有 yml 读成数组
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { readYAMLFile } from './hub.js';
|
|
5
|
+
|
|
6
|
+
export function listYAML(dir) {
|
|
7
|
+
try {
|
|
8
|
+
return fs.readdirSync(dir)
|
|
9
|
+
.filter((f) => /\.(ya?ml)$/.test(f))
|
|
10
|
+
.sort()
|
|
11
|
+
.map((f) => readYAMLFile(path.join(dir, f)))
|
|
12
|
+
.filter(Boolean);
|
|
13
|
+
} catch { return []; }
|
|
14
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// skillmkt SPA — no build. token from ?token=; SSE live updates.
|
|
2
|
+
const T = new URLSearchParams(location.search).get('token') || '';
|
|
3
|
+
const api = async (p, opt) => (await fetch(`/api${p}${p.includes('?') ? '&' : '?'}token=${T}`, { headers: { authorization: `Bearer ${T}` }, ...opt })).json();
|
|
4
|
+
const el = (h) => { const d = document.createElement('div'); d.innerHTML = h; return d.firstElementChild; };
|
|
5
|
+
const esc = (s) => String(s ?? '').replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' }[c]));
|
|
6
|
+
let S = null, tab = 'skills';
|
|
7
|
+
|
|
8
|
+
async function refresh() { S = await api('/state'); render(); }
|
|
9
|
+
document.querySelectorAll('.tab').forEach((t) => t.onclick = () => { document.querySelectorAll('.tab').forEach((x) => x.classList.remove('on')); t.classList.add('on'); tab = t.dataset.t; render(); });
|
|
10
|
+
const es = new EventSource(`/api/events?token=${T}`);
|
|
11
|
+
es.addEventListener('decide', () => refresh());
|
|
12
|
+
es.onopen = () => document.getElementById('live').textContent = '●live';
|
|
13
|
+
es.onerror = () => document.getElementById('live').textContent = '○offline';
|
|
14
|
+
|
|
15
|
+
const pill = (v) => `<span class="pill ${v === 'clean' || v === 'installed' || v === 'active' ? 'ok' : v === 'malicious' || v === 'pending' ? 'bad' : 'warn'}">${esc(v)}</span>`;
|
|
16
|
+
|
|
17
|
+
function render() {
|
|
18
|
+
const app = document.getElementById('app');
|
|
19
|
+
if (!S) return;
|
|
20
|
+
if (tab === 'skills') {
|
|
21
|
+
const skills = Object.entries(S.library.skills || {});
|
|
22
|
+
app.innerHTML = `<h3>installed (${skills.length})</h3>` + (skills.map(([n, s]) => `
|
|
23
|
+
<div class="card"><div class="row"><b>${esc(n)}</b><span class="mut">${esc(s.version || '-')}</span><span class="mut">${esc(s.source?.registry || '')}</span>${pill(s.audit || 'clean')}
|
|
24
|
+
<span class="mut" style="margin-left:auto">${(s.targets || []).join(', ') || 'no targets'}</span></div></div>`).join('') || '<p class="mut">none</p>');
|
|
25
|
+
app.innerHTML += `<h3>harnesses</h3>` + (S.harnesses || []).map((h) => `<div class="card row"><b>${esc(h.id)}</b>${pill(h.status)}<span class="mut">${esc(h.primaryDir || h.dirs?.[0] || '')}</span></div>`).join('');
|
|
26
|
+
const up = S.upstream.skills || {};
|
|
27
|
+
if (Object.keys(up).length) app.innerHTML += `<h3>upstream</h3>` + Object.entries(up).map(([n, u]) => `<div class="card row"><b>${esc(n)}</b>${u.outdated ? pill('outdated') : pill('clean')}<span class="mut">${esc(String(u.ref || '').slice(0, 8))}</span></div>`).join('');
|
|
28
|
+
}
|
|
29
|
+
if (tab === 'conflicts') {
|
|
30
|
+
const cs = S.conflicts || [];
|
|
31
|
+
app.innerHTML = `<h3>conflicts (${cs.filter((c) => c.status === 'pending').length} pending)</h3>`;
|
|
32
|
+
for (const c of cs) {
|
|
33
|
+
const card = el(`<div class="card"><div class="row"><b>${esc(c.id)}</b>${pill(c.status)}<span class="mut">${esc(c.domain || '')}</span></div>
|
|
34
|
+
<div class="side a">A [${esc(c.sides[0].source)}] ${esc(c.sides[0].text)}</div>
|
|
35
|
+
<div class="side b">B [${esc(c.sides[1].source)}] ${esc(c.sides[1].text)}</div>
|
|
36
|
+
${c.ai_explanation ? `<p class="mut">${esc(c.ai_explanation)}</p>` : ''}
|
|
37
|
+
<div class="ev-imgs"></div>
|
|
38
|
+
${c.status === 'pending' ? `<div class="row" style="margin-top:8px">
|
|
39
|
+
<button data-r="keep-a">keep A</button><button data-r="keep-b">keep B</button>
|
|
40
|
+
<button data-r="merge">merge…</button><button data-r="dismissed">误报</button></div>` : ''}</div>`);
|
|
41
|
+
if (c.evidence_files) card.querySelector('.ev-imgs').innerHTML = c.evidence_files.filter((f) => f.endsWith('.png')).map((f) => `<img class="ev" src="/evidence/${c.id}/${f}?token=${T}">`).join('');
|
|
42
|
+
card.querySelectorAll('button').forEach((b) => b.onclick = async () => {
|
|
43
|
+
let custom = null;
|
|
44
|
+
if (b.dataset.r === 'merge') { custom = prompt('合并文本:', `${c.sides[0].text} + ${c.sides[1].text}`); if (!custom) return; }
|
|
45
|
+
const reason = prompt('reason:', '') || 'web decision';
|
|
46
|
+
await api('/decide', { method: 'POST', body: JSON.stringify({ id: c.id, resolution: b.dataset.r, custom, reason }) });
|
|
47
|
+
refresh();
|
|
48
|
+
});
|
|
49
|
+
app.appendChild(card);
|
|
50
|
+
}
|
|
51
|
+
if (!cs.length) app.innerHTML += '<p class="mut">no conflicts — run skillmkt merge <a> <b></p>';
|
|
52
|
+
}
|
|
53
|
+
if (tab === 'review') {
|
|
54
|
+
app.innerHTML = `<h3>audit scans</h3>` + (S.scans || []).map((s) => `<div class="card row"><b>${esc(s.skill || s.name || '')}</b>${pill(s.verdict)}<span class="mut">${(s.findings || []).length} findings${s.llm ? ` · llm:${esc(s.llm.verdict)}` : ''}</span></div>`).join('') || '<p class="mut">none</p>';
|
|
55
|
+
}
|
|
56
|
+
if (tab === 'setup') {
|
|
57
|
+
const h = S.harnesses || [];
|
|
58
|
+
app.innerHTML = `<h3>setup</h3><div class="card">hub: <code>${esc(S.hub)}</code></div>
|
|
59
|
+
${h.map((x) => `<div class="card row"><b>${esc(x.id)}</b>${pill(x.status)}<span class="mut">${esc(x.primaryDir || '')}</span></div>`).join('')}
|
|
60
|
+
<p class="mut">CLI 是主操作面;本面板用于可视裁决与矩阵审阅。token 只在本地 daemon 生命周期内有效。</p>`;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
refresh();
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html><head><meta charset="utf-8"><title>skillmkt</title>
|
|
3
|
+
<style>
|
|
4
|
+
:root{color-scheme:dark;--bg:#0d1117;--fg:#e6edf3;--mut:#8b949e;--acc:#58a6ff;--warn:#d29922;--bad:#f85149;--ok:#3fb950;--card:#161b22;--brd:#30363d}
|
|
5
|
+
*{box-sizing:border-box}body{margin:0;font:14px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--bg);color:var(--fg)}
|
|
6
|
+
header{display:flex;gap:4px;align-items:center;padding:10px 16px;border-bottom:1px solid var(--brd)}
|
|
7
|
+
header b{margin-right:16px}.tab{padding:6px 14px;border-radius:6px;cursor:pointer;color:var(--mut)}
|
|
8
|
+
.tab.on{background:var(--card);color:var(--fg)}main{padding:16px;max-width:1100px}
|
|
9
|
+
.card{background:var(--card);border:1px solid var(--brd);border-radius:8px;padding:12px 14px;margin-bottom:10px}
|
|
10
|
+
table{width:100%;border-collapse:collapse}td,th{text-align:left;padding:4px 10px;border-bottom:1px solid var(--brd);font-size:13px}
|
|
11
|
+
th{color:var(--mut);font-weight:600}.mut{color:var(--mut)}.pill{display:inline-block;padding:1px 8px;border-radius:10px;font-size:11px;border:1px solid var(--brd)}
|
|
12
|
+
.pill.ok{color:var(--ok)}.pill.warn{color:var(--warn)}.pill.bad{color:var(--bad)}
|
|
13
|
+
button{background:#21262d;color:var(--fg);border:1px solid var(--brd);border-radius:6px;padding:5px 12px;cursor:pointer}
|
|
14
|
+
button:hover{border-color:var(--acc)}input,textarea{background:#0d1117;color:var(--fg);border:1px solid var(--brd);border-radius:6px;padding:6px 10px;width:100%;font:inherit}
|
|
15
|
+
.side{padding:8px 10px;border-left:3px solid var(--brd);margin:6px 0;font-size:13px}
|
|
16
|
+
.side.a{border-color:var(--acc)}.side.b{border-color:var(--warn)}img.ev{max-width:340px;border:1px solid var(--brd);border-radius:6px;margin:4px}
|
|
17
|
+
h3{margin:6px 0}.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
|
|
18
|
+
</style></head><body>
|
|
19
|
+
<header><b>skillmkt</b><span class="tab on" data-t="skills">skills</span><span class="tab" data-t="conflicts">conflicts</span><span class="tab" data-t="review">review</span><span class="tab" data-t="setup">setup</span><span id="live" class="mut" style="margin-left:auto"></span></header>
|
|
20
|
+
<main id="app">loading…</main>
|
|
21
|
+
<script src="/app.js"></script></body></html>
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "skillmkt",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Local-first agent skill manager: install, audit, merge, distribute.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": { "type": "git", "url": "https://github.com/terry2010/awesome-skill-market.git" },
|
|
8
|
+
"bugs": "https://github.com/terry2010/awesome-skill-market/issues",
|
|
9
|
+
"homepage": "https://github.com/terry2010/awesome-skill-market#readme",
|
|
10
|
+
"keywords": ["agent-skills", "skill-manager", "claude-code", "codex", "opencode", "devin", "skill-audit", "skill-merge", "anti-ai-slop"],
|
|
11
|
+
"bin": {
|
|
12
|
+
"skillmkt": "client/bin/skillmkt.js"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"client/",
|
|
16
|
+
"pipeline/lib/",
|
|
17
|
+
"skill/"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"skillmkt": "node client/bin/skillmkt.js",
|
|
21
|
+
"daemon": "node pipeline/daemon.js",
|
|
22
|
+
"once": "node pipeline/daemon.js --once",
|
|
23
|
+
"sync": "node pipeline/sync.js",
|
|
24
|
+
"extract": "node pipeline/extract.js",
|
|
25
|
+
"merge": "node pipeline/synthesize.js",
|
|
26
|
+
"synthesize": "node pipeline/synthesize.js",
|
|
27
|
+
"evidence": "node pipeline/evidence.js",
|
|
28
|
+
"issues": "node pipeline/issues.js",
|
|
29
|
+
"translate": "node pipeline/translate.js",
|
|
30
|
+
"poll": "node pipeline/poll.js",
|
|
31
|
+
"build": "node pipeline/build.js",
|
|
32
|
+
"decide": "node pipeline/decide.js",
|
|
33
|
+
"validate": "node pipeline/validate.js",
|
|
34
|
+
"setup": "npm install && npx playwright install chromium",
|
|
35
|
+
"test": "node --test \"test/**/*.test.js\""
|
|
36
|
+
},
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=22"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"yaml": "^2.6.1"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"playwright": "^1.49.0"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
|
|
5
|
+
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
|
|
6
|
+
|
|
7
|
+
const envFile = path.join(ROOT, '.env');
|
|
8
|
+
if (fs.existsSync(envFile)) {
|
|
9
|
+
try {
|
|
10
|
+
process.loadEnvFile(envFile);
|
|
11
|
+
} catch { /* tolerate malformed env file */ }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const CFG = {
|
|
15
|
+
baseUrl: (process.env.OMLX_BASE_URL || 'http://localhost:8001/v1').replace(/\/$/, ''),
|
|
16
|
+
apiKey: process.env.OMLX_API_KEY || '',
|
|
17
|
+
model: process.env.OMLX_MODEL || '',
|
|
18
|
+
githubRepo: process.env.GITHUB_REPO || '',
|
|
19
|
+
githubBranch: process.env.GITHUB_BRANCH || 'main',
|
|
20
|
+
intervalMin: Number(process.env.DAEMON_INTERVAL_MIN || 30),
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export const DIRS = {
|
|
24
|
+
work: path.join(ROOT, 'work'),
|
|
25
|
+
upstream: path.join(ROOT, 'work', 'upstream'),
|
|
26
|
+
extracted: path.join(ROOT, 'extracted'),
|
|
27
|
+
merged: path.join(ROOT, 'merged'),
|
|
28
|
+
conflicts: path.join(ROOT, 'conflicts'),
|
|
29
|
+
decisions: path.join(ROOT, 'decisions'),
|
|
30
|
+
evidence: path.join(ROOT, 'evidence'),
|
|
31
|
+
skill: path.join(ROOT, 'skill'),
|
|
32
|
+
lint: path.join(ROOT, 'lint'),
|
|
33
|
+
config: path.join(ROOT, 'config'),
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export const FILES = {
|
|
37
|
+
upstreams: path.join(DIRS.config, 'upstreams.json'),
|
|
38
|
+
lock: path.join(ROOT, 'upstream.lock.json'),
|
|
39
|
+
mergedRules: path.join(DIRS.merged, 'rules.yml'),
|
|
40
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { sh } from './util.js';
|
|
3
|
+
import { CFG } from './env.js';
|
|
4
|
+
|
|
5
|
+
/** gh api helper; returns parsed JSON. Retries transient failures (EOF/timeout). */
|
|
6
|
+
export function ghApi(path, { method = 'GET', fields = {} } = {}) {
|
|
7
|
+
const args = ['api', path, '-X', method];
|
|
8
|
+
for (const [k, v] of Object.entries(fields)) args.push('-f', `${k}=${v}`);
|
|
9
|
+
let lastErr;
|
|
10
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
11
|
+
try {
|
|
12
|
+
const out = sh('gh', args, { quiet: true });
|
|
13
|
+
return out ? JSON.parse(out) : null;
|
|
14
|
+
} catch (e) {
|
|
15
|
+
lastErr = e;
|
|
16
|
+
if (attempt < 2) execFileSync('sleep', [String(1 + attempt)]);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
throw lastErr;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function defaultBranch(repo) {
|
|
23
|
+
return ghApi(`repos/${repo}`).default_branch;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function headSha(repo) {
|
|
27
|
+
const b = defaultBranch(repo);
|
|
28
|
+
return ghApi(`repos/${repo}/commits/${b}`).sha;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function ensureLabels(repo, labels) {
|
|
32
|
+
const existing = new Set(
|
|
33
|
+
(ghApi(`repos/${repo}/labels?per_page=100`) || []).map((l) => l.name),
|
|
34
|
+
);
|
|
35
|
+
for (const { name, color, description } of labels) {
|
|
36
|
+
if (existing.has(name)) continue;
|
|
37
|
+
try {
|
|
38
|
+
ghApi(`repos/${repo}/labels`, { method: 'POST', fields: { name, color, description } });
|
|
39
|
+
} catch { /* race / perms: non-fatal */ }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function openIssuesWithLabel(repo, label) {
|
|
44
|
+
return ghApi(`repos/${repo}/issues?state=open&labels=${encodeURIComponent(label)}&per_page=100`) || [];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function createIssue(repo, { title, body, labels = [] }) {
|
|
48
|
+
const out = sh('gh', ['issue', 'create', '-R', repo, '--title', title, '--body', body, ...labels.flatMap((l) => ['--label', l])], { quiet: true });
|
|
49
|
+
return out.trim(); // issue URL
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export const rawURL = (repoPath) =>
|
|
53
|
+
`https://raw.githubusercontent.com/${CFG.githubRepo}/${CFG.githubBranch}/${repoPath}`;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { CFG } from './env.js';
|
|
2
|
+
import { log } from './util.js';
|
|
3
|
+
|
|
4
|
+
/** Extract the first JSON object/array from model output. Salvages truncated output:
|
|
5
|
+
* auto-closes dangling strings/brackets, and falls back to cutting at earlier comma
|
|
6
|
+
* boundaries so a malformed tail element can't sink the whole response. */
|
|
7
|
+
export function extractJSON(text) {
|
|
8
|
+
const start = text.search(/[{[]/);
|
|
9
|
+
if (start === -1) throw new Error('no JSON in output');
|
|
10
|
+
const stack = [];
|
|
11
|
+
const commas = [];
|
|
12
|
+
let inStr = false, esc = false;
|
|
13
|
+
for (let i = start; i < text.length; i++) {
|
|
14
|
+
const c = text[i];
|
|
15
|
+
if (inStr) {
|
|
16
|
+
if (esc) esc = false;
|
|
17
|
+
else if (c === '\\') esc = true;
|
|
18
|
+
else if (c === '"') inStr = false;
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
if (c === '"') inStr = true;
|
|
22
|
+
else if (c === '{' || c === '[') stack.push(c === '{' ? '}' : ']');
|
|
23
|
+
else if (c === '}' || c === ']') {
|
|
24
|
+
if (stack.pop() !== c) throw new Error(`unbalanced JSON at pos ${i}: ${JSON.stringify(text.slice(Math.max(0, i - 40), i + 40))}`);
|
|
25
|
+
if (stack.length === 0) return JSON.parse(text.slice(start, i + 1));
|
|
26
|
+
} else if (c === ',') commas.push(i);
|
|
27
|
+
}
|
|
28
|
+
// truncated or corrupted tail — build salvage candidates
|
|
29
|
+
const closersFor = (s) => {
|
|
30
|
+
const st = [];
|
|
31
|
+
let str = false, e2 = false;
|
|
32
|
+
for (const c of s) {
|
|
33
|
+
if (str) { if (e2) e2 = false; else if (c === '\\') e2 = true; else if (c === '"') str = false; continue; }
|
|
34
|
+
if (c === '"') str = true;
|
|
35
|
+
else if (c === '{' || c === '[') st.push(c === '{' ? '}' : ']');
|
|
36
|
+
else if (c === '}' || c === ']') st.pop();
|
|
37
|
+
}
|
|
38
|
+
return (str ? '"' : '') + st.reverse().join('');
|
|
39
|
+
};
|
|
40
|
+
const base = text.slice(start);
|
|
41
|
+
const attempts = [base + closersFor(base)];
|
|
42
|
+
for (let k = commas.length - 1; k >= 0 && attempts.length < 60; k--) {
|
|
43
|
+
const pre = base.slice(0, commas[k] - start);
|
|
44
|
+
attempts.push(pre + closersFor(pre));
|
|
45
|
+
}
|
|
46
|
+
for (const cand of attempts) {
|
|
47
|
+
try { return JSON.parse(cand); } catch { /* next boundary */ }
|
|
48
|
+
}
|
|
49
|
+
throw new Error(`unclosed JSON (${stack.length} open) tail: ${JSON.stringify(text.slice(-120))}`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function chat(messages, { temperature = 0, maxTokens = 8192, thinking = false } = {}) {
|
|
53
|
+
const body = {
|
|
54
|
+
model: CFG.model,
|
|
55
|
+
messages,
|
|
56
|
+
temperature,
|
|
57
|
+
max_tokens: maxTokens,
|
|
58
|
+
};
|
|
59
|
+
if (!thinking) body.chat_template_kwargs = { enable_thinking: false };
|
|
60
|
+
const res = await fetch(`${CFG.baseUrl}/chat/completions`, {
|
|
61
|
+
method: 'POST',
|
|
62
|
+
headers: {
|
|
63
|
+
'content-type': 'application/json',
|
|
64
|
+
authorization: `Bearer ${CFG.apiKey}`,
|
|
65
|
+
},
|
|
66
|
+
body: JSON.stringify(body),
|
|
67
|
+
});
|
|
68
|
+
if (!res.ok) throw new Error(`LLM ${res.status}: ${await res.text()}`);
|
|
69
|
+
const data = await res.json();
|
|
70
|
+
const choice = data.choices?.[0];
|
|
71
|
+
const out = choice?.message?.content;
|
|
72
|
+
if (!out) throw new Error(`empty LLM response (finish=${choice?.finish_reason ?? '?'})`);
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Ask the model for a JSON object matching `shapeDesc` (shown in prompt).
|
|
78
|
+
* Validates with `validate(obj)` -> true|string-error. Retries with the error fed back.
|
|
79
|
+
*/
|
|
80
|
+
export async function chatJSON({ system, user, shapeDesc, validate, temperature = 0, maxTokens = 8192, thinking = false, label = 'llm' }) {
|
|
81
|
+
const sys = `${system}\n\nRespond with ONE JSON object only. No markdown fences, no commentary.\nShape:\n${shapeDesc}`;
|
|
82
|
+
let err = '';
|
|
83
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
84
|
+
const u = attempt === 0 ? user : `${user}\n\nPrevious response was invalid: ${err}. Return corrected JSON only.`;
|
|
85
|
+
let raw;
|
|
86
|
+
try {
|
|
87
|
+
raw = await chat([{ role: 'system', content: sys }, { role: 'user', content: u }], { temperature, maxTokens, thinking });
|
|
88
|
+
const obj = extractJSON(raw);
|
|
89
|
+
const verr = validate?.(obj);
|
|
90
|
+
if (verr === true || verr === undefined || verr === null) return obj;
|
|
91
|
+
err = String(verr);
|
|
92
|
+
raw = null; // validated objects are fine; only dump on parse errors
|
|
93
|
+
} catch (e) {
|
|
94
|
+
err = e.message;
|
|
95
|
+
if (attempt === 2 && raw) {
|
|
96
|
+
try {
|
|
97
|
+
const { writeFileSync, mkdirSync } = await import('node:fs');
|
|
98
|
+
const { join } = await import('node:path');
|
|
99
|
+
const dir = join(process.cwd(), 'work');
|
|
100
|
+
mkdirSync(dir, { recursive: true });
|
|
101
|
+
writeFileSync(join(dir, `llm-raw-${label.replace(/[^\w-]/g, '_')}.txt`), raw);
|
|
102
|
+
} catch { /* diagnostics are best-effort */ }
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
log(`${label}: attempt ${attempt + 1} failed (${err})`);
|
|
106
|
+
}
|
|
107
|
+
throw new Error(`${label}: model failed 3 attempts (${err})`);
|
|
108
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import { execFileSync } from 'node:child_process';
|
|
5
|
+
import YAML from 'yaml';
|
|
6
|
+
|
|
7
|
+
export const log = (...a) => console.log(`[${new Date().toISOString().slice(11, 19)}]`, ...a);
|
|
8
|
+
|
|
9
|
+
export function readJSON(file, fallback = null) {
|
|
10
|
+
if (!fs.existsSync(file)) return fallback;
|
|
11
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function writeJSON(file, data) {
|
|
15
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
16
|
+
fs.writeFileSync(file, JSON.stringify(data, null, 2) + '\n');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function readYAML(file, fallback = null) {
|
|
20
|
+
if (!fs.existsSync(file)) return fallback;
|
|
21
|
+
return YAML.parse(fs.readFileSync(file, 'utf8'));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function writeYAML(file, data) {
|
|
25
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
26
|
+
fs.writeFileSync(file, YAML.stringify(data, { lineWidth: 0 }));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const sha1 = (s) => crypto.createHash('sha1').update(s).digest('hex').slice(0, 12);
|
|
30
|
+
|
|
31
|
+
/** Normalize rule text for hashing/similarity: lowercase, collapse punctuation/space. */
|
|
32
|
+
export const normText = (s) =>
|
|
33
|
+
String(s || '').toLowerCase().replace(/[`*_#>\-–—()[\]{}"',.;:!?/\\|]+/g, ' ').replace(/\s+/g, ' ').trim();
|
|
34
|
+
|
|
35
|
+
export const ruleHash = (text) => sha1(normText(text));
|
|
36
|
+
|
|
37
|
+
export function conflictFingerprint(sides) {
|
|
38
|
+
return sha1(sides.map((s) => s.text).map((t) => t.toLowerCase().replace(/\s+/g, ' ').trim()).sort().join('\n---\n'));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function* walk(dir, filter = () => true) {
|
|
42
|
+
if (!fs.existsSync(dir)) return;
|
|
43
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
44
|
+
const p = path.join(dir, e.name);
|
|
45
|
+
if (e.isDirectory()) yield* walk(p, filter);
|
|
46
|
+
else if (filter(p)) yield p;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export const listYAMLFiles = (dir) => [...walk(dir, (p) => /\.(ya?ml)$/.test(p))];
|
|
51
|
+
|
|
52
|
+
const STOP = new Set(('the a an and or of to in for on with without never always use when be is are not do does must should can will every each all any it its that this from by at as into no your you we they'.split(' ')));
|
|
53
|
+
|
|
54
|
+
export function tokens(text) {
|
|
55
|
+
return new Set(normText(text).split(' ').filter((t) => t.length > 2 && !STOP.has(t)));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function jaccard(a, b) {
|
|
59
|
+
if (!a.size || !b.size) return 0;
|
|
60
|
+
let i = 0;
|
|
61
|
+
for (const t of a) if (b.has(t)) i++;
|
|
62
|
+
return i / (a.size + b.size - i);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function sh(cmd, args, opts = {}) {
|
|
66
|
+
return execFileSync(cmd, args, { encoding: 'utf8', stdio: opts.quiet ? ['ignore', 'pipe', 'pipe'] : 'inherit', ...opts }).trim?.() ?? '';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function git(args, opts = {}) {
|
|
70
|
+
return sh('git', ['-C', opts.cwd || process.cwd(), ...args], { quiet: true, ...opts });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function gitDirty(cwd) {
|
|
74
|
+
return git(['status', '--porcelain'], { cwd }).length > 0;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function sleep(ms) {
|
|
78
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Run fn over items with at most `n` in flight. Results in input order. */
|
|
82
|
+
export async function mapPool(items, fn, n = 3) {
|
|
83
|
+
const out = new Array(items.length);
|
|
84
|
+
let i = 0;
|
|
85
|
+
await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => {
|
|
86
|
+
while (i < items.length) {
|
|
87
|
+
const idx = i++;
|
|
88
|
+
out[idx] = await fn(items[idx], idx);
|
|
89
|
+
}
|
|
90
|
+
}));
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function nextId(dir, prefix) {
|
|
95
|
+
let max = 0;
|
|
96
|
+
if (fs.existsSync(dir)) {
|
|
97
|
+
for (const f of fs.readdirSync(dir)) {
|
|
98
|
+
const m = f.match(new RegExp(`^${prefix}-(\\d+)`));
|
|
99
|
+
if (m) max = Math.max(max, Number(m[1]));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return `${prefix}-${String(max + 1).padStart(4, '0')}`;
|
|
103
|
+
}
|