opencode-skills-doctor 0.0.0-stage → 0.3.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.
@@ -0,0 +1,297 @@
1
+ import fs from "node:fs"
2
+ import path from "node:path"
3
+ import os from "node:os"
4
+ import { parseFrontmatter, estimateTokens, sha1 } from "./parse.mjs"
5
+
6
+ const CONFIG_FILES = ["opencode.jsonc", "opencode.json"]
7
+ const SKIP_DIRS = new Set(["node_modules", ".git", ".hg", ".svn", "dist", "build", ".venv", "__pycache__"])
8
+
9
+ export function expandHome(p, home = os.homedir()) {
10
+ if (p === "~") return home
11
+ if (p.startsWith("~/") || p.startsWith("~\\")) return path.join(home, p.slice(2))
12
+ return p
13
+ }
14
+
15
+ /** 去掉 JSONC 的注释和尾逗号,字符串内的内容不动。 */
16
+ export function stripJsonc(text) {
17
+ let out = ""
18
+ let inString = false
19
+ let escaped = false
20
+ let inLine = false
21
+ let inBlock = false
22
+
23
+ for (let i = 0; i < text.length; i++) {
24
+ const ch = text[i]
25
+ const next = text[i + 1]
26
+
27
+ if (inLine) {
28
+ if (ch === "\n") {
29
+ inLine = false
30
+ out += ch
31
+ }
32
+ continue
33
+ }
34
+ if (inBlock) {
35
+ if (ch === "*" && next === "/") {
36
+ inBlock = false
37
+ i++
38
+ }
39
+ continue
40
+ }
41
+ if (inString) {
42
+ out += ch
43
+ if (escaped) escaped = false
44
+ else if (ch === "\\") escaped = true
45
+ else if (ch === '"') inString = false
46
+ continue
47
+ }
48
+ if (ch === '"') {
49
+ inString = true
50
+ out += ch
51
+ continue
52
+ }
53
+ if (ch === "/" && next === "/") {
54
+ inLine = true
55
+ i++
56
+ continue
57
+ }
58
+ if (ch === "/" && next === "*") {
59
+ inBlock = true
60
+ i++
61
+ continue
62
+ }
63
+ out += ch
64
+ }
65
+
66
+ return out.replace(/,(\s*[}\]])/g, "$1")
67
+ }
68
+
69
+ export function readJsoncFile(file) {
70
+ const text = fs.readFileSync(file, "utf8").replace(/^\uFEFF/, "")
71
+ return JSON.parse(stripJsonc(text))
72
+ }
73
+
74
+ export function findProjectRoot(start) {
75
+ let dir = path.resolve(start)
76
+ for (;;) {
77
+ if (fs.existsSync(path.join(dir, ".git"))) return dir
78
+ const parent = path.dirname(dir)
79
+ if (parent === dir) return null
80
+ dir = parent
81
+ }
82
+ }
83
+
84
+ /** root 到 cwd 的路径链(远端在前,cwd 在最后)。 */
85
+ export function pathChain(root, cwd) {
86
+ const stop = path.resolve(root)
87
+ const start = path.resolve(cwd)
88
+ const rel = path.relative(stop, start)
89
+ if (rel.startsWith("..") || path.isAbsolute(rel)) return [start]
90
+
91
+ const chain = []
92
+ let dir = start
93
+ for (;;) {
94
+ chain.push(dir)
95
+ if (dir === stop) break
96
+ const parent = path.dirname(dir)
97
+ if (parent === dir) break
98
+ dir = parent
99
+ }
100
+ return chain.reverse()
101
+ }
102
+
103
+ function configCandidates(dir) {
104
+ return CONFIG_FILES.map((name) => path.join(dir, name))
105
+ }
106
+
107
+ /**
108
+ * 按官方文档的注册顺序返回 skill 来源(顺序即优先级,越后越高):
109
+ * 1. ~/.claude/skills
110
+ * 2. 项目 .claude/skills(远端 → cwd)
111
+ * 3. ~/.agents/skills
112
+ * 4. 项目 .agents/skills(远端 → cwd)
113
+ * 5. ~/.config/opencode/skills
114
+ * 6. 项目 .opencode/skills(项目根 → cwd)
115
+ * 7. opencode.json(c) 里的 skills 数组
116
+ */
117
+ export function discoverSources({ cwd = process.cwd(), home = os.homedir(), includeGlobal = true } = {}) {
118
+ const projectRoot = findProjectRoot(cwd) ?? path.resolve(cwd)
119
+ const projectChain = pathChain(projectRoot, cwd)
120
+ const sources = []
121
+ const catalogs = []
122
+ const missing = []
123
+ const seen = new Set()
124
+
125
+ const addSource = (kind, scope, dir) => {
126
+ const abs = path.resolve(dir)
127
+ if (seen.has(abs)) return
128
+ seen.add(abs)
129
+ sources.push({ kind, scope, dir: abs, order: sources.length })
130
+ }
131
+
132
+ if (includeGlobal) addSource("claude-global", "global", path.join(home, ".claude", "skills"))
133
+ for (const dir of projectChain) addSource("claude-project", "project", path.join(dir, ".claude", "skills"))
134
+
135
+ if (includeGlobal) addSource("agents-global", "global", path.join(home, ".agents", "skills"))
136
+ for (const dir of projectChain) addSource("agents-project", "project", path.join(dir, ".agents", "skills"))
137
+
138
+ if (includeGlobal) addSource("opencode-global", "global", path.join(home, ".config", "opencode", "skills"))
139
+ for (const dir of projectChain) addSource("opencode-project", "project", path.join(dir, ".opencode", "skills"))
140
+
141
+ const configFiles = []
142
+ if (includeGlobal) {
143
+ for (const file of configCandidates(path.join(home, ".config", "opencode"))) {
144
+ if (fs.existsSync(file)) configFiles.push(file)
145
+ }
146
+ }
147
+ for (const dir of projectChain) {
148
+ for (const file of configCandidates(dir)) {
149
+ if (fs.existsSync(file)) configFiles.push(file)
150
+ }
151
+ }
152
+
153
+ for (const file of configFiles) {
154
+ let config
155
+ try {
156
+ config = readJsoncFile(file)
157
+ } catch (err) {
158
+ missing.push({ kind: "config-error", path: file, error: err.message })
159
+ continue
160
+ }
161
+ const entries = Array.isArray(config?.skills) ? config.skills : []
162
+ for (const entry of entries) {
163
+ if (typeof entry !== "string" || !entry.trim()) continue
164
+ const value = entry.trim()
165
+ if (/^https?:\/\//i.test(value)) {
166
+ catalogs.push({ url: value, config: file })
167
+ continue
168
+ }
169
+ const expanded = expandHome(value, home)
170
+ const abs = path.isAbsolute(expanded) ? expanded : path.resolve(cwd, expanded)
171
+ if (fs.existsSync(abs)) addSource("config-path", "config", abs)
172
+ else missing.push({ kind: "missing-path", path: abs, entry: value, config: file })
173
+ }
174
+ }
175
+
176
+ return { sources, catalogs, missing, configs: configFiles, projectRoot }
177
+ }
178
+
179
+ function safeReaddir(dir) {
180
+ try {
181
+ return fs.readdirSync(dir, { withFileTypes: true })
182
+ } catch {
183
+ return []
184
+ }
185
+ }
186
+
187
+ function isSkippable(name) {
188
+ return name.startsWith(".") || SKIP_DIRS.has(name)
189
+ }
190
+
191
+ /** 跟随符号链接判断实际类型;坏链接返回 "broken"。 */
192
+ function direntKind(fullPath, entry) {
193
+ if (entry.isSymbolicLink()) {
194
+ try {
195
+ const stat = fs.statSync(fullPath)
196
+ if (stat.isDirectory()) return "dir"
197
+ if (stat.isFile()) return "file"
198
+ return "other"
199
+ } catch {
200
+ return "broken"
201
+ }
202
+ }
203
+ if (entry.isDirectory()) return "dir"
204
+ if (entry.isFile()) return "file"
205
+ return "other"
206
+ }
207
+
208
+ function walkForSkillMd(dir, source, out, depth, seen) {
209
+ if (depth > 8) return
210
+ let real
211
+ try {
212
+ real = fs.realpathSync(dir)
213
+ } catch {
214
+ return
215
+ }
216
+ if (seen.has(real)) return
217
+ seen.add(real)
218
+
219
+ for (const entry of safeReaddir(dir)) {
220
+ if (isSkippable(entry.name)) continue
221
+ const full = path.join(dir, entry.name)
222
+ const kind = direntKind(full, entry)
223
+ if (kind === "dir") {
224
+ walkForSkillMd(full, source, out, depth + 1, seen)
225
+ } else if (kind === "file" && entry.name === "SKILL.md") {
226
+ out.push(buildSkill({ id: path.basename(dir), file: full, source, form: "dir" }))
227
+ }
228
+ }
229
+ }
230
+
231
+ function buildSkill({ id, file, source, form }) {
232
+ let text = ""
233
+ try {
234
+ text = fs.readFileSync(file, "utf8")
235
+ } catch {
236
+ text = ""
237
+ }
238
+ const { data, body } = parseFrontmatter(text)
239
+ const autoinvoke = data?.metadata?.["opencode/autoinvoke"]
240
+ const disabled = data?.["disable-model-invocation"]
241
+ const description = typeof data.description === "string" ? data.description.trim() : ""
242
+ const displayName = typeof data.name === "string" && data.name.trim() ? data.name.trim() : id
243
+ const hidden = autoinvoke === false || disabled === true
244
+ let mtime = 0
245
+ try {
246
+ mtime = fs.statSync(file).mtimeMs
247
+ } catch {}
248
+
249
+ return {
250
+ id,
251
+ form,
252
+ file,
253
+ source,
254
+ order: source.order,
255
+ displayName,
256
+ description,
257
+ autoinvoke,
258
+ disabled,
259
+ hidden,
260
+ advertised: Boolean(description) && !hidden,
261
+ body,
262
+ bodyTokens: estimateTokens(body),
263
+ bytes: Buffer.byteLength(text),
264
+ descriptionTokens: estimateTokens(description),
265
+ hash: sha1(body.replace(/\s+/g, " ").trim()),
266
+ mtime,
267
+ }
268
+ }
269
+
270
+ export function scanSource(source) {
271
+ if (!fs.existsSync(source.dir)) return { source, skills: [], exists: false }
272
+ const stat = fs.statSync(source.dir)
273
+ if (!stat.isDirectory()) return { source, skills: [], exists: false }
274
+
275
+ const skills = []
276
+ for (const entry of safeReaddir(source.dir)) {
277
+ if (isSkippable(entry.name)) continue
278
+ const full = path.join(source.dir, entry.name)
279
+ const kind = direntKind(full, entry)
280
+ if (kind === "file" && /\.md$/i.test(entry.name)) {
281
+ const id = entry.name.replace(/\.md$/i, "")
282
+ skills.push(buildSkill({ id, file: full, source, form: "flat" }))
283
+ } else if (kind === "dir") {
284
+ walkForSkillMd(full, source, skills, 1, new Set())
285
+ }
286
+ }
287
+ return { source, skills, exists: true }
288
+ }
289
+
290
+ export function scanAll(discovered) {
291
+ const scans = discovered.sources.map(scanSource)
292
+ return {
293
+ ...discovered,
294
+ scans,
295
+ skills: scans.flatMap((s) => s.skills),
296
+ }
297
+ }
package/src/fix.mjs ADDED
@@ -0,0 +1,161 @@
1
+ import fs from "node:fs"
2
+ import path from "node:path"
3
+ import { resolveWinners } from "./lint.mjs"
4
+
5
+ export const ARCHIVE_DIR = ".skills-doctor-archive"
6
+
7
+ function collectSkillMds(dir, out = []) {
8
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
9
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue
10
+ const full = path.join(dir, entry.name)
11
+ let kind = entry.isDirectory() ? "dir" : entry.isFile() ? "file" : "other"
12
+ if (entry.isSymbolicLink()) {
13
+ try {
14
+ kind = fs.statSync(full).isDirectory() ? "dir" : "file"
15
+ } catch {
16
+ continue
17
+ }
18
+ }
19
+ if (kind === "dir") collectSkillMds(full, out)
20
+ else if (entry.name === "SKILL.md") out.push(full)
21
+ }
22
+ return out
23
+ }
24
+
25
+ function archiveTarget(skill, stamp) {
26
+ const sourceDir = skill.source.dir
27
+ const inner = skill.form === "dir" ? path.dirname(skill.file) : skill.file
28
+ const rel = path.relative(sourceDir, inner)
29
+ return path.join(sourceDir, ARCHIVE_DIR, stamp, rel)
30
+ }
31
+
32
+ /**
33
+ * 规划安全的结构性修复:只归档「被遮蔽、永远不会加载」的定义。
34
+ * 由更新器管理的文件不碰(应通过 update 恢复)。
35
+ */
36
+ export function planFixes(skills, managed = new Map(), { now = new Date() } = {}) {
37
+ const winners = resolveWinners(skills)
38
+ const byId = new Map()
39
+ for (const skill of skills) {
40
+ if (!byId.has(skill.id)) byId.set(skill.id, [])
41
+ byId.get(skill.id).push(skill)
42
+ }
43
+
44
+ const stamp = now.toISOString().replace(/[:.]/g, "-")
45
+ const plan = []
46
+ const skipped = []
47
+
48
+ for (const [id, defs] of byId) {
49
+ if (defs.length <= 1) continue
50
+ const winner = winners.get(id)
51
+ for (const loser of defs) {
52
+ if (loser === winner) continue
53
+ if (managed.has(loser.file)) {
54
+ skipped.push(loser)
55
+ continue
56
+ }
57
+ let from = loser.file
58
+ if (loser.form === "dir") {
59
+ const dir = path.dirname(loser.file)
60
+ // 目录里若还有别的 SKILL.md,只挪这一个文件,避免误伤其他 skill
61
+ from = collectSkillMds(dir).length > 1 ? loser.file : dir
62
+ }
63
+ plan.push({ id, from, file: loser.file, winner: winner.file, target: archiveTarget(loser, stamp) })
64
+ }
65
+ }
66
+
67
+ return { plan, skipped }
68
+ }
69
+
70
+ export function applyFixes(plan, { dryRun = false } = {}) {
71
+ const moved = []
72
+ const errors = []
73
+
74
+ for (const fix of plan) {
75
+ if (dryRun) {
76
+ moved.push(fix)
77
+ continue
78
+ }
79
+ try {
80
+ let target = fix.target
81
+ let n = 1
82
+ while (fs.existsSync(target)) target = `${fix.target}-${n++}`
83
+ fs.mkdirSync(path.dirname(target), { recursive: true })
84
+ fs.renameSync(fix.from, target)
85
+ moved.push({ ...fix, target })
86
+ } catch (err) {
87
+ errors.push({ ...fix, error: String(err?.message ?? err) })
88
+ }
89
+ }
90
+
91
+ return { moved, errors }
92
+ }
93
+
94
+ /** 在 frontmatter 里把 metadata.opencode/autoinvoke 设为 false。 */
95
+ export function setAutoinvokeFalse(text) {
96
+ const lines = text.split(/\r?\n/)
97
+ const snippet = ["metadata:", " opencode/autoinvoke: false"]
98
+ if (lines[0]?.trim() !== "---") return ["---", ...snippet, "---", ...lines].join("\n")
99
+
100
+ let end = -1
101
+ for (let i = 1; i < lines.length; i++) {
102
+ if (lines[i].trim() === "---") {
103
+ end = i
104
+ break
105
+ }
106
+ }
107
+ if (end === -1) return ["---", ...snippet, "---", ...lines].join("\n")
108
+
109
+ const fm = lines.slice(1, end)
110
+ const metaIdx = fm.findIndex((line) => /^metadata\s*:/.test(line.trim()))
111
+ if (metaIdx === -1) {
112
+ return [lines[0], ...fm, ...snippet, ...lines.slice(end)].join("\n")
113
+ }
114
+
115
+ const metaIndent = fm[metaIdx].length - fm[metaIdx].trimStart().length
116
+ let j = metaIdx + 1
117
+ while (j < fm.length && (fm[j].trim() === "" || fm[j].length - fm[j].trimStart().length > metaIndent)) j++
118
+
119
+ const block = fm.slice(metaIdx + 1, j)
120
+ let replaced = false
121
+ for (let k = 0; k < block.length; k++) {
122
+ if (/^\s*opencode\/autoinvoke\s*:/.test(block[k])) {
123
+ block[k] = " ".repeat(metaIndent + 2) + "opencode/autoinvoke: false"
124
+ replaced = true
125
+ }
126
+ }
127
+ if (!replaced) block.unshift(" ".repeat(metaIndent + 2) + "opencode/autoinvoke: false")
128
+
129
+ return [lines[0], ...fm.slice(0, metaIdx + 1), ...block, ...fm.slice(j), ...lines.slice(end)].join("\n")
130
+ }
131
+
132
+ /**
133
+ * 隐藏指定 ID 的 skill(给生效版本加 autoinvoke: false)。
134
+ * 用于给上下文预算减压:skill 仍可用 @id 手动加载。
135
+ */
136
+ export function hideSkills(skills, ids, { dryRun = false } = {}) {
137
+ const winners = resolveWinners(skills)
138
+ const wanted = [...new Set(ids)]
139
+ const changed = []
140
+ const errors = []
141
+ const missing = []
142
+
143
+ for (const id of wanted) {
144
+ const skill = winners.get(id)
145
+ if (!skill) {
146
+ missing.push(id)
147
+ continue
148
+ }
149
+ try {
150
+ if (!dryRun) {
151
+ const text = fs.readFileSync(skill.file, "utf8")
152
+ fs.writeFileSync(skill.file, setAutoinvokeFalse(text), "utf8")
153
+ }
154
+ changed.push({ id, file: skill.file })
155
+ } catch (err) {
156
+ errors.push({ id, file: skill.file, error: String(err?.message ?? err) })
157
+ }
158
+ }
159
+
160
+ return { changed, errors, missing }
161
+ }