@matrixfu/skill-set-manager 0.0.0-stage → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,237 @@
1
+ /**
2
+ * 生效清单生成(§7):项目目录 = 集条目(常驻经全局生效区可见,§5.3);
3
+ * 只对 managed 条目做增量;外来条目(含同名冲突)不进 plan、不动不删(ADR-0003);
4
+ * 悬空引用 warnMissing、不静默写入(§7.4)。
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { loadSet, RESIDENT_SLUG } from './sets.js';
9
+ import { resolveSkillTargets } from './resolver.js';
10
+ import { readManaged, writeManaged } from './managed.js';
11
+ import { readBinding } from './binding.js';
12
+ import { makeEntry, removeEntry, entryKind } from './linkx.js';
13
+ import { projectSkillsDir } from './paths.js';
14
+ import { diffPlan } from './plan.js';
15
+
16
+ export async function planEffective(roots, projectRoot, setSlug, { fs: fsImpl = fs } = {}) {
17
+ // 项目目录只放集条目;常驻经全局生效区可见(§5.3),display 口径的并集在 sets.effectiveNames。
18
+ // 期望口径必须与 readbackCheck/selfCheck 一致:集 ∪ 覆盖增 ∖ 覆盖减——否则重建/切换会
19
+ // 摘掉活动覆盖条目而覆盖标记仍在,自检反报「缺失」(活体回归两轮教训)。
20
+ const managed = readManaged(projectRoot, { fs: fsImpl });
21
+ const set = setSlug && setSlug !== RESIDENT_SLUG ? loadSet(roots, setSlug) : null;
22
+ let names = [...new Set(set?.skills ?? [])];
23
+ const ov = managed?.sessionOverride;
24
+ if (ov) {
25
+ const removed = new Set(ov.removed ?? []);
26
+ names = [...new Set([...names.filter((n) => !removed.has(n)), ...(ov.added ?? [])])];
27
+ }
28
+ const { targets, missing: unresolved } = await resolveSkillTargets(roots, projectRoot, names, { fs: fsImpl });
29
+ const skillsDir = projectSkillsDir(projectRoot);
30
+ const { add, remove, keep, warnMissing, warnForeign } = diffPlan({
31
+ names,
32
+ ledger: managed?.entries ?? {},
33
+ resolve: (name) => {
34
+ const t = targets.get(name);
35
+ return t ? { target: t.path, targetKind: t.kind, origin: t.origin } : null;
36
+ },
37
+ probe: (name) => {
38
+ const kDir = entryKind(path.join(skillsDir, name), { fs: fsImpl });
39
+ const kFile = entryKind(path.join(skillsDir, `${name}.md`), { fs: fsImpl });
40
+ return { onDisk: kDir !== 'missing' || kFile !== 'missing', kind: kDir === 'missing' ? kFile : kDir };
41
+ },
42
+ });
43
+ return { setSlug, add, remove, keep, warnMissing, warnForeign, missing: [...new Set([...unresolved, ...warnMissing])] };
44
+ }
45
+
46
+ /**
47
+ * plan.warnForeign / warnMissing → 用户可见文案(**唯一来源**)。
48
+ * claimHint = 「重新生成」场景:多一句「可用接管认领回台账」的处置指引。
49
+ */
50
+ export function describePlanWarnings(plan, { claimHint = false } = {}) {
51
+ return [
52
+ ...(plan.warnForeign ?? []).map((w) => {
53
+ const kind = w.kind === 'file' ? '文件' : '条目';
54
+ const tail = !claimHint
55
+ ? ',请改名或移除该条目后重试'
56
+ : (w.kind === 'junction' || w.kind === 'symlink'
57
+ ? '——与当前集同名,可用「接管」认领回台账'
58
+ : '——请改名或移除该条目后重试');
59
+ return `${w.name}: 生效目录已有同名${kind}(他人所有),未抢占未删除${tail}`;
60
+ }),
61
+ ...(plan.warnMissing ?? []).map((n) => `${n}: 库/生效区解析不到(悬空引用),未生成`),
62
+ ];
63
+ }
64
+
65
+ /** 直接写(崩溃即设计前提,§6.6):写前快照由 undo 层负责,这里只落盘。 */
66
+ export function applyPlan(projectRoot, plan, { fs: fsImpl = fs, claimHint = false } = {}) {
67
+ const managed = readManaged(projectRoot, { fs: fsImpl }) ?? { setSlug: null, entries: {}, sessionOverride: null };
68
+ const entries = { ...managed.entries };
69
+ const warnings = [];
70
+ const skillsDir = projectSkillsDir(projectRoot);
71
+ for (const item of plan.remove) {
72
+ removeEntry(path.join(skillsDir, item.name), item.kind, { fs: fsImpl });
73
+ delete entries[item.name];
74
+ }
75
+ for (const item of plan.add) {
76
+ const made = makeEntry(item.target, path.join(skillsDir, item.name), { fs: fsImpl });
77
+ entries[item.name] = { kind: made.kind, from: item.origin ?? item.target, ...(made.copied ? { copied: true } : {}), ...(made.flat ? { flat: true } : {}) };
78
+ if (made.copied) warnings.push(`${item.name}: 链接不可用,已复制(升级不自动传导,可「重新链接」)`);
79
+ }
80
+ warnings.push(...describePlanWarnings(plan, { claimHint }));
81
+ writeManaged(projectRoot, { setSlug: plan.setSlug ?? managed.setSlug, entries, sessionOverride: managed.sessionOverride }, { fs: fsImpl });
82
+ return { applied: { added: plan.add.length, removed: plan.remove.length, kept: plan.keep.length }, warnings };
83
+ }
84
+
85
+ /**
86
+ * 「按期望态收敛盘面」的唯一实现:plan + apply 两步。
87
+ * 收口前它是 7 处逐字相同的 `applyPlan(projectRoot, await planEffective(roots, projectRoot, slug))`
88
+ * (index.js bind/rebuild/reclaim/autoBind、pending.js restore/undo、lifecycle.js uninstall)。
89
+ */
90
+ export async function converge(roots, projectRoot, setSlug, { fs: fsImpl = fs, claimHint = false } = {}) {
91
+ const plan = await planEffective(roots, projectRoot, setSlug, { fs: fsImpl });
92
+ const { applied, warnings } = applyPlan(projectRoot, plan, { fs: fsImpl, claimHint });
93
+ return { plan, applied, warnings };
94
+ }
95
+
96
+ /** 读回自检原(§7.5;T5 的 selfCheck 在其上补外来条目/冻结绑定判定)。 */
97
+ export function readbackCheck(roots, projectRoot, setSlug, { override = null, fs: fsImpl = fs } = {}) {
98
+ const set = setSlug && setSlug !== RESIDENT_SLUG ? loadSet(roots, setSlug) : null;
99
+ // 期望态 = 集 ∪ 覆盖增 ∖ 覆盖减(§12.97 临时覆盖直接动目录)——漏算覆盖会把自家条目
100
+ // 报成「多出」(活体误报:session override 的 speckit-constitution)。
101
+ let expected = [...new Set(set?.skills ?? [])];
102
+ if (override) {
103
+ const removed = new Set(override.removed ?? []);
104
+ expected = [...new Set([...expected.filter((n) => !removed.has(n)), ...(override.added ?? [])])];
105
+ }
106
+ expected = expected.sort();
107
+ const actual = [];
108
+ let names2;
109
+ try { names2 = fsImpl.readdirSync(projectSkillsDir(projectRoot)); } catch { names2 = []; }
110
+ for (const n of names2) {
111
+ if (n.startsWith('.')) continue;
112
+ const kind = entryKind(path.join(projectSkillsDir(projectRoot), n), { fs: fsImpl });
113
+ if (kind === 'junction' || kind === 'dir' || kind === 'symlink') actual.push(n);
114
+ else if (kind === 'file' && n.endsWith('.md')) actual.push(n.slice(0, -3)); // flat 复制条目
115
+ }
116
+ const actualSet = new Set(actual);
117
+ return {
118
+ ok: expected.every((n) => actualSet.has(n)) && actual.length === expected.length,
119
+ expected,
120
+ actual: [...new Set(actual)].sort(),
121
+ missing: expected.filter((n) => !actualSet.has(n)),
122
+ extra: [...actualSet].filter((n) => !expected.includes(n)).sort(),
123
+ };
124
+ }
125
+
126
+ /**
127
+ * footer 徽标数据源(§7.5 + Review-Focus 1/2):
128
+ * - 冻结绑定:binding 指向已删除的技能集 → 清单原样保留、不再驱动、红标改绑。
129
+ * - 失效链接:managed 记录的条目在盘上已 missing。
130
+ * - 外来条目:盘上有、managed 没有——只报告不动手(ADR-0003)。
131
+ */
132
+ export function selfCheck(roots, projectRoot, { fs: fsImpl = fs } = {}) {
133
+ const binding = readBinding(projectRoot, { fs: fsImpl });
134
+ const managed = readManaged(projectRoot, { fs: fsImpl });
135
+ const base = { ok: true, missing: [], extra: [], foreign: [], brokenLinks: [], frozen: false, unbound: !binding?.setSlug, binding, setSlug: binding?.setSlug ?? null, detail: '' };
136
+ const override = managed?.sessionOverride ?? null;
137
+ const ovActive = !!(override?.added?.length || override?.removed?.length);
138
+ if (!binding || !binding.setSlug) {
139
+ // 未绑定但有会话覆盖:临时条目是自家条目(台账在),按「期望=覆盖新增」口径读回(设计 2026-10-28)
140
+ if (!ovActive) return { ...base, unbound: true, detail: '未绑定:插件不改动该项目' };
141
+ } else if (binding.setSlug !== RESIDENT_SLUG && !loadSet(roots, binding.setSlug)) {
142
+ return { ...base, ok: false, frozen: true, detail: `冻结绑定:技能集「${binding.setSlug}」已删除,生效清单原样保留,请改绑` };
143
+ }
144
+ const rc = readbackCheck(roots, projectRoot, binding?.setSlug ?? null, { override, fs: fsImpl });
145
+ const skillsDir = projectSkillsDir(projectRoot);
146
+ const entries = managed?.entries ?? {};
147
+ const brokenLinks = Object.keys(entries).filter((name) => {
148
+ const k = entryKind(path.join(skillsDir, entries[name].flat ? `${name}.md` : name), { fs: fsImpl });
149
+ return k === 'missing';
150
+ });
151
+ const foreign = [...new Set([...rc.actual, ...Object.keys(entries)])].filter((n) => !(n in entries)).sort(); // 盘上有、台账无 = 外来(即使名字恰与集重名也不当我托管)
152
+ // 未绑定:插件对该项目没有「期望清单」(ADR-0003 只认台账),盘上非台账条目一律归 foreign——
153
+ // 不得计成「多出」、不得把徽标拉红(设计 2026-10-28:未绑定 + 覆盖仍守「不改动该项目」口径)。
154
+ // 台账里确实属于插件、却不在本次覆盖新增里的条目仍算多出(插件自己漏在盘上的东西)。
155
+ const unboundNow = !binding?.setSlug;
156
+ const extra = unboundNow ? rc.extra.filter((n) => !foreign.includes(n)) : rc.extra;
157
+ const ok = unboundNow ? (rc.missing.length === 0 && brokenLinks.length === 0) : (rc.ok && brokenLinks.length === 0);
158
+ return {
159
+ ...base,
160
+ ok,
161
+ missing: rc.missing,
162
+ extra,
163
+ foreign,
164
+ brokenLinks,
165
+ detail: ok ? (binding?.setSlug ? '托管清单与目录一致' : '会话临时覆盖与目录一致') : [
166
+ rc.missing.length ? `缺失: ${rc.missing.join(', ')}` : '',
167
+ extra.length ? `多出: ${extra.join(', ')}` : '',
168
+ brokenLinks.length ? `失效链接: ${brokenLinks.join(', ')}` : '',
169
+ ].filter(Boolean).join(';'),
170
+ };
171
+ }
172
+
173
+ /** 路径归一化(Windows 大小写不敏感、末尾分隔符无关),用于比对链接真实目标。 */
174
+ const normPath = (p) => path.resolve(p).replace(/[\\/]+$/, '').toLowerCase();
175
+
176
+ /**
177
+ * 接管(认领)失配的自家条目。台账被上一代快照整体覆盖后(applyUndo 语义:pending.js 用
178
+ * 快照 entries 直接替换当前台账),本代链接全体降级成「外来」,planEffective 既不 add 也不
179
+ * remove → 「重新生成」永久空转(活体实锤 2026-10-27:盘上 16 条链接、台账 0 条,面板「多出」
180
+ * 红标点了重新生成毫无反应,且 warnings 被前端丢弃,用户连原因都看不到)。
181
+ * 口径:**只补台账、绝不动盘上条目**(ADR-0003「不动不删」在此同样成立),且只接管同时满足
182
+ * ①名字在本集期望清单(集 ∪ 覆盖增 ∖ 覆盖减)里、②盘上是链接(junction/symlink)、
183
+ * ③链接真实目标 = 该名字解析出的目标(库体或生效区本体)的条目。真目录、指向别处的链接、
184
+ * 不在本集里的条目一律 skipped 带理由——接管是「认领自己弄丢的东西」,不是「抢占别人的东西」。
185
+ */
186
+ export async function claimForeign(roots, projectRoot, { fs: fsImpl = fs } = {}) {
187
+ const claimed = [];
188
+ const skipped = [];
189
+ const binding = readBinding(projectRoot, { fs: fsImpl });
190
+ const managed = readManaged(projectRoot, { fs: fsImpl });
191
+ if (!binding?.setSlug) return { claimed, skipped, warnings: ['未绑定技能集:没有可接管的目标态'] };
192
+ const set = binding.setSlug !== RESIDENT_SLUG ? loadSet(roots, binding.setSlug) : null;
193
+ let names = [...new Set(set?.skills ?? [])];
194
+ const ov = managed?.sessionOverride;
195
+ if (ov) {
196
+ const removed = new Set(ov.removed ?? []);
197
+ names = [...new Set([...names.filter((n) => !removed.has(n)), ...(ov.added ?? [])])];
198
+ }
199
+ const { targets } = await resolveSkillTargets(roots, projectRoot, names, { fs: fsImpl });
200
+ const skillsDir = projectSkillsDir(projectRoot);
201
+ const entries = { ...(managed?.entries ?? {}) };
202
+ for (const name of names) {
203
+ if (name in entries) continue; // 台账已有:不是失配条目
204
+ const t = targets.get(name);
205
+ if (!t) { skipped.push({ name, reason: '库/生效区解析不到(悬空引用),未接管' }); continue; }
206
+ const p = path.join(skillsDir, name);
207
+ const kind = entryKind(p, { fs: fsImpl });
208
+ if (kind === 'missing') continue; // 盘上没有 = 「缺失」,归重新生成重建,不是接管对象
209
+ if (kind !== 'junction' && kind !== 'symlink') {
210
+ skipped.push({ name, reason: `盘上是${kind === 'file' ? '文件' : '真实目录'}(他人所有),未接管` });
211
+ continue;
212
+ }
213
+ let real;
214
+ try { real = fsImpl.realpathSync(p); } catch { real = null; } // 死链/无权限
215
+ if (!real || normPath(real) !== normPath(t.path)) {
216
+ skipped.push({ name, reason: `链接指向 ${real ?? '未知(死链)'},不是「${name}」的解析目标 ${t.path},未接管` });
217
+ continue;
218
+ }
219
+ entries[name] = { kind, from: t.origin ?? t.path };
220
+ claimed.push({ name, kind, from: t.origin ?? t.path, target: t.path });
221
+ }
222
+ // 盘上其余外来条目(不在本集清单里):一律不接管,但如实报出理由——面板据此解释「为什么没动」,
223
+ // 不再把「点了重新生成毫无反应」留给用户自己猜(活体复盘 2026-10-27)。
224
+ const rc = readbackCheck(roots, projectRoot, binding.setSlug, { override: ov, fs: fsImpl });
225
+ const inPlan = new Set(names);
226
+ for (const n of rc.actual) {
227
+ if (inPlan.has(n) || n in entries || skipped.some((s) => s.name === n)) continue;
228
+ skipped.push({ name: n, reason: '不在当前集合的清单里(不接管:要保留就把它加入集合,要清掉就摘链接)' });
229
+ }
230
+ if (claimed.length)
231
+ writeManaged(projectRoot, { setSlug: managed?.setSlug ?? binding.setSlug, entries, sessionOverride: managed?.sessionOverride ?? null }, { fs: fsImpl });
232
+ const warnings = [
233
+ ...claimed.map((c) => `${c.name}: 已接管进托管台账(盘上条目未改动)`),
234
+ ...skipped.map((s) => `${s.name}: ${s.reason}`),
235
+ ];
236
+ return { claimed, skipped, warnings };
237
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * git 失败信息口径(用户报告 2026-10-26:库「检查更新」只报出
3
+ * `warning: ----------------- SECURITY WARNING ----------------`)。
4
+ *
5
+ * stderr **首行**未必是真因:本机 git 全局 `http.sslVerify=false` 时,Git Credential
6
+ * Manager 每次 https 传输都先打 4 行 TLS 告警横幅,真结论(`fatal:`/`error:`)在其后。
7
+ * 只报首行 = 把「仓库不存在」显示成安全告警,用户据此误判成 GitHub 授权失败。
8
+ *
9
+ * 取法(从 stderr 里挑 git 自己的结论,不改 git 调用):
10
+ * 1) spawnSync 起不动(本机没装 git 等)→ r.error;
11
+ * 2) 最后一条 `fatal:`/`error:` 行(git 的真结论,remote 提示只是它的注脚);
12
+ * 3) 否则最后一条非空行(有些 git 版本只写 warning 级结论);
13
+ * 4) 全空 → 退出码。
14
+ * 叶子模块:github(稀疏拉取)与 updates(ls-remote)共用,不放任两处各写一份口径。
15
+ */
16
+ export function gitFailMessage(args, r) {
17
+ const head = `git ${String(args?.[0] ?? '').trim() || 'git'} failed`;
18
+ if (r?.error) return `${head}: ${String(r.error?.message ?? r.error)}`;
19
+ const lines = String(r?.stderr ?? '').split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
20
+ const verdict = [...lines].reverse().find((l) => /^(fatal|error):/i.test(l));
21
+ return `${head}: ${verdict || lines[lines.length - 1] || `exit ${r?.status ?? '未知'}`}`;
22
+ }
@@ -0,0 +1,256 @@
1
+ /**
2
+ * GitHub 稀疏安装(§8.3):格式 = owner/repo[@ref][/subpath](仿 dsh-skills-marketplace
3
+ * 「仓库+分支+稀疏路径」,实现格式自定、不依赖其代码);detached commit SHA 记录进
4
+ * manifest。git 一律注入(测试 file:// 夹具免网络;缺失/网络错归一为业务错上抛)。
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { createHash } from 'node:crypto';
9
+ import { spawn, spawnSync } from 'node:child_process';
10
+ import { writeSkillManifest, rootSkillName } from './manifest.js';
11
+ import { gitFailMessage } from './giterr.js';
12
+ import { classifyAttempt } from './gitnet.js';
13
+
14
+ /** 来源解析与归一在叶子模块 source.js(github 与 manifest 共用,避免 ESM 环);此处转发保持既有 import 不变。 */
15
+ export { parseRepoSpec, normalizeRepoSource } from './source.js';
16
+
17
+ /**
18
+ * 异步 git 子进程(2026-11-19 异步化,用户报:批量检查更新在飞的几分钟里整机冻结——
19
+ * spawnSync 把 host 事件循环占满整段 git,新建对话/刷 Git 状态全部排队等它)。
20
+ * timeoutMs 超时 kill,结论归一 `spawn git ETIMEDOUT`(gitnet 可重试口径);kill 后
21
+ * 存活的孙进程仍归 sweepGitOrphans 口径管。resolve 与注入 git 夹具同形
22
+ * {status,stdout,stderr},调用方只多一个 await。
23
+ */
24
+ function spawnGit(args, cwd, timeoutMs) {
25
+ return new Promise((resolve) => {
26
+ let settled = false;
27
+ const finish = (r) => { if (!settled) { settled = true; resolve(r); } };
28
+ let child;
29
+ try { child = spawn('git', args, { cwd, windowsHide: true }); }
30
+ catch (e) { return finish({ status: 'spawn', stdout: '', stderr: String(e?.message ?? e) }); }
31
+ let stdout = ''; let stderr = '';
32
+ child.stdout?.setEncoding('utf8'); child.stderr?.setEncoding('utf8');
33
+ child.stdout?.on('data', (c) => { stdout += c; });
34
+ child.stderr?.on('data', (c) => { stderr += c; });
35
+ const timer = timeoutMs > 0 ? setTimeout(() => {
36
+ try { child.kill('SIGKILL'); } catch {}
37
+ finish({ status: 'spawn', stdout, stderr: `${stderr ? stderr + '\n' : ''}spawn git ETIMEDOUT` });
38
+ }, timeoutMs) : null;
39
+ timer?.unref?.();
40
+ child.on('error', (e) => { if (timer) clearTimeout(timer); finish({ status: 'spawn', stdout: '', stderr: String(e?.message ?? e) }); });
41
+ child.on('close', (code) => { if (timer) clearTimeout(timer); finish({ status: code ?? 'killed', stdout, stderr }); });
42
+ });
43
+ }
44
+
45
+ /**
46
+ * 带硬超时的默认 git 工厂(2026-11-17 加固;2026-11-19 异步化,见 spawnGit 注释——
47
+ * **不得回退 spawnSync**,它会占满 host 事件循环整段 git 时长)。注入 git 的调用方
48
+ * (verify 夹具)自理超时;updates.js 的 ls-remote 也复用本工厂。
49
+ */
50
+ export function makeGit(timeoutMs) {
51
+ return (args, cwd) => spawnGit(args, cwd, timeoutMs || 0);
52
+ }
53
+
54
+ /** 上游缓存底(GLOSSARY「上游缓存」):owner/repo(+ref) 哈希定键;同仓不同 ref 不串底。 */
55
+ export function cacheDirFor(roots, spec) {
56
+ const key = `${spec.owner}/${spec.repo}@${spec.ref || ''}`;
57
+ const hash = createHash('sha1').update(key).digest('hex').slice(0, 8);
58
+ return path.join(roots.cacheDir, `${spec.owner}-${spec.repo}-${hash}`);
59
+ }
60
+
61
+ /** 目录树整拷(无 manifest 语义;T3 备份/恢复复用)。 */
62
+ export function copyDirTree(src, dst, fsImpl = fs) {
63
+ fsImpl.mkdirSync(dst, { recursive: true });
64
+ for (const ent of fsImpl.readdirSync(src, { withFileTypes: true })) {
65
+ const s = path.join(src, ent.name);
66
+ const d = path.join(dst, ent.name);
67
+ if (ent.isDirectory()) copyDirTree(s, d, fsImpl);
68
+ else if (ent.isFile()) fsImpl.writeFileSync(d, fsImpl.readFileSync(s));
69
+ }
70
+ }
71
+
72
+ /** 检出根 → 库条目(根即技能的单技能仓库):逐顶层条目拷,唯独跳过 `.git` 对象库——
73
+ * 技能本体里的点文件(.github/.gitignore…)照拷,与「一层子目录」路径口径一致。 */
74
+ function copyRepoRoot(src, dst, fsImpl = fs) {
75
+ fsImpl.mkdirSync(dst, { recursive: true });
76
+ for (const ent of fsImpl.readdirSync(src, { withFileTypes: true })) {
77
+ if (ent.name === '.git') continue;
78
+ const s = path.join(src, ent.name);
79
+ const d = path.join(dst, ent.name);
80
+ if (ent.isDirectory()) copyDirTree(s, d, fsImpl);
81
+ else if (ent.isFile()) fsImpl.writeFileSync(d, fsImpl.readFileSync(s));
82
+ }
83
+ }
84
+
85
+ /**
86
+ * 稀疏拉取(2026-11-17 加固版):在 `dir`(可持久缓存底)上 init(缺底时)+ remote add +
87
+ * fetch --depth 1 --filter=blob:none origin <ref|HEAD> + sparse-checkout(有 subpath 时)+
88
+ * checkout -q -f --detach FETCH_HEAD。返回 {commit, skillsDir}。
89
+ * - 已有 `.git` 底 → 不 init/不 remote add,只 `remote set-url` 对齐后增量 fetch
90
+ * (GLOSSARY「上游缓存」:每次仍真 fetch 最新,缓存只是传输层复用)。
91
+ * - `checkout -f`:上次超时被 kill 留下的脏 worktree 下次自愈。
92
+ * - fetch 步骤:网络类失败(gitnet 分类)自动重试一次,每次失败进 failLog;真因不重试。
93
+ * - `timeoutMs` 走 makeGit 硬超时(代理半死不吊死);注入 git 的夹具自理。
94
+ */
95
+ /** 清 git 尸(活体实测 2026-11-17):spawnSync 超时 kill 只杀 git.exe,孙进程 git-remote-https
96
+ * 存活且继承持锁句柄(index.lock 删不掉 EPERM、半尸目录删不掉),实测可挂 20+ 分钟,
97
+ * 期间该缓存仓每次检查秒红。长任务单飞口径(GLOSSARY「长任务」全局只允许一个)下,
98
+ * 撞到这个状态时清掉所有 git* 进程是正当修法:git.exe 是瞬态工具,编辑器/终端的 git 会被
99
+ * 自动重试,代价远小于「缓存仓永红且重试不自愈」。POSIX 下 kill 自带进程组语义,不清。 */
100
+ function sweepGitOrphans() {
101
+ if (process.platform !== 'win32') return;
102
+ const cmd = "Get-Process git,git-remote-https -ErrorAction SilentlyContinue | Stop-Process -Force";
103
+ for (const shell of ['pwsh', 'powershell']) { // 终审 St6:PS7 缺失回落 Windows PowerShell,不再静默 no-op
104
+ try {
105
+ const r = spawnSync(shell, ['-NoProfile', '-NonInteractive', '-Command', cmd], { timeout: 8000, windowsHide: true, encoding: 'utf8' });
106
+ if (!r?.error) break; // 起得来(不论退出码);只有 shell 本身 ENOENT 才换下一个
107
+ } catch {}
108
+ }
109
+ }
110
+
111
+ export async function fetchRepo(spec, { dir, git, url, timeoutMs, failLog, sweepOrphans = sweepGitOrphans } = {}) {
112
+ const repoUrl = url ?? `https://github.com/${spec.owner}/${spec.repo}.git`;
113
+ const runner = git ?? makeGit(timeoutMs);
114
+ const run = async (args) => {
115
+ let r;
116
+ // 强制 LF:autocrlf 机器上检出 CRLF 会使逐文件哈希随行尾漂移(manifest 不可移植)。
117
+ try { r = await runner(['-c', 'core.autocrlf=false', '-c', 'core.eol=lf', ...args], dir); }
118
+ catch (e) { throw new Error(`git ${args[0]} failed: ${e?.message ?? e}`); }
119
+ if (!r || r.status !== 0) throw new Error(gitFailMessage(args, r));
120
+ return r;
121
+ };
122
+ // 半尸自愈(活体实测 2026-11-17:git init 被硬超时 kill 留下无 HEAD 的空 .git,
123
+ // existsSync(.git) 为真会跳过 init,此后 remote set-url 秒报 not a git repository 永红):
124
+ // `.git/HEAD` 是 init 成功落盘的验收件,缺了即半尸——缓存底归我们所有,整目录推倒重建。
125
+ if (fs.existsSync(path.join(dir, '.git')) && !fs.existsSync(path.join(dir, '.git', 'HEAD'))) {
126
+ try { fs.rmSync(dir, { recursive: true, force: true }); }
127
+ catch { sweepOrphans(); try { fs.rmSync(dir, { recursive: true, force: true }); } catch {} }
128
+ }
129
+ fs.mkdirSync(dir, { recursive: true });
130
+ if (fs.existsSync(path.join(dir, '.git'))) {
131
+ try { await run(['remote', 'set-url', 'origin', repoUrl]); } // url 覆盖夹具/换 remote 都对齐
132
+ catch (e) { // 终审 St5:init 成功但 remote add 被超时 kill(HEAD 在、origin 缺)→
133
+ // set-url 报 No such remote(非可重试),回落 add,绝不落「该缓存仓永红」
134
+ if (!/No such remote/i.test(String(e?.message ?? e))) throw e;
135
+ await run(['remote', 'add', 'origin', repoUrl]);
136
+ }
137
+ } else {
138
+ await run(['init', '-q']);
139
+ await run(['remote', 'add', 'origin', repoUrl]);
140
+ }
141
+ // partial clone(用户报告 2026-10-26:大仓库检查更新报「invalid index-pack output」):
142
+ // 整仓 depth-1 也要把**全部 blob** 压成一个 pack(diagram-design 那种带素材的仓库最容易炸),
143
+ // 改 --filter=blob:none 只取树对象,blob 交给下面的 sparse-checkout 按需拉。
144
+ // 只有「服务器/老 git 不认 filter」才退回全量拉法;真因(仓库不存在)不重试——
145
+ // 慢网络下重试等于把等待翻倍(verify 有「非 filter 失败只拉一次」断言);
146
+ // 网络类(RPC failed/超时等,gitnet 口径)重试一次,失败各进 failLog。
147
+ const attemptFetch = async (filtered) => {
148
+ const bare = ['fetch', '--depth', '1', ...(filtered ? ['--filter=blob:none'] : []), 'origin', spec.ref || 'HEAD'];
149
+ const fetchArgs = ['-c', 'core.autocrlf=false', '-c', 'core.eol=lf', ...bare];
150
+ for (let attempt = 1; attempt <= 2; attempt++) {
151
+ const t0 = Date.now();
152
+ let r;
153
+ try { r = await runner(fetchArgs, dir); }
154
+ catch (e) { r = { status: 'spawn', stdout: '', stderr: String(e?.message ?? e) }; }
155
+ const v = classifyAttempt({ cmd: 'fetch', args: bare, r, t0, failLog, attempt }); // head 用裸 args:-c 前缀不进结论(gitFailMessage 口径=命令名)
156
+ if (v.ok) return;
157
+ if (!v.retry) {
158
+ const err = new Error(v.msg);
159
+ err.filterUnrecognized = /filter/i.test(v.msg); // 调用方据此决定退不退全量
160
+ throw err;
161
+ }
162
+ }
163
+ };
164
+ try { await attemptFetch(true); }
165
+ catch (e) { if (!e?.filterUnrecognized) throw e; await attemptFetch(false); }
166
+ // sparse-checkout/checkout 层同样走「网络类重试一次 + 留痕」(Review Focus #2):
167
+ // blob:none 的 blob 下载发生在 checkout 时,大素材仓库(hyperframes)吊死在这层,
168
+ // 与 fetch 层同款形状;两步皆幂等(set 可重入、detach -f 可重来),重试安全。
169
+ // 陈旧锁自愈每次 attempt 前都清(活体实测 2026-11-17:60s kill checkout 留 index.lock 尸,
170
+ // checkout -f 对它无解——只在开头清一次,重试必撞尸秒败,重试形同虚设);
171
+ // 长任务单飞口径(GLOSSARY「长任务」全局只允许一个)保证此刻必无活 git 在动这底,撞锁必是尸。
172
+ const runLogged = async (cmd, args) => {
173
+ for (let attempt = 1; attempt <= 2; attempt++) {
174
+ try { fs.rmSync(path.join(dir, '.git', 'index.lock'), { force: true }); }
175
+ catch { sweepOrphans(); try { fs.rmSync(path.join(dir, '.git', 'index.lock'), { force: true }); } catch {} }
176
+ const t0 = Date.now();
177
+ let r;
178
+ try { r = await runner(['-c', 'core.autocrlf=false', '-c', 'core.eol=lf', ...args], dir); }
179
+ catch (e) { r = { status: 'spawn', stdout: '', stderr: String(e?.message ?? e) }; }
180
+ const v = classifyAttempt({ cmd, args, r, t0, failLog, attempt }); // head 用裸 args(-c 前缀不进结论)
181
+ if (v.ok) return r;
182
+ if (!v.retry) {
183
+ // 锁清不掉 = 孤儿 git-remote-https 继承了持锁句柄(活体实测 2026-11-17:spawnSync
184
+ // 超时 kill 只杀 git.exe,孙进程 remote-https 存活且继承 index.lock 句柄,rmSync 吃 EPERM):
185
+ // 孤儿自己死掉后「重试失败仓库」就能过——给人话指路,别让人去翻 .git。
186
+ if (/index\.lock/.test(v.msg)) throw new Error(`${v.msg} ——锁被上次超时的残留进程占着,稍后用「重试失败仓库」再试`);
187
+ throw new Error(v.msg);
188
+ }
189
+ }
190
+ };
191
+ if (spec.subpath) await runLogged('sparse-checkout', ['sparse-checkout', 'set', '--', spec.subpath]);
192
+ await runLogged('checkout', ['checkout', '-q', '-f', '--detach', 'FETCH_HEAD']);
193
+ const commit = (await run(['rev-parse', 'FETCH_HEAD'])).stdout.trim();
194
+ return { commit, skillsDir: path.join(dir, ...(spec.subpath ? spec.subpath.split('/') : [])) };
195
+ }
196
+
197
+ /**
198
+ * 装入技能库:一层扫描含 SKILL.md 的目录(嵌套不追);no-clobber——库同名默认跳过
199
+ * (reason:'exists'),overwrite 必须先 backup(name) 再替换(ADR-0003 / Review Focus #2)。
200
+ * 每个成功项写 manifest(source/commit)。
201
+ * 一层候选为空时回退认「检出根即技能」的单技能仓库(SKILL.md 在检出根,库名 = frontmatter name,
202
+ * 见 rootSkillName);两种空手都报业务错——技能在子目录 → 指路稀疏路径,根 SKILL.md 无合法 name →
203
+ * 指路 frontmatter,绝不静默返回空结果(UI 会显示「安装完成」而库里没装)。
204
+ */
205
+ export async function installSkills(roots, { source, commit, skillsDir, names = null, overwrite = false, backup, fs: fsImpl = fs } = {}) {
206
+ const out = [];
207
+ const seen = new Set(); // names 里上游不存在的名字必须报 not-found,不得静默吞(review n2)
208
+ let entries;
209
+ try { entries = fsImpl.readdirSync(skillsDir, { withFileTypes: true }); }
210
+ catch { throw new Error(`技能目录不存在: ${skillsDir}`); }
211
+ /** 落一个技能:no-clobber / overwrite 先备份再替换 / 整树拷 / 写 manifest(source+commit)。 */
212
+ const place = async (name, src, copy = copyDirTree) => {
213
+ const dst = path.join(roots.libraryRoot, name);
214
+ let exists = false;
215
+ try { fsImpl.statSync(dst); exists = true; } catch {}
216
+ if (exists && !overwrite) { out.push({ name, ok: false, reason: 'exists' }); return; }
217
+ if (exists && overwrite) {
218
+ if (backup) await backup(name);
219
+ fsImpl.rmSync(dst, { recursive: true, force: true });
220
+ }
221
+ copy(src, dst, fsImpl);
222
+ writeSkillManifest(dst, { source, commit, fs: fsImpl });
223
+ out.push({ name, ok: true });
224
+ };
225
+ for (const ent of entries) {
226
+ if (ent.name.startsWith('.') || !ent.isDirectory()) continue;
227
+ const name = ent.name;
228
+ if (names && !names.includes(name)) continue;
229
+ const src = path.join(skillsDir, name);
230
+ try { fsImpl.statSync(path.join(src, 'SKILL.md')); } catch { continue; }
231
+ seen.add(name);
232
+ await place(name, src);
233
+ }
234
+ // 检出根即技能(单技能仓库:SKILL.md 直接在检出根,没有「一层目录 = 一个技能」那层)。
235
+ // 用户报告 2026-10-30:Moessif/code-video-showcase 粘仓库根 → 一层扫描(assets/ references/
236
+ // templates/ 都不含 SKILL.md)空手 → 库里什么都没装、检查更新也定位不到上游。只在候选为空时
237
+ // 下探检出根自身;库名 = frontmatter name(rootSkillName 口径,与 updates.js 定位上游同一条规则),
238
+ // 无合法 name 一律报真因、不猜仓库名。检出根的 .git 对象库不跟进库(copyRepoRoot)。
239
+ if (out.length === 0) {
240
+ const rootName = rootSkillName(skillsDir, { fs: fsImpl });
241
+ let rootHasSkillMd = false;
242
+ try { fsImpl.statSync(path.join(skillsDir, 'SKILL.md')); rootHasSkillMd = true; } catch {}
243
+ if (!names && rootHasSkillMd && !rootName)
244
+ throw new Error(`检出根含 SKILL.md 但 frontmatter 无合法 kebab-case name:${skillsDir}——请在 SKILL.md 写明 name(库条目名与更新认领都以它为准)`);
245
+ if (rootName && (!names || names.includes(rootName))) {
246
+ seen.add(rootName);
247
+ await place(rootName, skillsDir, copyRepoRoot);
248
+ }
249
+ }
250
+ if (names) for (const n of names) if (!seen.has(n)) out.push({ name: n, ok: false, reason: 'not-found' });
251
+ // 0 个可安装技能 ≠ 成功(用户报告 2026-10-30:粘贴仓库根而技能在 skills/ 子目录,一层扫描空手
252
+ // → results=[] → 任务照常 ok,UI 显示「安装完成」但库里什么都没装)。names 为空时空扫描 = 来源
253
+ // 与「目录名即技能名」口径差一层,必须报业务错并指路稀疏路径,不得静默当成功。
254
+ if (!names && out.length === 0) throw new Error(`上游未找到可安装技能:${skillsDir} 的一层目录中没有直接含 SKILL.md 的技能目录;若技能在仓库子目录(如 skills/),请在来源加稀疏路径 owner/repo[/subpath]`);
255
+ return out;
256
+ }
@@ -0,0 +1,35 @@
1
+ /** .gitignore 署名行(§7.6):幂等追加;开关关闭不写也不删用户已有内容。 */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { writeTextAtomic } from './atomic.js';
5
+
6
+ export const GITIGNORE_MARKER = '# skill-set-manager: project skill entries (managed)';
7
+ export const GITIGNORE_ENTRY = '.agents/skills/'; // 项目生效目录(2026-10-30 迁至 .agents/skills)
8
+ export const GITIGNORE_LEGACY_ENTRY = '.dsh/skills/'; // 2026-10-30 前的署名条目:升级时原地改写
9
+
10
+ export function ensureGitignoreLine(projectRoot, { enabled = true } = {}, { fs: fsImpl = fs } = {}) {
11
+ const file = path.join(projectRoot, '.gitignore');
12
+ if (!enabled) return { changed: false, line: GITIGNORE_MARKER }; // 不写不删(他人所有)
13
+ let text = '';
14
+ let existed = true;
15
+ try { text = fsImpl.readFileSync(file, 'utf8'); } catch (e) { if (e.code !== 'ENOENT') throw e; existed = false; }
16
+ // 幂等 = 条目行已在(用户自己的 .agents/skills/ 行同样视为已生效);
17
+ // 仅提及插件名的注释不构成已生效(e2e 发现的误判)。
18
+ const lines = text.split(/\r?\n/);
19
+ if (lines.some((l) => l.trim() === GITIGNORE_ENTRY)) return { changed: false, line: GITIGNORE_MARKER };
20
+
21
+ // 升级(2026-10-30):旧版本写的署名块是「marker + .dsh/skills/」两行。
22
+ // 原地改写该条目行,而不是再追加一组署名块——否则旧条目永久残留、文件里出现两组同名注释。
23
+ const mi = lines.findIndex((l) => l.trim() === GITIGNORE_MARKER);
24
+ if (mi >= 0 && lines[mi + 1]?.trim() === GITIGNORE_LEGACY_ENTRY) {
25
+ lines[mi + 1] = lines[mi + 1].replace(GITIGNORE_LEGACY_ENTRY, GITIGNORE_ENTRY);
26
+ // 保留原文件换行风格(Windows 仓库常见 CRLF)
27
+ writeTextAtomic(file, lines.join(text.includes('\r\n') ? '\r\n' : '\n'), { fs: fsImpl });
28
+ return { changed: true, line: GITIGNORE_MARKER };
29
+ }
30
+
31
+ const block = `${GITIGNORE_MARKER}\n${GITIGNORE_ENTRY}\n`;
32
+ const next = !existed || text === '' ? block : (text.endsWith('\n') ? text + block : text + '\n' + block);
33
+ writeTextAtomic(file, next, { fs: fsImpl });
34
+ return { changed: true, line: GITIGNORE_MARKER };
35
+ }