@namewta/skills-hub 0.1.44 → 0.1.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +3 -2
  2. package/package.json +1 -1
  3. package/scripts/persistence/home.md +3 -0
  4. package/skills/home/home-doctor/SKILL.md +1 -1
  5. package/skills/home/home-doctor/references/diagnosis.md +1 -0
  6. package/skills/home/home-doctor/scripts/doctor.mjs +43 -1
  7. package/skills/home/home-project-changelog/SKILL.md +16 -0
  8. package/skills/home/home-project-changelog/assets/project-changelog.md +25 -0
  9. package/skills/home/home-project-changelog/assets/worker-brief.md +13 -0
  10. package/skills/home/home-project-changelog/references/git-ranges.md +41 -0
  11. package/skills/home/home-project-changelog/references/tools.md +83 -0
  12. package/skills/home/home-project-changelog/references/workflow.md +15 -0
  13. package/skills/home/home-project-changelog/references/writing.md +30 -0
  14. package/skills/home/home-project-changelog/scripts/changelog.mjs +253 -0
  15. package/skills/home/home-project-changelog/scripts/contract.mjs +149 -0
  16. package/skills/home/home-project-changelog/scripts/git.mjs +340 -0
  17. package/skills/home/home-project-changelog/scripts/storage.mjs +201 -0
  18. package/skills/home/home-project-changelog/scripts/summary.mjs +95 -0
  19. package/skills/home/home-route/SKILL.md +1 -1
  20. package/skills/home/home-route/references/routing.md +4 -0
  21. package/skills/home/home-route/scripts/route.mjs +21 -15
  22. package/skills/home/home-setup/SKILL.md +3 -3
  23. package/skills/home/home-setup/assets/repos.schema.json +5 -0
  24. package/skills/home/home-setup/references/git.md +4 -2
  25. package/skills/home/home-setup/references/registry.md +17 -1
  26. package/skills/home/home-setup/scripts/checkout-tools.mjs +73 -0
  27. package/skills/home/home-setup/scripts/git.mjs +1 -1
  28. package/skills/home/home-setup/scripts/refresh-branches.mjs +79 -0
  29. package/skills/home/home-setup/scripts/registry.mjs +9 -2
  30. package/skills/home/home-setup/scripts/restore.mjs +33 -72
  31. package/skills/home/home-workflow/SKILL.md +3 -0
  32. package/skills/home/home-workflow/references/delegation.md +2 -0
@@ -0,0 +1,340 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { spawnSync } from 'node:child_process';
6
+ import {
7
+ digest, expectId, isBranchRef, isInstant, isLine, isOid, isRevisionRef, requireThat, sameTracking, validTracking,
8
+ } from './contract.mjs';
9
+
10
+ const diffOptions = ['--no-ext-diff', '--no-textconv', '--no-color', '--no-relative',
11
+ '--find-renames=50%', '-l0', '--diff-algorithm=myers', '--no-indent-heuristic'];
12
+ const readTimeout = 60_000;
13
+ const networkTimeout = 180_000;
14
+
15
+ function gitAt(cwd) {
16
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0',
17
+ GIT_NO_LAZY_FETCH: '1', GIT_ATTR_NOSYSTEM: '1', GIT_LITERAL_PATHSPECS: '1' };
18
+ for (const key of ['GIT_DIR', 'GIT_COMMON_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_NAMESPACE',
19
+ 'GIT_PREFIX', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_SHALLOW_FILE',
20
+ 'GIT_REPLACE_REF_BASE', 'GIT_GRAFT_FILE', 'GIT_CONFIG', 'GIT_CONFIG_COUNT', 'GIT_CONFIG_PARAMETERS',
21
+ 'GIT_EXTERNAL_DIFF', 'GIT_ATTR_SOURCE']) delete env[key];
22
+ return (args, { accept = [0], input, network = false, hooks, attributesAt } = {}) => {
23
+ const options = ['--no-replace-objects', '-c', 'core.fsmonitor=false', '-c', 'protocol.ext.allow=never',
24
+ '-c', `core.attributesFile=${os.devNull}`, '-C', cwd];
25
+ if (hooks) options.push('-c', `core.hooksPath=${hooks}`);
26
+ if (attributesAt) options.push(`--attr-source=${attributesAt}`);
27
+ const result = spawnSync('git', [...options, ...args], {
28
+ env, input, maxBuffer: 128 * 1024 * 1024, timeout: network ? networkTimeout : readTimeout, windowsHide: true,
29
+ });
30
+ requireThat(!result.error && accept.includes(result.status), network ? 'REMOTE_UNAVAILABLE' : 'GIT_READ',
31
+ `Git ${args[0]} 失败(${result.error?.code ?? result.status ?? result.signal})。${network ? '无法确认本次远端节点,保留游标。' : '核对仓库对象与 Git 能力。'}`);
32
+ return { status: result.status, bytes: result.stdout, text: result.stdout.toString('utf8') };
33
+ };
34
+ }
35
+
36
+ const value = (git, args, options) => git(args, options).text.replace(/\r?\n$/u, '');
37
+ const lines = text => text.split(/\r?\n/u).filter(Boolean);
38
+
39
+ function checkRef(git, ref) {
40
+ requireThat(git(['check-ref-format', ref], { accept: [0, 1] }).status === 0, 'ARGUMENT', '引用须使用有效的完整 Git ref 名称。');
41
+ }
42
+
43
+ export function resolveCommit(git, revision) {
44
+ const commit = value(git, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${revision}^{commit}`], { accept: [0, 1] });
45
+ requireThat(isOid(commit), 'COMMIT_UNAVAILABLE', '引用没有可读取的 commit 对象。检查指定引用、对象和历史深度。');
46
+ return commit;
47
+ }
48
+
49
+ function fullCommit(git, commit) {
50
+ requireThat(isOid(commit) && resolveCommit(git, commit) === commit, 'INVALID_COMMIT', '节点须为实际 commit 的完整 OID。');
51
+ }
52
+
53
+ function safeRemoteUrl(url) {
54
+ requireThat(isLine(url) && !url.startsWith('-') && !/^[a-z][a-z0-9+.-]*::/iu.test(url), 'IDENTITY', '有效 fetch 地址不可用。');
55
+ if (/^[a-z][a-z0-9+.-]*:\/\//iu.test(url)) {
56
+ let parsed;
57
+ try { parsed = new URL(url); } catch { requireThat(false, 'IDENTITY', 'fetch 地址无法解析。'); }
58
+ requireThat(['http:', 'https:', 'ssh:', 'git:', 'file:'].includes(parsed.protocol)
59
+ && !parsed.password && !parsed.search && !parsed.hash && (!parsed.username || parsed.protocol === 'ssh:'),
60
+ 'IDENTITY', '使用已核实且不含内嵌认证的 Git fetch 地址。');
61
+ return parsed.protocol === 'file:' ? fileURLToPath(parsed) : null;
62
+ }
63
+ if (/^(?:[^@\s/:]+@)?(?:\[[^\]]+\]|[^\s/:]+):.+$/u.test(url) && !/^[a-z]:[\\/]/iu.test(url)) return null;
64
+ return url;
65
+ }
66
+
67
+ function verifyBinding(binding) {
68
+ requireThat(binding?.executionHost === os.hostname() && isLine(binding.checkout) && isLine(binding.commonDir)
69
+ && isLine(binding.sourceIdentity), 'IDENTITY', '需要当前主机的实际 checkout、common directory 与来源依据。');
70
+ const checkout = fs.realpathSync.native(binding.checkout);
71
+ const git = gitAt(checkout);
72
+ const gitRoot = fs.realpathSync.native(value(git, ['rev-parse', '--show-toplevel']));
73
+ const commonDir = fs.realpathSync.native(value(git, ['rev-parse', '--path-format=absolute', '--git-common-dir']));
74
+ requireThat(gitRoot === checkout && commonDir === binding.commonDir, 'IDENTITY', 'checkout 或 Git common directory 已变更,重新运行路由。');
75
+ const graftPath = value(git, ['rev-parse', '--path-format=absolute', '--git-path', 'info/grafts']);
76
+ requireThat(!fs.statSync(graftPath, { throwIfNoEntry: false })?.size, 'GIT_GRAPH', '仓库有 grafts,需从未改写的历史取证。');
77
+ if (binding.remote === null) {
78
+ requireThat(!value(git, ['remote']), 'IDENTITY', '本地独有登记与实际远端不符。');
79
+ } else {
80
+ const { name, url } = binding.remote;
81
+ requireThat(isLine(name) && !name.startsWith('-') && !/\s/u.test(name), 'IDENTITY', '主远端名称无效。');
82
+ safeRemoteUrl(url);
83
+ requireThat(value(git, ['remote', 'get-url', '--', name], { accept: [0, 2, 128] }) === url, 'IDENTITY', '实际主 fetch 地址已变化,重新核实登记。');
84
+ }
85
+ return git;
86
+ }
87
+
88
+ export function openRoutedSource(home, route) {
89
+ expectId(route?.repoId);
90
+ requireThat(route.status === 'resolved' && isInstant(route.observedAt) && isLine(route.homeRoot)
91
+ && fs.realpathSync.native(route.homeRoot) === home, 'IDENTITY', '提供本次 Home 的已核实定位结果。');
92
+ const evidence = route.identityEvidence;
93
+ const binding = {
94
+ checkout: route.actualCheckout, commonDir: route.commonDir, executionHost: route.executionHost,
95
+ sourceIdentity: `local:${route.repoId}`, remote: null,
96
+ };
97
+ if (evidence?.type === 'remote') {
98
+ const name = evidence.primaryRemote ?? evidence.matchedRemoteNames?.[0];
99
+ const effective = route.effectiveFetchUrls?.find(item => item.name === name);
100
+ requireThat(effective && ['network', 'opaque'].includes(evidence.expected?.kind) && isLine(evidence.expected.identity)
101
+ && (!evidence.actual || (evidence.actual.identity === evidence.expected.identity && evidence.actual.kind === evidence.expected.kind)),
102
+ 'IDENTITY', '定位结果缺少已核实的登记主远端与实际 fetch 地址。');
103
+ const file = safeRemoteUrl(effective.url);
104
+ requireThat((file === null) === (evidence.expected.kind === 'network'), 'IDENTITY', '登记的来源类型与实际 fetch 不同。');
105
+ if (file === null) {
106
+ requireThat(!/[?#\\]/u.test(evidence.expected.identity) && !/^[a-z]+:\/\/[^/]*:[^/@]*@/iu.test(evidence.expected.identity),
107
+ 'IDENTITY', '使用无凭据的仓库身份。');
108
+ binding.sourceIdentity = evidence.expected.identity;
109
+ } else {
110
+ // A filesystem remote is bound to its resolved location without storing the absolute name.
111
+ binding.sourceIdentity = `file:sha256:${digest(path.resolve(binding.checkout, file))}`;
112
+ }
113
+ binding.remote = { name, url: effective.url };
114
+ } else {
115
+ requireThat(evidence?.type === 'local-only' && evidence.commonDir === binding.commonDir, 'IDENTITY', '缺少本地独有仓库的 common directory 依据。');
116
+ }
117
+ return { binding, git: verifyBinding(binding) };
118
+ }
119
+
120
+ export function openFrozenSource(frozen) {
121
+ return verifyBinding(frozen.binding);
122
+ }
123
+
124
+ function observeRemote(git, remote, ref, hooks) {
125
+ const options = { network: true, hooks };
126
+ const output = git(['ls-remote', '--symref', '--exit-code', '--upload-pack=git-upload-pack', '--', remote, ref], options);
127
+ const entries = lines(output.text).map(line => line.split('\t')).filter(parts => parts.length === 2 && parts[1] === ref);
128
+ const symbolic = entries.filter(([entry]) => entry.startsWith('ref: '));
129
+ const objects = entries.filter(([entry]) => isOid(entry));
130
+ requireThat(objects.length === 1 && (ref !== 'HEAD' || symbolic.length === 1 && isBranchRef(symbolic[0][0].slice(5))),
131
+ 'REMOTE_REF', '无法从主远端确认指定引用或默认分支。');
132
+ return {
133
+ ref: ref === 'HEAD' ? symbolic[0][0].slice(5) : ref,
134
+ object: objects[0][0],
135
+ observedAt: new Date().toISOString(),
136
+ };
137
+ }
138
+
139
+ function fetchObject(git, remote, object, hooks, completeHistory) {
140
+ const args = ['fetch', '--upload-pack=git-upload-pack', '--no-tags', '--no-write-fetch-head', '--no-auto-maintenance',
141
+ '--no-prune', '--no-prune-tags', '--no-recurse-submodules', '--refmap='];
142
+ if (completeHistory && value(git, ['rev-parse', '--is-shallow-repository']) === 'true') args.push('--unshallow');
143
+ git([...args, '--', remote, object], { network: true, hooks });
144
+ }
145
+
146
+ function mappedRef(pattern, candidate) {
147
+ const [prefix, suffix] = pattern.split('*');
148
+ if (suffix === undefined) return pattern === candidate ? '' : null;
149
+ if (!candidate.startsWith(prefix) || !candidate.endsWith(suffix) || candidate.length < prefix.length + suffix.length) return null;
150
+ return candidate.slice(prefix.length, candidate.length - suffix.length);
151
+ }
152
+
153
+ function cachedCommit(git, tracking) {
154
+ const fetchRules = lines(git(['config', '--get-all', `remote.${tracking.remote}.fetch`], { accept: [0, 1] }).text);
155
+ const excluded = fetchRules.some(rule => rule.startsWith('^') && mappedRef(rule.slice(1), tracking.ref) !== null);
156
+ const references = new Set(fetchRules.filter(rule => !rule.startsWith('^')).flatMap(rule => {
157
+ const [source, destination] = rule.replace(/^\+/u, '').split(':');
158
+ const match = mappedRef(source, tracking.ref);
159
+ return match === null || !destination?.startsWith('refs/remotes/') ? [] : [destination.replace('*', match)];
160
+ }));
161
+ requireThat(!excluded && references.size === 1, 'OFFLINE_REF', '未找到与同一远端跟踪来源唯一对应的缓存引用。');
162
+ const [ref] = references;
163
+ checkRef(git, ref);
164
+ return resolveCommit(git, ref);
165
+ }
166
+
167
+ export function observeTarget(source, selection, previous) {
168
+ const { git, binding } = source;
169
+ const configured = selection.tracking ?? previous?.tracking;
170
+ if (configured) requireThat(validTracking(configured), 'ARGUMENT', '提供有效的跟踪类型与完整引用。');
171
+ if (configured && configured.kind !== 'remote-branch' || !binding.remote) {
172
+ requireThat(configured?.kind !== 'remote-branch' && !selection.offline && !selection.completeHistory,
173
+ 'ARGUMENT', '本地引用使用现场对象,远端缓存及补全仅用于远端分支。');
174
+ let tracking = configured;
175
+ if (!tracking) {
176
+ const ref = value(git, ['symbolic-ref', '--quiet', 'HEAD'], { accept: [0, 1] });
177
+ requireThat(isBranchRef(ref), 'DETACHED_HEAD', '分离 HEAD 需要显式指定本次节点。');
178
+ const head = git(['rev-parse', '--verify', '--quiet', '--end-of-options', 'HEAD^{commit}'], { accept: [0, 1] });
179
+ requireThat(head.status === 0, 'NO_COMMITS', '仓库尚无提交。');
180
+ tracking = { kind: 'local-branch', ref };
181
+ }
182
+ if (!isOid(tracking.ref)) checkRef(git, tracking.ref);
183
+ return { tracking, commit: resolveCommit(git, tracking.ref), observedAt: new Date().toISOString(), freshness: 'local' };
184
+ }
185
+ const remote = binding.remote.name;
186
+ requireThat(!configured || configured.remote === remote, 'IDENTITY', '跟踪的远端须是已核实的登记主远端。');
187
+ if (configured) checkRef(git, configured.ref);
188
+ if (selection.offline) {
189
+ requireThat(previous && configured && sameTracking(previous.tracking, configured) && previous.sourceIdentity === binding.sourceIdentity
190
+ && !selection.completeHistory, 'OFFLINE_REF', '离线需要已经成功保存的同源远端引用。');
191
+ return { tracking: configured, commit: cachedCommit(git, configured), observedAt: new Date().toISOString(), freshness: 'remote-cache' };
192
+ }
193
+ const hooks = fs.mkdtempSync(path.join(os.tmpdir(), 'home-changelog-hooks-'));
194
+ try {
195
+ const target = observeRemote(git, remote, configured?.ref ?? 'HEAD', hooks);
196
+ checkRef(git, target.ref);
197
+ fetchObject(git, remote, target.object, hooks, selection.completeHistory);
198
+ fullCommit(git, target.object);
199
+ verifyBinding(binding);
200
+ return { tracking: { kind: 'remote-branch', remote, ref: target.ref }, commit: target.object,
201
+ observedAt: target.observedAt, freshness: 'remote-observed' };
202
+ } finally { fs.rmdirSync(hooks); }
203
+ }
204
+
205
+ export function resolveInitialBase(source, ref, freshness) {
206
+ requireThat(isRevisionRef(ref), 'ARGUMENT', '起点使用完整 tag 引用或完整 commit OID。');
207
+ if (!isOid(ref)) checkRef(source.git, ref);
208
+ try { return resolveCommit(source.git, ref); }
209
+ catch (error) {
210
+ if (error.code !== 'COMMIT_UNAVAILABLE' || freshness !== 'remote-observed') throw error;
211
+ }
212
+ const { git, binding } = source;
213
+ const hooks = fs.mkdtempSync(path.join(os.tmpdir(), 'home-changelog-hooks-'));
214
+ try {
215
+ const remote = binding.remote.name;
216
+ const object = isOid(ref) ? ref : observeRemote(git, remote, ref, hooks).object;
217
+ fetchObject(git, remote, object, hooks, false);
218
+ return resolveCommit(git, object);
219
+ } finally { fs.rmdirSync(hooks); }
220
+ }
221
+
222
+ export function point(git, commit, observedAt) {
223
+ fullCommit(git, commit);
224
+ const committedAt = value(git, ['show', '-s', '--no-notes', '--no-show-signature', '--format=%cI', commit, '--']);
225
+ requireThat(isInstant(committedAt) && isInstant(observedAt), 'GIT_DATE', '无法确认提交或来源观测时间。');
226
+ return { commit, committedAt, observedAt };
227
+ }
228
+
229
+ export function shallowBoundaries(git) {
230
+ if (value(git, ['rev-parse', '--is-shallow-repository']) === 'false') return new Set();
231
+ const filename = value(git, ['rev-parse', '--path-format=absolute', '--git-path', 'shallow']);
232
+ const ids = lines(fs.readFileSync(filename, 'utf8'));
233
+ requireThat(ids.length && ids.every(isOid), 'SHALLOW_HISTORY', '无法核对 Git 浅历史边界。');
234
+ return new Set(ids);
235
+ }
236
+
237
+ export function listCommits(git, from, to, shallow) {
238
+ if (from) {
239
+ fullCommit(git, from);
240
+ const ancestor = git(['merge-base', '--is-ancestor', from, to], { accept: [0, 1] }).status === 0;
241
+ if (!ancestor) {
242
+ const truncated = shallow.size && lines(value(git, ['rev-list', to])).some(commit => shallow.has(commit));
243
+ requireThat(false, truncated ? 'SHALLOW_HISTORY' : 'DIVERGED',
244
+ truncated ? '浅历史无法证明祖先关系,获取完整的来源历史后重试。' : '上次成功节点不在目标历史中,需核实回退、重写或换源。');
245
+ }
246
+ }
247
+ const revision = from ? `${from}..${to}` : to;
248
+ const commits = lines(value(git, ['rev-list', '--topo-order', '--reverse', revision, '--']));
249
+ requireThat(commits.every(isOid) && commits.length === new Set(commits).size, 'GIT_GRAPH', '提交集合无法完整解析。');
250
+ requireThat(!commits.some(commit => shallow.has(commit)), 'SHALLOW_HISTORY', '完整范围跨越浅边界,补齐对象或改用完整 checkout。');
251
+ return commits;
252
+ }
253
+
254
+ export function headCount(git, to, shallow) {
255
+ if (shallow.size && lines(value(git, ['rev-list', to, '--'])).some(commit => shallow.has(commit))) return null;
256
+ const count = Number(value(git, ['rev-list', '--count', to, '--']));
257
+ requireThat(Number.isSafeInteger(count) && count > 0, 'GIT_GRAPH', '无法核实累计提交数。');
258
+ return count;
259
+ }
260
+
261
+ function emptyTree(git) {
262
+ const oid = value(git, ['hash-object', '-t', 'tree', '--stdin'], { input: '' });
263
+ requireThat(isOid(oid), 'GIT_READ', '无法取得当前对象格式的空树。');
264
+ return oid;
265
+ }
266
+
267
+ function diff(git, a, b, options, attributesAt = b) {
268
+ return git(['diff', ...diffOptions, ...options, a ?? emptyTree(git), b, '--'], { attributesAt }).text;
269
+ }
270
+
271
+ function nulFields(output) {
272
+ if (!output) return [];
273
+ requireThat(output.endsWith('\0'), 'GIT_DIFF', 'Git 差异的 NUL 记录不完整。');
274
+ return output.slice(0, -1).split('\0');
275
+ }
276
+
277
+ export function parseNumstat(output) {
278
+ const fields = nulFields(output);
279
+ let linesAdded = 0, linesDeleted = 0;
280
+ for (let index = 0; index < fields.length; index += 1) {
281
+ const row = /^(\d+|-)\t(\d+|-)\t([\s\S]*)$/u.exec(fields[index]);
282
+ requireThat(row && (row[1] === '-') === (row[2] === '-'), 'GIT_DIFF', '无法解析文本行统计。');
283
+ if (!row[3]) {
284
+ requireThat(fields[index + 1] && fields[index + 2], 'GIT_DIFF', '重命名统计缺少路径。');
285
+ index += 2;
286
+ }
287
+ if (row[1] === '-') continue;
288
+ linesAdded += Number(row[1]);
289
+ linesDeleted += Number(row[2]);
290
+ requireThat(Number.isSafeInteger(linesAdded) && Number.isSafeInteger(linesDeleted), 'GIT_DIFF', '文本行统计超出精确整数范围。');
291
+ }
292
+ return { linesAdded, linesDeleted };
293
+ }
294
+
295
+ export function measureLines(git, from, to) {
296
+ const attributes = value(git, ['rev-parse', '--path-format=absolute', '--git-path', 'info/attributes']);
297
+ if (fs.statSync(attributes, { throwIfNoEntry: false })?.size) {
298
+ return { linesAdded: null, linesDeleted: null, reason: 'Git info/attributes 会覆盖目标提交的文本属性。' };
299
+ }
300
+ return parseNumstat(diff(git, from, to, ['--numstat', '-z', '--ignore-submodules=all']));
301
+ }
302
+
303
+ function changedFiles(output) {
304
+ const fields = nulFields(output);
305
+ const files = [];
306
+ for (let index = 0; index < fields.length;) {
307
+ const status = fields[index++];
308
+ const from = fields[index++];
309
+ requireThat(/^[A-Z][0-9]*$/u.test(status) && from, 'GIT_DIFF', '无法解析文件变更。');
310
+ if (/^[RC]/u.test(status)) {
311
+ const to = fields[index++];
312
+ requireThat(to, 'GIT_DIFF', '重命名缺少目标路径。');
313
+ files.push({ status, from, path: to });
314
+ } else files.push({ status, path: from });
315
+ }
316
+ return files;
317
+ }
318
+
319
+ export function commitEvidence(git, commit, { patch = false, includeFiles = true } = {}) {
320
+ const log = git(['show', '-s', '--no-notes', '--no-show-signature', '--encoding=UTF-8',
321
+ '--format=%H%x00%P%x00%aI%x00%cI%x00%s%x00%B', commit, '--']).text.split('\0');
322
+ const [oid, rawParents, authoredAt, committedAt, subject, message] = log;
323
+ const parents = rawParents?.split(' ').filter(Boolean);
324
+ requireThat(log.length === 6 && oid === commit && parents?.every(isOid) && isInstant(authoredAt) && isInstant(committedAt),
325
+ 'GIT_READ', '提交元数据不完整。');
326
+ // Git hides parents at shallow boundaries. For a selected range those commits
327
+ // were already excluded, so every displayed merge can be compared to each parent.
328
+ const differences = includeFiles ? (parents.length ? parents : [null]).map(parent => ({
329
+ parent,
330
+ files: changedFiles(diff(git, parent, commit, ['--name-status', '-z', '--ignore-submodules=none'])),
331
+ ...(patch ? { patch: diff(git, parent, commit, ['--patch', '--ignore-submodules=dirty', '--submodule=short']) } : {}),
332
+ })) : [];
333
+ return { commit, parents, authoredAt, committedAt, subject, message, differences };
334
+ }
335
+
336
+ export function isReachable(git, commit, from) {
337
+ if (!from) return false;
338
+ fullCommit(git, commit);
339
+ return git(['merge-base', '--is-ancestor', commit, from], { accept: [0, 1] }).status === 0;
340
+ }
@@ -0,0 +1,201 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import {
6
+ documentStamp, expectId, hasOwn, isId, requireThat, revisionOf, sameStamp, validateState,
7
+ } from './contract.mjs';
8
+
9
+ const stateName = 'state.json';
10
+ const lockName = '.state.lock';
11
+ const emptyState = () => ({ formatVersion: 1, projects: {} });
12
+
13
+ export function openStore(home, filesystem = fs) {
14
+ requireThat(typeof home === 'string' && home.length > 0, 'ARGUMENT', '显式传入 Home 根目录。');
15
+ const requested = path.resolve(home);
16
+ const info = filename => filesystem.lstatSync(filename, { throwIfNoEntry: false });
17
+ const regularDirectory = entry => entry?.isDirectory() && !entry.isSymbolicLink();
18
+ requireThat(regularDirectory(info(requested)), 'UNSAFE_HOME', 'Home 根必须是已有普通目录。');
19
+ const root = filesystem.realpathSync.native(requested);
20
+
21
+ function directory(create = false) {
22
+ requireThat(regularDirectory(info(requested)) && filesystem.realpathSync.native(requested) === root,
23
+ 'UNSAFE_HOME', 'Home 根在操作期间发生变化。');
24
+ let current = root;
25
+ for (const segment of ['.agents', 'home', 'changelogs']) {
26
+ current = path.join(current, segment);
27
+ let entry = info(current);
28
+ if (!entry) {
29
+ if (!create) return null;
30
+ try { filesystem.mkdirSync(current, { mode: 0o700 }); }
31
+ catch (error) { if (error.code !== 'EEXIST') throw error; }
32
+ entry = info(current);
33
+ }
34
+ requireThat(regularDirectory(entry), 'UNSAFE_PATH', 'Home 日志的父路径须是同仓普通目录。');
35
+ }
36
+ return current;
37
+ }
38
+
39
+ function filename(name) {
40
+ const base = directory();
41
+ return base === null ? null : path.join(base, name);
42
+ }
43
+
44
+ function read(name) {
45
+ const target = filename(name);
46
+ const entry = target === null ? null : info(target);
47
+ if (!entry) return null;
48
+ requireThat(entry.isFile() && !entry.isSymbolicLink(), 'UNSAFE_PATH', `${name} 必须是同仓普通文件。`);
49
+ const fd = filesystem.openSync(target, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
50
+ try {
51
+ const opened = filesystem.fstatSync(fd);
52
+ requireThat(opened.isFile() && opened.ino === entry.ino && opened.dev === entry.dev,
53
+ 'UNSAFE_PATH', `${name} 已被替换。`);
54
+ const bytes = filesystem.readFileSync(fd);
55
+ const current = filename(name) === target && info(target);
56
+ requireThat(current && !current.isSymbolicLink() && current.ino === opened.ino && current.dev === opened.dev,
57
+ 'READ_CONFLICT', `${name} 在读取期间发生变化。`);
58
+ return bytes;
59
+ } finally { filesystem.closeSync(fd); }
60
+ }
61
+
62
+ function readState() {
63
+ const bytes = read(stateName);
64
+ if (bytes === null) return { state: emptyState(), bytes };
65
+ let state;
66
+ try { state = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
67
+ catch { requireThat(false, 'STATE_FORMAT', 'state.json 无法解析,保留现场并暂停写入。'); }
68
+ return { state: validateState(state), bytes };
69
+ }
70
+
71
+ function documentName(id) {
72
+ expectId(id);
73
+ return `${id}.md`;
74
+ }
75
+
76
+ function view(id) {
77
+ const doc = documentName(id);
78
+ const { state, bytes } = readState();
79
+ const project = hasOwn(state.projects, id) ? state.projects[id] : null;
80
+ return { state, stateBytes: bytes, project, previous: project?.ranges.at(-1) ?? null, document: read(doc) };
81
+ }
82
+
83
+ function putFile(target, bytes) {
84
+ const fd = filesystem.openSync(target, 'wx', 0o600);
85
+ try {
86
+ filesystem.writeFileSync(fd, bytes);
87
+ filesystem.fsyncSync(fd);
88
+ } finally { filesystem.closeSync(fd); }
89
+ }
90
+
91
+ function withLock(action) {
92
+ const base = directory(true);
93
+ const lock = path.join(base, lockName);
94
+ const token = JSON.stringify({ pid: process.pid, host: os.hostname(), startedAt: new Date().toISOString(), token: randomUUID() });
95
+ try { putFile(lock, token); }
96
+ catch (error) {
97
+ if (error.code !== 'EEXIST') throw error;
98
+ const lockBytes = read(lockName);
99
+ let holder;
100
+ try { holder = JSON.parse(lockBytes?.toString('utf8')); } catch { /* An in-flight or interrupted lock can be empty. */ }
101
+ requireThat(false, 'LOCK_BUSY', '另一写入者占用 Home 日志短锁,先核实持锁运行。', { lock: holder ?? null });
102
+ }
103
+ try { return action(); }
104
+ finally {
105
+ if (read(lockName)?.toString('utf8') === token) filesystem.unlinkSync(lock);
106
+ }
107
+ }
108
+
109
+ function replace(name, bytes, expected, code, check) {
110
+ const base = directory();
111
+ requireThat(base, 'UNSAFE_PATH', 'Home 日志目录在更新期间消失。');
112
+ const temporary = path.join(base, `.changelog-${randomUUID()}.tmp`);
113
+ try {
114
+ putFile(temporary, bytes);
115
+ requireThat(sameStamp(documentStamp(read(name)), expected), code, `${name} 已变化,重新读取后再处理。`);
116
+ check?.();
117
+ requireThat(directory() === base, 'UNSAFE_PATH', 'Home 日志目录在更新期间变化。');
118
+ filesystem.renameSync(temporary, path.join(base, name));
119
+ } finally {
120
+ if (directory() === base && info(temporary)?.isFile()) filesystem.unlinkSync(temporary);
121
+ }
122
+ }
123
+
124
+ function saveState(state, before, check) {
125
+ validateState(state);
126
+ const bytes = Buffer.from(`${JSON.stringify(state, null, 2)}\n`);
127
+ replace(stateName, bytes, documentStamp(before), 'STATE_CHANGED', check);
128
+ requireThat(sameStamp(documentStamp(read(stateName)), documentStamp(bytes)), 'STATE_CHANGED', 'state.json 写入回读不一致。');
129
+ return bytes;
130
+ }
131
+
132
+ function confirm(id, state, stateBytes, project, record) {
133
+ const { pending, ...success } = project;
134
+ const saved = { ...record, savedAt: new Date().toISOString() };
135
+ const next = { ...success, ranges: [...success.ranges, saved], lastSuccessfulRangeId: saved.rangeId };
136
+ const hasExpectedDocument = () => requireThat(sameStamp(documentStamp(read(documentName(id))), pending.afterDocument),
137
+ 'DOCUMENT_CHANGED', 'Markdown 在最终确认前已变化,保留 pending。');
138
+ saveState({ ...state, projects: { ...state.projects, [id]: next } }, stateBytes, hasExpectedDocument);
139
+ const result = view(id);
140
+ requireThat(result.previous?.rangeId === saved.rangeId && !result.project.pending
141
+ && sameStamp(documentStamp(result.document), pending.afterDocument), 'READ_CONFLICT', '成功记录或 Markdown 回读不一致。');
142
+ return result.previous;
143
+ }
144
+
145
+ function commit(id, expected, record, document) {
146
+ return withLock(() => {
147
+ const current = view(id);
148
+ requireThat(!current.project?.pending, 'PENDING', '该项目存在待恢复写入,先执行 recover。');
149
+ if (current.previous?.rangeId === record.rangeId) {
150
+ requireThat(current.document !== null, 'DOCUMENT_MISSING', '成功记录对应的 Markdown 丢失,先恢复正文。');
151
+ return { status: 'already-saved', record: current.previous };
152
+ }
153
+ requireThat(revisionOf(current.project) === expected.projectRevision
154
+ && sameStamp(documentStamp(current.document), expected.document), 'STALE_CANDIDATE', '项目状态或 Markdown 已变化,重读后重新生成。');
155
+ const pending = {
156
+ transactionId: randomUUID(), rangeId: record.rangeId, expectedProjectRevision: expected.projectRevision,
157
+ beforeDocument: expected.document, afterDocument: documentStamp(document), nextRecord: record,
158
+ };
159
+ const project = {
160
+ ...(current.project ?? { initialization: record.initialization, ranges: [], lastSuccessfulRangeId: null }), pending,
161
+ };
162
+ const state = { ...current.state, projects: { ...current.state.projects, [id]: project } };
163
+ const intentBytes = saveState(state, current.stateBytes);
164
+ replace(documentName(id), document, pending.beforeDocument, 'DOCUMENT_CHANGED');
165
+ requireThat(sameStamp(documentStamp(read(documentName(id))), pending.afterDocument), 'DOCUMENT_CHANGED', 'Markdown 写入回读不一致,保留 pending。');
166
+ return { status: 'saved', record: confirm(id, state, intentBytes, project, record) };
167
+ });
168
+ }
169
+
170
+ function recover(id) {
171
+ expectId(id);
172
+ if (!view(id).project?.pending) return { status: 'no-pending' };
173
+ return withLock(() => {
174
+ const { state, stateBytes, project, previous, document } = view(id);
175
+ if (!project?.pending) return { status: 'no-pending' };
176
+ const { pending, ...success } = project;
177
+ const stamp = documentStamp(document);
178
+ if (sameStamp(stamp, pending.afterDocument)) {
179
+ return { status: 'confirmed', record: confirm(id, state, stateBytes, project, pending.nextRecord) };
180
+ }
181
+ requireThat(sameStamp(stamp, pending.beforeDocument), 'RECOVERY_CONFLICT', 'Markdown 与写入前后摘要均不同,保留正文和 pending。');
182
+ const projects = { ...state.projects };
183
+ if (previous) projects[id] = success;
184
+ else delete projects[id];
185
+ saveState({ ...state, projects }, stateBytes, () => requireThat(
186
+ sameStamp(documentStamp(read(documentName(id))), pending.beforeDocument), 'RECOVERY_CONFLICT', 'Markdown 在恢复时发生变化,保留 pending。',
187
+ ));
188
+ return { status: 'cleared', record: previous };
189
+ });
190
+ }
191
+
192
+ function list() {
193
+ const base = directory();
194
+ if (base === null) return [];
195
+ return filesystem.readdirSync(base, { withFileTypes: true })
196
+ .filter(entry => entry.isFile() && entry.name.endsWith('.md') && isId(entry.name.slice(0, -3)))
197
+ .map(entry => entry.name.slice(0, -3)).sort();
198
+ }
199
+
200
+ return { root, view, commit, recover, list, show: id => read(documentName(id)) };
201
+ }
@@ -0,0 +1,95 @@
1
+ import {
2
+ categories, expectKeys, isLine, isOid, markers, requireThat,
3
+ } from './contract.mjs';
4
+ import { isReachable } from './git.mjs';
5
+
6
+ const internalText = /(?:^|[^a-z0-9])[a-f0-9]{7,64}(?![a-z0-9])|[<>]|\]\s*[\[(]|:\/\/|\bwww\.|(?:^|\s)#\d+|\brangeId\b|\bB\.\.H\b/iu;
7
+
8
+ function displayLine(value) {
9
+ return isLine(value) && !internalText.test(value);
10
+ }
11
+
12
+ export function candidateEntries(candidate, snapshot, git) {
13
+ const { repoId, record, commits } = snapshot;
14
+ if (!commits.length && candidate === undefined) return [];
15
+ expectKeys(candidate, ['repoId', 'rangeId', 'batches', 'entries', 'noSignificantChanges', 'displayName'],
16
+ 'CANDIDATE', '候选需提供归属、范围、已处理批次和分类条目。');
17
+ requireThat(candidate.repoId === repoId && candidate.rangeId === record.rangeId,
18
+ 'CANDIDATE', '候选项目或冻结区间不匹配。');
19
+ requireThat(candidate.displayName === undefined || displayLine(candidate.displayName), 'DISPLAY', '项目显示名需是单行文字。');
20
+ requireThat(Array.isArray(candidate.batches) && candidate.batches.every(batch => Array.isArray(batch) && batch.length > 0)
21
+ && Array.isArray(candidate.entries), 'CANDIDATE', '候选需列出实际完成的取证批次与分类条目。');
22
+ const wanted = new Set(commits);
23
+ const processed = new Set(candidate.batches.flat());
24
+ requireThat(processed.size === wanted.size && [...processed].every(oid => wanted.has(oid)),
25
+ 'COVERAGE', '实际处理的提交集合与冻结范围不同。');
26
+ requireThat(commits.length || !candidate.entries.length, 'CANDIDATE', '基线无需历史摘要。');
27
+ requireThat(!commits.length || candidate.entries.length > 0 || candidate.noSignificantChanges === true,
28
+ 'CANDIDATE', '没有需单列的变更时,在候选中确认已复核范围。');
29
+ for (const entry of candidate.entries) {
30
+ expectKeys(entry, ['category', 'text', 'commits', 'markers', 'relatedCommits'], 'CANDIDATE', '条目需提供分类、描述和主要证据。');
31
+ requireThat(categories.includes(entry.category) && displayLine(entry.text),
32
+ 'DISPLAY', '条目使用精简分类和单行描述,证据身份单独提供。');
33
+ requireThat(Array.isArray(entry.commits) && entry.commits.length > 0 && entry.commits.every(oid => wanted.has(oid)),
34
+ 'COVERAGE', '条目的主要证据须在冻结范围内。');
35
+ requireThat(entry.markers === undefined || Array.isArray(entry.markers) && entry.markers.every(marker => markers.includes(marker)),
36
+ 'DISPLAY', '使用已定义的影响标识。');
37
+ requireThat(entry.relatedCommits === undefined || Array.isArray(entry.relatedCommits)
38
+ && entry.relatedCommits.every(oid => isOid(oid) && !wanted.has(oid) && isReachable(git, oid, record.from?.commit)),
39
+ 'COVERAGE', '跨区间关联证据须可从区间起点查到。');
40
+ }
41
+ return candidate.entries;
42
+ }
43
+
44
+ function oneLine(text) {
45
+ return text.trim().replace(/[[\]]/gu, '\\$&');
46
+ }
47
+
48
+ function section(record, entries) {
49
+ const { displayDates: { from, to }, kind, stats } = record;
50
+ const parts = [`## ${to}`];
51
+ if (kind === 'full-history') parts.push(`首次整理至 ${to}。`);
52
+ else if (kind === 'delta') {
53
+ parts.push(`统计区间为 ${from} 至 ${to}。`);
54
+ if (record.previousRangeId === null) parts.push('指定起点之前的变更未回填。');
55
+ if (record.changeReason) parts.push('本次按新指定的引用继续记录。');
56
+ } else {
57
+ const lead = kind === 'rebaseline' ? '重新建立基线。' : record.initialization.mode === 'from' ? '所选初始区间为空。' : '';
58
+ parts.push(`${lead}从 ${to} 开始记录,之前的变更未回填。`);
59
+ }
60
+ if (record.freshness === 'remote-cache') parts.push('本次采用本地缓存,远端新鲜度未验证。');
61
+ const number = value => value === null ? '未取得' : value.toLocaleString('en-US');
62
+ const line = key => stats[key] === null && record.coverage === 'not-backfilled' ? '—' : number(stats[key]);
63
+ parts.push([
64
+ '| 项目累计提交 | 本次提交 | 新增文本行 | 删除文本行 |',
65
+ '| ---: | ---: | ---: | ---: |',
66
+ `| ${number(stats.totalCommitCountAtHead)} | ${number(stats.rangeCommitCount)} | ${line('linesAdded')} | ${line('linesDeleted')} |`,
67
+ ].join('\n'));
68
+ for (const category of categories) {
69
+ const items = entries.filter(entry => entry.category === category).map(entry => {
70
+ const impacts = [...new Set(entry.markers)].map(marker => `**[${marker}]**`).join(' ');
71
+ return `- ${impacts ? `${impacts} ` : ''}${oneLine(entry.text)}`;
72
+ });
73
+ if (items.length) parts.push(`### ${category}`, items.join('\n'));
74
+ }
75
+ if (record.coverage === 'complete' && !entries.length) parts.push('本次没有需单列的变更。');
76
+ return parts.join('\n\n');
77
+ }
78
+
79
+ export function renderNext(before, repoId, displayName, record, entries) {
80
+ const body = section(record, entries);
81
+ if (before === null || !before.length) return Buffer.from(`# ${oneLine(displayName ?? repoId)} 变更日志\n\n${body}\n`);
82
+ let existing;
83
+ try { existing = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(before); }
84
+ catch { requireThat(false, 'DOCUMENT_FORMAT', '已有 Markdown 需要可读的 UTF-8 内容,保留原件。'); }
85
+ const start = existing.match(/^\uFEFF?(?:(?:---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$))?(?:[ \t]*\r?\n)*# [^\r\n]+(?:\r?\n|$)|(?:---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)))/u)?.[0]
86
+ ?? (existing.startsWith('\uFEFF') ? '\uFEFF' : '');
87
+ const at = Buffer.byteLength(start);
88
+ const insertion = `${at && start !== '\uFEFF' ? (start.endsWith('\n') ? '\n' : '\n\n') : ''}${body}\n${at < before.length ? '\n' : ''}`;
89
+ const newline = existing.match(/\r?\n/u)?.[0] ?? '\n';
90
+ return Buffer.concat([
91
+ before.subarray(0, at),
92
+ Buffer.from(insertion.replaceAll('\n', newline)),
93
+ before.subarray(at),
94
+ ]);
95
+ }
@@ -14,7 +14,7 @@ description: 只读定位已登记项目,解析项目名、别名、分组、
14
14
  1. 从实际 Home 根读取 `./.agents/home/AGENTS.md`。按用户所指 ID、别名或分组读取登记及合法本机路径覆盖。准确 ID 优先,别名重名时返回候选,以登记和用户明确指定的目标核对身份。
15
15
  2. 按显式 checkout → local.json → 登记路径选择入口。核对真实路径、Git root、主 remote 和 common directory,支持 `.git` 为文件的 worktree;路径指向不同仓库时停止该目标。v2 按指定主 remote 的首 fetch URL 核验,其他 remote 的变动单独报告;旧 v1 沿用原身份规则。
16
16
  3. 只确认统一入口是否存在;项目资料引用只解析 `repo ID + checkout 内相对路径`,不读取正文或扫描项目知识。
17
- 4. 将解析结果交回调用者。需要项目调查/开发时,由 `home-workflow` 按用户选择调用当地派遣方法;需要登记修改交 `home-setup`,结构异常交 `home-doctor`。
17
+ 4. 将解析结果交回调用者。项目调查和开发由 `home-workflow` 按用户选择调用当地派遣方法。已授权的 Git 区间采集交 `home-project-changelog`。登记修改交 `home-setup`,结构异常交 `home-doctor`。
18
18
 
19
19
  ## 包内工具
20
20