@namewta/skills-hub 0.1.48 → 0.1.49

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 (26) hide show
  1. package/package.json +1 -1
  2. package/skills/home/home-project-changelog/SKILL.md +3 -3
  3. package/skills/home/home-project-changelog/assets/project-changelog.md +7 -7
  4. package/skills/home/home-project-changelog/assets/worker-brief.md +1 -1
  5. package/skills/home/home-project-changelog/references/git-ranges.md +3 -0
  6. package/skills/home/home-project-changelog/references/tools.md +14 -4
  7. package/skills/home/home-project-changelog/references/workflow.md +2 -2
  8. package/skills/home/home-project-changelog/references/writing.md +20 -2
  9. package/skills/home/home-project-changelog/scripts/changelog.mjs +47 -5
  10. package/skills/home/home-project-changelog/scripts/contract.mjs +46 -2
  11. package/skills/home/home-project-changelog/scripts/git.mjs +15 -0
  12. package/skills/home/home-project-changelog/scripts/revision.mjs +231 -0
  13. package/skills/home/home-project-changelog/scripts/storage.mjs +24 -6
  14. package/skills/home/home-project-changelog/scripts/summary.mjs +17 -3
  15. package/skills/home/home-project-changelog/scripts/tasks.mjs +40 -0
  16. package/skills/home/home-website/SKILL.md +2 -2
  17. package/skills/home/home-website/assets/website/scripts/inputs.mjs +56 -14
  18. package/skills/home/home-website/assets/website/scripts/render.mjs +10 -5
  19. package/skills/home/home-website/assets/website/site/public/home-assets/app.js +69 -99
  20. package/skills/home/home-website/assets/website/site/public/home-assets/site.css +76 -83
  21. package/skills/home/home-website/assets/website/site/templates/layout.mjs +27 -15
  22. package/skills/home/home-website/assets/website/site/templates/ledger.mjs +55 -39
  23. package/skills/home/home-website/assets/website/site/templates/model.mjs +39 -1
  24. package/skills/home/home-website/assets/website/site/templates/pages.mjs +39 -57
  25. package/skills/home/home-website/assets/website/site/templates/project-logs.mjs +26 -10
  26. package/skills/home/home-website/references/website.md +8 -11
@@ -0,0 +1,231 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import {
3
+ categories, dateAt, documentStamp, isDigest, requireThat, revisionOf,
4
+ } from './contract.mjs';
5
+ import { firstCommitAt, listCommits, point, shallowBoundaries } from './git.mjs';
6
+ import { section } from './summary.mjs';
7
+ import { commitCalendar } from './tasks.mjs';
8
+
9
+ export function revisionSnapshot(view, frozen, git, rangeId) {
10
+ requireThat(!view.project?.pending, 'PENDING', '该项目存在待恢复写入,先执行 recover。');
11
+ requireThat(isDigest(rangeId), 'ARGUMENT', '提供完整的成功区间 ID。');
12
+ const record = view.project?.ranges.find(range => range.rangeId === rangeId);
13
+ requireThat(record, 'RANGE_NOT_FOUND', '项目中没有该成功区间。');
14
+ requireThat(view.document !== null, 'DOCUMENT_MISSING', '成功记录对应的 Markdown 丢失,先恢复正文。');
15
+ requireThat(record.sourceIdentity === frozen.binding.sourceIdentity, 'SOURCE_CHANGED', '当前已核实的项目来源与历史区间不同。');
16
+ for (const saved of [record.from, record.to].filter(Boolean)) {
17
+ requireThat(isDeepStrictEqual(saved, point(git, saved.commit, saved.observedAt)), 'GIT_RANGE_CHANGED', '历史提交与成功记录不同。');
18
+ }
19
+ const commits = record.coverage === 'complete'
20
+ ? listCommits(git, record.from?.commit, record.to.commit, shallowBoundaries(git)) : [];
21
+ const historyStart = record.kind === 'full-history' ? firstCommitAt(git, record.to.commit) : null;
22
+ requireThat(commits.length === record.stats.rangeCommitCount && (!record.firstCommitAt || historyStart === record.firstCommitAt),
23
+ 'GIT_RANGE_CHANGED', '历史区间的提交数或首提交已变化。');
24
+ if (record.ledger) {
25
+ const { days, commitMonths } = commitCalendar(git, record, commits);
26
+ requireThat(isDeepStrictEqual(commitMonths, record.ledger.commitMonths)
27
+ && record.ledger.tasks.every(task => days.get(task.deliveredBy) === task.date && task.commits.every(commit => days.has(commit))),
28
+ 'GIT_RANGE_CHANGED', '任务证据与历史区间的提交或日期不同。');
29
+ }
30
+ return {
31
+ status: 'ready', purpose: 'revision', repoId: frozen.repoId, record, commits, frozen, historyStart,
32
+ expected: { projectRevision: revisionOf(view.project), document: documentStamp(view.document) },
33
+ };
34
+ }
35
+
36
+ const titleFor = record => section(record, []).split('\n', 1)[0];
37
+ const emptyNotice = '本次没有需单列的变更。';
38
+ const failDocument = () => requireThat(false, 'DOCUMENT_FORMAT', '无法唯一识别历史区间的生成内容,保留 Markdown 和成功记录。');
39
+
40
+ function markdownLines(text) {
41
+ let fence = null;
42
+ let comment = false;
43
+ const frontmatter = text.match(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/u)?.[0].length ?? 0;
44
+ return [...text.matchAll(/([^\r\n]*)(\r\n|\n|\r|$)/gu)].filter(match => match[0]).map(match => {
45
+ const [, content, newline] = match;
46
+ const line = { content, newline, start: match.index, end: match.index + match[0].length };
47
+ if (match.index < frontmatter) return { ...line, visible: false };
48
+ if (!fence && (comment || /^ {0,3}<!--/u.test(content))) {
49
+ comment = !content.includes('-->');
50
+ return { ...line, visible: false };
51
+ }
52
+ const delimiter = content.match(/^ {0,3}(`{3,}|~{3,})(.*)$/u);
53
+ const visible = fence === null && delimiter === null;
54
+ if (delimiter) {
55
+ const [, token, rest] = delimiter;
56
+ if (!fence) fence = token;
57
+ else if (fence[0] === token[0] && token.length >= fence.length && !rest.trim()) fence = null;
58
+ }
59
+ return { ...line, visible };
60
+ });
61
+ }
62
+
63
+ function tableAt(lines, index, headers) {
64
+ const signatures = [headers, headers.map((header, offset) => `${header} ${offset ? '---:' : '新增'} |`)];
65
+ const signature = signatures.find(pair => pair.every((header, offset) => lines[index + offset]?.visible && lines[index + offset].content === header));
66
+ if (!signature) return null;
67
+ const row = lines[index + headers.length];
68
+ if (!row?.visible || !row.content.startsWith('|') || !row.content.endsWith('|')) return null;
69
+ const cells = row.content.slice(1,-1).split('|').map(value => value.trim());
70
+ if (!cells.every(value => /^(?:\d+|\d{1,3}(?:,\d{3})+)$/u.test(value))) return null;
71
+ const values = cells.map(value => Number(value.replaceAll(',', '')));
72
+ const commitIndex = categories.length + 1;
73
+ if (values.length !== signature[0].split('|').length - 2 || !values.every(Number.isSafeInteger)
74
+ || values[0] !== values.slice(1, commitIndex).reduce((sum, value) => sum + value, 0)
75
+ || values[commitIndex + 1] > values[1]) return null;
76
+ return { index, end: index + headers.length, values, row };
77
+ }
78
+
79
+ function parseGenerated(record, entries) {
80
+ const lines = section(record, entries).split('\n');
81
+ const tableIndex = lines.findIndex(line => line.startsWith('| '));
82
+ const groups = new Map();
83
+ let category;
84
+ for (const content of lines.slice(tableIndex + 3)) {
85
+ if (content.startsWith('### ')) {
86
+ category = content.slice(4);
87
+ groups.set(category, []);
88
+ } else if (content.startsWith('- ')) groups.get(category).push(content);
89
+ }
90
+ return { headers: lines.slice(tableIndex, tableIndex + 2), row: lines[tableIndex + 2], groups };
91
+ }
92
+
93
+ function locateRanges(lines, ranges, oldRecord, upgraded, headers) {
94
+ const headings = lines.flatMap((line, index) => line.visible && /^ {0,3}#{1,2}(?:\s|$)/u.test(line.content) ? [index] : []);
95
+ const blocks = headings.flatMap((index, order) => {
96
+ const end = headings[order + 1] ?? lines.length;
97
+ const title = lines[index].content;
98
+ if (!/^## \d{4}-\d{2}-\d{2}(?: 至 \d{4}-\d{2}-\d{2})?$/u.test(title)) return [];
99
+ const tables = [];
100
+ for (let position = index + 1; position < end - 2; position++) {
101
+ const table = tableAt(lines, position, headers);
102
+ if (table) tables.push(table);
103
+ }
104
+ return tables.length ? [{ index, end, title, tables }] : [];
105
+ });
106
+ function matches(block, range) {
107
+ const legacy = range.kind === 'full-history' && !range.firstCommitAt;
108
+ const isTarget = range.rangeId === oldRecord.rangeId;
109
+ const legacyTitle = legacy && (isTarget ? block.title === titleFor(upgraded)
110
+ : block.title.endsWith(` 至 ${range.displayDates.to}`));
111
+ return (block.title === titleFor(range) || legacyTitle) && block.tables.length === 1
112
+ && block.tables[0].values[categories.length + 1] === range.stats.rangeCommitCount;
113
+ }
114
+ // Both directions must select the same block. Unrelated hand-written ranges may sit between saved ones.
115
+ function locate(records, candidates) {
116
+ let position = 0;
117
+ for (const range of records) {
118
+ while (position < candidates.length && !matches(candidates[position], range)) position++;
119
+ if (position === candidates.length) failDocument();
120
+ if (range.rangeId === oldRecord.rangeId) return candidates[position];
121
+ position++;
122
+ }
123
+ failDocument();
124
+ }
125
+ const earliest = locate(ranges, [...blocks].reverse());
126
+ const latest = locate([...ranges].reverse(), blocks);
127
+ if (earliest !== latest) failDocument();
128
+ return { ...earliest, table: earliest.tables[0] };
129
+ }
130
+
131
+ export function rewriteRange(before, ranges, oldRecord, record) {
132
+ let text;
133
+ try { text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(before); }
134
+ catch { failDocument(); }
135
+ const bom = text.startsWith('\uFEFF') ? '\uFEFF' : '';
136
+ text = text.slice(bom.length);
137
+ const lines = markdownLines(text);
138
+ const old = parseGenerated(oldRecord, oldRecord.ledger?.tasks ?? []);
139
+ const next = parseGenerated(record, record.ledger.tasks);
140
+ const target = locateRanges(lines, ranges, oldRecord, record, parseGenerated(oldRecord, []).headers);
141
+ const table = target.table;
142
+ const newline = table.row.newline || lines[target.index].newline || '\n';
143
+ const edits = [];
144
+ const replaceLine = (line, replacement) => edits.push({ start: line.start, end: line.end,
145
+ value: replacement === null ? '' : `${replacement}${line.newline}` });
146
+ const insertAfter = (line, contents) => edits.push({ start: line.end, end: line.end,
147
+ value: `${line.newline ? '' : newline}${newline}${contents.join(newline)}${newline}` });
148
+ if (lines[target.index].content !== titleFor(record)) replaceLine(lines[target.index], titleFor(record));
149
+ for (const [offset, content] of next.headers.entries()) {
150
+ const line = lines[table.index + offset];
151
+ if (line.content !== content) replaceLine(line, content);
152
+ }
153
+ if (table.row.content !== next.row) replaceLine(table.row, next.row);
154
+
155
+ const groups = new Map();
156
+ const notices = [];
157
+ let group;
158
+ for (const line of lines.slice(table.end + 1, target.end)) {
159
+ if (!line.visible) continue;
160
+ const heading = line.content.match(/^ {0,3}#{3,6}(?:\s|$)/u);
161
+ if (heading) {
162
+ const category = line.content.startsWith('### ') ? line.content.slice(4) : null;
163
+ group = null;
164
+ if (categories.includes(category)) {
165
+ if (groups.has(category)) failDocument();
166
+ group = { heading: line, bullets: [] };
167
+ groups.set(category, group);
168
+ }
169
+ } else if (line.content === emptyNotice) notices.push(line);
170
+ else if (group && line.content.startsWith('- ')) group.bullets.push(line);
171
+ }
172
+
173
+ let insertion = table.row;
174
+ for (const [index, category] of categories.entries()) {
175
+ const group = groups.get(category);
176
+ const count = table.values[index + 1];
177
+ // The ledger identifies generated lines exactly. Legacy sections only supply their category counts.
178
+ const generated = oldRecord.ledger ? group?.bullets.filter(line => old.groups.get(category)?.includes(line.content)) ?? []
179
+ : count ? group?.bullets ?? [] : [];
180
+ if (generated.length !== count || oldRecord.ledger && !isDeepStrictEqual(generated.map(line => line.content), old.groups.get(category) ?? [])) failDocument();
181
+ if (oldRecord.ledger && group?.bullets.some(line => /^- \d{4}-\d{2}-\d{2} · .* · /u.test(line.content) && !generated.includes(line))) failDocument();
182
+ if (group && group.heading.start < insertion.start) failDocument();
183
+ const replacements = next.groups.get(category) ?? [];
184
+ if (!group && replacements.length) {
185
+ insertAfter(insertion, [`### ${category}`, '', ...replacements]);
186
+ continue;
187
+ }
188
+ if (!group) continue;
189
+ for (const [slot, line] of generated.entries()) {
190
+ if (replacements[slot] !== line.content) replaceLine(line, replacements[slot] ?? null);
191
+ }
192
+ insertion = generated.at(-1) ?? group.heading;
193
+ if (replacements.length > generated.length) {
194
+ const extra = replacements.slice(generated.length);
195
+ if (generated.length && insertion.newline) {
196
+ edits.push({ start: insertion.end, end: insertion.end, value: `${extra.join(newline)}${newline}` });
197
+ } else insertAfter(insertion, extra);
198
+ }
199
+ if (count && replacements.length === 0) {
200
+ const following = lines.slice(lines.indexOf(group.heading) + 1, target.end);
201
+ const attached = following.findIndex(line => line.visible && /^ {0,3}#{3,6}(?:\s|$)/u.test(line.content));
202
+ const body = following.slice(0, attached === -1 ? following.length : attached);
203
+ if (body.every(line => !line.content.trim() || generated.includes(line))) replaceLine(group.heading, null);
204
+ }
205
+ }
206
+ const hadNotice = oldRecord.coverage === 'complete' && table.values[0] === 0;
207
+ const needsNotice = record.coverage === 'complete' && record.ledger.tasks.length === 0;
208
+ if (hadNotice && notices.length !== 1) failDocument();
209
+ if (hadNotice && !needsNotice) replaceLine(notices[0], null);
210
+ if (!hadNotice && needsNotice) {
211
+ if (notices.length) failDocument();
212
+ insertAfter(insertion, [emptyNotice]);
213
+ }
214
+ edits.sort((a, b) => a.start - b.start || a.end - b.end);
215
+ // Keep all bytes outside the original generated lines and the insertion points.
216
+ let cursor = 0;
217
+ const chunks = [bom];
218
+ for (const edit of edits) {
219
+ if (edit.start < cursor) failDocument();
220
+ chunks.push(text.slice(cursor, edit.start), edit.value);
221
+ cursor = edit.end;
222
+ }
223
+ chunks.push(text.slice(cursor));
224
+ return Buffer.from(chunks.join(''));
225
+ }
226
+
227
+ export function upgradeRange(record, historyStart) {
228
+ if (!historyStart || record.firstCommitAt) return record;
229
+ return { ...record, firstCommitAt: historyStart,
230
+ displayDates: { ...record.displayDates, from: dateAt(historyStart, record.displayDates.timezone) } };
231
+ }
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
+ import { isDeepStrictEqual } from 'node:util';
5
6
  import {
6
7
  documentStamp, expectId, hasOwn, isId, requireThat, revisionOf, sameStamp, validateState,
7
8
  } from './contract.mjs';
@@ -138,36 +139,53 @@ export function openStore(home, filesystem = fs) {
138
139
  function confirm(id, state, stateBytes, project, record) {
139
140
  const { pending, ...success } = project;
140
141
  const saved = { ...record, savedAt: new Date().toISOString() };
141
- const next = { ...success, ranges: [...success.ranges, saved], lastSuccessfulRangeId: saved.rangeId };
142
+ const ranges = pending.operation === 'revision'
143
+ ? success.ranges.map(range => range.rangeId === saved.rangeId ? saved : range)
144
+ : [...success.ranges, saved];
145
+ const next = { ...success, ranges, lastSuccessfulRangeId: ranges.at(-1).rangeId };
142
146
  const hasExpectedDocument = () => requireThat(sameStamp(documentStamp(read(documentName(id))), pending.afterDocument),
143
147
  'DOCUMENT_CHANGED', 'Markdown 在最终确认前已变化,保留 pending。');
144
148
  saveState({ ...state, projects: { ...state.projects, [id]: next } }, stateBytes, hasExpectedDocument);
145
149
  const result = view(id);
146
- requireThat(result.previous?.rangeId === saved.rangeId && !result.project.pending
150
+ const persisted = result.project?.ranges.find(range => range.rangeId === saved.rangeId);
151
+ requireThat(isDeepStrictEqual(persisted, saved) && !result.project.pending
147
152
  && sameStamp(documentStamp(result.document), pending.afterDocument), 'READ_CONFLICT', '成功记录或 Markdown 回读不一致。');
148
- return result.previous;
153
+ return persisted;
149
154
  }
150
155
 
151
- function commit(id, expected, record, document) {
156
+ function commit(id, expected, record, document, { revision = false } = {}) {
152
157
  return withLock(() => {
153
158
  const current = view(id);
154
159
  requireThat(!current.project?.pending, 'PENDING', '该项目存在待恢复写入,先执行 recover。');
155
- if (current.previous?.rangeId === record.rangeId) {
160
+ const prior = current.project?.ranges.find(range => range.rangeId === record.rangeId);
161
+ if (revision && prior && prior.revisionRequest === record.revisionRequest
162
+ && sameStamp(documentStamp(current.document), documentStamp(document))) {
163
+ return { status: 'already-saved', record: prior };
164
+ }
165
+ if (!revision && current.previous?.rangeId === record.rangeId) {
156
166
  requireThat(current.document !== null, 'DOCUMENT_MISSING', '成功记录对应的 Markdown 丢失,先恢复正文。');
157
167
  return { status: 'already-saved', record: current.previous };
158
168
  }
159
169
  requireThat(revisionOf(current.project) === expected.projectRevision
160
170
  && sameStamp(documentStamp(current.document), expected.document), 'STALE_CANDIDATE', '项目状态或 Markdown 已变化,重读后重新生成。');
171
+ if (revision && prior && prior.firstCommitAt === record.firstCommitAt
172
+ && isDeepStrictEqual(prior.displayDates, record.displayDates) && isDeepStrictEqual(prior.ledger, record.ledger)
173
+ && sameStamp(expected.document, documentStamp(document))) {
174
+ return { status: 'already-saved', record: prior };
175
+ }
161
176
  const pending = {
162
177
  transactionId: randomUUID(), rangeId: record.rangeId, expectedProjectRevision: expected.projectRevision,
163
178
  beforeDocument: expected.document, afterDocument: documentStamp(document), nextRecord: record,
179
+ ...(revision ? { operation: 'revision' } : {}),
164
180
  };
165
181
  const project = {
166
182
  ...(current.project ?? { initialization: record.initialization, ranges: [], lastSuccessfulRangeId: null }), pending,
167
183
  };
168
184
  const state = { ...current.state, projects: { ...current.state.projects, [id]: project } };
169
185
  const intentBytes = saveState(state, current.stateBytes);
170
- replace(documentName(id), document, pending.beforeDocument, 'DOCUMENT_CHANGED');
186
+ if (!sameStamp(pending.beforeDocument, pending.afterDocument)) {
187
+ replace(documentName(id), document, pending.beforeDocument, 'DOCUMENT_CHANGED');
188
+ }
171
189
  requireThat(sameStamp(documentStamp(read(documentName(id))), pending.afterDocument), 'DOCUMENT_CHANGED', 'Markdown 写入回读不一致,保留 pending。');
172
190
  return { status: 'saved', record: confirm(id, state, intentBytes, project, record) };
173
191
  });
@@ -27,11 +27,19 @@ export function candidateEntries(candidate, snapshot, git) {
27
27
  requireThat(!commits.length || candidate.entries.length > 0 || candidate.noSignificantChanges === true,
28
28
  'CANDIDATE', '没有需单列的变更时,在候选中确认已复核范围。');
29
29
  for (const entry of candidate.entries) {
30
- expectKeys(entry, ['category', 'text', 'commits', 'markers', 'relatedCommits'], 'CANDIDATE', '条目需提供分类、描述和主要证据。');
30
+ expectKeys(entry, ['category', 'area', 'text', 'commits', 'deliveredBy', 'markers', 'relatedCommits', 'added'],
31
+ 'CANDIDATE', '条目需提供分类、描述和主要证据。');
31
32
  requireThat(categories.includes(entry.category) && displayLine(entry.text),
32
33
  'DISPLAY', '条目使用精简分类和单行描述,证据身份单独提供。');
33
34
  requireThat(Array.isArray(entry.commits) && entry.commits.length > 0 && entry.commits.every(oid => wanted.has(oid)),
34
35
  'COVERAGE', '条目的主要证据须在冻结范围内。');
36
+ requireThat((entry.deliveredBy !== undefined || !entry.area || entry.commits.length === 1)
37
+ && (entry.deliveredBy === undefined || entry.commits.includes(entry.deliveredBy)),
38
+ 'COVERAGE', '任务完成节点须属于该条目的主要证据。');
39
+ requireThat(entry.area === undefined || displayLine(entry.area) && entry.area.trim() !== '—' && !/[·*`]/u.test(entry.area),
40
+ 'DISPLAY', '模块使用可公开的单行名称,避开 Markdown 标记和中点分隔符。');
41
+ requireThat(entry.added === undefined || entry.category === '功能' && typeof entry.added === 'boolean',
42
+ 'CANDIDATE', '仅功能条目可标明是否新增能力。');
35
43
  requireThat(entry.markers === undefined || Array.isArray(entry.markers) && entry.markers.every(marker => markers.includes(marker)),
36
44
  'DISPLAY', '使用已定义的影响标识。');
37
45
  requireThat(entry.relatedCommits === undefined || Array.isArray(entry.relatedCommits)
@@ -45,7 +53,7 @@ function oneLine(text) {
45
53
  return text.trim().replace(/[[\]]/gu, '\\$&');
46
54
  }
47
55
 
48
- function section(record, entries) {
56
+ export function section(record, entries) {
49
57
  const { displayDates: { from, to }, kind, stats } = record;
50
58
  const parts = [`## ${from ? `${from} 至 ${to}` : to}`];
51
59
  if (kind === 'delta') {
@@ -60,6 +68,11 @@ function section(record, entries) {
60
68
  for (const entry of entries) byCategory.get(entry.category).push(entry);
61
69
  const columns = ['变更总数', ...categories, '本次提交'];
62
70
  const counts = [entries.length, ...categories.map(category => byCategory.get(category).length), stats.rangeCommitCount];
71
+ const features = byCategory.get('功能');
72
+ if (features.length && features.every(entry => typeof entry.added === 'boolean')) {
73
+ columns.push('新增');
74
+ counts.push(features.filter(entry => entry.added).length);
75
+ }
63
76
  const row = cells => `| ${cells.join(' | ')} |`;
64
77
  parts.push([
65
78
  row(columns),
@@ -69,7 +82,8 @@ function section(record, entries) {
69
82
  for (const [category, group] of byCategory) {
70
83
  const items = group.map(entry => {
71
84
  const impacts = [...new Set(entry.markers)].map(marker => `**[${marker}]**`).join(' ');
72
- return `- ${impacts ? `${impacts} ` : ''}${oneLine(entry.text)}`;
85
+ const source = entry.date ? `${entry.date} · ${entry.area ? oneLine(entry.area) : '—'} · ` : '';
86
+ return `- ${source}${impacts ? `${impacts} ` : ''}${oneLine(entry.text)}`;
73
87
  });
74
88
  if (items.length) parts.push(`### ${category}`, items.join('\n'));
75
89
  }
@@ -0,0 +1,40 @@
1
+ import { categories, dateAt, digest, requireThat } from './contract.mjs';
2
+ import { commitDates } from './git.mjs';
3
+
4
+ export function commitCalendar(git, record, commits) {
5
+ const times = commitDates(git, record);
6
+ requireThat(times.size === commits.length && commits.every(oid => times.has(oid)), 'COVERAGE', '日期证据与冻结提交集合不一致。');
7
+ const days = new Map();
8
+ const commitMonths = {};
9
+ for (const [oid, time] of times) {
10
+ const day = dateAt(time, record.displayDates.timezone);
11
+ days.set(oid, day);
12
+ const month = day.slice(0, 7);
13
+ commitMonths[month] = (commitMonths[month] ?? 0) + 1;
14
+ }
15
+ return { days, commitMonths };
16
+ }
17
+
18
+ export function taskLedger({ repoId, record, commits }, entries, git) {
19
+ const { days, commitMonths } = commitCalendar(git, record, commits);
20
+ const ids = new Set();
21
+ const tasks = entries.map(entry => {
22
+ // For a result with several supporting commits the writer identifies the one that delivers it.
23
+ const deliveredBy = entry.deliveredBy ?? entry.commits[0];
24
+ const area = entry.area?.trim() || null;
25
+ const text = entry.text.trim();
26
+ const identity = [repoId, record.rangeId, entry.category, area, text];
27
+ const id = 'task-' + digest(JSON.stringify(identity)).slice(0, 16);
28
+ requireThat(!ids.has(id), 'CANDIDATE', '同一区间有重复的模块、类别和任务描述:' + text);
29
+ ids.add(id);
30
+ return {
31
+ id, category: entry.category, area, text, date: days.get(deliveredBy),
32
+ markers: [...new Set(entry.markers)], commits: [...new Set(entry.commits)], deliveredBy,
33
+ ...(entry.relatedCommits?.length ? { relatedCommits: [...new Set(entry.relatedCommits)] } : {}),
34
+ ...(entry.added !== undefined ? { added: entry.added } : {}),
35
+ };
36
+ });
37
+ tasks.sort((a, b) => categories.indexOf(a.category) - categories.indexOf(b.category) ||
38
+ b.date.localeCompare(a.date) || (a.area ?? '').localeCompare(b.area ?? '', 'zh-CN'));
39
+ return { version: 1, commitMonths, tasks };
40
+ }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: home-website
3
- description: 初始化、刷新和预览 Home 已登记项目的静态展示站。用于「创建 Home 网站」「预览多仓变更时间线」「更新项目展示」或从登记和日志任务回写最新站点。项目登记由 home-setup 维护,Git 区间由 home-project-changelog 维护。
3
+ description: 把 Home 中已登记项目的 Git changelog 生成可部署的静态展示站,按项目、月份、模块关键词和类别查看任务及提交统计。用于创建、刷新、预览或部署多项目变更展示,承接 home-project-changelog 已保存的日志。
4
4
  ---
5
5
 
6
6
  # Home 项目展示站
@@ -15,6 +15,6 @@ description: 初始化、刷新和预览 Home 已登记项目的静态展示站
15
15
  | 上次构建中断或启动失败 | 按[修复本地刷新](references/website.md#修复本地刷新)核对进程、恢复已有产物并重试 |
16
16
  | 发布到指定目标 | 使用已验证的 `dist/`,按实际托管目标回读线上版本 |
17
17
 
18
- 公开模型取登记、已成功保存的日志和展示设置的交集。跨仓时间线按结束日划分观测窗口,窗口内按项目显示原段。目录先选项目再按日期查阅日志。站点、项目、窗口和单段的统计可从静态页面及 `dist/data/` 读取。[公开字段与统计](references/website.md#公开字段与数据来源) · [更新已有模板](references/website.md#更新已有模板)
18
+ 首页突出公开项目、任务及 Git 提交。项目卡直接给出累计提交和任务量,详情与跨仓时间线默认显示每月的任务正文。构建时按登记、成功记录和展示设置选取公开项目,核对结构化任务与 Markdown 后导出 `dist/data/`。[公开字段与统计](references/website.md#公开字段与数据来源) · [更新已有模板](references/website.md#更新已有模板)
19
19
 
20
20
  任务结束时说明构建状态、地址或制品位置、未纳入的项目和诊断。Home 更新成功但站点待刷新时分别报告,重试网站命令即可。
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { parseMarkdown, validDay } from '../site/templates/project-logs.mjs';
5
+ import { statistics } from '../site/templates/model.mjs';
5
6
 
6
7
  const idPattern = /^[a-z0-9][a-z0-9-]*$/u;
7
8
  const plain = value => !!value && typeof value === 'object' && !Array.isArray(value);
@@ -93,12 +94,14 @@ function readState(value) {
93
94
  for (const range of project.ranges) {
94
95
  const dates = range?.displayDates;
95
96
  const commits = range?.stats?.rangeCommitCount;
97
+ const head = range?.stats?.totalCommitCountAtHead;
96
98
  const baseline = ['baseline','rebaseline'].includes(range?.kind);
97
99
  if (!plain(range) || !line(range.rangeId) || ids.has(range.rangeId) || range.previousRangeId !== previous
98
100
  || typeof range.savedAt !== 'string' || !Number.isFinite(Date.parse(range.savedAt))
99
101
  || !['full-history','delta','baseline','rebaseline'].includes(range.kind)
100
102
  || !plain(dates) || !validDay(dates.to) || (dates.from !== null && (!validDay(dates.from) || dates.from > dates.to))
101
- || !Number.isSafeInteger(commits) || commits < 0 || (baseline && (dates.from !== null || commits !== 0))) {
103
+ || !Number.isSafeInteger(commits) || commits < 0 || (baseline && (dates.from !== null || commits !== 0))
104
+ || (head != null && (!Number.isSafeInteger(head) || head < commits))) {
102
105
  throw Error('changelogs/state.json 中 '+id+' 的成功区间无效,请用 home-project-changelog 核对。');
103
106
  }
104
107
  ids.add(range.rangeId);
@@ -119,9 +122,12 @@ function publicText(value, privateValues) {
119
122
  .replace(/[\u0000-\u0009\u000b-\u001f\u007f]/gu, ' ');
120
123
  }
121
124
 
122
- function savedPeriods(id, parsed, saved, warnings) {
123
- const oldest = [...parsed.periods].reverse();
124
- function matches(period, range) {
125
+ function savedPeriods(id, parsed, dated, saved, warnings) {
126
+ const blocks = parsed.periods.map((legacy,index) => ({legacy, dated:dated?.periods[index]}));
127
+ const oldest = [...blocks].reverse();
128
+ const bodyFor = (block, range) => range.ledger ? block.dated : block.legacy;
129
+ function matches(block, range) {
130
+ const period = bodyFor(block,range);
125
131
  const {from,to} = range.displayDates;
126
132
  const legacyStart = range.kind === 'full-history' && from === null;
127
133
  const baseline = range.kind === 'baseline' || range.kind === 'rebaseline';
@@ -140,14 +146,50 @@ function savedPeriods(id, parsed, saved, warnings) {
140
146
  }
141
147
  // 两个方向分别找最早和最晚的配对。两者都相同时,已保存区间的有序配对才唯一。
142
148
  const forward = ordered(saved.ranges,oldest);
143
- const backward = ordered([...saved.ranges].reverse(),parsed.periods).reverse();
149
+ const backward = ordered([...saved.ranges].reverse(),blocks).reverse();
144
150
  if (forward.some((period,index) => period !== backward[index])) throw Error(id+' 的成功区间与 Markdown 有多种配对,请先核对原文。');
145
151
  if (forward.length !== parsed.periods.length) warnings.push(id+' 有未匹配的日期段,保留在 Home。');
146
152
  if (parsed.legacy) warnings.push(id+' 含历史补记,保留在单仓页。');
147
- for (const period of forward) {
153
+ const paired = forward.map((block,index) => ({period:bodyFor(block,saved.ranges[index]),range:saved.ranges[index]}));
154
+ for (const {period} of paired) {
148
155
  if (period.notes.some(note => /^### |^[-*+] /u.test(note))) warnings.push(id+' '+period.key+' 含额外正文,保留在区间说明。');
149
156
  }
150
- return forward.reverse();
157
+ return paired.reverse();
158
+ }
159
+
160
+ function publicPeriod(id, period, range, text) {
161
+ const { ledger } = range;
162
+ let items, commitMonths;
163
+ if (ledger === undefined) {
164
+ items = period.items.map(([category, value, markers]) => [category, text(value), markers]);
165
+ } else {
166
+ const fail = () => { throw Error(id+' 的任务明细与成功记录不一致,请用 home-project-changelog 修订该区间。'); };
167
+ if (ledger?.version !== 1 || !plain(ledger.commitMonths) || !Array.isArray(ledger.tasks)
168
+ || ledger.tasks.length !== period.items.length) fail();
169
+ commitMonths = {};
170
+ let total = 0;
171
+ for (const [month,count] of Object.entries(ledger.commitMonths)) {
172
+ if (!validDay(month+'-01') || !Number.isSafeInteger(count) || count <= 0) fail();
173
+ total += count;
174
+ commitMonths[month] = count;
175
+ }
176
+ if (total !== period.commits) fail();
177
+ const ids = new Set();
178
+ items = period.items.map(([category,value,markers,meta],index) => {
179
+ const task = ledger.tasks[index];
180
+ if (!plain(task) || typeof task.id !== 'string' || !/^task-[0-9a-f]{16}$/u.test(task.id) || ids.has(task.id)
181
+ || !validDay(task.date) || !commitMonths[task.date.slice(0,7)] || task.date !== meta?.date
182
+ || task.area !== meta.area || (task.area !== null && !line(task.area))
183
+ || task.category !== category || task.text !== value || JSON.stringify(task.markers) !== JSON.stringify(markers)) fail();
184
+ ids.add(task.id);
185
+ return [category,text(value),markers,{id:task.id,date:task.date,area:task.area && text(task.area)}];
186
+ });
187
+ const features = ledger.tasks.filter(task => task.category === '功能');
188
+ const added = features.every(task => typeof task.added === 'boolean') ? features.filter(task => task.added).length : null;
189
+ if (period.added !== added) fail();
190
+ }
191
+ const notes = period.notes.map(text);
192
+ return {...period,items,notes,note:notes.join('\n'),commitMonths};
151
193
  }
152
194
 
153
195
  export function inputs(website) {
@@ -188,18 +230,18 @@ export function inputs(website) {
188
230
  if (saved.pending) throw Error(id+' 的日志有待确认写入,请先用 home-project-changelog 恢复。');
189
231
  const bytes = take(path.join(logs,id+'.md'));
190
232
  if (!bytes) throw Error(id+' 的日志正文缺失,请先恢复 Markdown。');
191
- let parsed;
192
- try { parsed = parseMarkdown(decode(bytes)); } catch { throw Error(id+' 的日志正文需要可读的 UTF-8 Markdown。'); }
193
- const periods = savedPeriods(id,parsed,saved,warnings).map(period => ({
194
- ...period, items:period.items.map(([type, value, tags]) => [type,text(value),tags]),
195
- notes:period.notes.map(text), note:period.notes.map(text).join('\n'),
196
- }));
233
+ let body;
234
+ try { body = decode(bytes); } catch { throw Error(id+' 的日志正文需要可读的 UTF-8 Markdown。'); }
235
+ const dated = saved.ranges.some(range=>range.ledger) ? parseMarkdown(body,{datedOnly:true}) : null;
236
+ const parsed = saved.ranges.some(range=>!range.ledger) ? parseMarkdown(body) : dated;
237
+ const periods = savedPeriods(id,parsed,dated,saved,warnings).map(({period,range}) => publicPeriod(id,period,range,text));
197
238
  const index = projects.length;
198
239
  projects.push({
199
240
  id, name:text(override.displayName ?? id), purpose:text(override.summary ?? repo.purpose),
200
241
  groups:(repo.groups ?? []).filter(group => settings.publicGroups.includes(group)).map(text),
201
242
  color:colors[index % colors.length], mark:marks[index % marks.length], repoUrl:override.repoUrl, docsUrl:override.docsUrl,
202
- periods, legacy:text(parsed.legacy),
243
+ periods, stats:statistics(periods), headCommits:saved.ranges.at(-1).stats.totalCommitCountAtHead ?? null,
244
+ legacy:text(parsed.legacy),
203
245
  });
204
246
  }
205
247
  return {
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { frame, logPath, projectPath } from '../site/templates/layout.mjs';
4
- import { itemId, observationWindows, periodTitle, rangeLabel, statistics } from '../site/templates/model.mjs';
4
+ import { activityMonths, itemId, observationWindows, periodTitle, rangeLabel, statistics } from '../site/templates/model.mjs';
5
5
  import { overview, catalog, detail, repositoryLog } from '../site/templates/pages.mjs';
6
6
  import { changelog } from '../site/templates/ledger.mjs';
7
7
  import { publicProject } from '../site/templates/project-logs.mjs';
@@ -63,7 +63,10 @@ export function render(website, run, model) {
63
63
  page('changelog/','变更时间线','changelog',changelog(base,projects,windows,stats));
64
64
  urls.push('404.html');
65
65
  const index = [];
66
- const catalogData = {schemaVersion:1,stats,projects:[],windows:windows.map(({from,to,groups,rangeCount,stats}) => ({
66
+ const catalogData = {schemaVersion:2,stats,projects:[],months:activityMonths(projects).map(({key,changes,commits,groups}) => ({
67
+ month:key === 'undated' ? null : key,changes,commits,
68
+ projects:groups.map(({project,commits,rows}) => ({id:project.id,commits,changes:rows.filter(row=>row.index >= 0).length})),
69
+ })),windows:windows.map(({from,to,groups,rangeCount,stats}) => ({
67
70
  from, to, projects:groups.map(({project}) => project.id), rangeCount, stats,
68
71
  }))};
69
72
  const expectedData = new Map();
@@ -77,13 +80,15 @@ export function render(website, run, model) {
77
80
  for (const period of periods) {
78
81
  const date = rangeLabel(period);
79
82
  if (!period.items.length) index.push({kind:'区间',name,id,title:periodTitle(period),text:period.note,date,url:logPath(project,period)});
80
- period.items.forEach(([category,text,markers],i) => {
81
- index.push({kind:'变更',name,id,title:text,text:[category,...markers].join(' · '),date,url:logPath(project)+'#'+itemId(period,i)});
83
+ period.items.forEach(([category,text,markers,meta],i) => {
84
+ index.push({kind:'变更',name,id,title:text,text:[category,meta?.area,...markers].filter(Boolean).join(' · '),
85
+ date:meta?.date ?? date,url:logPath(project)+'#'+itemId(period,i)});
82
86
  });
83
87
  }
84
88
  if (legacy) index.push({kind:'补记',name,id,title:'历史补记',text:legacy,url:logPath(project)+'#legacy'});
85
89
  expectedData.set('data/'+data,json(projected));
86
- catalogData.projects.push({id,name,purpose,ranges:periods.length,entries:projected.stats.changes,data});
90
+ catalogData.projects.push({id,name,purpose,ranges:periods.length,entries:projected.stats.changes,
91
+ commits:projected.stats.commits,headCommits:project.headCommits,data});
87
92
  }
88
93
  expectedData.set('data/catalog.json',json(catalogData));
89
94
  expectedData.set('home-assets/search-index.js','window.homeSearchIndex = '+JSON.stringify(index).replaceAll('<','\\u003c')+';\n');