@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.
- package/README.md +82 -2
- package/bin/workspace.mjs +36 -0
- package/package.json +26 -4
- package/src/init.mjs +112 -0
- package/src/tasks/baseline.mjs +86 -0
- package/src/tasks/check.mjs +48 -0
- package/src/tasks/document.mjs +69 -0
- package/src/tasks/extensions.mjs +67 -0
- package/src/tasks/index-schema.mjs +252 -0
- package/src/tasks/indexes.mjs +183 -0
- package/src/tasks/layout.mjs +102 -0
- package/src/tasks/main-tasks.mjs +109 -0
- package/src/tasks/migration.mjs +47 -0
- package/src/tasks/promotions.mjs +30 -0
- package/src/tasks/transitions.mjs +142 -0
- package/template/AGENTS.md +8 -0
- package/template/README.md +19 -0
- package/template/dev-docs/implementation/facts/index.md +3 -0
- package/template/dev-docs/implementation/index.md +3 -0
- package/template/dev-docs/index.md +13 -0
- package/template/dev-docs/specification/index.md +3 -0
- package/template/dev-docs/tasks/active/index.json +10 -0
- package/template/dev-docs/tasks/archive/index.json +7 -0
- package/template/dev-docs/tasks/drafts/index.json +7 -0
- package/template/dev-docs/tasks/index.json +23 -0
- package/template/gitignore.tpl +1 -0
- package/template/storage/gitignore.tpl +2 -0
- package/template/worktrees/gitignore.tpl +2 -0
package/README.md
CHANGED
|
@@ -1,3 +1,83 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @urland/workspace
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
为多仓库项目初始化工作空间,在根仓库内维护开发文档、任务和索引。Node.js 22 或以上版本可运行 CLI。
|
|
4
|
+
|
|
5
|
+
## 初始化工作空间
|
|
6
|
+
|
|
7
|
+
包发布到 npmjs 后,在目标目录执行以下命令。第一行通过 npx 运行初始化器,生成工作空间和内置的开发文档,并在 package.json 中登记工具版本。第二行安装项目依赖并生成锁文件。
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npx @urland/workspace init
|
|
11
|
+
npm install
|
|
12
|
+
npm run check:tasks
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
一次初始化生成以下内容。
|
|
16
|
+
|
|
17
|
+
```text
|
|
18
|
+
AGENTS.md
|
|
19
|
+
README.md
|
|
20
|
+
.gitignore
|
|
21
|
+
storage/.gitignore
|
|
22
|
+
worktrees/.gitignore
|
|
23
|
+
dev-docs/
|
|
24
|
+
index.md
|
|
25
|
+
specification/index.md
|
|
26
|
+
implementation/index.md
|
|
27
|
+
implementation/facts/index.md
|
|
28
|
+
tasks/
|
|
29
|
+
index.json
|
|
30
|
+
drafts/index.json
|
|
31
|
+
active/index.json
|
|
32
|
+
archive/index.json
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
在根 README 登记各独立仓库并将检出目录加入根忽略规则。同工作空间的 package.json、package-lock.json 和 dev-docs 一起提交。校验程序随 npm 依赖安装。
|
|
36
|
+
|
|
37
|
+
`init` 可重复运行,会补全缺少的模板文件。在已有 package.json 中保留依赖与脚本,并在缺少时登记 `check:tasks`。若项目已有自定义的同名脚本,直接执行 `npm exec -- workspace check` 可运行包内任务校验。如需指定初始化版本,使用 `npx @urland/workspace@0.1.0 init`。其他成员克隆工作空间后运行 `npm ci` 即可使用锁定版本。
|
|
38
|
+
|
|
39
|
+
## 校验开发任务
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
npm run check:tasks
|
|
43
|
+
npm run check:tasks -- --base <变更前提交>
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
默认读取当前工作空间的 `dev-docs/`。快照检查覆盖任务 YAML、P 项进度、索引、扩展登记、规范影响评估和归档位置。`--base` 接受本地可解析的 Git 提交或引用,同时检查状态迁移、草稿转正和应当随迁移更新的文件。跨多个提交检查归档时,工具会从 Git 历史读取归档前的活动记录,核对当时的状态、进度与扩展。CI 需检出基线和归档所在的提交历史。失败时命令输出原因并返回非零状态。权限、实际运行证据与用户授权由任务负责人核对。
|
|
47
|
+
|
|
48
|
+
`npm run check:tasks` 调用工作空间的 `workspace check`。已有独立检出的 `dev-docs/` 也可从工作空间根目录检查,其基线取自文档仓库。将独立检出并入工作空间涉及迁移历史、忽略规则和仓库清单,初始化命令会在识别到该检出时提示维护者。迁移后从根 `.gitignore` 移除旧的 `/dev-docs/` 规则,用 `git check-ignore -v --no-index dev-docs/index.md` 核对。退出码 1 表示该文件未被忽略,可随根仓库提交。
|
|
49
|
+
|
|
50
|
+
## 发布前试用
|
|
51
|
+
|
|
52
|
+
在工具仓库运行 `npm ci`、`npm test` 和 `npm pack`。进入新的试用目录,将下方路径替换为刚生成的压缩包绝对路径。通过 npx 初始化后,用同一个压缩包安装本地依赖。
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
workspace_tgz=/absolute/path/to/urland-workspace-0.1.0.tgz
|
|
56
|
+
npx --yes --package="$workspace_tgz" workspace init
|
|
57
|
+
npm add -D "$workspace_tgz"
|
|
58
|
+
npm run check:tasks
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## 维护
|
|
62
|
+
|
|
63
|
+
### 自动发布到 npmjs
|
|
64
|
+
|
|
65
|
+
维护者在 GitLab 的发布提交上推送 `vX.Y.Z` 标签后,推送镜像会将标签同步到 GitHub。GitHub Actions 校验标签与 `package.json` 版本一致,在该提交上运行测试,成功后通过 OIDC 直接将 `@urland/workspace` 公开发布为 npmjs 的 `latest`。正式版本由维护者打标签触发,日常分支推送只同步代码。
|
|
66
|
+
|
|
67
|
+
首次启用需要完成以下设置。
|
|
68
|
+
|
|
69
|
+
1. 在 GitLab 的 Settings → Repository → Mirroring repositories 添加指向 `urland-cn/npm-packages-workspace` 的推送镜像,确保发布分支和版本标签都会同步。镜像可使用仅对该 GitHub 仓库有写权限的 SSH deploy key。在 GitLab 保护 `v*` 标签,仅授权发布维护者创建,并限制 GitHub 镜像的直接写入权限。确认 GitHub 已启用 Actions 并已收到本仓库的 `.github/workflows/publish.yml`。
|
|
70
|
+
2. npm 要求包已存在才能绑定 Trusted Publisher。若是首次创建包,在准备好的首版发布提交上执行 `npm ci` 和 `npm test`,再用有权向 `@urland` 发布的维护账号运行 `npm login --registry=https://registry.npmjs.org/` 和 `npm publish --access public --registry=https://registry.npmjs.org/`,按 npm 提示完成身份验证。
|
|
71
|
+
3. 在 npmjs 的包设置中添加 **Trusted Publisher → GitHub Actions**。组织填 `urland-cn`,仓库填 `npm-packages-workspace`,工作流文件名填 `publish.yml`,Environment 留空。在允许的操作中勾选 **`npm publish`**。准备好下一个版本时再绑定,npm 要求新绑定在两天内完成首次成功发布。[npm Trusted Publishing 文档](https://docs.npmjs.com/trusted-publishers/)
|
|
72
|
+
|
|
73
|
+
后续升版时,在发布分支执行例如 `npm version 0.1.1 --no-git-tag-version`,将 `package.json` 和 `package-lock.json` 一起提交。合入 `master` 后,在对应提交上创建并推送同版本标签,如 `v0.1.1`。GitHub Actions 的发布作业成功后,可用 `npm view @urland/workspace@latest version --registry=https://registry.npmjs.org/` 核对线上版本。
|
|
74
|
+
|
|
75
|
+
### 模板和工具
|
|
76
|
+
|
|
77
|
+
`template/` 对应整个工作空间根目录。新增初始文件时,直接放在它应出现在工作空间里的相对路径,例如 `template/dev-docs/specification/index.md`。初始化遍历一次模板,补齐缺少的文件。`gitignore.tpl` 在生成时写为 `.gitignore`,避免 npm 安装时将其改名。根 package.json 单独合并工具依赖和任务检查命令,以保留项目自己的配置。
|
|
78
|
+
|
|
79
|
+
`bin/workspace.mjs` 分发命令,`src/init.mjs` 负责初始化,`src/tasks/check.mjs` 实现 `workspace check`。本包自身的测试和行数检查位于 `test/`。
|
|
80
|
+
|
|
81
|
+
升级已安装的版本时执行 `npm add -D --save-exact @urland/workspace@<版本>` 并重新运行任务门禁。工作空间内的开发文档由项目维护,日常升级只更新依赖与锁文件。
|
|
82
|
+
|
|
83
|
+
工具仓库开发者可用 `git config --local core.hooksPath .githooks` 启用提交前的源文件行数检查。CI 在 `npm test` 中执行同一检查。
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { initWorkspace } from '../src/init.mjs';
|
|
5
|
+
|
|
6
|
+
const help = `用法
|
|
7
|
+
npx @urland/workspace init
|
|
8
|
+
npm run check:tasks [-- --base <变更前提交>]
|
|
9
|
+
workspace check [文档目录] [--base <变更前提交>]
|
|
10
|
+
|
|
11
|
+
在工作空间根目录执行。文档目录默认是 ./dev-docs。
|
|
12
|
+
默认检查当前任务快照,--base 额外检查 Git 状态迁移和草稿转正。`;
|
|
13
|
+
|
|
14
|
+
try {
|
|
15
|
+
const { values, positionals } = parseArgs({
|
|
16
|
+
allowPositionals: true,
|
|
17
|
+
options: { help: { type: 'boolean', short: 'h' }, base: { type: 'string' } },
|
|
18
|
+
});
|
|
19
|
+
// 早期试用包生成的 npm 脚本使用 dev-docs check。
|
|
20
|
+
if (positionals[0] === 'dev-docs' && positionals[1] === 'check') positionals.shift();
|
|
21
|
+
const [command, directory] = positionals;
|
|
22
|
+
if (values.help || (!command && values.base === undefined)) {
|
|
23
|
+
console.log(help);
|
|
24
|
+
} else if (command === 'init' && positionals.length === 1 && values.base === undefined) {
|
|
25
|
+
await initWorkspace(process.cwd());
|
|
26
|
+
} else if (command === 'check' && positionals.length <= 2) {
|
|
27
|
+
if (values.base !== undefined && !values.base.trim()) throw new Error('--base 需要指定变更前提交');
|
|
28
|
+
const { runTaskChecks } = await import('../src/tasks/check.mjs');
|
|
29
|
+
process.exitCode = runTaskChecks(path.resolve(directory ?? 'dev-docs'), values.base);
|
|
30
|
+
} else {
|
|
31
|
+
throw new Error(help);
|
|
32
|
+
}
|
|
33
|
+
} catch (error) {
|
|
34
|
+
console.error(error.message);
|
|
35
|
+
process.exitCode = 1;
|
|
36
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@urland/workspace",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "初始化多仓库工作空间并校验内置 dev-docs 的任务与索引",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/urland-cn/npm-packages-workspace.git"
|
|
8
|
+
},
|
|
9
|
+
"type": "module",
|
|
10
|
+
"bin": {
|
|
11
|
+
"workspace": "bin/workspace.mjs"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"bin/",
|
|
15
|
+
"src/",
|
|
16
|
+
"template/"
|
|
17
|
+
],
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=22"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"test": "node test/check-source-lines.mjs && node --test test/*.test.mjs"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"ajv": "^8.20.0",
|
|
26
|
+
"yaml": "^2.9.1"
|
|
27
|
+
}
|
|
28
|
+
}
|
package/src/init.mjs
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { copyFile, link, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
|
|
7
|
+
const template = fileURLToPath(new URL('../template/', import.meta.url));
|
|
8
|
+
const metadata = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
|
|
9
|
+
const checkCommand = 'workspace check';
|
|
10
|
+
|
|
11
|
+
async function statIfPresent(target) {
|
|
12
|
+
try {
|
|
13
|
+
return await lstat(target);
|
|
14
|
+
} catch (error) {
|
|
15
|
+
if (error.code === 'ENOENT') return undefined;
|
|
16
|
+
throw error;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function planTemplate(source, destination, directories, files) {
|
|
21
|
+
const existing = await statIfPresent(destination);
|
|
22
|
+
if (existing && !existing.isDirectory()) throw new Error(`模板目录位置已被占用:${destination}`);
|
|
23
|
+
if (!existing) directories.push(destination);
|
|
24
|
+
for (const entry of await readdir(source, { withFileTypes: true })) {
|
|
25
|
+
const from = path.join(source, entry.name);
|
|
26
|
+
const target = path.join(destination, entry.name === 'gitignore.tpl' ? '.gitignore' : entry.name);
|
|
27
|
+
if (entry.isDirectory()) {
|
|
28
|
+
await planTemplate(from, target, directories, files);
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
const file = await statIfPresent(target);
|
|
32
|
+
if (!file) files.push({ from, target });
|
|
33
|
+
else if (!file.isFile()) throw new Error(`模板文件位置已被占用:${target}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function isObject(value) {
|
|
38
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function planManifest(file) {
|
|
42
|
+
const existing = await statIfPresent(file);
|
|
43
|
+
if (existing && !existing.isFile()) throw new Error(`请检查 ${file} 的文件类型`);
|
|
44
|
+
const original = existing && await readFile(file, 'utf8');
|
|
45
|
+
const manifest = existing ? JSON.parse(original) : { private: true };
|
|
46
|
+
if (!isObject(manifest)) throw new Error('package.json 必须是 JSON 对象');
|
|
47
|
+
for (const key of ['scripts', 'dependencies', 'devDependencies']) {
|
|
48
|
+
if (manifest[key] === undefined) continue;
|
|
49
|
+
if (!isObject(manifest[key]) || Object.values(manifest[key]).some((value) => typeof value !== 'string')) {
|
|
50
|
+
throw new Error(`package.json 的 ${key} 必须是值为字符串的 JSON 对象`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const hasDependency = Object.hasOwn(manifest.devDependencies ?? {}, metadata.name)
|
|
54
|
+
|| Object.hasOwn(manifest.dependencies ?? {}, metadata.name);
|
|
55
|
+
const hasCheck = Object.hasOwn(manifest.scripts ?? {}, 'check:tasks');
|
|
56
|
+
const customCheck = hasCheck && ![checkCommand, 'workspace dev-docs check'].includes(manifest.scripts['check:tasks']);
|
|
57
|
+
if (hasDependency && hasCheck) return { customCheck };
|
|
58
|
+
if (!hasDependency) manifest.devDependencies = { ...manifest.devDependencies, [metadata.name]: metadata.version };
|
|
59
|
+
if (!hasCheck) manifest.scripts = { ...manifest.scripts, 'check:tasks': checkCommand };
|
|
60
|
+
return { original, content: JSON.stringify(manifest, null, 2) + '\n', mode: existing?.mode, customCheck };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function updateManifest(file) {
|
|
64
|
+
// 复制期间项目可能已更新 package.json,以最后读取到的内容合并。
|
|
65
|
+
const manifest = await planManifest(file);
|
|
66
|
+
if (manifest.content !== undefined) {
|
|
67
|
+
const temporary = path.join(path.dirname(file), '.workspace-' + randomUUID() + '.tmp');
|
|
68
|
+
try {
|
|
69
|
+
await writeFile(temporary, manifest.content, { flag: 'wx', mode: manifest.mode });
|
|
70
|
+
if (manifest.original === undefined) {
|
|
71
|
+
await link(temporary, file);
|
|
72
|
+
} else {
|
|
73
|
+
if (await readFile(file, 'utf8') !== manifest.original) {
|
|
74
|
+
throw new Error('package.json 在初始化期间发生变化,请重新运行 init。');
|
|
75
|
+
}
|
|
76
|
+
await rename(temporary, file);
|
|
77
|
+
}
|
|
78
|
+
} finally {
|
|
79
|
+
await rm(temporary, { force: true });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return manifest.customCheck;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function initWorkspace(root) {
|
|
86
|
+
const docs = path.join(root, 'dev-docs');
|
|
87
|
+
if (await statIfPresent(path.join(docs, '.git'))) {
|
|
88
|
+
throw new Error('dev-docs 是独立 Git 检出。请先确定历史迁移方式,现有文档可从工作空间根目录运行 workspace check。');
|
|
89
|
+
}
|
|
90
|
+
const manifestFile = path.join(root, 'package.json');
|
|
91
|
+
await planManifest(manifestFile);
|
|
92
|
+
const directories = [];
|
|
93
|
+
const files = [];
|
|
94
|
+
await planTemplate(template, root, directories, files);
|
|
95
|
+
for (const dir of directories) {
|
|
96
|
+
await mkdir(dir, { recursive: true });
|
|
97
|
+
}
|
|
98
|
+
for (const { from, target } of files) {
|
|
99
|
+
try {
|
|
100
|
+
await copyFile(from, target, constants.COPYFILE_EXCL);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (error.code !== 'EEXIST' || !(await lstat(target)).isFile()) throw error;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const customCheck = await updateManifest(manifestFile);
|
|
106
|
+
console.log('工作空间已初始化。开发文档见 dev-docs/index.md。');
|
|
107
|
+
if (customCheck) {
|
|
108
|
+
console.log('项目已有自定义 check:tasks。首次使用请执行 npm install,再运行 npm exec -- workspace check 检查开发任务。');
|
|
109
|
+
} else {
|
|
110
|
+
console.log('首次使用请执行 npm install,再运行 npm run check:tasks。');
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
3
|
+
import { extName, parseFrontMatter, parseLegacyName, parseMainName } from './document.mjs';
|
|
4
|
+
import { isDocumentTreeRestructure } from './migration.mjs';
|
|
5
|
+
|
|
6
|
+
function files(output) {
|
|
7
|
+
return output.split('\0').filter(Boolean);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// 范围基线可以早于立项。归档准入取实际归档前一版的活动任务及那一次差异。
|
|
11
|
+
function readBeforeArchive(git, base, head, current) {
|
|
12
|
+
const archivedFile = current.relative;
|
|
13
|
+
const close = git('log', '-1', '--format=%H', '--diff-filter=A', '--no-renames',
|
|
14
|
+
base + '..' + head, '--', archivedFile).trim();
|
|
15
|
+
const parent = close ? close + '^1' : head;
|
|
16
|
+
const { id } = parseMainName(path.basename(archivedFile));
|
|
17
|
+
const activeFile = files(git('ls-tree', '-r', '-z', '--name-only', parent, '--', 'tasks/active'))
|
|
18
|
+
.find((file) => parseMainName(path.basename(file))?.id === id);
|
|
19
|
+
if (!activeFile) return;
|
|
20
|
+
|
|
21
|
+
const closeChanges = new Set(files(git('diff', '--relative', '--no-renames', '--name-only', '-z',
|
|
22
|
+
parent, ...(close ? [close] : []), '--', '.')));
|
|
23
|
+
if (!close) {
|
|
24
|
+
for (const file of files(git('ls-files', '--others', '--exclude-standard', '-z', '--', '.'))) closeChanges.add(file);
|
|
25
|
+
}
|
|
26
|
+
const text = git('show', parent + ':./' + activeFile);
|
|
27
|
+
return { file: activeFile, text, meta: parseFrontMatter(text, activeFile), closeChanges, close };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function readTaskBaseline(docsRoot, ref, documents, fail) {
|
|
31
|
+
const changed = new Set();
|
|
32
|
+
const baseTasks = new Map();
|
|
33
|
+
const draftFiles = new Set();
|
|
34
|
+
const activeDocuments = new Map();
|
|
35
|
+
if (ref) {
|
|
36
|
+
const options = { cwd: docsRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] };
|
|
37
|
+
const git = (...args) => execFileSync('git', args, options);
|
|
38
|
+
const commit = git('rev-parse', '--verify', '--end-of-options', ref + '^{commit}').trim();
|
|
39
|
+
for (const file of files(git('diff', '--relative', '--no-renames', '--name-only', '-z', commit, '--', '.'))) changed.add(file);
|
|
40
|
+
for (const file of files(git('ls-files', '--others', '--exclude-standard', '-z', '--', '.'))) changed.add(file);
|
|
41
|
+
|
|
42
|
+
const snapshot = new Map(documents.map((doc) => [doc.relative, doc]));
|
|
43
|
+
const tree = git('ls-tree', '-r', '-z', '--name-only', commit, '--', 'tasks', 'archived-tasks');
|
|
44
|
+
for (const file of files(tree)) {
|
|
45
|
+
if (file.startsWith('tasks/drafts/')) draftFiles.add(file);
|
|
46
|
+
const name = path.basename(file);
|
|
47
|
+
const task = parseMainName(name) ?? parseLegacyName(name);
|
|
48
|
+
const active = file.startsWith('tasks/active/');
|
|
49
|
+
if (!task && !(active && extName.test(name))) continue;
|
|
50
|
+
const cached = !changed.has(file) ? snapshot.get(file) : undefined;
|
|
51
|
+
const text = cached?.text ?? git('show', commit + ':./' + file);
|
|
52
|
+
if (active) activeDocuments.set(file, text);
|
|
53
|
+
if (!task) continue;
|
|
54
|
+
const priority = active ? 3 : file.startsWith('tasks/') ? 2 : 1;
|
|
55
|
+
const previous = baseTasks.get(task.id);
|
|
56
|
+
if (!previous || priority > previous.priority) {
|
|
57
|
+
baseTasks.set(task.id, { file, text, priority, meta: cached?.meta ?? parseFrontMatter(text, ref + ':' + file) });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const newArchives = documents.filter((doc) => doc.relative.startsWith('tasks/archive/')
|
|
62
|
+
&& changed.has(doc.relative) && parseMainName(path.basename(doc.file))
|
|
63
|
+
&& !baseTasks.get(doc.meta.id)?.file.startsWith('tasks/archive/'));
|
|
64
|
+
if (newArchives.length) {
|
|
65
|
+
const head = spawnSync('git', ['rev-parse', '--verify', '--quiet', 'HEAD'], options).stdout.trim();
|
|
66
|
+
if (head && head !== commit && spawnSync('git', ['merge-base', '--is-ancestor', commit, head], options).status === 0) {
|
|
67
|
+
for (const task of newArchives) {
|
|
68
|
+
const previous = readBeforeArchive(git, commit, head, task);
|
|
69
|
+
if (!previous) continue;
|
|
70
|
+
if (previous.close) {
|
|
71
|
+
const parentDir = path.posix.dirname(task.relative);
|
|
72
|
+
const extensionNames = Array.isArray(task.meta.extensions) ? task.meta.extensions : [];
|
|
73
|
+
const paths = [task.relative, ...extensionNames.filter((name) => typeof name === 'string' && extName.test(name))
|
|
74
|
+
.map((name) => path.posix.join(parentDir, name))];
|
|
75
|
+
const edited = files(git('diff', '--relative', '--name-only', '-z', previous.close, '--', ...paths));
|
|
76
|
+
for (const file of edited) {
|
|
77
|
+
fail(`${file}: 归档后的任务或扩展与收口提交不一致`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
baseTasks.set(task.meta.id, previous);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return { changed, baseTasks, draftFiles, activeDocuments, documentTreeRestructure: isDocumentTreeRestructure(changed) };
|
|
86
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { readTaskBaseline } from './baseline.mjs';
|
|
4
|
+
import { parseFrontMatter } from './document.mjs';
|
|
5
|
+
import { checkExtensions } from './extensions.mjs';
|
|
6
|
+
import { checkTaskIndexes } from './indexes.mjs';
|
|
7
|
+
import { readLayout } from './layout.mjs';
|
|
8
|
+
import { checkMainTasks } from './main-tasks.mjs';
|
|
9
|
+
import { checkPromotions } from './promotions.mjs';
|
|
10
|
+
import { checkTransitions } from './transitions.mjs';
|
|
11
|
+
|
|
12
|
+
export function runTaskChecks(docsRoot, base) {
|
|
13
|
+
const errors = [];
|
|
14
|
+
const fail = (message) => errors.push(message);
|
|
15
|
+
const rel = (file) => path.relative(docsRoot, file).split(path.sep).join('/');
|
|
16
|
+
const layout = readLayout(docsRoot, rel, fail);
|
|
17
|
+
const documents = new Map();
|
|
18
|
+
|
|
19
|
+
function readDocument(file) {
|
|
20
|
+
if (!documents.has(file)) {
|
|
21
|
+
const relative = rel(file);
|
|
22
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
23
|
+
let meta = {};
|
|
24
|
+
try {
|
|
25
|
+
meta = parseFrontMatter(text, relative);
|
|
26
|
+
} catch (error) {
|
|
27
|
+
fail(error.message);
|
|
28
|
+
}
|
|
29
|
+
documents.set(file, { file, relative, text, meta });
|
|
30
|
+
}
|
|
31
|
+
return documents.get(file);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const tasks = layout.allTasks.map(readDocument);
|
|
35
|
+
const extensions = layout.allExtensions.map(readDocument);
|
|
36
|
+
const baseline = readTaskBaseline(docsRoot, base, [...documents.values()], fail);
|
|
37
|
+
checkMainTasks(tasks, docsRoot, baseline, fail);
|
|
38
|
+
checkExtensions(tasks, extensions, fail);
|
|
39
|
+
checkTaskIndexes(layout, { rel, fail, readDocument });
|
|
40
|
+
if (base) {
|
|
41
|
+
checkTransitions(tasks, baseline, fail);
|
|
42
|
+
checkPromotions(docsRoot, [...tasks, ...extensions], baseline, fail);
|
|
43
|
+
}
|
|
44
|
+
for (const message of errors) console.error(`ERROR ${message}`);
|
|
45
|
+
if (errors.length) return 1;
|
|
46
|
+
console.log(`任务门禁通过:活动任务 ${layout.active.length} 个,归档任务 ${layout.archived.length} 个`);
|
|
47
|
+
return 0;
|
|
48
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { parseDocument } from 'yaml';
|
|
2
|
+
|
|
3
|
+
export const extTypes = new Set(['plan', 'decision', 'evidence', 'baseline', 'risk']);
|
|
4
|
+
export const mainName = /^task-([1-9][0-9]*)-main-([a-z0-9]+(?:-[a-z0-9]+)*)\.md$/;
|
|
5
|
+
export const extName = /^task-([1-9][0-9]*)-ext-(plan|decision|evidence|baseline|risk)-([a-z0-9]+(?:-[a-z0-9]+)*)\.md$/;
|
|
6
|
+
export const legacyName = /^task-([1-9][0-9]*)-([a-z0-9]+(?:-[a-z0-9]+)*)\.md$/;
|
|
7
|
+
|
|
8
|
+
export function parseFrontMatter(text, source = 'front matter') {
|
|
9
|
+
if (!/^---\r?\n/.test(text)) return {};
|
|
10
|
+
const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
|
|
11
|
+
if (!match) throw new Error(`${source}: YAML front matter 缺少结束分隔线 ---`);
|
|
12
|
+
const document = parseDocument(match[1], {
|
|
13
|
+
version: '1.2',
|
|
14
|
+
schema: 'core',
|
|
15
|
+
uniqueKeys: true,
|
|
16
|
+
prettyErrors: true,
|
|
17
|
+
});
|
|
18
|
+
if (document.errors.length > 0) {
|
|
19
|
+
const details = document.errors.map((error) => error.message).join(';');
|
|
20
|
+
throw new Error(`${source}: YAML front matter 无效:${details}`);
|
|
21
|
+
}
|
|
22
|
+
const value = document.toJS();
|
|
23
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
24
|
+
throw new Error(`${source}: YAML front matter 必须是映射对象`);
|
|
25
|
+
}
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function progressFromBody(body) {
|
|
30
|
+
const rows = [...body.matchAll(/^\s*- \[([ xX])\] (P-(\d+))\b/gm)];
|
|
31
|
+
if (rows.length === 0) throw new Error('正式任务至少需要一个 P-01 条目');
|
|
32
|
+
rows.forEach((match, index) => {
|
|
33
|
+
const expected = `P-${String(index + 1).padStart(2, '0')}`;
|
|
34
|
+
if (match[2] !== expected) throw new Error(`P-条目必须使用 ${expected},发现 ${match[2]}`);
|
|
35
|
+
});
|
|
36
|
+
return `${rows.filter((match) => match[1].toLowerCase() === 'x').length}/${rows.length}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function parseMainName(name) {
|
|
40
|
+
const match = name.match(mainName);
|
|
41
|
+
if (!match) return undefined;
|
|
42
|
+
return { number: match[1], id: `task-${match[1]}`, slug: match[2], stem: name.slice(0, -3) };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function parseExtName(name) {
|
|
46
|
+
const match = name.match(extName);
|
|
47
|
+
if (!match) return undefined;
|
|
48
|
+
return { number: match[1], parentTask: `task-${match[1]}`, type: match[2], slug: match[3], stem: name.slice(0, -3) };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function parseLegacyName(name) {
|
|
52
|
+
const match = name.match(legacyName);
|
|
53
|
+
if (!match || match[2] === 'main' || match[2].startsWith('main-') || match[2].startsWith('ext-')) return undefined;
|
|
54
|
+
return { number: match[1], id: `task-${match[1]}`, slug: match[2], stem: name.slice(0, -3) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const statusSet = new Set(['待开始', '进行中', '实施中', '待验收', '已阻塞', '待裁定', '已完成', '已关闭', '已合并', '已取消']);
|
|
58
|
+
export const terminalStatusSet = new Set(['已完成', '已关闭', '已合并', '已取消']);
|
|
59
|
+
export const activeStatusSet = new Set([...statusSet].filter((status) => !terminalStatusSet.has(status)));
|
|
60
|
+
export const typeSet = new Set(['模块', '跨域', '独立', '维护', '其他']);
|
|
61
|
+
export const archiveMonthName = /^\d{4}-(0[1-9]|1[0-2])$/;
|
|
62
|
+
export const documentSections = ['specification', 'implementation'];
|
|
63
|
+
|
|
64
|
+
export function isIsoDate(value) {
|
|
65
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(value ?? '')) return false;
|
|
66
|
+
const date = new Date(`${value}T00:00:00Z`);
|
|
67
|
+
if (Number.isNaN(date.getTime())) return false;
|
|
68
|
+
return date.toISOString().slice(0, 10) === value;
|
|
69
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { extName, extTypes, parseExtName, parseMainName } from './document.mjs';
|
|
4
|
+
|
|
5
|
+
export function checkExtensions(tasks, extensions, fail) {
|
|
6
|
+
const extMetadataKeys = new Set(['document-kind', 'parent-task', 'ext-type']);
|
|
7
|
+
const mainsByScope = new Map();
|
|
8
|
+
const extensionOwners = new Map();
|
|
9
|
+
const extensionsByMain = new Map();
|
|
10
|
+
for (const { file } of extensions) {
|
|
11
|
+
const name = path.basename(file);
|
|
12
|
+
const parent = parseExtName(name).parentTask;
|
|
13
|
+
const key = path.join(path.dirname(file), parent);
|
|
14
|
+
if (!extensionsByMain.has(key)) extensionsByMain.set(key, new Set());
|
|
15
|
+
extensionsByMain.get(key).add(name);
|
|
16
|
+
}
|
|
17
|
+
for (const { file, meta } of tasks) {
|
|
18
|
+
const parsed = parseMainName(path.basename(file));
|
|
19
|
+
if (parsed) mainsByScope.set(`${path.dirname(file)}:${parsed.id}`, meta);
|
|
20
|
+
}
|
|
21
|
+
for (const { file, meta, relative } of tasks) {
|
|
22
|
+
const parsed = parseMainName(path.basename(file));
|
|
23
|
+
if (!Array.isArray(meta.extensions)) {
|
|
24
|
+
fail(`${relative}: extensions 必须是扩展文件名列表;没有扩展时使用 []`);
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
const listed = new Set();
|
|
28
|
+
for (const target of meta.extensions) {
|
|
29
|
+
if (typeof target !== 'string' || !extName.test(target)) {
|
|
30
|
+
fail(`${relative}: extensions 只能登记 task-N-ext-<ext-type>-<slug>.md:${target}`);
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (listed.has(target)) fail(`${relative}: extensions 存在重复文件 ${target}`);
|
|
34
|
+
listed.add(target);
|
|
35
|
+
const targetPath = path.join(path.dirname(file), target);
|
|
36
|
+
const targetParsed = parseExtName(target);
|
|
37
|
+
if (targetParsed?.parentTask !== parsed?.id) fail(`${relative}: extensions 跨任务登记 ${target}`);
|
|
38
|
+
if (!fs.existsSync(targetPath) || !fs.statSync(targetPath).isFile()) {
|
|
39
|
+
fail(`${relative}: extensions 文件不存在 ${target}`);
|
|
40
|
+
} else {
|
|
41
|
+
const owner = extensionOwners.get(targetPath);
|
|
42
|
+
if (owner && owner !== file) fail(`${relative}: ext ${target} 已被其他主任务登记`);
|
|
43
|
+
extensionOwners.set(targetPath, file);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const actual = extensionsByMain.get(path.join(path.dirname(file), parsed.id)) ?? new Set();
|
|
47
|
+
for (const target of actual) if (!listed.has(target)) fail(`${relative}: 存在未登记的 ext ${target}`);
|
|
48
|
+
for (const target of listed) if (!actual.has(target) && fs.existsSync(path.join(path.dirname(file), target))) fail(`${relative}: extensions 登记了不属于当前任务的 ext ${target}`);
|
|
49
|
+
}
|
|
50
|
+
for (const { file, relative, meta, text: body } of extensions) {
|
|
51
|
+
const parsed = parseExtName(path.basename(file));
|
|
52
|
+
if (meta['document-kind'] !== 'ext') fail(`${relative}: document-kind 必须为 ext`);
|
|
53
|
+
for (const key of Object.keys(meta)) if (!extMetadataKeys.has(key)) fail(`${relative}: 未知 ext YAML 字段 ${key}`);
|
|
54
|
+
if (!parsed) continue;
|
|
55
|
+
if (!extTypes.has(meta['ext-type'])) fail(`${relative}: 非法 ext-type ${meta['ext-type']}`);
|
|
56
|
+
if (meta['ext-type'] !== parsed.type) fail(`${relative}: ext-type 与文件名不一致,应为 ${parsed.type}`);
|
|
57
|
+
if (meta['parent-task'] !== parsed.parentTask) fail(`${relative}: parent-task 必须为 ${parsed.parentTask}`);
|
|
58
|
+
const main = mainsByScope.get(`${path.dirname(file)}:${parsed.parentTask}`);
|
|
59
|
+
if (!main) {
|
|
60
|
+
fail(`${relative}: 找不到同一生命周期目录中的主任务 ${parsed.parentTask}`);
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (!Array.isArray(main.extensions) || !main.extensions.includes(path.basename(file))) fail(`${relative}: 未被主任务 extensions 登记`);
|
|
64
|
+
const heading = body.match(/^# (task-[^::]+)[::]/m);
|
|
65
|
+
if (!heading || heading[1] !== parsed.stem) fail(`${relative}: 首个一级标题必须包含 ${parsed.stem}`);
|
|
66
|
+
}
|
|
67
|
+
}
|