ylcwf 0.6.2 → 0.8.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/CHANGELOG.md +158 -1
- package/README.md +14 -4
- package/dist/index.js +3258 -683
- package/package.json +1 -1
- package/ui-dist/assets/{index-CQINVNzj.js → index-DPlkCr9x.js} +3 -3
- package/ui-dist/index.html +1 -1
package/dist/index.js
CHANGED
|
@@ -8,7 +8,7 @@ import node_readline from "node:readline";
|
|
|
8
8
|
import "node:tty";
|
|
9
9
|
import { homedir, tmpdir as external_node_os_tmpdir } from "node:os";
|
|
10
10
|
import { fileURLToPath } from "node:url";
|
|
11
|
-
import { randomBytes } from "node:crypto";
|
|
11
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
12
12
|
import { createServer } from "node:net";
|
|
13
13
|
import { createServer as external_node_http_createServer } from "node:http";
|
|
14
14
|
import { __webpack_require__ } from "./l.js";
|
|
@@ -8643,7 +8643,7 @@ function isActionKey(n, e) {
|
|
|
8643
8643
|
for (const s of n)if (void 0 !== s && isActionKey(s, e)) return true;
|
|
8644
8644
|
return false;
|
|
8645
8645
|
}
|
|
8646
|
-
function
|
|
8646
|
+
function dist_diffLines(i, s) {
|
|
8647
8647
|
if (i === s) return;
|
|
8648
8648
|
const e = i.split(`
|
|
8649
8649
|
`), t = s.split(`
|
|
@@ -8811,7 +8811,7 @@ let C$1 = class {
|
|
|
8811
8811
|
if (t !== this._prevFrame) {
|
|
8812
8812
|
if ("initial" === this.state) this.output.write(dist_cursor.hide);
|
|
8813
8813
|
else {
|
|
8814
|
-
const e =
|
|
8814
|
+
const e = dist_diffLines(this._prevFrame, t), i = getRows(this.output);
|
|
8815
8815
|
if (this.restoreCursor(), e) {
|
|
8816
8816
|
const s = Math.max(0, e.numLinesAfter - i), r = Math.max(0, e.numLinesBefore - i);
|
|
8817
8817
|
let n = e.lines.find((o)=>o >= s);
|
|
@@ -9439,6 +9439,7 @@ const DOCS_KEYS = new Set([
|
|
|
9439
9439
|
'validator'
|
|
9440
9440
|
]);
|
|
9441
9441
|
const VALIDATOR_KEYS = new Set([
|
|
9442
|
+
'strict',
|
|
9442
9443
|
'requireScript'
|
|
9443
9444
|
]);
|
|
9444
9445
|
const GIT_KEYS = new Set([
|
|
@@ -9454,7 +9455,7 @@ const DEFAULT_GIT_POLICY = {
|
|
|
9454
9455
|
push: false
|
|
9455
9456
|
};
|
|
9456
9457
|
const DEFAULT_VALIDATOR_POLICY = {
|
|
9457
|
-
|
|
9458
|
+
strict: true
|
|
9458
9459
|
};
|
|
9459
9460
|
const TERMINAL_KEYS = new Set([
|
|
9460
9461
|
'repos'
|
|
@@ -9474,7 +9475,7 @@ function schema_error(code, message, where) {
|
|
|
9474
9475
|
}
|
|
9475
9476
|
};
|
|
9476
9477
|
}
|
|
9477
|
-
function
|
|
9478
|
+
function schema_warning(code, message, where) {
|
|
9478
9479
|
return {
|
|
9479
9480
|
level: 'warning',
|
|
9480
9481
|
code,
|
|
@@ -9601,16 +9602,16 @@ function parseValidatorPolicy(raw, issues) {
|
|
|
9601
9602
|
return null;
|
|
9602
9603
|
}
|
|
9603
9604
|
issues.push(...unknownKeys(raw, VALIDATOR_KEYS, 'docs.validator'));
|
|
9604
|
-
const value = raw['requireScript'];
|
|
9605
|
+
const value = raw['strict'] ?? raw['requireScript'];
|
|
9605
9606
|
if (void 0 === value) return {
|
|
9606
9607
|
...DEFAULT_VALIDATOR_POLICY
|
|
9607
9608
|
};
|
|
9608
9609
|
if ('boolean' != typeof value) {
|
|
9609
|
-
issues.push(schema_error('VALIDATOR_POLICY_INVALID', 'docs.validator.
|
|
9610
|
+
issues.push(schema_error('VALIDATOR_POLICY_INVALID', 'docs.validator.strict 必须是布尔值', 'docs.validator.strict'));
|
|
9610
9611
|
return null;
|
|
9611
9612
|
}
|
|
9612
9613
|
return {
|
|
9613
|
-
|
|
9614
|
+
strict: value
|
|
9614
9615
|
};
|
|
9615
9616
|
}
|
|
9616
9617
|
function parseGitPolicy(raw, issues) {
|
|
@@ -9770,7 +9771,7 @@ function checkFsOfTerminals(config, issues) {
|
|
|
9770
9771
|
const targets = terminal.repos[side];
|
|
9771
9772
|
const where = `terminals.${name}.repos.${side}`;
|
|
9772
9773
|
if (0 === targets.length) {
|
|
9773
|
-
if ('fullstack' === config.profile.role) issues.push(
|
|
9774
|
+
if ('fullstack' === config.profile.role) issues.push(schema_warning('SIDE_NOT_CONFIGURED', `角色为 fullstack,但「${name}」未配置 ${side} 仓库`, where));
|
|
9774
9775
|
continue;
|
|
9775
9776
|
}
|
|
9776
9777
|
for (const target of targets){
|
|
@@ -9782,7 +9783,7 @@ function checkFsOfTerminals(config, issues) {
|
|
|
9782
9783
|
issues.push(schema_error('REPO_PATH_NOT_DIR', `仓库路径不是目录:${target}`, where));
|
|
9783
9784
|
continue;
|
|
9784
9785
|
}
|
|
9785
|
-
if (!external_node_fs_existsSync(external_node_path_join(target, '.git'))) issues.push(
|
|
9786
|
+
if (!external_node_fs_existsSync(external_node_path_join(target, '.git'))) issues.push(schema_warning('REPO_NOT_GIT', `路径不是 git 仓库:${target}`, where));
|
|
9786
9787
|
const entry = pathOwners.get(`${side}:${target}`) ?? {
|
|
9787
9788
|
side,
|
|
9788
9789
|
target,
|
|
@@ -9792,7 +9793,7 @@ function checkFsOfTerminals(config, issues) {
|
|
|
9792
9793
|
pathOwners.set(`${side}:${target}`, entry);
|
|
9793
9794
|
}
|
|
9794
9795
|
}
|
|
9795
|
-
for (const entry of pathOwners.values())if (!(entry.owners.length < 2)) issues.push(
|
|
9796
|
+
for (const entry of pathOwners.values())if (!(entry.owners.length < 2)) issues.push(schema_warning('REPO_PATH_SHARED', `${entry.side} 仓库路径被多个执行终端复用:${entry.target}(${entry.owners.join('、')})`, 'terminals'));
|
|
9796
9797
|
}
|
|
9797
9798
|
function checkConfig(raw, options = {}) {
|
|
9798
9799
|
const issues = [];
|
|
@@ -9819,7 +9820,7 @@ function checkConfig(raw, options = {}) {
|
|
|
9819
9820
|
docs,
|
|
9820
9821
|
terminals
|
|
9821
9822
|
};
|
|
9822
|
-
if (0 === Object.keys(terminals).length) issues.push(
|
|
9823
|
+
if (0 === Object.keys(terminals).length) issues.push(schema_warning('TERMINALS_EMPTY', "尚未配置任何执行终端映射:ylcwf resolve、任务「所属端」与仓库归属校验、doc migrate 回填都将不可用。\n 补配置:ylcwf terminal add <执行终端名> --frontend <仓库路径>\n (后端仓库用 --backend,两端都有就同时传;每端多个仓库可重复该选项)", 'terminals'));
|
|
9823
9824
|
issues.push(...checkTerminalIdentity(terminals));
|
|
9824
9825
|
if (true === options.checkFs) {
|
|
9825
9826
|
checkFsOfDocs(config, issues);
|
|
@@ -10318,7 +10319,7 @@ function renderHuman(path, config, issues) {
|
|
|
10318
10319
|
],
|
|
10319
10320
|
[
|
|
10320
10321
|
'文档校验',
|
|
10321
|
-
config.docs.validator.
|
|
10322
|
+
config.docs.validator.strict ? '严格模式:校验不通过或无法校验时拒绝写入' : '宽松:脚本不可用时仅告警'
|
|
10322
10323
|
]
|
|
10323
10324
|
]).join('\n'));
|
|
10324
10325
|
const names = Object.keys(config.terminals);
|
|
@@ -10783,59 +10784,6 @@ function aggregateRequirement(statuses) {
|
|
|
10783
10784
|
progress: roundProgressPercent(done, statuses.length)
|
|
10784
10785
|
};
|
|
10785
10786
|
}
|
|
10786
|
-
function resolveAggregates(docsRoot, lists) {
|
|
10787
|
-
const fallback = ()=>{
|
|
10788
|
-
const result = new Map();
|
|
10789
|
-
for (const [requirementId, statuses] of lists)result.set(requirementId, aggregateRequirement(statuses));
|
|
10790
|
-
return result;
|
|
10791
|
-
};
|
|
10792
|
-
if (0 === lists.size) return new Map();
|
|
10793
|
-
const remote = aggregateViaPython(docsRoot, lists);
|
|
10794
|
-
if (null !== remote) return remote;
|
|
10795
|
-
process.stderr.write("警告:未调用文档仓库 validate_task_doc.py --aggregate,需求状态与进度由本地实现计算;请确认文档仓库脚本已更新且本机具备 python3\n");
|
|
10796
|
-
return fallback();
|
|
10797
|
-
}
|
|
10798
|
-
function aggregateViaPython(docsRoot, lists) {
|
|
10799
|
-
const script = external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py');
|
|
10800
|
-
if (!external_node_fs_existsSync(script)) return null;
|
|
10801
|
-
const payload = {};
|
|
10802
|
-
for (const [requirementId, statuses] of lists)payload[requirementId] = statuses;
|
|
10803
|
-
const input = JSON.stringify(payload);
|
|
10804
|
-
for (const bin of [
|
|
10805
|
-
'python3',
|
|
10806
|
-
'python',
|
|
10807
|
-
'py'
|
|
10808
|
-
])try {
|
|
10809
|
-
const stdout = execFileSync(bin, [
|
|
10810
|
-
script,
|
|
10811
|
-
'--aggregate'
|
|
10812
|
-
], {
|
|
10813
|
-
input,
|
|
10814
|
-
encoding: 'utf8',
|
|
10815
|
-
timeout: 10000,
|
|
10816
|
-
maxBuffer: 4194304,
|
|
10817
|
-
stdio: [
|
|
10818
|
-
'pipe',
|
|
10819
|
-
'pipe',
|
|
10820
|
-
'pipe'
|
|
10821
|
-
]
|
|
10822
|
-
});
|
|
10823
|
-
const parsed = JSON.parse(stdout);
|
|
10824
|
-
if (true !== parsed.ok || void 0 === parsed.data) return null;
|
|
10825
|
-
const result = new Map();
|
|
10826
|
-
for (const [requirementId, value] of Object.entries(parsed.data)){
|
|
10827
|
-
if ('string' != typeof value.status || 'number' != typeof value.progress) return null;
|
|
10828
|
-
result.set(requirementId, {
|
|
10829
|
-
status: value.status,
|
|
10830
|
-
progress: value.progress
|
|
10831
|
-
});
|
|
10832
|
-
}
|
|
10833
|
-
return result;
|
|
10834
|
-
} catch {
|
|
10835
|
-
continue;
|
|
10836
|
-
}
|
|
10837
|
-
return null;
|
|
10838
|
-
}
|
|
10839
10787
|
const DEFAULT_ITERATIONS_ROOT = 'iterations';
|
|
10840
10788
|
const YEAR_PATTERN = /^\d{4}$/;
|
|
10841
10789
|
function currentIterationYear() {
|
|
@@ -11062,23 +11010,39 @@ const TASK_TYPE_GROUPS = [
|
|
|
11062
11010
|
'backend'
|
|
11063
11011
|
];
|
|
11064
11012
|
const SUPPORTED_SCHEMA_VERSION = 1;
|
|
11013
|
+
const MIN_VERSION_PATTERN = /^>=\s*(\d+)\.(\d+)\.(\d+)$/;
|
|
11014
|
+
function parseMinVersion(expression) {
|
|
11015
|
+
const matched = MIN_VERSION_PATTERN.exec(expression.trim());
|
|
11016
|
+
if (null === matched) return null;
|
|
11017
|
+
return [
|
|
11018
|
+
Number(matched[1]),
|
|
11019
|
+
Number(matched[2]),
|
|
11020
|
+
Number(matched[3])
|
|
11021
|
+
];
|
|
11022
|
+
}
|
|
11023
|
+
function compareVersions(a, b) {
|
|
11024
|
+
const parse = (value)=>{
|
|
11025
|
+
const matched = /^(\d+)\.(\d+)\.(\d+)/.exec(value.trim());
|
|
11026
|
+
return null === matched ? [
|
|
11027
|
+
0,
|
|
11028
|
+
0,
|
|
11029
|
+
0
|
|
11030
|
+
] : [
|
|
11031
|
+
Number(matched[1]),
|
|
11032
|
+
Number(matched[2]),
|
|
11033
|
+
Number(matched[3])
|
|
11034
|
+
];
|
|
11035
|
+
};
|
|
11036
|
+
const left = parse(a);
|
|
11037
|
+
const right = parse(b);
|
|
11038
|
+
for(let index = 0; index < 3; index += 1){
|
|
11039
|
+
const l = left[index] ?? 0;
|
|
11040
|
+
const r = right[index] ?? 0;
|
|
11041
|
+
if (l !== r) return l > r ? 1 : -1;
|
|
11042
|
+
}
|
|
11043
|
+
return 0;
|
|
11044
|
+
}
|
|
11065
11045
|
const SCOPE_SEPARATOR = '、';
|
|
11066
|
-
const PLAN_SOURCE_FIELDS = [
|
|
11067
|
-
'files',
|
|
11068
|
-
'plan',
|
|
11069
|
-
'selfTest',
|
|
11070
|
-
'testForms',
|
|
11071
|
-
'regression',
|
|
11072
|
-
'notes'
|
|
11073
|
-
];
|
|
11074
|
-
const RENDERER_BY_PLAN_FIELD = {
|
|
11075
|
-
files: 'code-change-list',
|
|
11076
|
-
selfTest: 'command-result-list',
|
|
11077
|
-
plan: 'list',
|
|
11078
|
-
testForms: 'list',
|
|
11079
|
-
regression: 'list',
|
|
11080
|
-
notes: 'inline'
|
|
11081
|
-
};
|
|
11082
11046
|
const SCHEMA_FILENAME = 'schema.json';
|
|
11083
11047
|
const REQUIRED_REQUIREMENT_KEYS = [
|
|
11084
11048
|
'id',
|
|
@@ -11141,6 +11105,12 @@ function parseDocSchema(raw, docsRoot) {
|
|
|
11141
11105
|
const version = data.schemaVersion;
|
|
11142
11106
|
if ('number' != typeof version || !Number.isInteger(version)) fail(docsRoot, 'schemaVersion 必须是整数');
|
|
11143
11107
|
if (version > SUPPORTED_SCHEMA_VERSION) fail(docsRoot, `schemaVersion ${version} 高于当前 ylcwf 支持的 ${SUPPORTED_SCHEMA_VERSION},请升级 ylcwf`);
|
|
11108
|
+
const requiresRaw = data.requiresYlcwf;
|
|
11109
|
+
let requiresYlcwf = null;
|
|
11110
|
+
if (null != requiresRaw) {
|
|
11111
|
+
if ('string' != typeof requiresRaw || null === parseMinVersion(requiresRaw)) fail(docsRoot, 'requiresYlcwf 必须是形如 ">=0.6.2" 的字符串');
|
|
11112
|
+
requiresYlcwf = requiresRaw.trim();
|
|
11113
|
+
}
|
|
11144
11114
|
const requirementTable = requireRecord(data.requirementTable, 'requirementTable', docsRoot);
|
|
11145
11115
|
const taskTable = requireRecord(data.taskTable, 'taskTable', docsRoot);
|
|
11146
11116
|
const requirementTableColumns = readColumns(requirementTable, REQUIRED_REQUIREMENT_KEYS, 'requirementTable', docsRoot);
|
|
@@ -11152,6 +11122,7 @@ function parseDocSchema(raw, docsRoot) {
|
|
|
11152
11122
|
const taskScopeEnum = derivedScopeEnum(roles, docsRoot);
|
|
11153
11123
|
return {
|
|
11154
11124
|
version,
|
|
11125
|
+
requiresYlcwf,
|
|
11155
11126
|
sections: requireStringArray(data.sections, 'sections', docsRoot),
|
|
11156
11127
|
iterationFields: readIterationFields(data.iterationFields, docsRoot).map((item)=>item.label),
|
|
11157
11128
|
iterationFieldItems: readIterationFields(data.iterationFields, docsRoot),
|
|
@@ -11337,7 +11308,6 @@ function readRoles(value, taskKeys, docsRoot) {
|
|
|
11337
11308
|
const scope = requireString(entry.scope, `${where}.scope`, docsRoot);
|
|
11338
11309
|
const detailFields = [];
|
|
11339
11310
|
const detailFieldItems = [];
|
|
11340
|
-
const mirrorFields = {};
|
|
11341
11311
|
if (void 0 !== entry.detailFields) {
|
|
11342
11312
|
if (!Array.isArray(entry.detailFields) || 0 === entry.detailFields.length) fail(docsRoot, `${where}.detailFields 必须是非空数组`);
|
|
11343
11313
|
entry.detailFields.forEach((item, index)=>{
|
|
@@ -11347,38 +11317,15 @@ function readRoles(value, taskKeys, docsRoot) {
|
|
|
11347
11317
|
if (detailFields.includes(name)) fail(docsRoot, `${where}.detailFields 内字段重复:${name}`);
|
|
11348
11318
|
detailFields.push(name);
|
|
11349
11319
|
const decl = {
|
|
11350
|
-
name
|
|
11320
|
+
name,
|
|
11321
|
+
required: void 0 === field.required ? false : true === field.required
|
|
11351
11322
|
};
|
|
11352
|
-
|
|
11353
|
-
|
|
11354
|
-
|
|
11355
|
-
|
|
11356
|
-
|
|
11357
|
-
|
|
11358
|
-
const semantic = source.slice(5);
|
|
11359
|
-
if (void 0 === taskKeys[semantic]) fail(docsRoot, `${at}.source 指向的任务列语义不存在:${semantic}`);
|
|
11360
|
-
const match = void 0 === field.match ? 'exact' : String(field.match);
|
|
11361
|
-
if ('exact' !== match && 'contains' !== match) fail(docsRoot, `${at}.match 必须是 exact / contains`);
|
|
11362
|
-
decl.source = semantic;
|
|
11363
|
-
decl.match = match;
|
|
11364
|
-
mirrorFields[name] = {
|
|
11365
|
-
source: semantic,
|
|
11366
|
-
match
|
|
11367
|
-
};
|
|
11368
|
-
}
|
|
11369
|
-
if (hasFrom) {
|
|
11370
|
-
const from = requireString(field.from, `${at}.from`, docsRoot);
|
|
11371
|
-
const planFields = PLAN_SOURCE_FIELDS;
|
|
11372
|
-
if (!planFields.includes(from)) fail(docsRoot, `${at}.from 必须是 ${planFields.join(' / ')} 之一`);
|
|
11373
|
-
const renderer = RENDERER_BY_PLAN_FIELD[from];
|
|
11374
|
-
if (void 0 !== field.as) {
|
|
11375
|
-
const declared = requireString(field.as, `${at}.as`, docsRoot);
|
|
11376
|
-
if (declared !== renderer) fail(docsRoot, `${at}.as 与 from 不匹配:from=${from} 只能是 ${renderer}`);
|
|
11377
|
-
}
|
|
11378
|
-
decl.from = from;
|
|
11379
|
-
decl.as = renderer;
|
|
11380
|
-
}
|
|
11381
|
-
if (void 0 !== field.placeholder) decl.placeholder = Array.isArray(field.placeholder) ? requireStringArray(field.placeholder, `${at}.placeholder`, docsRoot) : requireString(field.placeholder, `${at}.placeholder`, docsRoot);
|
|
11323
|
+
if (void 0 !== field.required && 'boolean' != typeof field.required) fail(docsRoot, `${at}.required 必须是布尔值`);
|
|
11324
|
+
if (void 0 !== field.placeholder) if (Array.isArray(field.placeholder)) {
|
|
11325
|
+
const items = requireStringArray(field.placeholder, `${at}.placeholder`, docsRoot);
|
|
11326
|
+
decl.placeholderItems = items;
|
|
11327
|
+
decl.placeholder = items.join(';');
|
|
11328
|
+
} else decl.placeholder = requireString(field.placeholder, `${at}.placeholder`, docsRoot);
|
|
11382
11329
|
detailFieldItems.push(decl);
|
|
11383
11330
|
});
|
|
11384
11331
|
}
|
|
@@ -11387,7 +11334,6 @@ function readRoles(value, taskKeys, docsRoot) {
|
|
|
11387
11334
|
scopeRequires: scopeRequiresOf(scope),
|
|
11388
11335
|
detailFields,
|
|
11389
11336
|
detailFieldItems,
|
|
11390
|
-
mirrorFields,
|
|
11391
11337
|
taskTypeGroups: []
|
|
11392
11338
|
};
|
|
11393
11339
|
}
|
|
@@ -11411,7 +11357,7 @@ function derivedScopeEnum(roles, docsRoot) {
|
|
|
11411
11357
|
if (0 === values.length) fail(docsRoot, '未从 roles.*.scope 派生出任何「所属端」');
|
|
11412
11358
|
return values;
|
|
11413
11359
|
}
|
|
11414
|
-
function loadDocSchema(docsRoot) {
|
|
11360
|
+
function loadDocSchema(docsRoot, options = {}) {
|
|
11415
11361
|
const target = docSchemaPath(docsRoot);
|
|
11416
11362
|
let text;
|
|
11417
11363
|
try {
|
|
@@ -11425,7 +11371,12 @@ function loadDocSchema(docsRoot) {
|
|
|
11425
11371
|
} catch (error) {
|
|
11426
11372
|
fail(docsRoot, `不是合法 JSON:${error instanceof Error ? error.message : String(error)}`);
|
|
11427
11373
|
}
|
|
11428
|
-
|
|
11374
|
+
const schema = parseDocSchema(raw, docsRoot);
|
|
11375
|
+
if (true !== options.allowTooOld && null !== schema.requiresYlcwf) {
|
|
11376
|
+
const required = parseMinVersion(schema.requiresYlcwf);
|
|
11377
|
+
if (null !== required && compareVersions("0.8.0", `${required[0]}.${required[1]}.${required[2]}`) < 0) fail(docsRoot, `文档仓库要求 ylcwf ${schema.requiresYlcwf},当前版本是 0.8.0,请先升级 ylcwf:\n npm install -g ylcwf@latest`);
|
|
11378
|
+
}
|
|
11379
|
+
return schema;
|
|
11429
11380
|
}
|
|
11430
11381
|
function taskTypesOf(schema, role) {
|
|
11431
11382
|
const config = schema.roles[role];
|
|
@@ -11446,11 +11397,6 @@ function detailFieldDeclsOfScope(schema, scope) {
|
|
|
11446
11397
|
if (null === role) return [];
|
|
11447
11398
|
return schema.roles[role]?.detailFieldItems ?? [];
|
|
11448
11399
|
}
|
|
11449
|
-
function mirrorFieldsOfScope(schema, scope) {
|
|
11450
|
-
const role = roleOfScope(schema, scope);
|
|
11451
|
-
if (null === role) return {};
|
|
11452
|
-
return schema.roles[role]?.mirrorFields ?? {};
|
|
11453
|
-
}
|
|
11454
11400
|
function sideOfTypeName(schema, typeName) {
|
|
11455
11401
|
const found = schema.taskTypeItems.find((item)=>item.name === typeName);
|
|
11456
11402
|
if (void 0 === found) return null;
|
|
@@ -11531,6 +11477,15 @@ const FILE_CHANGES = [
|
|
|
11531
11477
|
'修改',
|
|
11532
11478
|
'删除'
|
|
11533
11479
|
];
|
|
11480
|
+
const HTTP_METHODS = [
|
|
11481
|
+
'GET',
|
|
11482
|
+
'POST',
|
|
11483
|
+
'PUT',
|
|
11484
|
+
'PATCH',
|
|
11485
|
+
'DELETE',
|
|
11486
|
+
'HEAD',
|
|
11487
|
+
'OPTIONS'
|
|
11488
|
+
];
|
|
11534
11489
|
function docplan_fail(message) {
|
|
11535
11490
|
throw new errors_CliError(`plan 校验失败:${message}`, errors_EXIT.INVALID);
|
|
11536
11491
|
}
|
|
@@ -11553,9 +11508,8 @@ function optionalStringArray(value, where) {
|
|
|
11553
11508
|
}
|
|
11554
11509
|
function normalizeCode(raw) {
|
|
11555
11510
|
const trimmed = raw.trim();
|
|
11556
|
-
|
|
11557
|
-
|
|
11558
|
-
return `#${withoutHash}`;
|
|
11511
|
+
if (!/^\d{3,6}$/.test(trimmed)) docplan_fail(`需求编号格式非法:${raw}(应为纯数字,如 2755;不带 # 前缀)`);
|
|
11512
|
+
return trimmed;
|
|
11559
11513
|
}
|
|
11560
11514
|
function parseDocPlan(raw, schema, role) {
|
|
11561
11515
|
if (!docplan_isRecord(raw)) docplan_fail('顶层必须是对象');
|
|
@@ -11662,6 +11616,26 @@ function parseDocPlan(raw, schema, role) {
|
|
|
11662
11616
|
if (allowedTypes.size > 0 && !allowedTypes.has(type)) docplan_fail(`${where}.type 非法:${type}(「${scope}」端允许:${[
|
|
11663
11617
|
...allowedTypes
|
|
11664
11618
|
].join('、')})`);
|
|
11619
|
+
const apis = [];
|
|
11620
|
+
if (void 0 !== item.apis && null !== item.apis) {
|
|
11621
|
+
if (!Array.isArray(item.apis)) docplan_fail(`${where}.apis 必须是数组`);
|
|
11622
|
+
item.apis.forEach((entry, apiIndex)=>{
|
|
11623
|
+
const at = `${where}.apis[${apiIndex}]`;
|
|
11624
|
+
if (!docplan_isRecord(entry)) docplan_fail(`${at} 必须是对象 { id, method, path }`);
|
|
11625
|
+
const idRaw = entry.id;
|
|
11626
|
+
const id = 'number' == typeof idRaw ? idRaw : Number(idRaw);
|
|
11627
|
+
if (!Number.isInteger(id) || id <= 0) docplan_fail(`${at}.id 必须是正整数(YAPI 接口 ID,如 66141)`);
|
|
11628
|
+
const method = docplan_requireString(entry.method, `${at}.method`).toUpperCase();
|
|
11629
|
+
if (!HTTP_METHODS.includes(method)) docplan_fail(`${at}.method 非法:${method}(允许:${HTTP_METHODS.join('、')})`);
|
|
11630
|
+
const path = docplan_requireString(entry.path, `${at}.path`).trim();
|
|
11631
|
+
if (!path.startsWith('/') && !/^[A-Za-z0-9_.-]+(\/[A-Za-z0-9_.{}-]+)*$/.test(path)) docplan_fail(`${at}.path 非法:${path}(应形如 /api/user 或 user/detail)`);
|
|
11632
|
+
apis.push({
|
|
11633
|
+
id,
|
|
11634
|
+
method,
|
|
11635
|
+
path
|
|
11636
|
+
});
|
|
11637
|
+
});
|
|
11638
|
+
}
|
|
11665
11639
|
return {
|
|
11666
11640
|
requirement: normalizeCode(docplan_requireString(item.requirement, `${where}.requirement`)),
|
|
11667
11641
|
name: docplan_requireString(item.name, `${where}.name`),
|
|
@@ -11670,9 +11644,9 @@ function parseDocPlan(raw, schema, role) {
|
|
|
11670
11644
|
terminal: docplan_requireString(item.terminal, `${where}.terminal`),
|
|
11671
11645
|
dependsOn: optionalStringArray(item.dependsOn, `${where}.dependsOn`),
|
|
11672
11646
|
files,
|
|
11647
|
+
apis,
|
|
11673
11648
|
plan: optionalStringArray(item.plan, `${where}.plan`),
|
|
11674
11649
|
selfTest,
|
|
11675
|
-
testForms: optionalStringArray(item.testForms, `${where}.testForms`),
|
|
11676
11650
|
regression: optionalStringArray(item.regression, `${where}.regression`),
|
|
11677
11651
|
notes: optionalString(item.notes, `${where}.notes`) ?? '无',
|
|
11678
11652
|
detailFields
|
|
@@ -11692,18 +11666,140 @@ function validatePlanReferences(options) {
|
|
|
11692
11666
|
for (const task of options.plan.tasks){
|
|
11693
11667
|
if (!requirementCodes.has(task.requirement) && !knownRequirements.has(task.requirement)) docplan_fail(`任务「${task.name}」关联的需求 ${task.requirement} 既不在 requirements 中,也不在文档现有需求里`);
|
|
11694
11668
|
if (knownRepos.size > 0 && !isKnownRepo(options.index, task.terminal)) process.stderr.write(`提示:任务「${task.name}」的执行终端「${task.terminal}」不在本机执行终端配置中,跳过归属校验\n`);
|
|
11695
|
-
for (const dependency of task.dependsOn ?? []){
|
|
11696
|
-
|
|
11697
|
-
if (!options.knownTaskIds.includes(normalized)) {
|
|
11698
|
-
if (!options.plan.tasks.some((item)=>item.name === dependency)) docplan_fail(`任务「${task.name}」的前置依赖 ${dependency} 既不在文档中,也不在本次计划中`);
|
|
11699
|
-
}
|
|
11669
|
+
for (const dependency of task.dependsOn ?? [])if (!options.knownTaskIds.includes(dependency)) {
|
|
11670
|
+
if (!options.plan.tasks.some((item)=>item.name === dependency)) docplan_fail(`任务「${task.name}」的前置依赖 ${dependency} 既不在文档中,也不在本次计划中`);
|
|
11700
11671
|
}
|
|
11701
11672
|
}
|
|
11702
11673
|
}
|
|
11674
|
+
const MIRROR_BASE = [
|
|
11675
|
+
{
|
|
11676
|
+
name: '任务状态',
|
|
11677
|
+
value: {
|
|
11678
|
+
kind: 'mirror',
|
|
11679
|
+
column: 'status',
|
|
11680
|
+
match: 'exact'
|
|
11681
|
+
},
|
|
11682
|
+
renderer: 'inline'
|
|
11683
|
+
},
|
|
11684
|
+
{
|
|
11685
|
+
name: '自测状态',
|
|
11686
|
+
value: {
|
|
11687
|
+
kind: 'mirror',
|
|
11688
|
+
column: 'selfTest',
|
|
11689
|
+
match: 'exact'
|
|
11690
|
+
},
|
|
11691
|
+
renderer: 'inline'
|
|
11692
|
+
},
|
|
11693
|
+
{
|
|
11694
|
+
name: '人工验收',
|
|
11695
|
+
value: {
|
|
11696
|
+
kind: 'mirror',
|
|
11697
|
+
column: 'acceptance',
|
|
11698
|
+
match: 'exact'
|
|
11699
|
+
},
|
|
11700
|
+
renderer: 'inline'
|
|
11701
|
+
},
|
|
11702
|
+
{
|
|
11703
|
+
name: '所属需求',
|
|
11704
|
+
value: {
|
|
11705
|
+
kind: 'mirror',
|
|
11706
|
+
column: 'requirement',
|
|
11707
|
+
match: 'contains'
|
|
11708
|
+
},
|
|
11709
|
+
renderer: 'inline'
|
|
11710
|
+
},
|
|
11711
|
+
{
|
|
11712
|
+
name: '任务类型',
|
|
11713
|
+
value: {
|
|
11714
|
+
kind: 'mirror',
|
|
11715
|
+
column: 'type',
|
|
11716
|
+
match: 'exact'
|
|
11717
|
+
},
|
|
11718
|
+
renderer: 'inline'
|
|
11719
|
+
}
|
|
11720
|
+
];
|
|
11721
|
+
const CONTENT_BASE = [
|
|
11722
|
+
{
|
|
11723
|
+
name: '详细实现方案',
|
|
11724
|
+
value: {
|
|
11725
|
+
kind: 'plan',
|
|
11726
|
+
source: 'plan'
|
|
11727
|
+
},
|
|
11728
|
+
renderer: 'list'
|
|
11729
|
+
},
|
|
11730
|
+
{
|
|
11731
|
+
name: '核心文件清单',
|
|
11732
|
+
value: {
|
|
11733
|
+
kind: 'plan',
|
|
11734
|
+
source: 'files'
|
|
11735
|
+
},
|
|
11736
|
+
renderer: 'code-change-list'
|
|
11737
|
+
},
|
|
11738
|
+
{
|
|
11739
|
+
name: '自测证据',
|
|
11740
|
+
value: {
|
|
11741
|
+
kind: 'plan',
|
|
11742
|
+
source: 'selfTest'
|
|
11743
|
+
},
|
|
11744
|
+
renderer: 'command-result-list'
|
|
11745
|
+
},
|
|
11746
|
+
{
|
|
11747
|
+
name: '历史功能影响范围',
|
|
11748
|
+
value: {
|
|
11749
|
+
kind: 'plan',
|
|
11750
|
+
source: 'regression'
|
|
11751
|
+
},
|
|
11752
|
+
renderer: 'list'
|
|
11753
|
+
},
|
|
11754
|
+
{
|
|
11755
|
+
name: '遗留事项',
|
|
11756
|
+
value: {
|
|
11757
|
+
kind: 'plan',
|
|
11758
|
+
source: 'notes'
|
|
11759
|
+
},
|
|
11760
|
+
renderer: 'inline'
|
|
11761
|
+
}
|
|
11762
|
+
];
|
|
11763
|
+
const COMMON_EXTRA = [
|
|
11764
|
+
{
|
|
11765
|
+
name: '关联接口',
|
|
11766
|
+
value: {
|
|
11767
|
+
kind: 'apis'
|
|
11768
|
+
},
|
|
11769
|
+
renderer: 'api-ref-list',
|
|
11770
|
+
empty: '无'
|
|
11771
|
+
}
|
|
11772
|
+
];
|
|
11773
|
+
const TASK_FIELD_SPECS = {
|
|
11774
|
+
frontend: [
|
|
11775
|
+
...MIRROR_BASE,
|
|
11776
|
+
...CONTENT_BASE,
|
|
11777
|
+
...COMMON_EXTRA
|
|
11778
|
+
],
|
|
11779
|
+
backend: [
|
|
11780
|
+
...MIRROR_BASE,
|
|
11781
|
+
...CONTENT_BASE,
|
|
11782
|
+
...COMMON_EXTRA
|
|
11783
|
+
]
|
|
11784
|
+
};
|
|
11785
|
+
function taskFieldSpecsOfSides(side) {
|
|
11786
|
+
return TASK_FIELD_SPECS[side] ?? [];
|
|
11787
|
+
}
|
|
11788
|
+
function taskFieldSpecOf(side, name) {
|
|
11789
|
+
return taskFieldSpecsOfSides(side).find((spec)=>spec.name === name);
|
|
11790
|
+
}
|
|
11791
|
+
function mirrorColumnsOfSides(side) {
|
|
11792
|
+
const result = {};
|
|
11793
|
+
for (const spec of taskFieldSpecsOfSides(side))if ('mirror' === spec.value.kind) result[spec.name] = spec.value.column;
|
|
11794
|
+
return result;
|
|
11795
|
+
}
|
|
11796
|
+
function apiFieldsOfSides(side) {
|
|
11797
|
+
return taskFieldSpecsOfSides(side).filter((spec)=>'apis' === spec.value.kind).map((spec)=>spec.name);
|
|
11798
|
+
}
|
|
11703
11799
|
const PENDING_STATUS = '未开始';
|
|
11704
11800
|
const PENDING_SELF_TEST = '未执行';
|
|
11705
11801
|
const PENDING_ACCEPTANCE = '待验收';
|
|
11706
|
-
function
|
|
11802
|
+
function docrender_headings(schema) {
|
|
11707
11803
|
return {
|
|
11708
11804
|
info: `## ${schema.sections[0] ?? '一、迭代信息'}`,
|
|
11709
11805
|
requirement: `## ${schema.sections[1] ?? '二、需求清单'}`,
|
|
@@ -11722,9 +11818,9 @@ function docrender_separator(count) {
|
|
|
11722
11818
|
function nextSequence(existingTasks) {
|
|
11723
11819
|
const counters = new Map();
|
|
11724
11820
|
for (const task of existingTasks){
|
|
11725
|
-
const matched =
|
|
11821
|
+
const matched = /^(\d{3,6})-T(\d+)$/.exec(task.id);
|
|
11726
11822
|
if (null === matched) continue;
|
|
11727
|
-
const requirementId =
|
|
11823
|
+
const requirementId = matched[1] ?? '';
|
|
11728
11824
|
const sequence = Number(matched[2] ?? '0');
|
|
11729
11825
|
const current = counters.get(requirementId) ?? 0;
|
|
11730
11826
|
if (sequence > current) counters.set(requirementId, sequence);
|
|
@@ -11832,6 +11928,25 @@ const DETAIL_RENDERERS = {
|
|
|
11832
11928
|
list: true
|
|
11833
11929
|
};
|
|
11834
11930
|
},
|
|
11931
|
+
'api-ref-list': (value)=>{
|
|
11932
|
+
if (!Array.isArray(value)) return;
|
|
11933
|
+
if (0 === value.length) return {
|
|
11934
|
+
items: [
|
|
11935
|
+
'无'
|
|
11936
|
+
],
|
|
11937
|
+
list: false
|
|
11938
|
+
};
|
|
11939
|
+
const items = value.map((entry)=>entry).filter((entry)=>'string' == typeof entry.path && entry.path.length > 0).map((entry)=>`${String(entry.method ?? 'GET')} ${String(entry.path)}(YAPI ${String(entry.id)})`);
|
|
11940
|
+
return 0 === items.length ? {
|
|
11941
|
+
items: [
|
|
11942
|
+
'无'
|
|
11943
|
+
],
|
|
11944
|
+
list: false
|
|
11945
|
+
} : {
|
|
11946
|
+
items,
|
|
11947
|
+
list: true
|
|
11948
|
+
};
|
|
11949
|
+
},
|
|
11835
11950
|
'command-result-list': (value)=>{
|
|
11836
11951
|
if (!Array.isArray(value) || 0 === value.length) return;
|
|
11837
11952
|
const items = value.map((entry)=>entry).filter((entry)=>'string' == typeof entry.cmd && entry.cmd.length > 0).map((entry)=>`\`${String(entry.cmd)}\`:${String(entry.result ?? '')}`);
|
|
@@ -11843,54 +11958,58 @@ const DETAIL_RENDERERS = {
|
|
|
11843
11958
|
};
|
|
11844
11959
|
function renderDetail(options) {
|
|
11845
11960
|
const { taskId, task, requirement } = options;
|
|
11961
|
+
const side = roleOfScope(options.schema, task.scope);
|
|
11962
|
+
const specs = null === side ? [] : taskFieldSpecsOfSides(side);
|
|
11846
11963
|
const builtin = new Map();
|
|
11847
|
-
const mirrorInitial = (
|
|
11848
|
-
if ('status' ===
|
|
11964
|
+
const mirrorInitial = (column)=>{
|
|
11965
|
+
if ('status' === column) return {
|
|
11849
11966
|
items: [
|
|
11850
11967
|
PENDING_STATUS
|
|
11851
11968
|
],
|
|
11852
11969
|
list: false
|
|
11853
11970
|
};
|
|
11854
|
-
if ('selfTest' ===
|
|
11971
|
+
if ('selfTest' === column) return {
|
|
11855
11972
|
items: [
|
|
11856
11973
|
PENDING_SELF_TEST
|
|
11857
11974
|
],
|
|
11858
11975
|
list: false
|
|
11859
11976
|
};
|
|
11860
|
-
if ('acceptance' ===
|
|
11977
|
+
if ('acceptance' === column) return {
|
|
11861
11978
|
items: [
|
|
11862
11979
|
PENDING_ACCEPTANCE
|
|
11863
11980
|
],
|
|
11864
11981
|
list: false
|
|
11865
11982
|
};
|
|
11866
|
-
if ('requirement' ===
|
|
11983
|
+
if ('requirement' === column) return {
|
|
11867
11984
|
items: [
|
|
11868
11985
|
`${requirement.code} ${requirement.name}`
|
|
11869
11986
|
],
|
|
11870
11987
|
list: false
|
|
11871
11988
|
};
|
|
11872
|
-
if ('type' ===
|
|
11989
|
+
if ('type' === column) return {
|
|
11873
11990
|
items: [
|
|
11874
11991
|
task.type
|
|
11875
11992
|
],
|
|
11876
11993
|
list: false
|
|
11877
11994
|
};
|
|
11878
11995
|
};
|
|
11879
|
-
for (const
|
|
11880
|
-
|
|
11881
|
-
|
|
11882
|
-
|
|
11883
|
-
|
|
11884
|
-
|
|
11885
|
-
const
|
|
11886
|
-
const value =
|
|
11887
|
-
if (void 0 !== value) builtin.set(
|
|
11996
|
+
for (const spec of specs){
|
|
11997
|
+
if ('mirror' === spec.value.kind) {
|
|
11998
|
+
const value = mirrorInitial(spec.value.column);
|
|
11999
|
+
if (void 0 !== value) builtin.set(spec.name, value);
|
|
12000
|
+
continue;
|
|
12001
|
+
}
|
|
12002
|
+
const raw = 'apis' === spec.value.kind ? task.apis : task[spec.value.source];
|
|
12003
|
+
const value = DETAIL_RENDERERS[spec.renderer](raw);
|
|
12004
|
+
if (void 0 !== value) builtin.set(spec.name, value);
|
|
11888
12005
|
}
|
|
11889
12006
|
const lines = [
|
|
11890
12007
|
`### [${taskId}] ${task.name}`,
|
|
11891
12008
|
''
|
|
11892
12009
|
];
|
|
11893
|
-
for (const
|
|
12010
|
+
for (const decl of detailFieldDeclsOfScope(options.schema, task.scope)){
|
|
12011
|
+
const field = decl.name;
|
|
12012
|
+
const spec = specs.find((item)=>item.name === field);
|
|
11894
12013
|
const custom = task.detailFields?.[field];
|
|
11895
12014
|
const value = builtin.get(field) ?? (void 0 === custom ? void 0 : {
|
|
11896
12015
|
items: Array.isArray(custom) ? custom : [
|
|
@@ -11899,8 +12018,15 @@ function renderDetail(options) {
|
|
|
11899
12018
|
list: Array.isArray(custom)
|
|
11900
12019
|
});
|
|
11901
12020
|
if (void 0 === value) {
|
|
11902
|
-
const
|
|
11903
|
-
if (
|
|
12021
|
+
const empty = spec?.empty;
|
|
12022
|
+
if (void 0 !== empty) {
|
|
12023
|
+
lines.push(`- **${field}**:${empty}`);
|
|
12024
|
+
continue;
|
|
12025
|
+
}
|
|
12026
|
+
if (!decl.required) continue;
|
|
12027
|
+
const listShape = void 0 !== spec && 'inline' !== spec.renderer;
|
|
12028
|
+
if (void 0 !== empty) lines.push(`- **${field}**:${empty}`);
|
|
12029
|
+
else if (listShape) {
|
|
11904
12030
|
lines.push(`- **${field}**:`);
|
|
11905
12031
|
lines.push(' - <待补充>');
|
|
11906
12032
|
} else lines.push(`- **${field}**:<待补充>`);
|
|
@@ -11971,7 +12097,7 @@ function appendTableRows(options) {
|
|
|
11971
12097
|
}
|
|
11972
12098
|
function buildSkeleton(options) {
|
|
11973
12099
|
const { schema, role, plan, developer } = options;
|
|
11974
|
-
const head =
|
|
12100
|
+
const head = docrender_headings(schema);
|
|
11975
12101
|
const lines = [];
|
|
11976
12102
|
lines.push(`# ${developer}`, '');
|
|
11977
12103
|
lines.push(head.info, '');
|
|
@@ -12088,7 +12214,7 @@ function renderPlan(options) {
|
|
|
12088
12214
|
changes.push(`新增任务:${id} ${task.name}`);
|
|
12089
12215
|
return joinRow(cells);
|
|
12090
12216
|
});
|
|
12091
|
-
const head =
|
|
12217
|
+
const head = docrender_headings(schema);
|
|
12092
12218
|
let lines = null === existing.lines ? buildSkeleton({
|
|
12093
12219
|
schema,
|
|
12094
12220
|
role,
|
|
@@ -12485,6 +12611,494 @@ function isGitAvailable() {
|
|
|
12485
12611
|
return false;
|
|
12486
12612
|
}
|
|
12487
12613
|
}
|
|
12614
|
+
const API_REF_PATTERN = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\S+)\s*[((]\s*YAPI\s*(\d+)\s*[))]$/;
|
|
12615
|
+
const API_REF_NONE = new Set([
|
|
12616
|
+
'无',
|
|
12617
|
+
'无接口',
|
|
12618
|
+
'不涉及',
|
|
12619
|
+
'—',
|
|
12620
|
+
'-'
|
|
12621
|
+
]);
|
|
12622
|
+
const SELF_TEST_FREE_PATTERN = /^免测\s*(?:[((].+[))])?$/;
|
|
12623
|
+
const DETAIL_FIELD_PATTERN = /^\s*-\s+\*\*(.+?)\*\*\s*[::]\s*(.*)$/;
|
|
12624
|
+
function normalizeState(value) {
|
|
12625
|
+
return value.replace(/[((].*?[))]/g, '').trim();
|
|
12626
|
+
}
|
|
12627
|
+
function canonicalField(name) {
|
|
12628
|
+
return name.replace(/[((][^))]*[))]/g, '').replace(/\s+/g, '');
|
|
12629
|
+
}
|
|
12630
|
+
function cleanCell(text) {
|
|
12631
|
+
return text.replace(/\*\*/g, '').replace(/`/g, '').replace(/\s+/g, ' ').trim();
|
|
12632
|
+
}
|
|
12633
|
+
function splitTableRow(line) {
|
|
12634
|
+
let stripped = line.trim();
|
|
12635
|
+
if (stripped.startsWith('|')) stripped = stripped.slice(1);
|
|
12636
|
+
if (stripped.endsWith('|')) stripped = stripped.slice(0, -1);
|
|
12637
|
+
return stripped.split('|').map(cleanCell);
|
|
12638
|
+
}
|
|
12639
|
+
function isSeparatorRow(cells) {
|
|
12640
|
+
return cells.length > 0 && cells.every((cell)=>/^[-: ]*$/.test(cell));
|
|
12641
|
+
}
|
|
12642
|
+
function parseTables(lines) {
|
|
12643
|
+
const tables = [];
|
|
12644
|
+
let index = 0;
|
|
12645
|
+
while(index < lines.length){
|
|
12646
|
+
if (!(lines[index] ?? '').trim().startsWith('|')) {
|
|
12647
|
+
index += 1;
|
|
12648
|
+
continue;
|
|
12649
|
+
}
|
|
12650
|
+
const block = [];
|
|
12651
|
+
while(index < lines.length && (lines[index] ?? '').trim().startsWith('|')){
|
|
12652
|
+
block.push(lines[index] ?? '');
|
|
12653
|
+
index += 1;
|
|
12654
|
+
}
|
|
12655
|
+
if (block.length < 2) continue;
|
|
12656
|
+
const headers = splitTableRow(block[0] ?? '');
|
|
12657
|
+
const rows = block.slice(1).map(splitTableRow).filter((cells)=>!isSeparatorRow(cells));
|
|
12658
|
+
tables.push({
|
|
12659
|
+
headers,
|
|
12660
|
+
rows
|
|
12661
|
+
});
|
|
12662
|
+
}
|
|
12663
|
+
return tables;
|
|
12664
|
+
}
|
|
12665
|
+
function findTable(tables, required) {
|
|
12666
|
+
for (const table of tables)if (required.every((header)=>table.headers.includes(header))) return table;
|
|
12667
|
+
return null;
|
|
12668
|
+
}
|
|
12669
|
+
function toRecord(table, row) {
|
|
12670
|
+
const record = {};
|
|
12671
|
+
table.headers.forEach((header, index)=>{
|
|
12672
|
+
record[header] = row[index] ?? '';
|
|
12673
|
+
});
|
|
12674
|
+
return record;
|
|
12675
|
+
}
|
|
12676
|
+
function docvalidate_pick(record, keys, semantic) {
|
|
12677
|
+
const column = keys[semantic];
|
|
12678
|
+
return void 0 === column ? '' : record[column] ?? '';
|
|
12679
|
+
}
|
|
12680
|
+
function isValidUpdatedAt(value, format) {
|
|
12681
|
+
const tokens = [];
|
|
12682
|
+
let pattern = '^';
|
|
12683
|
+
if (format.includes('%')) for(let index = 0; index < format.length; index += 1){
|
|
12684
|
+
const char = format.charAt(index);
|
|
12685
|
+
if ('%' !== char || index + 1 >= format.length) {
|
|
12686
|
+
pattern += escapeRegExp(char);
|
|
12687
|
+
continue;
|
|
12688
|
+
}
|
|
12689
|
+
const code = format.charAt(index + 1);
|
|
12690
|
+
index += 1;
|
|
12691
|
+
if ('Y' === code || 'm' === code || 'd' === code || 'H' === code || 'M' === code || 'S' === code) {
|
|
12692
|
+
tokens.push(code);
|
|
12693
|
+
pattern += '(\\d{1,4})';
|
|
12694
|
+
} else pattern += '\\S+';
|
|
12695
|
+
}
|
|
12696
|
+
else {
|
|
12697
|
+
const literals = [
|
|
12698
|
+
[
|
|
12699
|
+
'YYYY',
|
|
12700
|
+
'Y'
|
|
12701
|
+
],
|
|
12702
|
+
[
|
|
12703
|
+
'MM',
|
|
12704
|
+
'm'
|
|
12705
|
+
],
|
|
12706
|
+
[
|
|
12707
|
+
'DD',
|
|
12708
|
+
'd'
|
|
12709
|
+
],
|
|
12710
|
+
[
|
|
12711
|
+
'HH',
|
|
12712
|
+
'H'
|
|
12713
|
+
],
|
|
12714
|
+
[
|
|
12715
|
+
'mm',
|
|
12716
|
+
'M'
|
|
12717
|
+
]
|
|
12718
|
+
];
|
|
12719
|
+
let index = 0;
|
|
12720
|
+
while(index < format.length){
|
|
12721
|
+
const rest = format.slice(index);
|
|
12722
|
+
const hit = literals.find(([literal])=>rest.startsWith(literal));
|
|
12723
|
+
if (void 0 === hit) {
|
|
12724
|
+
pattern += escapeRegExp(format.charAt(index));
|
|
12725
|
+
index += 1;
|
|
12726
|
+
continue;
|
|
12727
|
+
}
|
|
12728
|
+
tokens.push(hit[1]);
|
|
12729
|
+
pattern += 'Y' === hit[1] ? '(\\d{4})' : '(\\d{2})';
|
|
12730
|
+
index += hit[0].length;
|
|
12731
|
+
}
|
|
12732
|
+
}
|
|
12733
|
+
pattern += '$';
|
|
12734
|
+
const matched = new RegExp(pattern).exec(value);
|
|
12735
|
+
if (null === matched) return false;
|
|
12736
|
+
const parts = {};
|
|
12737
|
+
tokens.forEach((code, index)=>{
|
|
12738
|
+
parts[code] = Number.parseInt(matched[index + 1] ?? '', 10);
|
|
12739
|
+
});
|
|
12740
|
+
const year = parts['Y'];
|
|
12741
|
+
const month = parts['m'];
|
|
12742
|
+
const day = parts['d'];
|
|
12743
|
+
const hour = parts['H'];
|
|
12744
|
+
const minute = parts['M'];
|
|
12745
|
+
if (void 0 === year || void 0 === month || void 0 === day) return false;
|
|
12746
|
+
if (month < 1 || month > 12 || day < 1 || day > 31) return false;
|
|
12747
|
+
if (void 0 !== hour && hour > 23) return false;
|
|
12748
|
+
if (void 0 !== minute && minute > 59) return false;
|
|
12749
|
+
const date = new Date(year, month - 1, day);
|
|
12750
|
+
return date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
|
|
12751
|
+
}
|
|
12752
|
+
function splitDependencies(value) {
|
|
12753
|
+
if (0 === value.length || API_REF_NONE.has(value)) return [];
|
|
12754
|
+
return value.split(/[,,、\s]+/).map((item)=>item.trim()).filter((item)=>item.length > 0);
|
|
12755
|
+
}
|
|
12756
|
+
function detailHeadingPattern(schema) {
|
|
12757
|
+
const source = schema.taskIdPattern.replace(/^\^/, '').replace(/\$$/, '').replace(/\((?!\?)/g, '(?:');
|
|
12758
|
+
return new RegExp(`^###\\s+\\[(${source})\\]\\s*(.*)$`);
|
|
12759
|
+
}
|
|
12760
|
+
function parseDetailBlocks(sectionText, schema) {
|
|
12761
|
+
const heading = detailHeadingPattern(schema);
|
|
12762
|
+
const details = new Map();
|
|
12763
|
+
let currentTask = null;
|
|
12764
|
+
let currentField = null;
|
|
12765
|
+
for (const line of sectionText.split(/\r?\n/)){
|
|
12766
|
+
const matched = heading.exec(line);
|
|
12767
|
+
if (null !== matched) {
|
|
12768
|
+
currentTask = matched[1] ?? '';
|
|
12769
|
+
currentField = null;
|
|
12770
|
+
details.set(currentTask, {
|
|
12771
|
+
title: (matched[2] ?? '').trim(),
|
|
12772
|
+
fields: {}
|
|
12773
|
+
});
|
|
12774
|
+
continue;
|
|
12775
|
+
}
|
|
12776
|
+
if (line.startsWith('## ') || line.startsWith('### ')) {
|
|
12777
|
+
currentTask = null;
|
|
12778
|
+
currentField = null;
|
|
12779
|
+
continue;
|
|
12780
|
+
}
|
|
12781
|
+
if (null === currentTask) continue;
|
|
12782
|
+
const detail = details.get(currentTask);
|
|
12783
|
+
if (void 0 === detail) continue;
|
|
12784
|
+
const field = DETAIL_FIELD_PATTERN.exec(line);
|
|
12785
|
+
if (null !== field) {
|
|
12786
|
+
const name = (field[1] ?? '').trim();
|
|
12787
|
+
detail.fields[name] = (field[2] ?? '').trim();
|
|
12788
|
+
currentField = name;
|
|
12789
|
+
continue;
|
|
12790
|
+
}
|
|
12791
|
+
if (null !== currentField && /^\s{2,}\S/.test(line)) {
|
|
12792
|
+
const addition = line.trim().replace(/^[-*]\s+/, '');
|
|
12793
|
+
const existing = detail.fields[currentField] ?? '';
|
|
12794
|
+
detail.fields[currentField] = existing.length > 0 ? `${existing}\n${addition}` : addition;
|
|
12795
|
+
}
|
|
12796
|
+
}
|
|
12797
|
+
return details;
|
|
12798
|
+
}
|
|
12799
|
+
function roleOfDocument(markdown, schema) {
|
|
12800
|
+
const label = schema.iterationFieldItems.find((item)=>'scope' === item.key)?.label ?? '';
|
|
12801
|
+
if (0 === label.length) return null;
|
|
12802
|
+
const matched = new RegExp(`^[^\\S\\n]*\\|\\s*${escapeRegExp(label)}\\s*\\|\\s*([^|]*)\\|`, 'm').exec(markdown);
|
|
12803
|
+
const value = (matched?.[1] ?? '').trim();
|
|
12804
|
+
return Object.hasOwn(schema.roles, value) ? value : null;
|
|
12805
|
+
}
|
|
12806
|
+
class IssueCollector {
|
|
12807
|
+
issues = [];
|
|
12808
|
+
add(level, code, message, ref) {
|
|
12809
|
+
this.issues.push(void 0 === ref ? {
|
|
12810
|
+
level,
|
|
12811
|
+
code,
|
|
12812
|
+
message
|
|
12813
|
+
} : {
|
|
12814
|
+
level,
|
|
12815
|
+
code,
|
|
12816
|
+
message,
|
|
12817
|
+
ref
|
|
12818
|
+
});
|
|
12819
|
+
}
|
|
12820
|
+
get errors() {
|
|
12821
|
+
return this.issues.filter((issue)=>'error' === issue.level);
|
|
12822
|
+
}
|
|
12823
|
+
get warnings() {
|
|
12824
|
+
return this.issues.filter((issue)=>'warning' === issue.level);
|
|
12825
|
+
}
|
|
12826
|
+
}
|
|
12827
|
+
function validateDoc(options) {
|
|
12828
|
+
const { markdown, schema, role } = options;
|
|
12829
|
+
const collector = new IssueCollector();
|
|
12830
|
+
const requirementStatuses = new Set(schema.enums.requirementStatus);
|
|
12831
|
+
const taskStatuses = new Set(schema.enums.taskStatus);
|
|
12832
|
+
const selfTestStates = new Set(schema.enums.selfTest);
|
|
12833
|
+
const acceptanceStates = new Set(schema.enums.acceptance);
|
|
12834
|
+
const requirementIdPattern = new RegExp(schema.requirementIdPattern);
|
|
12835
|
+
const taskIdPattern = new RegExp(schema.taskIdPattern);
|
|
12836
|
+
const allowedTaskTypes = new Set(taskTypesOf(schema, role));
|
|
12837
|
+
const requiredSections = schema.sections;
|
|
12838
|
+
const infoLabel = (key)=>schema.iterationFieldItems.find((item)=>item.key === key)?.label ?? '';
|
|
12839
|
+
const sections = new Map();
|
|
12840
|
+
for (const section of requiredSections){
|
|
12841
|
+
const body = extractSection(markdown, `## ${section}`);
|
|
12842
|
+
if (0 === body.length) collector.add('error', 'SECTION_MISSING', `缺少章节:${section}`, section);
|
|
12843
|
+
sections.set(section, body);
|
|
12844
|
+
}
|
|
12845
|
+
const iterationInfo = {};
|
|
12846
|
+
const infoSection = sections.get(requiredSections[0] ?? '一、迭代信息') ?? '';
|
|
12847
|
+
const infoTable = findTable(parseTables(infoSection.split(/\r?\n/)), [
|
|
12848
|
+
'项',
|
|
12849
|
+
'内容'
|
|
12850
|
+
]);
|
|
12851
|
+
if (null === infoTable) collector.add('error', 'ITERATION_TABLE_MISSING', '第一章缺少「项 / 内容」表', '一、迭代信息');
|
|
12852
|
+
else {
|
|
12853
|
+
for (const row of infoTable.rows){
|
|
12854
|
+
const key = row[0] ?? '';
|
|
12855
|
+
if (0 !== key.length) iterationInfo[key] = row[1] ?? '';
|
|
12856
|
+
}
|
|
12857
|
+
for (const field of schema.iterationFieldItems)if (field.required && 0 === (iterationInfo[field.label] ?? '').length) collector.add('error', 'ITERATION_FIELD_MISSING', `迭代信息缺少字段或值为空:${field.label}`, field.label);
|
|
12858
|
+
const versionLabel = infoLabel('iteration');
|
|
12859
|
+
const version = versionLabel.length > 0 ? iterationInfo[versionLabel] ?? '' : '';
|
|
12860
|
+
if (versionLabel.length > 0 && version.length > 0 && version !== options.iterationName) collector.add('warning', 'ITERATION_VERSION_MISMATCH', `迭代版本「${version}」与迭代目录名「${options.iterationName}」不一致`, versionLabel);
|
|
12861
|
+
const prdLabel = infoLabel('prd');
|
|
12862
|
+
const source = prdLabel.length > 0 ? iterationInfo[prdLabel] ?? '' : '';
|
|
12863
|
+
if (prdLabel.length > 0 && source.length > 0 && !source.includes('alidocs') && !source.includes('http')) collector.add('warning', 'PRD_SOURCE_SUSPECT', `PRD 来源不像文档链接:${source}`, prdLabel);
|
|
12864
|
+
const scopeLabel = infoLabel('scope');
|
|
12865
|
+
const scopeText = scopeLabel.length > 0 ? iterationInfo[scopeLabel] ?? '' : '';
|
|
12866
|
+
if (scopeLabel.length > 0 && scopeText.length > 0 && scopeText.trim() !== role) collector.add('warning', 'ROLE_SCOPE_MISMATCH', `负责范围「${scopeText}」与校验角色「${role}」不一致(应写角色名)`, scopeLabel);
|
|
12867
|
+
}
|
|
12868
|
+
const requirements = [];
|
|
12869
|
+
const requirementSection = sections.get(requiredSections[1] ?? '二、需求清单') ?? '';
|
|
12870
|
+
const requirementTable = findTable(parseTables(requirementSection.split(/\r?\n/)), schema.requirementHeaders);
|
|
12871
|
+
if (null === requirementTable) collector.add('error', 'REQUIREMENT_TABLE_MISSING', '第二章缺少需求清单表(列名不符合模板)', '二、需求清单');
|
|
12872
|
+
else for (const row of requirementTable.rows){
|
|
12873
|
+
if (row.every((cell)=>0 === cell.length)) continue;
|
|
12874
|
+
const record = toRecord(requirementTable, row);
|
|
12875
|
+
const requirementId = docvalidate_pick(record, schema.requirementKeys, 'id');
|
|
12876
|
+
if (!requirementIdPattern.test(requirementId)) {
|
|
12877
|
+
collector.add('error', 'REQUIREMENT_ID_INVALID', `需求编号格式非法(应为纯数字,如 1234):${requirementId}`, requirementId);
|
|
12878
|
+
continue;
|
|
12879
|
+
}
|
|
12880
|
+
const updatedAt = docvalidate_pick(record, schema.requirementKeys, 'updatedAt').trim();
|
|
12881
|
+
if (!isValidUpdatedAt(updatedAt, schema.updatedAtFormat)) collector.add('error', 'UPDATED_AT_INVALID', `需求 ${requirementId} 的最后更新非法(应为合法的 ${schema.updatedAtFormat}):${updatedAt.length > 0 ? updatedAt : '空'}`, requirementId);
|
|
12882
|
+
const status = normalizeState(docvalidate_pick(record, schema.requirementKeys, 'status'));
|
|
12883
|
+
if (!requirementStatuses.has(status)) collector.add('error', 'REQUIREMENT_STATUS_INVALID', `需求 ${requirementId} 开发状态非法:${docvalidate_pick(record, schema.requirementKeys, 'status')}`, requirementId);
|
|
12884
|
+
const progressText = docvalidate_pick(record, schema.requirementKeys, 'progress').replace(/%/g, '').trim();
|
|
12885
|
+
const [progressMin, progressMax] = schema.progressRange;
|
|
12886
|
+
if (progressText.length > 0 && !/^\d+$/.test(progressText)) collector.add('error', 'REQUIREMENT_PROGRESS_INVALID', `需求 ${requirementId} 开发进度不是整数:${progressText}`, requirementId);
|
|
12887
|
+
else if (progressText.length > 0) {
|
|
12888
|
+
const progress = Number.parseInt(progressText, 10);
|
|
12889
|
+
if (progress < progressMin || progress > progressMax) collector.add('error', 'REQUIREMENT_PROGRESS_OUT_OF_RANGE', `需求 ${requirementId} 开发进度超出 ${progressMin}-${progressMax}:${progressText}`, requirementId);
|
|
12890
|
+
}
|
|
12891
|
+
requirements.push({
|
|
12892
|
+
id: requirementId,
|
|
12893
|
+
title: docvalidate_pick(record, schema.requirementKeys, 'title'),
|
|
12894
|
+
terminal: docvalidate_pick(record, schema.requirementKeys, 'terminal'),
|
|
12895
|
+
status,
|
|
12896
|
+
progress: progressText,
|
|
12897
|
+
note: docvalidate_pick(record, schema.requirementKeys, 'note'),
|
|
12898
|
+
updatedAt,
|
|
12899
|
+
taskIds: []
|
|
12900
|
+
});
|
|
12901
|
+
}
|
|
12902
|
+
const tasks = [];
|
|
12903
|
+
const taskSection = sections.get(requiredSections[2] ?? '三、任务清单') ?? '';
|
|
12904
|
+
const taskTable = findTable(parseTables(taskSection.split(/\r?\n/)), schema.taskHeaders);
|
|
12905
|
+
if (null === taskTable) collector.add('error', 'TASK_TABLE_MISSING', '第三章缺少任务清单表(列名不符合模板)', '三、任务清单');
|
|
12906
|
+
else {
|
|
12907
|
+
const requirementIds = new Set(requirements.map((item)=>item.id));
|
|
12908
|
+
const scopeEnum = schema.taskScopeEnum;
|
|
12909
|
+
for (const row of taskTable.rows){
|
|
12910
|
+
if (row.every((cell)=>0 === cell.length)) continue;
|
|
12911
|
+
const record = toRecord(taskTable, row);
|
|
12912
|
+
const taskId = docvalidate_pick(record, schema.taskKeys, 'id');
|
|
12913
|
+
if (!taskIdPattern.test(taskId)) {
|
|
12914
|
+
collector.add('error', 'TASK_ID_INVALID', `任务编号格式非法(应为 2755-T1):${taskId}`, taskId);
|
|
12915
|
+
continue;
|
|
12916
|
+
}
|
|
12917
|
+
const updatedAt = docvalidate_pick(record, schema.taskKeys, 'updatedAt').trim();
|
|
12918
|
+
if (!isValidUpdatedAt(updatedAt, schema.updatedAtFormat)) collector.add('error', 'UPDATED_AT_INVALID', `任务 ${taskId} 的最后更新非法(应为合法的 ${schema.updatedAtFormat}):${updatedAt.length > 0 ? updatedAt : '空'}`, taskId);
|
|
12919
|
+
const requirementId = docvalidate_pick(record, schema.taskKeys, 'requirement');
|
|
12920
|
+
if (requirementIdPattern.test(requirementId)) {
|
|
12921
|
+
if (!requirementIds.has(requirementId)) collector.add('error', 'TASK_REQUIREMENT_MISSING', `任务 ${taskId} 关联的需求 ${requirementId} 不在需求清单中`, taskId);
|
|
12922
|
+
} else collector.add('error', 'TASK_REQUIREMENT_ID_INVALID', `任务 ${taskId} 的关联需求编号格式非法(应为纯数字):${requirementId}`, taskId);
|
|
12923
|
+
const type = docvalidate_pick(record, schema.taskKeys, 'type');
|
|
12924
|
+
if (!allowedTaskTypes.has(type)) collector.add('error', 'TASK_TYPE_INVALID', `任务 ${taskId} 任务类型非法:${type}(允许值:${[
|
|
12925
|
+
...allowedTaskTypes
|
|
12926
|
+
].sort().join('、')})`, taskId);
|
|
12927
|
+
const scope = docvalidate_pick(record, schema.taskKeys, 'scope').trim();
|
|
12928
|
+
if (scopeEnum.includes(scope)) {
|
|
12929
|
+
const typeSide = sideOfTypeName(schema, type);
|
|
12930
|
+
const expectedScope = null === typeSide || 'both' === typeSide ? null : schema.roles[typeSide]?.scope ?? null;
|
|
12931
|
+
if (null !== expectedScope && scope !== expectedScope) collector.add('error', 'TASK_SCOPE_TYPE_MISMATCH', `任务 ${taskId} 类型「${type}」属于${expectedScope},但所属端填的是「${scope}」`, taskId);
|
|
12932
|
+
} else collector.add('error', 'TASK_SCOPE_INVALID', `任务 ${taskId} 所属端非法:${scope.length > 0 ? scope : '空'}(允许值:${scopeEnum.join('、')})`, taskId);
|
|
12933
|
+
const selfTest = docvalidate_pick(record, schema.taskKeys, 'selfTest');
|
|
12934
|
+
if (!selfTestStates.has(selfTest) && !SELF_TEST_FREE_PATTERN.test(selfTest)) collector.add('error', 'SELF_TEST_INVALID', `任务 ${taskId} AI 自测状态非法:${selfTest}`, taskId);
|
|
12935
|
+
const acceptance = normalizeState(docvalidate_pick(record, schema.taskKeys, 'acceptance'));
|
|
12936
|
+
if (!acceptanceStates.has(acceptance)) collector.add('error', 'ACCEPTANCE_INVALID', `任务 ${taskId} 开发人工验收非法:${docvalidate_pick(record, schema.taskKeys, 'acceptance')}`, taskId);
|
|
12937
|
+
const status = normalizeState(docvalidate_pick(record, schema.taskKeys, 'status'));
|
|
12938
|
+
if (!taskStatuses.has(status)) collector.add('error', 'TASK_STATUS_INVALID', `任务 ${taskId} 任务状态非法:${docvalidate_pick(record, schema.taskKeys, 'status')}`, taskId);
|
|
12939
|
+
if ('已完成' === status && '验收通过' !== acceptance) collector.add('error', 'ACCEPTANCE_GATE_VIOLATION', `任务 ${taskId} 状态为已完成,但开发人工验收为「${acceptance}」,必须先通过人工验收`, taskId);
|
|
12940
|
+
const selfTestPassed = '通过' === selfTest || SELF_TEST_FREE_PATTERN.test(selfTest);
|
|
12941
|
+
if (('待验收' === status || '已完成' === status) && !selfTestPassed) collector.add('error', 'SELF_TEST_GATE_VIOLATION', `任务 ${taskId} 状态为${status},但 AI 自测状态为「${selfTest}」,必须先完成自测`, taskId);
|
|
12942
|
+
if ('未开始' === status && '未执行' !== selfTest) collector.add('error', 'UNSTARTED_WITH_SELFTEST', `任务 ${taskId} 状态为未开始,但 AI 自测状态为「${selfTest}」`, taskId);
|
|
12943
|
+
tasks.push({
|
|
12944
|
+
id: taskId,
|
|
12945
|
+
requirementId,
|
|
12946
|
+
name: docvalidate_pick(record, schema.taskKeys, 'name'),
|
|
12947
|
+
type,
|
|
12948
|
+
scope,
|
|
12949
|
+
terminal: docvalidate_pick(record, schema.taskKeys, 'terminal'),
|
|
12950
|
+
dependencies: splitDependencies(docvalidate_pick(record, schema.taskKeys, 'dependencies')),
|
|
12951
|
+
selfTest,
|
|
12952
|
+
acceptance,
|
|
12953
|
+
status,
|
|
12954
|
+
updatedAt
|
|
12955
|
+
});
|
|
12956
|
+
}
|
|
12957
|
+
const allowedScopes = schema.roles[role]?.scopeRequires ?? [];
|
|
12958
|
+
const usedScopes = [
|
|
12959
|
+
...new Set(tasks.map((task)=>task.scope).filter((scope)=>scope.length > 0))
|
|
12960
|
+
].sort();
|
|
12961
|
+
for (const scope of usedScopes)if (!allowedScopes.includes(scope)) collector.add('error', 'DOCUMENT_SCOPE_MISMATCH', `任务清单中出现「${scope}」任务,但当前角色「${role}」只负责:${allowedScopes.join('、') || '(无)'}`);
|
|
12962
|
+
const requirementsById = new Map(requirements.map((item)=>[
|
|
12963
|
+
item.id,
|
|
12964
|
+
item
|
|
12965
|
+
]));
|
|
12966
|
+
for (const task of tasks){
|
|
12967
|
+
const requirement = requirementsById.get(task.requirementId);
|
|
12968
|
+
if (void 0 !== requirement) {
|
|
12969
|
+
requirement.taskIds.push(task.id);
|
|
12970
|
+
if (task.terminal.length > 0 && requirement.terminal.length > 0 && task.terminal !== requirement.terminal) collector.add('warning', 'TASK_TERMINAL_MISMATCH', `任务 ${task.id} 执行终端「${task.terminal}」与需求执行终端「${requirement.terminal}」不一致`, task.id);
|
|
12971
|
+
}
|
|
12972
|
+
}
|
|
12973
|
+
}
|
|
12974
|
+
const detailSection = sections.get(requiredSections[3] ?? '四、任务详情') ?? '';
|
|
12975
|
+
const details = parseDetailBlocks(detailSection, schema);
|
|
12976
|
+
const detailIds = new Set(details.keys());
|
|
12977
|
+
const taskIds = new Set(tasks.map((task)=>task.id));
|
|
12978
|
+
for (const taskId of [
|
|
12979
|
+
...taskIds
|
|
12980
|
+
].filter((id)=>!detailIds.has(id)).sort())collector.add('error', 'DETAIL_MISSING', `任务 ${taskId} 缺少第四章详情区块`, taskId);
|
|
12981
|
+
for (const taskId of [
|
|
12982
|
+
...detailIds
|
|
12983
|
+
].filter((id)=>!taskIds.has(id)).sort())collector.add('error', 'DETAIL_ORPHAN', `详情区块 ${taskId} 在任务清单中不存在`, taskId);
|
|
12984
|
+
const tasksById = new Map(tasks.map((task)=>[
|
|
12985
|
+
task.id,
|
|
12986
|
+
task
|
|
12987
|
+
]));
|
|
12988
|
+
for (const [taskId, detail] of details){
|
|
12989
|
+
const task = tasksById.get(taskId);
|
|
12990
|
+
if (void 0 === task) continue;
|
|
12991
|
+
const scopeRole = roleOfScope(schema, task.scope);
|
|
12992
|
+
const declared = detailFieldsOfScope(schema, task.scope);
|
|
12993
|
+
const declaredCanonical = new Set(declared.map(canonicalField));
|
|
12994
|
+
const canonical = new Map();
|
|
12995
|
+
for (const [name, value] of Object.entries(detail.fields))canonical.set(canonicalField(name), value);
|
|
12996
|
+
for (const name of Object.keys(detail.fields))if (!declaredCanonical.has(canonicalField(name))) collector.add('error', 'DETAIL_FIELD_UNKNOWN', `任务 ${taskId} 详情字段「${name}」不在 schema 的 detailFields 白名单内(该端允许:${declared.join('、')})`, taskId);
|
|
12997
|
+
for (const field of detailFieldDeclsOfScope(schema, task.scope)){
|
|
12998
|
+
if (!field.required) continue;
|
|
12999
|
+
const value = canonical.get(canonicalField(field.name)) ?? '';
|
|
13000
|
+
if (0 === value.trim().length) collector.add('error', 'DETAIL_FIELD_MISSING', `任务 ${taskId} 详情缺少字段或值为空:${field.name}`, taskId);
|
|
13001
|
+
}
|
|
13002
|
+
if (null === scopeRole) continue;
|
|
13003
|
+
for (const apiField of apiFieldsOfSides(scopeRole)){
|
|
13004
|
+
if (!declared.includes(apiField)) continue;
|
|
13005
|
+
const raw = canonical.get(canonicalField(apiField)) ?? '';
|
|
13006
|
+
if (!(0 === raw.trim().length || API_REF_NONE.has(raw.trim()))) {
|
|
13007
|
+
for (const line of raw.split(/\r?\n/).map((item)=>item.trim()).filter((item)=>item.length > 0))if (!API_REF_NONE.has(line)) {
|
|
13008
|
+
if (!API_REF_PATTERN.test(line)) collector.add('error', 'API_REF_INVALID', `任务 ${taskId} 的「${apiField}」格式非法:${line}(应为 \`METHOD 路径(YAPI id)\`,如 \`GET /api/user(YAPI 66141)\`;无接口请写「无」)`, taskId);
|
|
13009
|
+
}
|
|
13010
|
+
}
|
|
13011
|
+
}
|
|
13012
|
+
const attributes = {
|
|
13013
|
+
id: task.id,
|
|
13014
|
+
requirement: task.requirementId,
|
|
13015
|
+
name: task.name,
|
|
13016
|
+
type: task.type,
|
|
13017
|
+
scope: task.scope,
|
|
13018
|
+
terminal: task.terminal,
|
|
13019
|
+
dependencies: task.dependencies.join('、'),
|
|
13020
|
+
selfTest: task.selfTest,
|
|
13021
|
+
acceptance: task.acceptance,
|
|
13022
|
+
status: task.status,
|
|
13023
|
+
updatedAt: task.updatedAt
|
|
13024
|
+
};
|
|
13025
|
+
for (const fieldName of declared){
|
|
13026
|
+
const spec = taskFieldSpecOf(scopeRole, fieldName);
|
|
13027
|
+
if (void 0 === spec || 'mirror' !== spec.value.kind) continue;
|
|
13028
|
+
const column = spec.value.column;
|
|
13029
|
+
const actual = canonical.get(canonicalField(fieldName)) ?? '';
|
|
13030
|
+
if (0 === actual.length) continue;
|
|
13031
|
+
const expected = attributes[column] ?? '';
|
|
13032
|
+
if (0 === expected.length) continue;
|
|
13033
|
+
const matched = 'contains' === spec.value.match ? expected.includes(actual) || actual.includes(expected) : normalizeState(actual) === normalizeState(expected);
|
|
13034
|
+
if (!matched) collector.add('error', 'DETAIL_STATE_MISMATCH', `任务 ${taskId} 详情「${fieldName}」为「${actual}」,与任务清单「${schema.taskKeys[column] ?? column}」列「${expected}」不一致`, taskId);
|
|
13035
|
+
}
|
|
13036
|
+
}
|
|
13037
|
+
for (const requirement of requirements){
|
|
13038
|
+
const related = tasks.filter((task)=>task.requirementId === requirement.id);
|
|
13039
|
+
if (0 === related.length) {
|
|
13040
|
+
if ('未开始' !== requirement.status) collector.add('error', 'REQUIREMENT_STATUS_MISMATCH', `需求 ${requirement.id} 没有任务,开发状态只能是未开始,当前为「${requirement.status}」`, requirement.id);
|
|
13041
|
+
if ('' !== requirement.progress && '0' !== requirement.progress) collector.add('error', 'REQUIREMENT_PROGRESS_MISMATCH', `需求 ${requirement.id} 没有任务,开发进度只能为 0,当前为「${requirement.progress}」`, requirement.id);
|
|
13042
|
+
continue;
|
|
13043
|
+
}
|
|
13044
|
+
const aggregate = aggregateRequirement(related.map((task)=>task.status));
|
|
13045
|
+
if (requirement.status !== aggregate.status) collector.add('error', 'REQUIREMENT_STATUS_MISMATCH', `需求 ${requirement.id} 开发状态「${requirement.status}」与任务聚合结果「${aggregate.status}」不一致`, requirement.id);
|
|
13046
|
+
if (requirement.progress !== String(aggregate.progress)) collector.add('error', 'REQUIREMENT_PROGRESS_MISMATCH', `需求 ${requirement.id} 开发进度「${requirement.progress}%」应为「${aggregate.progress}%」`, requirement.id);
|
|
13047
|
+
}
|
|
13048
|
+
const tasksById2 = new Map(tasks.map((task)=>[
|
|
13049
|
+
task.id,
|
|
13050
|
+
task
|
|
13051
|
+
]));
|
|
13052
|
+
for (const task of tasks)for (const dependency of task.dependencies)if (taskIdPattern.test(dependency)) if (tasksById2.has(dependency)) {
|
|
13053
|
+
if (dependency === task.id) collector.add('error', 'DEPENDENCY_SELF', `任务 ${task.id} 依赖自身`, task.id);
|
|
13054
|
+
} else collector.add('error', 'DEPENDENCY_MISSING', `任务 ${task.id} 的前置依赖 ${dependency} 不在任务清单中`, task.id);
|
|
13055
|
+
else collector.add('error', 'DEPENDENCY_ID_INVALID', `任务 ${task.id} 的前置依赖编号格式非法:${dependency}`, task.id);
|
|
13056
|
+
const cycle = findCycle(tasksById2, tasks);
|
|
13057
|
+
if (cycle.length > 0) collector.add('error', 'DEPENDENCY_CYCLE', `前置依赖存在环:${cycle.join(' → ')}`, cycle[0] ?? '');
|
|
13058
|
+
const errors = collector.errors;
|
|
13059
|
+
return {
|
|
13060
|
+
valid: 0 === errors.length,
|
|
13061
|
+
role,
|
|
13062
|
+
iterationInfo,
|
|
13063
|
+
stats: {
|
|
13064
|
+
requirements: requirements.length,
|
|
13065
|
+
tasks: tasks.length,
|
|
13066
|
+
completedTasks: tasks.filter((task)=>'已完成' === task.status).length,
|
|
13067
|
+
details: details.size
|
|
13068
|
+
},
|
|
13069
|
+
requirements,
|
|
13070
|
+
tasks,
|
|
13071
|
+
errors,
|
|
13072
|
+
warnings: collector.warnings
|
|
13073
|
+
};
|
|
13074
|
+
}
|
|
13075
|
+
function findCycle(byId, order) {
|
|
13076
|
+
const visiting = [];
|
|
13077
|
+
const visited = new Set();
|
|
13078
|
+
const visit = (taskId)=>{
|
|
13079
|
+
const at = visiting.indexOf(taskId);
|
|
13080
|
+
if (at >= 0) return [
|
|
13081
|
+
...visiting.slice(at),
|
|
13082
|
+
taskId
|
|
13083
|
+
];
|
|
13084
|
+
if (visited.has(taskId)) return [];
|
|
13085
|
+
visiting.push(taskId);
|
|
13086
|
+
const task = byId.get(taskId);
|
|
13087
|
+
for (const dependency of task?.dependencies ?? []){
|
|
13088
|
+
if (!byId.has(dependency)) continue;
|
|
13089
|
+
const found = visit(dependency);
|
|
13090
|
+
if (found.length > 0) return found;
|
|
13091
|
+
}
|
|
13092
|
+
visiting.pop();
|
|
13093
|
+
visited.add(taskId);
|
|
13094
|
+
return [];
|
|
13095
|
+
};
|
|
13096
|
+
for (const task of order){
|
|
13097
|
+
const found = visit(task.id);
|
|
13098
|
+
if (found.length > 0) return found;
|
|
13099
|
+
}
|
|
13100
|
+
return [];
|
|
13101
|
+
}
|
|
12488
13102
|
function docViewMeta(schema) {
|
|
12489
13103
|
return {
|
|
12490
13104
|
requirementColumns: schema.requirementColumns,
|
|
@@ -12538,15 +13152,20 @@ function joinWithin(root, ...segments) {
|
|
|
12538
13152
|
if (!target.startsWith(base)) throw new errors_CliError(`路径越界:${target}`, errors_EXIT.USAGE);
|
|
12539
13153
|
return target;
|
|
12540
13154
|
}
|
|
13155
|
+
const DOC_ROLES = [
|
|
13156
|
+
"frontend",
|
|
13157
|
+
"backend",
|
|
13158
|
+
"fullstack"
|
|
13159
|
+
];
|
|
13160
|
+
const DOC_ROLE_HINT = DOC_ROLES.join(" / ");
|
|
12541
13161
|
function inferRole(markdown) {
|
|
12542
|
-
const match =
|
|
12543
|
-
const
|
|
12544
|
-
|
|
12545
|
-
|
|
12546
|
-
|
|
12547
|
-
|
|
12548
|
-
|
|
12549
|
-
return "frontend";
|
|
13162
|
+
const match = /^[^\S\n]*\|\s*负责范围\s*\|\s*([^|]*)\|/m.exec(markdown);
|
|
13163
|
+
const value = (match?.[1] ?? "").trim().toLowerCase();
|
|
13164
|
+
return DOC_ROLES.includes(value) ? value : null;
|
|
13165
|
+
}
|
|
13166
|
+
function readRoleText(markdown) {
|
|
13167
|
+
const match = /^[^\S\n]*\|\s*负责范围\s*\|\s*([^|]*)\|/m.exec(markdown);
|
|
13168
|
+
return (match?.[1] ?? "").trim();
|
|
12550
13169
|
}
|
|
12551
13170
|
function listMarkdownFiles(directory) {
|
|
12552
13171
|
let entries;
|
|
@@ -12644,174 +13263,12 @@ function buildIterationList(layout, source, base, refName) {
|
|
|
12644
13263
|
iterations: entries
|
|
12645
13264
|
};
|
|
12646
13265
|
}
|
|
12647
|
-
function
|
|
12648
|
-
|
|
12649
|
-
|
|
12650
|
-
|
|
12651
|
-
|
|
12652
|
-
|
|
12653
|
-
return void 0 === ref ? {
|
|
12654
|
-
level,
|
|
12655
|
-
code,
|
|
12656
|
-
message
|
|
12657
|
-
} : {
|
|
12658
|
-
level,
|
|
12659
|
-
code,
|
|
12660
|
-
message,
|
|
12661
|
-
ref
|
|
12662
|
-
};
|
|
12663
|
-
}
|
|
12664
|
-
function coerceRequirement(value) {
|
|
12665
|
-
if (!utils_isRecord(value)) return null;
|
|
12666
|
-
const id = "string" == typeof value["id"] ? value["id"] : "";
|
|
12667
|
-
if (0 === id.length) return null;
|
|
12668
|
-
return {
|
|
12669
|
-
id,
|
|
12670
|
-
title: "string" == typeof value["title"] ? value["title"] : "",
|
|
12671
|
-
terminal: "string" == typeof value["terminal"] ? value["terminal"] : "",
|
|
12672
|
-
status: "string" == typeof value["status"] ? value["status"] : "",
|
|
12673
|
-
progress: String(value["progress"] ?? ""),
|
|
12674
|
-
note: "string" == typeof value["note"] ? value["note"] : "",
|
|
12675
|
-
updatedAt: "string" == typeof value["updatedAt"] ? value["updatedAt"] : "",
|
|
12676
|
-
taskIds: isStringArray(value["taskIds"]) ? value["taskIds"] : []
|
|
12677
|
-
};
|
|
12678
|
-
}
|
|
12679
|
-
function coerceTask(value) {
|
|
12680
|
-
if (!utils_isRecord(value)) return null;
|
|
12681
|
-
const id = "string" == typeof value["id"] ? value["id"] : "";
|
|
12682
|
-
if (0 === id.length) return null;
|
|
12683
|
-
return {
|
|
12684
|
-
id,
|
|
12685
|
-
requirementId: "string" == typeof value["requirementId"] ? value["requirementId"] : "",
|
|
12686
|
-
name: "string" == typeof value["name"] ? value["name"] : "",
|
|
12687
|
-
type: "string" == typeof value["type"] ? value["type"] : "",
|
|
12688
|
-
scope: "string" == typeof value["scope"] ? value["scope"] : "",
|
|
12689
|
-
terminal: "string" == typeof value["terminal"] ? value["terminal"] : "",
|
|
12690
|
-
dependencies: isStringArray(value["dependencies"]) ? value["dependencies"] : [],
|
|
12691
|
-
selfTest: "string" == typeof value["selfTest"] ? value["selfTest"] : "",
|
|
12692
|
-
acceptance: "string" == typeof value["acceptance"] ? value["acceptance"] : "",
|
|
12693
|
-
status: "string" == typeof value["status"] ? value["status"] : "",
|
|
12694
|
-
updatedAt: "string" == typeof value["updatedAt"] ? value["updatedAt"] : ""
|
|
12695
|
-
};
|
|
12696
|
-
}
|
|
12697
|
-
function coerceInfo(value) {
|
|
12698
|
-
if (!utils_isRecord(value)) return {};
|
|
12699
|
-
const info = {};
|
|
12700
|
-
for (const [key, item] of Object.entries(value))if ("string" == typeof item) info[key] = item;
|
|
12701
|
-
return info;
|
|
12702
|
-
}
|
|
12703
|
-
function coercePayload(raw, schema) {
|
|
12704
|
-
if (!utils_isRecord(raw)) return null;
|
|
12705
|
-
const stats = utils_isRecord(raw["stats"]) ? raw["stats"] : {};
|
|
12706
|
-
const requirements = Array.isArray(raw["requirements"]) ? raw["requirements"].map(coerceRequirement).filter((item)=>null !== item) : [];
|
|
12707
|
-
const tasks = Array.isArray(raw["tasks"]) ? raw["tasks"].map(coerceTask).filter((item)=>null !== item) : [];
|
|
12708
|
-
const errors = Array.isArray(raw["errors"]) ? raw["errors"].map(coerceIssue).filter((item)=>null !== item) : [];
|
|
12709
|
-
const warnings = Array.isArray(raw["warnings"]) ? raw["warnings"].map(coerceIssue).filter((item)=>null !== item) : [];
|
|
12710
|
-
const asNumber = (value, fallback)=>"number" == typeof value ? value : fallback;
|
|
12711
|
-
return {
|
|
12712
|
-
valid: true === raw["valid"],
|
|
12713
|
-
view: docViewMeta(schema),
|
|
12714
|
-
iterationInfo: coerceInfo(raw["iterationInfo"]),
|
|
12715
|
-
stats: {
|
|
12716
|
-
requirements: asNumber(stats["requirements"], requirements.length),
|
|
12717
|
-
tasks: asNumber(stats["tasks"], tasks.length),
|
|
12718
|
-
completedTasks: asNumber(stats["completedTasks"], tasks.filter((task)=>"已完成" === task.status).length),
|
|
12719
|
-
details: asNumber(stats["details"], 0)
|
|
12720
|
-
},
|
|
12721
|
-
requirements,
|
|
12722
|
-
tasks,
|
|
12723
|
-
errors,
|
|
12724
|
-
warnings
|
|
12725
|
-
};
|
|
12726
|
-
}
|
|
12727
|
-
const validatorFailureCache = new Map();
|
|
12728
|
-
const warnedValidatorFailures = new Set();
|
|
12729
|
-
function warnValidatorFailureOnce(key, reason) {
|
|
12730
|
-
if (warnedValidatorFailures.has(key)) return;
|
|
12731
|
-
warnedValidatorFailures.add(key);
|
|
12732
|
-
process.stderr.write(`警告:文档校验器未运行(${reason}),已改用降级解析\n`);
|
|
12733
|
-
}
|
|
12734
|
-
function runValidator(input) {
|
|
12735
|
-
const script = input.scriptPath;
|
|
12736
|
-
if (null === script || !external_node_fs_existsSync(script)) {
|
|
12737
|
-
const missing = "文档仓库缺少 scripts/validate_task_doc.py";
|
|
12738
|
-
warnValidatorFailureOnce(`missing|${input.docsRoot}`, missing);
|
|
12739
|
-
return {
|
|
12740
|
-
payload: null,
|
|
12741
|
-
error: missing
|
|
12742
|
-
};
|
|
12743
|
-
}
|
|
12744
|
-
const cacheKey = `${script}|${input.docsRoot}|${input.iteration}|${input.developer}|${input.role}`;
|
|
12745
|
-
const cachedFailure = validatorFailureCache.get(cacheKey);
|
|
12746
|
-
if (void 0 !== cachedFailure) return {
|
|
12747
|
-
payload: null,
|
|
12748
|
-
error: cachedFailure
|
|
12749
|
-
};
|
|
12750
|
-
const args = [
|
|
12751
|
-
script,
|
|
12752
|
-
"--docs-root",
|
|
12753
|
-
input.docsRoot,
|
|
12754
|
-
"--iteration",
|
|
12755
|
-
input.iteration,
|
|
12756
|
-
"--developer",
|
|
12757
|
-
input.developer,
|
|
12758
|
-
"--role",
|
|
12759
|
-
input.role,
|
|
12760
|
-
"--format",
|
|
12761
|
-
"json"
|
|
12762
|
-
];
|
|
12763
|
-
let lastError = null;
|
|
12764
|
-
let interpreterMissing = true;
|
|
12765
|
-
for (const bin of [
|
|
12766
|
-
"python3",
|
|
12767
|
-
"python",
|
|
12768
|
-
"py"
|
|
12769
|
-
])try {
|
|
12770
|
-
const stdout = execFileSync(bin, args, {
|
|
12771
|
-
encoding: "utf8",
|
|
12772
|
-
timeout: 10000,
|
|
12773
|
-
maxBuffer: 16777216,
|
|
12774
|
-
stdio: [
|
|
12775
|
-
"ignore",
|
|
12776
|
-
"pipe",
|
|
12777
|
-
"pipe"
|
|
12778
|
-
]
|
|
12779
|
-
});
|
|
12780
|
-
const parsed = coercePayload(JSON.parse(stdout), input.schema);
|
|
12781
|
-
if (null !== parsed) return {
|
|
12782
|
-
payload: parsed,
|
|
12783
|
-
error: null
|
|
12784
|
-
};
|
|
12785
|
-
} catch (error) {
|
|
12786
|
-
const failure = error;
|
|
12787
|
-
const stdout = failure.stdout;
|
|
12788
|
-
if ("string" == typeof stdout && stdout.trim().length > 0) try {
|
|
12789
|
-
const parsed = coercePayload(JSON.parse(stdout), input.schema);
|
|
12790
|
-
if (null !== parsed) return {
|
|
12791
|
-
payload: parsed,
|
|
12792
|
-
error: null
|
|
12793
|
-
};
|
|
12794
|
-
} catch {}
|
|
12795
|
-
if ("ENOENT" === failure.code || 127 === failure.code) continue;
|
|
12796
|
-
interpreterMissing = false;
|
|
12797
|
-
const stderr = "string" == typeof failure.stderr ? failure.stderr.trim().split("\n") : [];
|
|
12798
|
-
lastError = stderr.length > 0 ? (stderr[stderr.length - 1] ?? "").slice(0, 200) : "校验器执行失败";
|
|
12799
|
-
}
|
|
12800
|
-
const reason = interpreterMissing ? "未找到 python 解释器(需 python3 / python / py)" : lastError;
|
|
12801
|
-
const failure = reason ?? "校验器执行失败";
|
|
12802
|
-
validatorFailureCache.set(cacheKey, failure);
|
|
12803
|
-
warnValidatorFailureOnce(failure, failure);
|
|
12804
|
-
return {
|
|
12805
|
-
payload: null,
|
|
12806
|
-
error: failure
|
|
12807
|
-
};
|
|
12808
|
-
}
|
|
12809
|
-
function extractSection(markdown, heading) {
|
|
12810
|
-
const lines = markdown.split(/\r?\n/);
|
|
12811
|
-
let start = -1;
|
|
12812
|
-
for(let index = 0; index < lines.length; index += 1)if ((lines[index] ?? "").trim() === heading) {
|
|
12813
|
-
start = index + 1;
|
|
12814
|
-
break;
|
|
13266
|
+
function extractSection(markdown, heading) {
|
|
13267
|
+
const lines = markdown.split(/\r?\n/);
|
|
13268
|
+
let start = -1;
|
|
13269
|
+
for(let index = 0; index < lines.length; index += 1)if ((lines[index] ?? "").trim() === heading) {
|
|
13270
|
+
start = index + 1;
|
|
13271
|
+
break;
|
|
12815
13272
|
}
|
|
12816
13273
|
if (start < 0) return "";
|
|
12817
13274
|
const collected = [];
|
|
@@ -12959,6 +13416,31 @@ function resolveIterationForRead(layout, iteration, source, presetRef, refName)
|
|
|
12959
13416
|
}
|
|
12960
13417
|
return resolveIterationDir(layout.root, layout.iterationsRoot, safeIteration);
|
|
12961
13418
|
}
|
|
13419
|
+
function validateLocally(options) {
|
|
13420
|
+
if (null === options.role) return {
|
|
13421
|
+
payload: parseMarkdownDoc(options.markdown, options.schema),
|
|
13422
|
+
error: `文档「负责范围」缺失或不是 ${DOC_ROLE_HINT},已跳过规则校验`
|
|
13423
|
+
};
|
|
13424
|
+
const result = validateDoc({
|
|
13425
|
+
markdown: options.markdown,
|
|
13426
|
+
schema: options.schema,
|
|
13427
|
+
role: options.role,
|
|
13428
|
+
iterationName: options.iterationName
|
|
13429
|
+
});
|
|
13430
|
+
return {
|
|
13431
|
+
payload: {
|
|
13432
|
+
valid: result.valid,
|
|
13433
|
+
view: docViewMeta(options.schema),
|
|
13434
|
+
iterationInfo: result.iterationInfo,
|
|
13435
|
+
stats: result.stats,
|
|
13436
|
+
requirements: result.requirements,
|
|
13437
|
+
tasks: result.tasks,
|
|
13438
|
+
errors: result.errors,
|
|
13439
|
+
warnings: result.warnings
|
|
13440
|
+
},
|
|
13441
|
+
error: null
|
|
13442
|
+
};
|
|
13443
|
+
}
|
|
12962
13444
|
function readIterationDoc(layout, iteration, developer, source = "local", presetRef, refName) {
|
|
12963
13445
|
const docsRoot = layout.root;
|
|
12964
13446
|
const safeDeveloper = iterations_safeSegment(developer, "开发者标识");
|
|
@@ -12968,12 +13450,10 @@ function readIterationDoc(layout, iteration, developer, source = "local", preset
|
|
|
12968
13450
|
const ref = presetRef ?? resolveRemoteRef(docsRoot, refName);
|
|
12969
13451
|
const exported = exportRemoteDoc(docsRoot, ref, resolved.year, safeIteration, safeDeveloper, layout.iterationsRoot);
|
|
12970
13452
|
const roleInferred = inferRole(exported.markdown);
|
|
12971
|
-
const
|
|
13453
|
+
const local = validateLocally({
|
|
13454
|
+
markdown: exported.markdown,
|
|
12972
13455
|
schema: loadDocSchema(exported.dir),
|
|
12973
|
-
|
|
12974
|
-
scriptPath: exported.scriptPath,
|
|
12975
|
-
iteration: safeIteration,
|
|
12976
|
-
developer: safeDeveloper,
|
|
13456
|
+
iterationName: safeIteration,
|
|
12977
13457
|
role: roleInferred
|
|
12978
13458
|
});
|
|
12979
13459
|
return {
|
|
@@ -12982,14 +13462,14 @@ function readIterationDoc(layout, iteration, developer, source = "local", preset
|
|
|
12982
13462
|
file: `${resolved.relPath}/${safeDeveloper}.md`,
|
|
12983
13463
|
mtime: exported.mtime,
|
|
12984
13464
|
roleInferred,
|
|
12985
|
-
parser: null ===
|
|
12986
|
-
parserError:
|
|
13465
|
+
parser: null === local.error ? "local" : "fallback",
|
|
13466
|
+
parserError: local.error,
|
|
12987
13467
|
source: "remote",
|
|
12988
13468
|
ref: {
|
|
12989
13469
|
name: ref.ref,
|
|
12990
13470
|
sha: ref.sha
|
|
12991
13471
|
},
|
|
12992
|
-
validation:
|
|
13472
|
+
validation: local.payload,
|
|
12993
13473
|
details: splitDetails(exported.markdown)
|
|
12994
13474
|
};
|
|
12995
13475
|
}
|
|
@@ -12999,27 +13479,23 @@ function readIterationDoc(layout, iteration, developer, source = "local", preset
|
|
|
12999
13479
|
if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${resolved.relPath}/${safeDeveloper}.md`, errors_EXIT.NOT_FOUND);
|
|
13000
13480
|
const markdown = readMarkdown(file);
|
|
13001
13481
|
const roleInferred = inferRole(markdown);
|
|
13002
|
-
const
|
|
13482
|
+
const local = validateLocally({
|
|
13483
|
+
markdown,
|
|
13003
13484
|
schema: loadDocSchema(docsRoot),
|
|
13004
|
-
|
|
13005
|
-
scriptPath: external_node_path_join(docsRoot, "scripts", "validate_task_doc.py"),
|
|
13006
|
-
iteration: resolved.relPath,
|
|
13007
|
-
developer: safeDeveloper,
|
|
13485
|
+
iterationName: safeIteration,
|
|
13008
13486
|
role: roleInferred
|
|
13009
13487
|
});
|
|
13010
|
-
const validation = scripted.payload ?? parseMarkdownDoc(markdown, loadDocSchema(docsRoot));
|
|
13011
|
-
const parser = null === scripted.payload ? "fallback" : "script";
|
|
13012
13488
|
return {
|
|
13013
13489
|
iteration: safeIteration,
|
|
13014
13490
|
developer: safeDeveloper,
|
|
13015
13491
|
file,
|
|
13016
13492
|
mtime: statSync(file).mtime.toISOString(),
|
|
13017
13493
|
roleInferred,
|
|
13018
|
-
parser,
|
|
13019
|
-
parserError:
|
|
13494
|
+
parser: null === local.error ? "local" : "fallback",
|
|
13495
|
+
parserError: local.error,
|
|
13020
13496
|
source: "local",
|
|
13021
13497
|
ref: null,
|
|
13022
|
-
validation,
|
|
13498
|
+
validation: local.payload,
|
|
13023
13499
|
details: splitDetails(markdown)
|
|
13024
13500
|
};
|
|
13025
13501
|
}
|
|
@@ -13145,6 +13621,28 @@ function checkDocTaskSides(options) {
|
|
|
13145
13621
|
}))
|
|
13146
13622
|
});
|
|
13147
13623
|
}
|
|
13624
|
+
const REQUIREMENT_ID_PATTERN = /^(\d{3,6})$/;
|
|
13625
|
+
const TASK_ID_PATTERN = /^(\d{3,6})-T(\d+)$/;
|
|
13626
|
+
const ID_HINT = '编号不带 # 前缀';
|
|
13627
|
+
function rejectHash(raw, kind) {
|
|
13628
|
+
if (raw.startsWith('#')) throw new errors_CliError(`${kind}编号格式非法:${raw}\n${ID_HINT},应写成 ${raw.replace(/^#/, '')}`, errors_EXIT.USAGE);
|
|
13629
|
+
}
|
|
13630
|
+
function normalizeRequirementId(raw) {
|
|
13631
|
+
const value = raw.trim();
|
|
13632
|
+
rejectHash(value, '需求');
|
|
13633
|
+
if (!REQUIREMENT_ID_PATTERN.test(value)) throw new errors_CliError(`需求编号格式非法:${raw}(应为 3–6 位数字,如 2755)`, errors_EXIT.USAGE);
|
|
13634
|
+
return value;
|
|
13635
|
+
}
|
|
13636
|
+
function normalizeTaskId(raw) {
|
|
13637
|
+
const value = raw.trim();
|
|
13638
|
+
rejectHash(value, '任务');
|
|
13639
|
+
if (!TASK_ID_PATTERN.test(value)) throw new errors_CliError(`任务编号格式非法:${raw}(应为 2755-T1 形式)`, errors_EXIT.USAGE);
|
|
13640
|
+
return value;
|
|
13641
|
+
}
|
|
13642
|
+
function requirementOfTaskId(taskId) {
|
|
13643
|
+
const matched = TASK_ID_PATTERN.exec(taskId.trim());
|
|
13644
|
+
return null === matched ? null : matched[1] ?? null;
|
|
13645
|
+
}
|
|
13148
13646
|
const taskdoc_SAFE_SEGMENT = /^(?:\d{4}\/)?[A-Za-z0-9._\-\u4e00-\u9fa5]+$/;
|
|
13149
13647
|
function taskdoc_safeSegment(value, label) {
|
|
13150
13648
|
const trimmed = value.trim();
|
|
@@ -13389,7 +13887,7 @@ function parseTaskRows(lines, keys) {
|
|
|
13389
13887
|
}
|
|
13390
13888
|
if (cells.every((cell)=>/^:?-{2,}:?$/.test(cell))) continue;
|
|
13391
13889
|
const taskId = cells[columnIndex(header, keys.task.id)] ?? '';
|
|
13392
|
-
if (
|
|
13890
|
+
if (TASK_ID_PATTERN.test(taskId)) rows.push({
|
|
13393
13891
|
index,
|
|
13394
13892
|
cells,
|
|
13395
13893
|
taskId,
|
|
@@ -13419,7 +13917,7 @@ function parseRequirementRows(lines, keys) {
|
|
|
13419
13917
|
}
|
|
13420
13918
|
if (cells.every((cell)=>/^:?-{2,}:?$/.test(cell))) continue;
|
|
13421
13919
|
const id = cells[columnIndex(header, keys.requirement.id)] ?? '';
|
|
13422
|
-
if (
|
|
13920
|
+
if (REQUIREMENT_ID_PATTERN.test(id)) rows.push({
|
|
13423
13921
|
index,
|
|
13424
13922
|
cells,
|
|
13425
13923
|
id
|
|
@@ -13511,12 +14009,7 @@ function computeUpdate(lines, taskId, action, keys, docsRoot) {
|
|
|
13511
14009
|
人工验收: nextAcceptance
|
|
13512
14010
|
});
|
|
13513
14011
|
const requirementStatuses = rows.filter((row)=>row.requirementId === target.requirementId).map((row)=>row.taskId === taskId ? nextStatus : row.status);
|
|
13514
|
-
const aggregate =
|
|
13515
|
-
[
|
|
13516
|
-
target.requirementId,
|
|
13517
|
-
requirementStatuses
|
|
13518
|
-
]
|
|
13519
|
-
])).get(target.requirementId) ?? aggregateRequirement(requirementStatuses);
|
|
14012
|
+
const aggregate = aggregateRequirement(requirementStatuses);
|
|
13520
14013
|
const requirementStatus = aggregate.status;
|
|
13521
14014
|
const progress = aggregate.progress;
|
|
13522
14015
|
const requirementParse = parseRequirementRows(withDetail, keys);
|
|
@@ -13550,18 +14043,12 @@ function syncRequirementAggregates(docsRoot, lines, keys, stamp) {
|
|
|
13550
14043
|
row.status
|
|
13551
14044
|
]);
|
|
13552
14045
|
}
|
|
13553
|
-
const aggregates = resolveAggregates(docsRoot, statusesByCode);
|
|
13554
|
-
const byStatuses = new Map();
|
|
13555
|
-
for (const [code, statuses] of statusesByCode){
|
|
13556
|
-
const value = aggregates.get(code);
|
|
13557
|
-
if (void 0 !== value) byStatuses.set(statuses.join('\u0000'), value);
|
|
13558
|
-
}
|
|
13559
14046
|
return refreshRequirementRows({
|
|
13560
14047
|
lines,
|
|
13561
14048
|
schema,
|
|
13562
14049
|
statusesByCode,
|
|
13563
14050
|
stamp,
|
|
13564
|
-
aggregate:
|
|
14051
|
+
aggregate: aggregateRequirement
|
|
13565
14052
|
});
|
|
13566
14053
|
} catch {
|
|
13567
14054
|
return {
|
|
@@ -13570,8 +14057,11 @@ function syncRequirementAggregates(docsRoot, lines, keys, stamp) {
|
|
|
13570
14057
|
};
|
|
13571
14058
|
}
|
|
13572
14059
|
}
|
|
14060
|
+
function assertFileUnmodified(file, expectedMtime) {
|
|
14061
|
+
if (statSync(file).mtimeMs !== expectedMtime) throw new errors_CliError('文件已被外部修改,请刷新后重试', errors_EXIT.INVALID);
|
|
14062
|
+
}
|
|
13573
14063
|
function commit(context, lines, changes, message, iteration, developer, action, taskIds, options) {
|
|
13574
|
-
|
|
14064
|
+
assertFileUnmodified(context.file, context.mtime);
|
|
13575
14065
|
const synced = syncRequirementAggregates(options.docsRoot, lines, buildKeys(loadDocSchema(options.docsRoot)), nowStamp());
|
|
13576
14066
|
lines = synced.lines;
|
|
13577
14067
|
changes = [
|
|
@@ -13587,14 +14077,18 @@ function commit(context, lines, changes, message, iteration, developer, action,
|
|
|
13587
14077
|
};
|
|
13588
14078
|
writeFileSync(context.file, output, 'utf8');
|
|
13589
14079
|
const outcome = validateAfterWrite(toLayout(options), iteration, developer);
|
|
14080
|
+
const strict = strictValidationEnabled();
|
|
13590
14081
|
if ('violation' === outcome.kind) {
|
|
13591
|
-
|
|
13592
|
-
|
|
14082
|
+
if (strict) {
|
|
14083
|
+
writeFileSync(context.file, context.original, 'utf8');
|
|
14084
|
+
throw new errors_CliError(`写入未通过文档校验,已回滚:${outcome.message}`, errors_EXIT.INVALID);
|
|
14085
|
+
}
|
|
14086
|
+
process.stderr.write(`警告:写入未通过文档校验(docs.validator.strict=false):${outcome.message}\n`);
|
|
13593
14087
|
}
|
|
13594
14088
|
if ('unavailable' === outcome.kind) {
|
|
13595
14089
|
writeFileSync(context.file, context.original, 'utf8');
|
|
13596
|
-
if (
|
|
13597
|
-
process.stderr.write(`警告:${outcome.reason};本次写入未做文档校验(docs.validator.
|
|
14090
|
+
if (strict) throw new errors_CliError(`未执行文档校验,已回滚:${outcome.reason}\n如需在无法校验时仍写入(不推荐),可配置 docs.validator.strict: false`, errors_EXIT.INVALID);
|
|
14091
|
+
process.stderr.write(`警告:${outcome.reason};本次写入未做文档校验(docs.validator.strict=false)\n`);
|
|
13598
14092
|
}
|
|
13599
14093
|
appendHistory({
|
|
13600
14094
|
iteration,
|
|
@@ -13622,7 +14116,9 @@ const LOCKED_MIRROR_SOURCES = new Set([
|
|
|
13622
14116
|
]);
|
|
13623
14117
|
function lockedDetailFields(schema, scope) {
|
|
13624
14118
|
const locked = new Set();
|
|
13625
|
-
|
|
14119
|
+
const role = roleOfScope(schema, scope);
|
|
14120
|
+
if (null === role) return locked;
|
|
14121
|
+
for (const [field, column] of Object.entries(mirrorColumnsOfSides(role)))if (LOCKED_MIRROR_SOURCES.has(column)) locked.add(field);
|
|
13626
14122
|
return locked;
|
|
13627
14123
|
}
|
|
13628
14124
|
function readDetailField(lines, taskId, field) {
|
|
@@ -13678,7 +14174,10 @@ function applyTaskDetail(options) {
|
|
|
13678
14174
|
const touched = [];
|
|
13679
14175
|
for (const update of options.updates){
|
|
13680
14176
|
const fieldName = allowed.get(normalizeDetailField(update.field));
|
|
13681
|
-
if (void 0 === fieldName)
|
|
14177
|
+
if (void 0 === fieldName) {
|
|
14178
|
+
const reason = 0 === allowedFields.length ? `任务的「所属端」为「${scope.length > 0 ? scope : '空'}」,不在 schema 的 roles 中,无法确定可编辑字段` : `可改:${allowedFields.join(' / ')}`;
|
|
14179
|
+
throw new errors_CliError(`字段「${update.field}」不可编辑(${reason})`, errors_EXIT.USAGE);
|
|
14180
|
+
}
|
|
13682
14181
|
if (lockedDetailFields(schema, scope).has(fieldName)) throw new errors_CliError(`字段「${fieldName}」由状态流转命令维护,请使用 task start/submit/accept/reject 或 task selftest`, errors_EXIT.USAGE);
|
|
13683
14182
|
const parsed = readDetailField(lines, options.taskId, fieldName);
|
|
13684
14183
|
if (null === parsed) throw new errors_CliError(`任务 ${options.taskId} 的详情区块缺少字段「${fieldName}」`, errors_EXIT.INVALID);
|
|
@@ -13812,94 +14311,38 @@ function applyTaskAction(options) {
|
|
|
13812
14311
|
});
|
|
13813
14312
|
}
|
|
13814
14313
|
function validateAfterWrite(layout, iteration, developer) {
|
|
13815
|
-
const
|
|
13816
|
-
const
|
|
13817
|
-
if (!external_node_fs_existsSync(script)) return {
|
|
13818
|
-
kind: 'unavailable',
|
|
13819
|
-
reason: `文档仓库缺少校验脚本 ${script}`
|
|
13820
|
-
};
|
|
13821
|
-
const resolved = resolveIterationDir(docsRoot, layout.iterationsRoot, iteration);
|
|
14314
|
+
const schema = loadDocSchema(layout.root);
|
|
14315
|
+
const resolved = resolveIterationDir(layout.root, layout.iterationsRoot, iteration);
|
|
13822
14316
|
const targetFile = external_node_path_join(resolved.dir, `${developer}.md`);
|
|
13823
|
-
|
|
13824
|
-
if (external_node_fs_existsSync(targetFile)) try {
|
|
13825
|
-
role = inferRole(readFileSync(targetFile, 'utf8'));
|
|
13826
|
-
} catch {
|
|
13827
|
-
role = 'frontend';
|
|
13828
|
-
}
|
|
13829
|
-
const args = [
|
|
13830
|
-
script,
|
|
13831
|
-
'--docs-root',
|
|
13832
|
-
docsRoot,
|
|
13833
|
-
'--iteration',
|
|
13834
|
-
resolved.relPath,
|
|
13835
|
-
'--developer',
|
|
13836
|
-
developer,
|
|
13837
|
-
'--role',
|
|
13838
|
-
role,
|
|
13839
|
-
'--format',
|
|
13840
|
-
'json'
|
|
13841
|
-
];
|
|
13842
|
-
let interpreterMissing = true;
|
|
13843
|
-
let scriptError = null;
|
|
13844
|
-
for (const bin of [
|
|
13845
|
-
'python3',
|
|
13846
|
-
'python',
|
|
13847
|
-
'py'
|
|
13848
|
-
])try {
|
|
13849
|
-
const stdout = execFileSync(bin, args, {
|
|
13850
|
-
encoding: 'utf8',
|
|
13851
|
-
timeout: 15000,
|
|
13852
|
-
maxBuffer: 16777216,
|
|
13853
|
-
stdio: [
|
|
13854
|
-
'ignore',
|
|
13855
|
-
'pipe',
|
|
13856
|
-
'pipe'
|
|
13857
|
-
]
|
|
13858
|
-
});
|
|
13859
|
-
const payload = JSON.parse(stdout);
|
|
13860
|
-
const first = payload.errors?.[0];
|
|
13861
|
-
return void 0 === first ? {
|
|
13862
|
-
kind: 'passed'
|
|
13863
|
-
} : {
|
|
13864
|
-
kind: 'violation',
|
|
13865
|
-
message: first.message ?? '校验器未通过'
|
|
13866
|
-
};
|
|
13867
|
-
} catch (error) {
|
|
13868
|
-
const { stdout, stderr, code } = error;
|
|
13869
|
-
if ('ENOENT' === code || 127 === code) continue;
|
|
13870
|
-
interpreterMissing = false;
|
|
13871
|
-
if ((stdout ?? '').trim().length > 0) try {
|
|
13872
|
-
const payload = JSON.parse(stdout ?? '');
|
|
13873
|
-
return {
|
|
13874
|
-
kind: 'violation',
|
|
13875
|
-
message: payload.errors?.[0]?.message ?? '校验器未通过'
|
|
13876
|
-
};
|
|
13877
|
-
} catch {
|
|
13878
|
-
scriptError = '校验器输出无法解析';
|
|
13879
|
-
continue;
|
|
13880
|
-
}
|
|
13881
|
-
const reason = (stderr ?? '').trim().split('\n')[0] ?? '';
|
|
13882
|
-
scriptError = reason.length > 0 ? `校验器执行失败:${reason}` : '校验器执行失败';
|
|
13883
|
-
continue;
|
|
13884
|
-
}
|
|
13885
|
-
if (null !== scriptError) return {
|
|
14317
|
+
if (!external_node_fs_existsSync(targetFile)) return {
|
|
13886
14318
|
kind: 'unavailable',
|
|
13887
|
-
reason:
|
|
14319
|
+
reason: `找不到个人任务文档:${targetFile}`
|
|
13888
14320
|
};
|
|
13889
|
-
|
|
14321
|
+
const markdown = readFileSync(targetFile, 'utf8');
|
|
14322
|
+
const role = roleOfDocument(markdown, schema);
|
|
14323
|
+
if (null === role) return {
|
|
13890
14324
|
kind: 'unavailable',
|
|
13891
|
-
reason: '
|
|
14325
|
+
reason: `文档「负责范围」缺失或不是 ${Object.keys(schema.roles).join(' / ')},无法确定校验角色`
|
|
13892
14326
|
};
|
|
13893
|
-
|
|
13894
|
-
|
|
13895
|
-
|
|
14327
|
+
const result = validateDoc({
|
|
14328
|
+
markdown,
|
|
14329
|
+
schema,
|
|
14330
|
+
role,
|
|
14331
|
+
iterationName: resolved.name
|
|
14332
|
+
});
|
|
14333
|
+
const first = result.errors[0];
|
|
14334
|
+
return void 0 === first ? {
|
|
14335
|
+
kind: 'passed'
|
|
14336
|
+
} : {
|
|
14337
|
+
kind: 'violation',
|
|
14338
|
+
message: first.message
|
|
13896
14339
|
};
|
|
13897
14340
|
}
|
|
13898
|
-
function
|
|
14341
|
+
function strictValidationEnabled() {
|
|
13899
14342
|
try {
|
|
13900
14343
|
const config = config_loadConfig().config;
|
|
13901
14344
|
if (null === config) return true;
|
|
13902
|
-
return config.docs.validator.
|
|
14345
|
+
return config.docs.validator.strict;
|
|
13903
14346
|
} catch {
|
|
13904
14347
|
return true;
|
|
13905
14348
|
}
|
|
@@ -13908,7 +14351,7 @@ function applyRequirementNote(options) {
|
|
|
13908
14351
|
assertWritableBranch(options.docsRoot);
|
|
13909
14352
|
const keys = buildKeys(loadDocSchema(options.docsRoot));
|
|
13910
14353
|
const context = loadDoc(options, options.iteration, options.developer);
|
|
13911
|
-
const requirementId = options.requirementId
|
|
14354
|
+
const requirementId = normalizeRequirementId(options.requirementId);
|
|
13912
14355
|
const requirementParse = parseRequirementRows(context.lines, keys);
|
|
13913
14356
|
const target = requirementParse.rows.find((row)=>row.id === requirementId);
|
|
13914
14357
|
if (void 0 === target) throw new errors_CliError(`需求清单中未找到 ${requirementId}`, errors_EXIT.NOT_FOUND);
|
|
@@ -13953,15 +14396,14 @@ function recalcRequirements(options) {
|
|
|
13953
14396
|
...context.lines
|
|
13954
14397
|
];
|
|
13955
14398
|
const changes = [];
|
|
13956
|
-
const
|
|
13957
|
-
|
|
13958
|
-
|
|
13959
|
-
|
|
14399
|
+
const statusesByRequirement = new Map();
|
|
14400
|
+
for (const row of taskRows){
|
|
14401
|
+
const list = statusesByRequirement.get(row.requirementId) ?? [];
|
|
14402
|
+
list.push(row.status);
|
|
14403
|
+
statusesByRequirement.set(row.requirementId, list);
|
|
14404
|
+
}
|
|
13960
14405
|
for (const requirement of requirementParse.rows){
|
|
13961
|
-
const aggregate =
|
|
13962
|
-
status: '未开始',
|
|
13963
|
-
progress: 0
|
|
13964
|
-
};
|
|
14406
|
+
const aggregate = aggregateRequirement(statusesByRequirement.get(requirement.id) ?? []);
|
|
13965
14407
|
const status = aggregate.status;
|
|
13966
14408
|
const progress = aggregate.progress;
|
|
13967
14409
|
const cells = [
|
|
@@ -14101,6 +14543,81 @@ function renameTaskColumns(options) {
|
|
|
14101
14543
|
renamed
|
|
14102
14544
|
};
|
|
14103
14545
|
}
|
|
14546
|
+
function stripHashIds(options) {
|
|
14547
|
+
const { schema } = options;
|
|
14548
|
+
const requirementIdLabel = schema.requirementKeys['id'] ?? '';
|
|
14549
|
+
const requirementTitleLabel = schema.requirementKeys['title'] ?? '';
|
|
14550
|
+
const taskIdLabel = schema.taskKeys['id'] ?? '';
|
|
14551
|
+
const taskNameLabel = schema.taskKeys['name'] ?? '';
|
|
14552
|
+
const taskRequirementLabel = schema.taskKeys['requirement'] ?? '';
|
|
14553
|
+
const taskDependenciesLabel = schema.taskKeys['dependencies'] ?? '';
|
|
14554
|
+
const HASH = /#(?=\d{3,6}(?:-T\d+)?)/g;
|
|
14555
|
+
let stripped = 0;
|
|
14556
|
+
const out = [];
|
|
14557
|
+
let current = null;
|
|
14558
|
+
for (const line of options.lines){
|
|
14559
|
+
const cells = doc_migrate_splitRow(line);
|
|
14560
|
+
if (null !== cells) {
|
|
14561
|
+
if (cells.includes(requirementIdLabel) && cells.includes(requirementTitleLabel)) {
|
|
14562
|
+
current = {
|
|
14563
|
+
kind: 'requirement',
|
|
14564
|
+
header: cells
|
|
14565
|
+
};
|
|
14566
|
+
out.push(line);
|
|
14567
|
+
continue;
|
|
14568
|
+
}
|
|
14569
|
+
if (cells.includes(taskIdLabel) && cells.includes(taskNameLabel)) {
|
|
14570
|
+
current = {
|
|
14571
|
+
kind: 'task',
|
|
14572
|
+
header: cells
|
|
14573
|
+
};
|
|
14574
|
+
out.push(line);
|
|
14575
|
+
continue;
|
|
14576
|
+
}
|
|
14577
|
+
if (null !== current && cells.every((cell)=>/^:?-{2,}:?$/.test(cell))) {
|
|
14578
|
+
out.push(line);
|
|
14579
|
+
continue;
|
|
14580
|
+
}
|
|
14581
|
+
if (null !== current) {
|
|
14582
|
+
const active = current;
|
|
14583
|
+
const targets = 'requirement' === active.kind ? [
|
|
14584
|
+
requirementIdLabel
|
|
14585
|
+
] : [
|
|
14586
|
+
taskIdLabel,
|
|
14587
|
+
taskRequirementLabel,
|
|
14588
|
+
taskDependenciesLabel
|
|
14589
|
+
];
|
|
14590
|
+
let touched = false;
|
|
14591
|
+
const next = cells.map((cell, index)=>{
|
|
14592
|
+
if (!targets.includes(active.header[index] ?? '')) return cell;
|
|
14593
|
+
const cleaned = cell.replace(HASH, '');
|
|
14594
|
+
if (cleaned !== cell) touched = true;
|
|
14595
|
+
return cleaned;
|
|
14596
|
+
});
|
|
14597
|
+
if (touched) {
|
|
14598
|
+
stripped += 1;
|
|
14599
|
+
out.push(doc_migrate_joinRow(next));
|
|
14600
|
+
continue;
|
|
14601
|
+
}
|
|
14602
|
+
}
|
|
14603
|
+
out.push(line);
|
|
14604
|
+
continue;
|
|
14605
|
+
}
|
|
14606
|
+
if (/^###\s+\[/.test(line.trim())) {
|
|
14607
|
+
const next = line.replace(/\[#(\d{3,6}-T\d+)\]/, '[$1]');
|
|
14608
|
+
if (next !== line) stripped += 1;
|
|
14609
|
+
out.push(next);
|
|
14610
|
+
continue;
|
|
14611
|
+
}
|
|
14612
|
+
const next = line.replace(HASH, '');
|
|
14613
|
+
if (next !== line) stripped += 1;
|
|
14614
|
+
out.push(next);
|
|
14615
|
+
}
|
|
14616
|
+
return {
|
|
14617
|
+
lines: out,
|
|
14618
|
+
stripped
|
|
14619
|
+
};
|
|
14620
|
+
}
|
|
14104
14621
|
function locateTaskTable(lines, schema) {
|
|
14105
14622
|
const heading = `## ${schema.sections[2] ?? '三、任务清单'}`;
|
|
14106
14623
|
const sectionStart = lines.findIndex((line)=>line.trim() === heading);
|
|
@@ -14204,7 +14721,7 @@ function locateDetailBlocks(lines, schema) {
|
|
|
14204
14721
|
for(let index = sectionStart + 1; index < lines.length; index += 1){
|
|
14205
14722
|
const line = lines[index] ?? '';
|
|
14206
14723
|
if (/^##\s+/.test(line)) break;
|
|
14207
|
-
const matched = /^###\s+\[(
|
|
14724
|
+
const matched = /^###\s+\[([^\]]+)\]/.exec(line.trim());
|
|
14208
14725
|
if (null !== matched) {
|
|
14209
14726
|
if (null !== current) current.endIndex = index;
|
|
14210
14727
|
current = {
|
|
@@ -14308,9 +14825,12 @@ function migrateDetailFields(options) {
|
|
|
14308
14825
|
break;
|
|
14309
14826
|
}
|
|
14310
14827
|
}
|
|
14828
|
+
const role = roleOfScope(schema, scope);
|
|
14829
|
+
const spec = null === role ? void 0 : taskFieldSpecOf(role, name);
|
|
14830
|
+
const filler = spec?.empty ?? '<待补充>';
|
|
14311
14831
|
lines = [
|
|
14312
14832
|
...lines.slice(0, insertAt),
|
|
14313
|
-
`- **${name}
|
|
14833
|
+
`- **${name}**:${filler}`,
|
|
14314
14834
|
...lines.slice(insertAt)
|
|
14315
14835
|
];
|
|
14316
14836
|
const refreshed = fieldSpans(lines, block);
|
|
@@ -14361,8 +14881,12 @@ function runDocMigrate(options) {
|
|
|
14361
14881
|
for (const name of files){
|
|
14362
14882
|
const target = external_node_path_join(dir, name);
|
|
14363
14883
|
const original = readFileSync(target, 'utf8');
|
|
14364
|
-
const
|
|
14884
|
+
const strippedResult = stripHashIds({
|
|
14365
14885
|
lines: original.split('\n'),
|
|
14886
|
+
schema
|
|
14887
|
+
});
|
|
14888
|
+
const renamedResult = renameTaskColumns({
|
|
14889
|
+
lines: strippedResult.lines,
|
|
14366
14890
|
schema,
|
|
14367
14891
|
renames
|
|
14368
14892
|
});
|
|
@@ -14387,7 +14911,8 @@ function runDocMigrate(options) {
|
|
|
14387
14911
|
const addedFields = detailMigrated.added;
|
|
14388
14912
|
const renamedColumns = renamedResult.renamed.length;
|
|
14389
14913
|
const reorderedBlocks = reordered.reordered;
|
|
14390
|
-
|
|
14914
|
+
const strippedIds = strippedResult.stripped;
|
|
14915
|
+
if (0 === addedRows && 0 === addedFields && 0 === renamedColumns && 0 === reorderedBlocks && 0 === strippedIds) continue;
|
|
14391
14916
|
const migrated = {
|
|
14392
14917
|
lines: reordered.lines,
|
|
14393
14918
|
unresolved: tableMigrated.unresolved
|
|
@@ -14398,6 +14923,7 @@ function runDocMigrate(options) {
|
|
|
14398
14923
|
addedFields,
|
|
14399
14924
|
renamed: renamedColumns,
|
|
14400
14925
|
reordered: reorderedBlocks,
|
|
14926
|
+
stripped: strippedIds,
|
|
14401
14927
|
unresolved: tableMigrated.unresolved
|
|
14402
14928
|
});
|
|
14403
14929
|
if (true === options.dryRun) continue;
|
|
@@ -14409,8 +14935,8 @@ function runDocMigrate(options) {
|
|
|
14409
14935
|
if ('passed' !== outcome.kind) {
|
|
14410
14936
|
writeFileSync(target, original, 'utf8');
|
|
14411
14937
|
const reason = 'violation' === outcome.kind ? outcome.message : outcome.reason;
|
|
14412
|
-
if (
|
|
14413
|
-
process.stderr.write(`警告:${
|
|
14938
|
+
if (!strictValidationEnabled()) {
|
|
14939
|
+
process.stderr.write(`警告:${reason};${iteration.relPath}/${name} 迁移后校验未通过(docs.validator.strict=false)\n`);
|
|
14414
14940
|
continue;
|
|
14415
14941
|
}
|
|
14416
14942
|
throw new errors_CliError(`迁移后校验未通过,已回滚 ${iteration.relPath}/${name}:${reason}`, errors_EXIT.INVALID);
|
|
@@ -14433,19 +14959,19 @@ function runDocMigrate(options) {
|
|
|
14433
14959
|
if (item.addedFields > 0) parts.push(`${item.addedFields} 个详情字段`);
|
|
14434
14960
|
if (item.renamed > 0) parts.push(`${item.renamed} 列改名`);
|
|
14435
14961
|
if (item.reordered > 0) parts.push(`${item.reordered} 个详情区块重排`);
|
|
14962
|
+
if (item.stripped > 0) parts.push(`${item.stripped} 处编号去掉 #`);
|
|
14436
14963
|
printLine(` · ${item.file} ${parts.join(' + ')}${extra}`);
|
|
14437
14964
|
}
|
|
14438
14965
|
if (totalUnresolved.length > 0) {
|
|
14439
14966
|
printLine('\n以下任务的「所属端」无法自动判定(执行终端未配置或类型两端通用),请手工补齐:');
|
|
14440
14967
|
printLine(` ${totalUnresolved.join('、')}`);
|
|
14441
14968
|
printLine('补齐后运行校验:');
|
|
14442
|
-
printLine(
|
|
14443
|
-
printLine(' --iteration <迭代> --developer <标识> --role <frontend|backend|fullstack>');
|
|
14969
|
+
printLine(' ylcwf doc validate -i <迭代> -d <开发者>');
|
|
14444
14970
|
}
|
|
14445
14971
|
if (true !== options.dryRun) {
|
|
14446
14972
|
const policy = config.docs.git.cli;
|
|
14447
14973
|
if (policy.commit) {
|
|
14448
|
-
const git = commitInDocsRepo(docsRoot, changedFiles, "docs:
|
|
14974
|
+
const git = commitInDocsRepo(docsRoot, changedFiles, "docs: 迁移任务表结构与编号格式(按 schema.json)", policy.push);
|
|
14449
14975
|
printLine(`\n${git.message}`);
|
|
14450
14976
|
}
|
|
14451
14977
|
}
|
|
@@ -14477,136 +15003,667 @@ function registerDocMigrate(doc) {
|
|
|
14477
15003
|
runDocMigrate(options);
|
|
14478
15004
|
});
|
|
14479
15005
|
}
|
|
14480
|
-
|
|
14481
|
-
|
|
14482
|
-
|
|
14483
|
-
|
|
15006
|
+
const RESERVED_DOC_FILES = new Set([
|
|
15007
|
+
'README.md',
|
|
15008
|
+
'AGENTS.md',
|
|
15009
|
+
'CLAUDE.md'
|
|
15010
|
+
]);
|
|
15011
|
+
function roleHintOf(schema) {
|
|
15012
|
+
return Object.keys(schema.roles).join(' / ');
|
|
14484
15013
|
}
|
|
14485
|
-
function
|
|
14486
|
-
if (!external_node_fs_existsSync(path)) throw new errors_CliError(`plan 文件不存在:${path}`, errors_EXIT.NOT_FOUND);
|
|
14487
|
-
const text = readFileSync(path, 'utf8');
|
|
15014
|
+
function gitLines(cwd, args) {
|
|
14488
15015
|
try {
|
|
14489
|
-
|
|
15016
|
+
const stdout = execFileSync('git', args, {
|
|
15017
|
+
cwd,
|
|
15018
|
+
encoding: 'utf8',
|
|
15019
|
+
stdio: [
|
|
15020
|
+
'ignore',
|
|
15021
|
+
'pipe',
|
|
15022
|
+
'pipe'
|
|
15023
|
+
]
|
|
15024
|
+
});
|
|
15025
|
+
return stdout.split('\n').map((line)=>line.trim()).filter((line)=>line.length > 0);
|
|
14490
15026
|
} catch (error) {
|
|
14491
|
-
|
|
15027
|
+
const reason = error instanceof Error ? error.message.split('\n')[0] : String(error);
|
|
15028
|
+
throw new errors_CliError(`git ${args.join(' ')} 执行失败:${reason ?? ''}`, errors_EXIT.INVALID);
|
|
14492
15029
|
}
|
|
14493
15030
|
}
|
|
14494
|
-
function
|
|
15031
|
+
function iterationsOfFiles(layout, files) {
|
|
15032
|
+
const prefix = `${layout.iterationsRoot}/`;
|
|
15033
|
+
const found = new Set();
|
|
15034
|
+
for (const file of files){
|
|
15035
|
+
if (!file.startsWith(prefix)) continue;
|
|
15036
|
+
const parts = file.slice(prefix.length).split('/');
|
|
15037
|
+
const year = parts[0];
|
|
15038
|
+
const name = parts[1];
|
|
15039
|
+
if (!(parts.length < 3) && void 0 !== year && void 0 !== name) found.add(`${year}/${name}`);
|
|
15040
|
+
}
|
|
15041
|
+
return [
|
|
15042
|
+
...found
|
|
15043
|
+
].sort();
|
|
15044
|
+
}
|
|
15045
|
+
function resolveTargets(options, layout) {
|
|
15046
|
+
const requested = (options.iteration ?? '').trim();
|
|
15047
|
+
const base = (options.base ?? '').trim();
|
|
15048
|
+
const chosen = [
|
|
15049
|
+
requested.length > 0,
|
|
15050
|
+
true === options.all,
|
|
15051
|
+
true === options.staged,
|
|
15052
|
+
base.length > 0
|
|
15053
|
+
].filter((item)=>item).length;
|
|
15054
|
+
if (0 === chosen) throw new errors_CliError('必须指定校验范围之一:-i/--iteration <迭代>、--all、--staged、--base <ref>', errors_EXIT.USAGE);
|
|
15055
|
+
if (chosen > 1) throw new errors_CliError('校验范围只能选一个:-i/--iteration、--all、--staged、--base', errors_EXIT.USAGE);
|
|
15056
|
+
if (requested.length > 0) return [
|
|
15057
|
+
requireIterationDir(layout.root, layout.iterationsRoot, requested).relPath
|
|
15058
|
+
];
|
|
15059
|
+
if (true === options.all) return listIterationDirs(layout.root, layout.iterationsRoot).map((item)=>item.relPath);
|
|
15060
|
+
if (true === options.staged) return iterationsOfFiles(layout, gitLines(layout.root, [
|
|
15061
|
+
'diff',
|
|
15062
|
+
'--cached',
|
|
15063
|
+
'--name-only'
|
|
15064
|
+
]));
|
|
15065
|
+
return iterationsOfFiles(layout, gitLines(layout.root, [
|
|
15066
|
+
'diff',
|
|
15067
|
+
'--name-only',
|
|
15068
|
+
`${base}...HEAD`
|
|
15069
|
+
]));
|
|
15070
|
+
}
|
|
15071
|
+
function validateIteration(options) {
|
|
15072
|
+
const { layout, schema, explicitRole, developerFilter } = options;
|
|
15073
|
+
const resolved = requireIterationDir(layout.root, layout.iterationsRoot, options.relPath);
|
|
15074
|
+
const developers = developerFilter.length > 0 ? [
|
|
15075
|
+
developerFilter
|
|
15076
|
+
] : external_node_fs_readdirSync(resolved.dir).filter((name)=>name.endsWith('.md') && !RESERVED_DOC_FILES.has(name)).map((name)=>name.slice(0, -3)).sort();
|
|
15077
|
+
if (0 === developers.length) return [
|
|
15078
|
+
{
|
|
15079
|
+
iteration: resolved.relPath,
|
|
15080
|
+
developer: developerFilter.length > 0 ? developerFilter : '(无成员文档)',
|
|
15081
|
+
role: null,
|
|
15082
|
+
fileRelPath: resolved.relPath,
|
|
15083
|
+
valid: false,
|
|
15084
|
+
stats: null,
|
|
15085
|
+
errors: [
|
|
15086
|
+
{
|
|
15087
|
+
level: 'error',
|
|
15088
|
+
code: 'DEVELOPER_DOC_EMPTY',
|
|
15089
|
+
message: `迭代 ${resolved.relPath} 下没有成员文档`
|
|
15090
|
+
}
|
|
15091
|
+
],
|
|
15092
|
+
warnings: []
|
|
15093
|
+
}
|
|
15094
|
+
];
|
|
15095
|
+
return developers.map((developer)=>{
|
|
15096
|
+
const file = external_node_path_join(resolved.dir, `${developer}.md`);
|
|
15097
|
+
const fileRelPath = external_node_path_relative(layout.root, file);
|
|
15098
|
+
if (!external_node_fs_existsSync(file)) return {
|
|
15099
|
+
iteration: resolved.relPath,
|
|
15100
|
+
developer,
|
|
15101
|
+
role: null,
|
|
15102
|
+
fileRelPath,
|
|
15103
|
+
valid: false,
|
|
15104
|
+
stats: null,
|
|
15105
|
+
errors: [
|
|
15106
|
+
{
|
|
15107
|
+
level: 'error',
|
|
15108
|
+
code: 'DEVELOPER_FILE_MISSING',
|
|
15109
|
+
message: `个人任务文档不存在:${fileRelPath}`
|
|
15110
|
+
}
|
|
15111
|
+
],
|
|
15112
|
+
warnings: []
|
|
15113
|
+
};
|
|
15114
|
+
const markdown = readFileSync(file, 'utf8');
|
|
15115
|
+
const role = explicitRole.length > 0 ? explicitRole : roleOfDocument(markdown, schema);
|
|
15116
|
+
if (null === role) return {
|
|
15117
|
+
iteration: resolved.relPath,
|
|
15118
|
+
developer,
|
|
15119
|
+
role: null,
|
|
15120
|
+
fileRelPath,
|
|
15121
|
+
valid: false,
|
|
15122
|
+
stats: null,
|
|
15123
|
+
errors: [
|
|
15124
|
+
{
|
|
15125
|
+
level: 'error',
|
|
15126
|
+
code: 'ROLE_UNKNOWN',
|
|
15127
|
+
message: `「负责范围」缺失或不是 ${roleHintOf(schema)},无法确定校验角色`
|
|
15128
|
+
}
|
|
15129
|
+
],
|
|
15130
|
+
warnings: []
|
|
15131
|
+
};
|
|
15132
|
+
const result = validateDoc({
|
|
15133
|
+
markdown,
|
|
15134
|
+
schema,
|
|
15135
|
+
role,
|
|
15136
|
+
iterationName: resolved.name
|
|
15137
|
+
});
|
|
15138
|
+
return {
|
|
15139
|
+
iteration: resolved.relPath,
|
|
15140
|
+
developer,
|
|
15141
|
+
role,
|
|
15142
|
+
fileRelPath,
|
|
15143
|
+
valid: result.valid,
|
|
15144
|
+
stats: result.stats,
|
|
15145
|
+
errors: result.errors,
|
|
15146
|
+
warnings: result.warnings
|
|
15147
|
+
};
|
|
15148
|
+
});
|
|
15149
|
+
}
|
|
15150
|
+
function runDocValidate(options) {
|
|
14495
15151
|
const format = parseFormat(options.format);
|
|
15152
|
+
enableJsonErrors('json' === format);
|
|
14496
15153
|
const loaded = config_loadConfig(options.config);
|
|
14497
15154
|
if (!loaded.exists || null === loaded.config) throw new errors_CliError(`配置未初始化:${loaded.path}\n请先运行:ylcwf init`, errors_EXIT.NOT_FOUND);
|
|
14498
15155
|
const config = loaded.config;
|
|
14499
|
-
const
|
|
14500
|
-
const layout =
|
|
14501
|
-
|
|
14502
|
-
|
|
14503
|
-
|
|
14504
|
-
|
|
14505
|
-
const
|
|
14506
|
-
const
|
|
14507
|
-
|
|
14508
|
-
const
|
|
14509
|
-
|
|
14510
|
-
|
|
14511
|
-
const exists = external_node_fs_existsSync(targetFile);
|
|
14512
|
-
const original = exists ? readFileSync(targetFile, 'utf8') : null;
|
|
14513
|
-
const mtime = exists ? statSync(targetFile).mtimeMs : 0;
|
|
14514
|
-
const parsed = null === original ? {
|
|
14515
|
-
requirements: [],
|
|
14516
|
-
tasks: []
|
|
14517
|
-
} : parseMarkdownDoc(original, schema);
|
|
14518
|
-
if (null !== original) {
|
|
14519
|
-
const documentRole = inferRole(original);
|
|
14520
|
-
if (documentRole !== role) process.stderr.write(`提示:${resolvedIteration.relPath}/${developer}.md 的负责范围是「${documentRole}」,与当前角色「${role}」不一致。\n 写入后的校验按文档为准(${documentRole});要让文档与本机角色一致,请手工修改「负责范围」为 ${role}。\n`);
|
|
14521
|
-
}
|
|
14522
|
-
validatePlanReferences({
|
|
14523
|
-
plan,
|
|
14524
|
-
schema,
|
|
14525
|
-
role,
|
|
14526
|
-
index: buildRepoSideIndex(config.terminals),
|
|
14527
|
-
knownTaskIds: parsed.tasks.map((task)=>task.id),
|
|
14528
|
-
knownRequirements: parsed.requirements.map((item)=>item.id)
|
|
14529
|
-
});
|
|
14530
|
-
const statusesByRequirement = new Map();
|
|
14531
|
-
for (const item of parsed.tasks){
|
|
14532
|
-
const list = statusesByRequirement.get(item.requirementId) ?? [];
|
|
14533
|
-
statusesByRequirement.set(item.requirementId, [
|
|
14534
|
-
...list,
|
|
14535
|
-
item.status
|
|
14536
|
-
]);
|
|
14537
|
-
}
|
|
14538
|
-
for (const task of plan.tasks){
|
|
14539
|
-
const list = statusesByRequirement.get(task.requirement) ?? [];
|
|
14540
|
-
statusesByRequirement.set(task.requirement, [
|
|
14541
|
-
...list,
|
|
14542
|
-
'未开始'
|
|
14543
|
-
]);
|
|
14544
|
-
}
|
|
14545
|
-
const aggregates = resolveAggregates(docsRoot, statusesByRequirement);
|
|
14546
|
-
const aggregateByStatuses = new Map();
|
|
14547
|
-
for (const [requirementId, statuses] of statusesByRequirement){
|
|
14548
|
-
const value = aggregates.get(requirementId);
|
|
14549
|
-
if (void 0 !== value) aggregateByStatuses.set(statuses.join('\u0000'), value);
|
|
14550
|
-
}
|
|
14551
|
-
const stamp = doc_nowStamp();
|
|
14552
|
-
const rendered = renderPlan({
|
|
14553
|
-
schema,
|
|
14554
|
-
role,
|
|
14555
|
-
plan,
|
|
14556
|
-
existing: {
|
|
14557
|
-
requirements: parsed.requirements,
|
|
14558
|
-
tasks: parsed.tasks,
|
|
14559
|
-
lines: null === original ? null : original.split('\n')
|
|
14560
|
-
},
|
|
14561
|
-
stamp,
|
|
14562
|
-
developer,
|
|
14563
|
-
aggregate: (statuses)=>aggregateByStatuses.get(statuses.join('\u0000')) ?? aggregateRequirement(statuses)
|
|
14564
|
-
});
|
|
14565
|
-
const sideIndex = buildRepoSideIndex(config.terminals);
|
|
14566
|
-
const sideReport = validateTaskSides({
|
|
14567
|
-
index: sideIndex,
|
|
14568
|
-
tasks: rendered.assigned.map((item)=>{
|
|
14569
|
-
const planned = plan.tasks.find((task)=>task.name === item.name);
|
|
14570
|
-
return {
|
|
14571
|
-
id: item.id,
|
|
14572
|
-
scope: planned?.scope ?? '',
|
|
14573
|
-
terminal: planned?.terminal ?? ''
|
|
14574
|
-
};
|
|
14575
|
-
})
|
|
14576
|
-
});
|
|
14577
|
-
const conflicts = sideReport.issues.filter((issue)=>'error' === issue.level);
|
|
14578
|
-
if (conflicts.length > 0) throw new errors_CliError(`任务类型与执行终端归属不一致,已中止:\n${conflicts.map((issue)=>` · ${issue.message}`).join('\n')}`, errors_EXIT.INVALID);
|
|
14579
|
-
const sideSkippedNote = sideReport.skipped > 0 ? `本机执行终端配置未覆盖 ${sideReport.skipped} 个任务,其「所属端 vs 仓库」未校验` + (0 === Object.keys(config.terminals).length ? '(terminals 为空)' : '') : null;
|
|
14580
|
-
if (0 === rendered.assigned.length && rendered.markdown === original) {
|
|
14581
|
-
if ('json' === format) printJson({
|
|
14582
|
-
ok: true,
|
|
14583
|
-
changed: false,
|
|
14584
|
-
file: targetFile,
|
|
14585
|
-
changes: [],
|
|
14586
|
-
assigned: []
|
|
14587
|
-
});
|
|
14588
|
-
else printLine('计划中的需求与任务都已存在,未做修改');
|
|
14589
|
-
return;
|
|
14590
|
-
}
|
|
14591
|
-
if ('diff' === mode || true === options.dryRun) {
|
|
15156
|
+
const baseLayout = layoutOf(config);
|
|
15157
|
+
const layout = void 0 === options.docsRoot ? baseLayout : {
|
|
15158
|
+
...baseLayout,
|
|
15159
|
+
root: external_node_path_resolve(options.docsRoot)
|
|
15160
|
+
};
|
|
15161
|
+
const schema = loadDocSchema(layout.root);
|
|
15162
|
+
const roles = Object.keys(schema.roles);
|
|
15163
|
+
const explicitRole = (options.role ?? '').trim();
|
|
15164
|
+
if (explicitRole.length > 0 && !roles.includes(explicitRole)) throw new errors_CliError(`--role 只能是 ${roles.join(' / ')}:${explicitRole}`, errors_EXIT.USAGE);
|
|
15165
|
+
const targets = resolveTargets(options, layout);
|
|
15166
|
+
if (0 === targets.length) {
|
|
15167
|
+
const scope = true === options.staged ? '暂存区' : void 0 === options.base ? '迭代根' : `${options.base}...HEAD`;
|
|
14592
15168
|
if ('json' === format) printJson({
|
|
14593
15169
|
ok: true,
|
|
14594
|
-
|
|
14595
|
-
|
|
14596
|
-
|
|
14597
|
-
|
|
14598
|
-
|
|
14599
|
-
|
|
15170
|
+
scope,
|
|
15171
|
+
iterations: [],
|
|
15172
|
+
summary: {
|
|
15173
|
+
iterations: 0,
|
|
15174
|
+
documents: 0,
|
|
15175
|
+
errors: 0,
|
|
15176
|
+
warnings: 0
|
|
15177
|
+
},
|
|
15178
|
+
documents: []
|
|
14600
15179
|
});
|
|
14601
|
-
else {
|
|
14602
|
-
printLine(`将写入:${targetFile}`);
|
|
14603
|
-
for (const change of rendered.changes)printLine(` · ${change}`);
|
|
14604
|
-
if (!exists) printLine('(文件不存在,将新建完整文档)');
|
|
14605
|
-
printLine('diff' === mode ? '\n(diff:未实际写入)' : '\n(--dry-run,未实际写入)');
|
|
14606
|
-
}
|
|
15180
|
+
else printLine(`${scope} 没有涉及任何迭代,无需校验`);
|
|
14607
15181
|
return;
|
|
14608
15182
|
}
|
|
14609
|
-
|
|
15183
|
+
const developerFilter = (options.developer ?? '').trim();
|
|
15184
|
+
const entries = targets.flatMap((relPath)=>validateIteration({
|
|
15185
|
+
layout,
|
|
15186
|
+
relPath,
|
|
15187
|
+
schema,
|
|
15188
|
+
explicitRole,
|
|
15189
|
+
developerFilter
|
|
15190
|
+
}));
|
|
15191
|
+
const errorCount = entries.reduce((sum, entry)=>sum + entry.errors.length, 0);
|
|
15192
|
+
const warningCount = entries.reduce((sum, entry)=>sum + entry.warnings.length, 0);
|
|
15193
|
+
const ok = 0 === errorCount;
|
|
15194
|
+
if ('json' === format) printJson({
|
|
15195
|
+
ok,
|
|
15196
|
+
iterations: targets,
|
|
15197
|
+
summary: {
|
|
15198
|
+
iterations: targets.length,
|
|
15199
|
+
documents: entries.length,
|
|
15200
|
+
errors: errorCount,
|
|
15201
|
+
warnings: warningCount
|
|
15202
|
+
},
|
|
15203
|
+
documents: entries
|
|
15204
|
+
});
|
|
15205
|
+
else {
|
|
15206
|
+
const byIteration = new Map();
|
|
15207
|
+
for (const entry of entries){
|
|
15208
|
+
const list = byIteration.get(entry.iteration) ?? [];
|
|
15209
|
+
list.push(entry);
|
|
15210
|
+
byIteration.set(entry.iteration, list);
|
|
15211
|
+
}
|
|
15212
|
+
for (const [iteration, items] of byIteration){
|
|
15213
|
+
printLine(`迭代:${iteration}`);
|
|
15214
|
+
for (const entry of items){
|
|
15215
|
+
const role = entry.role ?? '未识别';
|
|
15216
|
+
const mark = entry.valid ? '✓' : '✗';
|
|
15217
|
+
const stats = null === entry.stats ? '' : ` 需求 ${entry.stats.requirements} / 任务 ${entry.stats.tasks}(已完成 ${entry.stats.completedTasks}) / 详情 ${entry.stats.details}`;
|
|
15218
|
+
printLine(` ${mark} ${entry.developer}(${role})${stats}`);
|
|
15219
|
+
for (const issue of entry.errors)printLine(` [error] ${issue.code}:${issue.message}`);
|
|
15220
|
+
for (const issue of entry.warnings)printLine(` [warn ] ${issue.code}:${issue.message}`);
|
|
15221
|
+
}
|
|
15222
|
+
printLine('');
|
|
15223
|
+
}
|
|
15224
|
+
printLine(ok ? `校验通过:${targets.length} 个迭代 / ${entries.length} 份文档${warningCount > 0 ? `,${warningCount} 条 warning` : ''}` : `校验未通过:${errorCount} 个 error(${entries.filter((entry)=>!entry.valid).length}/${entries.length} 份文档)`);
|
|
15225
|
+
}
|
|
15226
|
+
if (!ok) process.exitCode = errors_EXIT.INVALID;
|
|
15227
|
+
}
|
|
15228
|
+
function registerDocValidate(doc) {
|
|
15229
|
+
doc.command('validate').description('校验迭代任务文档(只读;替代文档仓库的 validate_task_doc.py)').option('-i, --iteration <name>', '迭代目录名(可写「年份/迭代名」)').option('--all', '校验迭代根下的全部迭代').option('--staged', '只校验暂存区改动涉及的迭代(pre-commit 用)').option('--base <ref>', '只校验 <ref>...HEAD 改动涉及的迭代(CI 用)').option('-d, --developer <id>', '只校验指定成员文档(省略时校验整个迭代)').option('--role <role>', '校验角色(取值来自 schema.roles;默认从文档「负责范围」推断)').option('-c, --config <path>', '指定配置文件路径').option('--docs-root <path>', '覆盖配置里的文档仓库路径(pre-commit / CI 用)').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
|
|
15230
|
+
runDocValidate(options);
|
|
15231
|
+
});
|
|
15232
|
+
}
|
|
15233
|
+
const TEMPLATE_DIR = 'skills/iteration-task-docs/references';
|
|
15234
|
+
const STATUS_RULES = 'status-rules.md';
|
|
15235
|
+
const DETAIL_PREFIX = 'detail-fields-';
|
|
15236
|
+
const COMMON_BLOCKS = [
|
|
15237
|
+
'iteration-fields',
|
|
15238
|
+
'requirement-headers',
|
|
15239
|
+
'task-headers',
|
|
15240
|
+
'enums-requirement',
|
|
15241
|
+
'enums-task',
|
|
15242
|
+
'task-types'
|
|
15243
|
+
];
|
|
15244
|
+
const OPTIONAL_BLOCKS = new Set([
|
|
15245
|
+
'enums-table'
|
|
15246
|
+
]);
|
|
15247
|
+
const KNOWN_BLOCKS = new Set([
|
|
15248
|
+
...COMMON_BLOCKS,
|
|
15249
|
+
'enums-table',
|
|
15250
|
+
'enums-table-doc'
|
|
15251
|
+
]);
|
|
15252
|
+
function enumDisplay(item) {
|
|
15253
|
+
return void 0 === item.display || 0 === item.display.length ? item.values.join('、') : item.display;
|
|
15254
|
+
}
|
|
15255
|
+
function templateFiles(schema) {
|
|
15256
|
+
return Object.keys(schema.roles).map((role)=>({
|
|
15257
|
+
role,
|
|
15258
|
+
file: `${role}.md`
|
|
15259
|
+
}));
|
|
15260
|
+
}
|
|
15261
|
+
function requiredBlocks(schema, role) {
|
|
15262
|
+
const scopes = schema.roles[role]?.scopeRequires ?? [];
|
|
15263
|
+
return [
|
|
15264
|
+
...COMMON_BLOCKS,
|
|
15265
|
+
...scopes.map((scope)=>`${DETAIL_PREFIX}${scope}`)
|
|
15266
|
+
];
|
|
15267
|
+
}
|
|
15268
|
+
function blockBegin(name) {
|
|
15269
|
+
return `<!-- BEGIN GENERATED:${name} -->`;
|
|
15270
|
+
}
|
|
15271
|
+
function blockEnd(name) {
|
|
15272
|
+
return `<!-- END GENERATED:${name} -->`;
|
|
15273
|
+
}
|
|
15274
|
+
function findBlocks(text) {
|
|
15275
|
+
const names = [];
|
|
15276
|
+
const pattern = /<\x21-- BEGIN GENERATED:([^ ]+) --\x3e/g;
|
|
15277
|
+
let matched = pattern.exec(text);
|
|
15278
|
+
while(null !== matched){
|
|
15279
|
+
const name = matched[1] ?? '';
|
|
15280
|
+
if (name.length > 0 && !names.includes(name)) names.push(name);
|
|
15281
|
+
matched = pattern.exec(text);
|
|
15282
|
+
}
|
|
15283
|
+
return names;
|
|
15284
|
+
}
|
|
15285
|
+
function extractBlock(text, name) {
|
|
15286
|
+
const begin = blockBegin(name);
|
|
15287
|
+
const end = blockEnd(name);
|
|
15288
|
+
const start = text.indexOf(begin);
|
|
15289
|
+
if (start < 0) return null;
|
|
15290
|
+
const stop = text.indexOf(end, start + begin.length);
|
|
15291
|
+
if (stop < 0) return null;
|
|
15292
|
+
return text.slice(start + begin.length, stop).replace(/^\n+/, '').replace(/\n+$/, '');
|
|
15293
|
+
}
|
|
15294
|
+
function replaceBlock(text, name, body) {
|
|
15295
|
+
const begin = blockBegin(name);
|
|
15296
|
+
const end = blockEnd(name);
|
|
15297
|
+
const start = text.indexOf(begin);
|
|
15298
|
+
if (start < 0) return text;
|
|
15299
|
+
const stop = text.indexOf(end, start + begin.length);
|
|
15300
|
+
if (stop < 0) return text;
|
|
15301
|
+
return `${text.slice(0, start)}${begin}\n${body}\n${end}${text.slice(stop + end.length)}`;
|
|
15302
|
+
}
|
|
15303
|
+
function renderIterationFields(schema, role) {
|
|
15304
|
+
return schema.iterationFieldItems.map((item)=>{
|
|
15305
|
+
const value = 'scope' === item.key ? `<${role}>` : void 0 !== item.placeholder && item.placeholder.length > 0 ? item.placeholder : `<${item.label}>`;
|
|
15306
|
+
return `| ${item.label} | ${value} |`;
|
|
15307
|
+
}).join('\n');
|
|
15308
|
+
}
|
|
15309
|
+
function renderHeaders(headers) {
|
|
15310
|
+
return [
|
|
15311
|
+
`| ${headers.join(' | ')} |`,
|
|
15312
|
+
`| ${headers.map(()=>'---').join(' | ')} |`
|
|
15313
|
+
].join('\n');
|
|
15314
|
+
}
|
|
15315
|
+
function renderDetailFields(schema, scope) {
|
|
15316
|
+
const role = roleOfScope(schema, scope);
|
|
15317
|
+
if (null === role) throw new errors_CliError(`schema.roles 中找不到所属端「${scope}」对应的角色`, errors_EXIT.INVALID);
|
|
15318
|
+
const decls = schema.roles[role]?.detailFieldItems ?? [];
|
|
15319
|
+
return decls.map((field)=>{
|
|
15320
|
+
const items = field.placeholderItems;
|
|
15321
|
+
if (void 0 !== items && items.length > 0) return [
|
|
15322
|
+
`- **${field.name}**:`,
|
|
15323
|
+
...items.map((item)=>` - ${item}`)
|
|
15324
|
+
].join('\n');
|
|
15325
|
+
const placeholder = void 0 !== field.placeholder && field.placeholder.length > 0 ? field.placeholder : '<待补充>';
|
|
15326
|
+
return `- **${field.name}**:${placeholder}`;
|
|
15327
|
+
}).join('\n');
|
|
15328
|
+
}
|
|
15329
|
+
function renderEnumsRequirement(schema) {
|
|
15330
|
+
const first = schema.enumItems[0];
|
|
15331
|
+
return void 0 === first ? '' : `- **${first.label}**:${enumDisplay(first)}`;
|
|
15332
|
+
}
|
|
15333
|
+
function renderEnumsTask(schema, role) {
|
|
15334
|
+
const wanted = new Set([
|
|
15335
|
+
'selfTest',
|
|
15336
|
+
'acceptance',
|
|
15337
|
+
'taskStatus'
|
|
15338
|
+
]);
|
|
15339
|
+
const lines = schema.enumItems.filter((item)=>wanted.has(item.key)).map((item)=>`- **${item.label}**:${enumDisplay(item)}`);
|
|
15340
|
+
lines.push(`- **任务类型**:${taskTypesOf(schema, role).join('、')}`);
|
|
15341
|
+
return lines.join('\n');
|
|
15342
|
+
}
|
|
15343
|
+
function renderEnumsTable(schema, role) {
|
|
15344
|
+
const lines = [
|
|
15345
|
+
'| 维度 | 允许值 |',
|
|
15346
|
+
'| --- | --- |'
|
|
15347
|
+
];
|
|
15348
|
+
for (const item of schema.enumItems){
|
|
15349
|
+
const values = enumDisplay(item).split('、').map((value)=>`\`${value}\``).join('、');
|
|
15350
|
+
lines.push(`| ${item.label} | ${values} |`);
|
|
15351
|
+
}
|
|
15352
|
+
const types = taskTypesOf(schema, role).map((name)=>`\`${name}\``).join('、');
|
|
15353
|
+
lines.push(`| 任务类型 | ${types} |`);
|
|
15354
|
+
return lines.join('\n');
|
|
15355
|
+
}
|
|
15356
|
+
function renderEnumsTableDoc(schema) {
|
|
15357
|
+
const lines = [
|
|
15358
|
+
'| 维度 | 允许值 | 说明 |',
|
|
15359
|
+
'| --- | --- | --- |'
|
|
15360
|
+
];
|
|
15361
|
+
for (const item of schema.enumItems){
|
|
15362
|
+
const source = void 0 === item.display || 0 === item.display.length ? item.values : enumDisplay(item).split('、');
|
|
15363
|
+
const cells = source.map((value)=>`\`${value}\``).join('、');
|
|
15364
|
+
lines.push(`| ${item.label} | ${cells} | ${item.desc} |`);
|
|
15365
|
+
}
|
|
15366
|
+
lines.push('| 任务类型 | 前端/后端各自枚举 | 见 `frontend.md`、`backend.md` |');
|
|
15367
|
+
return lines.join('\n');
|
|
15368
|
+
}
|
|
15369
|
+
function renderTaskTypes(schema, role) {
|
|
15370
|
+
if (void 0 === schema.roles[role]) throw new errors_CliError(`schema.roles 中缺少角色:${role}`, errors_EXIT.INVALID);
|
|
15371
|
+
const sideLabel = {
|
|
15372
|
+
both: '通用',
|
|
15373
|
+
frontend: '前端',
|
|
15374
|
+
backend: '后端'
|
|
15375
|
+
};
|
|
15376
|
+
const descriptions = new Map(schema.taskTypeItems.map((item)=>[
|
|
15377
|
+
item.name,
|
|
15378
|
+
item.desc
|
|
15379
|
+
]));
|
|
15380
|
+
const names = [
|
|
15381
|
+
...taskTypesOf(schema, role)
|
|
15382
|
+
];
|
|
15383
|
+
names.sort((left, right)=>{
|
|
15384
|
+
const leftBoth = 'both' === sideOfTypeName(schema, left) ? 0 : 1;
|
|
15385
|
+
const rightBoth = 'both' === sideOfTypeName(schema, right) ? 0 : 1;
|
|
15386
|
+
return leftBoth - rightBoth;
|
|
15387
|
+
});
|
|
15388
|
+
const lines = [
|
|
15389
|
+
'| 类型 | 适用场景 | 归属 |',
|
|
15390
|
+
'| --- | --- | --- |'
|
|
15391
|
+
];
|
|
15392
|
+
for (const name of names){
|
|
15393
|
+
const side = sideOfTypeName(schema, name);
|
|
15394
|
+
const label = null === side ? '' : sideLabel[side] ?? side;
|
|
15395
|
+
lines.push(`| \`${name}\` | ${descriptions.get(name) ?? ''} | ${label} |`);
|
|
15396
|
+
}
|
|
15397
|
+
return lines.join('\n');
|
|
15398
|
+
}
|
|
15399
|
+
function renderBlock(schema, name, role) {
|
|
15400
|
+
if (name.startsWith(DETAIL_PREFIX)) return renderDetailFields(schema, name.slice(DETAIL_PREFIX.length));
|
|
15401
|
+
switch(name){
|
|
15402
|
+
case 'iteration-fields':
|
|
15403
|
+
return renderIterationFields(schema, role);
|
|
15404
|
+
case 'requirement-headers':
|
|
15405
|
+
return renderHeaders(schema.requirementHeaders);
|
|
15406
|
+
case 'task-headers':
|
|
15407
|
+
return renderHeaders(schema.taskHeaders);
|
|
15408
|
+
case 'enums-requirement':
|
|
15409
|
+
return renderEnumsRequirement(schema);
|
|
15410
|
+
case 'enums-task':
|
|
15411
|
+
return renderEnumsTask(schema, role);
|
|
15412
|
+
case 'enums-table':
|
|
15413
|
+
return renderEnumsTable(schema, role);
|
|
15414
|
+
case 'enums-table-doc':
|
|
15415
|
+
return renderEnumsTableDoc(schema);
|
|
15416
|
+
case 'task-types':
|
|
15417
|
+
return renderTaskTypes(schema, role);
|
|
15418
|
+
default:
|
|
15419
|
+
throw new errors_CliError(`未知生成区:${name}(可用:${[
|
|
15420
|
+
...KNOWN_BLOCKS
|
|
15421
|
+
].join('、')} 或 ${DETAIL_PREFIX}<端>)`, errors_EXIT.INVALID);
|
|
15422
|
+
}
|
|
15423
|
+
}
|
|
15424
|
+
function templatePath(docsRoot, file) {
|
|
15425
|
+
return external_node_path_join(docsRoot, TEMPLATE_DIR, file);
|
|
15426
|
+
}
|
|
15427
|
+
function checkTemplates(docsRoot, schema) {
|
|
15428
|
+
const result = {
|
|
15429
|
+
problems: [],
|
|
15430
|
+
outdated: [],
|
|
15431
|
+
written: []
|
|
15432
|
+
};
|
|
15433
|
+
for (const { role, file } of templateFiles(schema)){
|
|
15434
|
+
const path = templatePath(docsRoot, file);
|
|
15435
|
+
if (!external_node_fs_existsSync(path)) {
|
|
15436
|
+
result.problems.push(`${file}:文件不存在(${path})`);
|
|
15437
|
+
continue;
|
|
15438
|
+
}
|
|
15439
|
+
const text = readFileSync(path, 'utf8');
|
|
15440
|
+
const headings = new Set(text.split(/\r?\n/).filter((line)=>line.startsWith('## ')).map((line)=>line.slice(3).trim()));
|
|
15441
|
+
for (const section of schema.sections)if (!headings.has(section)) result.problems.push(`${file}:缺少必需章节「${section}」`);
|
|
15442
|
+
const present = findBlocks(text);
|
|
15443
|
+
for (const block of requiredBlocks(schema, role))if (!present.includes(block)) result.problems.push(`${file}:缺少生成区「${block}」`);
|
|
15444
|
+
for (const block of present){
|
|
15445
|
+
const known = KNOWN_BLOCKS.has(block) || block.startsWith(DETAIL_PREFIX);
|
|
15446
|
+
if (!known) {
|
|
15447
|
+
result.problems.push(`${file}:未知生成区「${block}」(可用:${[
|
|
15448
|
+
...KNOWN_BLOCKS
|
|
15449
|
+
].join('、')} 或 ${DETAIL_PREFIX}<端>)`);
|
|
15450
|
+
continue;
|
|
15451
|
+
}
|
|
15452
|
+
if (OPTIONAL_BLOCKS.has(block) && !present.includes(block)) continue;
|
|
15453
|
+
let expected;
|
|
15454
|
+
try {
|
|
15455
|
+
expected = renderBlock(schema, block, role);
|
|
15456
|
+
} catch (error) {
|
|
15457
|
+
result.problems.push(`${file}:${block} 渲染失败(${error instanceof Error ? error.message : String(error)})`);
|
|
15458
|
+
continue;
|
|
15459
|
+
}
|
|
15460
|
+
const actual = extractBlock(text, block);
|
|
15461
|
+
if (null === actual) {
|
|
15462
|
+
result.problems.push(`${file}:生成区「${block}」缺少结束标记`);
|
|
15463
|
+
continue;
|
|
15464
|
+
}
|
|
15465
|
+
if (actual.trim() !== expected.trim()) result.outdated.push(`${file}#${block}`);
|
|
15466
|
+
}
|
|
15467
|
+
}
|
|
15468
|
+
const rulesPath = templatePath(docsRoot, STATUS_RULES);
|
|
15469
|
+
if (external_node_fs_existsSync(rulesPath)) {
|
|
15470
|
+
const text = readFileSync(rulesPath, 'utf8');
|
|
15471
|
+
const actual = extractBlock(text, 'enums-table-doc');
|
|
15472
|
+
if (null === actual) result.problems.push(`${STATUS_RULES}:缺少生成区「enums-table-doc」`);
|
|
15473
|
+
else if (actual.trim() !== renderBlock(schema, 'enums-table-doc', 'frontend').trim()) result.outdated.push(`${STATUS_RULES}#enums-table-doc`);
|
|
15474
|
+
}
|
|
15475
|
+
return result;
|
|
15476
|
+
}
|
|
15477
|
+
function writeTemplates(docsRoot, schema) {
|
|
15478
|
+
const result = {
|
|
15479
|
+
problems: [],
|
|
15480
|
+
outdated: [],
|
|
15481
|
+
written: []
|
|
15482
|
+
};
|
|
15483
|
+
const targets = [
|
|
15484
|
+
...templateFiles(schema).map(({ role, file })=>({
|
|
15485
|
+
role,
|
|
15486
|
+
file
|
|
15487
|
+
})),
|
|
15488
|
+
{
|
|
15489
|
+
role: 'frontend',
|
|
15490
|
+
file: STATUS_RULES
|
|
15491
|
+
}
|
|
15492
|
+
];
|
|
15493
|
+
for (const { role, file } of targets){
|
|
15494
|
+
const path = templatePath(docsRoot, file);
|
|
15495
|
+
if (!external_node_fs_existsSync(path)) {
|
|
15496
|
+
result.problems.push(`${file}:文件不存在(${path})`);
|
|
15497
|
+
continue;
|
|
15498
|
+
}
|
|
15499
|
+
const original = readFileSync(path, 'utf8');
|
|
15500
|
+
const blocks = findBlocks(original);
|
|
15501
|
+
if (0 === blocks.length) {
|
|
15502
|
+
result.problems.push(`${file}:未找到任何生成区标记`);
|
|
15503
|
+
continue;
|
|
15504
|
+
}
|
|
15505
|
+
let updated = original;
|
|
15506
|
+
for (const block of blocks)try {
|
|
15507
|
+
updated = replaceBlock(updated, block, renderBlock(schema, block, role));
|
|
15508
|
+
} catch (error) {
|
|
15509
|
+
result.problems.push(`${file}:${block} 渲染失败(${error instanceof Error ? error.message : String(error)})`);
|
|
15510
|
+
}
|
|
15511
|
+
if (updated !== original) {
|
|
15512
|
+
result.written.push(file);
|
|
15513
|
+
writeFileSync(path, updated, 'utf8');
|
|
15514
|
+
}
|
|
15515
|
+
}
|
|
15516
|
+
return result;
|
|
15517
|
+
}
|
|
15518
|
+
function runDocTemplate(options) {
|
|
15519
|
+
const format = parseFormat(options.format);
|
|
15520
|
+
enableJsonErrors('json' === format);
|
|
15521
|
+
const loaded = config_loadConfig(options.config);
|
|
15522
|
+
if (!loaded.exists || null === loaded.config) throw new errors_CliError(`配置未初始化:${loaded.path}\n请先运行:ylcwf init`, errors_EXIT.NOT_FOUND);
|
|
15523
|
+
const baseLayout = layoutOf(loaded.config);
|
|
15524
|
+
const root = void 0 === options.docsRoot ? baseLayout.root : external_node_path_resolve(options.docsRoot);
|
|
15525
|
+
const schema = loadDocSchema(root);
|
|
15526
|
+
const write = true === options.write;
|
|
15527
|
+
const result = write ? writeTemplates(root, schema) : checkTemplates(root, schema);
|
|
15528
|
+
const ok = 0 === result.problems.length && (write || 0 === result.outdated.length);
|
|
15529
|
+
if ('json' === format) printJson({
|
|
15530
|
+
ok,
|
|
15531
|
+
mode: write ? 'write' : 'check',
|
|
15532
|
+
problems: result.problems,
|
|
15533
|
+
outdated: result.outdated,
|
|
15534
|
+
written: result.written
|
|
15535
|
+
});
|
|
15536
|
+
else if (result.problems.length > 0) {
|
|
15537
|
+
printLine('✗ 模板与 schema.json 不一致:');
|
|
15538
|
+
for (const problem of result.problems)printLine(` · ${problem}`);
|
|
15539
|
+
if (result.outdated.length > 0) {
|
|
15540
|
+
printLine('');
|
|
15541
|
+
printLine(` 生成区待刷新:${result.outdated.join('、')}`);
|
|
15542
|
+
printLine(' 执行 ylcwf doc template --write 重新生成');
|
|
15543
|
+
}
|
|
15544
|
+
} else if (write) printLine(0 === result.written.length ? '✓ 模板生成区已是 schema.json 的最新状态' : `✓ 已按 schema.json 重写:${result.written.join('、')}`);
|
|
15545
|
+
else if (result.outdated.length > 0) {
|
|
15546
|
+
printLine(`✗ 以下模板的生成区与 schema.json 不一致:${result.outdated.join('、')}`);
|
|
15547
|
+
printLine(' 执行 ylcwf doc template --write 重新生成');
|
|
15548
|
+
} else printLine('✓ 模板与 schema.json 一致(章节 + 生成区)');
|
|
15549
|
+
if (!ok) process.exitCode = errors_EXIT.INVALID;
|
|
15550
|
+
}
|
|
15551
|
+
function registerDocTemplate(doc) {
|
|
15552
|
+
doc.command('template').description('按 schema.json 校验或重写结构模板(替代 render_template / check_schema_sync)').option('--check', '只比对,不写盘(默认)').option('--write', '按 schema.json 重写模板的生成区').option('-c, --config <path>', '指定配置文件路径').option('--docs-root <path>', '覆盖配置里的文档仓库路径(pre-commit / CI 用)').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
|
|
15553
|
+
if (true === options.check && true === options.write) throw new errors_CliError('--check 与 --write 只能选一个', errors_EXIT.USAGE);
|
|
15554
|
+
runDocTemplate(options);
|
|
15555
|
+
});
|
|
15556
|
+
}
|
|
15557
|
+
function doc_nowStamp() {
|
|
15558
|
+
const now = new Date();
|
|
15559
|
+
const pad = (value)=>String(value).padStart(2, '0');
|
|
15560
|
+
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
|
|
15561
|
+
}
|
|
15562
|
+
function readPlanFile(path) {
|
|
15563
|
+
if (!external_node_fs_existsSync(path)) throw new errors_CliError(`plan 文件不存在:${path}`, errors_EXIT.NOT_FOUND);
|
|
15564
|
+
const text = readFileSync(path, 'utf8');
|
|
15565
|
+
try {
|
|
15566
|
+
return JSON.parse(text);
|
|
15567
|
+
} catch (error) {
|
|
15568
|
+
throw new errors_CliError(`plan 文件不是合法 JSON:${error instanceof Error ? error.message : String(error)}`, errors_EXIT.INVALID);
|
|
15569
|
+
}
|
|
15570
|
+
}
|
|
15571
|
+
function runDocApply(options, mode = 'apply') {
|
|
15572
|
+
const format = parseFormat(options.format);
|
|
15573
|
+
const loaded = config_loadConfig(options.config);
|
|
15574
|
+
if (!loaded.exists || null === loaded.config) throw new errors_CliError(`配置未初始化:${loaded.path}\n请先运行:ylcwf init`, errors_EXIT.NOT_FOUND);
|
|
15575
|
+
const config = loaded.config;
|
|
15576
|
+
const docsRoot = config.docs.root;
|
|
15577
|
+
const layout = layoutOf(config);
|
|
15578
|
+
const developer = config.profile.developer;
|
|
15579
|
+
const role = config.profile.role;
|
|
15580
|
+
const requested = options.iteration.trim();
|
|
15581
|
+
if (0 === requested.length) throw new errors_CliError('必须指定迭代目录:--iteration <迭代>', errors_EXIT.USAGE);
|
|
15582
|
+
const resolvedIteration = requireIterationDir(docsRoot, layout.iterationsRoot, requested);
|
|
15583
|
+
const iteration = resolvedIteration.name;
|
|
15584
|
+
const schema = loadDocSchema(docsRoot);
|
|
15585
|
+
const plan = parseDocPlan(readPlanFile(options.input), schema, role);
|
|
15586
|
+
const targetDir = resolvedIteration.dir;
|
|
15587
|
+
const targetFile = external_node_path_join(targetDir, `${developer}.md`);
|
|
15588
|
+
const exists = external_node_fs_existsSync(targetFile);
|
|
15589
|
+
const original = exists ? readFileSync(targetFile, 'utf8') : null;
|
|
15590
|
+
const mtime = exists ? statSync(targetFile).mtimeMs : 0;
|
|
15591
|
+
const parsed = null === original ? {
|
|
15592
|
+
requirements: [],
|
|
15593
|
+
tasks: []
|
|
15594
|
+
} : parseMarkdownDoc(original, schema);
|
|
15595
|
+
if (null !== original) {
|
|
15596
|
+
const documentRole = inferRole(original);
|
|
15597
|
+
if (null === documentRole) process.stderr.write(`提示:${resolvedIteration.relPath}/${developer}.md 的「负责范围」是「${readRoleText(original) || '(缺失)'}」,不是 ${DOC_ROLE_HINT}。\n 写入后的校验会因此跳过;请先把该行改成 ${role}(你的 profile.role)。\n`);
|
|
15598
|
+
else if (documentRole !== role) process.stderr.write(`提示:${resolvedIteration.relPath}/${developer}.md 的负责范围是「${documentRole}」,与当前角色「${role}」不一致。\n 写入后的校验按文档为准(${documentRole});要让文档与本机角色一致,请手工修改「负责范围」为 ${role}。\n`);
|
|
15599
|
+
}
|
|
15600
|
+
validatePlanReferences({
|
|
15601
|
+
plan,
|
|
15602
|
+
schema,
|
|
15603
|
+
role,
|
|
15604
|
+
index: buildRepoSideIndex(config.terminals),
|
|
15605
|
+
knownTaskIds: parsed.tasks.map((task)=>task.id),
|
|
15606
|
+
knownRequirements: parsed.requirements.map((item)=>item.id)
|
|
15607
|
+
});
|
|
15608
|
+
const stamp = doc_nowStamp();
|
|
15609
|
+
const rendered = renderPlan({
|
|
15610
|
+
schema,
|
|
15611
|
+
role,
|
|
15612
|
+
plan,
|
|
15613
|
+
existing: {
|
|
15614
|
+
requirements: parsed.requirements,
|
|
15615
|
+
tasks: parsed.tasks,
|
|
15616
|
+
lines: null === original ? null : original.split('\n')
|
|
15617
|
+
},
|
|
15618
|
+
stamp,
|
|
15619
|
+
developer,
|
|
15620
|
+
aggregate: aggregateRequirement
|
|
15621
|
+
});
|
|
15622
|
+
const sideIndex = buildRepoSideIndex(config.terminals);
|
|
15623
|
+
const sideReport = validateTaskSides({
|
|
15624
|
+
index: sideIndex,
|
|
15625
|
+
tasks: rendered.assigned.map((item)=>{
|
|
15626
|
+
const planned = plan.tasks.find((task)=>task.name === item.name);
|
|
15627
|
+
return {
|
|
15628
|
+
id: item.id,
|
|
15629
|
+
scope: planned?.scope ?? '',
|
|
15630
|
+
terminal: planned?.terminal ?? ''
|
|
15631
|
+
};
|
|
15632
|
+
})
|
|
15633
|
+
});
|
|
15634
|
+
const conflicts = sideReport.issues.filter((issue)=>'error' === issue.level);
|
|
15635
|
+
if (conflicts.length > 0) throw new errors_CliError(`任务类型与执行终端归属不一致,已中止:\n${conflicts.map((issue)=>` · ${issue.message}`).join('\n')}`, errors_EXIT.INVALID);
|
|
15636
|
+
const sideSkippedNote = sideReport.skipped > 0 ? `本机执行终端配置未覆盖 ${sideReport.skipped} 个任务,其「所属端 vs 仓库」未校验` + (0 === Object.keys(config.terminals).length ? '(terminals 为空)' : '') : null;
|
|
15637
|
+
if (0 === rendered.assigned.length && rendered.markdown === original) {
|
|
15638
|
+
if ('json' === format) printJson({
|
|
15639
|
+
ok: true,
|
|
15640
|
+
changed: false,
|
|
15641
|
+
file: targetFile,
|
|
15642
|
+
changes: [],
|
|
15643
|
+
assigned: []
|
|
15644
|
+
});
|
|
15645
|
+
else printLine('计划中的需求与任务都已存在,未做修改');
|
|
15646
|
+
return;
|
|
15647
|
+
}
|
|
15648
|
+
if ('diff' === mode || true === options.dryRun) {
|
|
15649
|
+
if ('json' === format) printJson({
|
|
15650
|
+
ok: true,
|
|
15651
|
+
dryRun: true,
|
|
15652
|
+
mode,
|
|
15653
|
+
file: targetFile,
|
|
15654
|
+
changes: rendered.changes,
|
|
15655
|
+
assigned: rendered.assigned,
|
|
15656
|
+
preview: rendered.markdown
|
|
15657
|
+
});
|
|
15658
|
+
else {
|
|
15659
|
+
printLine(`将写入:${targetFile}`);
|
|
15660
|
+
for (const change of rendered.changes)printLine(` · ${change}`);
|
|
15661
|
+
if (!exists) printLine('(文件不存在,将新建完整文档)');
|
|
15662
|
+
printLine('diff' === mode ? '\n(diff:未实际写入)' : '\n(--dry-run,未实际写入)');
|
|
15663
|
+
}
|
|
15664
|
+
return;
|
|
15665
|
+
}
|
|
15666
|
+
if (exists && statSync(targetFile).mtimeMs !== mtime) throw new errors_CliError('文件已被外部修改,请重试', errors_EXIT.INVALID);
|
|
14610
15667
|
assertWritableBranch(docsRoot);
|
|
14611
15668
|
mkdirSync(targetDir, {
|
|
14612
15669
|
recursive: true
|
|
@@ -14618,10 +15675,14 @@ function runDocApply(options, mode = 'apply') {
|
|
|
14618
15675
|
else writeFileSync(targetFile, original, 'utf8');
|
|
14619
15676
|
throw new errors_CliError(message, errors_EXIT.INVALID);
|
|
14620
15677
|
};
|
|
14621
|
-
|
|
15678
|
+
const strict = strictValidationEnabled();
|
|
15679
|
+
if ('violation' === outcome.kind) {
|
|
15680
|
+
if (strict) rollback(`写入未通过文档校验,已回滚:${outcome.message}`);
|
|
15681
|
+
process.stderr.write(`警告:写入未通过文档校验(docs.validator.strict=false):${outcome.message}\n`);
|
|
15682
|
+
}
|
|
14622
15683
|
if ('unavailable' === outcome.kind) {
|
|
14623
|
-
if (
|
|
14624
|
-
process.stderr.write(`警告:${outcome.reason};本次写入未做文档校验(docs.validator.
|
|
15684
|
+
if (strict) rollback(`未执行文档校验,已回滚:${outcome.reason}\n如需在无法校验时仍写入(不推荐),可配置 docs.validator.strict: false`);
|
|
15685
|
+
process.stderr.write(`警告:${outcome.reason};本次写入未做文档校验(docs.validator.strict=false)\n`);
|
|
14625
15686
|
}
|
|
14626
15687
|
const remainingReport = checkDocTaskSides({
|
|
14627
15688
|
docsRoot,
|
|
@@ -14658,6 +15719,59 @@ function runDocApply(options, mode = 'apply') {
|
|
|
14658
15719
|
if (void 0 !== git) printLine(`\n${git.message}`);
|
|
14659
15720
|
}
|
|
14660
15721
|
}
|
|
15722
|
+
const FALLBACK_TASK_STATES = [
|
|
15723
|
+
'未开始',
|
|
15724
|
+
'进行中',
|
|
15725
|
+
'待验收',
|
|
15726
|
+
'已完成'
|
|
15727
|
+
];
|
|
15728
|
+
function readStdin() {
|
|
15729
|
+
if (true === process.stdin.isTTY) return '';
|
|
15730
|
+
try {
|
|
15731
|
+
return readFileSync(0, 'utf8');
|
|
15732
|
+
} catch {
|
|
15733
|
+
return '';
|
|
15734
|
+
}
|
|
15735
|
+
}
|
|
15736
|
+
function loadTaskStates(configPath) {
|
|
15737
|
+
try {
|
|
15738
|
+
const loaded = config_loadConfig(configPath);
|
|
15739
|
+
if (null === loaded.config) return FALLBACK_TASK_STATES;
|
|
15740
|
+
const root = loaded.config.docs.root.trim();
|
|
15741
|
+
if (0 === root.length) return FALLBACK_TASK_STATES;
|
|
15742
|
+
const values = loadDocSchema(root).enums.taskStatus;
|
|
15743
|
+
return values.length > 0 ? values : FALLBACK_TASK_STATES;
|
|
15744
|
+
} catch {
|
|
15745
|
+
return FALLBACK_TASK_STATES;
|
|
15746
|
+
}
|
|
15747
|
+
}
|
|
15748
|
+
function runDocAggregate(options) {
|
|
15749
|
+
const format = parseFormat(options.format);
|
|
15750
|
+
enableJsonErrors('json' === format);
|
|
15751
|
+
const raw = void 0 === options.input ? readStdin() : readFileSync(options.input, 'utf8');
|
|
15752
|
+
let input;
|
|
15753
|
+
try {
|
|
15754
|
+
input = 0 === raw.trim().length ? {} : JSON.parse(raw);
|
|
15755
|
+
} catch (error) {
|
|
15756
|
+
throw new errors_CliError(`入参不是合法 JSON:${error instanceof Error ? error.message : String(error)}`, errors_EXIT.USAGE);
|
|
15757
|
+
}
|
|
15758
|
+
if (!utils_isRecord(input)) throw new errors_CliError('入参需为 { 需求编号: [任务状态...] } 对象', errors_EXIT.USAGE);
|
|
15759
|
+
const allowed = loadTaskStates(options.config);
|
|
15760
|
+
const data = {};
|
|
15761
|
+
for (const [requirementId, statuses] of Object.entries(input)){
|
|
15762
|
+
if (!isStringArray(statuses)) throw new errors_CliError(`需求 ${requirementId} 的任务状态需为字符串数组`, errors_EXIT.USAGE);
|
|
15763
|
+
const unknown = statuses.filter((item)=>!allowed.includes(item));
|
|
15764
|
+
if (unknown.length > 0) throw new errors_CliError(`需求 ${requirementId} 含非法任务状态:${unknown.join('、')}(允许:${allowed.join('、')})`, errors_EXIT.USAGE);
|
|
15765
|
+
data[requirementId] = aggregateRequirement(statuses);
|
|
15766
|
+
}
|
|
15767
|
+
if ('json' === format) return void printJson({
|
|
15768
|
+
ok: true,
|
|
15769
|
+
data
|
|
15770
|
+
});
|
|
15771
|
+
const entries = Object.entries(data);
|
|
15772
|
+
if (0 === entries.length) return void printLine('入参为空,未计算任何需求');
|
|
15773
|
+
for (const [requirementId, item] of entries)printLine(`${requirementId} ${item.status} ${item.progress}%`);
|
|
15774
|
+
}
|
|
14661
15775
|
function registerDoc(program) {
|
|
14662
15776
|
const doc = program.command('doc').description('按结构化计划生成/追加迭代任务文档');
|
|
14663
15777
|
doc.command('diff').description('预览 plan.json 将产生的变更,不写盘').requiredOption('-i, --iteration <name>', '迭代目录名').requiredOption('--input <path>', 'plan.json 路径').option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
|
|
@@ -14666,6 +15780,11 @@ function registerDoc(program) {
|
|
|
14666
15780
|
doc.command('apply').description('把 plan.json 渲染进文档(新增需求与任务,已存在的不覆盖)').requiredOption('-i, --iteration <name>', '迭代目录名').requiredOption('--input <path>', 'plan.json 路径').option('--dry-run', '只打印将要发生的变更,不写盘').option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
|
|
14667
15781
|
runDocApply(options);
|
|
14668
15782
|
});
|
|
15783
|
+
doc.command('aggregate').description('按任务状态聚合需求状态与进度(stdin 传 { 需求编号: [任务状态] })').option('--input <path>', '从文件读取入参(省略时读 stdin)').option('-c, --config <path>', '指定配置文件路径(用于读取任务状态枚举)').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
|
|
15784
|
+
runDocAggregate(options);
|
|
15785
|
+
});
|
|
15786
|
+
registerDocValidate(doc);
|
|
15787
|
+
registerDocTemplate(doc);
|
|
14669
15788
|
registerDocMigrate(doc);
|
|
14670
15789
|
}
|
|
14671
15790
|
function resolveDeveloper(options, configured) {
|
|
@@ -14950,7 +16069,7 @@ function collectSideIssues(options) {
|
|
|
14950
16069
|
function runAction(action, taskId, options) {
|
|
14951
16070
|
const { docsRoot, layout, developer, policy } = requireWriteContext(options);
|
|
14952
16071
|
const iteration = options.iteration?.trim() ? resolveIterationName(options, layout, loadIterations(layout)) : resolveIterationName(options, layout, loadIterations(layout), {
|
|
14953
|
-
taskId: taskId
|
|
16072
|
+
taskId: normalizeTaskId(taskId)
|
|
14954
16073
|
});
|
|
14955
16074
|
const format = parseFormat(options.format);
|
|
14956
16075
|
if (true === options.dryRun) {
|
|
@@ -15025,7 +16144,7 @@ function parseDetailUpdates(sets, appends) {
|
|
|
15025
16144
|
function runDetail(taskId, options) {
|
|
15026
16145
|
const { docsRoot, layout, developer, policy } = requireWriteContext(options);
|
|
15027
16146
|
const iteration = options.iteration?.trim() ? resolveIterationName(options, layout, loadIterations(layout)) : resolveIterationName(options, layout, loadIterations(layout), {
|
|
15028
|
-
taskId: taskId
|
|
16147
|
+
taskId: normalizeTaskId(taskId)
|
|
15029
16148
|
});
|
|
15030
16149
|
const format = parseFormat(options.format);
|
|
15031
16150
|
const updates = parseDetailUpdates(options.set, options.append);
|
|
@@ -15034,7 +16153,7 @@ function runDetail(taskId, options) {
|
|
|
15034
16153
|
iterationsRoot: layout.iterationsRoot,
|
|
15035
16154
|
iteration,
|
|
15036
16155
|
developer,
|
|
15037
|
-
taskId: taskId
|
|
16156
|
+
taskId: normalizeTaskId(taskId),
|
|
15038
16157
|
updates,
|
|
15039
16158
|
policy
|
|
15040
16159
|
});
|
|
@@ -15050,7 +16169,7 @@ function runDetail(taskId, options) {
|
|
|
15050
16169
|
function runSelfTest(taskId, options) {
|
|
15051
16170
|
const { docsRoot, layout, developer, policy } = requireWriteContext(options);
|
|
15052
16171
|
const iteration = options.iteration?.trim() ? resolveIterationName(options, layout, loadIterations(layout)) : resolveIterationName(options, layout, loadIterations(layout), {
|
|
15053
|
-
taskId: taskId
|
|
16172
|
+
taskId: normalizeTaskId(taskId)
|
|
15054
16173
|
});
|
|
15055
16174
|
const format = parseFormat(options.format);
|
|
15056
16175
|
const result = options.result.trim();
|
|
@@ -15059,7 +16178,7 @@ function runSelfTest(taskId, options) {
|
|
|
15059
16178
|
iterationsRoot: layout.iterationsRoot,
|
|
15060
16179
|
iteration,
|
|
15061
16180
|
developer,
|
|
15062
|
-
taskId: taskId
|
|
16181
|
+
taskId: normalizeTaskId(taskId),
|
|
15063
16182
|
result,
|
|
15064
16183
|
reason: options.reason,
|
|
15065
16184
|
policy
|
|
@@ -15169,9 +16288,9 @@ function runList(options) {
|
|
|
15169
16288
|
function runShow(taskId, options) {
|
|
15170
16289
|
const ctx = requireQueryContext(options);
|
|
15171
16290
|
const iteration = resolveIterationName(options, ctx.layout, loadIterations(ctx.layout), {
|
|
15172
|
-
taskId: taskId
|
|
16291
|
+
taskId: normalizeTaskId(taskId)
|
|
15173
16292
|
});
|
|
15174
|
-
const target = taskId
|
|
16293
|
+
const target = normalizeTaskId(taskId);
|
|
15175
16294
|
const docs = loadDeveloperDocs(ctx.layout, iteration);
|
|
15176
16295
|
for (const { developer, doc } of docs){
|
|
15177
16296
|
const task = doc.validation.tasks.find((item)=>item.id === target);
|
|
@@ -15296,7 +16415,7 @@ function iteration_runShow(name, options) {
|
|
|
15296
16415
|
const progress = roundProgressPercent(item.stats.completedTasks, item.stats.tasks);
|
|
15297
16416
|
return [
|
|
15298
16417
|
item.id,
|
|
15299
|
-
item.roleInferred,
|
|
16418
|
+
item.roleInferred ?? '未写明',
|
|
15300
16419
|
String(item.stats.requirements),
|
|
15301
16420
|
`${item.stats.completedTasks}/${item.stats.tasks}`,
|
|
15302
16421
|
`${progress}%`,
|
|
@@ -15378,8 +16497,21 @@ function runContext(options) {
|
|
|
15378
16497
|
const tasks = buildTaskRows(selected);
|
|
15379
16498
|
const completedTasks = tasks.filter((task)=>'已完成' === task.status).length;
|
|
15380
16499
|
const info = selected[0]?.doc.validation.iterationInfo ?? {};
|
|
16500
|
+
const errors = selected.flatMap((item)=>item.doc.validation.errors);
|
|
16501
|
+
const warnings = selected.flatMap((item)=>item.doc.validation.warnings);
|
|
16502
|
+
const readyTasks = tasks.filter((task)=>task.ready).map((task)=>task.id);
|
|
16503
|
+
const blockedTasks = tasks.filter((task)=>!task.ready && '已完成' !== task.status).map((task)=>({
|
|
16504
|
+
id: task.id,
|
|
16505
|
+
blockedBy: task.blockedBy.map((dep)=>dep.id)
|
|
16506
|
+
}));
|
|
16507
|
+
const targetId = options.task?.trim() ?? '';
|
|
16508
|
+
const targetTask = targetId.length > 0 ? tasks.find((task)=>task.id === targetId) ?? null : null;
|
|
16509
|
+
if (targetId.length > 0 && null === targetTask) throw new errors_CliError(`任务 ${targetId} 不在迭代 ${iteration} 的文档范围内(当前成员范围:${developerFilter ?? '全部成员'})`, errors_EXIT.NOT_FOUND);
|
|
16510
|
+
const relPath = iterations.find((item)=>item.name === iteration)?.relPath ?? iteration;
|
|
15381
16511
|
const payload = {
|
|
16512
|
+
ok: 0 === errors.length,
|
|
15382
16513
|
iteration,
|
|
16514
|
+
relPath,
|
|
15383
16515
|
developer: developerFilter ?? '全部成员',
|
|
15384
16516
|
info,
|
|
15385
16517
|
totals: {
|
|
@@ -15390,12 +16522,11 @@ function runContext(options) {
|
|
|
15390
16522
|
},
|
|
15391
16523
|
requirements,
|
|
15392
16524
|
tasks,
|
|
15393
|
-
|
|
15394
|
-
|
|
15395
|
-
|
|
15396
|
-
|
|
15397
|
-
|
|
15398
|
-
issues: selected.flatMap((item)=>item.doc.validation.errors)
|
|
16525
|
+
readyTasks,
|
|
16526
|
+
blockedTasks,
|
|
16527
|
+
targetTask,
|
|
16528
|
+
errors,
|
|
16529
|
+
warnings
|
|
15399
16530
|
};
|
|
15400
16531
|
if ('json' === ctx.format) return void printJson(payload);
|
|
15401
16532
|
printLine(`迭代:${iteration} 开发者:${payload.developer}`);
|
|
@@ -15405,12 +16536,202 @@ function runContext(options) {
|
|
|
15405
16536
|
for (const item of requirements)printLine(`- ${item.id} ${item.title} ${item.status} ${item.progress}%`);
|
|
15406
16537
|
printLine('任务清单:');
|
|
15407
16538
|
for (const task of tasks)printLine(`- ${task.id} [${task.type}] ${task.name} ${task.status} 自测:${task.selfTest} 验收:${task.acceptance}`);
|
|
15408
|
-
printLine(`当前可执行任务:${0 === payload.
|
|
15409
|
-
for (const item of payload.
|
|
16539
|
+
printLine(`当前可执行任务:${0 === payload.readyTasks.length ? '无' : payload.readyTasks.join('、')}`);
|
|
16540
|
+
for (const item of payload.blockedTasks)printLine(` 阻塞:${item.id} 等待 ${item.blockedBy.join('、')}`);
|
|
16541
|
+
if (null !== payload.targetTask) printLine(`目标:${payload.targetTask.id} ${payload.targetTask.name} ${payload.targetTask.status}`);
|
|
16542
|
+
if (payload.errors.length > 0) {
|
|
16543
|
+
printLine(`校验问题(${payload.errors.length}):`);
|
|
16544
|
+
for (const issue of payload.errors)printLine(` [error] ${issue.code}:${issue.message}`);
|
|
16545
|
+
}
|
|
15410
16546
|
}
|
|
15411
16547
|
function registerContext(program) {
|
|
15412
16548
|
program.command('context').description('一次拿全迭代上下文:需求、任务、可执行任务与阻塞关系').option('-c, --config <path>', '指定配置文件路径').option('-i, --iteration <name>', '迭代目录名(可省略:在迭代目录内执行时自动推断)').option('-d, --developer <name>', '指定成员(默认取配置身份)').option('--all', '合并全部成员').option('--task <taskId>', '已知任务编号时可用于反查迭代').option('--format <format>', '输出格式:human | json', 'human').action((options)=>runContext(options));
|
|
15413
16549
|
}
|
|
16550
|
+
const MODES = {
|
|
16551
|
+
plan: '计划分析',
|
|
16552
|
+
exec: '实施需求'
|
|
16553
|
+
};
|
|
16554
|
+
const guide_TEMPLATE_DIR = 'skills/iteration-task-docs/references';
|
|
16555
|
+
function parseMode(value) {
|
|
16556
|
+
const mode = (value ?? '').trim();
|
|
16557
|
+
if ('plan' === mode || 'exec' === mode) return mode;
|
|
16558
|
+
throw new errors_CliError(`--mode 只能是 plan 或 exec:${mode.length > 0 ? mode : '(未指定)'}`, errors_EXIT.USAGE);
|
|
16559
|
+
}
|
|
16560
|
+
function collectBlocking(input) {
|
|
16561
|
+
const blocking = [];
|
|
16562
|
+
const byId = new Map(input.tasks.map((task)=>[
|
|
16563
|
+
task.id,
|
|
16564
|
+
task
|
|
16565
|
+
]));
|
|
16566
|
+
const target = input.targetTaskId.length > 0 ? byId.get(input.targetTaskId) : void 0;
|
|
16567
|
+
if (input.targetTaskId.length > 0 && void 0 === target) blocking.push(`任务 ${input.targetTaskId} 不在任务清单中`);
|
|
16568
|
+
if (void 0 !== target) for (const dependency of target.dependencies){
|
|
16569
|
+
const dependencyTask = byId.get(dependency);
|
|
16570
|
+
if (void 0 === dependencyTask) blocking.push(`前置任务 ${dependency} 不存在`);
|
|
16571
|
+
else if ('已完成' !== dependencyTask.status) blocking.push(`前置任务 ${dependency} 状态为「${dependencyTask.status}」,未完成`);
|
|
16572
|
+
}
|
|
16573
|
+
if (input.requirementId.length > 0) {
|
|
16574
|
+
const matched = input.tasks.some((task)=>task.requirementId === input.requirementId);
|
|
16575
|
+
if (!matched) blocking.push(`需求 ${input.requirementId} 在任务清单中没有对应任务`);
|
|
16576
|
+
}
|
|
16577
|
+
for (const issue of input.errors)blocking.push(`${issue.code}:${issue.message}`);
|
|
16578
|
+
return blocking;
|
|
16579
|
+
}
|
|
16580
|
+
function planningActions(options) {
|
|
16581
|
+
return [
|
|
16582
|
+
'确认文档仓库路径、开发者标识与角色(三者缺失时必须先询问开发者,禁止猜测)',
|
|
16583
|
+
`用 dws 拉取 PRD 并生成快照:${options.prdBaseline}(先探测 updateTime,未变化不会重拉全文)`,
|
|
16584
|
+
"从 PRD 标题提取迭代目录名(PRD_ 后到 】 前);目录不存在时用 ylcwf iteration create <年份>/<名称>(必须由开发者确认年份)",
|
|
16585
|
+
'按 PRD 需求清单筛选本次负责需求;执行终端列写执行终端名,不得写迭代目录名',
|
|
16586
|
+
"逐需求拆解任务:编号 <需求>-Tn、类型、执行终端、前置依赖、核心文件清单、实现方案、自测方式、历史功能影响范围",
|
|
16587
|
+
`生成个人文档:ylcwf doc apply -i ${options.iteration} --input plan.json(模板见 ${options.templatePath},角色 ${options.role})`,
|
|
16588
|
+
`落盘后依次运行 ylcwf doc validate -i ${options.iteration} -d ${options.developer} 与 ylcwf context -i ${options.iteration} -d ${options.developer},确认无 error 再汇报`
|
|
16589
|
+
];
|
|
16590
|
+
}
|
|
16591
|
+
function executionActions(options) {
|
|
16592
|
+
return [
|
|
16593
|
+
`确认目标任务编号、关联需求、执行终端与核心文件清单(${options.contextCommand})`,
|
|
16594
|
+
'按执行终端查全局提示词映射表得到本地仓库路径;表中缺失该终端时必须询问开发者',
|
|
16595
|
+
`开始编码前确认 PRD 无未处理变更:${options.prdDelta}`,
|
|
16596
|
+
'仅修改该任务核心文件清单范围内的文件,超出范围先向开发者说明',
|
|
16597
|
+
'完成实现后执行详情中声明的自测命令,并把真实输出写入「自测证据」',
|
|
16598
|
+
`自测通过后把任务置为待验收(严禁直接置为已完成):ylcwf task submit <任务编号> -i ${options.iteration}`,
|
|
16599
|
+
'人工验收通过后,由开发者确认再把任务置为已完成:ylcwf task accept <任务编号>',
|
|
16600
|
+
`每次回写后运行 ylcwf doc validate -i ${options.iteration} -d ${options.developer},确认无 error`
|
|
16601
|
+
];
|
|
16602
|
+
}
|
|
16603
|
+
function schemaNotes(schema) {
|
|
16604
|
+
return [
|
|
16605
|
+
`状态流转唯一允许路径:${schema.enums.taskStatus.join(' → ')}`,
|
|
16606
|
+
`需求开发状态取值:${schema.enums.requirementStatus.join(' / ')}(由关联任务状态聚合得出,禁止手写与任务不一致的值)`,
|
|
16607
|
+
`AI 自测状态取值:${schema.enums.selfTest.join(' / ')}(免测必须带括号理由)`,
|
|
16608
|
+
`开发人工验收取值:${schema.enums.acceptance.join(' / ')}(只有「验收通过」才允许任务置为已完成)`
|
|
16609
|
+
];
|
|
16610
|
+
}
|
|
16611
|
+
function runGuide(options) {
|
|
16612
|
+
const format = parseFormat(options.format);
|
|
16613
|
+
enableJsonErrors('json' === format);
|
|
16614
|
+
const mode = parseMode(options.mode);
|
|
16615
|
+
const ctx = requireQueryContext(options);
|
|
16616
|
+
const iterations = loadIterations(ctx.layout);
|
|
16617
|
+
const requirementId = (options.requirement ?? '').trim();
|
|
16618
|
+
const taskId = (options.task ?? '').trim();
|
|
16619
|
+
const iteration = resolveIterationName(options, ctx.layout, iterations, {
|
|
16620
|
+
taskId: taskId.length > 0 ? taskId : void 0,
|
|
16621
|
+
requirementId: requirementId.length > 0 ? requirementId : void 0
|
|
16622
|
+
});
|
|
16623
|
+
const docs = loadDeveloperDocs(ctx.layout, iteration);
|
|
16624
|
+
const developerFilter = true === options.all ? void 0 : options.developer?.trim() || ctx.developer;
|
|
16625
|
+
const selected = filterDocs(docs, developerFilter);
|
|
16626
|
+
if (0 === selected.length) throw new errors_CliError(`迭代 ${iteration} 中没有成员文档(${developerFilter ?? '全部成员'})`, errors_EXIT.NOT_FOUND);
|
|
16627
|
+
const schema = loadDocSchema(ctx.layout.root);
|
|
16628
|
+
const role = ctx.config.profile.role;
|
|
16629
|
+
if (void 0 === schema.roles[role]) throw new errors_CliError(`配置里的角色「${role}」不在文档仓库 schema.roles 中(可用:${Object.keys(schema.roles).join(' / ')})`, errors_EXIT.INVALID);
|
|
16630
|
+
const tasks = buildTaskRows(selected);
|
|
16631
|
+
const errors = selected.flatMap((item)=>item.doc.validation.errors);
|
|
16632
|
+
const warnings = selected.flatMap((item)=>item.doc.validation.warnings);
|
|
16633
|
+
const developer = developerFilter ?? ctx.developer;
|
|
16634
|
+
const relPath = iterations.find((item)=>item.name === iteration)?.relPath ?? iteration;
|
|
16635
|
+
const contextCommand = taskId.length > 0 ? `ylcwf context -i ${iteration} --task ${taskId}` : `ylcwf context -i ${iteration} -d ${developer}`;
|
|
16636
|
+
const prdDelta = `ylcwf prd delta -i ${iteration}` + (requirementId.length > 0 ? ` --requirement ${requirementId}` : '');
|
|
16637
|
+
const prdBaseline = `ylcwf prd baseline -i ${iteration} --node <PRD 链接>`;
|
|
16638
|
+
const blocking = 'exec' === mode ? collectBlocking({
|
|
16639
|
+
tasks,
|
|
16640
|
+
targetTaskId: taskId,
|
|
16641
|
+
requirementId,
|
|
16642
|
+
errors
|
|
16643
|
+
}) : [];
|
|
16644
|
+
const targetTask = taskId.length > 0 ? tasks.find((task)=>task.id === taskId) ?? null : null;
|
|
16645
|
+
const payload = {
|
|
16646
|
+
ok: 0 === errors.length,
|
|
16647
|
+
mode,
|
|
16648
|
+
modeName: MODES[mode],
|
|
16649
|
+
iteration,
|
|
16650
|
+
relPath,
|
|
16651
|
+
role,
|
|
16652
|
+
developer,
|
|
16653
|
+
requirement: requirementId.length > 0 ? requirementId : null,
|
|
16654
|
+
task: taskId.length > 0 ? taskId : null,
|
|
16655
|
+
allowed: 0 === blocking.length,
|
|
16656
|
+
validation: {
|
|
16657
|
+
ok: 0 === errors.length,
|
|
16658
|
+
errors: errors.length,
|
|
16659
|
+
warnings: warnings.length,
|
|
16660
|
+
issues: [
|
|
16661
|
+
...errors,
|
|
16662
|
+
...warnings
|
|
16663
|
+
]
|
|
16664
|
+
},
|
|
16665
|
+
targetTask,
|
|
16666
|
+
requiredActions: 'plan' === mode ? planningActions({
|
|
16667
|
+
role,
|
|
16668
|
+
templatePath: `<文档仓库>/${guide_TEMPLATE_DIR}/${role}.md`,
|
|
16669
|
+
iteration,
|
|
16670
|
+
developer,
|
|
16671
|
+
prdBaseline
|
|
16672
|
+
}) : executionActions({
|
|
16673
|
+
iteration,
|
|
16674
|
+
developer,
|
|
16675
|
+
contextCommand,
|
|
16676
|
+
prdDelta
|
|
16677
|
+
}),
|
|
16678
|
+
forbiddenActions: 'plan' === mode ? [
|
|
16679
|
+
'未确认迭代目录名之前不得新建迭代目录',
|
|
16680
|
+
'不得把 AI 推断的需求名称、验收标准或终端归属写成 PRD 事实',
|
|
16681
|
+
'不得修改其他开发者的 md 文件或仓库 README / AGENTS',
|
|
16682
|
+
'PRD 拉取失败时不得补造需求,必须停止并请求授权',
|
|
16683
|
+
'不得自动 git add / commit / push'
|
|
16684
|
+
] : [
|
|
16685
|
+
'AI 自测未通过时不得把任务标记为待验收或已完成',
|
|
16686
|
+
'开发人工验收未通过时不得把任务标记为已完成',
|
|
16687
|
+
'前置依赖未完成时不得开始当前任务',
|
|
16688
|
+
'不得跨任务大包干一次性交付,必须单任务步进并等待开发者确认',
|
|
16689
|
+
'不得把未执行的测试写成通过,不得伪造自测证据',
|
|
16690
|
+
'不得自动 git add / commit / push'
|
|
16691
|
+
],
|
|
16692
|
+
nextCommands: 'plan' === mode ? [
|
|
16693
|
+
`ylcwf doc validate -i ${iteration} -d ${developer}`,
|
|
16694
|
+
contextCommand
|
|
16695
|
+
] : [
|
|
16696
|
+
contextCommand,
|
|
16697
|
+
`ylcwf doc validate -i ${iteration} -d ${developer}`,
|
|
16698
|
+
prdDelta
|
|
16699
|
+
],
|
|
16700
|
+
notes: [
|
|
16701
|
+
...schemaNotes(schema),
|
|
16702
|
+
...blocking.map((item)=>`阻断原因:${item}`)
|
|
16703
|
+
]
|
|
16704
|
+
};
|
|
16705
|
+
if ('json' === ctx.format) return void printJson(payload);
|
|
16706
|
+
printLine(`模式:${payload.modeName} 迭代:${payload.relPath} 角色:${payload.role}`);
|
|
16707
|
+
printLine(`开发者:${payload.developer} 需求:${payload.requirement ?? '—'} 任务:${payload.task ?? '—'} 允许推进:${payload.allowed ? '是' : '否'}`);
|
|
16708
|
+
printLine(`校验:${errors.length} error / ${warnings.length} warning`);
|
|
16709
|
+
if (blocking.length > 0) {
|
|
16710
|
+
printLine('');
|
|
16711
|
+
printLine('阻断原因:');
|
|
16712
|
+
for (const item of blocking)printLine(` · ${item}`);
|
|
16713
|
+
}
|
|
16714
|
+
printLine('');
|
|
16715
|
+
printLine('必做:');
|
|
16716
|
+
payload.requiredActions.forEach((item, index)=>printLine(` ${index + 1}. ${item}`));
|
|
16717
|
+
printLine('禁止:');
|
|
16718
|
+
for (const item of payload.forbiddenActions)printLine(` · ${item}`);
|
|
16719
|
+
printLine('');
|
|
16720
|
+
printLine('下一步命令:');
|
|
16721
|
+
for (const item of payload.nextCommands)printLine(` · ${item}`);
|
|
16722
|
+
printLine('');
|
|
16723
|
+
printLine('口径说明:');
|
|
16724
|
+
for (const item of schemaNotes(schema))printLine(` · ${item}`);
|
|
16725
|
+
if (null !== payload.targetTask) {
|
|
16726
|
+
printLine('');
|
|
16727
|
+
printLine(`目标任务:${payload.targetTask.id} ${payload.targetTask.name} ${payload.targetTask.status} 自测 ${payload.targetTask.selfTest} 验收 ${payload.targetTask.acceptance}`);
|
|
16728
|
+
}
|
|
16729
|
+
}
|
|
16730
|
+
function registerGuide(program) {
|
|
16731
|
+
program.command('guide').description('按模式输出动作门禁与下一步命令(替代文档仓库的 guide.py)').requiredOption('--mode <mode>', '模式:plan | exec').option('-c, --config <path>', '指定配置文件路径').option('-i, --iteration <name>', '迭代目录名(可省略:按任务/需求编号或当前分支推断)').option('-d, --developer <name>', '指定成员(默认取配置身份)').option('--all', '合并全部成员(默认只看本人)').option('--requirement <id>', '需求编号,用于实施模式的范围校验').option('--task <taskId>', '目标任务编号(实施模式必填)').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
|
|
16732
|
+
runGuide(options);
|
|
16733
|
+
});
|
|
16734
|
+
}
|
|
15414
16735
|
function collectRequirements(layout, iteration, developer) {
|
|
15415
16736
|
const docs = loadDeveloperDocs(layout, iteration);
|
|
15416
16737
|
const filtered = void 0 === developer ? docs : docs.filter((item)=>item.developer === developer);
|
|
@@ -15469,9 +16790,9 @@ function requirement_runList(options) {
|
|
|
15469
16790
|
function requirement_runShow(id, options) {
|
|
15470
16791
|
const ctx = requireQueryContext(options);
|
|
15471
16792
|
const iteration = resolveIterationName(options, ctx.layout, loadIterations(ctx.layout), {
|
|
15472
|
-
requirementId: id
|
|
16793
|
+
requirementId: normalizeRequirementId(id)
|
|
15473
16794
|
});
|
|
15474
|
-
const target = id
|
|
16795
|
+
const target = normalizeRequirementId(id);
|
|
15475
16796
|
const requirement = collectRequirements(ctx.layout, iteration, options.developer?.trim() || void 0).find((item)=>item.id === target);
|
|
15476
16797
|
if (void 0 === requirement) throw new errors_CliError(`迭代 ${iteration} 中没有需求 ${target}`, errors_EXIT.NOT_FOUND);
|
|
15477
16798
|
const docs = loadDeveloperDocs(ctx.layout, iteration);
|
|
@@ -15538,7 +16859,7 @@ function runRecalc(options) {
|
|
|
15538
16859
|
function runNote(requirementId, options) {
|
|
15539
16860
|
const { docsRoot, layout, developer, policy } = requireWriteContext(options);
|
|
15540
16861
|
const iteration = options.iteration?.trim() ? resolveIterationName(options, layout, loadIterations(layout)) : resolveIterationName(options, layout, loadIterations(layout), {
|
|
15541
|
-
requirementId: requirementId
|
|
16862
|
+
requirementId: normalizeRequirementId(requirementId)
|
|
15542
16863
|
});
|
|
15543
16864
|
const note = (options.set ?? '').trim();
|
|
15544
16865
|
if (0 === note.length) throw new errors_CliError('请用 --set 提供备注内容', errors_EXIT.USAGE);
|
|
@@ -15589,9 +16910,9 @@ async function fetchManifest(url) {
|
|
|
15589
16910
|
const payload = await response.json();
|
|
15590
16911
|
if ('string' != typeof payload.version || 0 === payload.version.length) return null;
|
|
15591
16912
|
return {
|
|
15592
|
-
current: "0.
|
|
16913
|
+
current: "0.8.0",
|
|
15593
16914
|
latest: payload.version,
|
|
15594
|
-
hasUpdate: isNewer(payload.version, "0.
|
|
16915
|
+
hasUpdate: isNewer(payload.version, "0.8.0"),
|
|
15595
16916
|
downloadUrl: 'string' == typeof payload.downloadUrl ? payload.downloadUrl : null,
|
|
15596
16917
|
source: 'manifest',
|
|
15597
16918
|
checkedAt: new Date().toISOString(),
|
|
@@ -15603,7 +16924,7 @@ async function fetchManifest(url) {
|
|
|
15603
16924
|
}
|
|
15604
16925
|
async function fetchNpm() {
|
|
15605
16926
|
const base = {
|
|
15606
|
-
current: "0.
|
|
16927
|
+
current: "0.8.0",
|
|
15607
16928
|
latest: null,
|
|
15608
16929
|
hasUpdate: false,
|
|
15609
16930
|
downloadUrl: null,
|
|
@@ -15630,7 +16951,7 @@ async function fetchNpm() {
|
|
|
15630
16951
|
return {
|
|
15631
16952
|
...base,
|
|
15632
16953
|
latest,
|
|
15633
|
-
hasUpdate: isNewer(latest, "0.
|
|
16954
|
+
hasUpdate: isNewer(latest, "0.8.0"),
|
|
15634
16955
|
downloadUrl: null
|
|
15635
16956
|
};
|
|
15636
16957
|
} catch (error) {
|
|
@@ -15653,95 +16974,245 @@ async function checkUpdate(force = false) {
|
|
|
15653
16974
|
};
|
|
15654
16975
|
return result;
|
|
15655
16976
|
}
|
|
15656
|
-
function
|
|
15657
|
-
|
|
15658
|
-
|
|
15659
|
-
|
|
15660
|
-
|
|
15661
|
-
|
|
16977
|
+
function normalizePathForCompare(value) {
|
|
16978
|
+
const unified = value.replace(/\\/g, '/').replace(/\/+$/, '');
|
|
16979
|
+
return 'win32' === process.platform ? unified.toLowerCase() : unified;
|
|
16980
|
+
}
|
|
16981
|
+
function isInside(child, parent) {
|
|
16982
|
+
if (null === parent || 0 === parent.length) return false;
|
|
16983
|
+
const target = normalizePathForCompare(external_node_path_resolve(child));
|
|
16984
|
+
const root = normalizePathForCompare(external_node_path_resolve(parent));
|
|
16985
|
+
return target === root || target.startsWith(`${root}/`);
|
|
16986
|
+
}
|
|
16987
|
+
function classifyInstallPaths(input) {
|
|
16988
|
+
const paths = input.paths.filter((item)=>item.length > 0);
|
|
16989
|
+
for (const path of paths)if (isInside(path, input.npmRoot)) return 'npm-global';
|
|
16990
|
+
for (const path of paths)if (isInside(path, input.pnpmRoot)) return 'pnpm-global';
|
|
16991
|
+
for (const path of paths){
|
|
16992
|
+
const normalized = normalizePathForCompare(path);
|
|
16993
|
+
if (/\/\.pnpm\/ylcwf@/.test(normalized) || /\/pnpm\/global\/\d+\//.test(normalized)) return 'pnpm-global';
|
|
16994
|
+
if (/\/npm\/node_modules\/ylcwf(\/|$)/.test(normalized)) return 'npm-global';
|
|
16995
|
+
}
|
|
16996
|
+
if (null !== input.miseInstallsRoot) {
|
|
16997
|
+
for (const path of paths)if (isInside(path, input.miseInstallsRoot)) return 'mise';
|
|
16998
|
+
}
|
|
16999
|
+
for (const path of paths)if (/\/mise[^/]*\/installs\/[^/]*ylcwf[^/]*\//.test(normalizePathForCompare(path))) return 'mise';
|
|
17000
|
+
for (const path of paths)if (isInside(path, input.scriptRoot)) return "script";
|
|
17001
|
+
for (const path of paths)if (isInside(path, input.sourceRoot)) return 'source';
|
|
17002
|
+
return 'unknown';
|
|
17003
|
+
}
|
|
17004
|
+
function miseInstallsRoot() {
|
|
17005
|
+
const candidates = [];
|
|
17006
|
+
const dataDir = process.env['MISE_DATA_DIR']?.trim();
|
|
17007
|
+
if (void 0 !== dataDir && dataDir.length > 0) candidates.push(external_node_path_join(dataDir, 'installs'));
|
|
17008
|
+
const localAppData = process.env['LOCALAPPDATA']?.trim();
|
|
17009
|
+
if (void 0 !== localAppData && localAppData.length > 0) candidates.push(external_node_path_join(localAppData, 'mise', 'installs'));
|
|
17010
|
+
candidates.push(external_node_path_join(homedir(), '.local', 'share', 'mise', 'installs'));
|
|
17011
|
+
candidates.push(external_node_path_join(homedir(), 'Library', 'Application Support', 'mise', 'installs'));
|
|
17012
|
+
candidates.push(external_node_path_join(homedir(), 'AppData', 'Local', 'mise', 'installs'));
|
|
17013
|
+
for (const candidate of candidates)if (external_node_fs_existsSync(candidate)) return candidate;
|
|
17014
|
+
return null;
|
|
17015
|
+
}
|
|
17016
|
+
function scriptInstallRoot() {
|
|
17017
|
+
if ('win32' === process.platform) {
|
|
17018
|
+
const localAppData = process.env['LOCALAPPDATA']?.trim() ?? external_node_path_join(homedir(), 'AppData', 'Local');
|
|
17019
|
+
return external_node_path_join(localAppData, 'ylcwf');
|
|
15662
17020
|
}
|
|
15663
|
-
|
|
15664
|
-
|
|
15665
|
-
|
|
15666
|
-
|
|
15667
|
-
|
|
15668
|
-
|
|
15669
|
-
[
|
|
15670
|
-
'root',
|
|
15671
|
-
'-g'
|
|
15672
|
-
]
|
|
15673
|
-
]
|
|
15674
|
-
],
|
|
15675
|
-
[
|
|
15676
|
-
'pnpm-global',
|
|
15677
|
-
[
|
|
15678
|
-
'pnpm',
|
|
15679
|
-
[
|
|
15680
|
-
'root',
|
|
15681
|
-
'-g'
|
|
15682
|
-
]
|
|
15683
|
-
]
|
|
15684
|
-
]
|
|
15685
|
-
])try {
|
|
15686
|
-
const dir = execFileSync(args[0], [
|
|
15687
|
-
...args[1]
|
|
17021
|
+
return external_node_path_join(homedir(), '.local', 'share', 'ylcwf');
|
|
17022
|
+
}
|
|
17023
|
+
function runQuietly(command, args) {
|
|
17024
|
+
try {
|
|
17025
|
+
const output = execFileSync(command, [
|
|
17026
|
+
...args
|
|
15688
17027
|
], {
|
|
15689
17028
|
encoding: 'utf8',
|
|
15690
17029
|
stdio: [
|
|
15691
17030
|
'ignore',
|
|
15692
17031
|
'pipe',
|
|
15693
17032
|
'ignore'
|
|
15694
|
-
]
|
|
17033
|
+
],
|
|
17034
|
+
timeout: 10000
|
|
15695
17035
|
}).trim();
|
|
15696
|
-
|
|
15697
|
-
|
|
15698
|
-
|
|
15699
|
-
|
|
15700
|
-
} catch {}
|
|
15701
|
-
for (const root of roots)if (self.startsWith(root.dir)) return root.kind;
|
|
15702
|
-
return 'linked';
|
|
17036
|
+
return output.length > 0 ? output : null;
|
|
17037
|
+
} catch {
|
|
17038
|
+
return null;
|
|
17039
|
+
}
|
|
15703
17040
|
}
|
|
15704
|
-
function
|
|
15705
|
-
|
|
15706
|
-
|
|
15707
|
-
'
|
|
15708
|
-
|
|
17041
|
+
function packageRootOf(entry) {
|
|
17042
|
+
let current = external_node_path_dirname(entry);
|
|
17043
|
+
for(let depth = 0; depth < 8; depth += 1){
|
|
17044
|
+
if (external_node_fs_existsSync(external_node_path_join(current, 'package.json'))) return current;
|
|
17045
|
+
const parent = external_node_path_dirname(current);
|
|
17046
|
+
if (parent === current) break;
|
|
17047
|
+
current = parent;
|
|
17048
|
+
}
|
|
17049
|
+
return null;
|
|
17050
|
+
}
|
|
17051
|
+
function sourceRootOf(packageRoot) {
|
|
17052
|
+
if (null === packageRoot) return null;
|
|
17053
|
+
let current = packageRoot;
|
|
17054
|
+
for(let depth = 0; depth < 4; depth += 1){
|
|
17055
|
+
if (external_node_fs_existsSync(external_node_path_join(current, 'pnpm-workspace.yaml'))) return current;
|
|
17056
|
+
const parent = external_node_path_dirname(current);
|
|
17057
|
+
if (parent === current) break;
|
|
17058
|
+
current = parent;
|
|
17059
|
+
}
|
|
17060
|
+
return null;
|
|
17061
|
+
}
|
|
17062
|
+
function detectInstallKind() {
|
|
17063
|
+
let entry = null;
|
|
17064
|
+
try {
|
|
17065
|
+
entry = fileURLToPath(import.meta.url);
|
|
17066
|
+
} catch {
|
|
17067
|
+
entry = null;
|
|
17068
|
+
}
|
|
17069
|
+
if (null === entry) return 'unknown';
|
|
17070
|
+
const paths = [
|
|
17071
|
+
entry
|
|
15709
17072
|
];
|
|
15710
|
-
printLine(`执行:npm ${args.join(' ')}`);
|
|
15711
|
-
if (dryRun) return;
|
|
15712
17073
|
try {
|
|
15713
|
-
|
|
17074
|
+
const real = realpathSync(entry);
|
|
17075
|
+
if (real !== entry) paths.push(real);
|
|
17076
|
+
} catch {}
|
|
17077
|
+
const packageRoot = packageRootOf(entry);
|
|
17078
|
+
if (null !== packageRoot) {
|
|
17079
|
+
const realPackageRoot = (()=>{
|
|
17080
|
+
try {
|
|
17081
|
+
return realpathSync(packageRoot);
|
|
17082
|
+
} catch {
|
|
17083
|
+
return packageRoot;
|
|
17084
|
+
}
|
|
17085
|
+
})();
|
|
17086
|
+
if (realPackageRoot !== packageRoot) paths.push(realPackageRoot);
|
|
17087
|
+
}
|
|
17088
|
+
return classifyInstallPaths({
|
|
17089
|
+
paths,
|
|
17090
|
+
npmRoot: runQuietly('npm', [
|
|
17091
|
+
'root',
|
|
17092
|
+
'-g'
|
|
17093
|
+
]),
|
|
17094
|
+
pnpmRoot: runQuietly('pnpm', [
|
|
17095
|
+
'root',
|
|
17096
|
+
'-g'
|
|
17097
|
+
]),
|
|
17098
|
+
miseInstallsRoot: miseInstallsRoot(),
|
|
17099
|
+
scriptRoot: scriptInstallRoot(),
|
|
17100
|
+
sourceRoot: sourceRootOf(packageRoot)
|
|
17101
|
+
});
|
|
17102
|
+
}
|
|
17103
|
+
function installKindLabel(kind) {
|
|
17104
|
+
switch(kind){
|
|
17105
|
+
case 'npm-global':
|
|
17106
|
+
return 'npm 全局安装';
|
|
17107
|
+
case 'pnpm-global':
|
|
17108
|
+
return 'pnpm 全局安装';
|
|
17109
|
+
case 'mise':
|
|
17110
|
+
return 'mise 安装';
|
|
17111
|
+
case "script":
|
|
17112
|
+
return '安装脚本安装';
|
|
17113
|
+
case 'source':
|
|
17114
|
+
return '源码仓库运行';
|
|
17115
|
+
default:
|
|
17116
|
+
return '无法识别安装方式';
|
|
17117
|
+
}
|
|
17118
|
+
}
|
|
17119
|
+
const SCRIPT_CDN = "https://cdn.jsdelivr.net/npm/ylcwf@latest/scripts";
|
|
17120
|
+
const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
|
|
17121
|
+
function assertVersion(version) {
|
|
17122
|
+
if (!VERSION_PATTERN.test(version)) throw new errors_CliError(`版本号不合法:${version}(应形如 0.6.2)`, errors_EXIT.USAGE);
|
|
17123
|
+
return version;
|
|
17124
|
+
}
|
|
17125
|
+
function runOrFail(command, args, manual) {
|
|
17126
|
+
printLine(`执行:${command} ${args.join(' ')}`);
|
|
17127
|
+
try {
|
|
17128
|
+
execFileSync(command, [
|
|
17129
|
+
...args
|
|
17130
|
+
], {
|
|
15714
17131
|
stdio: 'inherit'
|
|
15715
17132
|
});
|
|
15716
17133
|
} catch {
|
|
15717
|
-
throw new errors_CliError(
|
|
17134
|
+
throw new errors_CliError(`升级失败。常见原因:无写权限(可尝试 sudo)或网络不可达。\n手动执行:${manual}`, errors_EXIT.INVALID);
|
|
15718
17135
|
}
|
|
15719
17136
|
}
|
|
17137
|
+
function upgradeScriptInstall(dryRun) {
|
|
17138
|
+
if ('win32' === process.platform) {
|
|
17139
|
+
const command = `irm ${SCRIPT_CDN}/install.ps1 | iex`;
|
|
17140
|
+
printLine(`执行:powershell -NoProfile -Command "${command}"`);
|
|
17141
|
+
if (dryRun) return;
|
|
17142
|
+
runOrFail('powershell.exe', [
|
|
17143
|
+
'-NoProfile',
|
|
17144
|
+
'-Command',
|
|
17145
|
+
command
|
|
17146
|
+
], command);
|
|
17147
|
+
return;
|
|
17148
|
+
}
|
|
17149
|
+
const command = `curl -fsSL ${SCRIPT_CDN}/install.sh | sh`;
|
|
17150
|
+
printLine(`执行:${command}`);
|
|
17151
|
+
if (dryRun) return;
|
|
17152
|
+
runOrFail('sh', [
|
|
17153
|
+
'-c',
|
|
17154
|
+
command
|
|
17155
|
+
], command);
|
|
17156
|
+
}
|
|
15720
17157
|
async function runUpgrade(options) {
|
|
15721
17158
|
const kind = detectInstallKind();
|
|
15722
17159
|
const result = await checkUpdate(true);
|
|
15723
|
-
const target = options.to
|
|
15724
|
-
printLine("当前版本:0.
|
|
17160
|
+
const target = void 0 === options.to ? result.latest : assertVersion(options.to.trim());
|
|
17161
|
+
printLine("当前版本:0.8.0");
|
|
17162
|
+
printLine(`安装方式:${installKindLabel(kind)}`);
|
|
15725
17163
|
if (null !== result.error) printLine(`版本查询失败:${result.error}`);
|
|
15726
17164
|
else if (null !== result.latest) printLine(`最新版本:${result.latest}(来源:${result.source})`);
|
|
17165
|
+
if (true === options.check) {
|
|
17166
|
+
if (null === result.latest) throw new errors_CliError('无法查询最新版本,请稍后重试', errors_EXIT.NOT_FOUND);
|
|
17167
|
+
printLine(result.hasUpdate ? `发现新版本:${result.latest}` : '已是最新版本');
|
|
17168
|
+
return;
|
|
17169
|
+
}
|
|
15727
17170
|
if (null === target) throw new errors_CliError('无法确定目标版本,请稍后重试或用 --to 指定', errors_EXIT.NOT_FOUND);
|
|
15728
|
-
if (true === options.check) return void printLine(result.hasUpdate ? `发现新版本:${result.latest}` : '已是最新版本');
|
|
15729
17171
|
if (true !== result.hasUpdate && void 0 === options.to) return void printLine('已是最新版本,无需升级');
|
|
15730
|
-
|
|
15731
|
-
|
|
15732
|
-
|
|
15733
|
-
|
|
17172
|
+
const dryRun = true === options.dryRun;
|
|
17173
|
+
printLine('');
|
|
17174
|
+
if ('source' === kind) return void printLine('当前从源码目录运行,跳过自动升级。');
|
|
17175
|
+
if ("script" === kind) upgradeScriptInstall(dryRun);
|
|
17176
|
+
else if ('npm-global' === kind) {
|
|
17177
|
+
const args = [
|
|
17178
|
+
'install',
|
|
17179
|
+
'-g',
|
|
17180
|
+
`ylcwf@${target}`
|
|
17181
|
+
];
|
|
17182
|
+
printLine(`执行:npm ${args.join(' ')}`);
|
|
17183
|
+
if (!dryRun) runOrFail('npm', args, `npm install -g ylcwf@${target}`);
|
|
17184
|
+
} else if ('mise' === kind) {
|
|
17185
|
+
const args = [
|
|
17186
|
+
'upgrade',
|
|
17187
|
+
'npm:ylcwf',
|
|
17188
|
+
'--bump'
|
|
17189
|
+
];
|
|
17190
|
+
printLine(`执行:mise ${args.join(' ')}`);
|
|
17191
|
+
if (!dryRun) runOrFail('mise', args, "mise upgrade npm:ylcwf --bump");
|
|
17192
|
+
} else if ('pnpm-global' === kind) {
|
|
17193
|
+
const args = [
|
|
17194
|
+
'add',
|
|
17195
|
+
'-g',
|
|
17196
|
+
`ylcwf@${target}`
|
|
17197
|
+
];
|
|
17198
|
+
printLine(`执行:pnpm ${args.join(' ')}`);
|
|
17199
|
+
if (!dryRun) runOrFail('pnpm', args, `pnpm add -g ylcwf@${target}`);
|
|
17200
|
+
} else {
|
|
17201
|
+
printLine('无法识别当前安装方式,请按实际情况手动执行其中之一:');
|
|
17202
|
+
printLine(` npm install -g ylcwf@${target}`);
|
|
17203
|
+
printLine(` pnpm add -g ylcwf@${target}`);
|
|
17204
|
+
printLine(" mise upgrade npm:ylcwf --bump");
|
|
17205
|
+
printLine(` curl -fsSL ${SCRIPT_CDN}/install.sh | sh`);
|
|
17206
|
+
printLine(` powershell -NoProfile -Command "irm ${SCRIPT_CDN}/install.ps1 | iex"`);
|
|
15734
17207
|
return;
|
|
15735
17208
|
}
|
|
15736
|
-
|
|
15737
|
-
installLatest(target, true === options.dryRun);
|
|
15738
|
-
if (true === options.dryRun) return void printLine('(--dry-run:未实际执行)');
|
|
17209
|
+
if (dryRun) return void printLine('(--dry-run:未实际执行)');
|
|
15739
17210
|
printLine('');
|
|
15740
17211
|
printLine('升级完成。正在运行的 `ylcwf serve` 仍是旧进程,请重启后生效。');
|
|
15741
17212
|
printLine('桌面端 App 需要重新下载安装包,可用 `ylcwf serve` 的「设置 → 检查更新」查看下载地址。');
|
|
15742
17213
|
}
|
|
15743
17214
|
function registerUpgrade(program) {
|
|
15744
|
-
program.command('upgrade').description('检查并升级 ylcwf
|
|
17215
|
+
program.command('upgrade').alias('update').description('检查并升级 ylcwf 到最新版本(按安装方式自动选择更新方式)').option('--check', '只检查是否有新版本,不执行升级').option('--to <version>', '升级到指定版本(如 --to 0.6.2)').option('--dry-run', '只打印将执行的命令,不实际执行').option('-y, --yes', '跳过确认(保留参数以兼容脚本调用)').action(async (options)=>{
|
|
15745
17216
|
await runUpgrade(options);
|
|
15746
17217
|
});
|
|
15747
17218
|
}
|
|
@@ -16073,9 +17544,14 @@ function buildMatch(item, terminalName, matchedBy, catalog) {
|
|
|
16073
17544
|
function checkYapiAgainstTerminalCatalog(catalog, terminalNames) {
|
|
16074
17545
|
if (0 === terminalNames.length) return [];
|
|
16075
17546
|
const allowed = terminalNames.map((name)=>normalizeName(name));
|
|
16076
|
-
const
|
|
16077
|
-
for (const item of catalog.platforms)if (!allowed.includes(normalizeName(item.terminal)))
|
|
16078
|
-
|
|
17547
|
+
const unknown = [];
|
|
17548
|
+
for (const item of catalog.platforms)if (!allowed.includes(normalizeName(item.terminal))) {
|
|
17549
|
+
if (!unknown.includes(item.terminal)) unknown.push(item.terminal);
|
|
17550
|
+
}
|
|
17551
|
+
if (0 === unknown.length) return [];
|
|
17552
|
+
return [
|
|
17553
|
+
yapi_warning('YAPI_TERMINAL_NOT_IN_CATALOG', `${YAPI_PLATFORM_FILE} 中有 ${unknown.length} 个执行终端不在 execution_terminals.json 里:「${unknown.join('、')}」;可选:${terminalNames.join('、')}(以清单为准,请改 yapi 文件)`, 'platforms')
|
|
17554
|
+
];
|
|
16079
17555
|
}
|
|
16080
17556
|
function checkDocsSides(config) {
|
|
16081
17557
|
const messages = [];
|
|
@@ -16127,12 +17603,37 @@ function doctor_checkTerminalCatalog(config) {
|
|
|
16127
17603
|
});
|
|
16128
17604
|
return issues;
|
|
16129
17605
|
}
|
|
16130
|
-
const yapi = loadYapiCatalog(root);
|
|
16131
|
-
if (null !== yapi.catalog) issues.push(...checkYapiAgainstTerminalCatalog(yapi.catalog, names).map((issue)=>({
|
|
16132
|
-
level: issue.level,
|
|
16133
|
-
message: issue.message
|
|
16134
|
-
})));
|
|
16135
|
-
return issues;
|
|
17606
|
+
const yapi = loadYapiCatalog(root);
|
|
17607
|
+
if (null !== yapi.catalog) issues.push(...checkYapiAgainstTerminalCatalog(yapi.catalog, names).map((issue)=>({
|
|
17608
|
+
level: issue.level,
|
|
17609
|
+
message: issue.message
|
|
17610
|
+
})));
|
|
17611
|
+
return issues;
|
|
17612
|
+
}
|
|
17613
|
+
function checkSchemaRequirement(config) {
|
|
17614
|
+
try {
|
|
17615
|
+
const schema = loadDocSchema(config.docs.root, {
|
|
17616
|
+
allowTooOld: true
|
|
17617
|
+
});
|
|
17618
|
+
if (null === schema.requiresYlcwf) return [];
|
|
17619
|
+
const required = parseMinVersion(schema.requiresYlcwf);
|
|
17620
|
+
if (null === required) return [];
|
|
17621
|
+
const floor = `${required[0]}.${required[1]}.${required[2]}`;
|
|
17622
|
+
if (compareVersions("0.8.0", floor) >= 0) return [];
|
|
17623
|
+
return [
|
|
17624
|
+
{
|
|
17625
|
+
level: 'error',
|
|
17626
|
+
message: `文档仓库要求 ylcwf ${schema.requiresYlcwf},当前 0.8.0;请先升级:npm install -g ylcwf@latest`
|
|
17627
|
+
}
|
|
17628
|
+
];
|
|
17629
|
+
} catch (error) {
|
|
17630
|
+
return [
|
|
17631
|
+
{
|
|
17632
|
+
level: 'error',
|
|
17633
|
+
message: `无法读取 schema.json:${error instanceof Error ? error.message : String(error)}`
|
|
17634
|
+
}
|
|
17635
|
+
];
|
|
17636
|
+
}
|
|
16136
17637
|
}
|
|
16137
17638
|
function runDoctor(options) {
|
|
16138
17639
|
const format = parseFormat(options.format);
|
|
@@ -16145,6 +17646,7 @@ function runDoctor(options) {
|
|
|
16145
17646
|
const ok = !hasError(checked.issues);
|
|
16146
17647
|
const sideIssues = [];
|
|
16147
17648
|
if (true === options.docs && null !== checked.config && ok) {
|
|
17649
|
+
sideIssues.push(...checkSchemaRequirement(checked.config));
|
|
16148
17650
|
sideIssues.push(...doctor_checkTerminalCatalog(checked.config));
|
|
16149
17651
|
sideIssues.push(...checkDocsSides(checked.config));
|
|
16150
17652
|
}
|
|
@@ -16243,10 +17745,19 @@ function syncDocument(doc, next) {
|
|
|
16243
17745
|
], next.docs.git[side].push);
|
|
16244
17746
|
}
|
|
16245
17747
|
doc.setIn([
|
|
17748
|
+
'docs',
|
|
17749
|
+
'validator',
|
|
17750
|
+
'strict'
|
|
17751
|
+
], next.docs.validator.strict);
|
|
17752
|
+
if (doc.hasIn([
|
|
17753
|
+
'docs',
|
|
17754
|
+
'validator',
|
|
17755
|
+
'requireScript'
|
|
17756
|
+
])) doc.deleteIn([
|
|
16246
17757
|
'docs',
|
|
16247
17758
|
'validator',
|
|
16248
17759
|
'requireScript'
|
|
16249
|
-
]
|
|
17760
|
+
]);
|
|
16250
17761
|
const current = doc.toJS();
|
|
16251
17762
|
const currentTerminals = utils_isRecord(current) && utils_isRecord(current['terminals']) ? Object.keys(current['terminals']) : [];
|
|
16252
17763
|
for (const key of currentTerminals)if (!Object.hasOwn(next.terminals, key)) doc.deleteIn([
|
|
@@ -16349,7 +17860,7 @@ function readState(explicitPath) {
|
|
|
16349
17860
|
issues: checked.issues,
|
|
16350
17861
|
backups: listBackups(explicitPath),
|
|
16351
17862
|
meta: {
|
|
16352
|
-
version: "0.
|
|
17863
|
+
version: "0.8.0",
|
|
16353
17864
|
features: SERVER_FEATURES
|
|
16354
17865
|
}
|
|
16355
17866
|
};
|
|
@@ -17450,7 +18961,7 @@ function printMatch(match) {
|
|
|
17450
18961
|
function findSubject(layout, iteration, options) {
|
|
17451
18962
|
const docs = loadDeveloperDocs(layout, iteration);
|
|
17452
18963
|
if (void 0 !== options.taskId) {
|
|
17453
|
-
const wanted = options.taskId
|
|
18964
|
+
const wanted = normalizeTaskId(options.taskId);
|
|
17454
18965
|
for (const { doc } of docs){
|
|
17455
18966
|
const task = doc.validation.tasks.find((item)=>item.id === wanted);
|
|
17456
18967
|
if (void 0 !== task) return {
|
|
@@ -17461,7 +18972,7 @@ function findSubject(layout, iteration, options) {
|
|
|
17461
18972
|
}
|
|
17462
18973
|
throw new errors_CliError(`迭代 ${iteration} 中未找到任务:${wanted}`, errors_EXIT.NOT_FOUND);
|
|
17463
18974
|
}
|
|
17464
|
-
const wanted = (options.requirementId ?? '')
|
|
18975
|
+
const wanted = normalizeRequirementId(options.requirementId ?? '');
|
|
17465
18976
|
for (const { doc } of docs){
|
|
17466
18977
|
const requirement = doc.validation.requirements.find((item)=>item.id === wanted);
|
|
17467
18978
|
if (void 0 !== requirement) return {
|
|
@@ -17516,9 +19027,9 @@ function runFromDoc(kind, id, options) {
|
|
|
17516
19027
|
const catalog = requireCatalog(ctx.layout.root);
|
|
17517
19028
|
const iterations = loadIterations(ctx.layout);
|
|
17518
19029
|
const iteration = resolveIterationName(options, ctx.layout, iterations, 'task' === kind ? {
|
|
17519
|
-
taskId: id
|
|
19030
|
+
taskId: normalizeTaskId(id)
|
|
17520
19031
|
} : {
|
|
17521
|
-
requirementId: id
|
|
19032
|
+
requirementId: normalizeRequirementId(id)
|
|
17522
19033
|
});
|
|
17523
19034
|
const subject = findSubject(ctx.layout, iteration, 'task' === kind ? {
|
|
17524
19035
|
taskId: id
|
|
@@ -17530,11 +19041,15 @@ function runFromDoc(kind, id, options) {
|
|
|
17530
19041
|
terminals: ctx.config.terminals,
|
|
17531
19042
|
input: subject.terminal
|
|
17532
19043
|
});
|
|
19044
|
+
const requirementId = 'task' === kind ? requirementOfTaskId(subject.label) ?? subject.label : subject.label;
|
|
19045
|
+
const yapiTag = `${iteration}--${requirementId}`;
|
|
17533
19046
|
if ('json' === ctx.format) {
|
|
17534
19047
|
if (!match.matched) failUnmatched(match, subject.terminal, ctx.format);
|
|
17535
19048
|
printJson({
|
|
17536
19049
|
['task' === kind ? 'taskId' : 'requirementId']: subject.label,
|
|
17537
19050
|
iteration,
|
|
19051
|
+
requirementId,
|
|
19052
|
+
yapiTag,
|
|
17538
19053
|
terminalRepo: subject.terminal,
|
|
17539
19054
|
side: subject.side,
|
|
17540
19055
|
...match
|
|
@@ -17542,6 +19057,7 @@ function runFromDoc(kind, id, options) {
|
|
|
17542
19057
|
return;
|
|
17543
19058
|
}
|
|
17544
19059
|
printLine(`${'task' === kind ? '任务' : '需求'} ${subject.label}(迭代 ${iteration})`);
|
|
19060
|
+
printLine(`YAPI tag ${yapiTag}`);
|
|
17545
19061
|
printLine(`文档执行终端 ${subject.terminal}${null === subject.side ? '' : `(所属端:${subject.side})`}`);
|
|
17546
19062
|
if (!match.matched) failUnmatched(match, subject.terminal, ctx.format);
|
|
17547
19063
|
printMatch(match);
|
|
@@ -17553,6 +19069,1063 @@ function registerYapi(program) {
|
|
|
17553
19069
|
yapi.command('task <taskId>').description('按任务编号解析:读文档的「执行终端」列再查 YAPI 映射').option('-c, --config <path>', '指定配置文件路径').option('-i, --iteration <name>', '迭代目录名(可省略)').option('--format <format>', '输出格式:human | json', 'human').action((taskId, options)=>runFromDoc('task', taskId, options));
|
|
17554
19070
|
yapi.command('requirement <requirementId>').description('按需求编号解析:读文档的「执行终端」列再查 YAPI 映射').option('-c, --config <path>', '指定配置文件路径').option('-i, --iteration <name>', '迭代目录名(可省略)').option('--format <format>', '输出格式:human | json', 'human').action((requirementId, options)=>runFromDoc('requirement', requirementId, options));
|
|
17555
19071
|
}
|
|
19072
|
+
const PRD_SNAPSHOT_SCHEMA_VERSION = 'prd-snapshot';
|
|
19073
|
+
const PRD_META_SCHEMA_VERSION = 'prd-meta';
|
|
19074
|
+
const PRD_SNAPSHOT_NAME = 'snapshot.json';
|
|
19075
|
+
const PRD_META_NAME = 'meta.json';
|
|
19076
|
+
const CHANGELOG_KEYWORD = '变更记录';
|
|
19077
|
+
const HEADING_TAGS = new Set([
|
|
19078
|
+
'h1',
|
|
19079
|
+
'h2',
|
|
19080
|
+
'h3',
|
|
19081
|
+
'h4',
|
|
19082
|
+
'h5',
|
|
19083
|
+
'h6'
|
|
19084
|
+
]);
|
|
19085
|
+
const BLOCK_TAGS = new Set([
|
|
19086
|
+
'p',
|
|
19087
|
+
'li',
|
|
19088
|
+
'pre',
|
|
19089
|
+
'blockquote'
|
|
19090
|
+
]);
|
|
19091
|
+
const REQUIREMENT_HEADING_PATTERNS = [
|
|
19092
|
+
/[-–—]\s*(\d{3,6})\s*$/,
|
|
19093
|
+
/#\s*(\d{3,6})\b/,
|
|
19094
|
+
/需求\s*[::]?\s*(\d{3,6})\b/
|
|
19095
|
+
];
|
|
19096
|
+
const REQUIREMENT_BODY_PATTERN = /新增需求\s*[::]?\s*(\d{3,6})\b/;
|
|
19097
|
+
const SECTION_NO_PATTERN = /^(\d+(?:\.\d+)*)/;
|
|
19098
|
+
const CHANGELOG_SECTION_REF_PATTERN = /\d+\.\d+(?:\.\d+)*(?:\s*-\s*[A-Za-z])?/g;
|
|
19099
|
+
const CHANGELOG_REQUIREMENT_REF_PATTERN = /(?<![\d.])(\d{3,6})(?![\d.])/g;
|
|
19100
|
+
const CHANGELOG_DATE_PATTERN = /\d{4}-\d{1,2}-\d{1,2}/;
|
|
19101
|
+
const NODE_ID_PATTERN = /\/nodes\/([A-Za-z0-9_-]+)/;
|
|
19102
|
+
const NODE_ID_QUERY_PATTERN = /[?&]nodeId=([A-Za-z0-9_-]+)/;
|
|
19103
|
+
class PrdJsonmlError extends Error {
|
|
19104
|
+
constructor(message){
|
|
19105
|
+
super(message);
|
|
19106
|
+
this.name = 'PrdJsonmlError';
|
|
19107
|
+
}
|
|
19108
|
+
}
|
|
19109
|
+
function sha256Text(text) {
|
|
19110
|
+
return createHash('sha256').update(text, 'utf8').digest('hex');
|
|
19111
|
+
}
|
|
19112
|
+
function formatTimestamp(milliseconds) {
|
|
19113
|
+
if (null == milliseconds || 0 === milliseconds) return '未提供';
|
|
19114
|
+
const date = new Date(milliseconds);
|
|
19115
|
+
if (Number.isNaN(date.getTime())) return `原始值 ${milliseconds}`;
|
|
19116
|
+
const pad = (value)=>String(value).padStart(2, '0');
|
|
19117
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
19118
|
+
}
|
|
19119
|
+
function resolveNodeId(node) {
|
|
19120
|
+
const text = node.trim();
|
|
19121
|
+
const matched = NODE_ID_PATTERN.exec(text) ?? NODE_ID_QUERY_PATTERN.exec(text);
|
|
19122
|
+
return matched?.[1] ?? text;
|
|
19123
|
+
}
|
|
19124
|
+
function prd_isRecord(value) {
|
|
19125
|
+
return 'object' == typeof value && null !== value && !Array.isArray(value);
|
|
19126
|
+
}
|
|
19127
|
+
function splitNode(node) {
|
|
19128
|
+
if (!Array.isArray(node) || 0 === node.length) return {
|
|
19129
|
+
tag: null,
|
|
19130
|
+
attrs: {},
|
|
19131
|
+
children: []
|
|
19132
|
+
};
|
|
19133
|
+
const tag = 'string' == typeof node[0] ? node[0] : null;
|
|
19134
|
+
let attrs = {};
|
|
19135
|
+
const children = [];
|
|
19136
|
+
for (const item of node.slice(1)){
|
|
19137
|
+
if (prd_isRecord(item) && 0 === Object.keys(attrs).length) {
|
|
19138
|
+
attrs = item;
|
|
19139
|
+
continue;
|
|
19140
|
+
}
|
|
19141
|
+
children.push(item);
|
|
19142
|
+
}
|
|
19143
|
+
return {
|
|
19144
|
+
tag,
|
|
19145
|
+
attrs,
|
|
19146
|
+
children
|
|
19147
|
+
};
|
|
19148
|
+
}
|
|
19149
|
+
function collectText(node) {
|
|
19150
|
+
if ('string' == typeof node) return node;
|
|
19151
|
+
if (!Array.isArray(node)) return '';
|
|
19152
|
+
return splitNode(node).children.map(collectText).join('');
|
|
19153
|
+
}
|
|
19154
|
+
function normalizeText(text) {
|
|
19155
|
+
return text.replace(/\s+/g, ' ').trim();
|
|
19156
|
+
}
|
|
19157
|
+
function collectCellText(cell) {
|
|
19158
|
+
if (!Array.isArray(cell)) return normalizeText(collectText(cell));
|
|
19159
|
+
const parts = [];
|
|
19160
|
+
for (const child of splitNode(cell).children){
|
|
19161
|
+
if (!Array.isArray(child)) continue;
|
|
19162
|
+
const { tag } = splitNode(child);
|
|
19163
|
+
if (null !== tag && BLOCK_TAGS.has(tag)) {
|
|
19164
|
+
const text = normalizeText(collectText(child));
|
|
19165
|
+
if (text.length > 0) parts.push(text);
|
|
19166
|
+
}
|
|
19167
|
+
}
|
|
19168
|
+
if (parts.length > 0) return parts.join(' / ');
|
|
19169
|
+
return normalizeText(collectText(cell));
|
|
19170
|
+
}
|
|
19171
|
+
function parseJsonmlBlocks(jsonmlText) {
|
|
19172
|
+
let root;
|
|
19173
|
+
try {
|
|
19174
|
+
root = JSON.parse(jsonmlText);
|
|
19175
|
+
} catch {
|
|
19176
|
+
throw new PrdJsonmlError('dws 返回的 jsonml 不是合法 JSON');
|
|
19177
|
+
}
|
|
19178
|
+
const blocks = [];
|
|
19179
|
+
const walk = (node)=>{
|
|
19180
|
+
if (!Array.isArray(node)) return;
|
|
19181
|
+
const { tag, attrs, children } = splitNode(node);
|
|
19182
|
+
if (null === tag) {
|
|
19183
|
+
for (const child of children)walk(child);
|
|
19184
|
+
return;
|
|
19185
|
+
}
|
|
19186
|
+
const uuid = 'string' == typeof attrs['uuid'] ? attrs['uuid'] : '';
|
|
19187
|
+
if (HEADING_TAGS.has(tag)) return void blocks.push({
|
|
19188
|
+
tag,
|
|
19189
|
+
uuid,
|
|
19190
|
+
level: Number.parseInt(tag.slice(1), 10),
|
|
19191
|
+
text: normalizeText(collectText(node))
|
|
19192
|
+
});
|
|
19193
|
+
if (BLOCK_TAGS.has(tag)) {
|
|
19194
|
+
const text = normalizeText(collectText(node));
|
|
19195
|
+
if (text.length > 0) blocks.push({
|
|
19196
|
+
tag,
|
|
19197
|
+
uuid,
|
|
19198
|
+
text
|
|
19199
|
+
});
|
|
19200
|
+
return;
|
|
19201
|
+
}
|
|
19202
|
+
if ('tr' === tag) {
|
|
19203
|
+
const cells = children.filter((child)=>Array.isArray(child) && 'tc' === splitNode(child).tag).map(collectCellText);
|
|
19204
|
+
blocks.push({
|
|
19205
|
+
tag: 'tr',
|
|
19206
|
+
uuid,
|
|
19207
|
+
text: cells.filter((cell)=>cell.length > 0).join(' | '),
|
|
19208
|
+
cells
|
|
19209
|
+
});
|
|
19210
|
+
return;
|
|
19211
|
+
}
|
|
19212
|
+
for (const child of children)walk(child);
|
|
19213
|
+
};
|
|
19214
|
+
walk(root);
|
|
19215
|
+
return blocks;
|
|
19216
|
+
}
|
|
19217
|
+
function blockSignature(block) {
|
|
19218
|
+
return `${block.tag}\t${block.text}`;
|
|
19219
|
+
}
|
|
19220
|
+
function pagesDigest(blocks) {
|
|
19221
|
+
return sha256Text(blocks.map(blockSignature).join('\n'));
|
|
19222
|
+
}
|
|
19223
|
+
function extractRequirementIds(heading) {
|
|
19224
|
+
const found = [];
|
|
19225
|
+
for (const pattern of REQUIREMENT_HEADING_PATTERNS){
|
|
19226
|
+
const global = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`);
|
|
19227
|
+
let matched = global.exec(heading);
|
|
19228
|
+
while(null !== matched){
|
|
19229
|
+
const id = matched[1];
|
|
19230
|
+
if (void 0 !== id && !found.includes(id)) found.push(id);
|
|
19231
|
+
matched = global.exec(heading);
|
|
19232
|
+
}
|
|
19233
|
+
}
|
|
19234
|
+
return found;
|
|
19235
|
+
}
|
|
19236
|
+
function extractSectionNo(heading) {
|
|
19237
|
+
const matched = SECTION_NO_PATTERN.exec(heading);
|
|
19238
|
+
return matched?.[1] ?? null;
|
|
19239
|
+
}
|
|
19240
|
+
function headingRefs(blocks) {
|
|
19241
|
+
const refs = [];
|
|
19242
|
+
blocks.forEach((block, index)=>{
|
|
19243
|
+
if (!HEADING_TAGS.has(block.tag)) return;
|
|
19244
|
+
refs.push({
|
|
19245
|
+
index,
|
|
19246
|
+
level: block.level ?? 0,
|
|
19247
|
+
text: block.text
|
|
19248
|
+
});
|
|
19249
|
+
});
|
|
19250
|
+
return refs;
|
|
19251
|
+
}
|
|
19252
|
+
function buildRequirements(blocks) {
|
|
19253
|
+
const headings = headingRefs(blocks);
|
|
19254
|
+
const requirements = {};
|
|
19255
|
+
headings.forEach((heading, order)=>{
|
|
19256
|
+
const end = headings.slice(order + 1).find((later)=>later.level <= heading.level)?.index ?? blocks.length;
|
|
19257
|
+
const scope = blocks.slice(heading.index, end);
|
|
19258
|
+
const requirementIds = extractRequirementIds(heading.text);
|
|
19259
|
+
if (0 === requirementIds.length) return;
|
|
19260
|
+
for (const requirementId of requirementIds)if (void 0 === requirements[requirementId]) requirements[requirementId] = {
|
|
19261
|
+
requirement: requirementId,
|
|
19262
|
+
heading: heading.text,
|
|
19263
|
+
sectionNo: extractSectionNo(heading.text),
|
|
19264
|
+
start: heading.index,
|
|
19265
|
+
end: end - 1,
|
|
19266
|
+
blockCount: scope.length,
|
|
19267
|
+
digest: pagesDigest(scope)
|
|
19268
|
+
};
|
|
19269
|
+
});
|
|
19270
|
+
return requirements;
|
|
19271
|
+
}
|
|
19272
|
+
function findChangelog(blocks) {
|
|
19273
|
+
const headings = headingRefs(blocks);
|
|
19274
|
+
const candidates = headings.filter((heading)=>heading.text.includes(CHANGELOG_KEYWORD) && heading.level <= 3);
|
|
19275
|
+
if (0 === candidates.length) return null;
|
|
19276
|
+
const start = candidates.reduce((best, item)=>item.level < best.level || item.level === best.level && item.index < best.index ? item : best);
|
|
19277
|
+
const end = headings.find((heading)=>heading.index > start.index && heading.level <= start.level)?.index ?? blocks.length;
|
|
19278
|
+
const rows = [];
|
|
19279
|
+
for (const block of blocks.slice(start.index, end)){
|
|
19280
|
+
if ('tr' !== block.tag) continue;
|
|
19281
|
+
const cells = block.cells ?? [];
|
|
19282
|
+
if (0 !== cells.length) {
|
|
19283
|
+
if (!(cells[0] ?? '').startsWith('变更时间')) rows.push(cells);
|
|
19284
|
+
}
|
|
19285
|
+
}
|
|
19286
|
+
return {
|
|
19287
|
+
start: start.index,
|
|
19288
|
+
end: end - 1,
|
|
19289
|
+
rows,
|
|
19290
|
+
digest: sha256Text(rows.map((row)=>row.join(' | ')).join('\n'))
|
|
19291
|
+
};
|
|
19292
|
+
}
|
|
19293
|
+
function collectDeclaredRequirements(blocks) {
|
|
19294
|
+
const withSection = new Set();
|
|
19295
|
+
for (const block of blocks)if (HEADING_TAGS.has(block.tag)) for (const id of extractRequirementIds(block.text))withSection.add(id);
|
|
19296
|
+
const declared = {};
|
|
19297
|
+
for (const block of blocks){
|
|
19298
|
+
if (!BLOCK_TAGS.has(block.tag)) continue;
|
|
19299
|
+
const global = new RegExp(REQUIREMENT_BODY_PATTERN.source, 'g');
|
|
19300
|
+
let matched = global.exec(block.text);
|
|
19301
|
+
while(null !== matched){
|
|
19302
|
+
const candidate = matched[1];
|
|
19303
|
+
if (void 0 !== candidate && !withSection.has(candidate)) declared[candidate] = declared[candidate] ?? [];
|
|
19304
|
+
matched = global.exec(block.text);
|
|
19305
|
+
}
|
|
19306
|
+
}
|
|
19307
|
+
return declared;
|
|
19308
|
+
}
|
|
19309
|
+
function buildSnapshot(options) {
|
|
19310
|
+
const blocks = parseJsonmlBlocks(options.document.jsonml);
|
|
19311
|
+
return {
|
|
19312
|
+
schemaVersion: PRD_SNAPSHOT_SCHEMA_VERSION,
|
|
19313
|
+
iteration: options.iteration,
|
|
19314
|
+
nodeId: options.document.nodeId,
|
|
19315
|
+
docUrl: options.document.docUrl,
|
|
19316
|
+
title: options.document.title,
|
|
19317
|
+
revision: options.document.revision,
|
|
19318
|
+
updateTime: options.updateTime,
|
|
19319
|
+
updateTimeText: formatTimestamp(options.updateTime),
|
|
19320
|
+
blockCount: blocks.length,
|
|
19321
|
+
blocks,
|
|
19322
|
+
requirements: buildRequirements(blocks),
|
|
19323
|
+
changelog: findChangelog(blocks),
|
|
19324
|
+
declaredRequirements: collectDeclaredRequirements(blocks)
|
|
19325
|
+
};
|
|
19326
|
+
}
|
|
19327
|
+
function buildMeta(snapshot) {
|
|
19328
|
+
const requirements = {};
|
|
19329
|
+
for (const [id, entry] of Object.entries(snapshot.requirements))requirements[id] = {
|
|
19330
|
+
sectionNo: entry.sectionNo,
|
|
19331
|
+
heading: entry.heading,
|
|
19332
|
+
blockCount: entry.blockCount,
|
|
19333
|
+
digest: entry.digest
|
|
19334
|
+
};
|
|
19335
|
+
return {
|
|
19336
|
+
schemaVersion: PRD_META_SCHEMA_VERSION,
|
|
19337
|
+
iteration: snapshot.iteration,
|
|
19338
|
+
nodeId: snapshot.nodeId,
|
|
19339
|
+
docUrl: snapshot.docUrl,
|
|
19340
|
+
title: snapshot.title,
|
|
19341
|
+
revision: snapshot.revision,
|
|
19342
|
+
updateTime: snapshot.updateTime,
|
|
19343
|
+
updateTimeText: snapshot.updateTimeText,
|
|
19344
|
+
blockCount: snapshot.blockCount,
|
|
19345
|
+
requirements,
|
|
19346
|
+
changelog: {
|
|
19347
|
+
rowCount: snapshot.changelog?.rows.length ?? 0,
|
|
19348
|
+
digest: snapshot.changelog?.digest ?? null
|
|
19349
|
+
},
|
|
19350
|
+
declaredRequirements: snapshot.declaredRequirements
|
|
19351
|
+
};
|
|
19352
|
+
}
|
|
19353
|
+
function describeRow(cells) {
|
|
19354
|
+
const rowText = cells.join(' | ');
|
|
19355
|
+
const date = CHANGELOG_DATE_PATTERN.exec(rowText)?.[0] ?? '';
|
|
19356
|
+
const withoutDate = rowText.replace(CHANGELOG_DATE_PATTERN, ' ');
|
|
19357
|
+
return {
|
|
19358
|
+
row: rowText,
|
|
19359
|
+
cells: [
|
|
19360
|
+
...cells
|
|
19361
|
+
],
|
|
19362
|
+
date,
|
|
19363
|
+
sectionRefs: withoutDate.match(CHANGELOG_SECTION_REF_PATTERN) ?? [],
|
|
19364
|
+
requirementRefs: withoutDate.match(CHANGELOG_REQUIREMENT_REF_PATTERN) ?? []
|
|
19365
|
+
};
|
|
19366
|
+
}
|
|
19367
|
+
function matchedRows(rows, requirementId, sectionNo) {
|
|
19368
|
+
const matched = [];
|
|
19369
|
+
for (const cells of rows){
|
|
19370
|
+
const described = describeRow(cells);
|
|
19371
|
+
if (described.requirementRefs.includes(requirementId)) {
|
|
19372
|
+
matched.push(described);
|
|
19373
|
+
continue;
|
|
19374
|
+
}
|
|
19375
|
+
if (null !== sectionNo && described.sectionRefs.some((ref)=>ref.startsWith(sectionNo))) matched.push(described);
|
|
19376
|
+
}
|
|
19377
|
+
return matched;
|
|
19378
|
+
}
|
|
19379
|
+
function unifiedDiff(oldLines, newLines, context = 2) {
|
|
19380
|
+
const rows = oldLines.length;
|
|
19381
|
+
const cols = newLines.length;
|
|
19382
|
+
const lcs = Array.from({
|
|
19383
|
+
length: rows + 1
|
|
19384
|
+
}, ()=>new Array(cols + 1).fill(0));
|
|
19385
|
+
for(let i = rows - 1; i >= 0; i -= 1)for(let j = cols - 1; j >= 0; j -= 1)lcs[i][j] = oldLines[i] === newLines[j] ? (lcs[i + 1][j + 1] ?? 0) + 1 : Math.max(lcs[i + 1][j] ?? 0, lcs[i][j + 1] ?? 0);
|
|
19386
|
+
const edits = [];
|
|
19387
|
+
let i = 0;
|
|
19388
|
+
let j = 0;
|
|
19389
|
+
while(i < rows && j < cols){
|
|
19390
|
+
if (oldLines[i] === newLines[j]) {
|
|
19391
|
+
edits.push({
|
|
19392
|
+
kind: ' ',
|
|
19393
|
+
text: oldLines[i] ?? '',
|
|
19394
|
+
oldIndex: i,
|
|
19395
|
+
newIndex: j
|
|
19396
|
+
});
|
|
19397
|
+
i += 1;
|
|
19398
|
+
j += 1;
|
|
19399
|
+
continue;
|
|
19400
|
+
}
|
|
19401
|
+
if ((lcs[i + 1][j] ?? 0) >= (lcs[i][j + 1] ?? 0)) {
|
|
19402
|
+
edits.push({
|
|
19403
|
+
kind: '-',
|
|
19404
|
+
text: oldLines[i] ?? '',
|
|
19405
|
+
oldIndex: i,
|
|
19406
|
+
newIndex: j
|
|
19407
|
+
});
|
|
19408
|
+
i += 1;
|
|
19409
|
+
} else {
|
|
19410
|
+
edits.push({
|
|
19411
|
+
kind: '+',
|
|
19412
|
+
text: newLines[j] ?? '',
|
|
19413
|
+
oldIndex: i,
|
|
19414
|
+
newIndex: j
|
|
19415
|
+
});
|
|
19416
|
+
j += 1;
|
|
19417
|
+
}
|
|
19418
|
+
}
|
|
19419
|
+
while(i < rows){
|
|
19420
|
+
edits.push({
|
|
19421
|
+
kind: '-',
|
|
19422
|
+
text: oldLines[i] ?? '',
|
|
19423
|
+
oldIndex: i,
|
|
19424
|
+
newIndex: j
|
|
19425
|
+
});
|
|
19426
|
+
i += 1;
|
|
19427
|
+
}
|
|
19428
|
+
while(j < cols){
|
|
19429
|
+
edits.push({
|
|
19430
|
+
kind: '+',
|
|
19431
|
+
text: newLines[j] ?? '',
|
|
19432
|
+
oldIndex: i,
|
|
19433
|
+
newIndex: j
|
|
19434
|
+
});
|
|
19435
|
+
j += 1;
|
|
19436
|
+
}
|
|
19437
|
+
const changed = edits.map((edit, index)=>' ' === edit.kind ? -1 : index).filter((index)=>index >= 0);
|
|
19438
|
+
if (0 === changed.length) return [];
|
|
19439
|
+
const hunks = [];
|
|
19440
|
+
for (const index of changed){
|
|
19441
|
+
const start = Math.max(0, index - context);
|
|
19442
|
+
const end = Math.min(edits.length - 1, index + context);
|
|
19443
|
+
const last = hunks[hunks.length - 1];
|
|
19444
|
+
if (void 0 !== last && start <= last.end + 1) last.end = Math.max(last.end, end);
|
|
19445
|
+
else hunks.push({
|
|
19446
|
+
start,
|
|
19447
|
+
end
|
|
19448
|
+
});
|
|
19449
|
+
}
|
|
19450
|
+
const lines = [
|
|
19451
|
+
'--- baseline',
|
|
19452
|
+
'+++ current'
|
|
19453
|
+
];
|
|
19454
|
+
for (const hunk of hunks){
|
|
19455
|
+
const slice = edits.slice(hunk.start, hunk.end + 1);
|
|
19456
|
+
const oldCount = slice.filter((edit)=>'+' !== edit.kind).length;
|
|
19457
|
+
const newCount = slice.filter((edit)=>'-' !== edit.kind).length;
|
|
19458
|
+
const oldStart = (slice.find((edit)=>'+' !== edit.kind)?.oldIndex ?? 0) + 1;
|
|
19459
|
+
const newStart = (slice.find((edit)=>'-' !== edit.kind)?.newIndex ?? 0) + 1;
|
|
19460
|
+
lines.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`);
|
|
19461
|
+
for (const edit of slice)lines.push(`${edit.kind}${edit.text}`);
|
|
19462
|
+
}
|
|
19463
|
+
return lines;
|
|
19464
|
+
}
|
|
19465
|
+
function blockDiff(options) {
|
|
19466
|
+
const oldLines = options.oldBlocks.slice(options.oldRange[0], options.oldRange[1] + 1).map(blockSignature);
|
|
19467
|
+
const newLines = options.newBlocks.slice(options.newRange[0], options.newRange[1] + 1).map(blockSignature);
|
|
19468
|
+
const oldSet = new Set(oldLines);
|
|
19469
|
+
const newSet = new Set(newLines);
|
|
19470
|
+
const diffLines = unifiedDiff(oldLines, newLines);
|
|
19471
|
+
return {
|
|
19472
|
+
diff: diffLines.slice(0, options.maxLines).join('\n'),
|
|
19473
|
+
truncated: diffLines.length > options.maxLines,
|
|
19474
|
+
diffLineCount: diffLines.length,
|
|
19475
|
+
addedBlocks: newLines.filter((line)=>!oldSet.has(line)).length,
|
|
19476
|
+
removedBlocks: oldLines.filter((line)=>!newSet.has(line)).length
|
|
19477
|
+
};
|
|
19478
|
+
}
|
|
19479
|
+
class PrdDwsError extends Error {
|
|
19480
|
+
code;
|
|
19481
|
+
hint;
|
|
19482
|
+
constructor(code, message, hint = ''){
|
|
19483
|
+
super(message);
|
|
19484
|
+
this.name = 'PrdDwsError';
|
|
19485
|
+
this.code = code;
|
|
19486
|
+
this.hint = hint;
|
|
19487
|
+
}
|
|
19488
|
+
toDict() {
|
|
19489
|
+
return {
|
|
19490
|
+
code: this.code,
|
|
19491
|
+
message: this.message,
|
|
19492
|
+
hint: this.hint
|
|
19493
|
+
};
|
|
19494
|
+
}
|
|
19495
|
+
}
|
|
19496
|
+
const PRD_DWS_HINTS = {
|
|
19497
|
+
DWS_NOT_FOUND: '请安装 dws CLI 并执行 dws auth login,或用 --dws-path 指定绝对路径',
|
|
19498
|
+
DWS_TIMEOUT: 'dws 响应超时,请检查网络后重试',
|
|
19499
|
+
DWS_BAD_OUTPUT: 'dws 输出异常,请升级 dws 或反馈维护者',
|
|
19500
|
+
CONTENT_NOT_READY: 'PRD 正文尚未就绪,请稍后重试(本次已自动重试一次)',
|
|
19501
|
+
CONTENT_EMPTY: 'PRD 正文为空或尚未发布,请确认文档内容已就绪',
|
|
19502
|
+
AUTH_REQUIRED: '请执行 dws auth login 完成登录后重试',
|
|
19503
|
+
PERMISSION_DENIED: '当前账号没有该文档权限,请联系文档所有者开通',
|
|
19504
|
+
NODE_NOT_FOUND: '请核对 PRD 链接或 nodeId 是否正确',
|
|
19505
|
+
NODE_MISSING: '请传 --node(PRD 链接或 nodeId)',
|
|
19506
|
+
NO_BASELINE: '先执行 ylcwf prd baseline 建立快照,或本次显式传 --node'
|
|
19507
|
+
};
|
|
19508
|
+
function hintOf(code) {
|
|
19509
|
+
return PRD_DWS_HINTS[code] ?? '';
|
|
19510
|
+
}
|
|
19511
|
+
function classifyDwsMessage(message) {
|
|
19512
|
+
const lowered = message.toLowerCase();
|
|
19513
|
+
if (message.includes('尚未就绪') || lowered.includes('not ready')) return 'CONTENT_NOT_READY';
|
|
19514
|
+
if (message.includes('未登录') || lowered.includes('authenticate') || lowered.includes('access token')) return 'AUTH_REQUIRED';
|
|
19515
|
+
if (message.includes('无权') || lowered.includes('accessdenied') || lowered.includes('forbidden')) return 'PERMISSION_DENIED';
|
|
19516
|
+
if (message.includes('不存在') || lowered.includes('notfound') || lowered.includes('not found')) return 'NODE_NOT_FOUND';
|
|
19517
|
+
return 'DWS_ERROR';
|
|
19518
|
+
}
|
|
19519
|
+
function prd_sleepSync(milliseconds) {
|
|
19520
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
|
|
19521
|
+
}
|
|
19522
|
+
function src_prd_isRecord(value) {
|
|
19523
|
+
return 'object' == typeof value && null !== value && !Array.isArray(value);
|
|
19524
|
+
}
|
|
19525
|
+
function execDws(dwsPath, args) {
|
|
19526
|
+
let stdout;
|
|
19527
|
+
try {
|
|
19528
|
+
stdout = execFileSync(dwsPath, [
|
|
19529
|
+
...args,
|
|
19530
|
+
'--format',
|
|
19531
|
+
'json'
|
|
19532
|
+
], {
|
|
19533
|
+
encoding: 'utf8',
|
|
19534
|
+
timeout: 120000,
|
|
19535
|
+
maxBuffer: 33554432,
|
|
19536
|
+
stdio: [
|
|
19537
|
+
'ignore',
|
|
19538
|
+
'pipe',
|
|
19539
|
+
'pipe'
|
|
19540
|
+
]
|
|
19541
|
+
});
|
|
19542
|
+
} catch (error) {
|
|
19543
|
+
const failure = error;
|
|
19544
|
+
if ('ENOENT' === failure.code || 127 === failure.code) throw new PrdDwsError('DWS_NOT_FOUND', `未找到 dws 可执行文件:${dwsPath}`, '请安装 dws CLI 并完成 dws auth login,或用 --dws-path 指定绝对路径');
|
|
19545
|
+
if (true === failure.killed || 'SIGTERM' === failure.signal) throw new PrdDwsError('DWS_TIMEOUT', `dws 调用超时(120 秒):${args.join(' ')}`, hintOf('DWS_TIMEOUT'));
|
|
19546
|
+
const rawStdout = 'string' == typeof failure.stdout ? failure.stdout.trim() : '';
|
|
19547
|
+
if (rawStdout.length > 0) try {
|
|
19548
|
+
const payload = JSON.parse(rawStdout);
|
|
19549
|
+
if (src_prd_isRecord(payload) && src_prd_isRecord(payload['error'])) {
|
|
19550
|
+
const message = String(payload['error']['message'] ?? 'dws 返回错误');
|
|
19551
|
+
const code = classifyDwsMessage(message);
|
|
19552
|
+
throw new PrdDwsError(code, message, String(payload['error']['hint'] ?? '') || hintOf(code));
|
|
19553
|
+
}
|
|
19554
|
+
if (src_prd_isRecord(payload) && 'string' == typeof payload['message']) {
|
|
19555
|
+
const code = classifyDwsMessage(payload['message']);
|
|
19556
|
+
throw new PrdDwsError(code, payload['message'], hintOf(code));
|
|
19557
|
+
}
|
|
19558
|
+
} catch (inner) {
|
|
19559
|
+
if (inner instanceof PrdDwsError) throw inner;
|
|
19560
|
+
}
|
|
19561
|
+
const stderr = 'string' == typeof failure.stderr ? failure.stderr.trim() : '';
|
|
19562
|
+
const message = stderr.length > 0 ? stderr.split('\n').at(-1) ?? stderr : 'dws 没有任何输出';
|
|
19563
|
+
const code = classifyDwsMessage(message);
|
|
19564
|
+
throw new PrdDwsError(code, message, hintOf(code));
|
|
19565
|
+
}
|
|
19566
|
+
try {
|
|
19567
|
+
const payload = JSON.parse(stdout);
|
|
19568
|
+
if (!src_prd_isRecord(payload)) throw new PrdDwsError('DWS_BAD_OUTPUT', `dws 输出不是对象:${stdout.slice(0, 200)}`, hintOf('DWS_BAD_OUTPUT'));
|
|
19569
|
+
if (src_prd_isRecord(payload['error'])) {
|
|
19570
|
+
const message = String(payload['error']['message'] ?? 'dws 返回错误');
|
|
19571
|
+
const code = classifyDwsMessage(message);
|
|
19572
|
+
throw new PrdDwsError(code, message, String(payload['error']['hint'] ?? '') || hintOf(code));
|
|
19573
|
+
}
|
|
19574
|
+
return payload;
|
|
19575
|
+
} catch (error) {
|
|
19576
|
+
if (error instanceof PrdDwsError) throw error;
|
|
19577
|
+
throw new PrdDwsError('DWS_BAD_OUTPUT', `dws 输出不是合法 JSON:${stdout.slice(0, 200)}`, hintOf('DWS_BAD_OUTPUT'));
|
|
19578
|
+
}
|
|
19579
|
+
}
|
|
19580
|
+
function probePrd(dwsPath, node) {
|
|
19581
|
+
const nodeId = resolveNodeId(node);
|
|
19582
|
+
if (0 === nodeId.length) throw new PrdDwsError('NODE_MISSING', '未提供 PRD 文档 nodeId 或链接', hintOf('NODE_MISSING'));
|
|
19583
|
+
const info = execDws(dwsPath, [
|
|
19584
|
+
'doc',
|
|
19585
|
+
'+inspect',
|
|
19586
|
+
'--node',
|
|
19587
|
+
nodeId
|
|
19588
|
+
]);
|
|
19589
|
+
const data = src_prd_isRecord(info['data']) ? info['data'] : {};
|
|
19590
|
+
const document = src_prd_isRecord(data['document']) ? data['document'] : {};
|
|
19591
|
+
return {
|
|
19592
|
+
nodeId: String(document['nodeId'] ?? nodeId),
|
|
19593
|
+
docUrl: String(document['docUrl'] ?? ''),
|
|
19594
|
+
title: String(document['name'] ?? ''),
|
|
19595
|
+
updateTime: Number(document['updateTime'] ?? 0),
|
|
19596
|
+
extension: String(document['extension'] ?? '')
|
|
19597
|
+
};
|
|
19598
|
+
}
|
|
19599
|
+
function fetchPrd(dwsPath, node, retryDelayMs = 3000) {
|
|
19600
|
+
const nodeId = resolveNodeId(node);
|
|
19601
|
+
const args = [
|
|
19602
|
+
'doc',
|
|
19603
|
+
'+fetch',
|
|
19604
|
+
'--node',
|
|
19605
|
+
nodeId,
|
|
19606
|
+
'--scope',
|
|
19607
|
+
'full',
|
|
19608
|
+
'--detail',
|
|
19609
|
+
'full'
|
|
19610
|
+
];
|
|
19611
|
+
let payload;
|
|
19612
|
+
try {
|
|
19613
|
+
payload = execDws(dwsPath, args);
|
|
19614
|
+
} catch (error) {
|
|
19615
|
+
if (error instanceof PrdDwsError && 'CONTENT_NOT_READY' === error.code) {
|
|
19616
|
+
prd_sleepSync(retryDelayMs);
|
|
19617
|
+
payload = execDws(dwsPath, args);
|
|
19618
|
+
} else throw error;
|
|
19619
|
+
}
|
|
19620
|
+
const content = src_prd_isRecord(payload['content']) ? payload['content'] : {};
|
|
19621
|
+
const jsonml = 'string' == typeof content['jsonml'] ? content['jsonml'] : '';
|
|
19622
|
+
if (0 === jsonml.trim().length) throw new PrdDwsError('CONTENT_EMPTY', 'PRD 文档 JSONML 正文为空,无法作为需求事实', hintOf('CONTENT_EMPTY'));
|
|
19623
|
+
return {
|
|
19624
|
+
nodeId: String(content['nodeId'] ?? nodeId),
|
|
19625
|
+
docUrl: String(content['docUrl'] ?? ''),
|
|
19626
|
+
title: String(content['title'] ?? ''),
|
|
19627
|
+
revision: String(content['revision'] ?? ''),
|
|
19628
|
+
jsonml
|
|
19629
|
+
};
|
|
19630
|
+
}
|
|
19631
|
+
function prdDirOf(layout, iteration) {
|
|
19632
|
+
const resolved = resolveIterationDir(layout.root, layout.iterationsRoot, iteration);
|
|
19633
|
+
return external_node_path_join(resolved.dir, "_prd");
|
|
19634
|
+
}
|
|
19635
|
+
function readJsonFile(path) {
|
|
19636
|
+
if (!external_node_fs_existsSync(path)) return null;
|
|
19637
|
+
try {
|
|
19638
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
19639
|
+
} catch {
|
|
19640
|
+
return null;
|
|
19641
|
+
}
|
|
19642
|
+
}
|
|
19643
|
+
function readSnapshot(prdDir) {
|
|
19644
|
+
const raw = readJsonFile(external_node_path_join(prdDir, PRD_SNAPSHOT_NAME));
|
|
19645
|
+
if (!src_prd_isRecord(raw) || !Array.isArray(raw['blocks'])) return null;
|
|
19646
|
+
return raw;
|
|
19647
|
+
}
|
|
19648
|
+
function readMeta(prdDir) {
|
|
19649
|
+
const raw = readJsonFile(external_node_path_join(prdDir, PRD_META_NAME));
|
|
19650
|
+
if (!src_prd_isRecord(raw)) return null;
|
|
19651
|
+
return raw;
|
|
19652
|
+
}
|
|
19653
|
+
function writeSnapshotFiles(prdDir, snapshot, meta) {
|
|
19654
|
+
mkdirSync(external_node_path_dirname(external_node_path_join(prdDir, PRD_SNAPSHOT_NAME)), {
|
|
19655
|
+
recursive: true
|
|
19656
|
+
});
|
|
19657
|
+
writeFileSync(external_node_path_join(prdDir, PRD_SNAPSHOT_NAME), `${JSON.stringify(snapshot, null, 2)}\n`, 'utf8');
|
|
19658
|
+
writeFileSync(external_node_path_join(prdDir, PRD_META_NAME), `${JSON.stringify(meta, null, 2)}\n`, 'utf8');
|
|
19659
|
+
}
|
|
19660
|
+
function splitRequirements(raw) {
|
|
19661
|
+
if (void 0 === raw) return [];
|
|
19662
|
+
const result = [];
|
|
19663
|
+
for (const item of raw.split(/[,,\s]+/)){
|
|
19664
|
+
const cleaned = item.trim();
|
|
19665
|
+
if (cleaned.length > 0 && !result.includes(cleaned)) result.push(cleaned);
|
|
19666
|
+
}
|
|
19667
|
+
return result;
|
|
19668
|
+
}
|
|
19669
|
+
function prd_prdBaseline(options) {
|
|
19670
|
+
const prdDir = prdDirOf(options.layout, options.iteration);
|
|
19671
|
+
if (void 0 === options.node || 0 === options.node.trim().length) throw new PrdDwsError('NODE_MISSING', 'baseline 必须提供 --node(PRD 链接或 nodeId)');
|
|
19672
|
+
const documentMeta = probePrd(options.dwsPath, options.node);
|
|
19673
|
+
const existing = readMeta(prdDir);
|
|
19674
|
+
const sameRevision = null !== existing && Number(existing.updateTime ?? 0) === documentMeta.updateTime && existing.nodeId === documentMeta.nodeId;
|
|
19675
|
+
if (sameRevision && true !== options.force) return {
|
|
19676
|
+
exitCode: 0,
|
|
19677
|
+
result: {
|
|
19678
|
+
status: 'unchanged_baseline',
|
|
19679
|
+
mode: 'baseline',
|
|
19680
|
+
iteration: options.iteration,
|
|
19681
|
+
prdDirectory: prdDir,
|
|
19682
|
+
nodeId: documentMeta.nodeId,
|
|
19683
|
+
document: {
|
|
19684
|
+
title: documentMeta.title,
|
|
19685
|
+
updateTime: documentMeta.updateTime,
|
|
19686
|
+
updateTimeText: formatTimestamp(documentMeta.updateTime)
|
|
19687
|
+
},
|
|
19688
|
+
message: '基线与当前文档 updateTime 一致,未覆盖快照;如需强制重建请加 --force。'
|
|
19689
|
+
}
|
|
19690
|
+
};
|
|
19691
|
+
const document = fetchPrd(options.dwsPath, options.node);
|
|
19692
|
+
const snapshot = buildSnapshot({
|
|
19693
|
+
document,
|
|
19694
|
+
updateTime: documentMeta.updateTime,
|
|
19695
|
+
iteration: options.iteration
|
|
19696
|
+
});
|
|
19697
|
+
const meta = buildMeta(snapshot);
|
|
19698
|
+
writeSnapshotFiles(prdDir, snapshot, meta);
|
|
19699
|
+
const warnings = [];
|
|
19700
|
+
if ((meta.changelog.rowCount ?? 0) === 0) warnings.push('未识别到「变更记录」表格数据行:后续只能依赖章节摘要判定变更,无法给出产品登记的变更清单。');
|
|
19701
|
+
if (0 === Object.keys(meta.requirements).length) warnings.push('标题中未识别到需求编号:请确认 PRD 是否按「需求编号」组织章节。');
|
|
19702
|
+
for (const declaredId of Object.keys(meta.declaredRequirements))warnings.push(`需求 ${declaredId} 仅在正文中被声明,PRD 中无独立章节,无法按章节 diff。`);
|
|
19703
|
+
const wanted = splitRequirements(options.requirements);
|
|
19704
|
+
if (wanted.length > 0) {
|
|
19705
|
+
const missing = wanted.filter((id)=>void 0 === meta.requirements[id]);
|
|
19706
|
+
if (missing.length > 0) warnings.push(`以下需求编号在当前 PRD 中未找到对应章节:${missing.join(', ')}。`);
|
|
19707
|
+
}
|
|
19708
|
+
return {
|
|
19709
|
+
exitCode: 0,
|
|
19710
|
+
result: {
|
|
19711
|
+
status: 'success',
|
|
19712
|
+
mode: 'baseline',
|
|
19713
|
+
iteration: options.iteration,
|
|
19714
|
+
prdDirectory: prdDir,
|
|
19715
|
+
nodeId: document.nodeId,
|
|
19716
|
+
document: {
|
|
19717
|
+
title: document.title,
|
|
19718
|
+
docUrl: document.docUrl,
|
|
19719
|
+
revision: document.revision,
|
|
19720
|
+
updateTime: meta.updateTime,
|
|
19721
|
+
updateTimeText: meta.updateTimeText,
|
|
19722
|
+
blockCount: meta.blockCount,
|
|
19723
|
+
changelogRows: meta.changelog.rowCount
|
|
19724
|
+
},
|
|
19725
|
+
requirements: Object.fromEntries(Object.entries(meta.requirements).map(([id, entry])=>[
|
|
19726
|
+
id,
|
|
19727
|
+
{
|
|
19728
|
+
heading: entry.heading,
|
|
19729
|
+
sectionNo: entry.sectionNo,
|
|
19730
|
+
blockCount: entry.blockCount
|
|
19731
|
+
}
|
|
19732
|
+
])),
|
|
19733
|
+
warnings,
|
|
19734
|
+
nextCommands: [
|
|
19735
|
+
`ylcwf prd delta -i ${options.iteration}`
|
|
19736
|
+
]
|
|
19737
|
+
}
|
|
19738
|
+
};
|
|
19739
|
+
}
|
|
19740
|
+
function prd_prdDelta(options) {
|
|
19741
|
+
const prdDir = prdDirOf(options.layout, options.iteration);
|
|
19742
|
+
const meta = readMeta(prdDir);
|
|
19743
|
+
const snapshot = readSnapshot(prdDir);
|
|
19744
|
+
const requested = splitRequirements(options.requirement);
|
|
19745
|
+
const hasBaseline = null !== meta && null !== snapshot;
|
|
19746
|
+
const node = options.node ?? meta?.nodeId;
|
|
19747
|
+
if (!hasBaseline) {
|
|
19748
|
+
if (void 0 === node || 0 === node.trim().length) throw new PrdDwsError('NO_BASELINE', `未找到快照 ${external_node_path_join(prdDir, PRD_SNAPSHOT_NAME)},且未提供 --node`, '先执行 ylcwf prd baseline 建立快照,或在本次调用显式传 --node');
|
|
19749
|
+
const documentMeta = probePrd(options.dwsPath, node);
|
|
19750
|
+
const document = fetchPrd(options.dwsPath, node);
|
|
19751
|
+
const current = buildSnapshot({
|
|
19752
|
+
document,
|
|
19753
|
+
updateTime: documentMeta.updateTime,
|
|
19754
|
+
iteration: options.iteration
|
|
19755
|
+
});
|
|
19756
|
+
return {
|
|
19757
|
+
exitCode: 0,
|
|
19758
|
+
result: {
|
|
19759
|
+
status: 'no_baseline',
|
|
19760
|
+
mode: 'delta',
|
|
19761
|
+
iteration: options.iteration,
|
|
19762
|
+
prdDirectory: prdDir,
|
|
19763
|
+
nonPrecise: true,
|
|
19764
|
+
document: {
|
|
19765
|
+
nodeId: current.nodeId,
|
|
19766
|
+
title: current.title,
|
|
19767
|
+
revision: current.revision,
|
|
19768
|
+
updateTime: current.updateTime,
|
|
19769
|
+
updateTimeText: current.updateTimeText,
|
|
19770
|
+
blockCount: current.blockCount
|
|
19771
|
+
},
|
|
19772
|
+
warnings: [
|
|
19773
|
+
'当前没有可用快照,本次为全量现状,无法给出变更判定;建议执行 ylcwf prd baseline 建立基线。'
|
|
19774
|
+
],
|
|
19775
|
+
nextCommands: [
|
|
19776
|
+
`ylcwf prd baseline -i ${options.iteration} --node ${current.nodeId}`
|
|
19777
|
+
]
|
|
19778
|
+
}
|
|
19779
|
+
};
|
|
19780
|
+
}
|
|
19781
|
+
const baselineUpdate = Number(meta.updateTime ?? 0);
|
|
19782
|
+
const documentMeta = probePrd(options.dwsPath, node ?? meta.nodeId);
|
|
19783
|
+
const currentUpdate = documentMeta.updateTime;
|
|
19784
|
+
if (baselineUpdate === currentUpdate && true !== options.force) return {
|
|
19785
|
+
exitCode: 0,
|
|
19786
|
+
result: {
|
|
19787
|
+
status: 'unchanged',
|
|
19788
|
+
mode: 'delta',
|
|
19789
|
+
iteration: options.iteration,
|
|
19790
|
+
nodeId: meta.nodeId,
|
|
19791
|
+
nonPrecise: false,
|
|
19792
|
+
document: {
|
|
19793
|
+
title: meta.title,
|
|
19794
|
+
revision: meta.revision,
|
|
19795
|
+
updateTime: currentUpdate,
|
|
19796
|
+
updateTimeText: formatTimestamp(currentUpdate)
|
|
19797
|
+
},
|
|
19798
|
+
baseline: {
|
|
19799
|
+
revision: meta.revision,
|
|
19800
|
+
updateTime: baselineUpdate,
|
|
19801
|
+
updateTimeText: formatTimestamp(baselineUpdate)
|
|
19802
|
+
},
|
|
19803
|
+
message: 'PRD updateTime 与快照一致,未检测到文档更新;如需强制重拉请加 --force。',
|
|
19804
|
+
warnings: []
|
|
19805
|
+
}
|
|
19806
|
+
};
|
|
19807
|
+
const document = fetchPrd(options.dwsPath, options.node ?? meta.nodeId);
|
|
19808
|
+
const current = buildSnapshot({
|
|
19809
|
+
document,
|
|
19810
|
+
updateTime: currentUpdate,
|
|
19811
|
+
iteration: options.iteration
|
|
19812
|
+
});
|
|
19813
|
+
const oldBlocks = snapshot.blocks ?? [];
|
|
19814
|
+
const newBlocks = current.blocks;
|
|
19815
|
+
const oldRequirements = snapshot.requirements ?? {};
|
|
19816
|
+
const newRequirements = current.requirements;
|
|
19817
|
+
const oldChangelog = snapshot.changelog ?? {
|
|
19818
|
+
start: 0,
|
|
19819
|
+
end: -1,
|
|
19820
|
+
rows: [],
|
|
19821
|
+
digest: ''
|
|
19822
|
+
};
|
|
19823
|
+
const newChangelog = current.changelog;
|
|
19824
|
+
const oldRowKeys = new Set((oldChangelog.rows ?? []).map((cells)=>cells.join(' | ')));
|
|
19825
|
+
const newRowKeys = new Set((newChangelog?.rows ?? []).map((cells)=>cells.join(' | ')));
|
|
19826
|
+
const addedRows = (newChangelog?.rows ?? []).filter((cells)=>!oldRowKeys.has(cells.join(' | ')));
|
|
19827
|
+
const removedRows = (oldChangelog.rows ?? []).filter((cells)=>!newRowKeys.has(cells.join(' | ')));
|
|
19828
|
+
const targets = requested.length > 0 ? requested : [
|
|
19829
|
+
...new Set([
|
|
19830
|
+
...Object.keys(oldRequirements),
|
|
19831
|
+
...Object.keys(newRequirements)
|
|
19832
|
+
])
|
|
19833
|
+
];
|
|
19834
|
+
const warnings = [];
|
|
19835
|
+
const verdicts = [];
|
|
19836
|
+
const changedBlocks = [];
|
|
19837
|
+
const maxDiffLines = options.maxDiffLines ?? 120;
|
|
19838
|
+
const maxChanged = options.maxChangedRequirements ?? 5;
|
|
19839
|
+
for (const requirementId of targets){
|
|
19840
|
+
const oldEntry = oldRequirements[requirementId];
|
|
19841
|
+
const newEntry = newRequirements[requirementId];
|
|
19842
|
+
if (void 0 === oldEntry && void 0 === newEntry) {
|
|
19843
|
+
warnings.push(`需求 ${requirementId} 在当前 PRD 与快照中都不存在,请核对编号。`);
|
|
19844
|
+
verdicts.push({
|
|
19845
|
+
requirement: requirementId,
|
|
19846
|
+
verdict: 'unknown_requirement',
|
|
19847
|
+
registered: false,
|
|
19848
|
+
changed: false,
|
|
19849
|
+
evidence: []
|
|
19850
|
+
});
|
|
19851
|
+
continue;
|
|
19852
|
+
}
|
|
19853
|
+
const sectionNo = newEntry?.sectionNo ?? oldEntry?.sectionNo ?? null;
|
|
19854
|
+
const registeredRows = matchedRows(addedRows.map((cells)=>[
|
|
19855
|
+
...cells
|
|
19856
|
+
]), requirementId, sectionNo);
|
|
19857
|
+
const registered = registeredRows.length > 0;
|
|
19858
|
+
const changed = oldEntry?.digest !== newEntry?.digest;
|
|
19859
|
+
let verdict = 'unchanged';
|
|
19860
|
+
if (registered && changed) verdict = 'registered_and_changed';
|
|
19861
|
+
else if (registered && !changed) verdict = 'registered_not_changed';
|
|
19862
|
+
else if (changed) {
|
|
19863
|
+
verdict = 'unregistered_change';
|
|
19864
|
+
warnings.push(`需求 ${requirementId} 正文已变化,但变更记录没有对应新增条目(疑似静默改稿),必须人工确认。`);
|
|
19865
|
+
}
|
|
19866
|
+
verdicts.push({
|
|
19867
|
+
requirement: requirementId,
|
|
19868
|
+
verdict,
|
|
19869
|
+
registered,
|
|
19870
|
+
changed,
|
|
19871
|
+
heading: newEntry?.heading ?? oldEntry?.heading ?? null,
|
|
19872
|
+
sectionNo,
|
|
19873
|
+
evidence: registeredRows.map((row)=>row.row)
|
|
19874
|
+
});
|
|
19875
|
+
if (changed && changedBlocks.length < maxChanged) {
|
|
19876
|
+
const diff = blockDiff({
|
|
19877
|
+
oldBlocks,
|
|
19878
|
+
newBlocks,
|
|
19879
|
+
oldRange: void 0 === oldEntry ? [
|
|
19880
|
+
0,
|
|
19881
|
+
-1
|
|
19882
|
+
] : [
|
|
19883
|
+
oldEntry.start,
|
|
19884
|
+
oldEntry.end
|
|
19885
|
+
],
|
|
19886
|
+
newRange: void 0 === newEntry ? [
|
|
19887
|
+
0,
|
|
19888
|
+
-1
|
|
19889
|
+
] : [
|
|
19890
|
+
newEntry.start,
|
|
19891
|
+
newEntry.end
|
|
19892
|
+
],
|
|
19893
|
+
maxLines: maxDiffLines
|
|
19894
|
+
});
|
|
19895
|
+
changedBlocks.push({
|
|
19896
|
+
...diff,
|
|
19897
|
+
requirement: requirementId,
|
|
19898
|
+
heading: newEntry?.heading ?? oldEntry?.heading ?? null,
|
|
19899
|
+
status: void 0 !== oldEntry && void 0 !== newEntry ? 'modified' : void 0 !== newEntry ? 'added' : 'removed'
|
|
19900
|
+
});
|
|
19901
|
+
}
|
|
19902
|
+
}
|
|
19903
|
+
if (removedRows.length > 0) warnings.push('变更记录中存在被删除或改写的行,请确认是产品整理还是回滚。');
|
|
19904
|
+
return {
|
|
19905
|
+
exitCode: 0,
|
|
19906
|
+
result: {
|
|
19907
|
+
status: 0 === addedRows.length && 0 === changedBlocks.length ? 'formatting_only' : 'success',
|
|
19908
|
+
mode: 'delta',
|
|
19909
|
+
iteration: options.iteration,
|
|
19910
|
+
prdDirectory: prdDir,
|
|
19911
|
+
nodeId: current.nodeId,
|
|
19912
|
+
nonPrecise: false,
|
|
19913
|
+
document: {
|
|
19914
|
+
title: current.title,
|
|
19915
|
+
docUrl: current.docUrl,
|
|
19916
|
+
revision: current.revision,
|
|
19917
|
+
updateTime: currentUpdate,
|
|
19918
|
+
updateTimeText: formatTimestamp(currentUpdate)
|
|
19919
|
+
},
|
|
19920
|
+
baseline: {
|
|
19921
|
+
revision: meta.revision,
|
|
19922
|
+
updateTime: baselineUpdate,
|
|
19923
|
+
updateTimeText: formatTimestamp(baselineUpdate),
|
|
19924
|
+
changelogRowCount: (oldChangelog.rows ?? []).length
|
|
19925
|
+
},
|
|
19926
|
+
changelog: {
|
|
19927
|
+
available: null !== newChangelog,
|
|
19928
|
+
addedCount: addedRows.length,
|
|
19929
|
+
removedCount: removedRows.length,
|
|
19930
|
+
added: addedRows.map((cells)=>describeRow(cells)),
|
|
19931
|
+
removed: removedRows.map((cells)=>describeRow(cells))
|
|
19932
|
+
},
|
|
19933
|
+
changedBlocks,
|
|
19934
|
+
verdicts,
|
|
19935
|
+
warnings,
|
|
19936
|
+
nextCommands: [
|
|
19937
|
+
`ylcwf prd baseline -i ${options.iteration} --node ${current.nodeId} --force`
|
|
19938
|
+
]
|
|
19939
|
+
}
|
|
19940
|
+
};
|
|
19941
|
+
}
|
|
19942
|
+
function prdCheck(options) {
|
|
19943
|
+
const prdDir = prdDirOf(options.layout, options.iteration);
|
|
19944
|
+
const meta = readMeta(prdDir);
|
|
19945
|
+
const snapshot = readSnapshot(prdDir);
|
|
19946
|
+
const problems = [];
|
|
19947
|
+
const warnings = [];
|
|
19948
|
+
if (null === meta || null === snapshot) {
|
|
19949
|
+
const missing = [
|
|
19950
|
+
...null === meta ? [
|
|
19951
|
+
PRD_META_NAME
|
|
19952
|
+
] : [],
|
|
19953
|
+
...null === snapshot ? [
|
|
19954
|
+
PRD_SNAPSHOT_NAME
|
|
19955
|
+
] : []
|
|
19956
|
+
];
|
|
19957
|
+
return {
|
|
19958
|
+
exitCode: 1,
|
|
19959
|
+
result: {
|
|
19960
|
+
status: 'no_baseline',
|
|
19961
|
+
mode: 'check',
|
|
19962
|
+
iteration: options.iteration,
|
|
19963
|
+
prdDirectory: prdDir,
|
|
19964
|
+
problems: [
|
|
19965
|
+
`缺少基线文件:${missing.join(', ')}`
|
|
19966
|
+
],
|
|
19967
|
+
warnings: []
|
|
19968
|
+
}
|
|
19969
|
+
};
|
|
19970
|
+
}
|
|
19971
|
+
if (snapshot.schemaVersion !== PRD_SNAPSHOT_SCHEMA_VERSION) warnings.push(`snapshot.json 的结构标识为「${snapshot.schemaVersion}」,当前版本期望「${PRD_SNAPSHOT_SCHEMA_VERSION}」;建议 baseline --force 重建。`);
|
|
19972
|
+
if (meta.schemaVersion !== PRD_META_SCHEMA_VERSION) warnings.push(`meta.json 的结构标识为「${meta.schemaVersion}」,当前版本期望「${PRD_META_SCHEMA_VERSION}」;建议 baseline --force 重建。`);
|
|
19973
|
+
const blocks = snapshot.blocks ?? [];
|
|
19974
|
+
if (Number(snapshot.blockCount ?? 0) !== blocks.length) problems.push('snapshot.blockCount 与 blocks 实际数量不一致');
|
|
19975
|
+
for (const [requirementId, entry] of Object.entries(snapshot.requirements ?? {})){
|
|
19976
|
+
if (entry.start < 0 || entry.end >= blocks.length || entry.start > entry.end) {
|
|
19977
|
+
problems.push(`需求 ${requirementId} 的块区间越界:${entry.start}..${entry.end}`);
|
|
19978
|
+
continue;
|
|
19979
|
+
}
|
|
19980
|
+
if (pagesDigest(blocks.slice(entry.start, entry.end + 1)) !== entry.digest) problems.push(`需求 ${requirementId} 的块区间摘要与 digest 不一致`);
|
|
19981
|
+
}
|
|
19982
|
+
const recomputedChangelog = findChangelog(blocks);
|
|
19983
|
+
if ((recomputedChangelog?.digest ?? null) !== (snapshot.changelog?.digest ?? null)) problems.push('snapshot.changelog 的 digest 与块内容不一致');
|
|
19984
|
+
const metaRequirements = meta.requirements ?? {};
|
|
19985
|
+
const snapshotRequirements = snapshot.requirements ?? {};
|
|
19986
|
+
if (Object.keys(metaRequirements).sort().join(',') !== Object.keys(snapshotRequirements).sort().join(',')) warnings.push('meta.json 与 snapshot.json 的需求编号集合不一致,建议重建基线');
|
|
19987
|
+
else for (const [requirementId, entry] of Object.entries(metaRequirements))if (entry.digest !== snapshotRequirements[requirementId]?.digest) problems.push(`需求 ${requirementId} 的 digest 在两份文件中不一致`);
|
|
19988
|
+
if (meta.revision !== snapshot.revision) problems.push('meta.json 与 snapshot.json 的 revision 不一致');
|
|
19989
|
+
return {
|
|
19990
|
+
exitCode: 0 === problems.length ? 0 : 1,
|
|
19991
|
+
result: {
|
|
19992
|
+
status: 0 === problems.length ? 'success' : 'broken',
|
|
19993
|
+
mode: 'check',
|
|
19994
|
+
iteration: options.iteration,
|
|
19995
|
+
prdDirectory: prdDir,
|
|
19996
|
+
nodeId: meta.nodeId,
|
|
19997
|
+
document: {
|
|
19998
|
+
title: meta.title,
|
|
19999
|
+
revision: meta.revision,
|
|
20000
|
+
updateTimeText: meta.updateTimeText,
|
|
20001
|
+
blockCount: meta.blockCount
|
|
20002
|
+
},
|
|
20003
|
+
problems,
|
|
20004
|
+
warnings
|
|
20005
|
+
}
|
|
20006
|
+
};
|
|
20007
|
+
}
|
|
20008
|
+
function positiveInteger(value, label, fallback) {
|
|
20009
|
+
if (void 0 === value) return fallback;
|
|
20010
|
+
const parsed = Number.parseInt(value, 10);
|
|
20011
|
+
if (!Number.isInteger(parsed) || parsed <= 0) throw new errors_CliError(`${label} 必须是正整数:${value}`, errors_EXIT.USAGE);
|
|
20012
|
+
return parsed;
|
|
20013
|
+
}
|
|
20014
|
+
function buildOptions(options) {
|
|
20015
|
+
const loaded = config_loadConfig(options.config);
|
|
20016
|
+
if (!loaded.exists || null === loaded.config) throw new errors_CliError(`配置未初始化:${loaded.path}\n请先运行:ylcwf init`, errors_EXIT.NOT_FOUND);
|
|
20017
|
+
const baseLayout = layoutOf(loaded.config);
|
|
20018
|
+
const layout = void 0 === options.docsRoot ? baseLayout : {
|
|
20019
|
+
...baseLayout,
|
|
20020
|
+
root: external_node_path_resolve(options.docsRoot)
|
|
20021
|
+
};
|
|
20022
|
+
return {
|
|
20023
|
+
layout,
|
|
20024
|
+
iteration: options.iteration.trim(),
|
|
20025
|
+
dwsPath: (options.dwsPath ?? 'dws').trim()
|
|
20026
|
+
};
|
|
20027
|
+
}
|
|
20028
|
+
function printPrdHuman(result) {
|
|
20029
|
+
const mode = String(result['mode'] ?? '');
|
|
20030
|
+
printLine(`模式:${mode} 迭代:${String(result['iteration'] ?? '')} 状态:${String(result['status'] ?? '')}`);
|
|
20031
|
+
const document = result['document'];
|
|
20032
|
+
if ('object' == typeof document && null !== document) {
|
|
20033
|
+
const info = document;
|
|
20034
|
+
printLine(`文档:${String(info['title'] ?? '未提供')} revision ${String(info['revision'] ?? '—')} 更新时间:${String(info['updateTimeText'] ?? '—')}`);
|
|
20035
|
+
}
|
|
20036
|
+
const baseline = result['baseline'];
|
|
20037
|
+
if ('object' == typeof baseline && null !== baseline) {
|
|
20038
|
+
const info = baseline;
|
|
20039
|
+
printLine(`基线:revision ${String(info['revision'] ?? '—')} ${String(info['updateTimeText'] ?? '—')}`);
|
|
20040
|
+
}
|
|
20041
|
+
const changelog = result['changelog'];
|
|
20042
|
+
if ('delta' === mode && 'object' == typeof changelog && null !== changelog) {
|
|
20043
|
+
const info = changelog;
|
|
20044
|
+
printLine(`变更记录:新增 ${String(info['addedCount'] ?? 0)} 行,删除或改写 ${String(info['removedCount'] ?? 0)} 行`);
|
|
20045
|
+
const added = Array.isArray(info['added']) ? info['added'] : [];
|
|
20046
|
+
for (const row of added)printLine(` + ${String(row['row'] ?? '')}`);
|
|
20047
|
+
}
|
|
20048
|
+
const verdicts = Array.isArray(result['verdicts']) ? result['verdicts'] : [];
|
|
20049
|
+
if (verdicts.length > 0) {
|
|
20050
|
+
printLine('四态判定:');
|
|
20051
|
+
for (const verdict of verdicts)printLine(` #${String(verdict['requirement'] ?? '')} ${String(verdict['heading'] ?? '')} → ${String(verdict['verdict'] ?? '')}`);
|
|
20052
|
+
}
|
|
20053
|
+
const changed = Array.isArray(result['changedBlocks']) ? result['changedBlocks'] : [];
|
|
20054
|
+
for (const block of changed){
|
|
20055
|
+
printLine('');
|
|
20056
|
+
printLine(`块级差异:#${String(block['requirement'] ?? '')} ${String(block['heading'] ?? '')}(+${String(block['addedBlocks'] ?? 0)}/-${String(block['removedBlocks'] ?? 0)})`);
|
|
20057
|
+
printLine(String(block['diff'] ?? ''));
|
|
20058
|
+
if (true === block['truncated']) printLine('... diff 已截断,可用 --max-diff-lines 放大');
|
|
20059
|
+
}
|
|
20060
|
+
const requirements = result['requirements'];
|
|
20061
|
+
if ('baseline' === mode && 'object' == typeof requirements && null !== requirements) {
|
|
20062
|
+
printLine('需求章节:');
|
|
20063
|
+
for (const [id, entry] of Object.entries(requirements))printLine(` #${id} ${String(entry['heading'] ?? '')}`);
|
|
20064
|
+
}
|
|
20065
|
+
for (const warning of Array.isArray(result['warnings']) ? result['warnings'] : [])printLine(`警告:${warning}`);
|
|
20066
|
+
for (const problem of Array.isArray(result['problems']) ? result['problems'] : [])printLine(`问题:${problem}`);
|
|
20067
|
+
if ('string' == typeof result['message']) printLine(`说明:${result['message']}`);
|
|
20068
|
+
for (const command of Array.isArray(result['nextCommands']) ? result['nextCommands'] : [])printLine(`下一步:${command}`);
|
|
20069
|
+
}
|
|
20070
|
+
function prd_run(handler, format, onSuccess) {
|
|
20071
|
+
let outcome;
|
|
20072
|
+
try {
|
|
20073
|
+
outcome = handler();
|
|
20074
|
+
} catch (error) {
|
|
20075
|
+
if (error instanceof PrdDwsError) {
|
|
20076
|
+
const payload = {
|
|
20077
|
+
status: 'failed',
|
|
20078
|
+
error: error.toDict()
|
|
20079
|
+
};
|
|
20080
|
+
if ('json' === format) printJson(payload);
|
|
20081
|
+
else {
|
|
20082
|
+
printLine(`失败:${error.code} ${error.message}`);
|
|
20083
|
+
if (error.hint.length > 0) printLine(`建议:${error.hint}`);
|
|
20084
|
+
}
|
|
20085
|
+
process.exitCode = errors_EXIT.INVALID;
|
|
20086
|
+
return;
|
|
20087
|
+
}
|
|
20088
|
+
throw error;
|
|
20089
|
+
}
|
|
20090
|
+
if ('json' === format) printJson(outcome.result);
|
|
20091
|
+
else printPrdHuman(outcome.result);
|
|
20092
|
+
if (0 !== outcome.exitCode) process.exitCode = outcome.exitCode;
|
|
20093
|
+
onSuccess?.(outcome.exitCode);
|
|
20094
|
+
}
|
|
20095
|
+
function registerPrd(program) {
|
|
20096
|
+
const prd = program.command('prd').description('钉钉 PRD 快照与变更检测(通过本机 dws 取数)');
|
|
20097
|
+
const common = (command)=>command.requiredOption('-i, --iteration <name>', '迭代目录名(可写「年份/迭代名」)').option('-c, --config <path>', '指定配置文件路径').option('--docs-root <path>', '覆盖配置里的文档仓库路径').option('--dws-path <path>', 'dws 可执行文件路径(默认从 PATH 探测)').option('--format <format>', '输出格式:human | json', 'human');
|
|
20098
|
+
common(prd.command('baseline')).description('生成/刷新 PRD 快照(updateTime 未变且未加 --force 时不拉全文)').requiredOption('--node <node>', 'PRD 文档链接或 nodeId').option('--requirements <ids>', '关注的需求编号,逗号分隔(仅用于命中校验)').option('--force', 'updateTime 未变时也重建快照').action((options)=>{
|
|
20099
|
+
const format = parseFormat(options.format);
|
|
20100
|
+
enableJsonErrors('json' === format);
|
|
20101
|
+
const base = buildOptions(options);
|
|
20102
|
+
prd_run(()=>prd_prdBaseline({
|
|
20103
|
+
...base,
|
|
20104
|
+
force: true === options.force,
|
|
20105
|
+
node: options.node,
|
|
20106
|
+
requirements: options.requirements
|
|
20107
|
+
}), format);
|
|
20108
|
+
});
|
|
20109
|
+
common(prd.command('delta')).description('比对当前 PRD 与快照(先探测 updateTime,未变化不拉全文)').option('--node <node>', 'PRD 链接或 nodeId(缺省用快照记录的 nodeId)').option('--requirement <ids>', '只看指定需求编号,逗号分隔').option('--max-diff-lines <n>', '单个需求的块级 diff 最大行数', '120').option('--max-changed-requirements <n>', '最多输出块级 diff 的需求数', '5').option('--force', 'updateTime 未变时也强制重拉比对').action((options)=>{
|
|
20110
|
+
const format = parseFormat(options.format);
|
|
20111
|
+
enableJsonErrors('json' === format);
|
|
20112
|
+
const base = buildOptions(options);
|
|
20113
|
+
prd_run(()=>prd_prdDelta({
|
|
20114
|
+
...base,
|
|
20115
|
+
force: true === options.force,
|
|
20116
|
+
node: options.node,
|
|
20117
|
+
requirement: options.requirement,
|
|
20118
|
+
maxDiffLines: positiveInteger(options.maxDiffLines, '--max-diff-lines', 120),
|
|
20119
|
+
maxChangedRequirements: positiveInteger(options.maxChangedRequirements, '--max-changed-requirements', 5)
|
|
20120
|
+
}), format);
|
|
20121
|
+
});
|
|
20122
|
+
common(prd.command('check')).description('校验快照文件完整性(只读,不调用 dws)').action((options)=>{
|
|
20123
|
+
const format = parseFormat(options.format);
|
|
20124
|
+
enableJsonErrors('json' === format);
|
|
20125
|
+
const base = buildOptions(options);
|
|
20126
|
+
prd_run(()=>prdCheck(base), format);
|
|
20127
|
+
});
|
|
20128
|
+
}
|
|
17556
20129
|
async function runReset(options) {
|
|
17557
20130
|
const configPath = paths_resolveConfigPath(options.config);
|
|
17558
20131
|
const targets = collectResetTargets(configPath);
|
|
@@ -17578,7 +20151,7 @@ function registerReset(program) {
|
|
|
17578
20151
|
}
|
|
17579
20152
|
function buildProgram() {
|
|
17580
20153
|
const program = new command_Command();
|
|
17581
|
-
program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与执行终端仓库映射').version("0.
|
|
20154
|
+
program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与执行终端仓库映射').version("0.8.0", '-v, --version', '显示版本号').showHelpAfterError();
|
|
17582
20155
|
registerInit(program);
|
|
17583
20156
|
registerShow(program);
|
|
17584
20157
|
registerGet(program);
|
|
@@ -17586,6 +20159,7 @@ function buildProgram() {
|
|
|
17586
20159
|
registerTerminal(program);
|
|
17587
20160
|
registerIteration(program);
|
|
17588
20161
|
registerContext(program);
|
|
20162
|
+
registerGuide(program);
|
|
17589
20163
|
registerRequirement(program);
|
|
17590
20164
|
registerDoc(program);
|
|
17591
20165
|
registerTask(program);
|
|
@@ -17595,6 +20169,7 @@ function buildProgram() {
|
|
|
17595
20169
|
registerPath(program);
|
|
17596
20170
|
registerServe(program);
|
|
17597
20171
|
registerYapi(program);
|
|
20172
|
+
registerPrd(program);
|
|
17598
20173
|
registerReset(program);
|
|
17599
20174
|
return program;
|
|
17600
20175
|
}
|