@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,253 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { isDeepStrictEqual, parseArgs } from 'node:util';
5
+ import {
6
+ dateAt, documentStamp, expectId, expectKeys, isDigest, isInstant, isLine, isOid, isRevisionRef,
7
+ lineMetricScope, rangeIdFor, requireThat, revisionOf, sameStamp, sameTracking, validTracking,
8
+ } from './contract.mjs';
9
+ import {
10
+ commitEvidence, headCount, isReachable, listCommits, measureLines, observeTarget, openFrozenSource, openRoutedSource,
11
+ point, resolveInitialBase, shallowBoundaries,
12
+ } from './git.mjs';
13
+ import { openStore } from './storage.mjs';
14
+ import { candidateEntries, renderNext } from './summary.mjs';
15
+
16
+ function checkSelection(selection, view) {
17
+ expectKeys(selection, ['tracking', 'mode', 'base', 'timezone', 'offline', 'completeHistory', 'adoptExisting',
18
+ 'changeReason', 'rebaselineReason'], 'ARGUMENT', '选择文件包含未知字段或格式无效。');
19
+ requireThat(!view.project?.pending, 'PENDING', '该项目有待恢复写入,先执行 recover。');
20
+ requireThat(selection.tracking === undefined || validTracking(selection.tracking), 'ARGUMENT', '跟踪引用无效。');
21
+ for (const key of ['offline', 'completeHistory', 'adoptExisting']) {
22
+ requireThat(selection[key] === undefined || typeof selection[key] === 'boolean', 'ARGUMENT', `${key} 使用布尔值。`);
23
+ }
24
+ for (const key of ['timezone', 'changeReason', 'rebaselineReason']) {
25
+ requireThat(selection[key] === undefined || isLine(selection[key]), 'ARGUMENT', `${key} 使用单行值。`);
26
+ }
27
+ if (view.previous) {
28
+ requireThat(view.document !== null, 'DOCUMENT_MISSING', '成功记录对应的 Markdown 丢失,先恢复实际正文。');
29
+ requireThat(selection.mode === undefined && selection.base === undefined && !selection.adoptExisting,
30
+ 'ARGUMENT', '此项目已初始化。按既有节点续写,或明确提供重建基线的理由。');
31
+ return;
32
+ }
33
+ const mode = selection.mode ?? 'full-history';
34
+ requireThat(['full-history', 'from', 'baseline'].includes(mode) && (mode === 'from' ? isRevisionRef(selection.base) : selection.base === undefined)
35
+ && selection.changeReason === undefined && selection.rebaselineReason === undefined,
36
+ 'ARGUMENT', '首次采用全历史、指定起点或只建基线。');
37
+ if (view.document !== null) {
38
+ requireThat(selection.adoptExisting && mode !== 'full-history', 'ORPHAN_DOCUMENT',
39
+ '已有 Markdown 缺少成功状态。先恢复 JSON,或按明确意图保留原文并接管。');
40
+ } else requireThat(!selection.adoptExisting, 'ARGUMENT', '没有待接管的 Markdown。');
41
+ }
42
+
43
+ export function freeze(home, route, selection = {}) {
44
+ expectId(route?.repoId);
45
+ const store = openStore(home);
46
+ const view = store.view(route.repoId);
47
+ checkSelection(selection, view);
48
+ const source = openRoutedSource(store.root, route);
49
+ requireThat(!view.previous || view.previous.sourceIdentity === source.binding.sourceIdentity || selection.rebaselineReason,
50
+ 'SOURCE_CHANGED', '登记来源已变化,核实身份后明确选择重建基线。');
51
+ const timezone = selection.timezone ?? view.previous?.displayDates.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
52
+ dateAt(new Date(), timezone);
53
+ const target = observeTarget(source, selection, view.previous);
54
+ const base = selection.mode === 'from' ? resolveInitialBase(source, selection.base, target.freshness) : null;
55
+ return {
56
+ formatVersion: 1, homeRoot: store.root, repoId: route.repoId, binding: source.binding, selection, timezone, base,
57
+ expectedProjectRevision: revisionOf(view.project), ...target,
58
+ };
59
+ }
60
+
61
+ function checkFrozen(frozen, view) {
62
+ requireThat(frozen?.formatVersion === 1 && isOid(frozen.commit) && isInstant(frozen.observedAt)
63
+ && isLine(frozen.timezone) && validTracking(frozen.tracking)
64
+ && (frozen.expectedProjectRevision === null || isDigest(frozen.expectedProjectRevision)),
65
+ 'FROZEN', '需要本次 freeze 的完整结果。');
66
+ checkSelection(frozen.selection, view);
67
+ requireThat(frozen.expectedProjectRevision === revisionOf(view.project), 'STALE_CANDIDATE', '项目的成功状态已变化,重新冻结。');
68
+ const { tracking, binding, freshness, selection } = frozen;
69
+ requireThat((selection.mode === 'from' ? isOid(frozen.base) : frozen.base === null)
70
+ && (!selection.tracking || sameTracking(selection.tracking, tracking))
71
+ && (tracking.kind === 'remote-branch' ? tracking.remote === binding?.remote?.name
72
+ && freshness === (selection.offline ? 'remote-cache' : 'remote-observed') : freshness === 'local'),
73
+ 'FROZEN', '冻结记录中的初始边界、跟踪引用或观测方式不一致。');
74
+ }
75
+
76
+ function statistics(git, to, shallow, count, lines) {
77
+ const totalCommitCountAtHead = headCount(git, to, shallow);
78
+ const unavailable = {};
79
+ if (totalCommitCountAtHead === null) unavailable.totalCommitCountAtHead = '可达历史存在未补全的浅边界。';
80
+ if (lines.linesAdded === null) {
81
+ unavailable.linesAdded = lines.reason;
82
+ unavailable.linesDeleted = lines.reason;
83
+ }
84
+ return { totalCommitCountAtHead, rangeCommitCount: count, linesAdded: lines.linesAdded, linesDeleted: lines.linesDeleted,
85
+ lineMetricScope, unavailable };
86
+ }
87
+
88
+ function collect(frozen, view, git) {
89
+ const { previous } = view;
90
+ const { repoId, timezone, selection, tracking, freshness, observedAt } = frozen;
91
+ const { sourceIdentity } = frozen.binding;
92
+ const to = point(git, frozen.commit, observedAt);
93
+ const shallow = shallowBoundaries(git);
94
+ const sameSource = !previous || previous.sourceIdentity === sourceIdentity;
95
+ const movedTracking = previous && !sameTracking(tracking, previous.tracking);
96
+ requireThat(sameSource || selection.rebaselineReason, 'SOURCE_CHANGED', '核实新登记身份并明确重建基线。');
97
+ requireThat(!movedTracking || (selection.tracking && selection.changeReason) || selection.rebaselineReason,
98
+ 'TRACKING_CHANGED', '更换已保存的引用需要明确目标和理由。');
99
+ if (previous && sameSource && !movedTracking && previous.to.commit === to.commit && !selection.rebaselineReason) {
100
+ return { status: 'no-changes', repoId, tracking, freshness, to, stats: statistics(git, to.commit, shallow, 0, { linesAdded: 0, linesDeleted: 0 }) };
101
+ }
102
+
103
+ const initialization = view.project?.initialization ?? { mode: selection.mode ?? 'full-history', base: frozen.base };
104
+ let kind, from = null, changeReason;
105
+ if (previous) {
106
+ if (selection.rebaselineReason || movedTracking && previous.to.commit === to.commit) {
107
+ kind = 'rebaseline';
108
+ changeReason = selection.rebaselineReason ?? selection.changeReason;
109
+ } else {
110
+ kind = 'delta';
111
+ from = previous.to;
112
+ if (movedTracking) changeReason = selection.changeReason;
113
+ }
114
+ } else if (initialization.mode === 'from' && initialization.base !== to.commit) {
115
+ kind = 'delta';
116
+ from = point(git, initialization.base, observedAt);
117
+ } else kind = initialization.mode === 'full-history' ? 'full-history' : 'baseline';
118
+
119
+ const complete = kind === 'full-history' || kind === 'delta';
120
+ const commits = complete ? listCommits(git, from?.commit, to.commit, shallow) : [];
121
+ const metrics = complete ? measureLines(git, from?.commit, to.commit)
122
+ : { linesAdded: null, linesDeleted: null, reason: '本次只保存基线,历史未回填。' };
123
+ const record = {
124
+ kind, sourceIdentity, tracking, initialization, previousRangeId: previous?.rangeId ?? null,
125
+ from, to, freshness,
126
+ ...(changeReason ? { changeReason, previousSourceIdentity: previous.sourceIdentity } : {}),
127
+ displayDates: { from: from ? dateAt(from.observedAt, timezone) : null, to: dateAt(to.observedAt, timezone), timezone },
128
+ coverage: complete ? 'complete' : 'not-backfilled',
129
+ stats: statistics(git, to.commit, shallow, commits.length, metrics),
130
+ };
131
+ return { status: 'ready', repoId, frozen, record: { ...record, rangeId: rangeIdFor(repoId, record) }, commits,
132
+ expected: { projectRevision: frozen.expectedProjectRevision, document: documentStamp(view.document) } };
133
+ }
134
+
135
+ export function snapshot(home, frozen) {
136
+ const store = openStore(home);
137
+ requireThat(frozen?.homeRoot === store.root, 'IDENTITY', '冻结节点来自另一 Home。');
138
+ const view = store.view(frozen?.repoId);
139
+ checkFrozen(frozen, view);
140
+ return collect(frozen, view, openFrozenSource(frozen));
141
+ }
142
+
143
+ export function evidence(input, { offset = 0, limit = 25, commit, related, patch = false } = {}) {
144
+ requireThat(input?.status === 'ready' && Array.isArray(input.commits) && input.record?.rangeId === rangeIdFor(input.repoId, input.record),
145
+ 'SNAPSHOT', '取证需要完整的 snapshot 结果。');
146
+ requireThat(Number.isSafeInteger(offset) && offset >= 0 && offset <= input.commits.length
147
+ && Number.isSafeInteger(limit) && limit > 0 && ![commit, related].every(Boolean), 'ARGUMENT', '批次偏移、数量或单提交参数无效。');
148
+ const git = openFrozenSource(input.frozen);
149
+ if (commit) requireThat(input.commits.includes(commit), 'COVERAGE', '指定提交不属于冻结范围。');
150
+ if (related) requireThat(isOid(related) && !input.commits.includes(related) && isReachable(git, related, input.record.from?.commit),
151
+ 'COVERAGE', '关联提交不属于起点历史。');
152
+ const batch = commit || related ? [commit ?? related] : input.commits.slice(offset, offset + limit);
153
+ requireThat(batch.every(isOid) && (!patch || batch.length === 1), 'ARGUMENT', '一次读取一个提交的补丁。');
154
+ const nextOffset = offset + batch.length;
155
+ return {
156
+ repoId: input.repoId, rangeId: input.record.rangeId, related: Boolean(related),
157
+ evidence: batch.map(oid => commitEvidence(git, oid, { patch })),
158
+ nextOffset: commit || related || nextOffset >= input.commits.length ? null : nextOffset,
159
+ };
160
+ }
161
+
162
+ export function apply(home, input, candidate, { filesystem } = {}) {
163
+ requireThat(input?.status === 'ready' && input.repoId === input.frozen?.repoId
164
+ && isDigest(input.record?.rangeId), 'SNAPSHOT', '写入需要待保存的完整 snapshot。');
165
+ const store = openStore(home, filesystem);
166
+ requireThat(input.frozen.homeRoot === store.root, 'IDENTITY', '冻结节点来自另一 Home。');
167
+ const view = store.view(input.repoId);
168
+ requireThat(!view.project?.pending, 'PENDING', '该项目有待恢复写入,先执行 recover。');
169
+ if (view.previous?.rangeId === input.record.rangeId) {
170
+ requireThat(view.document !== null, 'DOCUMENT_MISSING', '成功记录对应的 Markdown 丢失,先恢复正文。');
171
+ return { status: 'already-saved', record: view.previous };
172
+ }
173
+ checkFrozen(input.frozen, view);
174
+ requireThat(sameStamp(documentStamp(view.document), input.expected?.document), 'STALE_CANDIDATE', 'Markdown 已变化,重读后重新生成。');
175
+ const git = openFrozenSource(input.frozen);
176
+ const actual = collect(input.frozen, view, git);
177
+ requireThat(isDeepStrictEqual(input, actual), 'SNAPSHOT', '实际范围、统计或写入基线与 snapshot 不一致。');
178
+ const entries = candidateEntries(candidate, actual, git);
179
+ const record = { ...actual.record, generatedAt: new Date().toISOString(), savedAt: null };
180
+ const document = renderNext(view.document, actual.repoId, candidate?.displayName, record, entries);
181
+ return store.commit(actual.repoId, actual.expected, record, document);
182
+ }
183
+
184
+ const commands = {
185
+ freeze: { strings: ['home', 'route', 'selection', 'output'], required: ['home', 'route'] },
186
+ snapshot: { strings: ['home', 'frozen', 'output'], required: ['home', 'frozen'] },
187
+ evidence: { strings: ['snapshot', 'offset', 'limit', 'commit', 'related', 'output'], bools: ['patch'], required: ['snapshot'] },
188
+ apply: { strings: ['home', 'snapshot', 'candidate'], required: ['home', 'snapshot'] },
189
+ recover: { strings: ['home', 'repo'], required: ['home', 'repo'] },
190
+ show: { strings: ['home', 'repo'], required: ['home'] },
191
+ };
192
+
193
+ function json(filename) {
194
+ try { return JSON.parse(fs.readFileSync(filename, 'utf8').replace(/^\uFEFF/u, '')); }
195
+ catch (error) { requireThat(false, 'INPUT', `无法读取 UTF-8 JSON(${error.code ?? '语法错误'})。`); }
196
+ }
197
+
198
+ export function main(argv = process.argv.slice(2)) {
199
+ try {
200
+ if (argv.length === 1 && argv[0] === '--help') {
201
+ console.log('用法:node changelog.mjs freeze | snapshot | evidence | apply | recover | show\n各命令使用 --help 查看参数。正式资料在指定 Home 的 .agents/home/changelogs/。');
202
+ return 0;
203
+ }
204
+ const [command, ...args] = argv;
205
+ requireThat(Object.hasOwn(commands, command), 'ARGUMENT', '用 --help 查看项目变更日志命令。');
206
+ const { strings, required, bools = [] } = commands[command];
207
+ if (args.length === 1 && args[0] === '--help') {
208
+ console.log([`node changelog.mjs ${command}`,
209
+ ...strings.map(name => required.includes(name) ? `--${name} VALUE` : `[--${name} VALUE]`),
210
+ ...bools.map(name => `[--${name}]`)].join(' '));
211
+ return 0;
212
+ }
213
+ const { values } = parseArgs({ args, options: Object.fromEntries([
214
+ ...strings.map(name => [name, { type: 'string' }]), ...bools.map(name => [name, { type: 'boolean' }]),
215
+ ]) });
216
+ requireThat(required.every(name => isLine(values[name])), 'ARGUMENT', '缺少必需参数,按命令的 --help 核对。');
217
+ let result;
218
+ switch (command) {
219
+ case 'freeze': result = freeze(values.home, json(values.route), values.selection ? json(values.selection) : {}); break;
220
+ case 'snapshot': result = snapshot(values.home, json(values.frozen)); break;
221
+ case 'evidence': result = evidence(json(values.snapshot), {
222
+ offset: Number(values.offset ?? 0), limit: Number(values.limit ?? 25),
223
+ commit: values.commit, related: values.related, patch: values.patch,
224
+ }); break;
225
+ case 'apply': result = apply(values.home, json(values.snapshot), values.candidate ? json(values.candidate) : undefined); break;
226
+ case 'recover': result = openStore(values.home).recover(values.repo); break;
227
+ case 'show': {
228
+ const store = openStore(values.home);
229
+ if (values.repo === undefined) { result = { projects: store.list() }; break; }
230
+ const bytes = store.show(values.repo);
231
+ requireThat(bytes !== null, 'DOCUMENT_MISSING', '未找到此项目的 Markdown。');
232
+ process.stdout.write(bytes);
233
+ return 0;
234
+ }
235
+ }
236
+ const output = `${JSON.stringify(result, null, 2)}\n`;
237
+ if (values.output) fs.writeFileSync(values.output, output, { flag: 'wx', mode: 0o600 });
238
+ else process.stdout.write(output);
239
+ return 0;
240
+ } catch (error) {
241
+ console.error(JSON.stringify({ status: 'blocked', code: error.code ?? 'FAILED', message: error.message,
242
+ ...(error.code === 'LOCK_BUSY' ? { lock: error.lock } : {}) }));
243
+ return 2;
244
+ }
245
+ }
246
+
247
+ function isDirectInvocation() {
248
+ if (!process.argv[1]) return false;
249
+ try { return fs.realpathSync.native(process.argv[1]) === fs.realpathSync.native(fileURLToPath(import.meta.url)); }
250
+ catch { return false; }
251
+ }
252
+
253
+ if (isDirectInvocation()) process.exitCode = main();
@@ -0,0 +1,149 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ export const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+ export const isLine = value => typeof value === 'string' && Boolean(value.trim()) && !/[\x00-\x1f\x7f]/u.test(value);
5
+ export const isId = value => typeof value === 'string' && /^[a-z0-9][a-z0-9-]*$/u.test(value)
6
+ && !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/u.test(value);
7
+ export const isOid = value => typeof value === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(value);
8
+ export const isDigest = value => typeof value === 'string' && /^[a-f0-9]{64}$/u.test(value);
9
+ export const digest = bytes => createHash('sha256').update(bytes).digest('hex');
10
+ export const revisionOf = project => project === null ? null : digest(JSON.stringify(project));
11
+ export const hasOwn = (object, key) => Object.hasOwn(object, key);
12
+ export const isBranchRef = value => isLine(value) && value.startsWith('refs/heads/');
13
+ export const isRevisionRef = value => isOid(value) || (isLine(value) && value.startsWith('refs/tags/'));
14
+ export const categories = ['功能', '修复', '重构', '优化', '维护'];
15
+ export const markers = ['破坏性', '安全', '弃用', '移除', '回退'];
16
+ export const lineMetricScope = 'all-git-text-files';
17
+
18
+ export function requireThat(condition, code, message, details = {}) {
19
+ if (!condition) throw Object.assign(new Error(message), { code, ...details });
20
+ }
21
+
22
+ export function expectId(id) {
23
+ requireThat(isId(id), 'ARGUMENT', '使用 Home 登记的稳定项目 ID。');
24
+ }
25
+
26
+ export function expectKeys(value, keys, code, label) {
27
+ requireThat(isObject(value) && Object.keys(value).every(key => keys.includes(key)), code, label);
28
+ }
29
+
30
+ export function validTracking(value) {
31
+ if (!isObject(value)) return false;
32
+ switch (value.kind) {
33
+ case 'remote-branch': return isLine(value.remote) && isBranchRef(value.ref);
34
+ case 'local-branch': return isBranchRef(value.ref) && !hasOwn(value, 'remote');
35
+ case 'revision': return isRevisionRef(value.ref) && !hasOwn(value, 'remote');
36
+ default: return false;
37
+ }
38
+ }
39
+
40
+ export function sameTracking(a, b) {
41
+ return a.kind === b.kind && a.ref === b.ref && a.remote === b.remote;
42
+ }
43
+
44
+ const formatters = new Map();
45
+ export function dateAt(time, timezone) {
46
+ try {
47
+ if (!formatters.has(timezone)) {
48
+ formatters.set(timezone, new Intl.DateTimeFormat('en-CA', {
49
+ timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit',
50
+ }));
51
+ }
52
+ const pieces = Object.fromEntries(formatters.get(timezone).formatToParts(new Date(time)).map(part => [part.type, part.value]));
53
+ return `${pieces.year}-${pieces.month}-${pieces.day}`;
54
+ } catch {
55
+ requireThat(false, 'TIMEZONE', '提供有效的 Home 时区与 ISO 8601 时间。');
56
+ }
57
+ }
58
+
59
+ export const isInstant = value => typeof value === 'string'
60
+ && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u.test(value)
61
+ && Number.isFinite(Date.parse(value));
62
+
63
+ export function rangeIdFor(id, record) {
64
+ return digest(JSON.stringify([
65
+ id, record.kind, record.sourceIdentity, record.tracking.kind, record.tracking.remote ?? null,
66
+ record.tracking.ref, record.initialization.mode, record.initialization.base, record.previousRangeId,
67
+ record.from?.commit ?? null, record.to.commit,
68
+ ]));
69
+ }
70
+
71
+ export const documentStamp = bytes => ({ exists: bytes !== null, sha256: bytes === null ? null : digest(bytes) });
72
+ export const sameStamp = (a, b) => a?.exists === b?.exists && a?.sha256 === b?.sha256;
73
+
74
+ function validStamp(stamp) {
75
+ return isObject(stamp) && (stamp.exists === true ? isDigest(stamp.sha256) : stamp.exists === false && stamp.sha256 === null);
76
+ }
77
+
78
+ const validPoint = value => isObject(value) && isOid(value.commit) && isInstant(value.committedAt) && isInstant(value.observedAt);
79
+ const nonnegative = value => Number.isSafeInteger(value) && value >= 0;
80
+
81
+ function validStats(stats, coverage) {
82
+ if (!isObject(stats) || stats.lineMetricScope !== lineMetricScope || !nonnegative(stats.rangeCommitCount)) return false;
83
+ if (!isObject(stats.unavailable) || Object.keys(stats.unavailable).some(key => !['totalCommitCountAtHead', 'linesAdded', 'linesDeleted'].includes(key))) return false;
84
+ const optional = ['totalCommitCountAtHead', 'linesAdded', 'linesDeleted'];
85
+ if (!optional.every(key => stats[key] === null ? isLine(stats.unavailable[key]) : nonnegative(stats[key]) && !hasOwn(stats.unavailable, key))) return false;
86
+ if ((stats.linesAdded === null) !== (stats.linesDeleted === null) || stats.totalCommitCountAtHead !== null && stats.totalCommitCountAtHead < stats.rangeCommitCount) return false;
87
+ return coverage === 'complete' ? stats.rangeCommitCount > 0 : stats.rangeCommitCount === 0 && stats.linesAdded === null;
88
+ }
89
+
90
+ function validInitialization(value) {
91
+ return isObject(value) && (value.mode === 'from' ? isOid(value.base) : ['full-history', 'baseline'].includes(value.mode) && value.base === null);
92
+ }
93
+
94
+ function validRecord(id, entry, previous, initialization, saved) {
95
+ if (!isObject(entry) || !validInitialization(initialization)
96
+ || !validInitialization(entry.initialization)
97
+ || initialization.mode !== entry.initialization.mode || initialization.base !== entry.initialization.base
98
+ || !validPoint(entry.to) || !isLine(entry.sourceIdentity) || !validTracking(entry.tracking)
99
+ || entry.rangeId !== rangeIdFor(id, entry) || entry.previousRangeId !== (previous?.rangeId ?? null)
100
+ || !isInstant(entry.generatedAt) || (saved ? !isInstant(entry.savedAt) : entry.savedAt !== null)
101
+ || !['remote-observed', 'remote-cache', 'local'].includes(entry.freshness)) return false;
102
+ if (entry.tracking.kind === 'remote-branch' ? entry.freshness === 'local' : entry.freshness !== 'local') return false;
103
+ const complete = ['delta', 'full-history'].includes(entry.kind);
104
+ if (entry.coverage !== (complete ? 'complete' : 'not-backfilled') || !validStats(entry.stats, entry.coverage)) return false;
105
+ if (entry.kind === 'delta') {
106
+ if (!validPoint(entry.from) || entry.from.commit === entry.to.commit) return false;
107
+ if (previous) {
108
+ if (entry.from.commit !== previous.to.commit || entry.sourceIdentity !== previous.sourceIdentity
109
+ || entry.from.observedAt !== previous.to.observedAt || entry.from.committedAt !== previous.to.committedAt
110
+ || (!sameTracking(entry.tracking, previous.tracking) && (!isLine(entry.changeReason) || entry.previousSourceIdentity !== previous.sourceIdentity))) return false;
111
+ } else if (initialization.mode !== 'from' || entry.from.commit !== initialization.base) return false;
112
+ } else if (entry.from !== null) return false;
113
+ if (entry.kind === 'full-history' && (previous || initialization.mode !== entry.kind || entry.stats.rangeCommitCount !== entry.stats.totalCommitCountAtHead)) return false;
114
+ if (entry.kind === 'baseline' && (previous || (initialization.mode !== 'baseline' && initialization.base !== entry.to.commit))) return false;
115
+ if (entry.kind === 'rebaseline' && (!previous || !isLine(entry.changeReason) || entry.previousSourceIdentity !== previous.sourceIdentity)) return false;
116
+ if (!['full-history', 'delta', 'baseline', 'rebaseline'].includes(entry.kind) || !isObject(entry.displayDates) || !isLine(entry.displayDates.timezone)) return false;
117
+ try {
118
+ return entry.displayDates.from === (entry.from ? dateAt(entry.from.observedAt, entry.displayDates.timezone) : null)
119
+ && entry.displayDates.to === dateAt(entry.to.observedAt, entry.displayDates.timezone);
120
+ } catch { return false; }
121
+ }
122
+
123
+ export function validateState(state) {
124
+ requireThat(isObject(state) && state.formatVersion === 1 && isObject(state.projects), 'STATE_FORMAT', 'state.json 的版本或 projects 无法核对。');
125
+ for (const [id, project] of Object.entries(state.projects)) {
126
+ const message = `${id} 的成功记录或 pending 无法核对。`;
127
+ requireThat(isId(id) && isObject(project) && validInitialization(project.initialization) && Array.isArray(project.ranges), 'STATE_FORMAT', message);
128
+ let previous = null;
129
+ for (const range of project.ranges) {
130
+ requireThat(validRecord(id, range, previous, project.initialization, true), 'STATE_FORMAT', message);
131
+ previous = range;
132
+ }
133
+ requireThat(project.lastSuccessfulRangeId === (previous?.rangeId ?? null)
134
+ && new Set(project.ranges.map(range => range.rangeId)).size === project.ranges.length, 'STATE_FORMAT', message);
135
+ if (!hasOwn(project, 'pending')) {
136
+ requireThat(previous !== null, 'STATE_FORMAT', message);
137
+ continue;
138
+ }
139
+ const pending = project.pending;
140
+ const { pending: ignored, ...success } = project;
141
+ requireThat(isObject(pending) && isLine(pending.transactionId)
142
+ && pending.expectedProjectRevision === revisionOf(previous ? success : null)
143
+ && validStamp(pending.beforeDocument) && validStamp(pending.afterDocument)
144
+ && pending.afterDocument.exists && !sameStamp(pending.beforeDocument, pending.afterDocument)
145
+ && validRecord(id, pending.nextRecord, previous, project.initialization, false)
146
+ && pending.rangeId === pending.nextRecord.rangeId, 'STATE_FORMAT', message);
147
+ }
148
+ return state;
149
+ }