@matrixfu/skill-set-manager 0.0.0-stage → 1.1.3
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/client.js +1618 -0
- package/cordis.patch.yml +5 -0
- package/icon.svg +7 -0
- package/index.js +1091 -0
- package/lib/core/atomic.js +16 -0
- package/lib/core/backup.js +123 -0
- package/lib/core/binding.js +22 -0
- package/lib/core/commandLine.js +31 -0
- package/lib/core/dataPlane.js +81 -0
- package/lib/core/diagnose.js +167 -0
- package/lib/core/effective.js +237 -0
- package/lib/core/giterr.js +22 -0
- package/lib/core/github.js +256 -0
- package/lib/core/gitignore.js +35 -0
- package/lib/core/gitnet.js +112 -0
- package/lib/core/lifecycle.js +88 -0
- package/lib/core/linkx.js +92 -0
- package/lib/core/managed.js +24 -0
- package/lib/core/manifest.js +169 -0
- package/lib/core/migrate.js +145 -0
- package/lib/core/opgate.js +62 -0
- package/lib/core/paths.js +52 -0
- package/lib/core/pending.js +210 -0
- package/lib/core/plan.js +33 -0
- package/lib/core/projectRoot.js +20 -0
- package/lib/core/providerSkills.js +26 -0
- package/lib/core/provision.js +32 -0
- package/lib/core/resident.js +98 -0
- package/lib/core/resolver.js +136 -0
- package/lib/core/search.js +28 -0
- package/lib/core/sets.js +250 -0
- package/lib/core/source.js +64 -0
- package/lib/core/storage.js +87 -0
- package/lib/core/translateExec.js +122 -0
- package/lib/core/translations.js +62 -0
- package/lib/core/updates.js +181 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +63 -4
- package/README.md +0 -3
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 网络失败语义(2026-11-17 加固 T1,叶子模块):
|
|
3
|
+
* - `isRetryableGitFailure`:只有「网络传输抖动」值得自动重试一次;真因失败
|
|
4
|
+
* (仓库不存在、上游无技能、来源格式不符)不重试——慢网络下重试等于把等待翻倍
|
|
5
|
+
* (github.js 2026-10-26 教训,GLOSSARY「可重试失败」口径)。
|
|
6
|
+
* - `logGitFailure`:failures.log 一行一条 JSON 追加——插件无常驻日志,这是「经常
|
|
7
|
+
* 失败」事后复盘的唯一证据源(命令结论行 + 耗时 + 第几次尝试)。
|
|
8
|
+
* - `probeProxy`:联网动作前探测 git 实际会走的代理(env → git config 全局)是否
|
|
9
|
+
* 有人监听;失联当场报人话错,而不是吊死或抛 git 乱码(Watt Toolkit PAC 模式,
|
|
10
|
+
* 代理未启动时 git 指死 26561 直接 refused)。两处都没配 = 直连环境,不探测。
|
|
11
|
+
*/
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { spawnSync } from 'node:child_process';
|
|
15
|
+
import net from 'node:net';
|
|
16
|
+
import { gitFailMessage } from './giterr.js';
|
|
17
|
+
|
|
18
|
+
/** 网络类结论行形状(git/curl 的 stderr 措辞);ETIMEDOUT/timed out = spawnSync 硬超时也算。 */
|
|
19
|
+
const RETRYABLE_PATTERNS = [
|
|
20
|
+
/RPC failed/i,
|
|
21
|
+
/invalid index-pack output/i,
|
|
22
|
+
/early EOF/i,
|
|
23
|
+
/Could not resolve host/i,
|
|
24
|
+
/Failed to connect/i,
|
|
25
|
+
/Connection reset/i,
|
|
26
|
+
/Connection refused/i,
|
|
27
|
+
/Empty reply/i,
|
|
28
|
+
/transfer closed/i,
|
|
29
|
+
/The requested URL returned error: (?:408|5\d\d)/i,
|
|
30
|
+
/ETIMEDOUT/,
|
|
31
|
+
/timed out/i,
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
/** 可重试失败判定:输入是 gitFailMessage 产出的业务错文案(或原始 stderr)。 */
|
|
35
|
+
export function isRetryableGitFailure(message) {
|
|
36
|
+
const s = String(message ?? '');
|
|
37
|
+
return RETRYABLE_PATTERNS.some((re) => re.test(s));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 失败留痕:一行一条 JSON 追加;嵌套目录自动建;任何异常吞掉——留痕绝不炸主流程。 */
|
|
41
|
+
export function logGitFailure(failLogPath, rec) {
|
|
42
|
+
try {
|
|
43
|
+
fs.mkdirSync(path.dirname(failLogPath), { recursive: true });
|
|
44
|
+
fs.appendFileSync(failLogPath, JSON.stringify(rec) + '\n', 'utf8');
|
|
45
|
+
} catch {}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const defaultGit = (args, cwd) => spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 1500, windowsHide: true }); // 终审 St6:git config 卡住不得无界吊死 host 事件循环
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 「跑了一次 attempt,怎么判」统一入口(GLOSSARY「可重试失败」口径只写这一处;
|
|
52
|
+
* 终审 St1:fetch/sparse-checkout/checkout/ls-remote 四个调用点共用,B 阶段加第五处也不漂移)。
|
|
53
|
+
* 调用方自持循环与差异钩子(清锁 / 空 sha / filterUnrecognized),本函数只做:
|
|
54
|
+
* 成功判定 → 结论归一 → 留痕 → 可重试分类。r = 已跑完的 {status,stdout,stderr}(抛错侧归一后传入)。
|
|
55
|
+
* ok 谓词可覆写(remoteHead 认「有 sha 才算成」);failMsg 可覆写空响应这类 status=0 假成。
|
|
56
|
+
*/
|
|
57
|
+
export function classifyAttempt({ cmd, args, r, t0, failLog, attempt, maxAttempts = 2, ok = (x) => x && x.status === 0, failMsg = null }) {
|
|
58
|
+
if (ok(r)) return { ok: true, r };
|
|
59
|
+
const msg = failMsg ? failMsg(r) : gitFailMessage(args, r);
|
|
60
|
+
if (failLog) logGitFailure(failLog, { cmd, status: r?.status ?? 'spawn', verdict: msg, ms: Date.now() - t0, attempt });
|
|
61
|
+
return { ok: false, msg, retry: attempt < maxAttempts && isRetryableGitFailure(msg) };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 代理地址解析序:env(大小写都认)→ git 全局 https.proxy/http.proxy;无配置返回 null。 */
|
|
65
|
+
function proxyTarget(git, env) {
|
|
66
|
+
const fromEnv = env.HTTPS_PROXY || env.https_proxy || env.HTTP_PROXY || env.http_proxy;
|
|
67
|
+
if (fromEnv) return String(fromEnv);
|
|
68
|
+
for (const key of ['https.proxy', 'http.proxy']) {
|
|
69
|
+
let r;
|
|
70
|
+
try { r = git(['config', '--global', '--get', key]); } catch { continue; }
|
|
71
|
+
const v = String(r?.stdout ?? '').trim();
|
|
72
|
+
if (r?.status === 0 && v) return v;
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 代理 TCP 预检:`{ dead: 'host:port' | null }`。地址解析不了当无配置放行
|
|
79
|
+
* (不拦,让 git 自己报它的错);connect 成功=null,error/超时=dead。
|
|
80
|
+
* net/git/env 全可注入(verify 夹具免真网络;host 默认拿 node:net + process.env)。
|
|
81
|
+
*/
|
|
82
|
+
export async function probeProxy({ git = defaultGit, net: netImpl = net, env = process.env, timeoutMs = 1500 } = {}) {
|
|
83
|
+
const raw = proxyTarget(git, env);
|
|
84
|
+
if (!raw) return { dead: null };
|
|
85
|
+
let url;
|
|
86
|
+
try { url = new URL(raw.includes('://') ? raw : `http://${raw}`); }
|
|
87
|
+
catch { return { dead: null }; }
|
|
88
|
+
const host = url.hostname;
|
|
89
|
+
const port = Number(url.port) || (url.protocol === 'https:' ? 443 : 80);
|
|
90
|
+
const dead = `${host}:${port}`;
|
|
91
|
+
const alive = await new Promise((resolve) => {
|
|
92
|
+
let done = false;
|
|
93
|
+
let sock;
|
|
94
|
+
let timer;
|
|
95
|
+
const finish = (v) => {
|
|
96
|
+
if (done) return;
|
|
97
|
+
done = true;
|
|
98
|
+
try { clearTimeout(timer); } catch {}
|
|
99
|
+
try { sock?.destroy?.(); } catch {}
|
|
100
|
+
resolve(v);
|
|
101
|
+
};
|
|
102
|
+
try { sock = netImpl.connect({ host, port, timeout: timeoutMs }, () => finish(true)); }
|
|
103
|
+
catch { finish(false); return; }
|
|
104
|
+
sock.on?.('connect', () => finish(true));
|
|
105
|
+
sock.on?.('error', () => finish(false));
|
|
106
|
+
sock.on?.('timeout', () => finish(false));
|
|
107
|
+
if (typeof sock.setTimeout === 'function') sock.setTimeout(timeoutMs, () => finish(false));
|
|
108
|
+
timer = setTimeout(() => finish(false), timeoutMs + 200);
|
|
109
|
+
timer.unref?.(); // 兜底定时器不拖住测试进程退出
|
|
110
|
+
});
|
|
111
|
+
return { dead: alive ? null : dead };
|
|
112
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 卸载(§8.7):确认由 UI 层做,本模块执行——备份 → 删库体 → 所有技能集移除该名 →
|
|
3
|
+
* 按各项目 .managed.json 精确回收(冻结项目不动)→ 可回滚操作日志。
|
|
4
|
+
* bindings = 候选项目根列表(host 半从 bindings 索引提供;ADR-0003 只动托管条目)。
|
|
5
|
+
*/
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { snapshot } from './backup.js';
|
|
9
|
+
import { listSets, loadSet, saveSet } from './sets.js';
|
|
10
|
+
import { readBinding, bindingFile } from './binding.js';
|
|
11
|
+
import { readManaged, writeManaged, managedFile } from './managed.js';
|
|
12
|
+
import { converge } from './effective.js';
|
|
13
|
+
import { entryKind, removeEntry } from './linkx.js';
|
|
14
|
+
import { projectSkillsDir } from './paths.js';
|
|
15
|
+
import { writeTextAtomic } from './atomic.js';
|
|
16
|
+
|
|
17
|
+
export async function uninstallSkill(roots, { name, bindings = [] }, { fs: fsImpl = fs } = {}) {
|
|
18
|
+
const backup = snapshot(roots, name, { fs: fsImpl });
|
|
19
|
+
const libDir = path.join(roots.libraryRoot, name);
|
|
20
|
+
fsImpl.rmSync(libDir, { recursive: true, force: true });
|
|
21
|
+
|
|
22
|
+
const removedFromSets = [];
|
|
23
|
+
for (const s of listSets(roots)) {
|
|
24
|
+
const set = loadSet(roots, s.slug);
|
|
25
|
+
if (set && Array.isArray(set.skills) && set.skills.includes(name)) {
|
|
26
|
+
saveSet(roots, { ...set, skills: set.skills.filter((n) => n !== name) });
|
|
27
|
+
removedFromSets.push(set.slug);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const rewrittenProjects = [];
|
|
32
|
+
const frozenProjects = [];
|
|
33
|
+
const warnings = [];
|
|
34
|
+
for (const projectRoot of bindings) {
|
|
35
|
+
let binding;
|
|
36
|
+
try { binding = readBinding(projectRoot, { fs: fsImpl }); } catch { continue; }
|
|
37
|
+
if (!binding?.setSlug) continue;
|
|
38
|
+
const set = loadSet(roots, binding.setSlug);
|
|
39
|
+
if (!set) { frozenProjects.push(projectRoot); continue; } // 冻结绑定:原样保留(§7.8)
|
|
40
|
+
const managed = readManaged(projectRoot, { fs: fsImpl }) ?? { entries: {} };
|
|
41
|
+
if (managed.entries?.[name]) {
|
|
42
|
+
const entryPath = path.join(projectSkillsDir(projectRoot), name);
|
|
43
|
+
try { removeEntry(entryPath, entryKind(entryPath, { fs: fsImpl })); } catch (e) { warnings.push(`${projectRoot}: ${e?.message ?? e}`); }
|
|
44
|
+
delete managed.entries[name];
|
|
45
|
+
writeManaged(projectRoot, managed, { fs: fsImpl });
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
await converge(roots, projectRoot, binding.setSlug, { fs: fsImpl });
|
|
49
|
+
rewrittenProjects.push(projectRoot);
|
|
50
|
+
} catch (e) { warnings.push(`${projectRoot} 重写失败: ${e?.message ?? e}`); }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// 可回滚操作日志(回收站根下,与快照同区)
|
|
54
|
+
const logFile = path.join(roots.libraryRoot, '.backups', 'oplog.json');
|
|
55
|
+
const OPLOG_CAP = 200; // 审计流水封顶(review n3/n8)
|
|
56
|
+
let log = [];
|
|
57
|
+
try { log = JSON.parse(fsImpl.readFileSync(logFile, 'utf8')); } catch {}
|
|
58
|
+
log.push({ ts: new Date().toISOString(), action: 'uninstall', name, backup, removedFromSets, rewrittenProjects, frozenProjects });
|
|
59
|
+
if (log.length > OPLOG_CAP) log = log.slice(-OPLOG_CAP); // 封顶保最新(review n8/n3)
|
|
60
|
+
fsImpl.mkdirSync(path.dirname(logFile), { recursive: true });
|
|
61
|
+
writeTextAtomic(logFile, JSON.stringify(log, null, 2) + '\n', { fs: fsImpl }); // 原子写(review m8)
|
|
62
|
+
|
|
63
|
+
return { backup, removedFromSets, rewrittenProjects, frozenProjects, warnings };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 候选项目里绑定到 slug 的全量列表(deleteSet affectedProjects 数据源)。 */
|
|
67
|
+
export function findBoundProjects(projectRoots, slug, { fs: fsImpl = fs } = {}) {
|
|
68
|
+
return projectRoots.filter((pr) => {
|
|
69
|
+
try { return readBinding(pr, { fs: fsImpl })?.setSlug === slug; } catch { return false; }
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 解绑(P1a 面板缺口):删 binding + 按托管清单精确回收全部托管条目 + 删
|
|
75
|
+
* .managed.json。用户自有条目与 .gitignore 行一律不动(ADR-0003)。幂等。
|
|
76
|
+
*/
|
|
77
|
+
export function unbindProject(projectRoot, { fs: fsImpl = fs } = {}) {
|
|
78
|
+
const binding = readBinding(projectRoot, { fs: fsImpl });
|
|
79
|
+
const managed = readManaged(projectRoot, { fs: fsImpl });
|
|
80
|
+
const removed = [];
|
|
81
|
+
for (const name of Object.keys(managed?.entries ?? {})) {
|
|
82
|
+
const p = path.join(projectSkillsDir(projectRoot), name);
|
|
83
|
+
try { removeEntry(p, entryKind(p, { fs: fsImpl })); removed.push(name); } catch {}
|
|
84
|
+
}
|
|
85
|
+
try { fsImpl.rmSync(managedFile(projectRoot), { force: true }); } catch {}
|
|
86
|
+
if (binding) { try { fsImpl.rmSync(bindingFile(projectRoot), { force: true }); } catch {} }
|
|
87
|
+
return { wasBound: !!binding, removed };
|
|
88
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 条目原语(§4.3):junction 优先(node fs.symlink 'junction',禁 MSYS ln -s / 禁 symlink 类型),
|
|
3
|
+
* 失败回退复制(副本不随库演进,kind 由调用方写进 .managed.json)。
|
|
4
|
+
* 性质判定照抄取证:readdir Dirent 把 junction 报成 symlink、lstat 反而看不出——
|
|
5
|
+
* 所以 junction 检测用「父目录 Dirent.isSymbolicLink() + stat 是否目录」,其余一律 stat/lstat。
|
|
6
|
+
*/
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
|
|
10
|
+
/** fs 层真相:'junction' | 'symlink' | 'dir' | 'file' | 'missing' | 'other'(copy 与 dir 在 fs 层不可分,归托管清单记)。 */
|
|
11
|
+
export function entryKind(linkPath, { fs: fsImpl = fs } = {}) {
|
|
12
|
+
let st;
|
|
13
|
+
try { st = fsImpl.statSync(linkPath); } catch { return 'missing'; } // stat 跟随:失效链接 → missing
|
|
14
|
+
let ents;
|
|
15
|
+
try { ents = fsImpl.readdirSync(path.dirname(linkPath), { withFileTypes: true }); } catch { return 'other'; }
|
|
16
|
+
const ent = ents.find((e) => e.name === path.basename(linkPath));
|
|
17
|
+
if (ent && ent.isSymbolicLink()) return st.isDirectory() ? 'junction' : 'symlink';
|
|
18
|
+
if (st.isDirectory()) return 'dir';
|
|
19
|
+
if (st.isFile()) return 'file';
|
|
20
|
+
return 'other';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function makeEntry(target, linkPath, { fs: fsImpl = fs } = {}) {
|
|
24
|
+
let targetStat;
|
|
25
|
+
try { targetStat = fsImpl.statSync(target); } catch (e) { throw new Error(`链接本体不存在: ${target}`); } // 失效引用在 plan 阶段已挡
|
|
26
|
+
removeEntry(linkPath, undefined, { fs: fsImpl }); // EEXIST 或死 stub 都先清(死 stub stat 失败,removeEntry 走 Dirent 支路)
|
|
27
|
+
fsImpl.mkdirSync(path.dirname(linkPath), { recursive: true });
|
|
28
|
+
if (targetStat.isFile()) {
|
|
29
|
+
// flat <name>.md 本体:文件复制(junction 只用于目录)
|
|
30
|
+
fsImpl.cpSync(target, linkPath);
|
|
31
|
+
return { kind: 'copy', copied: true, flat: true };
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
fsImpl.symlinkSync(target, linkPath, 'junction');
|
|
35
|
+
if (fsImpl.statSync(linkPath).isDirectory()) return { kind: 'junction' };
|
|
36
|
+
throw new Error('junction 建立后不可读');
|
|
37
|
+
} catch {
|
|
38
|
+
try { fsImpl.rmSync(linkPath, { recursive: true, force: true }); } catch {}
|
|
39
|
+
fsImpl.cpSync(target, linkPath, { recursive: true });
|
|
40
|
+
return { kind: 'copy', copied: true };
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 链接点是否指向 root 之内(含 root 自身):失效链、越界、读不到真身一律 false。
|
|
46
|
+
* 调用方须先经 entryKind 确认是链接(普通目录本就落在 root 内时也会返回 true)。
|
|
47
|
+
* 真身取 readlinkSync:一步即得、不跟随链中链,也不受 junction/symlink 类型差异影响;
|
|
48
|
+
* 相对目标按链接父目录解析,win32 盘符/大小写 resolve+lowercase 归一。
|
|
49
|
+
* 注意:DSH 文件沙箱会把 junction 虚拟化成普通目录(readlink 报 EINVAL、realpath 原地返回),
|
|
50
|
+
* 此时退化为 false(按外部链接处理)——link 类验收必须在沙箱外跑 scripts/verify.mjs(实锤 2026-10-26)。
|
|
51
|
+
*/
|
|
52
|
+
export function linkPointsInto(linkPath, root, { fs: fsImpl = fs } = {}) {
|
|
53
|
+
const norm = (p) => {
|
|
54
|
+
const r = path.resolve(p);
|
|
55
|
+
return process.platform === 'win32' ? r.toLowerCase() : r;
|
|
56
|
+
};
|
|
57
|
+
try {
|
|
58
|
+
const t = norm(path.resolve(path.dirname(linkPath), fsImpl.readlinkSync(linkPath)));
|
|
59
|
+
const r = norm(root);
|
|
60
|
+
return t === r || t.startsWith(r + path.sep);
|
|
61
|
+
} catch { return false; }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 只删条目自身,永不跟随删本体。kind 缺省时按 entryKind 自判;
|
|
66
|
+
* stat 失败但父目录 Dirent 显示仍在(死 junction/死 symlink 挂角)→ 按链摘除,
|
|
67
|
+
* 否则外删条目永远删不掉、重建永远 EEXIST(review M1)。
|
|
68
|
+
*/
|
|
69
|
+
export function removeEntry(linkPath, kind, { fs: fsImpl = fs } = {}) {
|
|
70
|
+
let k = kind ?? entryKind(linkPath, { fs: fsImpl });
|
|
71
|
+
if (k === 'missing') {
|
|
72
|
+
let ent;
|
|
73
|
+
try {
|
|
74
|
+
ent = fsImpl.readdirSync(path.dirname(linkPath), { withFileTypes: true })
|
|
75
|
+
.find((e) => e.name === path.basename(linkPath));
|
|
76
|
+
} catch { return false; }
|
|
77
|
+
if (!ent) return false; // 盘上真没有:视作已摘
|
|
78
|
+
k = ent.isSymbolicLink() ? 'symlink' : ent.isDirectory() ? 'dir' : 'file';
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
if (k === 'junction' || k === 'symlink') fsImpl.rmdirSync(linkPath); // 摘链接点,不碰本体
|
|
82
|
+
else fsImpl.rmSync(linkPath, { recursive: true, force: true });
|
|
83
|
+
return true;
|
|
84
|
+
} catch (e) {
|
|
85
|
+
if (e.code === 'ENOENT') return false; // 已被外部手删:视作已摘,台账照常收敛
|
|
86
|
+
if (e.code === 'ENOTDIR' || e.code === 'EPERM') {
|
|
87
|
+
// 失效 junction(本体已没了):rmdir 有时报 ENOTDIR/EPERM,强制摘
|
|
88
|
+
try { fsImpl.rmSync(linkPath, { force: true }); return true; } catch {}
|
|
89
|
+
}
|
|
90
|
+
throw e;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** 托管清单(§11):<projectRoot>/.agents/skills/.managed.json —— 插件区分自己条目与外来条目的唯一依据。 */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { writeTextAtomic } from './atomic.js';
|
|
5
|
+
import { projectSkillsDir } from './paths.js';
|
|
6
|
+
|
|
7
|
+
export const managedFile = (projectRoot) => path.join(projectSkillsDir(projectRoot), '.managed.json');
|
|
8
|
+
|
|
9
|
+
export function readManaged(projectRoot, { fs: fsImpl = fs } = {}) {
|
|
10
|
+
let doc;
|
|
11
|
+
try { doc = JSON.parse(fsImpl.readFileSync(managedFile(projectRoot), 'utf8')); } catch (e) {
|
|
12
|
+
if (e.code === 'ENOENT') return null;
|
|
13
|
+
throw new Error(`${managedFile(projectRoot)}: 解析失败(文件被手改坏?请人工修复,插件不覆盖): ${e.message}`);
|
|
14
|
+
}
|
|
15
|
+
return { setSlug: doc.setSlug ?? null, entries: doc.entries ?? {}, sessionOverride: doc.sessionOverride ?? null };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function writeManaged(projectRoot, managed, { fs: fsImpl = fs } = {}) {
|
|
19
|
+
writeTextAtomic(
|
|
20
|
+
managedFile(projectRoot),
|
|
21
|
+
JSON.stringify({ setSlug: managed.setSlug, entries: managed.entries, sessionOverride: managed.sessionOverride ?? null }, null, 2) + '\n',
|
|
22
|
+
{ fs: fsImpl },
|
|
23
|
+
);
|
|
24
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/** 扫描登记(§8.1):为库内缺 manifest 的技能补写 .manifest.json(本地技能 source:'unknown')。 */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import { parseFrontmatter } from './resolver.js';
|
|
6
|
+
import { writeTextAtomic } from './atomic.js';
|
|
7
|
+
import { SKILL_NAME_RE } from './paths.js';
|
|
8
|
+
import { normalizeRepoSource } from './source.js';
|
|
9
|
+
|
|
10
|
+
const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 一次遍历同时产出两样东西:逐文件哈希(基线)与逐文件 stat 摘要(size:mtime)。
|
|
14
|
+
* `hash:false` = 只 stat 不读内容——「本地改动」判定的廉价口径。
|
|
15
|
+
* 实测本机 96 技能 / 11386 文件 / 451.8MB:读+sha256 1483ms(其中读盘占 84%),
|
|
16
|
+
* 只 stat 172ms;旧口径每次开面板都全库读盘,就是面板与设置页 2~3 秒的来源。
|
|
17
|
+
*/
|
|
18
|
+
function walkScan(root, { fs: fsImpl = fs, hash = true } = {}) {
|
|
19
|
+
const files = {};
|
|
20
|
+
const stats = {};
|
|
21
|
+
const walk = (dir, rel) => {
|
|
22
|
+
for (const ent of fsImpl.readdirSync(dir, { withFileTypes: true })) {
|
|
23
|
+
if (ent.name.startsWith('.')) continue; // .manifest.json 自身与点目录一律不进哈希表
|
|
24
|
+
const abs = path.join(dir, ent.name);
|
|
25
|
+
const r = rel ? `${rel}/${ent.name}` : ent.name;
|
|
26
|
+
const st = fsImpl.statSync(abs); // 跟随 junction
|
|
27
|
+
if (st.isDirectory()) walk(abs, r);
|
|
28
|
+
else if (st.isFile()) {
|
|
29
|
+
stats[r] = `${st.size}:${Math.round(st.mtimeMs)}`;
|
|
30
|
+
if (hash) files[r] = 'sha256:' + sha256(fsImpl.readFileSync(abs));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
walk(root, '');
|
|
35
|
+
return { files, stats };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function walkFiles(root, opts) {
|
|
39
|
+
return walkScan(root, opts).files;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 与 walkFiles 同一趟遍历,但不读内容、不哈希,只回 size:mtime 摘要(staleness 快路径)。 */
|
|
43
|
+
export function walkStat(root, opts) {
|
|
44
|
+
return walkScan(root, { ...opts, hash: false }).stats;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const hashFile = (abs, fsImpl = fs) => 'sha256:' + sha256(fsImpl.readFileSync(abs));
|
|
48
|
+
|
|
49
|
+
/** 两张哈希表是否不同(现口径:任一方向有差异即不同)。 */
|
|
50
|
+
function hashDiffers(baseline, now) {
|
|
51
|
+
return Object.keys(baseline).some((p) => baseline[p] !== now[p]) || Object.keys(now).some((p) => now[p] !== baseline[p]);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 「本地改动」判定(§6.4 徽标):盘上现状 vs manifest 基线,只回布尔。
|
|
56
|
+
* 快路径靠 manifest.stats(登记/安装时记下的 size:mtime):stat 口径没变即内容没变,一个文件都不读;
|
|
57
|
+
* stat 不匹配才回读该文件哈希比对(只 touch 不假红)。
|
|
58
|
+
* 已知代价:内容变了但 size 与 mtime 都没变(工具刻意保留 mtime 那类)会漏判——
|
|
59
|
+
* 升级检查/卸载/备份还原等真正要命的判定仍走 walkFiles 全量哈希,不受此影响。
|
|
60
|
+
* 旧 manifest 没有 stats:回退一次全量哈希,由调用方补写 stats(backfillManifestStats)后即走快路径。
|
|
61
|
+
*/
|
|
62
|
+
export function localModified(dir, mf, { fs: fsImpl = fs } = {}) {
|
|
63
|
+
const baseline = mf?.files;
|
|
64
|
+
if (!baseline || !Object.keys(baseline).length) return false; // 无基线 = 无从比对(照旧口径)
|
|
65
|
+
if (!mf.stats) return hashDiffers(baseline, walkFiles(dir, { fs: fsImpl }));
|
|
66
|
+
const nowStats = walkStat(dir, { fs: fsImpl });
|
|
67
|
+
for (const [p, baseHash] of Object.entries(baseline)) {
|
|
68
|
+
const now = nowStats[p];
|
|
69
|
+
if (now === undefined) return true; // 基线文件已不在盘上
|
|
70
|
+
if (now === mf.stats[p]) continue; // size+mtime 未变 → 不读盘
|
|
71
|
+
if (hashFile(path.join(dir, p), fsImpl) !== baseHash) return true;
|
|
72
|
+
}
|
|
73
|
+
return Object.keys(nowStats).some((p) => !(p in baseline)); // 基线外新增文件
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 给升级前的旧 manifest 补写 stats(一次性)。只加字段,files/dirDigest 基线口径一字不动。 */
|
|
77
|
+
export function backfillManifestStats(dir, mf, { fs: fsImpl = fs } = {}) {
|
|
78
|
+
if (!mf || mf.stats) return mf;
|
|
79
|
+
const next = { ...mf, stats: walkStat(dir, { fs: fsImpl }) };
|
|
80
|
+
writeTextAtomic(path.join(dir, '.manifest.json'), JSON.stringify(next, null, 2) + '\n', { fs: fsImpl });
|
|
81
|
+
return next;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 逐文件哈希 + 目录摘要(§11 manifest 形状,#8 验收字段)。 */
|
|
85
|
+
function buildManifest(dir, name, { source = 'unknown', commit = null }, fsImpl) {
|
|
86
|
+
const skillMd = fsImpl.readFileSync(path.join(dir, 'SKILL.md'), 'utf8');
|
|
87
|
+
const fm = parseFrontmatter(skillMd);
|
|
88
|
+
const { files, stats } = walkScan(dir, { fs: fsImpl });
|
|
89
|
+
const dirDigest = 'sha256:' + sha256(Buffer.from(
|
|
90
|
+
Object.entries(files).sort().map(([k, v]) => `${k}:${v}`).join('\n'),
|
|
91
|
+
));
|
|
92
|
+
return {
|
|
93
|
+
name: (fm && fm.name) || name,
|
|
94
|
+
source,
|
|
95
|
+
commit,
|
|
96
|
+
installedAt: new Date().toISOString(),
|
|
97
|
+
managed: true,
|
|
98
|
+
files,
|
|
99
|
+
stats,
|
|
100
|
+
dirDigest,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 检出根即技能(单技能仓库:SKILL.md 直接在检出根,没有「一层目录 = 一个技能」那层)时的技能名:
|
|
106
|
+
* **只认 frontmatter 里合法 kebab-case 的 name**,否则 null。名字不猜仓库名——猜错等于库条目名与
|
|
107
|
+
* manifest.name 分叉,更新认领还会拿错基线误覆盖本地文件(§7.3 目录名即技能名)。
|
|
108
|
+
*/
|
|
109
|
+
export function rootSkillName(dir, { fs: fsImpl = fs } = {}) {
|
|
110
|
+
let text;
|
|
111
|
+
try { text = fsImpl.readFileSync(path.join(dir, 'SKILL.md'), 'utf8'); } catch { return null; }
|
|
112
|
+
const name = String(parseFrontmatter(text)?.name ?? '').trim();
|
|
113
|
+
return SKILL_NAME_RE.test(name) ? name : null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** 读单个技能目录的 manifest;缺失/损坏返回 null。 */
|
|
117
|
+
export function readManifest(dir, { fs: fsImpl = fs } = {}) {
|
|
118
|
+
try { return JSON.parse(fsImpl.readFileSync(path.join(dir, '.manifest.json'), 'utf8')); }
|
|
119
|
+
catch { return null; }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** 单技能直写 manifest(GitHub 安装/恢复用;覆盖式)。P1a-T0。 */
|
|
123
|
+
export function writeSkillManifest(dir, { source = 'unknown', commit = null, fs: fsImpl = fs } = {}) {
|
|
124
|
+
const manifest = buildManifest(dir, path.basename(dir), { source, commit }, fsImpl);
|
|
125
|
+
writeTextAtomic(path.join(dir, '.manifest.json'), JSON.stringify(manifest, null, 2) + '\n', { fs: fsImpl });
|
|
126
|
+
return manifest;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 认领来源(§8.1):给库内本地技能补写 manifest——**认领时的盘上内容即基线**,
|
|
131
|
+
* 之后本地改动才谈得上「升级时跳过并保留」。只作用于技能库(库外条目他人所有,ADR-0003)。
|
|
132
|
+
* `source` 走 normalizeRepoSource 单一口径(非法来源抛业务错、不落盘);
|
|
133
|
+
* 字面 `'unknown'` = 撤认领,回落 §8.1 的「本地技能已登记」态(哈希基线保留)。
|
|
134
|
+
*/
|
|
135
|
+
export function claimSource(roots, { name, source, commit = null }, { fs: fsImpl = fs } = {}) {
|
|
136
|
+
if (!SKILL_NAME_RE.test(String(name ?? ''))) throw new Error(`技能名不合法(非 kebab-case): ${name}`);
|
|
137
|
+
const dir = path.join(roots.libraryRoot, name);
|
|
138
|
+
let isDir = false;
|
|
139
|
+
try { isDir = fsImpl.statSync(dir).isDirectory(); } catch {}
|
|
140
|
+
if (!isDir) throw new Error(`技能库内不存在该技能(认领来源只作用于 ~/.dsh/skill-library): ${name}`);
|
|
141
|
+
const raw = String(source ?? '').trim();
|
|
142
|
+
const unknown = raw === '' || raw === 'unknown';
|
|
143
|
+
const canonical = unknown ? 'unknown' : normalizeRepoSource(raw); // 非法来源在此抛
|
|
144
|
+
return writeSkillManifest(dir, {
|
|
145
|
+
source: canonical,
|
|
146
|
+
commit: canonical === 'unknown' ? null : (commit ? String(commit).trim() : null),
|
|
147
|
+
fs: fsImpl,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function registerLibrary(roots, { fs: fsImpl = fs, source = 'unknown', commit = null } = {}) {
|
|
152
|
+
const registered = [];
|
|
153
|
+
const manifests = [];
|
|
154
|
+
let names;
|
|
155
|
+
try { names = fsImpl.readdirSync(roots.libraryRoot); } catch { return { registered, manifests }; }
|
|
156
|
+
for (const name of names) {
|
|
157
|
+
if (name.startsWith('.')) continue;
|
|
158
|
+
const dir = path.join(roots.libraryRoot, name);
|
|
159
|
+
try { if (!fsImpl.statSync(dir).isDirectory()) continue; } catch { continue; }
|
|
160
|
+
const mfPath = path.join(dir, '.manifest.json');
|
|
161
|
+
try { fsImpl.statSync(mfPath); continue; } catch {} // 已有 manifest 不覆盖
|
|
162
|
+
let manifest;
|
|
163
|
+
try { manifest = buildManifest(dir, name, { source, commit }, fsImpl); } catch { continue; }
|
|
164
|
+
writeTextAtomic(mfPath, JSON.stringify(manifest, null, 2) + '\n', { fs: fsImpl });
|
|
165
|
+
registered.push(manifest.name);
|
|
166
|
+
manifests.push(mfPath);
|
|
167
|
+
}
|
|
168
|
+
return { registered, manifests };
|
|
169
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 迁移向导(§8.2,一次性可跳过):默认把通用生效区(~/.dsh/skills)的技能**移动**
|
|
3
|
+
* 入库,常驻子集经 syncResident 链回原区;ledger(host 半接 storageDomain)逐项
|
|
4
|
+
* 即时落账 → 中断重跑幂等续传;undo 逆序回滚。库同名一律 keep 不动(ADR-0003)。
|
|
5
|
+
*/
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { copyDirTree } from './github.js';
|
|
9
|
+
import { syncResident } from './resident.js';
|
|
10
|
+
import { entryKind, removeEntry, linkPointsInto } from './linkx.js';
|
|
11
|
+
import { claimSource, readManifest } from './manifest.js';
|
|
12
|
+
|
|
13
|
+
const hasSkillMd = (d, fsImpl) => { try { fsImpl.statSync(path.join(d, 'SKILL.md')); return true; } catch { return false; } };
|
|
14
|
+
|
|
15
|
+
function moveDir(from, to, fsImpl) {
|
|
16
|
+
try { fsImpl.renameSync(from, to); }
|
|
17
|
+
catch (e) {
|
|
18
|
+
if (e.code === 'EXDEV') { copyDirTree(from, to, fsImpl); fsImpl.rmSync(from, { recursive: true, force: true }); }
|
|
19
|
+
else throw e;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 预览:一层扫描含 SKILL.md 的目录;库同名 keep。固定披露「只剩常驻」警告。 */
|
|
24
|
+
export function preview(roots, { fromDir = roots.userDshRoot } = {}, { fs: fsImpl = fs } = {}) {
|
|
25
|
+
const moves = [];
|
|
26
|
+
const keep = [];
|
|
27
|
+
let names;
|
|
28
|
+
try { names = fsImpl.readdirSync(fromDir).filter((n) => !n.startsWith('.')); } catch { names = []; }
|
|
29
|
+
for (const name of names.sort()) {
|
|
30
|
+
const from = path.join(fromDir, name);
|
|
31
|
+
let st;
|
|
32
|
+
try { st = fsImpl.statSync(from); } catch { continue; }
|
|
33
|
+
if (!st.isDirectory() || !hasSkillMd(from, fsImpl)) continue;
|
|
34
|
+
const to = path.join(roots.libraryRoot, name);
|
|
35
|
+
let exists = false;
|
|
36
|
+
try { fsImpl.statSync(to); exists = true; } catch {}
|
|
37
|
+
if (exists) { keep.push({ name, reason: 'exists', from }); continue; }
|
|
38
|
+
moves.push({ name, from, to });
|
|
39
|
+
}
|
|
40
|
+
const warnings = ['旧通用区(~/.dsh/skills)中的技能将整体移入技能库;移空后,其他 harness 将只剩常驻技能(§8.2)。跨 harness 通用区(~/.agents/skills)不在本向导范围——请使用「跨 harness 通用区迁移」(同页上方)。'];
|
|
41
|
+
return { moves, keep, warnings };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 执行:逐项 rename(EXDEV 退化为拷+删),每项即时写 ledger → 中断可续。 */
|
|
45
|
+
export async function apply(roots, { moves, ledger }, { fs: fsImpl = fs } = {}) {
|
|
46
|
+
const data = (await ledger.load()) ?? { moved: [] };
|
|
47
|
+
const done = new Set(data.moved.map((x) => x.name));
|
|
48
|
+
for (const mv of moves) {
|
|
49
|
+
if (done.has(mv.name)) continue;
|
|
50
|
+
if (!fsImpl.existsSync(mv.from)) {
|
|
51
|
+
if (hasSkillMd(mv.to, fsImpl)) { // 上次已挪走但没落账 → 补账
|
|
52
|
+
data.moved.push({ name: mv.name, from: mv.from, to: mv.to });
|
|
53
|
+
done.add(mv.name);
|
|
54
|
+
await ledger.save(data);
|
|
55
|
+
}
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
moveDir(mv.from, mv.to, fsImpl);
|
|
59
|
+
data.moved.push({ name: mv.name, from: mv.from, to: mv.to });
|
|
60
|
+
done.add(mv.name);
|
|
61
|
+
await ledger.save(data);
|
|
62
|
+
}
|
|
63
|
+
const res = await syncResident(roots, { fs: fsImpl }); // 常驻子集链回原区(§8.2)
|
|
64
|
+
return { moved: [...done], warnings: res?.warnings ?? [] }; // syncResident 返回对象不是数组(review m4)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** 回滚:按 ledger 逆序移回;原位被占则跳过并报告。 */
|
|
68
|
+
export async function undo(roots, { ledger }, { fs: fsImpl = fs } = {}) {
|
|
69
|
+
const data = (await ledger.load()) ?? { moved: [] };
|
|
70
|
+
const restored = [];
|
|
71
|
+
const warnings = [];
|
|
72
|
+
for (const item of [...data.moved].reverse()) {
|
|
73
|
+
try {
|
|
74
|
+
if (fsImpl.existsSync(item.to)) {
|
|
75
|
+
// 常驻链先摘(apply 时 syncResident 把曾常驻技能链回了原区,review m4)
|
|
76
|
+
const kFrom = entryKind(item.from, { fs: fsImpl });
|
|
77
|
+
if (kFrom === 'junction' || kFrom === 'symlink') removeEntry(item.from, kFrom, { fs: fsImpl });
|
|
78
|
+
if (fsImpl.existsSync(item.from)) warnings.push(`原位已存在同名目录,跳过 "${item.name}"`);
|
|
79
|
+
else {
|
|
80
|
+
moveDir(item.to, item.from, fsImpl);
|
|
81
|
+
if (item.claimed) { try { fsImpl.rmSync(path.join(item.from, '.manifest.json'), { force: true }); } catch {} } // agents 迁移的认领随回滚撤销(不留 foreign 假象)
|
|
82
|
+
restored.push(item.name);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
} catch (e) { warnings.push(`${item.name}: ${e?.message ?? e}`); }
|
|
86
|
+
data.moved = data.moved.filter((x) => x.name !== item.name);
|
|
87
|
+
await ledger.save(data);
|
|
88
|
+
}
|
|
89
|
+
const w2 = await syncResident(roots, { fs: fsImpl });
|
|
90
|
+
return { restored, warnings: [...warnings, ...(w2?.warnings ?? [])] };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* P3 agents 存量迁移(设计 §5.7/§6.6):只移「无 .manifest.json、非链接、库无同名」的 agents 区纯目录。
|
|
95
|
+
* 带 manifest = 他人记账(ADR-0003 不动);链接(自家常驻/外部)不搬真身。
|
|
96
|
+
* 保留理由分三类(用户报告 2026-10-26:迁完后预览把 47 条自建常驻链全报成「同名保留(exists)」,
|
|
97
|
+
* 像迁移失败):resident = 链回本库的常驻链接(已是迁移后状态)|link = 外部真身的链接|manifest = 他人记账。
|
|
98
|
+
* 0 移动时「只剩常驻」是**待迁移动作**的预告,不该继续弹:挪进 notes 做中性说明。
|
|
99
|
+
*/
|
|
100
|
+
export function previewAgents(roots, { fs: fsImpl = fs } = {}) {
|
|
101
|
+
const pv = preview(roots, { fromDir: roots.userAgentsRoot }, { fs: fsImpl });
|
|
102
|
+
const moves = [];
|
|
103
|
+
const kept = [];
|
|
104
|
+
for (const mv of pv.moves) {
|
|
105
|
+
const k = entryKind(mv.from, { fs: fsImpl });
|
|
106
|
+
if (k !== 'dir') { kept.push({ name: mv.name, reason: 'link' }); continue; }
|
|
107
|
+
if (readManifest(mv.from, { fs: fsImpl })) { kept.push({ name: mv.name, reason: 'manifest' }); continue; }
|
|
108
|
+
moves.push(mv);
|
|
109
|
+
}
|
|
110
|
+
const keep = pv.keep.map((k) => { // 库同名先分辨:链回库的是自家常驻链,不是他人同名条目
|
|
111
|
+
const from = k.from ?? path.join(roots.userAgentsRoot, k.name);
|
|
112
|
+
const kind = entryKind(from, { fs: fsImpl });
|
|
113
|
+
if (kind !== 'junction' && kind !== 'symlink') return { name: k.name, reason: k.reason };
|
|
114
|
+
return { name: k.name, reason: linkPointsInto(from, roots.libraryRoot, { fs: fsImpl }) ? 'resident' : 'link' };
|
|
115
|
+
});
|
|
116
|
+
const all = [...keep, ...kept];
|
|
117
|
+
const resident = all.filter((k) => k.reason === 'resident').length;
|
|
118
|
+
const pending = moves.length > 0;
|
|
119
|
+
return {
|
|
120
|
+
moves,
|
|
121
|
+
keep: all,
|
|
122
|
+
warnings: pending ? ['跨 harness 通用区(~/.agents/skills)中的技能将移入技能库并登记为本地技能(source unknown);移动后,其他 harness 将只剩常驻技能(P3,设计 §5.7)。'] : [],
|
|
123
|
+
notes: pending ? [] : [all.length
|
|
124
|
+
? `已是迁移后状态:跨 harness 通用区常驻链接 ${resident} 项、保留不搬 ${all.length - resident} 项(他人条目/同名冲突),无需再迁移。`
|
|
125
|
+
: '跨 harness 通用区(~/.agents/skills)没有待迁移的条目。'],
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** 执行 + 逐项认领 source:'unknown'(盘上内容即基线,§8.1),ledger 条目标 claimed 供 undo 删认领。 */
|
|
130
|
+
export async function applyAgents(roots, { ledger }, { fs: fsImpl = fs } = {}) {
|
|
131
|
+
const pv = previewAgents(roots, { fs: fsImpl });
|
|
132
|
+
const res = await apply(roots, { moves: pv.moves, ledger }, { fs: fsImpl });
|
|
133
|
+
const data = (await ledger.load()) ?? { moved: [] }; // 空预览时 apply 不落盘,load 为 null(M3 回归 2026-10-26)
|
|
134
|
+
for (const item of data.moved) {
|
|
135
|
+
if (item.claimed) continue;
|
|
136
|
+
try { claimSource(roots, { name: item.name, source: 'unknown' }, { fs: fsImpl }); item.claimed = true; } catch {}
|
|
137
|
+
}
|
|
138
|
+
await ledger.save(data);
|
|
139
|
+
return { ...res, kept: pv.keep.map((k) => k.name) };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** 回滚:复用 undo(claimed 条目回移后删认领 manifest)。 */
|
|
143
|
+
export async function undoAgents(roots, { ledger }, { fs: fsImpl = fs } = {}) {
|
|
144
|
+
return undo(roots, { ledger }, { fs: fsImpl });
|
|
145
|
+
}
|