@urland/workspace 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,252 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parseDocument } from 'yaml';
4
+ import { statusSet, typeSet } from './document.mjs';
5
+ import Ajv from 'ajv/dist/2020.js';
6
+
7
+ const taskId = { type: 'string', pattern: '^task-[1-9][0-9]*$' };
8
+ const mainFile = { type: 'string', pattern: '^task-[1-9][0-9]*-main-[a-z0-9]+(?:-[a-z0-9]+)*\\.md$' };
9
+ const draftFile = { type: 'string', pattern: '^draft-[a-z0-9]+(?:-[a-z0-9]+)*\\.md$' };
10
+ const date = { type: 'string', pattern: '^\\d{4}-\\d{2}-\\d{2}$' };
11
+ const month = { type: 'string', pattern: '^\\d{4}-(?:0[1-9]|1[0-2])$' };
12
+ const text = { type: 'string', minLength: 1 };
13
+ const status = {
14
+ type: 'string',
15
+ enum: [...statusSet],
16
+ };
17
+ const taskType = { type: 'string', enum: [...typeSet] };
18
+ const taskEntryBase = {
19
+ type: 'object',
20
+ required: ['file'],
21
+ properties: { file: { type: 'string', minLength: 1 } },
22
+ };
23
+ const implementation = {
24
+ type: 'array',
25
+ items: {
26
+ type: 'object',
27
+ additionalProperties: false,
28
+ required: ['label', 'file'],
29
+ properties: {
30
+ label: text,
31
+ file: { type: 'string', pattern: '^\\.\\./\\.\\./\\.\\./implementation/[a-z0-9._/-]+\\.md$' },
32
+ },
33
+ },
34
+ };
35
+
36
+ const formalTask = {
37
+ type: 'object',
38
+ allOf: [
39
+ { $ref: '#/$defs/task-entry-base' },
40
+ {
41
+ type: 'object',
42
+ required: ['id', 'file', 'type', 'summary', 'status', 'created'],
43
+ properties: {
44
+ id: taskId,
45
+ file: mainFile,
46
+ type: taskType,
47
+ summary: text,
48
+ status,
49
+ progress: { type: 'string', pattern: '^\\d+\\/\\d+$' },
50
+ judgment: text,
51
+ next_step: text,
52
+ created: date,
53
+ updated: date,
54
+ group: text,
55
+ archived_at: date,
56
+ archive_reason: text,
57
+ replacement: text,
58
+ implementation,
59
+ },
60
+ },
61
+ ],
62
+ unevaluatedProperties: false,
63
+ };
64
+
65
+ const draftEntry = {
66
+ type: 'object',
67
+ allOf: [
68
+ { $ref: '#/$defs/task-entry-base' },
69
+ {
70
+ type: 'object',
71
+ required: ['file', 'title'],
72
+ properties: { file: draftFile, title: text },
73
+ },
74
+ ],
75
+ unevaluatedProperties: false,
76
+ };
77
+
78
+ const indexBase = {
79
+ type: 'object',
80
+ required: ['kind', 'version', 'description', 'notes', 'entries'],
81
+ properties: {
82
+ kind: { type: 'string' },
83
+ version: { const: 1 },
84
+ description: text,
85
+ notes: { type: 'array', items: text },
86
+ scope: { type: 'object' },
87
+ entries: { type: 'array' },
88
+ },
89
+ };
90
+ const emptyScope = { type: 'object', additionalProperties: false };
91
+
92
+ const schemaBase = {
93
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
94
+ type: 'object',
95
+ $defs: { 'task-entry-base': taskEntryBase, 'index-base': indexBase },
96
+ };
97
+
98
+ const schemas = {
99
+ 'tasks-root-index': {
100
+ ...schemaBase,
101
+ allOf: [
102
+ { $ref: '#/$defs/index-base' },
103
+ {
104
+ type: 'object',
105
+ properties: {
106
+ kind: { const: 'tasks-root-index' },
107
+ scope: emptyScope,
108
+ entries: {
109
+ type: 'array',
110
+ minItems: 3,
111
+ items: {
112
+ type: 'object',
113
+ additionalProperties: false,
114
+ required: ['name', 'title', 'file'],
115
+ properties: {
116
+ name: { type: 'string', enum: ['drafts', 'active', 'archive'] },
117
+ title: text,
118
+ file: { type: 'string', pattern: '^(?:drafts|active|archive)/index\\.json$' },
119
+ },
120
+ },
121
+ },
122
+ },
123
+ },
124
+ ],
125
+ unevaluatedProperties: false,
126
+ },
127
+ 'tasks-drafts-index': {
128
+ ...schemaBase,
129
+ allOf: [
130
+ { $ref: '#/$defs/index-base' },
131
+ {
132
+ type: 'object',
133
+ properties: {
134
+ kind: { const: 'tasks-drafts-index' },
135
+ scope: emptyScope,
136
+ entries: { type: 'array', items: draftEntry },
137
+ },
138
+ },
139
+ ],
140
+ unevaluatedProperties: false,
141
+ },
142
+ 'tasks-active-index': {
143
+ ...schemaBase,
144
+ allOf: [
145
+ { $ref: '#/$defs/index-base' },
146
+ {
147
+ type: 'object',
148
+ required: ['scope'],
149
+ properties: {
150
+ kind: { const: 'tasks-active-index' },
151
+ scope: {
152
+ type: 'object',
153
+ additionalProperties: false,
154
+ required: ['next_task_number'],
155
+ properties: { next_task_number: { type: 'integer', minimum: 1 } },
156
+ },
157
+ entries: { type: 'array', items: formalTask },
158
+ },
159
+ },
160
+ ],
161
+ unevaluatedProperties: false,
162
+ },
163
+ 'tasks-archive-index': {
164
+ ...schemaBase,
165
+ allOf: [
166
+ { $ref: '#/$defs/index-base' },
167
+ {
168
+ type: 'object',
169
+ properties: {
170
+ kind: { const: 'tasks-archive-index' },
171
+ scope: emptyScope,
172
+ entries: {
173
+ type: 'array',
174
+ items: {
175
+ type: 'object',
176
+ additionalProperties: false,
177
+ required: ['month', 'count', 'file'],
178
+ properties: {
179
+ month,
180
+ count: { type: 'integer', minimum: 0 },
181
+ file: { type: 'string', pattern: '^[0-9]{4}-(?:0[1-9]|1[0-2])/index\\.json$' },
182
+ },
183
+ },
184
+ },
185
+ },
186
+ },
187
+ ],
188
+ unevaluatedProperties: false,
189
+ },
190
+ 'tasks-archive-month-index': {
191
+ ...schemaBase,
192
+ allOf: [
193
+ { $ref: '#/$defs/index-base' },
194
+ {
195
+ type: 'object',
196
+ required: ['scope'],
197
+ properties: {
198
+ kind: { const: 'tasks-archive-month-index' },
199
+ scope: {
200
+ type: 'object',
201
+ additionalProperties: false,
202
+ required: ['month'],
203
+ properties: { month },
204
+ },
205
+ entries: { type: 'array', items: formalTask },
206
+ },
207
+ },
208
+ ],
209
+ unevaluatedProperties: false,
210
+ },
211
+ };
212
+
213
+ const ajv = new Ajv({ allErrors: true, strict: true });
214
+ const validators = new Map(Object.entries(schemas).map(([kind, schema]) => [kind, ajv.compile(schema)]));
215
+
216
+ function formatError(error) {
217
+ const location = error.instancePath || '/';
218
+ return `${location} ${error.message}`;
219
+ }
220
+
221
+ export function readIndexJson(file, kind, fail) {
222
+ let source;
223
+ try {
224
+ source = fs.readFileSync(file, 'utf8');
225
+ } catch (error) {
226
+ fail(`${path.relative(process.cwd(), file)}:无法读取 index.json:${error.message}`);
227
+ return undefined;
228
+ }
229
+ let value;
230
+ try {
231
+ const document = parseDocument(source, {
232
+ version: '1.2',
233
+ schema: 'core',
234
+ uniqueKeys: true,
235
+ prettyErrors: true,
236
+ });
237
+ if (document.errors.length > 0) {
238
+ throw new Error(document.errors.map((error) => error.message).join(';'));
239
+ }
240
+ value = JSON.parse(source);
241
+ } catch (error) {
242
+ fail(`${path.relative(process.cwd(), file)}:JSON 语法无效:${error.message}`);
243
+ return undefined;
244
+ }
245
+ const validate = validators.get(kind);
246
+ if (!validate) throw new Error(`未注册任务索引 schema:${kind}`);
247
+ if (!validate(value)) {
248
+ for (const error of validate.errors ?? []) fail(`${path.relative(process.cwd(), file)}:${formatError(error)}`);
249
+ return undefined;
250
+ }
251
+ return value;
252
+ }
@@ -0,0 +1,183 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { terminalStatusSet, parseFrontMatter, isIsoDate } from './document.mjs';
4
+ import { readIndexJson } from './index-schema.mjs';
5
+
6
+ function indexPath(file) {
7
+ return path.relative(process.cwd(), file).split(path.sep).join('/');
8
+ }
9
+
10
+ function uniqueRows(rows, field, file, fail) {
11
+ const seen = new Set();
12
+ rows.forEach((row, index) => {
13
+ const value = row[field];
14
+ if (seen.has(value)) fail(`${indexPath(file)}:第 ${index + 1} 项重复 ${field} ${value}`);
15
+ seen.add(value);
16
+ });
17
+ }
18
+
19
+ function checkTaskFileRow(row, file, dir, expectedFiles, context, { archived = false } = {}) {
20
+ const { fail, readDocument, rel } = context;
21
+ const archiveFields = ['group', 'archived_at', 'archive_reason', 'replacement', 'implementation'];
22
+ const taskFile = path.join(dir, row.file);
23
+ if (!fs.existsSync(taskFile)) {
24
+ fail(`${rel(file)}:索引引用的任务文件不存在 ${row.file}`);
25
+ return;
26
+ }
27
+ const metadata = readDocument(taskFile).meta;
28
+ if (row.id !== metadata.id) fail(`${rel(file)}:${row.file} 的 id 与任务 YAML 不一致`);
29
+ if (row.type && row.type !== metadata.type) fail(`${rel(file)}:${row.file} 的 type 与任务 YAML 不一致`);
30
+ if (row.status !== metadata.status) fail(`${rel(file)}:${row.file} 的 status 与任务 YAML 不一致`);
31
+ if (row.progress && row.progress !== metadata.progress) fail(`${rel(file)}:${row.file} 的 progress 与任务 YAML 不一致`);
32
+ if (row.created !== metadata.created) fail(`${rel(file)}:${row.file} 的 created 与任务 YAML 不一致`);
33
+ if (row.updated && row.updated !== metadata.updated) fail(`${rel(file)}:${row.file} 的 updated 与任务 YAML 不一致`);
34
+ if (archived) {
35
+ for (const field of archiveFields) {
36
+ if (!(field in row)) fail(`${rel(file)}:归档任务 ${row.file} 缺少 ${field}`);
37
+ }
38
+ if (!terminalStatusSet.has(metadata.status)) fail(`${rel(file)}:归档任务 ${row.file} 必须处于终态`);
39
+ if (!isIsoDate(row.archived_at)) fail(`${rel(file)}:${row.file} 的 archived_at 必须为有效日期`);
40
+ if (isIsoDate(metadata.updated) && row.archived_at < metadata.updated) {
41
+ fail(`${rel(file)}:${row.file} 的 archived_at 不能早于 updated`);
42
+ }
43
+ for (const implementation of row.implementation ?? []) {
44
+ const target = path.resolve(path.dirname(file), implementation.file);
45
+ if (!fs.existsSync(target) || !fs.statSync(target).isFile()) {
46
+ fail(`${rel(file)}:${row.file} 的 implementation 文件不存在 ${implementation.file}`);
47
+ }
48
+ }
49
+ } else {
50
+ for (const field of ['progress', 'judgment', 'next_step', 'updated']) {
51
+ if (!(field in row)) fail(`${rel(file)}:活动任务 ${row.file} 缺少 ${field}`);
52
+ }
53
+ for (const field of archiveFields) {
54
+ if (field in row) fail(`${rel(file)}:活动任务 ${row.file} 不得包含归档字段 ${field}`);
55
+ }
56
+ }
57
+ expectedFiles.add(taskFile);
58
+ }
59
+
60
+ function checkRootIndex(indexFile, context) {
61
+ const { fail } = context;
62
+ const index = readIndexJson(indexFile, 'tasks-root-index', fail);
63
+ if (!index) return;
64
+ const expected = new Map([
65
+ ['drafts', { title: '需求草稿', file: 'drafts/index.json' }],
66
+ ['active', { title: '活动任务', file: 'active/index.json' }],
67
+ ['archive', { title: '历史归档', file: 'archive/index.json' }],
68
+ ]);
69
+ uniqueRows(index.entries, 'name', indexFile, fail);
70
+ if (index.entries.length !== expected.size) fail(`${indexPath(indexFile)}:entries 必须完整登记 drafts、active、archive`);
71
+ for (const entry of index.entries) {
72
+ const wanted = expected.get(entry.name);
73
+ if (!wanted) continue;
74
+ if (entry.title !== wanted.title) fail(`${indexPath(indexFile)}:${entry.name} 的 title 不符合固定值`);
75
+ if (entry.file !== wanted.file) fail(`${indexPath(indexFile)}:${entry.name} 的 file 不符合固定路径`);
76
+ }
77
+ }
78
+
79
+ function checkDraftIndex(indexFile, dir, expectedFiles, context) {
80
+ const { fail, rel } = context;
81
+ const draftForbiddenMetadata = new Set(['id', 'status', 'type', 'progress', 'specification', 'implementation']);
82
+ for (const file of expectedFiles) {
83
+ const text = fs.readFileSync(file, 'utf8');
84
+ try {
85
+ const metadata = parseFrontMatter(text, rel(file));
86
+ for (const key of Object.keys(metadata)) {
87
+ if (draftForbiddenMetadata.has(key)) fail(`${rel(file)}:草稿不得包含正式任务 YAML 字段 ${key}`);
88
+ }
89
+ } catch (error) {
90
+ fail(error.message);
91
+ }
92
+ }
93
+ const index = readIndexJson(indexFile, 'tasks-drafts-index', fail);
94
+ if (!index) return;
95
+ const listed = new Set();
96
+ uniqueRows(index.entries, 'file', indexFile, fail);
97
+ for (const draft of index.entries) {
98
+ if (listed.has(draft.file)) fail(`${rel(indexFile)}:草稿重复登记 ${draft.file}`);
99
+ listed.add(draft.file);
100
+ const target = path.join(dir, draft.file);
101
+ if (!fs.existsSync(target)) fail(`${rel(indexFile)}:草稿文件不存在 ${draft.file}`);
102
+ }
103
+ for (const file of expectedFiles) {
104
+ const expected = path.relative(dir, file).split(path.sep).join('/');
105
+ if (!listed.has(expected)) fail(`${rel(indexFile)}:缺少草稿 ${expected}`);
106
+ }
107
+ for (const listedFile of listed) {
108
+ if (!expectedFiles.some((file) => path.relative(dir, file).split(path.sep).join('/') === listedFile)) {
109
+ fail(`${rel(indexFile)}:登记了不存在或不受支持的草稿 ${listedFile}`);
110
+ }
111
+ }
112
+ }
113
+
114
+ function checkActiveIndex(indexFile, dir, activeFiles, allTaskFiles, context) {
115
+ const { fail, rel } = context;
116
+ const index = readIndexJson(indexFile, 'tasks-active-index', fail);
117
+ if (!index) return;
118
+ uniqueRows(index.entries, 'id', indexFile, fail);
119
+ uniqueRows(index.entries, 'file', indexFile, fail);
120
+ const expected = new Set();
121
+ for (const row of index.entries) {
122
+ const file = path.join(dir, row.file);
123
+ checkTaskFileRow(row, indexFile, dir, expected, context);
124
+ if (!activeFiles.includes(file)) fail(`${rel(indexFile)}:登记了不属于 active/ 的任务 ${row.file}`);
125
+ }
126
+ for (const file of activeFiles) {
127
+ const expectedFile = path.relative(dir, file).split(path.sep).join('/');
128
+ if (!expected.has(file)) fail(`${rel(indexFile)}:缺少任务 ${expectedFile}`);
129
+ }
130
+ const maxId = Math.max(0, ...allTaskFiles.map((file) => Number(path.basename(file).match(/^task-(\d+)-/)?.[1] ?? 0)));
131
+ if (index.scope.next_task_number <= maxId) fail(`${rel(indexFile)}:scope.next_task_number 必须大于现有最大任务编号 ${maxId}`);
132
+ }
133
+
134
+ function checkArchiveRootIndex(indexFile, groups, context) {
135
+ const { fail, rel } = context;
136
+ const index = readIndexJson(indexFile, 'tasks-archive-index', fail);
137
+ if (!index) return;
138
+ uniqueRows(index.entries, 'month', indexFile, fail);
139
+ const expectedMonths = new Set(groups.keys());
140
+ for (const entry of index.entries) {
141
+ const group = groups.get(entry.month);
142
+ if (!group) {
143
+ fail(`${rel(indexFile)}:登记了不存在的归档月份 ${entry.month}`);
144
+ continue;
145
+ }
146
+ if (entry.file !== `${entry.month}/index.json`) fail(`${rel(indexFile)}:${entry.month} 的 file 路径错误`);
147
+ if (entry.count !== group.files.length) fail(`${rel(indexFile)}:${entry.month} 的 count 与实际任务数不一致`);
148
+ expectedMonths.delete(entry.month);
149
+ }
150
+ for (const month of expectedMonths) fail(`${rel(indexFile)}:缺少归档月份 ${month}`);
151
+ }
152
+
153
+ function checkArchiveMonthIndex(indexFile, month, group, context) {
154
+ const { fail, rel } = context;
155
+ const index = readIndexJson(indexFile, 'tasks-archive-month-index', fail);
156
+ if (!index) return;
157
+ if (index.scope.month !== month) fail(`${rel(indexFile)}:scope.month 必须为 ${month}`);
158
+ uniqueRows(index.entries, 'id', indexFile, fail);
159
+ uniqueRows(index.entries, 'file', indexFile, fail);
160
+ const expected = new Set();
161
+ for (const row of index.entries) {
162
+ checkTaskFileRow(row, indexFile, group.dir, expected, context, { archived: true });
163
+ if (!group.files.includes(path.join(group.dir, row.file))) fail(`${rel(indexFile)}:登记了不属于本月份的任务 ${row.file}`);
164
+ }
165
+ for (const file of group.files) {
166
+ const expectedFile = path.relative(group.dir, file).split(path.sep).join('/');
167
+ if (!expected.has(file)) fail(`${rel(indexFile)}:缺少归档任务 ${expectedFile}`);
168
+ }
169
+ }
170
+
171
+ export function checkTaskIndexes(layout, context) {
172
+ const { draftsRoot, drafts, activeRoot, active, archiveRoot, archivedGroups, archived } = layout;
173
+ const draftsIndex = path.join(draftsRoot, 'index.json');
174
+ const activeIndex = path.join(activeRoot, 'index.json');
175
+ const archiveIndex = path.join(archiveRoot, 'index.json');
176
+ checkRootIndex(path.join(path.dirname(draftsRoot), 'index.json'), context);
177
+ checkDraftIndex(draftsIndex, draftsRoot, drafts, context);
178
+ checkActiveIndex(activeIndex, activeRoot, active, [...active, ...archived], context);
179
+ checkArchiveRootIndex(archiveIndex, archivedGroups, context);
180
+ for (const [month, group] of archivedGroups) {
181
+ checkArchiveMonthIndex(path.join(group.dir, 'index.json'), month, group, context);
182
+ }
183
+ }
@@ -0,0 +1,102 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { mainName, extName, archiveMonthName } from './document.mjs';
4
+
5
+ function walk(dir) {
6
+ const result = [];
7
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
8
+ if (entry.name === '.git' || entry.name === 'node_modules' || entry.name === 'coverage') continue;
9
+ const full = path.join(dir, entry.name);
10
+ if (entry.isDirectory()) result.push(...walk(full));
11
+ else result.push(full);
12
+ }
13
+ return result;
14
+ }
15
+
16
+ function taskFiles(dir) {
17
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
18
+ return entries
19
+ .filter((entry) => entry.isFile() && mainName.test(entry.name))
20
+ .map((entry) => path.join(dir, entry.name));
21
+ }
22
+
23
+ function extensionFiles(dir) {
24
+ return fs.readdirSync(dir, { withFileTypes: true })
25
+ .filter((entry) => entry.isFile() && extName.test(entry.name))
26
+ .map((entry) => path.join(dir, entry.name));
27
+ }
28
+
29
+ function archivedTaskGroups(dir, rel, fail) {
30
+ const groups = new Map();
31
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
32
+ const full = path.join(dir, entry.name);
33
+ if (entry.isFile()) {
34
+ if (entry.name !== 'index.json') {
35
+ fail(`${rel(full)}: tasks/archive/ 根目录只允许 index.json 和月份目录`);
36
+ }
37
+ continue;
38
+ }
39
+ if (entry.name === '.git') continue;
40
+ if (!archiveMonthName.test(entry.name)) {
41
+ fail(`${rel(full)}: 归档任务目录必须使用 tasks/archive/YYYY-MM/ 格式`);
42
+ continue;
43
+ }
44
+ const index = path.join(full, 'index.json');
45
+ if (!fs.existsSync(index)) fail(`${rel(full)}: 缺少月份索引 index.json`);
46
+ const files = [];
47
+ const extensions = [];
48
+ for (const monthEntry of fs.readdirSync(full, { withFileTypes: true })) {
49
+ const monthFile = path.join(full, monthEntry.name);
50
+ if (monthEntry.isDirectory()) {
51
+ fail(`${rel(monthFile)}: 月份目录不能继续嵌套目录`);
52
+ } else if (monthEntry.isFile() && mainName.test(monthEntry.name)) {
53
+ files.push(monthFile);
54
+ } else if (monthEntry.isFile() && extName.test(monthEntry.name)) {
55
+ extensions.push(monthFile);
56
+ } else if (monthEntry.isFile() && monthEntry.name !== 'index.json') {
57
+ fail(`${rel(monthFile)}: 月份目录只允许 index.json、主任务和补充文档`);
58
+ }
59
+ }
60
+ groups.set(entry.name, { dir: full, files, extensions });
61
+ }
62
+ return groups;
63
+ }
64
+
65
+ export function readLayout(docsRoot, rel, fail) {
66
+ const draftName = /^draft-[a-z0-9]+(?:-[a-z0-9]+)*\.md$/;
67
+ const tasksRoot = path.join(docsRoot, 'tasks');
68
+ const activeRoot = path.join(tasksRoot, 'active');
69
+ const draftsRoot = path.join(tasksRoot, 'drafts');
70
+ const archiveRoot = path.join(tasksRoot, 'archive');
71
+ const taskRootDirectories = new Set(['drafts', 'active', 'archive']);
72
+ const active = taskFiles(activeRoot);
73
+ const archivedGroups = archivedTaskGroups(archiveRoot, rel, fail);
74
+ const drafts = fs.readdirSync(draftsRoot, { withFileTypes: true })
75
+ .filter((entry) => entry.isFile() && draftName.test(entry.name))
76
+ .map((entry) => path.join(draftsRoot, entry.name));
77
+ const archived = [...archivedGroups.values()].flatMap((group) => group.files);
78
+ const activeExtensions = extensionFiles(activeRoot);
79
+ const archivedExtensions = [...archivedGroups.values()].flatMap((group) => group.extensions);
80
+ const allExtensions = [...activeExtensions, ...archivedExtensions];
81
+ const allTasks = [...active, ...archived];
82
+ const managedTaskFiles = new Set([...allTasks, ...allExtensions]);
83
+ for (const entry of fs.readdirSync(tasksRoot, { withFileTypes: true })) {
84
+ if (entry.isFile() && entry.name !== 'index.json') fail(`tasks/${entry.name}: tasks/ 根目录只允许 index.json 和生命周期目录`);
85
+ if (entry.isDirectory() && !taskRootDirectories.has(entry.name)) fail(`tasks/${entry.name}: 不是受支持的任务生命周期目录`);
86
+ }
87
+ for (const [directory, allowed] of [[draftsRoot, (name) => draftName.test(name)], [activeRoot, (name) => mainName.test(name) || extName.test(name)]]) {
88
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
89
+ if (entry.isDirectory()) fail(`${rel(path.join(directory, entry.name))}: 任务生命周期目录不能继续嵌套目录`);
90
+ else if (entry.name !== 'index.json' && !allowed(entry.name)) fail(`${rel(path.join(directory, entry.name))}: 不是受支持的任务文档文件名`);
91
+ }
92
+ }
93
+ for (const file of walk(tasksRoot)) {
94
+ const name = path.basename(file);
95
+ if ((mainName.test(name) || extName.test(name)) && !managedTaskFiles.has(file)) {
96
+ fail(`${rel(file)}: 任务文档只能放在 tasks/active/ 或 tasks/archive/YYYY-MM/,并必须登记到对应主任务`);
97
+ } else if (/^task-[1-9][0-9]*-.*\.md$/.test(name) && !mainName.test(name) && !extName.test(name)) {
98
+ fail(`${rel(file)}: 任务文件名必须使用 task-N-main-<task-slug>.md 或 task-N-ext-<ext-type>-<slug>.md`);
99
+ }
100
+ }
101
+ return { tasksRoot, draftsRoot, activeRoot, archiveRoot, drafts, active, archivedGroups, archived, allTasks, allExtensions };
102
+ }
@@ -0,0 +1,109 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import {
4
+ activeStatusSet, archiveMonthName, documentSections, isIsoDate,
5
+ parseMainName, progressFromBody, statusSet, terminalStatusSet, typeSet,
6
+ } from './document.mjs';
7
+ import { allowsHistoricalPathMigration } from './migration.mjs';
8
+
9
+ const taskMetadataKeys = new Set(['id', 'document-kind', 'status', 'type', 'created', 'updated', 'progress', 'extensions', 'specification', 'implementation', 'related-projects']);
10
+
11
+ function checkSpecificationImpact(relative, text, meta, fail) {
12
+ const heading = /^## 规范影响评估\s*$/m.exec(text);
13
+ if (!heading) {
14
+ fail(`${relative}: 正式任务必须包含“规范影响评估”章节`);
15
+ return;
16
+ }
17
+ const section = text.slice(heading.index + heading[0].length).split(/^## /m, 1)[0];
18
+ const conclusion = /^结论[::]\s*(有|无)\s*$/m.exec(section)?.[1];
19
+ if (!conclusion) fail(`${relative}: 规范影响评估必须写“结论:有”或“结论:无”`);
20
+ if (!/^依据[::]\s*\S/m.test(section)) fail(`${relative}: 规范影响评估必须写明“依据”`);
21
+ const specification = Array.isArray(meta.specification) ? meta.specification : [];
22
+ if (conclusion === '有' && specification.length === 0) {
23
+ fail(`${relative}: 规范影响评估结论为“有”时 specification 不能是空列表`);
24
+ }
25
+ if (conclusion === '无' && specification.length > 0) {
26
+ fail(`${relative}: 规范影响评估结论为“无”时 specification 必须是空列表`);
27
+ }
28
+ }
29
+
30
+ export function checkMainTasks(tasks, docsRoot, baseline, fail) {
31
+ const ids = new Set();
32
+ for (const { file, relative, meta, text: body } of tasks) {
33
+ const parsedName = parseMainName(path.basename(file));
34
+ const expectedId = parsedName?.id ?? '';
35
+ const isArchived = relative.startsWith('tasks/archive/');
36
+ if (isArchived && !terminalStatusSet.has(meta.status)) {
37
+ fail(`${relative}: 归档任务必须使用终态(已完成/已关闭/已合并/已取消),当前为 ${meta.status}`);
38
+ }
39
+ if (!isArchived && !activeStatusSet.has(meta.status)) {
40
+ fail(`${relative}: 活动任务不能使用终态 ${meta.status};完成后必须移入 tasks/archive/YYYY-MM/ 并同步索引`);
41
+ }
42
+ if (isArchived) {
43
+ const archiveParts = relative.split('/');
44
+ const archiveMonth = archiveParts[2];
45
+ if (archiveParts.length !== 4 || !archiveMonthName.test(archiveMonth)) {
46
+ fail(`${relative}: 归档任务必须放在 tasks/archive/YYYY-MM/ 目录`);
47
+ } else if (typeof meta.updated === 'string' && meta.updated.slice(0, 7) !== archiveMonth) {
48
+ fail(`${relative}: 归档目录月份必须与 updated 的月份一致`);
49
+ }
50
+ }
51
+ if (meta.id !== expectedId) fail(`${relative}: YAML id 必须与任务编号一致:${expectedId}`);
52
+ if (meta['document-kind'] !== 'main') fail(`${relative}: document-kind 必须为 main`);
53
+ for (const key of Object.keys(meta)) if (!taskMetadataKeys.has(key)) fail(`${relative}: 未知任务 YAML 字段 ${key}`);
54
+ if (ids.has(meta.id)) fail(`${relative}: 任务 id 重复 ${meta.id}`);
55
+ ids.add(meta.id);
56
+ if (!statusSet.has(meta.status)) fail(`${relative}: 非法状态 ${meta.status}`);
57
+ if (!typeSet.has(meta.type)) fail(`${relative}: 非法任务类型 ${meta.type}`);
58
+ for (const key of ['created', 'updated']) if (!isIsoDate(meta[key])) fail(`${relative}: ${key} 必须为有效的 YYYY-MM-DD 日期`);
59
+ if (isIsoDate(meta.created) && isIsoDate(meta.updated) && meta.updated < meta.created) fail(`${relative}: updated 不能早于 created`);
60
+ if (!/^\d+\/\d+$/.test(meta.progress ?? '')) fail(`${relative}: progress 必须为 n/m`);
61
+ let calculated = '';
62
+ try {
63
+ calculated = progressFromBody(body);
64
+ const [complete, total] = calculated.split('/');
65
+ if (meta.status === '已完成' && complete !== total) fail(`${relative}: 已完成任务的 P 项必须全部勾选`);
66
+ } catch (error) {
67
+ fail(`${relative}: ${error.message}`);
68
+ }
69
+ if (meta.progress !== calculated) fail(`${relative}: YAML progress=${meta.progress},复选框计算值=${calculated}`);
70
+ const heading = body.match(/^# (task-[^::]+)[::]/m);
71
+ if (!heading || heading[1] !== parsedName?.stem) fail(`${relative}: 首个一级标题必须包含 ${parsedName?.stem}`);
72
+ const bodyStatus = body.match(/^状态:(.+)$/m);
73
+ if (!bodyStatus || bodyStatus[1].trim() !== meta.status) fail(`${relative}: 正文状态必须与 YAML status 一致`);
74
+ const baseTask = baseline.baseTasks.get(meta.id);
75
+ const changed = baseTask?.closeChanges ?? baseline.changed;
76
+ const taskChanged = changed.has(relative);
77
+ const historicalMigration = allowsHistoricalPathMigration({
78
+ documentTreeRestructure: baseline.documentTreeRestructure, isArchived, baseTask, status: meta.status,
79
+ previousText: baseTask?.text, currentText: body,
80
+ });
81
+ if ((!isArchived || taskChanged) && !historicalMigration) checkSpecificationImpact(relative, body, meta, fail);
82
+ for (const key of documentSections) {
83
+ const root = path.join(docsRoot, key);
84
+ const paths = meta[key];
85
+ if (!Array.isArray(paths)) {
86
+ fail(`${relative}: ${key} 必须是文件路径列表;没有变更时使用空列表`);
87
+ continue;
88
+ }
89
+ const seen = new Set();
90
+ for (const target of paths) {
91
+ if (typeof target !== 'string' || !target.startsWith(`${key}/`)) {
92
+ fail(`${relative}: ${key} 只能指向 ${key}/ 下的文件:${target}`);
93
+ continue;
94
+ }
95
+ if (seen.has(target)) fail(`${relative}: ${key} 存在重复路径 ${target}`);
96
+ seen.add(target);
97
+ const resolved = path.resolve(docsRoot, target);
98
+ if (!resolved.startsWith(`${root}${path.sep}`)) {
99
+ fail(`${relative}: ${key} 路径越出目录:${target}`);
100
+ } else if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
101
+ fail(`${relative}: ${key} 文件路径不存在或不是文件 ${target}`);
102
+ }
103
+ if (key === 'implementation' && taskChanged && terminalStatusSet.has(meta.status) && !changed.has(target) && !historicalMigration) {
104
+ fail(`${relative}: 终态任务的 ${key} 文件 ${target} 未出现在 --base 差异中`);
105
+ }
106
+ }
107
+ }
108
+ }
109
+ }