ylcwf 0.7.0 → 0.9.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/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import { EventEmitter } from "node:events";
2
2
  import node_child_process, { execFile, execFileSync, spawn } from "node:child_process";
3
3
  import node_path, { basename, dirname as external_node_path_dirname, extname, isAbsolute as external_node_path_isAbsolute, join as external_node_path_join, relative as external_node_path_relative, resolve as external_node_path_resolve, sep } from "node:path";
4
- import node_fs, { appendFileSync, chmodSync, closeSync, copyFileSync, existsSync as external_node_fs_existsSync, mkdirSync, openSync, readFileSync, readdirSync as external_node_fs_readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
4
+ import node_fs, { accessSync, appendFileSync, chmodSync, closeSync, constants, copyFileSync, existsSync as external_node_fs_existsSync, mkdirSync, openSync, readFileSync, readdirSync as external_node_fs_readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync, writeSync } from "node:fs";
5
5
  import node_process, { stdin as external_node_process_stdin, stdout as external_node_process_stdout } from "node:process";
6
6
  import { stripVTControlCharacters as external_node_util_stripVTControlCharacters, styleText as external_node_util_styleText } from "node:util";
7
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";
@@ -8194,10 +8194,12 @@ const errors_EXIT = {
8194
8194
  };
8195
8195
  class errors_CliError extends Error {
8196
8196
  exitCode;
8197
- constructor(message, exitCode){
8197
+ details;
8198
+ constructor(message, exitCode, details){
8198
8199
  super(message);
8199
8200
  this.name = 'CliError';
8200
8201
  this.exitCode = exitCode;
8202
+ this.details = details;
8201
8203
  }
8202
8204
  }
8203
8205
  function printJson(value) {
@@ -8216,13 +8218,14 @@ function enableJsonErrors(value) {
8216
8218
  function jsonErrorsEnabled() {
8217
8219
  return jsonErrors;
8218
8220
  }
8219
- function printJsonError(message, exitCode) {
8221
+ function printJsonError(message, exitCode, details) {
8220
8222
  printJson({
8221
8223
  ok: false,
8222
8224
  exitCode,
8223
8225
  error: {
8224
8226
  message,
8225
- code: exitCode
8227
+ code: exitCode,
8228
+ ...details
8226
8229
  }
8227
8230
  });
8228
8231
  }
@@ -8643,7 +8646,7 @@ function isActionKey(n, e) {
8643
8646
  for (const s of n)if (void 0 !== s && isActionKey(s, e)) return true;
8644
8647
  return false;
8645
8648
  }
8646
- function diffLines(i, s) {
8649
+ function dist_diffLines(i, s) {
8647
8650
  if (i === s) return;
8648
8651
  const e = i.split(`
8649
8652
  `), t = s.split(`
@@ -8811,7 +8814,7 @@ let C$1 = class {
8811
8814
  if (t !== this._prevFrame) {
8812
8815
  if ("initial" === this.state) this.output.write(dist_cursor.hide);
8813
8816
  else {
8814
- const e = diffLines(this._prevFrame, t), i = getRows(this.output);
8817
+ const e = dist_diffLines(this._prevFrame, t), i = getRows(this.output);
8815
8818
  if (this.restoreCursor(), e) {
8816
8819
  const s = Math.max(0, e.numLinesAfter - i), r = Math.max(0, e.numLinesBefore - i);
8817
8820
  let n = e.lines.find((o)=>o >= s);
@@ -9248,6 +9251,85 @@ function historyPath() {
9248
9251
  function backupsDir(configPath) {
9249
9252
  return external_node_path_join(external_node_path_dirname(configPath), 'backups');
9250
9253
  }
9254
+ const HINTS = {
9255
+ EPERM: '策略拒绝(不是普通权限不足)。常见于 AI 会话只被授权写当前工作区,或文件带不可修改标记',
9256
+ EACCES: '权限不足。目标目录的属主或权限位不允许当前用户写入',
9257
+ EROFS: '目标位于只读文件系统或只读挂载上',
9258
+ EBUSY: '文件正被其它进程占用(IDE、同步盘、杀毒软件)',
9259
+ ETXTBSY: '文件正在被当作可执行文件使用',
9260
+ ENOSPC: '磁盘空间不足',
9261
+ EMFILE: '进程打开的文件数超过上限'
9262
+ };
9263
+ const READ_HINTS = {
9264
+ EPERM: '策略拒绝(不是普通权限不足)。当前会话可能未被授权访问该路径(会话文件访问范围限制)',
9265
+ EACCES: '权限不足。目标目录的属主或权限位不允许当前用户读取',
9266
+ EROFS: '目标位于只读文件系统或只读挂载上',
9267
+ EBUSY: '文件正被其它进程占用(IDE、同步盘、杀毒软件)'
9268
+ };
9269
+ function describeFsHint(code, kind = 'write') {
9270
+ if (void 0 === code) return null;
9271
+ return ('read' === kind ? READ_HINTS[code] : HINTS[code]) ?? null;
9272
+ }
9273
+ function fsError(kind, error, scope) {
9274
+ const errnoError = error;
9275
+ const code = errnoError.code;
9276
+ const syscall = errnoError.syscall;
9277
+ const paths = [
9278
+ scope.target,
9279
+ ...scope.others ?? []
9280
+ ];
9281
+ const verb = 'read' === kind ? '读取' : '写入';
9282
+ const lines = [
9283
+ `${verb}失败:${scope.action ?? ('read' === kind ? '读文件' : '写文件')}`
9284
+ ];
9285
+ lines.push(` · 目标:${scope.target}`);
9286
+ if (paths.length > 1) {
9287
+ lines.push(' · 本次还需要写:');
9288
+ for (const path of paths.slice(1))lines.push(` - ${path}`);
9289
+ }
9290
+ lines.push('');
9291
+ lines.push(`原因:${code ?? '未知错误'}(${errnoError.message.split('\n')[0] ?? String(error)})`);
9292
+ const hint = describeFsHint(code, kind);
9293
+ if (null !== hint) lines.push(`可能原因:${hint}`);
9294
+ if ('EPERM' === code || 'EACCES' === code) if ('read' === kind) {
9295
+ lines.push(' → 当前会话没有该目录的访问权限:让会话能访问文档仓库所在目录');
9296
+ lines.push(' (放宽会话的文件访问范围),或换一个有权限的终端执行');
9297
+ lines.push(' → 或把 docs.root 指到会话内的仓库');
9298
+ } else {
9299
+ lines.push(' → 当前会话没有该目录的写权限:让会话能写文档仓库所在目录');
9300
+ lines.push(' (放宽会话的文件写入范围),或换一个有权限的终端执行');
9301
+ lines.push(' → 或把 docs.root 指到会话内可写的位置');
9302
+ lines.push(' → 文件被加锁:确认没有同步盘/杀软占用(macOS 可用 ls -lO 看 uchg 标记)');
9303
+ }
9304
+ else if ('EROFS' === code) lines.push(' → 目标位于只读挂载:换到可写位置,或重新挂载为可写');
9305
+ else if ('EBUSY' === code || 'ETXTBSY' === code) lines.push(' → 关闭占用该文件的程序后重试');
9306
+ if (void 0 !== syscall) lines.push(` (syscall: ${syscall})`);
9307
+ const details = {
9308
+ kind: 'read' === kind ? 'read-failed' : 'write-failed',
9309
+ path: scope.target,
9310
+ paths,
9311
+ ...void 0 === code ? {} : {
9312
+ errno: code
9313
+ },
9314
+ ...void 0 === syscall ? {} : {
9315
+ syscall
9316
+ }
9317
+ };
9318
+ return new errors_CliError(lines.join('\n'), errors_EXIT.INVALID, details);
9319
+ }
9320
+ function writeError(error, scope) {
9321
+ return fsError('write', error, scope);
9322
+ }
9323
+ function readError(error, scope) {
9324
+ return fsError('read', error, scope);
9325
+ }
9326
+ function writeTextFile(scope, text) {
9327
+ try {
9328
+ writeFileSync(scope.target, text, 'utf8');
9329
+ } catch (error) {
9330
+ throw writeError(error, scope);
9331
+ }
9332
+ }
9251
9333
  const TERMINAL_CATALOG_FILE = 'execution_terminals.json';
9252
9334
  function terminals_error(code, message, where) {
9253
9335
  return void 0 === where ? {
@@ -9439,7 +9521,7 @@ const DOCS_KEYS = new Set([
9439
9521
  'validator'
9440
9522
  ]);
9441
9523
  const VALIDATOR_KEYS = new Set([
9442
- 'requireScript'
9524
+ 'strict'
9443
9525
  ]);
9444
9526
  const GIT_KEYS = new Set([
9445
9527
  'cli',
@@ -9450,11 +9532,11 @@ const POLICY_KEYS = new Set([
9450
9532
  'push'
9451
9533
  ]);
9452
9534
  const DEFAULT_GIT_POLICY = {
9453
- commit: true,
9535
+ commit: false,
9454
9536
  push: false
9455
9537
  };
9456
9538
  const DEFAULT_VALIDATOR_POLICY = {
9457
- requireScript: true
9539
+ strict: true
9458
9540
  };
9459
9541
  const TERMINAL_KEYS = new Set([
9460
9542
  'repos'
@@ -9474,7 +9556,7 @@ function schema_error(code, message, where) {
9474
9556
  }
9475
9557
  };
9476
9558
  }
9477
- function warning(code, message, where) {
9559
+ function schema_warning(code, message, where) {
9478
9560
  return {
9479
9561
  level: 'warning',
9480
9562
  code,
@@ -9601,16 +9683,16 @@ function parseValidatorPolicy(raw, issues) {
9601
9683
  return null;
9602
9684
  }
9603
9685
  issues.push(...unknownKeys(raw, VALIDATOR_KEYS, 'docs.validator'));
9604
- const value = raw['requireScript'];
9686
+ const value = raw['strict'];
9605
9687
  if (void 0 === value) return {
9606
9688
  ...DEFAULT_VALIDATOR_POLICY
9607
9689
  };
9608
9690
  if ('boolean' != typeof value) {
9609
- issues.push(schema_error('VALIDATOR_POLICY_INVALID', 'docs.validator.requireScript 必须是布尔值', 'docs.validator.requireScript'));
9691
+ issues.push(schema_error('VALIDATOR_POLICY_INVALID', 'docs.validator.strict 必须是布尔值', 'docs.validator.strict'));
9610
9692
  return null;
9611
9693
  }
9612
9694
  return {
9613
- requireScript: value
9695
+ strict: value
9614
9696
  };
9615
9697
  }
9616
9698
  function parseGitPolicy(raw, issues) {
@@ -9762,6 +9844,13 @@ function checkFsOfDocs(config, issues) {
9762
9844
  if ('' === root) return;
9763
9845
  if (!external_node_fs_existsSync(root)) return void issues.push(schema_error('DOCS_ROOT_MISSING', `文档仓库不存在:${root}`, 'docs.root'));
9764
9846
  if (!statSync(root).isDirectory()) return void issues.push(schema_error('DOCS_ROOT_NOT_DIR', `文档仓库不是目录:${root}`, 'docs.root'));
9847
+ try {
9848
+ accessSync(root, constants.R_OK);
9849
+ } catch (failure) {
9850
+ const code = failure.code;
9851
+ issues.push(schema_error('DOCS_ROOT_UNREADABLE', `文档仓库不可读:${root}(${code ?? '未知错误'})\n 当前会话可能未被授权访问该目录(会话文件访问范围限制),或目录权限位不允许读取\n → 把文档仓库所在目录授权给会话后重试`, 'docs.root'));
9852
+ return;
9853
+ }
9765
9854
  if (!external_node_fs_existsSync(external_node_path_join(root, 'skills', 'iteration-task-docs', 'SKILL.md'))) issues.push(schema_error('DOCS_ROOT_NO_SKILL', `文档仓库缺少 skills/iteration-task-docs/SKILL.md:${root}`, 'docs.root'));
9766
9855
  }
9767
9856
  function checkFsOfTerminals(config, issues) {
@@ -9770,7 +9859,7 @@ function checkFsOfTerminals(config, issues) {
9770
9859
  const targets = terminal.repos[side];
9771
9860
  const where = `terminals.${name}.repos.${side}`;
9772
9861
  if (0 === targets.length) {
9773
- if ('fullstack' === config.profile.role) issues.push(warning('SIDE_NOT_CONFIGURED', `角色为 fullstack,但「${name}」未配置 ${side} 仓库`, where));
9862
+ if ('fullstack' === config.profile.role) issues.push(schema_warning('SIDE_NOT_CONFIGURED', `角色为 fullstack,但「${name}」未配置 ${side} 仓库`, where));
9774
9863
  continue;
9775
9864
  }
9776
9865
  for (const target of targets){
@@ -9782,7 +9871,7 @@ function checkFsOfTerminals(config, issues) {
9782
9871
  issues.push(schema_error('REPO_PATH_NOT_DIR', `仓库路径不是目录:${target}`, where));
9783
9872
  continue;
9784
9873
  }
9785
- if (!external_node_fs_existsSync(external_node_path_join(target, '.git'))) issues.push(warning('REPO_NOT_GIT', `路径不是 git 仓库:${target}`, where));
9874
+ if (!external_node_fs_existsSync(external_node_path_join(target, '.git'))) issues.push(schema_warning('REPO_NOT_GIT', `路径不是 git 仓库:${target}`, where));
9786
9875
  const entry = pathOwners.get(`${side}:${target}`) ?? {
9787
9876
  side,
9788
9877
  target,
@@ -9792,7 +9881,7 @@ function checkFsOfTerminals(config, issues) {
9792
9881
  pathOwners.set(`${side}:${target}`, entry);
9793
9882
  }
9794
9883
  }
9795
- for (const entry of pathOwners.values())if (!(entry.owners.length < 2)) issues.push(warning('REPO_PATH_SHARED', `${entry.side} 仓库路径被多个执行终端复用:${entry.target}(${entry.owners.join('、')})`, 'terminals'));
9884
+ 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
9885
  }
9797
9886
  function checkConfig(raw, options = {}) {
9798
9887
  const issues = [];
@@ -9819,7 +9908,7 @@ function checkConfig(raw, options = {}) {
9819
9908
  docs,
9820
9909
  terminals
9821
9910
  };
9822
- if (0 === Object.keys(terminals).length) issues.push(warning('TERMINALS_EMPTY', "尚未配置任何执行终端映射:ylcwf resolve、任务「所属端」与仓库归属校验、doc migrate 回填都将不可用。\n 补配置:ylcwf terminal add <执行终端名> --frontend <仓库路径>\n (后端仓库用 --backend,两端都有就同时传;每端多个仓库可重复该选项)", 'terminals'));
9911
+ 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
9912
  issues.push(...checkTerminalIdentity(terminals));
9824
9913
  if (true === options.checkFs) {
9825
9914
  checkFsOfDocs(config, issues);
@@ -9932,8 +10021,8 @@ profile:
9932
10021
  docs:
9933
10022
  root: ''
9934
10023
  git:
9935
- cli: { commit: true, push: false }
9936
- ui: { commit: true, push: false }
10024
+ cli: { commit: false, push: false }
10025
+ ui: { commit: false, push: false }
9937
10026
 
9938
10027
  terminals: {}
9939
10028
  `;
@@ -10052,8 +10141,19 @@ function saveDocument(doc, target) {
10052
10141
  withConfigLock(target, ()=>{
10053
10142
  if (external_node_fs_existsSync(target)) backup(target);
10054
10143
  const tmp = `${target}.tmp-${process.pid}`;
10055
- writeFileSync(tmp, text, 'utf8');
10056
- renameSync(tmp, target);
10144
+ try {
10145
+ writeFileSync(tmp, text, 'utf8');
10146
+ renameSync(tmp, target);
10147
+ } catch (error) {
10148
+ throw writeError(error, {
10149
+ action: '保存配置',
10150
+ target,
10151
+ others: [
10152
+ tmp,
10153
+ backupsDir(target)
10154
+ ]
10155
+ });
10156
+ }
10057
10157
  });
10058
10158
  }
10059
10159
  function backup(target) {
@@ -10318,7 +10418,7 @@ function renderHuman(path, config, issues) {
10318
10418
  ],
10319
10419
  [
10320
10420
  '文档校验',
10321
- config.docs.validator.requireScript ? '强制由文档仓库脚本裁决(缺脚本或 python 时拒绝写入)' : '宽松:脚本不可用时仅告警'
10421
+ config.docs.validator.strict ? '严格模式:校验不通过或无法校验时拒绝写入' : '宽松:脚本不可用时仅告警'
10322
10422
  ]
10323
10423
  ]).join('\n'));
10324
10424
  const names = Object.keys(config.terminals);
@@ -10783,59 +10883,6 @@ function aggregateRequirement(statuses) {
10783
10883
  progress: roundProgressPercent(done, statuses.length)
10784
10884
  };
10785
10885
  }
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
10886
  const DEFAULT_ITERATIONS_ROOT = 'iterations';
10840
10887
  const YEAR_PATTERN = /^\d{4}$/;
10841
10888
  function currentIterationYear() {
@@ -11048,13 +11095,40 @@ function resolveIterationFromBranch(docsRoot, iterations) {
11048
11095
  candidates: []
11049
11096
  };
11050
11097
  }
11098
+ function describeRepoAccessFailure(docsRoot) {
11099
+ try {
11100
+ execFileSync('git', [
11101
+ 'rev-parse',
11102
+ '--is-inside-work-tree'
11103
+ ], {
11104
+ cwd: docsRoot,
11105
+ encoding: 'utf8',
11106
+ stdio: [
11107
+ 'ignore',
11108
+ 'pipe',
11109
+ 'pipe'
11110
+ ]
11111
+ });
11112
+ return null;
11113
+ } catch (error) {
11114
+ const detail = error.stderr?.trim() ?? '';
11115
+ const firstLine = detail.split('\n')[0] ?? '';
11116
+ if (firstLine.includes('not a git repository')) return `文档仓库不是 git 仓库:${docsRoot}`;
11117
+ if (0 === firstLine.length) return `无法执行 git:${error instanceof Error ? error.message.split('\n')[0] : String(error)}\n 请确认已安装 git 并在 PATH 中`;
11118
+ return `无法访问文档仓库:${docsRoot}\n git 输出:${firstLine}\n 常见原因:当前会话没有该目录的访问权限(会话文件访问范围限制),或目录已被移动/删除`;
11119
+ }
11120
+ }
11051
11121
  const PROTECTED_BRANCHES = new Set([
11052
11122
  'main',
11053
11123
  'master'
11054
11124
  ]);
11055
11125
  function assertWritableBranch(docsRoot) {
11056
11126
  const branch = currentBranch(docsRoot);
11057
- if (null === branch) throw new errors_CliError("文档仓库处于 detached HEAD,无法确认所在分支,写操作已拒绝。\n请先切到迭代分支再重试:git switch <分支>", errors_EXIT.INVALID);
11127
+ if (null === branch) {
11128
+ const accessFailure = describeRepoAccessFailure(docsRoot);
11129
+ if (null !== accessFailure) throw new errors_CliError(accessFailure, errors_EXIT.INVALID);
11130
+ throw new errors_CliError("文档仓库处于 detached HEAD,无法确认所在分支,写操作已拒绝。\n请先切到迭代分支再重试:git switch <分支>", errors_EXIT.INVALID);
11131
+ }
11058
11132
  if (PROTECTED_BRANCHES.has(branch.toLowerCase())) throw new errors_CliError(`文档仓库当前在 ${branch} 分支,禁止直接修改文档。\n请先切到该迭代的分支再重试,例如:\n git switch -c feature_<迭代名>`, errors_EXIT.INVALID);
11059
11133
  }
11060
11134
  const TASK_TYPE_GROUPS = [
@@ -11373,7 +11447,11 @@ function readRoles(value, taskKeys, docsRoot) {
11373
11447
  required: void 0 === field.required ? false : true === field.required
11374
11448
  };
11375
11449
  if (void 0 !== field.required && 'boolean' != typeof field.required) fail(docsRoot, `${at}.required 必须是布尔值`);
11376
- if (void 0 !== field.placeholder) decl.placeholder = Array.isArray(field.placeholder) ? requireStringArray(field.placeholder, `${at}.placeholder`, docsRoot).join(';') : requireString(field.placeholder, `${at}.placeholder`, docsRoot);
11450
+ if (void 0 !== field.placeholder) if (Array.isArray(field.placeholder)) {
11451
+ const items = requireStringArray(field.placeholder, `${at}.placeholder`, docsRoot);
11452
+ decl.placeholderItems = items;
11453
+ decl.placeholder = items.join(';');
11454
+ } else decl.placeholder = requireString(field.placeholder, `${at}.placeholder`, docsRoot);
11377
11455
  detailFieldItems.push(decl);
11378
11456
  });
11379
11457
  }
@@ -11410,8 +11488,14 @@ function loadDocSchema(docsRoot, options = {}) {
11410
11488
  let text;
11411
11489
  try {
11412
11490
  text = readFileSync(target, 'utf8');
11413
- } catch {
11414
- fail(docsRoot, '文件不存在或不可读');
11491
+ } catch (error) {
11492
+ const code = error.code;
11493
+ if ('ENOENT' === code) fail(docsRoot, '文件不存在或不可读');
11494
+ const failure = readError(error, {
11495
+ action: `读取文档仓库 ${SCHEMA_FILENAME}`,
11496
+ target
11497
+ });
11498
+ throw new errors_CliError(`${failure.message}\n\n该文件是文档格式的唯一来源,请确认文档仓库可访问后重试。`, errors_EXIT.NOT_FOUND);
11415
11499
  }
11416
11500
  let raw;
11417
11501
  try {
@@ -11422,7 +11506,7 @@ function loadDocSchema(docsRoot, options = {}) {
11422
11506
  const schema = parseDocSchema(raw, docsRoot);
11423
11507
  if (true !== options.allowTooOld && null !== schema.requiresYlcwf) {
11424
11508
  const required = parseMinVersion(schema.requiresYlcwf);
11425
- if (null !== required && compareVersions("0.7.0", `${required[0]}.${required[1]}.${required[2]}`) < 0) fail(docsRoot, `文档仓库要求 ylcwf ${schema.requiresYlcwf},当前版本是 0.7.0,请先升级 ylcwf:\n npm install -g ylcwf@latest`);
11509
+ if (null !== required && compareVersions("0.9.0", `${required[0]}.${required[1]}.${required[2]}`) < 0) fail(docsRoot, `文档仓库要求 ylcwf ${schema.requiresYlcwf},当前版本是 0.9.0,请先升级 ylcwf:\n npm install -g ylcwf@latest`);
11426
11510
  }
11427
11511
  return schema;
11428
11512
  }
@@ -11452,6 +11536,23 @@ function sideOfTypeName(schema, typeName) {
11452
11536
  if (sides.length > 1) return 'both';
11453
11537
  return sides[0] ?? null;
11454
11538
  }
11539
+ function toLf(text) {
11540
+ return text.replace(/\r\n/g, '\n');
11541
+ }
11542
+ function detectEol(text) {
11543
+ return text.includes('\r\n') ? '\r\n' : '\n';
11544
+ }
11545
+ function applyEol(text, eol) {
11546
+ const lf = toLf(text);
11547
+ return '\n' === eol ? lf : lf.replace(/\n/g, '\r\n');
11548
+ }
11549
+ function readTextFile(path) {
11550
+ const raw = readFileSync(path, 'utf8');
11551
+ return {
11552
+ text: toLf(raw),
11553
+ eol: detectEol(raw)
11554
+ };
11555
+ }
11455
11556
  function buildRepoSideIndex(terminals) {
11456
11557
  const byName = new Map();
11457
11558
  for (const terminal of Object.values(terminals))for (const side of [
@@ -11841,10 +11942,13 @@ function mirrorColumnsOfSides(side) {
11841
11942
  for (const spec of taskFieldSpecsOfSides(side))if ('mirror' === spec.value.kind) result[spec.name] = spec.value.column;
11842
11943
  return result;
11843
11944
  }
11945
+ function apiFieldsOfSides(side) {
11946
+ return taskFieldSpecsOfSides(side).filter((spec)=>'apis' === spec.value.kind).map((spec)=>spec.name);
11947
+ }
11844
11948
  const PENDING_STATUS = '未开始';
11845
11949
  const PENDING_SELF_TEST = '未执行';
11846
11950
  const PENDING_ACCEPTANCE = '待验收';
11847
- function headings(schema) {
11951
+ function docrender_headings(schema) {
11848
11952
  return {
11849
11953
  info: `## ${schema.sections[0] ?? '一、迭代信息'}`,
11850
11954
  requirement: `## ${schema.sections[1] ?? '二、需求清单'}`,
@@ -12142,7 +12246,7 @@ function appendTableRows(options) {
12142
12246
  }
12143
12247
  function buildSkeleton(options) {
12144
12248
  const { schema, role, plan, developer } = options;
12145
- const head = headings(schema);
12249
+ const head = docrender_headings(schema);
12146
12250
  const lines = [];
12147
12251
  lines.push(`# ${developer}`, '');
12148
12252
  lines.push(head.info, '');
@@ -12259,7 +12363,7 @@ function renderPlan(options) {
12259
12363
  changes.push(`新增任务:${id} ${task.name}`);
12260
12364
  return joinRow(cells);
12261
12365
  });
12262
- const head = headings(schema);
12366
+ const head = docrender_headings(schema);
12263
12367
  let lines = null === existing.lines ? buildSkeleton({
12264
12368
  schema,
12265
12369
  role,
@@ -12485,8 +12589,91 @@ function isDocMarkdown(path) {
12485
12589
  if (RESERVED_PREFIXES.some((prefix)=>path.startsWith(prefix) || path.includes(`/${prefix}`))) return false;
12486
12590
  return true;
12487
12591
  }
12592
+ class RecentCache {
12593
+ limit;
12594
+ entries = new Map();
12595
+ constructor(limit){
12596
+ this.limit = limit;
12597
+ }
12598
+ get(key) {
12599
+ const hit = this.entries.get(key);
12600
+ if (void 0 === hit) return;
12601
+ this.entries.delete(key);
12602
+ this.entries.set(key, hit);
12603
+ return hit;
12604
+ }
12605
+ set(key, value) {
12606
+ this.entries.delete(key);
12607
+ this.entries.set(key, value);
12608
+ while(this.entries.size > this.limit){
12609
+ const oldest = this.entries.keys().next();
12610
+ if (true === oldest.done) break;
12611
+ this.entries.delete(oldest.value);
12612
+ }
12613
+ }
12614
+ clear() {
12615
+ this.entries.clear();
12616
+ }
12617
+ }
12618
+ const treeCache = new RecentCache(4);
12619
+ const commitTimeCache = new RecentCache(512);
12620
+ const MATERIALIZE_MARKER = '.ylcwf-materialized';
12621
+ const REMOTE_CACHE_PREFIX = 'ylcwf-remote-';
12622
+ function remoteCacheRoot() {
12623
+ return external_node_os_tmpdir();
12624
+ }
12625
+ function listRemoteCacheDirs() {
12626
+ const base = remoteCacheRoot();
12627
+ let names;
12628
+ try {
12629
+ names = external_node_fs_readdirSync(base);
12630
+ } catch {
12631
+ return [];
12632
+ }
12633
+ return names.filter((name)=>name.startsWith(REMOTE_CACHE_PREFIX)).map((name)=>{
12634
+ const path = external_node_path_join(base, name);
12635
+ try {
12636
+ return {
12637
+ path,
12638
+ mtime: statSync(path).mtime.toISOString()
12639
+ };
12640
+ } catch {
12641
+ return null;
12642
+ }
12643
+ }).filter((item)=>null !== item).sort((left, right)=>right.mtime.localeCompare(left.mtime));
12644
+ }
12645
+ const PRUNE_INTERVAL_MS = 300000;
12646
+ let lastPruneAt = 0;
12647
+ function snapshotTree(docsRoot, sha) {
12648
+ const key = `${docsRoot}\u0000${sha}`;
12649
+ const cached = treeCache.get(key);
12650
+ if (void 0 !== cached) return cached;
12651
+ const output = tryGit(docsRoot, [
12652
+ 'ls-tree',
12653
+ '-r',
12654
+ '-l',
12655
+ '--full-tree',
12656
+ sha
12657
+ ]);
12658
+ if (null === output) throw new errors_CliError(`无法读取远程快照:${sha}`, errors_EXIT.NOT_FOUND);
12659
+ const sizes = new Map();
12660
+ for (const rawLine of output.split('\n')){
12661
+ const line = rawLine.replace(/\r$/, '');
12662
+ const tab = line.indexOf('\t');
12663
+ if (tab < 0) continue;
12664
+ const path = line.slice(tab + 1);
12665
+ const sizeText = line.slice(0, tab).trim().split(/\s+/)[3];
12666
+ const size = void 0 === sizeText || '-' === sizeText ? 0 : Number.parseInt(sizeText, 10);
12667
+ sizes.set(path, Number.isNaN(size) ? 0 : size);
12668
+ }
12669
+ treeCache.set(key, sizes);
12670
+ return sizes;
12671
+ }
12488
12672
  function lastCommitIso(docsRoot, sha, path) {
12489
- return tryGit(docsRoot, [
12673
+ const key = `${docsRoot}\u0000${sha}\u0000${path}`;
12674
+ const cached = commitTimeCache.get(key);
12675
+ if (void 0 !== cached) return cached;
12676
+ const value = tryGit(docsRoot, [
12490
12677
  'log',
12491
12678
  '-1',
12492
12679
  '--format=%cI',
@@ -12494,6 +12681,8 @@ function lastCommitIso(docsRoot, sha, path) {
12494
12681
  '--',
12495
12682
  path
12496
12683
  ]) ?? '';
12684
+ commitTimeCache.set(key, value);
12685
+ return value;
12497
12686
  }
12498
12687
  function getBranchInfo(docsRoot) {
12499
12688
  const current = tryGit(docsRoot, [
@@ -12525,18 +12714,21 @@ function getBranchInfo(docsRoot) {
12525
12714
  remote: branches.split('\n').map((line)=>line.trim().replace(/^refs\/remotes\//, '')).filter((line)=>line.length > 0 && line.includes('/') && !line.endsWith('/HEAD')).sort()
12526
12715
  };
12527
12716
  }
12717
+ const remoteListCache = new RecentCache(4);
12528
12718
  function listRemoteIterations(layout, ref) {
12719
+ const cacheKey = `${layout.root}\u0000${layout.iterationsRoot}\u0000${ref.sha}`;
12720
+ const cached = remoteListCache.get(cacheKey);
12721
+ if (void 0 !== cached) return {
12722
+ docsRoot: layout.root,
12723
+ source: 'remote',
12724
+ ref,
12725
+ iterations: structuredClone(cached)
12726
+ };
12529
12727
  const docsRoot = layout.root;
12530
- const listed = tryGit(docsRoot, [
12531
- 'ls-tree',
12532
- '-r',
12533
- '--name-only',
12534
- ref.sha
12535
- ]);
12536
- if (null === listed) throw new errors_CliError(`无法读取远程快照:${ref.ref}`, errors_EXIT.NOT_FOUND);
12728
+ const sizes = snapshotTree(docsRoot, ref.sha);
12537
12729
  const prefix = `${layout.iterationsRoot.replace(/\/+$/, '')}/`;
12538
12730
  const groups = new Map();
12539
- for (const path of listed.split('\n')){
12731
+ for (const path of sizes.keys()){
12540
12732
  if (!isDocMarkdown(path)) continue;
12541
12733
  if (!path.startsWith(prefix)) continue;
12542
12734
  const segments = path.slice(prefix.length).split('/');
@@ -12546,16 +12738,11 @@ function listRemoteIterations(layout, ref) {
12546
12738
  if (!isYearDirectory(yearText)) continue;
12547
12739
  const year = Number.parseInt(yearText, 10);
12548
12740
  const relPath = `${yearText}/${iteration}`;
12549
- const sizeText = tryGit(docsRoot, [
12550
- 'cat-file',
12551
- '-s',
12552
- `${ref.sha}:${path}`
12553
- ]) ?? '0';
12554
12741
  const entry = {
12555
12742
  id: file.replace(/\.md$/, ''),
12556
12743
  file,
12557
12744
  mtime: lastCommitIso(docsRoot, ref.sha, path),
12558
- size: Number.parseInt(sizeText, 10) || 0
12745
+ size: sizes.get(path) ?? 0
12559
12746
  };
12560
12747
  const bucket = groups.get(relPath) ?? {
12561
12748
  year,
@@ -12574,14 +12761,16 @@ function listRemoteIterations(layout, ref) {
12574
12761
  relPath: group.relPath,
12575
12762
  mtime: lastCommitIso(docsRoot, ref.sha, `${prefix}${group.relPath}`),
12576
12763
  developers: group.developers.sort((left, right)=>right.mtime.localeCompare(left.mtime)),
12577
- hasPrd: listed.includes(`${prefix}${group.relPath}/_prd/meta.json`)
12764
+ hasPrd: sizes.has(`${prefix}${group.relPath}/_prd/meta.json`)
12578
12765
  })).sort((left, right)=>left.year === right.year ? right.mtime.localeCompare(left.mtime) : right.year - left.year);
12579
- return {
12766
+ const snapshot = {
12580
12767
  docsRoot,
12581
12768
  source: 'remote',
12582
12769
  ref,
12583
12770
  iterations
12584
12771
  };
12772
+ remoteListCache.set(cacheKey, iterations);
12773
+ return structuredClone(snapshot);
12585
12774
  }
12586
12775
  function gitShow(docsRoot, sha, path) {
12587
12776
  return tryGit(docsRoot, [
@@ -12589,14 +12778,81 @@ function gitShow(docsRoot, sha, path) {
12589
12778
  `${sha}:${path}`
12590
12779
  ]);
12591
12780
  }
12781
+ const REMOTE_CACHE_KEEP = 20;
12782
+ function pruneRemoteCache(options = {}) {
12783
+ const keep = options.keep ?? REMOTE_CACHE_KEEP;
12784
+ const base = options.baseDir ?? external_node_os_tmpdir();
12785
+ let names;
12786
+ try {
12787
+ names = external_node_fs_readdirSync(base);
12788
+ } catch {
12789
+ return [];
12790
+ }
12791
+ const candidates = names.filter((name)=>name.startsWith(REMOTE_CACHE_PREFIX)).map((name)=>{
12792
+ const path = external_node_path_join(base, name);
12793
+ try {
12794
+ return {
12795
+ path,
12796
+ mtime: statSync(path).mtimeMs
12797
+ };
12798
+ } catch {
12799
+ return null;
12800
+ }
12801
+ }).filter((item)=>null !== item).sort((left, right)=>right.mtime - left.mtime);
12802
+ const removed = [];
12803
+ for (const [index, item] of candidates.entries())if (!(index < keep)) try {
12804
+ rmSync(item.path, {
12805
+ recursive: true,
12806
+ force: true
12807
+ });
12808
+ removed.push(item.path);
12809
+ } catch {}
12810
+ return removed;
12811
+ }
12812
+ function touchDir(dir) {
12813
+ try {
12814
+ const now = new Date();
12815
+ utimesSync(dir, now, now);
12816
+ } catch {}
12817
+ }
12818
+ function maybePruneRemoteCache() {
12819
+ const now = Date.now();
12820
+ if (now - lastPruneAt < PRUNE_INTERVAL_MS) return;
12821
+ lastPruneAt = now;
12822
+ pruneRemoteCache();
12823
+ }
12824
+ function writeFileAtomic(target, content) {
12825
+ const temp = `${target}.${process.pid}.tmp`;
12826
+ writeFileSync(temp, content, 'utf8');
12827
+ try {
12828
+ renameSync(temp, target);
12829
+ } catch (error) {
12830
+ const code = error.code;
12831
+ const occupied = 'EBUSY' === code || 'EPERM' === code || 'EACCES' === code;
12832
+ if (!occupied) {
12833
+ rmSync(temp, {
12834
+ force: true
12835
+ });
12836
+ throw error;
12837
+ }
12838
+ writeFileSync(target, content, 'utf8');
12839
+ rmSync(temp, {
12840
+ force: true
12841
+ });
12842
+ }
12843
+ }
12592
12844
  function materializeRemote(docsRoot, ref) {
12593
- const dir = external_node_path_join(external_node_os_tmpdir(), `ylcwf-remote-${ref.sha.slice(0, 12)}`);
12845
+ const dir = external_node_path_join(remoteCacheRoot(), `${REMOTE_CACHE_PREFIX}${ref.sha.slice(0, 12)}`);
12594
12846
  mkdirSync(external_node_path_join(dir, "scripts"), {
12595
12847
  recursive: true
12596
12848
  });
12849
+ touchDir(dir);
12850
+ maybePruneRemoteCache();
12597
12851
  return dir;
12598
12852
  }
12599
12853
  function materializeScripts(docsRoot, ref, dir) {
12854
+ const marker = external_node_path_join(dir, MATERIALIZE_MARKER);
12855
+ if (external_node_fs_existsSync(marker)) return;
12600
12856
  const listed = tryGit(docsRoot, [
12601
12857
  'ls-tree',
12602
12858
  '-r',
@@ -12613,9 +12869,10 @@ function materializeScripts(docsRoot, ref, dir) {
12613
12869
  mkdirSync(external_node_path_dirname(target), {
12614
12870
  recursive: true
12615
12871
  });
12616
- writeFileSync(target, content, 'utf8');
12872
+ writeFileAtomic(target, content);
12617
12873
  }
12618
12874
  }
12875
+ writeFileAtomic(marker, ref.sha);
12619
12876
  }
12620
12877
  function exportRemoteDoc(docsRoot, ref, year, iteration, developer, iterationsRoot = 'iterations') {
12621
12878
  const safeIteration = safeSegment(iteration, '迭代目录');
@@ -12628,12 +12885,12 @@ function exportRemoteDoc(docsRoot, ref, year, iteration, developer, iterationsRo
12628
12885
  mkdirSync(external_node_path_dirname(target), {
12629
12886
  recursive: true
12630
12887
  });
12631
- writeFileSync(target, markdown, 'utf8');
12888
+ writeFileAtomic(target, markdown);
12632
12889
  materializeScripts(docsRoot, ref, dir);
12633
12890
  const schemaPath = external_node_path_join(dir, 'schema.json');
12634
12891
  if (!external_node_fs_existsSync(schemaPath)) {
12635
12892
  const schemaText = gitShow(docsRoot, ref.sha, 'schema.json');
12636
- if (null !== schemaText) writeFileSync(schemaPath, schemaText, 'utf8');
12893
+ if (null !== schemaText) writeFileAtomic(schemaPath, schemaText);
12637
12894
  }
12638
12895
  const scriptPath = external_node_path_join(dir, "scripts", 'validate_task_doc.py');
12639
12896
  return {
@@ -12656,6 +12913,494 @@ function isGitAvailable() {
12656
12913
  return false;
12657
12914
  }
12658
12915
  }
12916
+ const API_REF_PATTERN = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\S+)\s*[((]\s*YAPI\s*(\d+)\s*[))]$/;
12917
+ const API_REF_NONE = new Set([
12918
+ '无',
12919
+ '无接口',
12920
+ '不涉及',
12921
+ '—',
12922
+ '-'
12923
+ ]);
12924
+ const SELF_TEST_FREE_PATTERN = /^免测\s*(?:[((].+[))])?$/;
12925
+ const DETAIL_FIELD_PATTERN = /^\s*-\s+\*\*(.+?)\*\*\s*[::]\s*(.*)$/;
12926
+ function normalizeState(value) {
12927
+ return value.replace(/[((].*?[))]/g, '').trim();
12928
+ }
12929
+ function canonicalField(name) {
12930
+ return name.replace(/[((][^))]*[))]/g, '').replace(/\s+/g, '');
12931
+ }
12932
+ function cleanCell(text) {
12933
+ return text.replace(/\*\*/g, '').replace(/`/g, '').replace(/\s+/g, ' ').trim();
12934
+ }
12935
+ function splitTableRow(line) {
12936
+ let stripped = line.trim();
12937
+ if (stripped.startsWith('|')) stripped = stripped.slice(1);
12938
+ if (stripped.endsWith('|')) stripped = stripped.slice(0, -1);
12939
+ return stripped.split('|').map(cleanCell);
12940
+ }
12941
+ function isSeparatorRow(cells) {
12942
+ return cells.length > 0 && cells.every((cell)=>/^[-: ]*$/.test(cell));
12943
+ }
12944
+ function parseTables(lines) {
12945
+ const tables = [];
12946
+ let index = 0;
12947
+ while(index < lines.length){
12948
+ if (!(lines[index] ?? '').trim().startsWith('|')) {
12949
+ index += 1;
12950
+ continue;
12951
+ }
12952
+ const block = [];
12953
+ while(index < lines.length && (lines[index] ?? '').trim().startsWith('|')){
12954
+ block.push(lines[index] ?? '');
12955
+ index += 1;
12956
+ }
12957
+ if (block.length < 2) continue;
12958
+ const headers = splitTableRow(block[0] ?? '');
12959
+ const rows = block.slice(1).map(splitTableRow).filter((cells)=>!isSeparatorRow(cells));
12960
+ tables.push({
12961
+ headers,
12962
+ rows
12963
+ });
12964
+ }
12965
+ return tables;
12966
+ }
12967
+ function findTable(tables, required) {
12968
+ for (const table of tables)if (required.every((header)=>table.headers.includes(header))) return table;
12969
+ return null;
12970
+ }
12971
+ function toRecord(table, row) {
12972
+ const record = {};
12973
+ table.headers.forEach((header, index)=>{
12974
+ record[header] = row[index] ?? '';
12975
+ });
12976
+ return record;
12977
+ }
12978
+ function docvalidate_pick(record, keys, semantic) {
12979
+ const column = keys[semantic];
12980
+ return void 0 === column ? '' : record[column] ?? '';
12981
+ }
12982
+ function isValidUpdatedAt(value, format) {
12983
+ const tokens = [];
12984
+ let pattern = '^';
12985
+ if (format.includes('%')) for(let index = 0; index < format.length; index += 1){
12986
+ const char = format.charAt(index);
12987
+ if ('%' !== char || index + 1 >= format.length) {
12988
+ pattern += escapeRegExp(char);
12989
+ continue;
12990
+ }
12991
+ const code = format.charAt(index + 1);
12992
+ index += 1;
12993
+ if ('Y' === code || 'm' === code || 'd' === code || 'H' === code || 'M' === code || 'S' === code) {
12994
+ tokens.push(code);
12995
+ pattern += '(\\d{1,4})';
12996
+ } else pattern += '\\S+';
12997
+ }
12998
+ else {
12999
+ const literals = [
13000
+ [
13001
+ 'YYYY',
13002
+ 'Y'
13003
+ ],
13004
+ [
13005
+ 'MM',
13006
+ 'm'
13007
+ ],
13008
+ [
13009
+ 'DD',
13010
+ 'd'
13011
+ ],
13012
+ [
13013
+ 'HH',
13014
+ 'H'
13015
+ ],
13016
+ [
13017
+ 'mm',
13018
+ 'M'
13019
+ ]
13020
+ ];
13021
+ let index = 0;
13022
+ while(index < format.length){
13023
+ const rest = format.slice(index);
13024
+ const hit = literals.find(([literal])=>rest.startsWith(literal));
13025
+ if (void 0 === hit) {
13026
+ pattern += escapeRegExp(format.charAt(index));
13027
+ index += 1;
13028
+ continue;
13029
+ }
13030
+ tokens.push(hit[1]);
13031
+ pattern += 'Y' === hit[1] ? '(\\d{4})' : '(\\d{2})';
13032
+ index += hit[0].length;
13033
+ }
13034
+ }
13035
+ pattern += '$';
13036
+ const matched = new RegExp(pattern).exec(value);
13037
+ if (null === matched) return false;
13038
+ const parts = {};
13039
+ tokens.forEach((code, index)=>{
13040
+ parts[code] = Number.parseInt(matched[index + 1] ?? '', 10);
13041
+ });
13042
+ const year = parts['Y'];
13043
+ const month = parts['m'];
13044
+ const day = parts['d'];
13045
+ const hour = parts['H'];
13046
+ const minute = parts['M'];
13047
+ if (void 0 === year || void 0 === month || void 0 === day) return false;
13048
+ if (month < 1 || month > 12 || day < 1 || day > 31) return false;
13049
+ if (void 0 !== hour && hour > 23) return false;
13050
+ if (void 0 !== minute && minute > 59) return false;
13051
+ const date = new Date(year, month - 1, day);
13052
+ return date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
13053
+ }
13054
+ function splitDependencies(value) {
13055
+ if (0 === value.length || API_REF_NONE.has(value)) return [];
13056
+ return value.split(/[,,、\s]+/).map((item)=>item.trim()).filter((item)=>item.length > 0);
13057
+ }
13058
+ function detailHeadingPattern(schema) {
13059
+ const source = schema.taskIdPattern.replace(/^\^/, '').replace(/\$$/, '').replace(/\((?!\?)/g, '(?:');
13060
+ return new RegExp(`^###\\s+\\[(${source})\\]\\s*(.*)$`);
13061
+ }
13062
+ function parseDetailBlocks(sectionText, schema) {
13063
+ const heading = detailHeadingPattern(schema);
13064
+ const details = new Map();
13065
+ let currentTask = null;
13066
+ let currentField = null;
13067
+ for (const line of sectionText.split(/\r?\n/)){
13068
+ const matched = heading.exec(line);
13069
+ if (null !== matched) {
13070
+ currentTask = matched[1] ?? '';
13071
+ currentField = null;
13072
+ details.set(currentTask, {
13073
+ title: (matched[2] ?? '').trim(),
13074
+ fields: {}
13075
+ });
13076
+ continue;
13077
+ }
13078
+ if (line.startsWith('## ') || line.startsWith('### ')) {
13079
+ currentTask = null;
13080
+ currentField = null;
13081
+ continue;
13082
+ }
13083
+ if (null === currentTask) continue;
13084
+ const detail = details.get(currentTask);
13085
+ if (void 0 === detail) continue;
13086
+ const field = DETAIL_FIELD_PATTERN.exec(line);
13087
+ if (null !== field) {
13088
+ const name = (field[1] ?? '').trim();
13089
+ detail.fields[name] = (field[2] ?? '').trim();
13090
+ currentField = name;
13091
+ continue;
13092
+ }
13093
+ if (null !== currentField && /^\s{2,}\S/.test(line)) {
13094
+ const addition = line.trim().replace(/^[-*]\s+/, '');
13095
+ const existing = detail.fields[currentField] ?? '';
13096
+ detail.fields[currentField] = existing.length > 0 ? `${existing}\n${addition}` : addition;
13097
+ }
13098
+ }
13099
+ return details;
13100
+ }
13101
+ function roleOfDocument(markdown, schema) {
13102
+ const label = schema.iterationFieldItems.find((item)=>'scope' === item.key)?.label ?? '';
13103
+ if (0 === label.length) return null;
13104
+ const matched = new RegExp(`^[^\\S\\n]*\\|\\s*${escapeRegExp(label)}\\s*\\|\\s*([^|]*)\\|`, 'm').exec(markdown);
13105
+ const value = (matched?.[1] ?? '').trim();
13106
+ return Object.hasOwn(schema.roles, value) ? value : null;
13107
+ }
13108
+ class IssueCollector {
13109
+ issues = [];
13110
+ add(level, code, message, ref) {
13111
+ this.issues.push(void 0 === ref ? {
13112
+ level,
13113
+ code,
13114
+ message
13115
+ } : {
13116
+ level,
13117
+ code,
13118
+ message,
13119
+ ref
13120
+ });
13121
+ }
13122
+ get errors() {
13123
+ return this.issues.filter((issue)=>'error' === issue.level);
13124
+ }
13125
+ get warnings() {
13126
+ return this.issues.filter((issue)=>'warning' === issue.level);
13127
+ }
13128
+ }
13129
+ function validateDoc(options) {
13130
+ const { markdown, schema, role } = options;
13131
+ const collector = new IssueCollector();
13132
+ const requirementStatuses = new Set(schema.enums.requirementStatus);
13133
+ const taskStatuses = new Set(schema.enums.taskStatus);
13134
+ const selfTestStates = new Set(schema.enums.selfTest);
13135
+ const acceptanceStates = new Set(schema.enums.acceptance);
13136
+ const requirementIdPattern = new RegExp(schema.requirementIdPattern);
13137
+ const taskIdPattern = new RegExp(schema.taskIdPattern);
13138
+ const allowedTaskTypes = new Set(taskTypesOf(schema, role));
13139
+ const requiredSections = schema.sections;
13140
+ const infoLabel = (key)=>schema.iterationFieldItems.find((item)=>item.key === key)?.label ?? '';
13141
+ const sections = new Map();
13142
+ for (const section of requiredSections){
13143
+ const body = extractSection(markdown, `## ${section}`);
13144
+ if (0 === body.length) collector.add('error', 'SECTION_MISSING', `缺少章节:${section}`, section);
13145
+ sections.set(section, body);
13146
+ }
13147
+ const iterationInfo = {};
13148
+ const infoSection = sections.get(requiredSections[0] ?? '一、迭代信息') ?? '';
13149
+ const infoTable = findTable(parseTables(infoSection.split(/\r?\n/)), [
13150
+ '项',
13151
+ '内容'
13152
+ ]);
13153
+ if (null === infoTable) collector.add('error', 'ITERATION_TABLE_MISSING', '第一章缺少「项 / 内容」表', '一、迭代信息');
13154
+ else {
13155
+ for (const row of infoTable.rows){
13156
+ const key = row[0] ?? '';
13157
+ if (0 !== key.length) iterationInfo[key] = row[1] ?? '';
13158
+ }
13159
+ for (const field of schema.iterationFieldItems)if (field.required && 0 === (iterationInfo[field.label] ?? '').length) collector.add('error', 'ITERATION_FIELD_MISSING', `迭代信息缺少字段或值为空:${field.label}`, field.label);
13160
+ const versionLabel = infoLabel('iteration');
13161
+ const version = versionLabel.length > 0 ? iterationInfo[versionLabel] ?? '' : '';
13162
+ if (versionLabel.length > 0 && version.length > 0 && version !== options.iterationName) collector.add('warning', 'ITERATION_VERSION_MISMATCH', `迭代版本「${version}」与迭代目录名「${options.iterationName}」不一致`, versionLabel);
13163
+ const prdLabel = infoLabel('prd');
13164
+ const source = prdLabel.length > 0 ? iterationInfo[prdLabel] ?? '' : '';
13165
+ if (prdLabel.length > 0 && source.length > 0 && !source.includes('alidocs') && !source.includes('http')) collector.add('warning', 'PRD_SOURCE_SUSPECT', `PRD 来源不像文档链接:${source}`, prdLabel);
13166
+ const scopeLabel = infoLabel('scope');
13167
+ const scopeText = scopeLabel.length > 0 ? iterationInfo[scopeLabel] ?? '' : '';
13168
+ if (scopeLabel.length > 0 && scopeText.length > 0 && scopeText.trim() !== role) collector.add('warning', 'ROLE_SCOPE_MISMATCH', `负责范围「${scopeText}」与校验角色「${role}」不一致(应写角色名)`, scopeLabel);
13169
+ }
13170
+ const requirements = [];
13171
+ const requirementSection = sections.get(requiredSections[1] ?? '二、需求清单') ?? '';
13172
+ const requirementTable = findTable(parseTables(requirementSection.split(/\r?\n/)), schema.requirementHeaders);
13173
+ if (null === requirementTable) collector.add('error', 'REQUIREMENT_TABLE_MISSING', '第二章缺少需求清单表(列名不符合模板)', '二、需求清单');
13174
+ else for (const row of requirementTable.rows){
13175
+ if (row.every((cell)=>0 === cell.length)) continue;
13176
+ const record = toRecord(requirementTable, row);
13177
+ const requirementId = docvalidate_pick(record, schema.requirementKeys, 'id');
13178
+ if (!requirementIdPattern.test(requirementId)) {
13179
+ collector.add('error', 'REQUIREMENT_ID_INVALID', `需求编号格式非法(应为纯数字,如 1234):${requirementId}`, requirementId);
13180
+ continue;
13181
+ }
13182
+ const updatedAt = docvalidate_pick(record, schema.requirementKeys, 'updatedAt').trim();
13183
+ if (!isValidUpdatedAt(updatedAt, schema.updatedAtFormat)) collector.add('error', 'UPDATED_AT_INVALID', `需求 ${requirementId} 的最后更新非法(应为合法的 ${schema.updatedAtFormat}):${updatedAt.length > 0 ? updatedAt : '空'}`, requirementId);
13184
+ const status = normalizeState(docvalidate_pick(record, schema.requirementKeys, 'status'));
13185
+ if (!requirementStatuses.has(status)) collector.add('error', 'REQUIREMENT_STATUS_INVALID', `需求 ${requirementId} 开发状态非法:${docvalidate_pick(record, schema.requirementKeys, 'status')}`, requirementId);
13186
+ const progressText = docvalidate_pick(record, schema.requirementKeys, 'progress').replace(/%/g, '').trim();
13187
+ const [progressMin, progressMax] = schema.progressRange;
13188
+ if (progressText.length > 0 && !/^\d+$/.test(progressText)) collector.add('error', 'REQUIREMENT_PROGRESS_INVALID', `需求 ${requirementId} 开发进度不是整数:${progressText}`, requirementId);
13189
+ else if (progressText.length > 0) {
13190
+ const progress = Number.parseInt(progressText, 10);
13191
+ if (progress < progressMin || progress > progressMax) collector.add('error', 'REQUIREMENT_PROGRESS_OUT_OF_RANGE', `需求 ${requirementId} 开发进度超出 ${progressMin}-${progressMax}:${progressText}`, requirementId);
13192
+ }
13193
+ requirements.push({
13194
+ id: requirementId,
13195
+ title: docvalidate_pick(record, schema.requirementKeys, 'title'),
13196
+ terminal: docvalidate_pick(record, schema.requirementKeys, 'terminal'),
13197
+ status,
13198
+ progress: progressText,
13199
+ note: docvalidate_pick(record, schema.requirementKeys, 'note'),
13200
+ updatedAt,
13201
+ taskIds: []
13202
+ });
13203
+ }
13204
+ const tasks = [];
13205
+ const taskSection = sections.get(requiredSections[2] ?? '三、任务清单') ?? '';
13206
+ const taskTable = findTable(parseTables(taskSection.split(/\r?\n/)), schema.taskHeaders);
13207
+ if (null === taskTable) collector.add('error', 'TASK_TABLE_MISSING', '第三章缺少任务清单表(列名不符合模板)', '三、任务清单');
13208
+ else {
13209
+ const requirementIds = new Set(requirements.map((item)=>item.id));
13210
+ const scopeEnum = schema.taskScopeEnum;
13211
+ for (const row of taskTable.rows){
13212
+ if (row.every((cell)=>0 === cell.length)) continue;
13213
+ const record = toRecord(taskTable, row);
13214
+ const taskId = docvalidate_pick(record, schema.taskKeys, 'id');
13215
+ if (!taskIdPattern.test(taskId)) {
13216
+ collector.add('error', 'TASK_ID_INVALID', `任务编号格式非法(应为 2755-T1):${taskId}`, taskId);
13217
+ continue;
13218
+ }
13219
+ const updatedAt = docvalidate_pick(record, schema.taskKeys, 'updatedAt').trim();
13220
+ if (!isValidUpdatedAt(updatedAt, schema.updatedAtFormat)) collector.add('error', 'UPDATED_AT_INVALID', `任务 ${taskId} 的最后更新非法(应为合法的 ${schema.updatedAtFormat}):${updatedAt.length > 0 ? updatedAt : '空'}`, taskId);
13221
+ const requirementId = docvalidate_pick(record, schema.taskKeys, 'requirement');
13222
+ if (requirementIdPattern.test(requirementId)) {
13223
+ if (!requirementIds.has(requirementId)) collector.add('error', 'TASK_REQUIREMENT_MISSING', `任务 ${taskId} 关联的需求 ${requirementId} 不在需求清单中`, taskId);
13224
+ } else collector.add('error', 'TASK_REQUIREMENT_ID_INVALID', `任务 ${taskId} 的关联需求编号格式非法(应为纯数字):${requirementId}`, taskId);
13225
+ const type = docvalidate_pick(record, schema.taskKeys, 'type');
13226
+ if (!allowedTaskTypes.has(type)) collector.add('error', 'TASK_TYPE_INVALID', `任务 ${taskId} 任务类型非法:${type}(允许值:${[
13227
+ ...allowedTaskTypes
13228
+ ].sort().join('、')})`, taskId);
13229
+ const scope = docvalidate_pick(record, schema.taskKeys, 'scope').trim();
13230
+ if (scopeEnum.includes(scope)) {
13231
+ const typeSide = sideOfTypeName(schema, type);
13232
+ const expectedScope = null === typeSide || 'both' === typeSide ? null : schema.roles[typeSide]?.scope ?? null;
13233
+ if (null !== expectedScope && scope !== expectedScope) collector.add('error', 'TASK_SCOPE_TYPE_MISMATCH', `任务 ${taskId} 类型「${type}」属于${expectedScope},但所属端填的是「${scope}」`, taskId);
13234
+ } else collector.add('error', 'TASK_SCOPE_INVALID', `任务 ${taskId} 所属端非法:${scope.length > 0 ? scope : '空'}(允许值:${scopeEnum.join('、')})`, taskId);
13235
+ const selfTest = docvalidate_pick(record, schema.taskKeys, 'selfTest');
13236
+ if (!selfTestStates.has(selfTest) && !SELF_TEST_FREE_PATTERN.test(selfTest)) collector.add('error', 'SELF_TEST_INVALID', `任务 ${taskId} AI 自测状态非法:${selfTest}`, taskId);
13237
+ const acceptance = normalizeState(docvalidate_pick(record, schema.taskKeys, 'acceptance'));
13238
+ if (!acceptanceStates.has(acceptance)) collector.add('error', 'ACCEPTANCE_INVALID', `任务 ${taskId} 开发人工验收非法:${docvalidate_pick(record, schema.taskKeys, 'acceptance')}`, taskId);
13239
+ const status = normalizeState(docvalidate_pick(record, schema.taskKeys, 'status'));
13240
+ if (!taskStatuses.has(status)) collector.add('error', 'TASK_STATUS_INVALID', `任务 ${taskId} 任务状态非法:${docvalidate_pick(record, schema.taskKeys, 'status')}`, taskId);
13241
+ if ('已完成' === status && '验收通过' !== acceptance) collector.add('error', 'ACCEPTANCE_GATE_VIOLATION', `任务 ${taskId} 状态为已完成,但开发人工验收为「${acceptance}」,必须先通过人工验收`, taskId);
13242
+ const selfTestPassed = '通过' === selfTest || SELF_TEST_FREE_PATTERN.test(selfTest);
13243
+ if (('待验收' === status || '已完成' === status) && !selfTestPassed) collector.add('error', 'SELF_TEST_GATE_VIOLATION', `任务 ${taskId} 状态为${status},但 AI 自测状态为「${selfTest}」,必须先完成自测`, taskId);
13244
+ if ('未开始' === status && '未执行' !== selfTest) collector.add('error', 'UNSTARTED_WITH_SELFTEST', `任务 ${taskId} 状态为未开始,但 AI 自测状态为「${selfTest}」`, taskId);
13245
+ tasks.push({
13246
+ id: taskId,
13247
+ requirementId,
13248
+ name: docvalidate_pick(record, schema.taskKeys, 'name'),
13249
+ type,
13250
+ scope,
13251
+ terminal: docvalidate_pick(record, schema.taskKeys, 'terminal'),
13252
+ dependencies: splitDependencies(docvalidate_pick(record, schema.taskKeys, 'dependencies')),
13253
+ selfTest,
13254
+ acceptance,
13255
+ status,
13256
+ updatedAt
13257
+ });
13258
+ }
13259
+ const allowedScopes = schema.roles[role]?.scopeRequires ?? [];
13260
+ const usedScopes = [
13261
+ ...new Set(tasks.map((task)=>task.scope).filter((scope)=>scope.length > 0))
13262
+ ].sort();
13263
+ for (const scope of usedScopes)if (!allowedScopes.includes(scope)) collector.add('error', 'DOCUMENT_SCOPE_MISMATCH', `任务清单中出现「${scope}」任务,但当前角色「${role}」只负责:${allowedScopes.join('、') || '(无)'}`);
13264
+ const requirementsById = new Map(requirements.map((item)=>[
13265
+ item.id,
13266
+ item
13267
+ ]));
13268
+ for (const task of tasks){
13269
+ const requirement = requirementsById.get(task.requirementId);
13270
+ if (void 0 !== requirement) {
13271
+ requirement.taskIds.push(task.id);
13272
+ 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);
13273
+ }
13274
+ }
13275
+ }
13276
+ const detailSection = sections.get(requiredSections[3] ?? '四、任务详情') ?? '';
13277
+ const details = parseDetailBlocks(detailSection, schema);
13278
+ const detailIds = new Set(details.keys());
13279
+ const taskIds = new Set(tasks.map((task)=>task.id));
13280
+ for (const taskId of [
13281
+ ...taskIds
13282
+ ].filter((id)=>!detailIds.has(id)).sort())collector.add('error', 'DETAIL_MISSING', `任务 ${taskId} 缺少第四章详情区块`, taskId);
13283
+ for (const taskId of [
13284
+ ...detailIds
13285
+ ].filter((id)=>!taskIds.has(id)).sort())collector.add('error', 'DETAIL_ORPHAN', `详情区块 ${taskId} 在任务清单中不存在`, taskId);
13286
+ const tasksById = new Map(tasks.map((task)=>[
13287
+ task.id,
13288
+ task
13289
+ ]));
13290
+ for (const [taskId, detail] of details){
13291
+ const task = tasksById.get(taskId);
13292
+ if (void 0 === task) continue;
13293
+ const scopeRole = roleOfScope(schema, task.scope);
13294
+ const declared = detailFieldsOfScope(schema, task.scope);
13295
+ const declaredCanonical = new Set(declared.map(canonicalField));
13296
+ const canonical = new Map();
13297
+ for (const [name, value] of Object.entries(detail.fields))canonical.set(canonicalField(name), value);
13298
+ 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);
13299
+ for (const field of detailFieldDeclsOfScope(schema, task.scope)){
13300
+ if (!field.required) continue;
13301
+ const value = canonical.get(canonicalField(field.name)) ?? '';
13302
+ if (0 === value.trim().length) collector.add('error', 'DETAIL_FIELD_MISSING', `任务 ${taskId} 详情缺少字段或值为空:${field.name}`, taskId);
13303
+ }
13304
+ if (null === scopeRole) continue;
13305
+ for (const apiField of apiFieldsOfSides(scopeRole)){
13306
+ if (!declared.includes(apiField)) continue;
13307
+ const raw = canonical.get(canonicalField(apiField)) ?? '';
13308
+ if (!(0 === raw.trim().length || API_REF_NONE.has(raw.trim()))) {
13309
+ for (const line of raw.split(/\r?\n/).map((item)=>item.trim()).filter((item)=>item.length > 0))if (!API_REF_NONE.has(line)) {
13310
+ if (!API_REF_PATTERN.test(line)) collector.add('error', 'API_REF_INVALID', `任务 ${taskId} 的「${apiField}」格式非法:${line}(应为 \`METHOD 路径(YAPI id)\`,如 \`GET /api/user(YAPI 66141)\`;无接口请写「无」)`, taskId);
13311
+ }
13312
+ }
13313
+ }
13314
+ const attributes = {
13315
+ id: task.id,
13316
+ requirement: task.requirementId,
13317
+ name: task.name,
13318
+ type: task.type,
13319
+ scope: task.scope,
13320
+ terminal: task.terminal,
13321
+ dependencies: task.dependencies.join('、'),
13322
+ selfTest: task.selfTest,
13323
+ acceptance: task.acceptance,
13324
+ status: task.status,
13325
+ updatedAt: task.updatedAt
13326
+ };
13327
+ for (const fieldName of declared){
13328
+ const spec = taskFieldSpecOf(scopeRole, fieldName);
13329
+ if (void 0 === spec || 'mirror' !== spec.value.kind) continue;
13330
+ const column = spec.value.column;
13331
+ const actual = canonical.get(canonicalField(fieldName)) ?? '';
13332
+ if (0 === actual.length) continue;
13333
+ const expected = attributes[column] ?? '';
13334
+ if (0 === expected.length) continue;
13335
+ const matched = 'contains' === spec.value.match ? expected.includes(actual) || actual.includes(expected) : normalizeState(actual) === normalizeState(expected);
13336
+ if (!matched) collector.add('error', 'DETAIL_STATE_MISMATCH', `任务 ${taskId} 详情「${fieldName}」为「${actual}」,与任务清单「${schema.taskKeys[column] ?? column}」列「${expected}」不一致`, taskId);
13337
+ }
13338
+ }
13339
+ for (const requirement of requirements){
13340
+ const related = tasks.filter((task)=>task.requirementId === requirement.id);
13341
+ if (0 === related.length) {
13342
+ if ('未开始' !== requirement.status) collector.add('error', 'REQUIREMENT_STATUS_MISMATCH', `需求 ${requirement.id} 没有任务,开发状态只能是未开始,当前为「${requirement.status}」`, requirement.id);
13343
+ if ('' !== requirement.progress && '0' !== requirement.progress) collector.add('error', 'REQUIREMENT_PROGRESS_MISMATCH', `需求 ${requirement.id} 没有任务,开发进度只能为 0,当前为「${requirement.progress}」`, requirement.id);
13344
+ continue;
13345
+ }
13346
+ const aggregate = aggregateRequirement(related.map((task)=>task.status));
13347
+ if (requirement.status !== aggregate.status) collector.add('error', 'REQUIREMENT_STATUS_MISMATCH', `需求 ${requirement.id} 开发状态「${requirement.status}」与任务聚合结果「${aggregate.status}」不一致`, requirement.id);
13348
+ if (requirement.progress !== String(aggregate.progress)) collector.add('error', 'REQUIREMENT_PROGRESS_MISMATCH', `需求 ${requirement.id} 开发进度「${requirement.progress}%」应为「${aggregate.progress}%」`, requirement.id);
13349
+ }
13350
+ const tasksById2 = new Map(tasks.map((task)=>[
13351
+ task.id,
13352
+ task
13353
+ ]));
13354
+ for (const task of tasks)for (const dependency of task.dependencies)if (taskIdPattern.test(dependency)) if (tasksById2.has(dependency)) {
13355
+ if (dependency === task.id) collector.add('error', 'DEPENDENCY_SELF', `任务 ${task.id} 依赖自身`, task.id);
13356
+ } else collector.add('error', 'DEPENDENCY_MISSING', `任务 ${task.id} 的前置依赖 ${dependency} 不在任务清单中`, task.id);
13357
+ else collector.add('error', 'DEPENDENCY_ID_INVALID', `任务 ${task.id} 的前置依赖编号格式非法:${dependency}`, task.id);
13358
+ const cycle = findCycle(tasksById2, tasks);
13359
+ if (cycle.length > 0) collector.add('error', 'DEPENDENCY_CYCLE', `前置依赖存在环:${cycle.join(' → ')}`, cycle[0] ?? '');
13360
+ const errors = collector.errors;
13361
+ return {
13362
+ valid: 0 === errors.length,
13363
+ role,
13364
+ iterationInfo,
13365
+ stats: {
13366
+ requirements: requirements.length,
13367
+ tasks: tasks.length,
13368
+ completedTasks: tasks.filter((task)=>'已完成' === task.status).length,
13369
+ details: details.size
13370
+ },
13371
+ requirements,
13372
+ tasks,
13373
+ errors,
13374
+ warnings: collector.warnings
13375
+ };
13376
+ }
13377
+ function findCycle(byId, order) {
13378
+ const visiting = [];
13379
+ const visited = new Set();
13380
+ const visit = (taskId)=>{
13381
+ const at = visiting.indexOf(taskId);
13382
+ if (at >= 0) return [
13383
+ ...visiting.slice(at),
13384
+ taskId
13385
+ ];
13386
+ if (visited.has(taskId)) return [];
13387
+ visiting.push(taskId);
13388
+ const task = byId.get(taskId);
13389
+ for (const dependency of task?.dependencies ?? []){
13390
+ if (!byId.has(dependency)) continue;
13391
+ const found = visit(dependency);
13392
+ if (found.length > 0) return found;
13393
+ }
13394
+ visiting.pop();
13395
+ visited.add(taskId);
13396
+ return [];
13397
+ };
13398
+ for (const task of order){
13399
+ const found = visit(task.id);
13400
+ if (found.length > 0) return found;
13401
+ }
13402
+ return [];
13403
+ }
12659
13404
  function docViewMeta(schema) {
12660
13405
  return {
12661
13406
  requirementColumns: schema.requirementColumns,
@@ -12744,7 +13489,12 @@ function listMarkdownFiles(directory) {
12744
13489
  }
12745
13490
  function accessReason(error) {
12746
13491
  const code = error.code;
12747
- if ("EACCES" === code || "EPERM" === code) return "没有访问权限,请联系管理员开通文档仓库访问权限";
13492
+ const target = error.path;
13493
+ if ("EACCES" === code || "EPERM" === code) return [
13494
+ `没有访问权限:${target ?? ""}`,
13495
+ " 当前会话可能未被授权访问该目录(会话文件访问范围限制),或目录权限位不允许当前用户读取",
13496
+ " → 让会话能访问文档仓库所在目录(放宽会话的文件访问范围),或换一个有权限的终端执行"
13497
+ ].filter((line)=>line.length > 0).join("\n");
12748
13498
  if ("ENOENT" === code) return "文档仓库路径不存在";
12749
13499
  if (error instanceof Error) return error.message;
12750
13500
  return String(error);
@@ -12820,172 +13570,6 @@ function buildIterationList(layout, source, base, refName) {
12820
13570
  iterations: entries
12821
13571
  };
12822
13572
  }
12823
- function coerceIssue(value) {
12824
- if (!utils_isRecord(value)) return null;
12825
- const level = "warning" === value["level"] ? "warning" : "error";
12826
- const code = "string" == typeof value["code"] ? value["code"] : "UNKNOWN";
12827
- const message = "string" == typeof value["message"] ? value["message"] : "";
12828
- const ref = "string" == typeof value["ref"] ? value["ref"] : void 0;
12829
- return void 0 === ref ? {
12830
- level,
12831
- code,
12832
- message
12833
- } : {
12834
- level,
12835
- code,
12836
- message,
12837
- ref
12838
- };
12839
- }
12840
- function coerceRequirement(value) {
12841
- if (!utils_isRecord(value)) return null;
12842
- const id = "string" == typeof value["id"] ? value["id"] : "";
12843
- if (0 === id.length) return null;
12844
- return {
12845
- id,
12846
- title: "string" == typeof value["title"] ? value["title"] : "",
12847
- terminal: "string" == typeof value["terminal"] ? value["terminal"] : "",
12848
- status: "string" == typeof value["status"] ? value["status"] : "",
12849
- progress: String(value["progress"] ?? ""),
12850
- note: "string" == typeof value["note"] ? value["note"] : "",
12851
- updatedAt: "string" == typeof value["updatedAt"] ? value["updatedAt"] : "",
12852
- taskIds: isStringArray(value["taskIds"]) ? value["taskIds"] : []
12853
- };
12854
- }
12855
- function coerceTask(value) {
12856
- if (!utils_isRecord(value)) return null;
12857
- const id = "string" == typeof value["id"] ? value["id"] : "";
12858
- if (0 === id.length) return null;
12859
- return {
12860
- id,
12861
- requirementId: "string" == typeof value["requirementId"] ? value["requirementId"] : "",
12862
- name: "string" == typeof value["name"] ? value["name"] : "",
12863
- type: "string" == typeof value["type"] ? value["type"] : "",
12864
- scope: "string" == typeof value["scope"] ? value["scope"] : "",
12865
- terminal: "string" == typeof value["terminal"] ? value["terminal"] : "",
12866
- dependencies: isStringArray(value["dependencies"]) ? value["dependencies"] : [],
12867
- selfTest: "string" == typeof value["selfTest"] ? value["selfTest"] : "",
12868
- acceptance: "string" == typeof value["acceptance"] ? value["acceptance"] : "",
12869
- status: "string" == typeof value["status"] ? value["status"] : "",
12870
- updatedAt: "string" == typeof value["updatedAt"] ? value["updatedAt"] : ""
12871
- };
12872
- }
12873
- function coerceInfo(value) {
12874
- if (!utils_isRecord(value)) return {};
12875
- const info = {};
12876
- for (const [key, item] of Object.entries(value))if ("string" == typeof item) info[key] = item;
12877
- return info;
12878
- }
12879
- function coercePayload(raw, schema) {
12880
- if (!utils_isRecord(raw)) return null;
12881
- const stats = utils_isRecord(raw["stats"]) ? raw["stats"] : {};
12882
- const requirements = Array.isArray(raw["requirements"]) ? raw["requirements"].map(coerceRequirement).filter((item)=>null !== item) : [];
12883
- const tasks = Array.isArray(raw["tasks"]) ? raw["tasks"].map(coerceTask).filter((item)=>null !== item) : [];
12884
- const errors = Array.isArray(raw["errors"]) ? raw["errors"].map(coerceIssue).filter((item)=>null !== item) : [];
12885
- const warnings = Array.isArray(raw["warnings"]) ? raw["warnings"].map(coerceIssue).filter((item)=>null !== item) : [];
12886
- const asNumber = (value, fallback)=>"number" == typeof value ? value : fallback;
12887
- return {
12888
- valid: true === raw["valid"],
12889
- view: docViewMeta(schema),
12890
- iterationInfo: coerceInfo(raw["iterationInfo"]),
12891
- stats: {
12892
- requirements: asNumber(stats["requirements"], requirements.length),
12893
- tasks: asNumber(stats["tasks"], tasks.length),
12894
- completedTasks: asNumber(stats["completedTasks"], tasks.filter((task)=>"已完成" === task.status).length),
12895
- details: asNumber(stats["details"], 0)
12896
- },
12897
- requirements,
12898
- tasks,
12899
- errors,
12900
- warnings
12901
- };
12902
- }
12903
- const validatorFailureCache = new Map();
12904
- const warnedValidatorFailures = new Set();
12905
- function warnValidatorFailureOnce(key, reason) {
12906
- if (warnedValidatorFailures.has(key)) return;
12907
- warnedValidatorFailures.add(key);
12908
- process.stderr.write(`警告:文档校验器未运行(${reason}),已改用降级解析\n`);
12909
- }
12910
- function runValidator(input) {
12911
- if (null === input.role) return {
12912
- payload: null,
12913
- error: `文档「负责范围」缺失或不是 ${DOC_ROLE_HINT},已跳过校验`
12914
- };
12915
- const script = input.scriptPath;
12916
- if (null === script || !external_node_fs_existsSync(script)) {
12917
- const missing = "文档仓库缺少 scripts/validate_task_doc.py";
12918
- warnValidatorFailureOnce(`missing|${input.docsRoot}`, missing);
12919
- return {
12920
- payload: null,
12921
- error: missing
12922
- };
12923
- }
12924
- const cacheKey = `${script}|${input.docsRoot}|${input.iteration}|${input.developer}|${input.role}`;
12925
- const cachedFailure = validatorFailureCache.get(cacheKey);
12926
- if (void 0 !== cachedFailure) return {
12927
- payload: null,
12928
- error: cachedFailure
12929
- };
12930
- const args = [
12931
- script,
12932
- "--docs-root",
12933
- input.docsRoot,
12934
- "--iteration",
12935
- input.iteration,
12936
- "--developer",
12937
- input.developer,
12938
- "--role",
12939
- input.role,
12940
- "--format",
12941
- "json"
12942
- ];
12943
- let lastError = null;
12944
- let interpreterMissing = true;
12945
- for (const bin of [
12946
- "python3",
12947
- "python",
12948
- "py"
12949
- ])try {
12950
- const stdout = execFileSync(bin, args, {
12951
- encoding: "utf8",
12952
- timeout: 10000,
12953
- maxBuffer: 16777216,
12954
- stdio: [
12955
- "ignore",
12956
- "pipe",
12957
- "pipe"
12958
- ]
12959
- });
12960
- const parsed = coercePayload(JSON.parse(stdout), input.schema);
12961
- if (null !== parsed) return {
12962
- payload: parsed,
12963
- error: null
12964
- };
12965
- } catch (error) {
12966
- const failure = error;
12967
- const stdout = failure.stdout;
12968
- if ("string" == typeof stdout && stdout.trim().length > 0) try {
12969
- const parsed = coercePayload(JSON.parse(stdout), input.schema);
12970
- if (null !== parsed) return {
12971
- payload: parsed,
12972
- error: null
12973
- };
12974
- } catch {}
12975
- if ("ENOENT" === failure.code || 127 === failure.code) continue;
12976
- interpreterMissing = false;
12977
- const stderr = "string" == typeof failure.stderr ? failure.stderr.trim().split("\n") : [];
12978
- lastError = stderr.length > 0 ? (stderr[stderr.length - 1] ?? "").slice(0, 200) : "校验器执行失败";
12979
- }
12980
- const reason = interpreterMissing ? "未找到 python 解释器(需 python3 / python / py)" : lastError;
12981
- const failure = reason ?? "校验器执行失败";
12982
- validatorFailureCache.set(cacheKey, failure);
12983
- warnValidatorFailureOnce(failure, failure);
12984
- return {
12985
- payload: null,
12986
- error: failure
12987
- };
12988
- }
12989
13573
  function extractSection(markdown, heading) {
12990
13574
  const lines = markdown.split(/\r?\n/);
12991
13575
  let start = -1;
@@ -13114,7 +13698,7 @@ function parseMarkdownDoc(markdown, schema) {
13114
13698
  };
13115
13699
  }
13116
13700
  function readMarkdown(target) {
13117
- return readFileSync(target, "utf8");
13701
+ return readTextFile(target).text;
13118
13702
  }
13119
13703
  function resolveIterationForRead(layout, iteration, source, presetRef, refName) {
13120
13704
  const safeIteration = iterations_safeSegment(iteration, "迭代目录");
@@ -13139,6 +13723,31 @@ function resolveIterationForRead(layout, iteration, source, presetRef, refName)
13139
13723
  }
13140
13724
  return resolveIterationDir(layout.root, layout.iterationsRoot, safeIteration);
13141
13725
  }
13726
+ function validateLocally(options) {
13727
+ if (null === options.role) return {
13728
+ payload: parseMarkdownDoc(options.markdown, options.schema),
13729
+ error: `文档「负责范围」缺失或不是 ${DOC_ROLE_HINT},已跳过规则校验`
13730
+ };
13731
+ const result = validateDoc({
13732
+ markdown: options.markdown,
13733
+ schema: options.schema,
13734
+ role: options.role,
13735
+ iterationName: options.iterationName
13736
+ });
13737
+ return {
13738
+ payload: {
13739
+ valid: result.valid,
13740
+ view: docViewMeta(options.schema),
13741
+ iterationInfo: result.iterationInfo,
13742
+ stats: result.stats,
13743
+ requirements: result.requirements,
13744
+ tasks: result.tasks,
13745
+ errors: result.errors,
13746
+ warnings: result.warnings
13747
+ },
13748
+ error: null
13749
+ };
13750
+ }
13142
13751
  function readIterationDoc(layout, iteration, developer, source = "local", presetRef, refName) {
13143
13752
  const docsRoot = layout.root;
13144
13753
  const safeDeveloper = iterations_safeSegment(developer, "开发者标识");
@@ -13148,12 +13757,10 @@ function readIterationDoc(layout, iteration, developer, source = "local", preset
13148
13757
  const ref = presetRef ?? resolveRemoteRef(docsRoot, refName);
13149
13758
  const exported = exportRemoteDoc(docsRoot, ref, resolved.year, safeIteration, safeDeveloper, layout.iterationsRoot);
13150
13759
  const roleInferred = inferRole(exported.markdown);
13151
- const scripted = runValidator({
13760
+ const local = validateLocally({
13761
+ markdown: exported.markdown,
13152
13762
  schema: loadDocSchema(exported.dir),
13153
- docsRoot: exported.dir,
13154
- scriptPath: exported.scriptPath,
13155
- iteration: safeIteration,
13156
- developer: safeDeveloper,
13763
+ iterationName: safeIteration,
13157
13764
  role: roleInferred
13158
13765
  });
13159
13766
  return {
@@ -13162,14 +13769,15 @@ function readIterationDoc(layout, iteration, developer, source = "local", preset
13162
13769
  file: `${resolved.relPath}/${safeDeveloper}.md`,
13163
13770
  mtime: exported.mtime,
13164
13771
  roleInferred,
13165
- parser: null === scripted.payload ? "fallback" : "script",
13166
- parserError: scripted.error,
13772
+ parser: null === local.error ? "local" : "fallback",
13773
+ parserError: local.error,
13167
13774
  source: "remote",
13168
13775
  ref: {
13169
13776
  name: ref.ref,
13170
13777
  sha: ref.sha
13171
13778
  },
13172
- validation: scripted.payload ?? parseMarkdownDoc(exported.markdown, loadDocSchema(exported.dir)),
13779
+ schemaFrom: "snapshot",
13780
+ validation: local.payload,
13173
13781
  details: splitDetails(exported.markdown)
13174
13782
  };
13175
13783
  }
@@ -13179,27 +13787,24 @@ function readIterationDoc(layout, iteration, developer, source = "local", preset
13179
13787
  if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${resolved.relPath}/${safeDeveloper}.md`, errors_EXIT.NOT_FOUND);
13180
13788
  const markdown = readMarkdown(file);
13181
13789
  const roleInferred = inferRole(markdown);
13182
- const scripted = runValidator({
13790
+ const local = validateLocally({
13791
+ markdown,
13183
13792
  schema: loadDocSchema(docsRoot),
13184
- docsRoot,
13185
- scriptPath: external_node_path_join(docsRoot, "scripts", "validate_task_doc.py"),
13186
- iteration: resolved.relPath,
13187
- developer: safeDeveloper,
13793
+ iterationName: safeIteration,
13188
13794
  role: roleInferred
13189
13795
  });
13190
- const validation = scripted.payload ?? parseMarkdownDoc(markdown, loadDocSchema(docsRoot));
13191
- const parser = null === scripted.payload ? "fallback" : "script";
13192
13796
  return {
13193
13797
  iteration: safeIteration,
13194
13798
  developer: safeDeveloper,
13195
13799
  file,
13196
13800
  mtime: statSync(file).mtime.toISOString(),
13197
13801
  roleInferred,
13198
- parser,
13199
- parserError: scripted.error,
13802
+ parser: null === local.error ? "local" : "fallback",
13803
+ parserError: local.error,
13200
13804
  source: "local",
13201
13805
  ref: null,
13202
- validation,
13806
+ schemaFrom: "workspace",
13807
+ validation: local.payload,
13203
13808
  details: splitDetails(markdown)
13204
13809
  };
13205
13810
  }
@@ -13309,11 +13914,33 @@ function readIterationSummary(layout, iteration, source = "local", refName) {
13309
13914
  blocked
13310
13915
  };
13311
13916
  }
13917
+ function readCurrentIteration(layout) {
13918
+ const listed = listIterations(layout, "local");
13919
+ if (!listed.accessible) return {
13920
+ accessible: false,
13921
+ reason: listed.reason,
13922
+ branch: null,
13923
+ iteration: null,
13924
+ candidates: [],
13925
+ available: []
13926
+ };
13927
+ const available = listed.iterations.map((item)=>({
13928
+ name: item.name,
13929
+ relPath: item.relPath
13930
+ }));
13931
+ const matched = resolveIterationFromBranch(layout.root, available.map((item)=>item.name));
13932
+ return {
13933
+ accessible: true,
13934
+ reason: null,
13935
+ ...matched,
13936
+ available
13937
+ };
13938
+ }
13312
13939
  function checkDocTaskSides(options) {
13313
13940
  const resolved = resolveIterationDir(options.docsRoot, options.iterationsRoot, options.iteration);
13314
13941
  const file = external_node_path_join(resolved.dir, `${options.developer}.md`);
13315
13942
  if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${resolved.relPath}/${options.developer}.md`, errors_EXIT.NOT_FOUND);
13316
- const markdown = readFileSync(file, 'utf8');
13943
+ const markdown = readTextFile(file).text;
13317
13944
  const schema = loadDocSchema(options.docsRoot);
13318
13945
  const payload = parseMarkdownDoc(markdown, schema);
13319
13946
  return validateTaskSides({
@@ -13482,6 +14109,27 @@ function commitInDocsRepo(docsRoot, file, message, push) {
13482
14109
  message: '已提交并推送'
13483
14110
  };
13484
14111
  }
14112
+ function hasPendingChange(docsRoot, file) {
14113
+ try {
14114
+ const output = execFileSync('git', [
14115
+ 'status',
14116
+ '--porcelain',
14117
+ '--',
14118
+ file
14119
+ ], {
14120
+ cwd: docsRoot,
14121
+ encoding: 'utf8',
14122
+ stdio: [
14123
+ 'ignore',
14124
+ 'pipe',
14125
+ 'pipe'
14126
+ ]
14127
+ });
14128
+ return output.trim().length > 0;
14129
+ } catch {
14130
+ return false;
14131
+ }
14132
+ }
13485
14133
  function appendHistory(entry) {
13486
14134
  try {
13487
14135
  const target = historyPath();
@@ -13498,7 +14146,7 @@ function readTaskHistory(options) {
13498
14146
  const target = historyPath();
13499
14147
  if (!external_node_fs_existsSync(target)) return [];
13500
14148
  const limit = options.limit ?? 5;
13501
- const lines = readFileSync(target, 'utf8').trim().split('\n').filter((line)=>line.length > 0);
14149
+ const lines = readTextFile(target).text.trim().split('\n').filter((line)=>line.length > 0);
13502
14150
  const entries = [];
13503
14151
  for(let index = lines.length - 1; index >= 0 && entries.length < limit; index -= 1){
13504
14152
  const line = lines[index];
@@ -13673,12 +14321,13 @@ function loadDoc(locator, iterationRaw, developerRaw) {
13673
14321
  const file = external_node_path_join(dir, `${developer}.md`);
13674
14322
  if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${relPath}/${developer}.md`, errors_EXIT.NOT_FOUND);
13675
14323
  const mtime = statSync(file).mtimeMs;
13676
- const original = readFileSync(file, 'utf8');
14324
+ const { text, eol } = readTextFile(file);
13677
14325
  return {
13678
14326
  file,
13679
14327
  mtime,
13680
- original,
13681
- lines: original.split('\n')
14328
+ original: text,
14329
+ eol,
14330
+ lines: text.split('\n')
13682
14331
  };
13683
14332
  }
13684
14333
  function computeUpdate(lines, taskId, action, keys, docsRoot) {
@@ -13713,12 +14362,7 @@ function computeUpdate(lines, taskId, action, keys, docsRoot) {
13713
14362
  人工验收: nextAcceptance
13714
14363
  });
13715
14364
  const requirementStatuses = rows.filter((row)=>row.requirementId === target.requirementId).map((row)=>row.taskId === taskId ? nextStatus : row.status);
13716
- const aggregate = resolveAggregates(docsRoot, new Map([
13717
- [
13718
- target.requirementId,
13719
- requirementStatuses
13720
- ]
13721
- ])).get(target.requirementId) ?? aggregateRequirement(requirementStatuses);
14365
+ const aggregate = aggregateRequirement(requirementStatuses);
13722
14366
  const requirementStatus = aggregate.status;
13723
14367
  const progress = aggregate.progress;
13724
14368
  const requirementParse = parseRequirementRows(withDetail, keys);
@@ -13752,18 +14396,12 @@ function syncRequirementAggregates(docsRoot, lines, keys, stamp) {
13752
14396
  row.status
13753
14397
  ]);
13754
14398
  }
13755
- const aggregates = resolveAggregates(docsRoot, statusesByCode);
13756
- const byStatuses = new Map();
13757
- for (const [code, statuses] of statusesByCode){
13758
- const value = aggregates.get(code);
13759
- if (void 0 !== value) byStatuses.set(statuses.join('\u0000'), value);
13760
- }
13761
14399
  return refreshRequirementRows({
13762
14400
  lines,
13763
14401
  schema,
13764
14402
  statusesByCode,
13765
14403
  stamp,
13766
- aggregate: (statuses)=>byStatuses.get(statuses.join('\u0000')) ?? aggregateRequirement(statuses)
14404
+ aggregate: aggregateRequirement
13767
14405
  });
13768
14406
  } catch {
13769
14407
  return {
@@ -13772,8 +14410,11 @@ function syncRequirementAggregates(docsRoot, lines, keys, stamp) {
13772
14410
  };
13773
14411
  }
13774
14412
  }
14413
+ function assertFileUnmodified(file, expectedMtime) {
14414
+ if (statSync(file).mtimeMs !== expectedMtime) throw new errors_CliError('文件已被外部修改,请刷新后重试', errors_EXIT.INVALID);
14415
+ }
13775
14416
  function commit(context, lines, changes, message, iteration, developer, action, taskIds, options) {
13776
- if (statSync(context.file).mtimeMs !== context.mtime) throw new errors_CliError('文件已被外部修改,请刷新后重试', errors_EXIT.INVALID);
14417
+ assertFileUnmodified(context.file, context.mtime);
13777
14418
  const synced = syncRequirementAggregates(options.docsRoot, lines, buildKeys(loadDocSchema(options.docsRoot)), nowStamp());
13778
14419
  lines = synced.lines;
13779
14420
  changes = [
@@ -13787,16 +14428,37 @@ function commit(context, lines, changes, message, iteration, developer, action,
13787
14428
  changes: [],
13788
14429
  file: context.file
13789
14430
  };
13790
- writeFileSync(context.file, output, 'utf8');
14431
+ const pendingBefore = options.policy.commit ? hasPendingChange(options.docsRoot, context.file) : false;
14432
+ const scope = {
14433
+ action: '写入任务文档',
14434
+ target: context.file,
14435
+ others: options.policy.commit ? [
14436
+ historyPath(),
14437
+ external_node_path_join(options.docsRoot, '.git')
14438
+ ] : [
14439
+ historyPath()
14440
+ ]
14441
+ };
14442
+ writeTextFile(scope, applyEol(output, context.eol));
13791
14443
  const outcome = validateAfterWrite(toLayout(options), iteration, developer);
14444
+ const strict = strictValidationEnabled();
13792
14445
  if ('violation' === outcome.kind) {
13793
- writeFileSync(context.file, context.original, 'utf8');
13794
- throw new errors_CliError(`写入被校验器拒绝,已回滚:${outcome.message}`, errors_EXIT.INVALID);
14446
+ if (strict) {
14447
+ writeTextFile({
14448
+ action: '回滚任务文档',
14449
+ target: context.file
14450
+ }, applyEol(context.original, context.eol));
14451
+ throw new errors_CliError(`写入未通过文档校验,已回滚(文档未改变):${outcome.message}`, errors_EXIT.INVALID);
14452
+ }
14453
+ process.stderr.write(`警告:写入未通过文档校验(docs.validator.strict=false):${outcome.message}\n`);
13795
14454
  }
13796
14455
  if ('unavailable' === outcome.kind) {
13797
- writeFileSync(context.file, context.original, 'utf8');
13798
- if (requireValidatorScript()) throw new errors_CliError(`未执行文档校验,已回滚:${outcome.reason}\n文档校验必须由文档仓库 scripts/validate_task_doc.py 裁决;如确需跳过(不推荐),可配置 docs.validator.requireScript: false`, errors_EXIT.INVALID);
13799
- process.stderr.write(`警告:${outcome.reason};本次写入未做文档校验(docs.validator.requireScript=false)\n`);
14456
+ writeTextFile({
14457
+ action: '回滚任务文档',
14458
+ target: context.file
14459
+ }, applyEol(context.original, context.eol));
14460
+ if (strict) throw new errors_CliError(`未执行文档校验,已回滚(文档未改变):${outcome.reason}\n如需在无法校验时仍写入(不推荐),可配置 docs.validator.strict: false`, errors_EXIT.INVALID);
14461
+ process.stderr.write(`警告:${outcome.reason};本次写入未做文档校验(docs.validator.strict=false)\n`);
13800
14462
  }
13801
14463
  appendHistory({
13802
14464
  iteration,
@@ -13806,12 +14468,16 @@ function commit(context, lines, changes, message, iteration, developer, action,
13806
14468
  changes
13807
14469
  });
13808
14470
  const git = options.policy.commit ? commitInDocsRepo(options.docsRoot, context.file, options.commitMessage, options.policy.push) : void 0;
14471
+ const warnings = [];
14472
+ if (pendingBefore) warnings.push(`该文档在本次操作前已有未提交改动,本次提交会一并包含:${context.file}\n 如需分开提交,请先提交(或 stash)遗留改动后重试`);
14473
+ if (void 0 !== git && !git.committed) warnings.push(`文档已写入,但未提交:${git.message}`);
13809
14474
  return {
13810
14475
  ok: true,
13811
14476
  message,
13812
14477
  changes,
13813
14478
  file: context.file,
13814
- git
14479
+ git,
14480
+ warnings
13815
14481
  };
13816
14482
  }
13817
14483
  function normalizeDetailField(name) {
@@ -13882,7 +14548,10 @@ function applyTaskDetail(options) {
13882
14548
  const touched = [];
13883
14549
  for (const update of options.updates){
13884
14550
  const fieldName = allowed.get(normalizeDetailField(update.field));
13885
- if (void 0 === fieldName) throw new errors_CliError(`字段「${update.field}」不可编辑(可改:${allowedFields.join(' / ')})`, errors_EXIT.USAGE);
14551
+ if (void 0 === fieldName) {
14552
+ const reason = 0 === allowedFields.length ? `任务的「所属端」为「${scope.length > 0 ? scope : '空'}」,不在 schema 的 roles 中,无法确定可编辑字段` : `可改:${allowedFields.join(' / ')}`;
14553
+ throw new errors_CliError(`字段「${update.field}」不可编辑(${reason})`, errors_EXIT.USAGE);
14554
+ }
13886
14555
  if (lockedDetailFields(schema, scope).has(fieldName)) throw new errors_CliError(`字段「${fieldName}」由状态流转命令维护,请使用 task start/submit/accept/reject 或 task selftest`, errors_EXIT.USAGE);
13887
14556
  const parsed = readDetailField(lines, options.taskId, fieldName);
13888
14557
  if (null === parsed) throw new errors_CliError(`任务 ${options.taskId} 的详情区块缺少字段「${fieldName}」`, errors_EXIT.INVALID);
@@ -14016,93 +14685,38 @@ function applyTaskAction(options) {
14016
14685
  });
14017
14686
  }
14018
14687
  function validateAfterWrite(layout, iteration, developer) {
14019
- const docsRoot = layout.root;
14020
- const script = external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py');
14021
- if (!external_node_fs_existsSync(script)) return {
14688
+ const schema = loadDocSchema(layout.root);
14689
+ const resolved = resolveIterationDir(layout.root, layout.iterationsRoot, iteration);
14690
+ const targetFile = external_node_path_join(resolved.dir, `${developer}.md`);
14691
+ if (!external_node_fs_existsSync(targetFile)) return {
14022
14692
  kind: 'unavailable',
14023
- reason: `文档仓库缺少校验脚本 ${script}`
14693
+ reason: `找不到个人任务文档:${targetFile}`
14024
14694
  };
14025
- const resolved = resolveIterationDir(docsRoot, layout.iterationsRoot, iteration);
14026
- const targetFile = external_node_path_join(resolved.dir, `${developer}.md`);
14027
- const role = external_node_fs_existsSync(targetFile) ? inferRole(readFileSync(targetFile, 'utf8')) : null;
14695
+ const markdown = readTextFile(targetFile).text;
14696
+ const role = roleOfDocument(markdown, schema);
14028
14697
  if (null === role) return {
14029
14698
  kind: 'unavailable',
14030
- reason: `文档「负责范围」缺失或不是 ${DOC_ROLE_HINT},无法确定校验角色`
14699
+ reason: `文档「负责范围」缺失或不是 ${Object.keys(schema.roles).join(' / ')},无法确定校验角色`
14031
14700
  };
14032
- const args = [
14033
- script,
14034
- '--docs-root',
14035
- docsRoot,
14036
- '--iteration',
14037
- resolved.relPath,
14038
- '--developer',
14039
- developer,
14040
- '--role',
14701
+ const result = validateDoc({
14702
+ markdown,
14703
+ schema,
14041
14704
  role,
14042
- '--format',
14043
- 'json'
14044
- ];
14045
- let interpreterMissing = true;
14046
- let scriptError = null;
14047
- for (const bin of [
14048
- 'python3',
14049
- 'python',
14050
- 'py'
14051
- ])try {
14052
- const stdout = execFileSync(bin, args, {
14053
- encoding: 'utf8',
14054
- timeout: 15000,
14055
- maxBuffer: 16777216,
14056
- stdio: [
14057
- 'ignore',
14058
- 'pipe',
14059
- 'pipe'
14060
- ]
14061
- });
14062
- const payload = JSON.parse(stdout);
14063
- const first = payload.errors?.[0];
14064
- return void 0 === first ? {
14065
- kind: 'passed'
14066
- } : {
14067
- kind: 'violation',
14068
- message: first.message ?? '校验器未通过'
14069
- };
14070
- } catch (error) {
14071
- const { stdout, stderr, code } = error;
14072
- if ('ENOENT' === code || 127 === code) continue;
14073
- interpreterMissing = false;
14074
- if ((stdout ?? '').trim().length > 0) try {
14075
- const payload = JSON.parse(stdout ?? '');
14076
- return {
14077
- kind: 'violation',
14078
- message: payload.errors?.[0]?.message ?? '校验器未通过'
14079
- };
14080
- } catch {
14081
- scriptError = '校验器输出无法解析';
14082
- continue;
14083
- }
14084
- const reason = (stderr ?? '').trim().split('\n')[0] ?? '';
14085
- scriptError = reason.length > 0 ? `校验器执行失败:${reason}` : '校验器执行失败';
14086
- continue;
14087
- }
14088
- if (null !== scriptError) return {
14089
- kind: 'unavailable',
14090
- reason: scriptError
14091
- };
14092
- if (interpreterMissing) return {
14093
- kind: 'unavailable',
14094
- reason: '未找到 python 解释器(需 python3 / python / py)'
14095
- };
14096
- return {
14097
- kind: 'unavailable',
14098
- reason: '校验器无法执行'
14705
+ iterationName: resolved.name
14706
+ });
14707
+ const first = result.errors[0];
14708
+ return void 0 === first ? {
14709
+ kind: 'passed'
14710
+ } : {
14711
+ kind: 'violation',
14712
+ message: first.message
14099
14713
  };
14100
14714
  }
14101
- function requireValidatorScript() {
14715
+ function strictValidationEnabled() {
14102
14716
  try {
14103
14717
  const config = config_loadConfig().config;
14104
14718
  if (null === config) return true;
14105
- return config.docs.validator.requireScript;
14719
+ return config.docs.validator.strict;
14106
14720
  } catch {
14107
14721
  return true;
14108
14722
  }
@@ -14156,15 +14770,14 @@ function recalcRequirements(options) {
14156
14770
  ...context.lines
14157
14771
  ];
14158
14772
  const changes = [];
14159
- const aggregates = resolveAggregates(options.docsRoot, new Map(requirementParse.rows.map((requirement)=>[
14160
- requirement.id,
14161
- taskRows.filter((row)=>row.requirementId === requirement.id).map((row)=>row.status)
14162
- ])));
14773
+ const statusesByRequirement = new Map();
14774
+ for (const row of taskRows){
14775
+ const list = statusesByRequirement.get(row.requirementId) ?? [];
14776
+ list.push(row.status);
14777
+ statusesByRequirement.set(row.requirementId, list);
14778
+ }
14163
14779
  for (const requirement of requirementParse.rows){
14164
- const aggregate = aggregates.get(requirement.id) ?? {
14165
- status: '未开始',
14166
- progress: 0
14167
- };
14780
+ const aggregate = aggregateRequirement(statusesByRequirement.get(requirement.id) ?? []);
14168
14781
  const status = aggregate.status;
14169
14782
  const progress = aggregate.progress;
14170
14783
  const cells = [
@@ -14207,7 +14820,7 @@ function availableActions(options) {
14207
14820
  }
14208
14821
  const file = external_node_path_join(dir, `${developer}.md`);
14209
14822
  if (!external_node_fs_existsSync(file)) return {};
14210
- const lines = readFileSync(file, 'utf8').split('\n');
14823
+ const lines = readTextFile(file).text.split('\n');
14211
14824
  const { rows } = parseTaskRows(lines, buildKeys(loadDocSchema(options.docsRoot)));
14212
14825
  const result = {};
14213
14826
  for (const row of rows){
@@ -14222,7 +14835,10 @@ function availableActions(options) {
14222
14835
  list.push({
14223
14836
  action: 'submit',
14224
14837
  enabled: ok,
14225
- reason: ok ? '' : `AI 自测为「${row.selfTest}」,需先通过自测`
14838
+ reason: ok ? '' : '需先自测通过',
14839
+ ...ok ? {} : {
14840
+ nextStep: `ylcwf task selftest --iteration ${options.iteration} ${row.taskId} --result 通过`
14841
+ }
14226
14842
  });
14227
14843
  }
14228
14844
  if ('待验收' === row.status) {
@@ -14641,7 +15257,7 @@ function runDocMigrate(options) {
14641
15257
  const files = external_node_fs_readdirSync(dir).filter((name)=>name.endsWith('.md') && !name.startsWith('_'));
14642
15258
  for (const name of files){
14643
15259
  const target = external_node_path_join(dir, name);
14644
- const original = readFileSync(target, 'utf8');
15260
+ const { text: original, eol } = readTextFile(target);
14645
15261
  const strippedResult = stripHashIds({
14646
15262
  lines: original.split('\n'),
14647
15263
  schema
@@ -14688,16 +15304,22 @@ function runDocMigrate(options) {
14688
15304
  unresolved: tableMigrated.unresolved
14689
15305
  });
14690
15306
  if (true === options.dryRun) continue;
14691
- writeFileSync(target, migrated.lines.join('\n'), 'utf8');
15307
+ writeTextFile({
15308
+ action: '迁移迭代任务文档',
15309
+ target
15310
+ }, applyEol(migrated.lines.join('\n'), eol));
14692
15311
  changedFiles.push(target);
14693
15312
  if (migrated.unresolved.length > 0) continue;
14694
15313
  const developer = basename(name, '.md');
14695
15314
  const outcome = validateAfterWrite(layout, iteration.relPath, developer);
14696
15315
  if ('passed' !== outcome.kind) {
14697
- writeFileSync(target, original, 'utf8');
15316
+ writeTextFile({
15317
+ action: '回滚迁移',
15318
+ target
15319
+ }, applyEol(original, eol));
14698
15320
  const reason = 'violation' === outcome.kind ? outcome.message : outcome.reason;
14699
- if ('unavailable' === outcome.kind && !requireValidatorScript()) {
14700
- process.stderr.write(`警告:${outcome.reason};${iteration.relPath}/${name} 未做迁移后校验(docs.validator.requireScript=false)\n`);
15321
+ if (!strictValidationEnabled()) {
15322
+ process.stderr.write(`警告:${reason};${iteration.relPath}/${name} 迁移后校验未通过(docs.validator.strict=false)\n`);
14701
15323
  continue;
14702
15324
  }
14703
15325
  throw new errors_CliError(`迁移后校验未通过,已回滚 ${iteration.relPath}/${name}:${reason}`, errors_EXIT.INVALID);
@@ -14727,8 +15349,7 @@ function runDocMigrate(options) {
14727
15349
  printLine('\n以下任务的「所属端」无法自动判定(执行终端未配置或类型两端通用),请手工补齐:');
14728
15350
  printLine(` ${totalUnresolved.join('、')}`);
14729
15351
  printLine('补齐后运行校验:');
14730
- printLine(" python3 <文档仓库>/scripts/validate_task_doc.py --docs-root <文档仓库> \\");
14731
- printLine(' --iteration <迭代> --developer <标识> --role <frontend|backend|fullstack>');
15352
+ printLine(' ylcwf doc validate -i <迭代> -d <开发者>');
14732
15353
  }
14733
15354
  if (true !== options.dryRun) {
14734
15355
  const policy = config.docs.git.cli;
@@ -14765,127 +15386,662 @@ function registerDocMigrate(doc) {
14765
15386
  runDocMigrate(options);
14766
15387
  });
14767
15388
  }
14768
- function doc_nowStamp() {
14769
- const now = new Date();
14770
- const pad = (value)=>String(value).padStart(2, '0');
14771
- return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
15389
+ const RESERVED_DOC_FILES = new Set([
15390
+ 'README.md',
15391
+ 'AGENTS.md',
15392
+ 'CLAUDE.md'
15393
+ ]);
15394
+ function roleHintOf(schema) {
15395
+ return Object.keys(schema.roles).join(' / ');
14772
15396
  }
14773
- function readPlanFile(path) {
14774
- if (!external_node_fs_existsSync(path)) throw new errors_CliError(`plan 文件不存在:${path}`, errors_EXIT.NOT_FOUND);
14775
- const text = readFileSync(path, 'utf8');
15397
+ function gitLines(cwd, args) {
14776
15398
  try {
14777
- return JSON.parse(text);
15399
+ const stdout = execFileSync('git', args, {
15400
+ cwd,
15401
+ encoding: 'utf8',
15402
+ stdio: [
15403
+ 'ignore',
15404
+ 'pipe',
15405
+ 'pipe'
15406
+ ]
15407
+ });
15408
+ return stdout.split('\n').map((line)=>line.trim()).filter((line)=>line.length > 0);
14778
15409
  } catch (error) {
14779
- throw new errors_CliError(`plan 文件不是合法 JSON:${error instanceof Error ? error.message : String(error)}`, errors_EXIT.INVALID);
15410
+ const reason = error instanceof Error ? error.message.split('\n')[0] : String(error);
15411
+ throw new errors_CliError(`git ${args.join(' ')} 执行失败:${reason ?? ''}`, errors_EXIT.INVALID);
14780
15412
  }
14781
15413
  }
14782
- function runDocApply(options, mode = 'apply') {
15414
+ function iterationsOfFiles(layout, files) {
15415
+ const prefix = `${layout.iterationsRoot}/`;
15416
+ const found = new Set();
15417
+ for (const file of files){
15418
+ if (!file.startsWith(prefix)) continue;
15419
+ const parts = file.slice(prefix.length).split('/');
15420
+ const year = parts[0];
15421
+ const name = parts[1];
15422
+ if (!(parts.length < 3) && void 0 !== year && void 0 !== name) found.add(`${year}/${name}`);
15423
+ }
15424
+ return [
15425
+ ...found
15426
+ ].sort();
15427
+ }
15428
+ function resolveTargets(options, layout) {
15429
+ const requested = (options.iteration ?? '').trim();
15430
+ const base = (options.base ?? '').trim();
15431
+ const chosen = [
15432
+ requested.length > 0,
15433
+ true === options.all,
15434
+ true === options.staged,
15435
+ base.length > 0
15436
+ ].filter((item)=>item).length;
15437
+ if (0 === chosen) throw new errors_CliError('必须指定校验范围之一:-i/--iteration <迭代>、--all、--staged、--base <ref>', errors_EXIT.USAGE);
15438
+ if (chosen > 1) throw new errors_CliError('校验范围只能选一个:-i/--iteration、--all、--staged、--base', errors_EXIT.USAGE);
15439
+ if (requested.length > 0) return [
15440
+ requireIterationDir(layout.root, layout.iterationsRoot, requested).relPath
15441
+ ];
15442
+ if (true === options.all) return listIterationDirs(layout.root, layout.iterationsRoot).map((item)=>item.relPath);
15443
+ if (true === options.staged) return iterationsOfFiles(layout, gitLines(layout.root, [
15444
+ 'diff',
15445
+ '--cached',
15446
+ '--name-only'
15447
+ ]));
15448
+ return iterationsOfFiles(layout, gitLines(layout.root, [
15449
+ 'diff',
15450
+ '--name-only',
15451
+ `${base}...HEAD`
15452
+ ]));
15453
+ }
15454
+ function validateIteration(options) {
15455
+ const { layout, schema, explicitRole, developerFilter } = options;
15456
+ const resolved = requireIterationDir(layout.root, layout.iterationsRoot, options.relPath);
15457
+ const developers = developerFilter.length > 0 ? [
15458
+ developerFilter
15459
+ ] : external_node_fs_readdirSync(resolved.dir).filter((name)=>name.endsWith('.md') && !RESERVED_DOC_FILES.has(name)).map((name)=>name.slice(0, -3)).sort();
15460
+ if (0 === developers.length) return [
15461
+ {
15462
+ iteration: resolved.relPath,
15463
+ developer: developerFilter.length > 0 ? developerFilter : '(无成员文档)',
15464
+ role: null,
15465
+ fileRelPath: resolved.relPath,
15466
+ valid: false,
15467
+ stats: null,
15468
+ errors: [
15469
+ {
15470
+ level: 'error',
15471
+ code: 'DEVELOPER_DOC_EMPTY',
15472
+ message: `迭代 ${resolved.relPath} 下没有成员文档`
15473
+ }
15474
+ ],
15475
+ warnings: []
15476
+ }
15477
+ ];
15478
+ return developers.map((developer)=>{
15479
+ const file = external_node_path_join(resolved.dir, `${developer}.md`);
15480
+ const fileRelPath = external_node_path_relative(layout.root, file);
15481
+ if (!external_node_fs_existsSync(file)) return {
15482
+ iteration: resolved.relPath,
15483
+ developer,
15484
+ role: null,
15485
+ fileRelPath,
15486
+ valid: false,
15487
+ stats: null,
15488
+ errors: [
15489
+ {
15490
+ level: 'error',
15491
+ code: 'DEVELOPER_FILE_MISSING',
15492
+ message: `个人任务文档不存在:${fileRelPath}`
15493
+ }
15494
+ ],
15495
+ warnings: []
15496
+ };
15497
+ const markdown = readTextFile(file).text;
15498
+ const role = explicitRole.length > 0 ? explicitRole : roleOfDocument(markdown, schema);
15499
+ if (null === role) return {
15500
+ iteration: resolved.relPath,
15501
+ developer,
15502
+ role: null,
15503
+ fileRelPath,
15504
+ valid: false,
15505
+ stats: null,
15506
+ errors: [
15507
+ {
15508
+ level: 'error',
15509
+ code: 'ROLE_UNKNOWN',
15510
+ message: `「负责范围」缺失或不是 ${roleHintOf(schema)},无法确定校验角色`
15511
+ }
15512
+ ],
15513
+ warnings: []
15514
+ };
15515
+ const result = validateDoc({
15516
+ markdown,
15517
+ schema,
15518
+ role,
15519
+ iterationName: resolved.name
15520
+ });
15521
+ return {
15522
+ iteration: resolved.relPath,
15523
+ developer,
15524
+ role,
15525
+ fileRelPath,
15526
+ valid: result.valid,
15527
+ stats: result.stats,
15528
+ errors: result.errors,
15529
+ warnings: result.warnings
15530
+ };
15531
+ });
15532
+ }
15533
+ function runDocValidate(options) {
14783
15534
  const format = parseFormat(options.format);
15535
+ enableJsonErrors('json' === format);
14784
15536
  const loaded = config_loadConfig(options.config);
14785
15537
  if (!loaded.exists || null === loaded.config) throw new errors_CliError(`配置未初始化:${loaded.path}\n请先运行:ylcwf init`, errors_EXIT.NOT_FOUND);
14786
15538
  const config = loaded.config;
14787
- const docsRoot = config.docs.root;
14788
- const layout = layoutOf(config);
14789
- const developer = config.profile.developer;
14790
- const role = config.profile.role;
14791
- const requested = options.iteration.trim();
14792
- if (0 === requested.length) throw new errors_CliError('必须指定迭代目录:--iteration <迭代>', errors_EXIT.USAGE);
14793
- const resolvedIteration = requireIterationDir(docsRoot, layout.iterationsRoot, requested);
14794
- const iteration = resolvedIteration.name;
14795
- const schema = loadDocSchema(docsRoot);
14796
- const plan = parseDocPlan(readPlanFile(options.input), schema, role);
14797
- const targetDir = resolvedIteration.dir;
14798
- const targetFile = external_node_path_join(targetDir, `${developer}.md`);
14799
- const exists = external_node_fs_existsSync(targetFile);
14800
- const original = exists ? readFileSync(targetFile, 'utf8') : null;
14801
- const mtime = exists ? statSync(targetFile).mtimeMs : 0;
14802
- const parsed = null === original ? {
14803
- requirements: [],
14804
- tasks: []
14805
- } : parseMarkdownDoc(original, schema);
14806
- if (null !== original) {
14807
- const documentRole = inferRole(original);
14808
- if (null === documentRole) process.stderr.write(`提示:${resolvedIteration.relPath}/${developer}.md 的「负责范围」是「${readRoleText(original) || '(缺失)'}」,不是 ${DOC_ROLE_HINT}。\n 写入后的校验会因此跳过;请先把该行改成 ${role}(你的 profile.role)。\n`);
14809
- else if (documentRole !== role) process.stderr.write(`提示:${resolvedIteration.relPath}/${developer}.md 的负责范围是「${documentRole}」,与当前角色「${role}」不一致。\n 写入后的校验按文档为准(${documentRole});要让文档与本机角色一致,请手工修改「负责范围」为 ${role}。\n`);
14810
- }
14811
- validatePlanReferences({
14812
- plan,
14813
- schema,
14814
- role,
14815
- index: buildRepoSideIndex(config.terminals),
14816
- knownTaskIds: parsed.tasks.map((task)=>task.id),
14817
- knownRequirements: parsed.requirements.map((item)=>item.id)
14818
- });
14819
- const statusesByRequirement = new Map();
14820
- for (const item of parsed.tasks){
14821
- const list = statusesByRequirement.get(item.requirementId) ?? [];
14822
- statusesByRequirement.set(item.requirementId, [
14823
- ...list,
14824
- item.status
14825
- ]);
14826
- }
14827
- for (const task of plan.tasks){
14828
- const list = statusesByRequirement.get(task.requirement) ?? [];
14829
- statusesByRequirement.set(task.requirement, [
14830
- ...list,
14831
- '未开始'
14832
- ]);
14833
- }
14834
- const aggregates = resolveAggregates(docsRoot, statusesByRequirement);
14835
- const aggregateByStatuses = new Map();
14836
- for (const [requirementId, statuses] of statusesByRequirement){
14837
- const value = aggregates.get(requirementId);
14838
- if (void 0 !== value) aggregateByStatuses.set(statuses.join('\u0000'), value);
14839
- }
14840
- const stamp = doc_nowStamp();
14841
- const rendered = renderPlan({
14842
- schema,
14843
- role,
14844
- plan,
14845
- existing: {
14846
- requirements: parsed.requirements,
14847
- tasks: parsed.tasks,
14848
- lines: null === original ? null : original.split('\n')
14849
- },
14850
- stamp,
14851
- developer,
14852
- aggregate: (statuses)=>aggregateByStatuses.get(statuses.join('\u0000')) ?? aggregateRequirement(statuses)
14853
- });
14854
- const sideIndex = buildRepoSideIndex(config.terminals);
14855
- const sideReport = validateTaskSides({
14856
- index: sideIndex,
14857
- tasks: rendered.assigned.map((item)=>{
14858
- const planned = plan.tasks.find((task)=>task.name === item.name);
14859
- return {
14860
- id: item.id,
14861
- scope: planned?.scope ?? '',
14862
- terminal: planned?.terminal ?? ''
14863
- };
14864
- })
14865
- });
14866
- const conflicts = sideReport.issues.filter((issue)=>'error' === issue.level);
14867
- if (conflicts.length > 0) throw new errors_CliError(`任务类型与执行终端归属不一致,已中止:\n${conflicts.map((issue)=>` · ${issue.message}`).join('\n')}`, errors_EXIT.INVALID);
14868
- const sideSkippedNote = sideReport.skipped > 0 ? `本机执行终端配置未覆盖 ${sideReport.skipped} 个任务,其「所属端 vs 仓库」未校验` + (0 === Object.keys(config.terminals).length ? '(terminals 为空)' : '') : null;
14869
- if (0 === rendered.assigned.length && rendered.markdown === original) {
15539
+ const baseLayout = layoutOf(config);
15540
+ const layout = void 0 === options.docsRoot ? baseLayout : {
15541
+ ...baseLayout,
15542
+ root: external_node_path_resolve(options.docsRoot)
15543
+ };
15544
+ const schema = loadDocSchema(layout.root);
15545
+ const roles = Object.keys(schema.roles);
15546
+ const explicitRole = (options.role ?? '').trim();
15547
+ if (explicitRole.length > 0 && !roles.includes(explicitRole)) throw new errors_CliError(`--role 只能是 ${roles.join(' / ')}:${explicitRole}`, errors_EXIT.USAGE);
15548
+ const targets = resolveTargets(options, layout);
15549
+ if (0 === targets.length) {
15550
+ const scope = true === options.staged ? '暂存区' : void 0 === options.base ? '迭代根' : `${options.base}...HEAD`;
14870
15551
  if ('json' === format) printJson({
14871
15552
  ok: true,
14872
- changed: false,
14873
- file: targetFile,
14874
- changes: [],
14875
- assigned: []
15553
+ scope,
15554
+ iterations: [],
15555
+ summary: {
15556
+ iterations: 0,
15557
+ documents: 0,
15558
+ errors: 0,
15559
+ warnings: 0
15560
+ },
15561
+ documents: []
14876
15562
  });
14877
- else printLine('计划中的需求与任务都已存在,未做修改');
15563
+ else printLine(`${scope} 没有涉及任何迭代,无需校验`);
14878
15564
  return;
14879
15565
  }
14880
- if ('diff' === mode || true === options.dryRun) {
14881
- if ('json' === format) printJson({
14882
- ok: true,
14883
- dryRun: true,
14884
- mode,
14885
- file: targetFile,
14886
- changes: rendered.changes,
14887
- assigned: rendered.assigned,
14888
- preview: rendered.markdown
15566
+ const developerFilter = (options.developer ?? '').trim();
15567
+ const entries = targets.flatMap((relPath)=>validateIteration({
15568
+ layout,
15569
+ relPath,
15570
+ schema,
15571
+ explicitRole,
15572
+ developerFilter
15573
+ }));
15574
+ const errorCount = entries.reduce((sum, entry)=>sum + entry.errors.length, 0);
15575
+ const warningCount = entries.reduce((sum, entry)=>sum + entry.warnings.length, 0);
15576
+ const ok = 0 === errorCount;
15577
+ if ('json' === format) printJson({
15578
+ ok,
15579
+ iterations: targets,
15580
+ summary: {
15581
+ iterations: targets.length,
15582
+ documents: entries.length,
15583
+ errors: errorCount,
15584
+ warnings: warningCount
15585
+ },
15586
+ documents: entries
15587
+ });
15588
+ else {
15589
+ const byIteration = new Map();
15590
+ for (const entry of entries){
15591
+ const list = byIteration.get(entry.iteration) ?? [];
15592
+ list.push(entry);
15593
+ byIteration.set(entry.iteration, list);
15594
+ }
15595
+ for (const [iteration, items] of byIteration){
15596
+ printLine(`迭代:${iteration}`);
15597
+ for (const entry of items){
15598
+ const role = entry.role ?? '未识别';
15599
+ const mark = entry.valid ? '✓' : '✗';
15600
+ const stats = null === entry.stats ? '' : ` 需求 ${entry.stats.requirements} / 任务 ${entry.stats.tasks}(已完成 ${entry.stats.completedTasks}) / 详情 ${entry.stats.details}`;
15601
+ printLine(` ${mark} ${entry.developer}(${role})${stats}`);
15602
+ for (const issue of entry.errors)printLine(` [error] ${issue.code}:${issue.message}`);
15603
+ for (const issue of entry.warnings)printLine(` [warn ] ${issue.code}:${issue.message}`);
15604
+ }
15605
+ printLine('');
15606
+ }
15607
+ printLine(ok ? `校验通过:${targets.length} 个迭代 / ${entries.length} 份文档${warningCount > 0 ? `,${warningCount} 条 warning` : ''}` : `校验未通过:${errorCount} 个 error(${entries.filter((entry)=>!entry.valid).length}/${entries.length} 份文档)`);
15608
+ }
15609
+ if (!ok) process.exitCode = errors_EXIT.INVALID;
15610
+ }
15611
+ function registerDocValidate(doc) {
15612
+ 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)=>{
15613
+ runDocValidate(options);
15614
+ });
15615
+ }
15616
+ const TEMPLATE_DIR = 'skills/iteration-task-docs/references';
15617
+ const STATUS_RULES = 'status-rules.md';
15618
+ const DETAIL_PREFIX = 'detail-fields-';
15619
+ const COMMON_BLOCKS = [
15620
+ 'iteration-fields',
15621
+ 'requirement-headers',
15622
+ 'task-headers',
15623
+ 'enums-requirement',
15624
+ 'enums-task',
15625
+ 'task-types'
15626
+ ];
15627
+ const OPTIONAL_BLOCKS = new Set([
15628
+ 'enums-table'
15629
+ ]);
15630
+ const KNOWN_BLOCKS = new Set([
15631
+ ...COMMON_BLOCKS,
15632
+ 'enums-table',
15633
+ 'enums-table-doc'
15634
+ ]);
15635
+ function enumDisplay(item) {
15636
+ return void 0 === item.display || 0 === item.display.length ? item.values.join('、') : item.display;
15637
+ }
15638
+ function templateFiles(schema) {
15639
+ return Object.keys(schema.roles).map((role)=>({
15640
+ role,
15641
+ file: `${role}.md`
15642
+ }));
15643
+ }
15644
+ function requiredBlocks(schema, role) {
15645
+ const scopes = schema.roles[role]?.scopeRequires ?? [];
15646
+ return [
15647
+ ...COMMON_BLOCKS,
15648
+ ...scopes.map((scope)=>`${DETAIL_PREFIX}${scope}`)
15649
+ ];
15650
+ }
15651
+ function blockBegin(name) {
15652
+ return `<!-- BEGIN GENERATED:${name} -->`;
15653
+ }
15654
+ function blockEnd(name) {
15655
+ return `<!-- END GENERATED:${name} -->`;
15656
+ }
15657
+ function findBlocks(text) {
15658
+ const names = [];
15659
+ const pattern = /<\x21-- BEGIN GENERATED:([^ ]+) --\x3e/g;
15660
+ let matched = pattern.exec(text);
15661
+ while(null !== matched){
15662
+ const name = matched[1] ?? '';
15663
+ if (name.length > 0 && !names.includes(name)) names.push(name);
15664
+ matched = pattern.exec(text);
15665
+ }
15666
+ return names;
15667
+ }
15668
+ function extractBlock(text, name) {
15669
+ const begin = blockBegin(name);
15670
+ const end = blockEnd(name);
15671
+ const start = text.indexOf(begin);
15672
+ if (start < 0) return null;
15673
+ const stop = text.indexOf(end, start + begin.length);
15674
+ if (stop < 0) return null;
15675
+ return text.slice(start + begin.length, stop).replace(/^\n+/, '').replace(/\n+$/, '');
15676
+ }
15677
+ function replaceBlock(text, name, body) {
15678
+ const begin = blockBegin(name);
15679
+ const end = blockEnd(name);
15680
+ const start = text.indexOf(begin);
15681
+ if (start < 0) return text;
15682
+ const stop = text.indexOf(end, start + begin.length);
15683
+ if (stop < 0) return text;
15684
+ return `${text.slice(0, start)}${begin}\n${body}\n${end}${text.slice(stop + end.length)}`;
15685
+ }
15686
+ function renderIterationFields(schema, role) {
15687
+ return schema.iterationFieldItems.map((item)=>{
15688
+ const value = 'scope' === item.key ? `<${role}>` : void 0 !== item.placeholder && item.placeholder.length > 0 ? item.placeholder : `<${item.label}>`;
15689
+ return `| ${item.label} | ${value} |`;
15690
+ }).join('\n');
15691
+ }
15692
+ function renderHeaders(headers) {
15693
+ return [
15694
+ `| ${headers.join(' | ')} |`,
15695
+ `| ${headers.map(()=>'---').join(' | ')} |`
15696
+ ].join('\n');
15697
+ }
15698
+ function renderDetailFields(schema, scope) {
15699
+ const role = roleOfScope(schema, scope);
15700
+ if (null === role) throw new errors_CliError(`schema.roles 中找不到所属端「${scope}」对应的角色`, errors_EXIT.INVALID);
15701
+ const decls = schema.roles[role]?.detailFieldItems ?? [];
15702
+ return decls.map((field)=>{
15703
+ const items = field.placeholderItems;
15704
+ if (void 0 !== items && items.length > 0) return [
15705
+ `- **${field.name}**:`,
15706
+ ...items.map((item)=>` - ${item}`)
15707
+ ].join('\n');
15708
+ const placeholder = void 0 !== field.placeholder && field.placeholder.length > 0 ? field.placeholder : '<待补充>';
15709
+ return `- **${field.name}**:${placeholder}`;
15710
+ }).join('\n');
15711
+ }
15712
+ function renderEnumsRequirement(schema) {
15713
+ const first = schema.enumItems[0];
15714
+ return void 0 === first ? '' : `- **${first.label}**:${enumDisplay(first)}`;
15715
+ }
15716
+ function renderEnumsTask(schema, role) {
15717
+ const wanted = new Set([
15718
+ 'selfTest',
15719
+ 'acceptance',
15720
+ 'taskStatus'
15721
+ ]);
15722
+ const lines = schema.enumItems.filter((item)=>wanted.has(item.key)).map((item)=>`- **${item.label}**:${enumDisplay(item)}`);
15723
+ lines.push(`- **任务类型**:${taskTypesOf(schema, role).join('、')}`);
15724
+ return lines.join('\n');
15725
+ }
15726
+ function renderEnumsTable(schema, role) {
15727
+ const lines = [
15728
+ '| 维度 | 允许值 |',
15729
+ '| --- | --- |'
15730
+ ];
15731
+ for (const item of schema.enumItems){
15732
+ const values = enumDisplay(item).split('、').map((value)=>`\`${value}\``).join('、');
15733
+ lines.push(`| ${item.label} | ${values} |`);
15734
+ }
15735
+ const types = taskTypesOf(schema, role).map((name)=>`\`${name}\``).join('、');
15736
+ lines.push(`| 任务类型 | ${types} |`);
15737
+ return lines.join('\n');
15738
+ }
15739
+ function renderEnumsTableDoc(schema) {
15740
+ const lines = [
15741
+ '| 维度 | 允许值 | 说明 |',
15742
+ '| --- | --- | --- |'
15743
+ ];
15744
+ for (const item of schema.enumItems){
15745
+ const source = void 0 === item.display || 0 === item.display.length ? item.values : enumDisplay(item).split('、');
15746
+ const cells = source.map((value)=>`\`${value}\``).join('、');
15747
+ lines.push(`| ${item.label} | ${cells} | ${item.desc} |`);
15748
+ }
15749
+ lines.push('| 任务类型 | 前端/后端各自枚举 | 见 `frontend.md`、`backend.md` |');
15750
+ return lines.join('\n');
15751
+ }
15752
+ function renderTaskTypes(schema, role) {
15753
+ if (void 0 === schema.roles[role]) throw new errors_CliError(`schema.roles 中缺少角色:${role}`, errors_EXIT.INVALID);
15754
+ const sideLabel = {
15755
+ both: '通用',
15756
+ frontend: '前端',
15757
+ backend: '后端'
15758
+ };
15759
+ const descriptions = new Map(schema.taskTypeItems.map((item)=>[
15760
+ item.name,
15761
+ item.desc
15762
+ ]));
15763
+ const names = [
15764
+ ...taskTypesOf(schema, role)
15765
+ ];
15766
+ names.sort((left, right)=>{
15767
+ const leftBoth = 'both' === sideOfTypeName(schema, left) ? 0 : 1;
15768
+ const rightBoth = 'both' === sideOfTypeName(schema, right) ? 0 : 1;
15769
+ return leftBoth - rightBoth;
15770
+ });
15771
+ const lines = [
15772
+ '| 类型 | 适用场景 | 归属 |',
15773
+ '| --- | --- | --- |'
15774
+ ];
15775
+ for (const name of names){
15776
+ const side = sideOfTypeName(schema, name);
15777
+ const label = null === side ? '' : sideLabel[side] ?? side;
15778
+ lines.push(`| \`${name}\` | ${descriptions.get(name) ?? ''} | ${label} |`);
15779
+ }
15780
+ return lines.join('\n');
15781
+ }
15782
+ function renderBlock(schema, name, role) {
15783
+ if (name.startsWith(DETAIL_PREFIX)) return renderDetailFields(schema, name.slice(DETAIL_PREFIX.length));
15784
+ switch(name){
15785
+ case 'iteration-fields':
15786
+ return renderIterationFields(schema, role);
15787
+ case 'requirement-headers':
15788
+ return renderHeaders(schema.requirementHeaders);
15789
+ case 'task-headers':
15790
+ return renderHeaders(schema.taskHeaders);
15791
+ case 'enums-requirement':
15792
+ return renderEnumsRequirement(schema);
15793
+ case 'enums-task':
15794
+ return renderEnumsTask(schema, role);
15795
+ case 'enums-table':
15796
+ return renderEnumsTable(schema, role);
15797
+ case 'enums-table-doc':
15798
+ return renderEnumsTableDoc(schema);
15799
+ case 'task-types':
15800
+ return renderTaskTypes(schema, role);
15801
+ default:
15802
+ throw new errors_CliError(`未知生成区:${name}(可用:${[
15803
+ ...KNOWN_BLOCKS
15804
+ ].join('、')} 或 ${DETAIL_PREFIX}<端>)`, errors_EXIT.INVALID);
15805
+ }
15806
+ }
15807
+ function templatePath(docsRoot, file) {
15808
+ return external_node_path_join(docsRoot, TEMPLATE_DIR, file);
15809
+ }
15810
+ function checkTemplates(docsRoot, schema) {
15811
+ const result = {
15812
+ problems: [],
15813
+ outdated: [],
15814
+ written: []
15815
+ };
15816
+ for (const { role, file } of templateFiles(schema)){
15817
+ const path = templatePath(docsRoot, file);
15818
+ if (!external_node_fs_existsSync(path)) {
15819
+ result.problems.push(`${file}:文件不存在(${path})`);
15820
+ continue;
15821
+ }
15822
+ const text = readTextFile(path).text;
15823
+ const headings = new Set(text.split(/\r?\n/).filter((line)=>line.startsWith('## ')).map((line)=>line.slice(3).trim()));
15824
+ for (const section of schema.sections)if (!headings.has(section)) result.problems.push(`${file}:缺少必需章节「${section}」`);
15825
+ const present = findBlocks(text);
15826
+ for (const block of requiredBlocks(schema, role))if (!present.includes(block)) result.problems.push(`${file}:缺少生成区「${block}」`);
15827
+ for (const block of present){
15828
+ const known = KNOWN_BLOCKS.has(block) || block.startsWith(DETAIL_PREFIX);
15829
+ if (!known) {
15830
+ result.problems.push(`${file}:未知生成区「${block}」(可用:${[
15831
+ ...KNOWN_BLOCKS
15832
+ ].join('、')} 或 ${DETAIL_PREFIX}<端>)`);
15833
+ continue;
15834
+ }
15835
+ if (OPTIONAL_BLOCKS.has(block) && !present.includes(block)) continue;
15836
+ let expected;
15837
+ try {
15838
+ expected = renderBlock(schema, block, role);
15839
+ } catch (error) {
15840
+ result.problems.push(`${file}:${block} 渲染失败(${error instanceof Error ? error.message : String(error)})`);
15841
+ continue;
15842
+ }
15843
+ const actual = extractBlock(text, block);
15844
+ if (null === actual) {
15845
+ result.problems.push(`${file}:生成区「${block}」缺少结束标记`);
15846
+ continue;
15847
+ }
15848
+ if (actual.trim() !== expected.trim()) result.outdated.push(`${file}#${block}`);
15849
+ }
15850
+ }
15851
+ const rulesPath = templatePath(docsRoot, STATUS_RULES);
15852
+ if (external_node_fs_existsSync(rulesPath)) {
15853
+ const text = readTextFile(rulesPath).text;
15854
+ const actual = extractBlock(text, 'enums-table-doc');
15855
+ if (null === actual) result.problems.push(`${STATUS_RULES}:缺少生成区「enums-table-doc」`);
15856
+ else if (actual.trim() !== renderBlock(schema, 'enums-table-doc', 'frontend').trim()) result.outdated.push(`${STATUS_RULES}#enums-table-doc`);
15857
+ }
15858
+ return result;
15859
+ }
15860
+ function writeTemplates(docsRoot, schema) {
15861
+ const result = {
15862
+ problems: [],
15863
+ outdated: [],
15864
+ written: []
15865
+ };
15866
+ const targets = [
15867
+ ...templateFiles(schema).map(({ role, file })=>({
15868
+ role,
15869
+ file
15870
+ })),
15871
+ {
15872
+ role: 'frontend',
15873
+ file: STATUS_RULES
15874
+ }
15875
+ ];
15876
+ for (const { role, file } of targets){
15877
+ const path = templatePath(docsRoot, file);
15878
+ if (!external_node_fs_existsSync(path)) {
15879
+ result.problems.push(`${file}:文件不存在(${path})`);
15880
+ continue;
15881
+ }
15882
+ const { text: original, eol } = readTextFile(path);
15883
+ const blocks = findBlocks(original);
15884
+ if (0 === blocks.length) {
15885
+ result.problems.push(`${file}:未找到任何生成区标记`);
15886
+ continue;
15887
+ }
15888
+ let updated = original;
15889
+ for (const block of blocks)try {
15890
+ updated = replaceBlock(updated, block, renderBlock(schema, block, role));
15891
+ } catch (error) {
15892
+ result.problems.push(`${file}:${block} 渲染失败(${error instanceof Error ? error.message : String(error)})`);
15893
+ }
15894
+ if (updated !== original) {
15895
+ result.written.push(file);
15896
+ writeTextFile({
15897
+ action: '重写模板生成区',
15898
+ target: path
15899
+ }, applyEol(updated, eol));
15900
+ }
15901
+ }
15902
+ return result;
15903
+ }
15904
+ function runDocTemplate(options) {
15905
+ const format = parseFormat(options.format);
15906
+ enableJsonErrors('json' === format);
15907
+ const loaded = config_loadConfig(options.config);
15908
+ if (!loaded.exists || null === loaded.config) throw new errors_CliError(`配置未初始化:${loaded.path}\n请先运行:ylcwf init`, errors_EXIT.NOT_FOUND);
15909
+ const baseLayout = layoutOf(loaded.config);
15910
+ const root = void 0 === options.docsRoot ? baseLayout.root : external_node_path_resolve(options.docsRoot);
15911
+ const schema = loadDocSchema(root);
15912
+ const write = true === options.write;
15913
+ const result = write ? writeTemplates(root, schema) : checkTemplates(root, schema);
15914
+ const ok = 0 === result.problems.length && (write || 0 === result.outdated.length);
15915
+ if ('json' === format) printJson({
15916
+ ok,
15917
+ mode: write ? 'write' : 'check',
15918
+ problems: result.problems,
15919
+ outdated: result.outdated,
15920
+ written: result.written
15921
+ });
15922
+ else if (result.problems.length > 0) {
15923
+ printLine('✗ 模板与 schema.json 不一致:');
15924
+ for (const problem of result.problems)printLine(` · ${problem}`);
15925
+ if (result.outdated.length > 0) {
15926
+ printLine('');
15927
+ printLine(` 生成区待刷新:${result.outdated.join('、')}`);
15928
+ printLine(' 执行 ylcwf doc template --write 重新生成');
15929
+ }
15930
+ } else if (write) printLine(0 === result.written.length ? '✓ 模板生成区已是 schema.json 的最新状态' : `✓ 已按 schema.json 重写:${result.written.join('、')}`);
15931
+ else if (result.outdated.length > 0) {
15932
+ printLine(`✗ 以下模板的生成区与 schema.json 不一致:${result.outdated.join('、')}`);
15933
+ printLine(' 执行 ylcwf doc template --write 重新生成');
15934
+ } else printLine('✓ 模板与 schema.json 一致(章节 + 生成区)');
15935
+ if (!ok) process.exitCode = errors_EXIT.INVALID;
15936
+ }
15937
+ function registerDocTemplate(doc) {
15938
+ 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)=>{
15939
+ if (true === options.check && true === options.write) throw new errors_CliError('--check 与 --write 只能选一个', errors_EXIT.USAGE);
15940
+ runDocTemplate(options);
15941
+ });
15942
+ }
15943
+ function doc_nowStamp() {
15944
+ const now = new Date();
15945
+ const pad = (value)=>String(value).padStart(2, '0');
15946
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
15947
+ }
15948
+ function readPlanFile(path) {
15949
+ if (!external_node_fs_existsSync(path)) throw new errors_CliError(`plan 文件不存在:${path}`, errors_EXIT.NOT_FOUND);
15950
+ const text = readFileSync(path, 'utf8');
15951
+ try {
15952
+ return JSON.parse(text);
15953
+ } catch (error) {
15954
+ throw new errors_CliError(`plan 文件不是合法 JSON:${error instanceof Error ? error.message : String(error)}`, errors_EXIT.INVALID);
15955
+ }
15956
+ }
15957
+ function runDocApply(options, mode = 'apply') {
15958
+ const format = parseFormat(options.format);
15959
+ const loaded = config_loadConfig(options.config);
15960
+ if (!loaded.exists || null === loaded.config) throw new errors_CliError(`配置未初始化:${loaded.path}\n请先运行:ylcwf init`, errors_EXIT.NOT_FOUND);
15961
+ const config = loaded.config;
15962
+ const docsRoot = config.docs.root;
15963
+ const layout = layoutOf(config);
15964
+ const developer = config.profile.developer;
15965
+ const role = config.profile.role;
15966
+ const requested = options.iteration.trim();
15967
+ if (0 === requested.length) throw new errors_CliError('必须指定迭代目录:--iteration <迭代>', errors_EXIT.USAGE);
15968
+ const resolvedIteration = requireIterationDir(docsRoot, layout.iterationsRoot, requested);
15969
+ const iteration = resolvedIteration.name;
15970
+ const schema = loadDocSchema(docsRoot);
15971
+ const plan = parseDocPlan(readPlanFile(options.input), schema, role);
15972
+ const targetDir = resolvedIteration.dir;
15973
+ const targetFile = external_node_path_join(targetDir, `${developer}.md`);
15974
+ const exists = external_node_fs_existsSync(targetFile);
15975
+ const existing = exists ? readTextFile(targetFile) : null;
15976
+ const original = null === existing ? null : existing.text;
15977
+ const eol = existing?.eol ?? '\n';
15978
+ const mtime = exists ? statSync(targetFile).mtimeMs : 0;
15979
+ const parsed = null === original ? {
15980
+ requirements: [],
15981
+ tasks: []
15982
+ } : parseMarkdownDoc(original, schema);
15983
+ if (null !== original) {
15984
+ const documentRole = inferRole(original);
15985
+ if (null === documentRole) process.stderr.write(`提示:${resolvedIteration.relPath}/${developer}.md 的「负责范围」是「${readRoleText(original) || '(缺失)'}」,不是 ${DOC_ROLE_HINT}。\n 写入后的校验会因此跳过;请先把该行改成 ${role}(你的 profile.role)。\n`);
15986
+ else if (documentRole !== role) process.stderr.write(`提示:${resolvedIteration.relPath}/${developer}.md 的负责范围是「${documentRole}」,与当前角色「${role}」不一致。\n 写入后的校验按文档为准(${documentRole});要让文档与本机角色一致,请手工修改「负责范围」为 ${role}。\n`);
15987
+ }
15988
+ validatePlanReferences({
15989
+ plan,
15990
+ schema,
15991
+ role,
15992
+ index: buildRepoSideIndex(config.terminals),
15993
+ knownTaskIds: parsed.tasks.map((task)=>task.id),
15994
+ knownRequirements: parsed.requirements.map((item)=>item.id)
15995
+ });
15996
+ const stamp = doc_nowStamp();
15997
+ const rendered = renderPlan({
15998
+ schema,
15999
+ role,
16000
+ plan,
16001
+ existing: {
16002
+ requirements: parsed.requirements,
16003
+ tasks: parsed.tasks,
16004
+ lines: null === original ? null : original.split('\n')
16005
+ },
16006
+ stamp,
16007
+ developer,
16008
+ aggregate: aggregateRequirement
16009
+ });
16010
+ const sideIndex = buildRepoSideIndex(config.terminals);
16011
+ const sideReport = validateTaskSides({
16012
+ index: sideIndex,
16013
+ tasks: rendered.assigned.map((item)=>{
16014
+ const planned = plan.tasks.find((task)=>task.name === item.name);
16015
+ return {
16016
+ id: item.id,
16017
+ scope: planned?.scope ?? '',
16018
+ terminal: planned?.terminal ?? ''
16019
+ };
16020
+ })
16021
+ });
16022
+ const conflicts = sideReport.issues.filter((issue)=>'error' === issue.level);
16023
+ if (conflicts.length > 0) throw new errors_CliError(`任务类型与执行终端归属不一致,已中止:\n${conflicts.map((issue)=>` · ${issue.message}`).join('\n')}`, errors_EXIT.INVALID);
16024
+ const sideSkippedNote = sideReport.skipped > 0 ? `本机执行终端配置未覆盖 ${sideReport.skipped} 个任务,其「所属端 vs 仓库」未校验` + (0 === Object.keys(config.terminals).length ? '(terminals 为空)' : '') : null;
16025
+ if (0 === rendered.assigned.length && rendered.markdown === original) {
16026
+ if ('json' === format) printJson({
16027
+ ok: true,
16028
+ changed: false,
16029
+ file: targetFile,
16030
+ changes: [],
16031
+ assigned: []
16032
+ });
16033
+ else printLine('计划中的需求与任务都已存在,未做修改');
16034
+ return;
16035
+ }
16036
+ if ('diff' === mode || true === options.dryRun) {
16037
+ if ('json' === format) printJson({
16038
+ ok: true,
16039
+ dryRun: true,
16040
+ mode,
16041
+ file: targetFile,
16042
+ changes: rendered.changes,
16043
+ assigned: rendered.assigned,
16044
+ preview: rendered.markdown
14889
16045
  });
14890
16046
  else {
14891
16047
  printLine(`将写入:${targetFile}`);
@@ -14900,17 +16056,30 @@ function runDocApply(options, mode = 'apply') {
14900
16056
  mkdirSync(targetDir, {
14901
16057
  recursive: true
14902
16058
  });
14903
- writeFileSync(targetFile, rendered.markdown, 'utf8');
16059
+ writeTextFile({
16060
+ action: '写入迭代任务文档',
16061
+ target: targetFile,
16062
+ others: [
16063
+ `${docsRoot}/.git`
16064
+ ]
16065
+ }, applyEol(rendered.markdown, eol));
14904
16066
  const outcome = validateAfterWrite(layout, iteration, developer);
14905
16067
  const rollback = (message)=>{
14906
16068
  if (null === original) unlinkSync(targetFile);
14907
- else writeFileSync(targetFile, original, 'utf8');
16069
+ else writeTextFile({
16070
+ action: '回滚迭代任务文档',
16071
+ target: targetFile
16072
+ }, applyEol(original, eol));
14908
16073
  throw new errors_CliError(message, errors_EXIT.INVALID);
14909
16074
  };
14910
- if ('violation' === outcome.kind) rollback(`写入被校验器拒绝,已回滚:${outcome.message}`);
16075
+ const strict = strictValidationEnabled();
16076
+ if ('violation' === outcome.kind) {
16077
+ if (strict) rollback(`写入未通过文档校验,已回滚:${outcome.message}`);
16078
+ process.stderr.write(`警告:写入未通过文档校验(docs.validator.strict=false):${outcome.message}\n`);
16079
+ }
14911
16080
  if ('unavailable' === outcome.kind) {
14912
- if (requireValidatorScript()) rollback(`未执行文档校验,已回滚:${outcome.reason}\n文档校验必须由文档仓库 scripts/validate_task_doc.py 裁决;如确需跳过(不推荐),可配置 docs.validator.requireScript: false`);
14913
- process.stderr.write(`警告:${outcome.reason};本次写入未做文档校验(docs.validator.requireScript=false)\n`);
16081
+ if (strict) rollback(`未执行文档校验,已回滚:${outcome.reason}\n如需在无法校验时仍写入(不推荐),可配置 docs.validator.strict: false`);
16082
+ process.stderr.write(`警告:${outcome.reason};本次写入未做文档校验(docs.validator.strict=false)\n`);
14914
16083
  }
14915
16084
  const remainingReport = checkDocTaskSides({
14916
16085
  docsRoot,
@@ -14947,6 +16116,59 @@ function runDocApply(options, mode = 'apply') {
14947
16116
  if (void 0 !== git) printLine(`\n${git.message}`);
14948
16117
  }
14949
16118
  }
16119
+ const FALLBACK_TASK_STATES = [
16120
+ '未开始',
16121
+ '进行中',
16122
+ '待验收',
16123
+ '已完成'
16124
+ ];
16125
+ function readStdin() {
16126
+ if (true === process.stdin.isTTY) return '';
16127
+ try {
16128
+ return readFileSync(0, 'utf8');
16129
+ } catch {
16130
+ return '';
16131
+ }
16132
+ }
16133
+ function loadTaskStates(configPath) {
16134
+ try {
16135
+ const loaded = config_loadConfig(configPath);
16136
+ if (null === loaded.config) return FALLBACK_TASK_STATES;
16137
+ const root = loaded.config.docs.root.trim();
16138
+ if (0 === root.length) return FALLBACK_TASK_STATES;
16139
+ const values = loadDocSchema(root).enums.taskStatus;
16140
+ return values.length > 0 ? values : FALLBACK_TASK_STATES;
16141
+ } catch {
16142
+ return FALLBACK_TASK_STATES;
16143
+ }
16144
+ }
16145
+ function runDocAggregate(options) {
16146
+ const format = parseFormat(options.format);
16147
+ enableJsonErrors('json' === format);
16148
+ const raw = void 0 === options.input ? readStdin() : readFileSync(options.input, 'utf8');
16149
+ let input;
16150
+ try {
16151
+ input = 0 === raw.trim().length ? {} : JSON.parse(raw);
16152
+ } catch (error) {
16153
+ throw new errors_CliError(`入参不是合法 JSON:${error instanceof Error ? error.message : String(error)}`, errors_EXIT.USAGE);
16154
+ }
16155
+ if (!utils_isRecord(input)) throw new errors_CliError('入参需为 { 需求编号: [任务状态...] } 对象', errors_EXIT.USAGE);
16156
+ const allowed = loadTaskStates(options.config);
16157
+ const data = {};
16158
+ for (const [requirementId, statuses] of Object.entries(input)){
16159
+ if (!isStringArray(statuses)) throw new errors_CliError(`需求 ${requirementId} 的任务状态需为字符串数组`, errors_EXIT.USAGE);
16160
+ const unknown = statuses.filter((item)=>!allowed.includes(item));
16161
+ if (unknown.length > 0) throw new errors_CliError(`需求 ${requirementId} 含非法任务状态:${unknown.join('、')}(允许:${allowed.join('、')})`, errors_EXIT.USAGE);
16162
+ data[requirementId] = aggregateRequirement(statuses);
16163
+ }
16164
+ if ('json' === format) return void printJson({
16165
+ ok: true,
16166
+ data
16167
+ });
16168
+ const entries = Object.entries(data);
16169
+ if (0 === entries.length) return void printLine('入参为空,未计算任何需求');
16170
+ for (const [requirementId, item] of entries)printLine(`${requirementId} ${item.status} ${item.progress}%`);
16171
+ }
14950
16172
  function registerDoc(program) {
14951
16173
  const doc = program.command('doc').description('按结构化计划生成/追加迭代任务文档');
14952
16174
  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)=>{
@@ -14955,6 +16177,11 @@ function registerDoc(program) {
14955
16177
  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)=>{
14956
16178
  runDocApply(options);
14957
16179
  });
16180
+ doc.command('aggregate').description('按任务状态聚合需求状态与进度(stdin 传 { 需求编号: [任务状态] })').option('--input <path>', '从文件读取入参(省略时读 stdin)').option('-c, --config <path>', '指定配置文件路径(用于读取任务状态枚举)').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
16181
+ runDocAggregate(options);
16182
+ });
16183
+ registerDocValidate(doc);
16184
+ registerDocTemplate(doc);
14958
16185
  registerDocMigrate(doc);
14959
16186
  }
14960
16187
  function resolveDeveloper(options, configured) {
@@ -14967,10 +16194,7 @@ function requireWriteContext(options) {
14967
16194
  const ready = requireConfig(options.config);
14968
16195
  const config = ready.config;
14969
16196
  if (0 === config.docs.root.trim().length) throw new errors_CliError('未配置文档仓库:请先设置 docs.root', errors_EXIT.NOT_FOUND);
14970
- const base = config.docs.git?.cli ?? {
14971
- commit: true,
14972
- push: false
14973
- };
16197
+ const base = config.docs.git?.cli ?? DEFAULT_GIT_POLICY;
14974
16198
  const policy = {
14975
16199
  commit: options.commit ?? base.commit,
14976
16200
  push: options.push ?? base.push
@@ -15286,6 +16510,7 @@ function runAction(action, taskId, options) {
15286
16510
  for (const change of result.changes)printLine(` · ${change}`);
15287
16511
  printLine(`文档:${result.file}`);
15288
16512
  if (void 0 !== result.git) printLine(`git:${result.git.message}`);
16513
+ for (const warning of result.warnings ?? [])printLine(`⚠ ${warning}`);
15289
16514
  if (sideIssues.length > 0) {
15290
16515
  printLine('\n注意:该文档存在任务类型与执行终端归属不一致(可用 ylcwf doctor --docs 复查):');
15291
16516
  for (const message of sideIssues)printLine(` · ${message}`);
@@ -15335,6 +16560,7 @@ function runDetail(taskId, options) {
15335
16560
  for (const change of applied.changes)printLine(` · ${change}`);
15336
16561
  printLine(`文档:${applied.file}`);
15337
16562
  if (void 0 !== applied.git) printLine(`git:${applied.git.message}`);
16563
+ for (const warning of applied.warnings ?? [])printLine(`⚠ ${warning}`);
15338
16564
  }
15339
16565
  function runSelfTest(taskId, options) {
15340
16566
  const { docsRoot, layout, developer, policy } = requireWriteContext(options);
@@ -15361,6 +16587,7 @@ function runSelfTest(taskId, options) {
15361
16587
  for (const change of applied.changes)printLine(` · ${change}`);
15362
16588
  printLine(`文档:${applied.file}`);
15363
16589
  if (void 0 !== applied.git) printLine(`git:${applied.git.message}`);
16590
+ for (const warning of applied.warnings ?? [])printLine(`⚠ ${warning}`);
15364
16591
  }
15365
16592
  function runActions(options) {
15366
16593
  const { docsRoot, layout, developer } = requireWriteContext(options);
@@ -15401,6 +16628,7 @@ function runBatch(action, taskIds, options) {
15401
16628
  printLine(result.message);
15402
16629
  for (const change of result.changes)printLine(` · ${change}`);
15403
16630
  if (void 0 !== result.git) printLine(`git:${result.git.message}`);
16631
+ for (const warning of result.warnings ?? [])printLine(`⚠ ${warning}`);
15404
16632
  }
15405
16633
  function runHistory(taskId, options) {
15406
16634
  const { layout, developer } = requireWriteContext(options);
@@ -15612,18 +16840,21 @@ function iteration_runShow(name, options) {
15612
16840
  function runCurrent(options) {
15613
16841
  const format = parseFormat(options.format);
15614
16842
  const ctx = requireQueryContext(options);
15615
- const iterations = loadIterations(ctx.layout).map((item)=>item.name);
15616
- const result = resolveIterationFromBranch(ctx.docsRoot, iterations);
16843
+ const result = readCurrentIteration(ctx.layout);
16844
+ if (!result.accessible) throw new errors_CliError(result.reason ?? '无法读取文档仓库', errors_EXIT.NOT_FOUND);
16845
+ const available = result.available.map((item)=>item.name);
15617
16846
  if ('json' === format) return void printJson({
15618
16847
  ok: true,
15619
- ...result,
15620
- available: iterations
16848
+ branch: result.branch,
16849
+ iteration: result.iteration,
16850
+ candidates: result.candidates,
16851
+ available
15621
16852
  });
15622
16853
  printLine(`分支:${result.branch ?? '(detached HEAD)'}`);
15623
16854
  if (null !== result.iteration) return void printLine(`迭代:${result.iteration}`);
15624
16855
  if (result.candidates.length > 0) return void printLine(`分支名同时匹配多个迭代,请显式指定 -i:${result.candidates.join('、')}`);
15625
16856
  printLine('迭代:未从分支名识别出迭代目录');
15626
- if (iterations.length > 0) printLine(`可用迭代:${iterations.join('、')}`);
16857
+ if (available.length > 0) printLine(`可用迭代:${available.join('、')}`);
15627
16858
  }
15628
16859
  function runCreate(name, options) {
15629
16860
  const ctx = requireQueryContext(options);
@@ -15667,8 +16898,21 @@ function runContext(options) {
15667
16898
  const tasks = buildTaskRows(selected);
15668
16899
  const completedTasks = tasks.filter((task)=>'已完成' === task.status).length;
15669
16900
  const info = selected[0]?.doc.validation.iterationInfo ?? {};
16901
+ const errors = selected.flatMap((item)=>item.doc.validation.errors);
16902
+ const warnings = selected.flatMap((item)=>item.doc.validation.warnings);
16903
+ const readyTasks = tasks.filter((task)=>task.ready).map((task)=>task.id);
16904
+ const blockedTasks = tasks.filter((task)=>!task.ready && '已完成' !== task.status).map((task)=>({
16905
+ id: task.id,
16906
+ blockedBy: task.blockedBy.map((dep)=>dep.id)
16907
+ }));
16908
+ const targetId = options.task?.trim() ?? '';
16909
+ const targetTask = targetId.length > 0 ? tasks.find((task)=>task.id === targetId) ?? null : null;
16910
+ if (targetId.length > 0 && null === targetTask) throw new errors_CliError(`任务 ${targetId} 不在迭代 ${iteration} 的文档范围内(当前成员范围:${developerFilter ?? '全部成员'})`, errors_EXIT.NOT_FOUND);
16911
+ const relPath = iterations.find((item)=>item.name === iteration)?.relPath ?? iteration;
15670
16912
  const payload = {
16913
+ ok: 0 === errors.length,
15671
16914
  iteration,
16915
+ relPath,
15672
16916
  developer: developerFilter ?? '全部成员',
15673
16917
  info,
15674
16918
  totals: {
@@ -15679,12 +16923,11 @@ function runContext(options) {
15679
16923
  },
15680
16924
  requirements,
15681
16925
  tasks,
15682
- ready: tasks.filter((task)=>task.ready).map((task)=>task.id),
15683
- blocked: tasks.filter((task)=>!task.ready && '已完成' !== task.status).map((task)=>({
15684
- id: task.id,
15685
- blockedBy: task.blockedBy.map((dep)=>dep.id)
15686
- })),
15687
- issues: selected.flatMap((item)=>item.doc.validation.errors)
16926
+ readyTasks,
16927
+ blockedTasks,
16928
+ targetTask,
16929
+ errors,
16930
+ warnings
15688
16931
  };
15689
16932
  if ('json' === ctx.format) return void printJson(payload);
15690
16933
  printLine(`迭代:${iteration} 开发者:${payload.developer}`);
@@ -15694,45 +16937,235 @@ function runContext(options) {
15694
16937
  for (const item of requirements)printLine(`- ${item.id} ${item.title} ${item.status} ${item.progress}%`);
15695
16938
  printLine('任务清单:');
15696
16939
  for (const task of tasks)printLine(`- ${task.id} [${task.type}] ${task.name} ${task.status} 自测:${task.selfTest} 验收:${task.acceptance}`);
15697
- printLine(`当前可执行任务:${0 === payload.ready.length ? '无' : payload.ready.join('、')}`);
15698
- for (const item of payload.blocked)printLine(` 阻塞:${item.id} 等待 ${item.blockedBy.join('、')}`);
16940
+ printLine(`当前可执行任务:${0 === payload.readyTasks.length ? '无' : payload.readyTasks.join('、')}`);
16941
+ for (const item of payload.blockedTasks)printLine(` 阻塞:${item.id} 等待 ${item.blockedBy.join('、')}`);
16942
+ if (null !== payload.targetTask) printLine(`目标:${payload.targetTask.id} ${payload.targetTask.name} ${payload.targetTask.status}`);
16943
+ if (payload.errors.length > 0) {
16944
+ printLine(`校验问题(${payload.errors.length}):`);
16945
+ for (const issue of payload.errors)printLine(` [error] ${issue.code}:${issue.message}`);
16946
+ }
15699
16947
  }
15700
16948
  function registerContext(program) {
15701
16949
  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));
15702
16950
  }
15703
- function collectRequirements(layout, iteration, developer) {
15704
- const docs = loadDeveloperDocs(layout, iteration);
15705
- const filtered = void 0 === developer ? docs : docs.filter((item)=>item.developer === developer);
15706
- if (0 === filtered.length) throw new errors_CliError(`迭代 ${iteration} 中没有成员文档${void 0 === developer ? '' : `(${developer})`}`, errors_EXIT.NOT_FOUND);
15707
- const map = new Map();
15708
- for (const { developer: owner, doc } of filtered)for (const requirement of doc.validation.requirements){
15709
- const entry = map.get(requirement.id) ?? {
15710
- id: requirement.id,
15711
- title: requirement.title,
15712
- terminal: requirement.terminal,
15713
- status: requirement.status,
15714
- progress: requirement.progress,
15715
- note: requirement.note,
15716
- updatedAt: requirement.updatedAt,
15717
- developers: [],
15718
- taskIds: []
15719
- };
15720
- entry.developers.push(owner);
15721
- entry.taskIds.push(...requirement.taskIds);
15722
- map.set(requirement.id, entry);
16951
+ const MODES = {
16952
+ plan: '计划分析',
16953
+ exec: '实施需求'
16954
+ };
16955
+ const guide_TEMPLATE_DIR = 'skills/iteration-task-docs/references';
16956
+ function parseMode(value) {
16957
+ const mode = (value ?? '').trim();
16958
+ if ('plan' === mode || 'exec' === mode) return mode;
16959
+ throw new errors_CliError(`--mode 只能是 plan 或 exec:${mode.length > 0 ? mode : '(未指定)'}`, errors_EXIT.USAGE);
16960
+ }
16961
+ function collectBlocking(input) {
16962
+ const blocking = [];
16963
+ const byId = new Map(input.tasks.map((task)=>[
16964
+ task.id,
16965
+ task
16966
+ ]));
16967
+ const target = input.targetTaskId.length > 0 ? byId.get(input.targetTaskId) : void 0;
16968
+ if (input.targetTaskId.length > 0 && void 0 === target) blocking.push(`任务 ${input.targetTaskId} 不在任务清单中`);
16969
+ if (void 0 !== target) for (const dependency of target.dependencies){
16970
+ const dependencyTask = byId.get(dependency);
16971
+ if (void 0 === dependencyTask) blocking.push(`前置任务 ${dependency} 不存在`);
16972
+ else if ('已完成' !== dependencyTask.status) blocking.push(`前置任务 ${dependency} 状态为「${dependencyTask.status}」,未完成`);
16973
+ }
16974
+ if (input.requirementId.length > 0) {
16975
+ const matched = input.tasks.some((task)=>task.requirementId === input.requirementId);
16976
+ if (!matched) blocking.push(`需求 ${input.requirementId} 在任务清单中没有对应任务`);
15723
16977
  }
16978
+ for (const issue of input.errors)blocking.push(`${issue.code}:${issue.message}`);
16979
+ return blocking;
16980
+ }
16981
+ function planningActions(options) {
15724
16982
  return [
15725
- ...map.values()
15726
- ].sort((left, right)=>left.id.localeCompare(right.id));
16983
+ '确认文档仓库路径、开发者标识与角色(三者缺失时必须先询问开发者,禁止猜测)',
16984
+ `用 dws 拉取 PRD 并生成快照:${options.prdBaseline}(先探测 updateTime,未变化不会重拉全文)`,
16985
+ "从 PRD 标题提取迭代目录名(PRD_ 后到 】 前);目录不存在时用 ylcwf iteration create <年份>/<名称>(必须由开发者确认年份)",
16986
+ '按 PRD 需求清单筛选本次负责需求;执行终端列写执行终端名,不得写迭代目录名',
16987
+ "逐需求拆解任务:编号 <需求>-Tn、类型、执行终端、前置依赖、核心文件清单、实现方案、自测方式、历史功能影响范围",
16988
+ `生成个人文档:ylcwf doc apply -i ${options.iteration} --input plan.json(模板见 ${options.templatePath},角色 ${options.role})`,
16989
+ `落盘后依次运行 ylcwf doc validate -i ${options.iteration} -d ${options.developer} 与 ylcwf context -i ${options.iteration} -d ${options.developer},确认无 error 再汇报`
16990
+ ];
15727
16991
  }
15728
- function requirement_runList(options) {
15729
- const ctx = requireQueryContext(options);
15730
- const iteration = resolveIterationName(options, ctx.layout, loadIterations(ctx.layout));
15731
- const requirements = collectRequirements(ctx.layout, iteration, options.developer?.trim() || void 0);
15732
- if ('json' === ctx.format) return void printJson({
15733
- iteration,
15734
- requirements
15735
- });
16992
+ function executionActions(options) {
16993
+ return [
16994
+ `确认目标任务编号、关联需求、执行终端与核心文件清单(${options.contextCommand})`,
16995
+ '按执行终端查全局提示词映射表得到本地仓库路径;表中缺失该终端时必须询问开发者',
16996
+ `开始编码前确认 PRD 无未处理变更:${options.prdDelta}`,
16997
+ '仅修改该任务核心文件清单范围内的文件,超出范围先向开发者说明',
16998
+ '完成实现后执行详情中声明的自测命令,并把真实输出写入「自测证据」',
16999
+ `自测通过后把任务置为待验收(严禁直接置为已完成):ylcwf task submit <任务编号> -i ${options.iteration}`,
17000
+ '人工验收通过后,由开发者确认再把任务置为已完成:ylcwf task accept <任务编号>',
17001
+ `每次回写后运行 ylcwf doc validate -i ${options.iteration} -d ${options.developer},确认无 error`
17002
+ ];
17003
+ }
17004
+ function schemaNotes(schema) {
17005
+ return [
17006
+ `状态流转唯一允许路径:${schema.enums.taskStatus.join(' → ')}`,
17007
+ `需求开发状态取值:${schema.enums.requirementStatus.join(' / ')}(由关联任务状态聚合得出,禁止手写与任务不一致的值)`,
17008
+ `AI 自测状态取值:${schema.enums.selfTest.join(' / ')}(免测必须带括号理由)`,
17009
+ `开发人工验收取值:${schema.enums.acceptance.join(' / ')}(只有「验收通过」才允许任务置为已完成)`
17010
+ ];
17011
+ }
17012
+ function runGuide(options) {
17013
+ const format = parseFormat(options.format);
17014
+ enableJsonErrors('json' === format);
17015
+ const mode = parseMode(options.mode);
17016
+ const ctx = requireQueryContext(options);
17017
+ const iterations = loadIterations(ctx.layout);
17018
+ const requirementId = (options.requirement ?? '').trim();
17019
+ const taskId = (options.task ?? '').trim();
17020
+ const iteration = resolveIterationName(options, ctx.layout, iterations, {
17021
+ taskId: taskId.length > 0 ? taskId : void 0,
17022
+ requirementId: requirementId.length > 0 ? requirementId : void 0
17023
+ });
17024
+ const docs = loadDeveloperDocs(ctx.layout, iteration);
17025
+ const developerFilter = true === options.all ? void 0 : options.developer?.trim() || ctx.developer;
17026
+ const selected = filterDocs(docs, developerFilter);
17027
+ if (0 === selected.length) throw new errors_CliError(`迭代 ${iteration} 中没有成员文档(${developerFilter ?? '全部成员'})`, errors_EXIT.NOT_FOUND);
17028
+ const schema = loadDocSchema(ctx.layout.root);
17029
+ const role = ctx.config.profile.role;
17030
+ if (void 0 === schema.roles[role]) throw new errors_CliError(`配置里的角色「${role}」不在文档仓库 schema.roles 中(可用:${Object.keys(schema.roles).join(' / ')})`, errors_EXIT.INVALID);
17031
+ const tasks = buildTaskRows(selected);
17032
+ const errors = selected.flatMap((item)=>item.doc.validation.errors);
17033
+ const warnings = selected.flatMap((item)=>item.doc.validation.warnings);
17034
+ const developer = developerFilter ?? ctx.developer;
17035
+ const relPath = iterations.find((item)=>item.name === iteration)?.relPath ?? iteration;
17036
+ const contextCommand = taskId.length > 0 ? `ylcwf context -i ${iteration} --task ${taskId}` : `ylcwf context -i ${iteration} -d ${developer}`;
17037
+ const prdDelta = `ylcwf prd delta -i ${iteration}` + (requirementId.length > 0 ? ` --requirement ${requirementId}` : '');
17038
+ const prdBaseline = `ylcwf prd baseline -i ${iteration} --node <PRD 链接>`;
17039
+ const blocking = 'exec' === mode ? collectBlocking({
17040
+ tasks,
17041
+ targetTaskId: taskId,
17042
+ requirementId,
17043
+ errors
17044
+ }) : [];
17045
+ const targetTask = taskId.length > 0 ? tasks.find((task)=>task.id === taskId) ?? null : null;
17046
+ const payload = {
17047
+ ok: 0 === errors.length,
17048
+ mode,
17049
+ modeName: MODES[mode],
17050
+ iteration,
17051
+ relPath,
17052
+ role,
17053
+ developer,
17054
+ requirement: requirementId.length > 0 ? requirementId : null,
17055
+ task: taskId.length > 0 ? taskId : null,
17056
+ allowed: 0 === blocking.length,
17057
+ validation: {
17058
+ ok: 0 === errors.length,
17059
+ errors: errors.length,
17060
+ warnings: warnings.length,
17061
+ issues: [
17062
+ ...errors,
17063
+ ...warnings
17064
+ ]
17065
+ },
17066
+ targetTask,
17067
+ requiredActions: 'plan' === mode ? planningActions({
17068
+ role,
17069
+ templatePath: `<文档仓库>/${guide_TEMPLATE_DIR}/${role}.md`,
17070
+ iteration,
17071
+ developer,
17072
+ prdBaseline
17073
+ }) : executionActions({
17074
+ iteration,
17075
+ developer,
17076
+ contextCommand,
17077
+ prdDelta
17078
+ }),
17079
+ forbiddenActions: 'plan' === mode ? [
17080
+ '未确认迭代目录名之前不得新建迭代目录',
17081
+ '不得把 AI 推断的需求名称、验收标准或终端归属写成 PRD 事实',
17082
+ '不得修改其他开发者的 md 文件或仓库 README / AGENTS',
17083
+ 'PRD 拉取失败时不得补造需求,必须停止并请求授权',
17084
+ '不得自动 git add / commit / push'
17085
+ ] : [
17086
+ 'AI 自测未通过时不得把任务标记为待验收或已完成',
17087
+ '开发人工验收未通过时不得把任务标记为已完成',
17088
+ '前置依赖未完成时不得开始当前任务',
17089
+ '不得跨任务大包干一次性交付,必须单任务步进并等待开发者确认',
17090
+ '不得把未执行的测试写成通过,不得伪造自测证据',
17091
+ '不得自动 git add / commit / push'
17092
+ ],
17093
+ nextCommands: 'plan' === mode ? [
17094
+ `ylcwf doc validate -i ${iteration} -d ${developer}`,
17095
+ contextCommand
17096
+ ] : [
17097
+ contextCommand,
17098
+ `ylcwf doc validate -i ${iteration} -d ${developer}`,
17099
+ prdDelta
17100
+ ],
17101
+ notes: [
17102
+ ...schemaNotes(schema),
17103
+ ...blocking.map((item)=>`阻断原因:${item}`)
17104
+ ]
17105
+ };
17106
+ if ('json' === ctx.format) return void printJson(payload);
17107
+ printLine(`模式:${payload.modeName} 迭代:${payload.relPath} 角色:${payload.role}`);
17108
+ printLine(`开发者:${payload.developer} 需求:${payload.requirement ?? '—'} 任务:${payload.task ?? '—'} 允许推进:${payload.allowed ? '是' : '否'}`);
17109
+ printLine(`校验:${errors.length} error / ${warnings.length} warning`);
17110
+ if (blocking.length > 0) {
17111
+ printLine('');
17112
+ printLine('阻断原因:');
17113
+ for (const item of blocking)printLine(` · ${item}`);
17114
+ }
17115
+ printLine('');
17116
+ printLine('必做:');
17117
+ payload.requiredActions.forEach((item, index)=>printLine(` ${index + 1}. ${item}`));
17118
+ printLine('禁止:');
17119
+ for (const item of payload.forbiddenActions)printLine(` · ${item}`);
17120
+ printLine('');
17121
+ printLine('下一步命令:');
17122
+ for (const item of payload.nextCommands)printLine(` · ${item}`);
17123
+ printLine('');
17124
+ printLine('口径说明:');
17125
+ for (const item of schemaNotes(schema))printLine(` · ${item}`);
17126
+ if (null !== payload.targetTask) {
17127
+ printLine('');
17128
+ printLine(`目标任务:${payload.targetTask.id} ${payload.targetTask.name} ${payload.targetTask.status} 自测 ${payload.targetTask.selfTest} 验收 ${payload.targetTask.acceptance}`);
17129
+ }
17130
+ }
17131
+ function registerGuide(program) {
17132
+ 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)=>{
17133
+ runGuide(options);
17134
+ });
17135
+ }
17136
+ function collectRequirements(layout, iteration, developer) {
17137
+ const docs = loadDeveloperDocs(layout, iteration);
17138
+ const filtered = void 0 === developer ? docs : docs.filter((item)=>item.developer === developer);
17139
+ if (0 === filtered.length) throw new errors_CliError(`迭代 ${iteration} 中没有成员文档${void 0 === developer ? '' : `(${developer})`}`, errors_EXIT.NOT_FOUND);
17140
+ const map = new Map();
17141
+ for (const { developer: owner, doc } of filtered)for (const requirement of doc.validation.requirements){
17142
+ const entry = map.get(requirement.id) ?? {
17143
+ id: requirement.id,
17144
+ title: requirement.title,
17145
+ terminal: requirement.terminal,
17146
+ status: requirement.status,
17147
+ progress: requirement.progress,
17148
+ note: requirement.note,
17149
+ updatedAt: requirement.updatedAt,
17150
+ developers: [],
17151
+ taskIds: []
17152
+ };
17153
+ entry.developers.push(owner);
17154
+ entry.taskIds.push(...requirement.taskIds);
17155
+ map.set(requirement.id, entry);
17156
+ }
17157
+ return [
17158
+ ...map.values()
17159
+ ].sort((left, right)=>left.id.localeCompare(right.id));
17160
+ }
17161
+ function requirement_runList(options) {
17162
+ const ctx = requireQueryContext(options);
17163
+ const iteration = resolveIterationName(options, ctx.layout, loadIterations(ctx.layout));
17164
+ const requirements = collectRequirements(ctx.layout, iteration, options.developer?.trim() || void 0);
17165
+ if ('json' === ctx.format) return void printJson({
17166
+ iteration,
17167
+ requirements
17168
+ });
15736
17169
  if (0 === requirements.length) return void printLine(`迭代 ${iteration} 没有需求`);
15737
17170
  const rows = requirements.map((item)=>[
15738
17171
  item.id,
@@ -15878,9 +17311,9 @@ async function fetchManifest(url) {
15878
17311
  const payload = await response.json();
15879
17312
  if ('string' != typeof payload.version || 0 === payload.version.length) return null;
15880
17313
  return {
15881
- current: "0.7.0",
17314
+ current: "0.9.0",
15882
17315
  latest: payload.version,
15883
- hasUpdate: isNewer(payload.version, "0.7.0"),
17316
+ hasUpdate: isNewer(payload.version, "0.9.0"),
15884
17317
  downloadUrl: 'string' == typeof payload.downloadUrl ? payload.downloadUrl : null,
15885
17318
  source: 'manifest',
15886
17319
  checkedAt: new Date().toISOString(),
@@ -15892,7 +17325,7 @@ async function fetchManifest(url) {
15892
17325
  }
15893
17326
  async function fetchNpm() {
15894
17327
  const base = {
15895
- current: "0.7.0",
17328
+ current: "0.9.0",
15896
17329
  latest: null,
15897
17330
  hasUpdate: false,
15898
17331
  downloadUrl: null,
@@ -15919,7 +17352,7 @@ async function fetchNpm() {
15919
17352
  return {
15920
17353
  ...base,
15921
17354
  latest,
15922
- hasUpdate: isNewer(latest, "0.7.0"),
17355
+ hasUpdate: isNewer(latest, "0.9.0"),
15923
17356
  downloadUrl: null
15924
17357
  };
15925
17358
  } catch (error) {
@@ -15961,10 +17394,26 @@ function classifyInstallPaths(input) {
15961
17394
  if (/\/\.pnpm\/ylcwf@/.test(normalized) || /\/pnpm\/global\/\d+\//.test(normalized)) return 'pnpm-global';
15962
17395
  if (/\/npm\/node_modules\/ylcwf(\/|$)/.test(normalized)) return 'npm-global';
15963
17396
  }
17397
+ if (null !== input.miseInstallsRoot) {
17398
+ for (const path of paths)if (isInside(path, input.miseInstallsRoot)) return 'mise';
17399
+ }
17400
+ for (const path of paths)if (/\/mise[^/]*\/installs\/[^/]*ylcwf[^/]*\//.test(normalizePathForCompare(path))) return 'mise';
15964
17401
  for (const path of paths)if (isInside(path, input.scriptRoot)) return "script";
15965
17402
  for (const path of paths)if (isInside(path, input.sourceRoot)) return 'source';
15966
17403
  return 'unknown';
15967
17404
  }
17405
+ function miseInstallsRoot() {
17406
+ const candidates = [];
17407
+ const dataDir = process.env['MISE_DATA_DIR']?.trim();
17408
+ if (void 0 !== dataDir && dataDir.length > 0) candidates.push(external_node_path_join(dataDir, 'installs'));
17409
+ const localAppData = process.env['LOCALAPPDATA']?.trim();
17410
+ if (void 0 !== localAppData && localAppData.length > 0) candidates.push(external_node_path_join(localAppData, 'mise', 'installs'));
17411
+ candidates.push(external_node_path_join(homedir(), '.local', 'share', 'mise', 'installs'));
17412
+ candidates.push(external_node_path_join(homedir(), 'Library', 'Application Support', 'mise', 'installs'));
17413
+ candidates.push(external_node_path_join(homedir(), 'AppData', 'Local', 'mise', 'installs'));
17414
+ for (const candidate of candidates)if (external_node_fs_existsSync(candidate)) return candidate;
17415
+ return null;
17416
+ }
15968
17417
  function scriptInstallRoot() {
15969
17418
  if ('win32' === process.platform) {
15970
17419
  const localAppData = process.env['LOCALAPPDATA']?.trim() ?? external_node_path_join(homedir(), 'AppData', 'Local');
@@ -16047,6 +17496,7 @@ function detectInstallKind() {
16047
17496
  'root',
16048
17497
  '-g'
16049
17498
  ]),
17499
+ miseInstallsRoot: miseInstallsRoot(),
16050
17500
  scriptRoot: scriptInstallRoot(),
16051
17501
  sourceRoot: sourceRootOf(packageRoot)
16052
17502
  });
@@ -16057,6 +17507,8 @@ function installKindLabel(kind) {
16057
17507
  return 'npm 全局安装';
16058
17508
  case 'pnpm-global':
16059
17509
  return 'pnpm 全局安装';
17510
+ case 'mise':
17511
+ return 'mise 安装';
16060
17512
  case "script":
16061
17513
  return '安装脚本安装';
16062
17514
  case 'source':
@@ -16107,7 +17559,7 @@ async function runUpgrade(options) {
16107
17559
  const kind = detectInstallKind();
16108
17560
  const result = await checkUpdate(true);
16109
17561
  const target = void 0 === options.to ? result.latest : assertVersion(options.to.trim());
16110
- printLine("当前版本:0.7.0");
17562
+ printLine("当前版本:0.9.0");
16111
17563
  printLine(`安装方式:${installKindLabel(kind)}`);
16112
17564
  if (null !== result.error) printLine(`版本查询失败:${result.error}`);
16113
17565
  else if (null !== result.latest) printLine(`最新版本:${result.latest}(来源:${result.source})`);
@@ -16130,6 +17582,14 @@ async function runUpgrade(options) {
16130
17582
  ];
16131
17583
  printLine(`执行:npm ${args.join(' ')}`);
16132
17584
  if (!dryRun) runOrFail('npm', args, `npm install -g ylcwf@${target}`);
17585
+ } else if ('mise' === kind) {
17586
+ const args = [
17587
+ 'upgrade',
17588
+ 'npm:ylcwf',
17589
+ '--bump'
17590
+ ];
17591
+ printLine(`执行:mise ${args.join(' ')}`);
17592
+ if (!dryRun) runOrFail('mise', args, "mise upgrade npm:ylcwf --bump");
16133
17593
  } else if ('pnpm-global' === kind) {
16134
17594
  const args = [
16135
17595
  'add',
@@ -16142,6 +17602,7 @@ async function runUpgrade(options) {
16142
17602
  printLine('无法识别当前安装方式,请按实际情况手动执行其中之一:');
16143
17603
  printLine(` npm install -g ylcwf@${target}`);
16144
17604
  printLine(` pnpm add -g ylcwf@${target}`);
17605
+ printLine(" mise upgrade npm:ylcwf --bump");
16145
17606
  printLine(` curl -fsSL ${SCRIPT_CDN}/install.sh | sh`);
16146
17607
  printLine(` powershell -NoProfile -Command "irm ${SCRIPT_CDN}/install.ps1 | iex"`);
16147
17608
  return;
@@ -16484,9 +17945,14 @@ function buildMatch(item, terminalName, matchedBy, catalog) {
16484
17945
  function checkYapiAgainstTerminalCatalog(catalog, terminalNames) {
16485
17946
  if (0 === terminalNames.length) return [];
16486
17947
  const allowed = terminalNames.map((name)=>normalizeName(name));
16487
- const issues = [];
16488
- for (const item of catalog.platforms)if (!allowed.includes(normalizeName(item.terminal))) issues.push(yapi_warning('YAPI_TERMINAL_NOT_IN_CATALOG', `${YAPI_PLATFORM_FILE} 中的执行终端「${item.terminal}」不在 execution_terminals.json 里;可选:${terminalNames.join('、')}(以清单为准,请改 yapi 文件)`, `platforms.${item.terminal}`));
16489
- return issues;
17948
+ const unknown = [];
17949
+ for (const item of catalog.platforms)if (!allowed.includes(normalizeName(item.terminal))) {
17950
+ if (!unknown.includes(item.terminal)) unknown.push(item.terminal);
17951
+ }
17952
+ if (0 === unknown.length) return [];
17953
+ return [
17954
+ yapi_warning('YAPI_TERMINAL_NOT_IN_CATALOG', `${YAPI_PLATFORM_FILE} 中有 ${unknown.length} 个执行终端不在 execution_terminals.json 里:「${unknown.join('、')}」;可选:${terminalNames.join('、')}(以清单为准,请改 yapi 文件)`, 'platforms')
17955
+ ];
16490
17956
  }
16491
17957
  function checkDocsSides(config) {
16492
17958
  const messages = [];
@@ -16554,11 +18020,11 @@ function checkSchemaRequirement(config) {
16554
18020
  const required = parseMinVersion(schema.requiresYlcwf);
16555
18021
  if (null === required) return [];
16556
18022
  const floor = `${required[0]}.${required[1]}.${required[2]}`;
16557
- if (compareVersions("0.7.0", floor) >= 0) return [];
18023
+ if (compareVersions("0.9.0", floor) >= 0) return [];
16558
18024
  return [
16559
18025
  {
16560
18026
  level: 'error',
16561
- message: `文档仓库要求 ylcwf ${schema.requiresYlcwf},当前 0.7.0;请先升级:npm install -g ylcwf@latest`
18027
+ message: `文档仓库要求 ylcwf ${schema.requiresYlcwf},当前 0.9.0;请先升级:npm install -g ylcwf@latest`
16562
18028
  }
16563
18029
  ];
16564
18030
  } catch (error) {
@@ -16570,6 +18036,33 @@ function checkSchemaRequirement(config) {
16570
18036
  ];
16571
18037
  }
16572
18038
  }
18039
+ function checkWritability(config, configPath) {
18040
+ const issues = [];
18041
+ const probe = (target, label, hint)=>{
18042
+ try {
18043
+ accessSync(target, constants.W_OK);
18044
+ } catch (error) {
18045
+ const code = error.code;
18046
+ if ('ENOENT' === code) return void issues.push({
18047
+ level: 'error',
18048
+ message: `${label}不存在:${target}`
18049
+ });
18050
+ issues.push({
18051
+ level: 'error',
18052
+ message: `${label}不可写:${target}(${code ?? '未知错误'})${hint}`
18053
+ });
18054
+ }
18055
+ };
18056
+ const root = config.docs.root.trim();
18057
+ if (root.length > 0) {
18058
+ probe(root, '文档仓库', '写任务文档会失败;会话需能写该目录');
18059
+ const iterationsRoot = external_node_path_join(root, DEFAULT_ITERATIONS_ROOT);
18060
+ if (external_node_fs_existsSync(iterationsRoot)) probe(iterationsRoot, '文档仓库迭代目录', '写任务文档会失败;确认迭代目录可写');
18061
+ if (config.docs.git.cli.commit || config.docs.git.ui.commit) probe(external_node_path_join(root, '.git'), '文档仓库 .git', '已开启自动提交,提交会写 .git;可关闭 docs.git.*.commit');
18062
+ }
18063
+ probe(external_node_path_dirname(configPath), '配置目录', '变更历史与配置备份写不进去;确认家目录可写');
18064
+ return issues;
18065
+ }
16573
18066
  function runDoctor(options) {
16574
18067
  const format = parseFormat(options.format);
16575
18068
  const loaded = config_loadConfig(options.config);
@@ -16580,10 +18073,13 @@ function runDoctor(options) {
16580
18073
  const errors = countIssues(checked.issues).errors;
16581
18074
  const ok = !hasError(checked.issues);
16582
18075
  const sideIssues = [];
16583
- if (true === options.docs && null !== checked.config && ok) {
16584
- sideIssues.push(...checkSchemaRequirement(checked.config));
16585
- sideIssues.push(...doctor_checkTerminalCatalog(checked.config));
16586
- sideIssues.push(...checkDocsSides(checked.config));
18076
+ if (null !== checked.config) {
18077
+ sideIssues.push(...checkWritability(checked.config, loaded.path));
18078
+ if (true === options.docs && ok) {
18079
+ sideIssues.push(...checkSchemaRequirement(checked.config));
18080
+ sideIssues.push(...doctor_checkTerminalCatalog(checked.config));
18081
+ sideIssues.push(...checkDocsSides(checked.config));
18082
+ }
16587
18083
  }
16588
18084
  const sideErrors = sideIssues.filter((item)=>'error' === item.level).length;
16589
18085
  const allOk = ok && 0 === sideErrors;
@@ -16611,9 +18107,32 @@ function registerDoctor(program) {
16611
18107
  runDoctor(options);
16612
18108
  });
16613
18109
  }
18110
+ function runRemoteCache(options, format) {
18111
+ const root = remoteCacheRoot();
18112
+ const entries = listRemoteCacheDirs();
18113
+ if (true === options.exists) {
18114
+ const present = entries.length > 0;
18115
+ if ('json' === format) printJson({
18116
+ remoteCacheRoot: root,
18117
+ entries: entries.length,
18118
+ exists: present
18119
+ });
18120
+ else printLine(present ? 'true' : 'false');
18121
+ if (!present) process.exitCode = errors_EXIT.NOT_FOUND;
18122
+ return;
18123
+ }
18124
+ if ('json' === format) return void printJson({
18125
+ remoteCacheRoot: root,
18126
+ prefix: REMOTE_CACHE_PREFIX,
18127
+ entries
18128
+ });
18129
+ printLine(root);
18130
+ printLine(0 === entries.length ? '(当前没有远程快照缓存;在界面切到「远程」或调用 export 后才会生成)' : `快照缓存目录 ${entries.length} 个(${REMOTE_CACHE_PREFIX}*),保留最近 20 个`);
18131
+ }
16614
18132
  function runPath(options) {
16615
- const target = paths_resolveConfigPath(options.config);
16616
18133
  const format = parseFormat(options.format);
18134
+ if (true === options.remoteCache) return void runRemoteCache(options, format);
18135
+ const target = paths_resolveConfigPath(options.config);
16617
18136
  if (true === options.exists) {
16618
18137
  const present = external_node_fs_existsSync(target);
16619
18138
  if ('json' === format) printJson({
@@ -16627,7 +18146,7 @@ function runPath(options) {
16627
18146
  printLine(target);
16628
18147
  }
16629
18148
  function registerPath(program) {
16630
- program.command('path').description('输出配置文件绝对路径').option('-c, --config <path>', '指定配置文件路径').option('--exists', '改为输出配置文件是否存在(true/false)').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
18149
+ program.command('path').description('输出配置文件绝对路径,或远程快照缓存目录').option('-c, --config <path>', '指定配置文件路径').option('--exists', '改为输出目标是否存在(true/false)').option('--remote-cache', '改为输出远程快照缓存目录(系统临时目录)').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
16631
18150
  runPath(options);
16632
18151
  });
16633
18152
  }
@@ -16682,8 +18201,8 @@ function syncDocument(doc, next) {
16682
18201
  doc.setIn([
16683
18202
  'docs',
16684
18203
  'validator',
16685
- 'requireScript'
16686
- ], next.docs.validator.requireScript);
18204
+ 'strict'
18205
+ ], next.docs.validator.strict);
16687
18206
  const current = doc.toJS();
16688
18207
  const currentTerminals = utils_isRecord(current) && utils_isRecord(current['terminals']) ? Object.keys(current['terminals']) : [];
16689
18208
  for (const key of currentTerminals)if (!Object.hasOwn(next.terminals, key)) doc.deleteIn([
@@ -16714,7 +18233,15 @@ function syncDocument(doc, next) {
16714
18233
  ], terminal.repos.backend);
16715
18234
  }
16716
18235
  }
16717
- function collectResetTargets(configPath) {
18236
+ function backupsTarget(configPath) {
18237
+ const path = backupsDir(configPath);
18238
+ return external_node_fs_existsSync(path) ? {
18239
+ path,
18240
+ label: '配置备份',
18241
+ kind: 'dir'
18242
+ } : null;
18243
+ }
18244
+ function collectResetTargets(configPath, options = {}) {
16718
18245
  const targets = [
16719
18246
  {
16720
18247
  path: configPath,
@@ -16725,13 +18252,12 @@ function collectResetTargets(configPath) {
16725
18252
  path: `${configPath}.lock`,
16726
18253
  label: '锁文件',
16727
18254
  kind: 'file'
16728
- },
16729
- {
16730
- path: backupsDir(configPath),
16731
- label: '配置备份',
16732
- kind: 'dir'
16733
18255
  }
16734
18256
  ];
18257
+ if (true === options.removeBackups) {
18258
+ const backups = backupsTarget(configPath);
18259
+ if (null !== backups) targets.push(backups);
18260
+ }
16735
18261
  return targets.filter((target)=>external_node_fs_existsSync(target.path));
16736
18262
  }
16737
18263
  function describeTarget(target) {
@@ -16742,6 +18268,13 @@ function describeTarget(target) {
16742
18268
  const count = external_node_fs_readdirSync(target.path).length;
16743
18269
  return `${target.label}:${target.path}(${count} 项)`;
16744
18270
  }
18271
+ function countBackups(configPath) {
18272
+ try {
18273
+ return external_node_fs_readdirSync(backupsDir(configPath)).length;
18274
+ } catch {
18275
+ return 0;
18276
+ }
18277
+ }
16745
18278
  function performReset(configPath, targets) {
16746
18279
  for (const target of targets)rmSync(target.path, {
16747
18280
  recursive: true,
@@ -16786,7 +18319,7 @@ function readState(explicitPath) {
16786
18319
  issues: checked.issues,
16787
18320
  backups: listBackups(explicitPath),
16788
18321
  meta: {
16789
- version: "0.7.0",
18322
+ version: "0.9.0",
16790
18323
  features: SERVER_FEATURES
16791
18324
  }
16792
18325
  };
@@ -16859,13 +18392,17 @@ function resolveRequest(name, side, explicitPath) {
16859
18392
  repos
16860
18393
  };
16861
18394
  }
16862
- function resetConfig(explicitPath) {
18395
+ function resetConfig(explicitPath, options = {}) {
16863
18396
  const configPath = paths_resolveConfigPath(explicitPath);
16864
- const targets = collectResetTargets(configPath);
18397
+ const targets = collectResetTargets(configPath, {
18398
+ removeBackups: true === options.removeBackups
18399
+ });
16865
18400
  const removed = performReset(configPath, targets);
18401
+ const keptBackups = true === options.removeBackups ? 0 : countBackups(configPath);
16866
18402
  return {
16867
18403
  removed,
16868
- configPath
18404
+ configPath,
18405
+ keptBackups
16869
18406
  };
16870
18407
  }
16871
18408
  function inspectPath(target) {
@@ -17210,10 +18747,7 @@ function requireOwnDeveloper(input, configPath, options = {}) {
17210
18747
  if (developer !== loaded.config.profile.developer) throw new OperationError('只能修改自己的任务文档', options.forbidStatus ?? 403);
17211
18748
  return {
17212
18749
  developer,
17213
- policy: loaded.config.docs.git?.ui ?? {
17214
- commit: true,
17215
- push: false
17216
- }
18750
+ policy: loaded.config.docs.git?.ui ?? DEFAULT_GIT_POLICY
17217
18751
  };
17218
18752
  }
17219
18753
  function requireAction(input) {
@@ -17314,8 +18848,12 @@ const OPERATIONS = [
17314
18848
  path: '/api/reset'
17315
18849
  },
17316
18850
  ipc: 'ylcwf:reset',
17317
- ipcParams: [],
17318
- run: (_input, context)=>resetConfig(context.configPath)
18851
+ ipcParams: [
18852
+ 'all'
18853
+ ],
18854
+ run: (input, context)=>resetConfig(context.configPath, {
18855
+ removeBackups: input.bool('all')
18856
+ })
17319
18857
  },
17320
18858
  {
17321
18859
  name: 'onboarding-complete',
@@ -17550,6 +19088,16 @@ const OPERATIONS = [
17550
19088
  return listIterations(layoutOf(loaded.config), parseSource(input.text('source')), input.optionalText('ref'));
17551
19089
  }
17552
19090
  },
19091
+ {
19092
+ name: 'iteration-current',
19093
+ http: {
19094
+ method: 'GET',
19095
+ path: '/api/iteration-current'
19096
+ },
19097
+ ipc: 'ylcwf:iterationCurrent',
19098
+ ipcParams: [],
19099
+ run: (_input, context)=>readCurrentIteration(layoutOf(config_loadConfig(context.configPath).config))
19100
+ },
17553
19101
  {
17554
19102
  name: 'iteration-summary',
17555
19103
  http: {
@@ -17995,12 +19543,1082 @@ function registerYapi(program) {
17995
19543
  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));
17996
19544
  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));
17997
19545
  }
19546
+ const PRD_SNAPSHOT_SCHEMA_VERSION = 'prd-snapshot';
19547
+ const PRD_META_SCHEMA_VERSION = 'prd-meta';
19548
+ const PRD_SNAPSHOT_NAME = 'snapshot.json';
19549
+ const PRD_META_NAME = 'meta.json';
19550
+ const CHANGELOG_KEYWORD = '变更记录';
19551
+ const HEADING_TAGS = new Set([
19552
+ 'h1',
19553
+ 'h2',
19554
+ 'h3',
19555
+ 'h4',
19556
+ 'h5',
19557
+ 'h6'
19558
+ ]);
19559
+ const BLOCK_TAGS = new Set([
19560
+ 'p',
19561
+ 'li',
19562
+ 'pre',
19563
+ 'blockquote'
19564
+ ]);
19565
+ const REQUIREMENT_HEADING_PATTERNS = [
19566
+ /[-–—]\s*(\d{3,6})\s*$/,
19567
+ /#\s*(\d{3,6})\b/,
19568
+ /需求\s*[::]?\s*(\d{3,6})\b/
19569
+ ];
19570
+ const REQUIREMENT_BODY_PATTERN = /新增需求\s*[::]?\s*(\d{3,6})\b/;
19571
+ const SECTION_NO_PATTERN = /^(\d+(?:\.\d+)*)/;
19572
+ const CHANGELOG_SECTION_REF_PATTERN = /\d+\.\d+(?:\.\d+)*(?:\s*-\s*[A-Za-z])?/g;
19573
+ const CHANGELOG_REQUIREMENT_REF_PATTERN = /(?<![\d.])(\d{3,6})(?![\d.])/g;
19574
+ const CHANGELOG_DATE_PATTERN = /\d{4}-\d{1,2}-\d{1,2}/;
19575
+ const NODE_ID_PATTERN = /\/nodes\/([A-Za-z0-9_-]+)/;
19576
+ const NODE_ID_QUERY_PATTERN = /[?&]nodeId=([A-Za-z0-9_-]+)/;
19577
+ class PrdJsonmlError extends Error {
19578
+ constructor(message){
19579
+ super(message);
19580
+ this.name = 'PrdJsonmlError';
19581
+ }
19582
+ }
19583
+ function sha256Text(text) {
19584
+ return createHash('sha256').update(text, 'utf8').digest('hex');
19585
+ }
19586
+ function formatTimestamp(milliseconds) {
19587
+ if (null == milliseconds || 0 === milliseconds) return '未提供';
19588
+ const date = new Date(milliseconds);
19589
+ if (Number.isNaN(date.getTime())) return `原始值 ${milliseconds}`;
19590
+ const pad = (value)=>String(value).padStart(2, '0');
19591
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
19592
+ }
19593
+ function resolveNodeId(node) {
19594
+ const text = node.trim();
19595
+ const matched = NODE_ID_PATTERN.exec(text) ?? NODE_ID_QUERY_PATTERN.exec(text);
19596
+ return matched?.[1] ?? text;
19597
+ }
19598
+ function prd_isRecord(value) {
19599
+ return 'object' == typeof value && null !== value && !Array.isArray(value);
19600
+ }
19601
+ function splitNode(node) {
19602
+ if (!Array.isArray(node) || 0 === node.length) return {
19603
+ tag: null,
19604
+ attrs: {},
19605
+ children: []
19606
+ };
19607
+ const tag = 'string' == typeof node[0] ? node[0] : null;
19608
+ let attrs = {};
19609
+ const children = [];
19610
+ for (const item of node.slice(1)){
19611
+ if (prd_isRecord(item) && 0 === Object.keys(attrs).length) {
19612
+ attrs = item;
19613
+ continue;
19614
+ }
19615
+ children.push(item);
19616
+ }
19617
+ return {
19618
+ tag,
19619
+ attrs,
19620
+ children
19621
+ };
19622
+ }
19623
+ function collectText(node) {
19624
+ if ('string' == typeof node) return node;
19625
+ if (!Array.isArray(node)) return '';
19626
+ return splitNode(node).children.map(collectText).join('');
19627
+ }
19628
+ function normalizeText(text) {
19629
+ return text.replace(/\s+/g, ' ').trim();
19630
+ }
19631
+ function collectCellText(cell) {
19632
+ if (!Array.isArray(cell)) return normalizeText(collectText(cell));
19633
+ const parts = [];
19634
+ for (const child of splitNode(cell).children){
19635
+ if (!Array.isArray(child)) continue;
19636
+ const { tag } = splitNode(child);
19637
+ if (null !== tag && BLOCK_TAGS.has(tag)) {
19638
+ const text = normalizeText(collectText(child));
19639
+ if (text.length > 0) parts.push(text);
19640
+ }
19641
+ }
19642
+ if (parts.length > 0) return parts.join(' / ');
19643
+ return normalizeText(collectText(cell));
19644
+ }
19645
+ function parseJsonmlBlocks(jsonmlText) {
19646
+ let root;
19647
+ try {
19648
+ root = JSON.parse(jsonmlText);
19649
+ } catch {
19650
+ throw new PrdJsonmlError('dws 返回的 jsonml 不是合法 JSON');
19651
+ }
19652
+ const blocks = [];
19653
+ const walk = (node)=>{
19654
+ if (!Array.isArray(node)) return;
19655
+ const { tag, attrs, children } = splitNode(node);
19656
+ if (null === tag) {
19657
+ for (const child of children)walk(child);
19658
+ return;
19659
+ }
19660
+ const uuid = 'string' == typeof attrs['uuid'] ? attrs['uuid'] : '';
19661
+ if (HEADING_TAGS.has(tag)) return void blocks.push({
19662
+ tag,
19663
+ uuid,
19664
+ level: Number.parseInt(tag.slice(1), 10),
19665
+ text: normalizeText(collectText(node))
19666
+ });
19667
+ if (BLOCK_TAGS.has(tag)) {
19668
+ const text = normalizeText(collectText(node));
19669
+ if (text.length > 0) blocks.push({
19670
+ tag,
19671
+ uuid,
19672
+ text
19673
+ });
19674
+ return;
19675
+ }
19676
+ if ('tr' === tag) {
19677
+ const cells = children.filter((child)=>Array.isArray(child) && 'tc' === splitNode(child).tag).map(collectCellText);
19678
+ blocks.push({
19679
+ tag: 'tr',
19680
+ uuid,
19681
+ text: cells.filter((cell)=>cell.length > 0).join(' | '),
19682
+ cells
19683
+ });
19684
+ return;
19685
+ }
19686
+ for (const child of children)walk(child);
19687
+ };
19688
+ walk(root);
19689
+ return blocks;
19690
+ }
19691
+ function blockSignature(block) {
19692
+ return `${block.tag}\t${block.text}`;
19693
+ }
19694
+ function pagesDigest(blocks) {
19695
+ return sha256Text(blocks.map(blockSignature).join('\n'));
19696
+ }
19697
+ function extractRequirementIds(heading) {
19698
+ const found = [];
19699
+ for (const pattern of REQUIREMENT_HEADING_PATTERNS){
19700
+ const global = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`);
19701
+ let matched = global.exec(heading);
19702
+ while(null !== matched){
19703
+ const id = matched[1];
19704
+ if (void 0 !== id && !found.includes(id)) found.push(id);
19705
+ matched = global.exec(heading);
19706
+ }
19707
+ }
19708
+ return found;
19709
+ }
19710
+ function extractSectionNo(heading) {
19711
+ const matched = SECTION_NO_PATTERN.exec(heading);
19712
+ return matched?.[1] ?? null;
19713
+ }
19714
+ function headingRefs(blocks) {
19715
+ const refs = [];
19716
+ blocks.forEach((block, index)=>{
19717
+ if (!HEADING_TAGS.has(block.tag)) return;
19718
+ refs.push({
19719
+ index,
19720
+ level: block.level ?? 0,
19721
+ text: block.text
19722
+ });
19723
+ });
19724
+ return refs;
19725
+ }
19726
+ function buildRequirements(blocks) {
19727
+ const headings = headingRefs(blocks);
19728
+ const requirements = {};
19729
+ headings.forEach((heading, order)=>{
19730
+ const end = headings.slice(order + 1).find((later)=>later.level <= heading.level)?.index ?? blocks.length;
19731
+ const scope = blocks.slice(heading.index, end);
19732
+ const requirementIds = extractRequirementIds(heading.text);
19733
+ if (0 === requirementIds.length) return;
19734
+ for (const requirementId of requirementIds)if (void 0 === requirements[requirementId]) requirements[requirementId] = {
19735
+ requirement: requirementId,
19736
+ heading: heading.text,
19737
+ sectionNo: extractSectionNo(heading.text),
19738
+ start: heading.index,
19739
+ end: end - 1,
19740
+ blockCount: scope.length,
19741
+ digest: pagesDigest(scope)
19742
+ };
19743
+ });
19744
+ return requirements;
19745
+ }
19746
+ function findChangelog(blocks) {
19747
+ const headings = headingRefs(blocks);
19748
+ const candidates = headings.filter((heading)=>heading.text.includes(CHANGELOG_KEYWORD) && heading.level <= 3);
19749
+ if (0 === candidates.length) return null;
19750
+ const start = candidates.reduce((best, item)=>item.level < best.level || item.level === best.level && item.index < best.index ? item : best);
19751
+ const end = headings.find((heading)=>heading.index > start.index && heading.level <= start.level)?.index ?? blocks.length;
19752
+ const rows = [];
19753
+ for (const block of blocks.slice(start.index, end)){
19754
+ if ('tr' !== block.tag) continue;
19755
+ const cells = block.cells ?? [];
19756
+ if (0 !== cells.length) {
19757
+ if (!(cells[0] ?? '').startsWith('变更时间')) rows.push(cells);
19758
+ }
19759
+ }
19760
+ return {
19761
+ start: start.index,
19762
+ end: end - 1,
19763
+ rows,
19764
+ digest: sha256Text(rows.map((row)=>row.join(' | ')).join('\n'))
19765
+ };
19766
+ }
19767
+ function collectDeclaredRequirements(blocks) {
19768
+ const withSection = new Set();
19769
+ for (const block of blocks)if (HEADING_TAGS.has(block.tag)) for (const id of extractRequirementIds(block.text))withSection.add(id);
19770
+ const declared = {};
19771
+ for (const block of blocks){
19772
+ if (!BLOCK_TAGS.has(block.tag)) continue;
19773
+ const global = new RegExp(REQUIREMENT_BODY_PATTERN.source, 'g');
19774
+ let matched = global.exec(block.text);
19775
+ while(null !== matched){
19776
+ const candidate = matched[1];
19777
+ if (void 0 !== candidate && !withSection.has(candidate)) declared[candidate] = declared[candidate] ?? [];
19778
+ matched = global.exec(block.text);
19779
+ }
19780
+ }
19781
+ return declared;
19782
+ }
19783
+ function buildSnapshot(options) {
19784
+ const blocks = parseJsonmlBlocks(options.document.jsonml);
19785
+ return {
19786
+ schemaVersion: PRD_SNAPSHOT_SCHEMA_VERSION,
19787
+ iteration: options.iteration,
19788
+ nodeId: options.document.nodeId,
19789
+ docUrl: options.document.docUrl,
19790
+ title: options.document.title,
19791
+ revision: options.document.revision,
19792
+ updateTime: options.updateTime,
19793
+ updateTimeText: formatTimestamp(options.updateTime),
19794
+ blockCount: blocks.length,
19795
+ blocks,
19796
+ requirements: buildRequirements(blocks),
19797
+ changelog: findChangelog(blocks),
19798
+ declaredRequirements: collectDeclaredRequirements(blocks)
19799
+ };
19800
+ }
19801
+ function buildMeta(snapshot) {
19802
+ const requirements = {};
19803
+ for (const [id, entry] of Object.entries(snapshot.requirements))requirements[id] = {
19804
+ sectionNo: entry.sectionNo,
19805
+ heading: entry.heading,
19806
+ blockCount: entry.blockCount,
19807
+ digest: entry.digest
19808
+ };
19809
+ return {
19810
+ schemaVersion: PRD_META_SCHEMA_VERSION,
19811
+ iteration: snapshot.iteration,
19812
+ nodeId: snapshot.nodeId,
19813
+ docUrl: snapshot.docUrl,
19814
+ title: snapshot.title,
19815
+ revision: snapshot.revision,
19816
+ updateTime: snapshot.updateTime,
19817
+ updateTimeText: snapshot.updateTimeText,
19818
+ blockCount: snapshot.blockCount,
19819
+ requirements,
19820
+ changelog: {
19821
+ rowCount: snapshot.changelog?.rows.length ?? 0,
19822
+ digest: snapshot.changelog?.digest ?? null
19823
+ },
19824
+ declaredRequirements: snapshot.declaredRequirements
19825
+ };
19826
+ }
19827
+ function describeRow(cells) {
19828
+ const rowText = cells.join(' | ');
19829
+ const date = CHANGELOG_DATE_PATTERN.exec(rowText)?.[0] ?? '';
19830
+ const withoutDate = rowText.replace(CHANGELOG_DATE_PATTERN, ' ');
19831
+ return {
19832
+ row: rowText,
19833
+ cells: [
19834
+ ...cells
19835
+ ],
19836
+ date,
19837
+ sectionRefs: withoutDate.match(CHANGELOG_SECTION_REF_PATTERN) ?? [],
19838
+ requirementRefs: withoutDate.match(CHANGELOG_REQUIREMENT_REF_PATTERN) ?? []
19839
+ };
19840
+ }
19841
+ function matchedRows(rows, requirementId, sectionNo) {
19842
+ const matched = [];
19843
+ for (const cells of rows){
19844
+ const described = describeRow(cells);
19845
+ if (described.requirementRefs.includes(requirementId)) {
19846
+ matched.push(described);
19847
+ continue;
19848
+ }
19849
+ if (null !== sectionNo && described.sectionRefs.some((ref)=>ref.startsWith(sectionNo))) matched.push(described);
19850
+ }
19851
+ return matched;
19852
+ }
19853
+ function unifiedDiff(oldLines, newLines, context = 2) {
19854
+ const rows = oldLines.length;
19855
+ const cols = newLines.length;
19856
+ const lcs = Array.from({
19857
+ length: rows + 1
19858
+ }, ()=>new Array(cols + 1).fill(0));
19859
+ 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);
19860
+ const edits = [];
19861
+ let i = 0;
19862
+ let j = 0;
19863
+ while(i < rows && j < cols){
19864
+ if (oldLines[i] === newLines[j]) {
19865
+ edits.push({
19866
+ kind: ' ',
19867
+ text: oldLines[i] ?? '',
19868
+ oldIndex: i,
19869
+ newIndex: j
19870
+ });
19871
+ i += 1;
19872
+ j += 1;
19873
+ continue;
19874
+ }
19875
+ if ((lcs[i + 1][j] ?? 0) >= (lcs[i][j + 1] ?? 0)) {
19876
+ edits.push({
19877
+ kind: '-',
19878
+ text: oldLines[i] ?? '',
19879
+ oldIndex: i,
19880
+ newIndex: j
19881
+ });
19882
+ i += 1;
19883
+ } else {
19884
+ edits.push({
19885
+ kind: '+',
19886
+ text: newLines[j] ?? '',
19887
+ oldIndex: i,
19888
+ newIndex: j
19889
+ });
19890
+ j += 1;
19891
+ }
19892
+ }
19893
+ while(i < rows){
19894
+ edits.push({
19895
+ kind: '-',
19896
+ text: oldLines[i] ?? '',
19897
+ oldIndex: i,
19898
+ newIndex: j
19899
+ });
19900
+ i += 1;
19901
+ }
19902
+ while(j < cols){
19903
+ edits.push({
19904
+ kind: '+',
19905
+ text: newLines[j] ?? '',
19906
+ oldIndex: i,
19907
+ newIndex: j
19908
+ });
19909
+ j += 1;
19910
+ }
19911
+ const changed = edits.map((edit, index)=>' ' === edit.kind ? -1 : index).filter((index)=>index >= 0);
19912
+ if (0 === changed.length) return [];
19913
+ const hunks = [];
19914
+ for (const index of changed){
19915
+ const start = Math.max(0, index - context);
19916
+ const end = Math.min(edits.length - 1, index + context);
19917
+ const last = hunks[hunks.length - 1];
19918
+ if (void 0 !== last && start <= last.end + 1) last.end = Math.max(last.end, end);
19919
+ else hunks.push({
19920
+ start,
19921
+ end
19922
+ });
19923
+ }
19924
+ const lines = [
19925
+ '--- baseline',
19926
+ '+++ current'
19927
+ ];
19928
+ for (const hunk of hunks){
19929
+ const slice = edits.slice(hunk.start, hunk.end + 1);
19930
+ const oldCount = slice.filter((edit)=>'+' !== edit.kind).length;
19931
+ const newCount = slice.filter((edit)=>'-' !== edit.kind).length;
19932
+ const oldStart = (slice.find((edit)=>'+' !== edit.kind)?.oldIndex ?? 0) + 1;
19933
+ const newStart = (slice.find((edit)=>'-' !== edit.kind)?.newIndex ?? 0) + 1;
19934
+ lines.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`);
19935
+ for (const edit of slice)lines.push(`${edit.kind}${edit.text}`);
19936
+ }
19937
+ return lines;
19938
+ }
19939
+ function blockDiff(options) {
19940
+ const oldLines = options.oldBlocks.slice(options.oldRange[0], options.oldRange[1] + 1).map(blockSignature);
19941
+ const newLines = options.newBlocks.slice(options.newRange[0], options.newRange[1] + 1).map(blockSignature);
19942
+ const oldSet = new Set(oldLines);
19943
+ const newSet = new Set(newLines);
19944
+ const diffLines = unifiedDiff(oldLines, newLines);
19945
+ return {
19946
+ diff: diffLines.slice(0, options.maxLines).join('\n'),
19947
+ truncated: diffLines.length > options.maxLines,
19948
+ diffLineCount: diffLines.length,
19949
+ addedBlocks: newLines.filter((line)=>!oldSet.has(line)).length,
19950
+ removedBlocks: oldLines.filter((line)=>!newSet.has(line)).length
19951
+ };
19952
+ }
19953
+ class PrdDwsError extends Error {
19954
+ code;
19955
+ hint;
19956
+ constructor(code, message, hint = ''){
19957
+ super(message);
19958
+ this.name = 'PrdDwsError';
19959
+ this.code = code;
19960
+ this.hint = hint;
19961
+ }
19962
+ toDict() {
19963
+ return {
19964
+ code: this.code,
19965
+ message: this.message,
19966
+ hint: this.hint
19967
+ };
19968
+ }
19969
+ }
19970
+ const PRD_DWS_HINTS = {
19971
+ DWS_NOT_FOUND: '请安装 dws CLI 并执行 dws auth login,或用 --dws-path 指定绝对路径',
19972
+ DWS_TIMEOUT: 'dws 响应超时,请检查网络后重试',
19973
+ DWS_BAD_OUTPUT: 'dws 输出异常,请升级 dws 或反馈维护者',
19974
+ CONTENT_NOT_READY: 'PRD 正文尚未就绪,请稍后重试(本次已自动重试一次)',
19975
+ CONTENT_EMPTY: 'PRD 正文为空或尚未发布,请确认文档内容已就绪',
19976
+ AUTH_REQUIRED: '请执行 dws auth login 完成登录后重试',
19977
+ PERMISSION_DENIED: '当前账号没有该文档权限,请联系文档所有者开通',
19978
+ NODE_NOT_FOUND: '请核对 PRD 链接或 nodeId 是否正确',
19979
+ NODE_MISSING: '请传 --node(PRD 链接或 nodeId)',
19980
+ NO_BASELINE: '先执行 ylcwf prd baseline 建立快照,或本次显式传 --node'
19981
+ };
19982
+ function hintOf(code) {
19983
+ return PRD_DWS_HINTS[code] ?? '';
19984
+ }
19985
+ function classifyDwsMessage(message) {
19986
+ const lowered = message.toLowerCase();
19987
+ if (message.includes('尚未就绪') || lowered.includes('not ready')) return 'CONTENT_NOT_READY';
19988
+ if (message.includes('未登录') || lowered.includes('authenticate') || lowered.includes('access token')) return 'AUTH_REQUIRED';
19989
+ if (message.includes('无权') || lowered.includes('accessdenied') || lowered.includes('forbidden')) return 'PERMISSION_DENIED';
19990
+ if (message.includes('不存在') || lowered.includes('notfound') || lowered.includes('not found')) return 'NODE_NOT_FOUND';
19991
+ return 'DWS_ERROR';
19992
+ }
19993
+ function prd_sleepSync(milliseconds) {
19994
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
19995
+ }
19996
+ function src_prd_isRecord(value) {
19997
+ return 'object' == typeof value && null !== value && !Array.isArray(value);
19998
+ }
19999
+ function execDws(dwsPath, args) {
20000
+ let stdout;
20001
+ try {
20002
+ stdout = execFileSync(dwsPath, [
20003
+ ...args,
20004
+ '--format',
20005
+ 'json'
20006
+ ], {
20007
+ encoding: 'utf8',
20008
+ timeout: 120000,
20009
+ maxBuffer: 33554432,
20010
+ stdio: [
20011
+ 'ignore',
20012
+ 'pipe',
20013
+ 'pipe'
20014
+ ]
20015
+ });
20016
+ } catch (error) {
20017
+ const failure = error;
20018
+ if ('ENOENT' === failure.code || 127 === failure.code) throw new PrdDwsError('DWS_NOT_FOUND', `未找到 dws 可执行文件:${dwsPath}`, '请安装 dws CLI 并完成 dws auth login,或用 --dws-path 指定绝对路径');
20019
+ if (true === failure.killed || 'SIGTERM' === failure.signal) throw new PrdDwsError('DWS_TIMEOUT', `dws 调用超时(120 秒):${args.join(' ')}`, hintOf('DWS_TIMEOUT'));
20020
+ const rawStdout = 'string' == typeof failure.stdout ? failure.stdout.trim() : '';
20021
+ if (rawStdout.length > 0) try {
20022
+ const payload = JSON.parse(rawStdout);
20023
+ if (src_prd_isRecord(payload) && src_prd_isRecord(payload['error'])) {
20024
+ const message = String(payload['error']['message'] ?? 'dws 返回错误');
20025
+ const code = classifyDwsMessage(message);
20026
+ throw new PrdDwsError(code, message, String(payload['error']['hint'] ?? '') || hintOf(code));
20027
+ }
20028
+ if (src_prd_isRecord(payload) && 'string' == typeof payload['message']) {
20029
+ const code = classifyDwsMessage(payload['message']);
20030
+ throw new PrdDwsError(code, payload['message'], hintOf(code));
20031
+ }
20032
+ } catch (inner) {
20033
+ if (inner instanceof PrdDwsError) throw inner;
20034
+ }
20035
+ const stderr = 'string' == typeof failure.stderr ? failure.stderr.trim() : '';
20036
+ const message = stderr.length > 0 ? stderr.split('\n').at(-1) ?? stderr : 'dws 没有任何输出';
20037
+ const code = classifyDwsMessage(message);
20038
+ throw new PrdDwsError(code, message, hintOf(code));
20039
+ }
20040
+ try {
20041
+ const payload = JSON.parse(stdout);
20042
+ if (!src_prd_isRecord(payload)) throw new PrdDwsError('DWS_BAD_OUTPUT', `dws 输出不是对象:${stdout.slice(0, 200)}`, hintOf('DWS_BAD_OUTPUT'));
20043
+ if (src_prd_isRecord(payload['error'])) {
20044
+ const message = String(payload['error']['message'] ?? 'dws 返回错误');
20045
+ const code = classifyDwsMessage(message);
20046
+ throw new PrdDwsError(code, message, String(payload['error']['hint'] ?? '') || hintOf(code));
20047
+ }
20048
+ return payload;
20049
+ } catch (error) {
20050
+ if (error instanceof PrdDwsError) throw error;
20051
+ throw new PrdDwsError('DWS_BAD_OUTPUT', `dws 输出不是合法 JSON:${stdout.slice(0, 200)}`, hintOf('DWS_BAD_OUTPUT'));
20052
+ }
20053
+ }
20054
+ function probePrd(dwsPath, node) {
20055
+ const nodeId = resolveNodeId(node);
20056
+ if (0 === nodeId.length) throw new PrdDwsError('NODE_MISSING', '未提供 PRD 文档 nodeId 或链接', hintOf('NODE_MISSING'));
20057
+ const info = execDws(dwsPath, [
20058
+ 'doc',
20059
+ '+inspect',
20060
+ '--node',
20061
+ nodeId
20062
+ ]);
20063
+ const data = src_prd_isRecord(info['data']) ? info['data'] : {};
20064
+ const document = src_prd_isRecord(data['document']) ? data['document'] : {};
20065
+ return {
20066
+ nodeId: String(document['nodeId'] ?? nodeId),
20067
+ docUrl: String(document['docUrl'] ?? ''),
20068
+ title: String(document['name'] ?? ''),
20069
+ updateTime: Number(document['updateTime'] ?? 0),
20070
+ extension: String(document['extension'] ?? '')
20071
+ };
20072
+ }
20073
+ function fetchPrd(dwsPath, node, retryDelayMs = 3000) {
20074
+ const nodeId = resolveNodeId(node);
20075
+ const args = [
20076
+ 'doc',
20077
+ '+fetch',
20078
+ '--node',
20079
+ nodeId,
20080
+ '--scope',
20081
+ 'full',
20082
+ '--detail',
20083
+ 'full'
20084
+ ];
20085
+ let payload;
20086
+ try {
20087
+ payload = execDws(dwsPath, args);
20088
+ } catch (error) {
20089
+ if (error instanceof PrdDwsError && 'CONTENT_NOT_READY' === error.code) {
20090
+ prd_sleepSync(retryDelayMs);
20091
+ payload = execDws(dwsPath, args);
20092
+ } else throw error;
20093
+ }
20094
+ const content = src_prd_isRecord(payload['content']) ? payload['content'] : {};
20095
+ const jsonml = 'string' == typeof content['jsonml'] ? content['jsonml'] : '';
20096
+ if (0 === jsonml.trim().length) throw new PrdDwsError('CONTENT_EMPTY', 'PRD 文档 JSONML 正文为空,无法作为需求事实', hintOf('CONTENT_EMPTY'));
20097
+ return {
20098
+ nodeId: String(content['nodeId'] ?? nodeId),
20099
+ docUrl: String(content['docUrl'] ?? ''),
20100
+ title: String(content['title'] ?? ''),
20101
+ revision: String(content['revision'] ?? ''),
20102
+ jsonml
20103
+ };
20104
+ }
20105
+ function prdDirOf(layout, iteration) {
20106
+ const resolved = resolveIterationDir(layout.root, layout.iterationsRoot, iteration);
20107
+ return external_node_path_join(resolved.dir, "_prd");
20108
+ }
20109
+ function readJsonFile(path) {
20110
+ if (!external_node_fs_existsSync(path)) return null;
20111
+ try {
20112
+ return JSON.parse(readFileSync(path, 'utf8'));
20113
+ } catch {
20114
+ return null;
20115
+ }
20116
+ }
20117
+ function readSnapshot(prdDir) {
20118
+ const raw = readJsonFile(external_node_path_join(prdDir, PRD_SNAPSHOT_NAME));
20119
+ if (!src_prd_isRecord(raw) || !Array.isArray(raw['blocks'])) return null;
20120
+ return raw;
20121
+ }
20122
+ function readMeta(prdDir) {
20123
+ const raw = readJsonFile(external_node_path_join(prdDir, PRD_META_NAME));
20124
+ if (!src_prd_isRecord(raw)) return null;
20125
+ return raw;
20126
+ }
20127
+ function writeSnapshotFiles(prdDir, snapshot, meta) {
20128
+ mkdirSync(external_node_path_dirname(external_node_path_join(prdDir, PRD_SNAPSHOT_NAME)), {
20129
+ recursive: true
20130
+ });
20131
+ writeFileSync(external_node_path_join(prdDir, PRD_SNAPSHOT_NAME), `${JSON.stringify(snapshot, null, 2)}\n`, 'utf8');
20132
+ writeFileSync(external_node_path_join(prdDir, PRD_META_NAME), `${JSON.stringify(meta, null, 2)}\n`, 'utf8');
20133
+ }
20134
+ function splitRequirements(raw) {
20135
+ if (void 0 === raw) return [];
20136
+ const result = [];
20137
+ for (const item of raw.split(/[,,\s]+/)){
20138
+ const cleaned = item.trim();
20139
+ if (cleaned.length > 0 && !result.includes(cleaned)) result.push(cleaned);
20140
+ }
20141
+ return result;
20142
+ }
20143
+ function prd_prdBaseline(options) {
20144
+ const prdDir = prdDirOf(options.layout, options.iteration);
20145
+ if (void 0 === options.node || 0 === options.node.trim().length) throw new PrdDwsError('NODE_MISSING', 'baseline 必须提供 --node(PRD 链接或 nodeId)');
20146
+ const documentMeta = probePrd(options.dwsPath, options.node);
20147
+ const existing = readMeta(prdDir);
20148
+ const sameRevision = null !== existing && Number(existing.updateTime ?? 0) === documentMeta.updateTime && existing.nodeId === documentMeta.nodeId;
20149
+ if (sameRevision && true !== options.force) return {
20150
+ exitCode: 0,
20151
+ result: {
20152
+ status: 'unchanged_baseline',
20153
+ mode: 'baseline',
20154
+ iteration: options.iteration,
20155
+ prdDirectory: prdDir,
20156
+ nodeId: documentMeta.nodeId,
20157
+ document: {
20158
+ title: documentMeta.title,
20159
+ updateTime: documentMeta.updateTime,
20160
+ updateTimeText: formatTimestamp(documentMeta.updateTime)
20161
+ },
20162
+ message: '基线与当前文档 updateTime 一致,未覆盖快照;如需强制重建请加 --force。'
20163
+ }
20164
+ };
20165
+ const document = fetchPrd(options.dwsPath, options.node);
20166
+ const snapshot = buildSnapshot({
20167
+ document,
20168
+ updateTime: documentMeta.updateTime,
20169
+ iteration: options.iteration
20170
+ });
20171
+ const meta = buildMeta(snapshot);
20172
+ writeSnapshotFiles(prdDir, snapshot, meta);
20173
+ const warnings = [];
20174
+ if ((meta.changelog.rowCount ?? 0) === 0) warnings.push('未识别到「变更记录」表格数据行:后续只能依赖章节摘要判定变更,无法给出产品登记的变更清单。');
20175
+ if (0 === Object.keys(meta.requirements).length) warnings.push('标题中未识别到需求编号:请确认 PRD 是否按「需求编号」组织章节。');
20176
+ for (const declaredId of Object.keys(meta.declaredRequirements))warnings.push(`需求 ${declaredId} 仅在正文中被声明,PRD 中无独立章节,无法按章节 diff。`);
20177
+ const wanted = splitRequirements(options.requirements);
20178
+ if (wanted.length > 0) {
20179
+ const missing = wanted.filter((id)=>void 0 === meta.requirements[id]);
20180
+ if (missing.length > 0) warnings.push(`以下需求编号在当前 PRD 中未找到对应章节:${missing.join(', ')}。`);
20181
+ }
20182
+ return {
20183
+ exitCode: 0,
20184
+ result: {
20185
+ status: 'success',
20186
+ mode: 'baseline',
20187
+ iteration: options.iteration,
20188
+ prdDirectory: prdDir,
20189
+ nodeId: document.nodeId,
20190
+ document: {
20191
+ title: document.title,
20192
+ docUrl: document.docUrl,
20193
+ revision: document.revision,
20194
+ updateTime: meta.updateTime,
20195
+ updateTimeText: meta.updateTimeText,
20196
+ blockCount: meta.blockCount,
20197
+ changelogRows: meta.changelog.rowCount
20198
+ },
20199
+ requirements: Object.fromEntries(Object.entries(meta.requirements).map(([id, entry])=>[
20200
+ id,
20201
+ {
20202
+ heading: entry.heading,
20203
+ sectionNo: entry.sectionNo,
20204
+ blockCount: entry.blockCount
20205
+ }
20206
+ ])),
20207
+ warnings,
20208
+ nextCommands: [
20209
+ `ylcwf prd delta -i ${options.iteration}`
20210
+ ]
20211
+ }
20212
+ };
20213
+ }
20214
+ function prd_prdDelta(options) {
20215
+ const prdDir = prdDirOf(options.layout, options.iteration);
20216
+ const meta = readMeta(prdDir);
20217
+ const snapshot = readSnapshot(prdDir);
20218
+ const requested = splitRequirements(options.requirement);
20219
+ const hasBaseline = null !== meta && null !== snapshot;
20220
+ const node = options.node ?? meta?.nodeId;
20221
+ if (!hasBaseline) {
20222
+ 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');
20223
+ const documentMeta = probePrd(options.dwsPath, node);
20224
+ const document = fetchPrd(options.dwsPath, node);
20225
+ const current = buildSnapshot({
20226
+ document,
20227
+ updateTime: documentMeta.updateTime,
20228
+ iteration: options.iteration
20229
+ });
20230
+ return {
20231
+ exitCode: 0,
20232
+ result: {
20233
+ status: 'no_baseline',
20234
+ mode: 'delta',
20235
+ iteration: options.iteration,
20236
+ prdDirectory: prdDir,
20237
+ nonPrecise: true,
20238
+ document: {
20239
+ nodeId: current.nodeId,
20240
+ title: current.title,
20241
+ revision: current.revision,
20242
+ updateTime: current.updateTime,
20243
+ updateTimeText: current.updateTimeText,
20244
+ blockCount: current.blockCount
20245
+ },
20246
+ warnings: [
20247
+ '当前没有可用快照,本次为全量现状,无法给出变更判定;建议执行 ylcwf prd baseline 建立基线。'
20248
+ ],
20249
+ nextCommands: [
20250
+ `ylcwf prd baseline -i ${options.iteration} --node ${current.nodeId}`
20251
+ ]
20252
+ }
20253
+ };
20254
+ }
20255
+ const baselineUpdate = Number(meta.updateTime ?? 0);
20256
+ const documentMeta = probePrd(options.dwsPath, node ?? meta.nodeId);
20257
+ const currentUpdate = documentMeta.updateTime;
20258
+ if (baselineUpdate === currentUpdate && true !== options.force) return {
20259
+ exitCode: 0,
20260
+ result: {
20261
+ status: 'unchanged',
20262
+ mode: 'delta',
20263
+ iteration: options.iteration,
20264
+ nodeId: meta.nodeId,
20265
+ nonPrecise: false,
20266
+ document: {
20267
+ title: meta.title,
20268
+ revision: meta.revision,
20269
+ updateTime: currentUpdate,
20270
+ updateTimeText: formatTimestamp(currentUpdate)
20271
+ },
20272
+ baseline: {
20273
+ revision: meta.revision,
20274
+ updateTime: baselineUpdate,
20275
+ updateTimeText: formatTimestamp(baselineUpdate)
20276
+ },
20277
+ message: 'PRD updateTime 与快照一致,未检测到文档更新;如需强制重拉请加 --force。',
20278
+ warnings: []
20279
+ }
20280
+ };
20281
+ const document = fetchPrd(options.dwsPath, options.node ?? meta.nodeId);
20282
+ const current = buildSnapshot({
20283
+ document,
20284
+ updateTime: currentUpdate,
20285
+ iteration: options.iteration
20286
+ });
20287
+ const oldBlocks = snapshot.blocks ?? [];
20288
+ const newBlocks = current.blocks;
20289
+ const oldRequirements = snapshot.requirements ?? {};
20290
+ const newRequirements = current.requirements;
20291
+ const oldChangelog = snapshot.changelog ?? {
20292
+ start: 0,
20293
+ end: -1,
20294
+ rows: [],
20295
+ digest: ''
20296
+ };
20297
+ const newChangelog = current.changelog;
20298
+ const oldRowKeys = new Set((oldChangelog.rows ?? []).map((cells)=>cells.join(' | ')));
20299
+ const newRowKeys = new Set((newChangelog?.rows ?? []).map((cells)=>cells.join(' | ')));
20300
+ const addedRows = (newChangelog?.rows ?? []).filter((cells)=>!oldRowKeys.has(cells.join(' | ')));
20301
+ const removedRows = (oldChangelog.rows ?? []).filter((cells)=>!newRowKeys.has(cells.join(' | ')));
20302
+ const targets = requested.length > 0 ? requested : [
20303
+ ...new Set([
20304
+ ...Object.keys(oldRequirements),
20305
+ ...Object.keys(newRequirements)
20306
+ ])
20307
+ ];
20308
+ const warnings = [];
20309
+ const verdicts = [];
20310
+ const changedBlocks = [];
20311
+ const maxDiffLines = options.maxDiffLines ?? 120;
20312
+ const maxChanged = options.maxChangedRequirements ?? 5;
20313
+ for (const requirementId of targets){
20314
+ const oldEntry = oldRequirements[requirementId];
20315
+ const newEntry = newRequirements[requirementId];
20316
+ if (void 0 === oldEntry && void 0 === newEntry) {
20317
+ warnings.push(`需求 ${requirementId} 在当前 PRD 与快照中都不存在,请核对编号。`);
20318
+ verdicts.push({
20319
+ requirement: requirementId,
20320
+ verdict: 'unknown_requirement',
20321
+ registered: false,
20322
+ changed: false,
20323
+ evidence: []
20324
+ });
20325
+ continue;
20326
+ }
20327
+ const sectionNo = newEntry?.sectionNo ?? oldEntry?.sectionNo ?? null;
20328
+ const registeredRows = matchedRows(addedRows.map((cells)=>[
20329
+ ...cells
20330
+ ]), requirementId, sectionNo);
20331
+ const registered = registeredRows.length > 0;
20332
+ const changed = oldEntry?.digest !== newEntry?.digest;
20333
+ let verdict = 'unchanged';
20334
+ if (registered && changed) verdict = 'registered_and_changed';
20335
+ else if (registered && !changed) verdict = 'registered_not_changed';
20336
+ else if (changed) {
20337
+ verdict = 'unregistered_change';
20338
+ warnings.push(`需求 ${requirementId} 正文已变化,但变更记录没有对应新增条目(疑似静默改稿),必须人工确认。`);
20339
+ }
20340
+ verdicts.push({
20341
+ requirement: requirementId,
20342
+ verdict,
20343
+ registered,
20344
+ changed,
20345
+ heading: newEntry?.heading ?? oldEntry?.heading ?? null,
20346
+ sectionNo,
20347
+ evidence: registeredRows.map((row)=>row.row)
20348
+ });
20349
+ if (changed && changedBlocks.length < maxChanged) {
20350
+ const diff = blockDiff({
20351
+ oldBlocks,
20352
+ newBlocks,
20353
+ oldRange: void 0 === oldEntry ? [
20354
+ 0,
20355
+ -1
20356
+ ] : [
20357
+ oldEntry.start,
20358
+ oldEntry.end
20359
+ ],
20360
+ newRange: void 0 === newEntry ? [
20361
+ 0,
20362
+ -1
20363
+ ] : [
20364
+ newEntry.start,
20365
+ newEntry.end
20366
+ ],
20367
+ maxLines: maxDiffLines
20368
+ });
20369
+ changedBlocks.push({
20370
+ ...diff,
20371
+ requirement: requirementId,
20372
+ heading: newEntry?.heading ?? oldEntry?.heading ?? null,
20373
+ status: void 0 !== oldEntry && void 0 !== newEntry ? 'modified' : void 0 !== newEntry ? 'added' : 'removed'
20374
+ });
20375
+ }
20376
+ }
20377
+ if (removedRows.length > 0) warnings.push('变更记录中存在被删除或改写的行,请确认是产品整理还是回滚。');
20378
+ return {
20379
+ exitCode: 0,
20380
+ result: {
20381
+ status: 0 === addedRows.length && 0 === changedBlocks.length ? 'formatting_only' : 'success',
20382
+ mode: 'delta',
20383
+ iteration: options.iteration,
20384
+ prdDirectory: prdDir,
20385
+ nodeId: current.nodeId,
20386
+ nonPrecise: false,
20387
+ document: {
20388
+ title: current.title,
20389
+ docUrl: current.docUrl,
20390
+ revision: current.revision,
20391
+ updateTime: currentUpdate,
20392
+ updateTimeText: formatTimestamp(currentUpdate)
20393
+ },
20394
+ baseline: {
20395
+ revision: meta.revision,
20396
+ updateTime: baselineUpdate,
20397
+ updateTimeText: formatTimestamp(baselineUpdate),
20398
+ changelogRowCount: (oldChangelog.rows ?? []).length
20399
+ },
20400
+ changelog: {
20401
+ available: null !== newChangelog,
20402
+ addedCount: addedRows.length,
20403
+ removedCount: removedRows.length,
20404
+ added: addedRows.map((cells)=>describeRow(cells)),
20405
+ removed: removedRows.map((cells)=>describeRow(cells))
20406
+ },
20407
+ changedBlocks,
20408
+ verdicts,
20409
+ warnings,
20410
+ nextCommands: [
20411
+ `ylcwf prd baseline -i ${options.iteration} --node ${current.nodeId} --force`
20412
+ ]
20413
+ }
20414
+ };
20415
+ }
20416
+ function prdCheck(options) {
20417
+ const prdDir = prdDirOf(options.layout, options.iteration);
20418
+ const meta = readMeta(prdDir);
20419
+ const snapshot = readSnapshot(prdDir);
20420
+ const problems = [];
20421
+ const warnings = [];
20422
+ if (null === meta || null === snapshot) {
20423
+ const missing = [
20424
+ ...null === meta ? [
20425
+ PRD_META_NAME
20426
+ ] : [],
20427
+ ...null === snapshot ? [
20428
+ PRD_SNAPSHOT_NAME
20429
+ ] : []
20430
+ ];
20431
+ return {
20432
+ exitCode: 1,
20433
+ result: {
20434
+ status: 'no_baseline',
20435
+ mode: 'check',
20436
+ iteration: options.iteration,
20437
+ prdDirectory: prdDir,
20438
+ problems: [
20439
+ `缺少基线文件:${missing.join(', ')}`
20440
+ ],
20441
+ warnings: []
20442
+ }
20443
+ };
20444
+ }
20445
+ if (snapshot.schemaVersion !== PRD_SNAPSHOT_SCHEMA_VERSION) warnings.push(`snapshot.json 的结构标识为「${snapshot.schemaVersion}」,当前版本期望「${PRD_SNAPSHOT_SCHEMA_VERSION}」;建议 baseline --force 重建。`);
20446
+ if (meta.schemaVersion !== PRD_META_SCHEMA_VERSION) warnings.push(`meta.json 的结构标识为「${meta.schemaVersion}」,当前版本期望「${PRD_META_SCHEMA_VERSION}」;建议 baseline --force 重建。`);
20447
+ const blocks = snapshot.blocks ?? [];
20448
+ if (Number(snapshot.blockCount ?? 0) !== blocks.length) problems.push('snapshot.blockCount 与 blocks 实际数量不一致');
20449
+ for (const [requirementId, entry] of Object.entries(snapshot.requirements ?? {})){
20450
+ if (entry.start < 0 || entry.end >= blocks.length || entry.start > entry.end) {
20451
+ problems.push(`需求 ${requirementId} 的块区间越界:${entry.start}..${entry.end}`);
20452
+ continue;
20453
+ }
20454
+ if (pagesDigest(blocks.slice(entry.start, entry.end + 1)) !== entry.digest) problems.push(`需求 ${requirementId} 的块区间摘要与 digest 不一致`);
20455
+ }
20456
+ const recomputedChangelog = findChangelog(blocks);
20457
+ if ((recomputedChangelog?.digest ?? null) !== (snapshot.changelog?.digest ?? null)) problems.push('snapshot.changelog 的 digest 与块内容不一致');
20458
+ const metaRequirements = meta.requirements ?? {};
20459
+ const snapshotRequirements = snapshot.requirements ?? {};
20460
+ if (Object.keys(metaRequirements).sort().join(',') !== Object.keys(snapshotRequirements).sort().join(',')) warnings.push('meta.json 与 snapshot.json 的需求编号集合不一致,建议重建基线');
20461
+ else for (const [requirementId, entry] of Object.entries(metaRequirements))if (entry.digest !== snapshotRequirements[requirementId]?.digest) problems.push(`需求 ${requirementId} 的 digest 在两份文件中不一致`);
20462
+ if (meta.revision !== snapshot.revision) problems.push('meta.json 与 snapshot.json 的 revision 不一致');
20463
+ return {
20464
+ exitCode: 0 === problems.length ? 0 : 1,
20465
+ result: {
20466
+ status: 0 === problems.length ? 'success' : 'broken',
20467
+ mode: 'check',
20468
+ iteration: options.iteration,
20469
+ prdDirectory: prdDir,
20470
+ nodeId: meta.nodeId,
20471
+ document: {
20472
+ title: meta.title,
20473
+ revision: meta.revision,
20474
+ updateTimeText: meta.updateTimeText,
20475
+ blockCount: meta.blockCount
20476
+ },
20477
+ problems,
20478
+ warnings
20479
+ }
20480
+ };
20481
+ }
20482
+ function positiveInteger(value, label, fallback) {
20483
+ if (void 0 === value) return fallback;
20484
+ const parsed = Number.parseInt(value, 10);
20485
+ if (!Number.isInteger(parsed) || parsed <= 0) throw new errors_CliError(`${label} 必须是正整数:${value}`, errors_EXIT.USAGE);
20486
+ return parsed;
20487
+ }
20488
+ function buildOptions(options) {
20489
+ const loaded = config_loadConfig(options.config);
20490
+ if (!loaded.exists || null === loaded.config) throw new errors_CliError(`配置未初始化:${loaded.path}\n请先运行:ylcwf init`, errors_EXIT.NOT_FOUND);
20491
+ const baseLayout = layoutOf(loaded.config);
20492
+ const layout = void 0 === options.docsRoot ? baseLayout : {
20493
+ ...baseLayout,
20494
+ root: external_node_path_resolve(options.docsRoot)
20495
+ };
20496
+ return {
20497
+ layout,
20498
+ iteration: options.iteration.trim(),
20499
+ dwsPath: (options.dwsPath ?? 'dws').trim()
20500
+ };
20501
+ }
20502
+ function printPrdHuman(result) {
20503
+ const mode = String(result['mode'] ?? '');
20504
+ printLine(`模式:${mode} 迭代:${String(result['iteration'] ?? '')} 状态:${String(result['status'] ?? '')}`);
20505
+ const document = result['document'];
20506
+ if ('object' == typeof document && null !== document) {
20507
+ const info = document;
20508
+ printLine(`文档:${String(info['title'] ?? '未提供')} revision ${String(info['revision'] ?? '—')} 更新时间:${String(info['updateTimeText'] ?? '—')}`);
20509
+ }
20510
+ const baseline = result['baseline'];
20511
+ if ('object' == typeof baseline && null !== baseline) {
20512
+ const info = baseline;
20513
+ printLine(`基线:revision ${String(info['revision'] ?? '—')} ${String(info['updateTimeText'] ?? '—')}`);
20514
+ }
20515
+ const changelog = result['changelog'];
20516
+ if ('delta' === mode && 'object' == typeof changelog && null !== changelog) {
20517
+ const info = changelog;
20518
+ printLine(`变更记录:新增 ${String(info['addedCount'] ?? 0)} 行,删除或改写 ${String(info['removedCount'] ?? 0)} 行`);
20519
+ const added = Array.isArray(info['added']) ? info['added'] : [];
20520
+ for (const row of added)printLine(` + ${String(row['row'] ?? '')}`);
20521
+ }
20522
+ const verdicts = Array.isArray(result['verdicts']) ? result['verdicts'] : [];
20523
+ if (verdicts.length > 0) {
20524
+ printLine('四态判定:');
20525
+ for (const verdict of verdicts)printLine(` #${String(verdict['requirement'] ?? '')} ${String(verdict['heading'] ?? '')} → ${String(verdict['verdict'] ?? '')}`);
20526
+ }
20527
+ const changed = Array.isArray(result['changedBlocks']) ? result['changedBlocks'] : [];
20528
+ for (const block of changed){
20529
+ printLine('');
20530
+ printLine(`块级差异:#${String(block['requirement'] ?? '')} ${String(block['heading'] ?? '')}(+${String(block['addedBlocks'] ?? 0)}/-${String(block['removedBlocks'] ?? 0)})`);
20531
+ printLine(String(block['diff'] ?? ''));
20532
+ if (true === block['truncated']) printLine('... diff 已截断,可用 --max-diff-lines 放大');
20533
+ }
20534
+ const requirements = result['requirements'];
20535
+ if ('baseline' === mode && 'object' == typeof requirements && null !== requirements) {
20536
+ printLine('需求章节:');
20537
+ for (const [id, entry] of Object.entries(requirements))printLine(` #${id} ${String(entry['heading'] ?? '')}`);
20538
+ }
20539
+ for (const warning of Array.isArray(result['warnings']) ? result['warnings'] : [])printLine(`警告:${warning}`);
20540
+ for (const problem of Array.isArray(result['problems']) ? result['problems'] : [])printLine(`问题:${problem}`);
20541
+ if ('string' == typeof result['message']) printLine(`说明:${result['message']}`);
20542
+ for (const command of Array.isArray(result['nextCommands']) ? result['nextCommands'] : [])printLine(`下一步:${command}`);
20543
+ }
20544
+ function prd_run(handler, format, onSuccess) {
20545
+ let outcome;
20546
+ try {
20547
+ outcome = handler();
20548
+ } catch (error) {
20549
+ if (error instanceof PrdDwsError) {
20550
+ const payload = {
20551
+ status: 'failed',
20552
+ error: error.toDict()
20553
+ };
20554
+ if ('json' === format) printJson(payload);
20555
+ else {
20556
+ printLine(`失败:${error.code} ${error.message}`);
20557
+ if (error.hint.length > 0) printLine(`建议:${error.hint}`);
20558
+ }
20559
+ process.exitCode = errors_EXIT.INVALID;
20560
+ return;
20561
+ }
20562
+ throw error;
20563
+ }
20564
+ if ('json' === format) printJson(outcome.result);
20565
+ else printPrdHuman(outcome.result);
20566
+ if (0 !== outcome.exitCode) process.exitCode = outcome.exitCode;
20567
+ onSuccess?.(outcome.exitCode);
20568
+ }
20569
+ function registerPrd(program) {
20570
+ const prd = program.command('prd').description('钉钉 PRD 快照与变更检测(通过本机 dws 取数)');
20571
+ 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');
20572
+ common(prd.command('baseline')).description('生成/刷新 PRD 快照(updateTime 未变且未加 --force 时不拉全文)').requiredOption('--node <node>', 'PRD 文档链接或 nodeId').option('--requirements <ids>', '关注的需求编号,逗号分隔(仅用于命中校验)').option('--force', 'updateTime 未变时也重建快照').action((options)=>{
20573
+ const format = parseFormat(options.format);
20574
+ enableJsonErrors('json' === format);
20575
+ const base = buildOptions(options);
20576
+ prd_run(()=>prd_prdBaseline({
20577
+ ...base,
20578
+ force: true === options.force,
20579
+ node: options.node,
20580
+ requirements: options.requirements
20581
+ }), format);
20582
+ });
20583
+ 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)=>{
20584
+ const format = parseFormat(options.format);
20585
+ enableJsonErrors('json' === format);
20586
+ const base = buildOptions(options);
20587
+ prd_run(()=>prd_prdDelta({
20588
+ ...base,
20589
+ force: true === options.force,
20590
+ node: options.node,
20591
+ requirement: options.requirement,
20592
+ maxDiffLines: positiveInteger(options.maxDiffLines, '--max-diff-lines', 120),
20593
+ maxChangedRequirements: positiveInteger(options.maxChangedRequirements, '--max-changed-requirements', 5)
20594
+ }), format);
20595
+ });
20596
+ common(prd.command('check')).description('校验快照文件完整性(只读,不调用 dws)').action((options)=>{
20597
+ const format = parseFormat(options.format);
20598
+ enableJsonErrors('json' === format);
20599
+ const base = buildOptions(options);
20600
+ prd_run(()=>prdCheck(base), format);
20601
+ });
20602
+ }
17998
20603
  async function runReset(options) {
17999
20604
  const configPath = paths_resolveConfigPath(options.config);
18000
- const targets = collectResetTargets(configPath);
18001
- if (0 === targets.length) return void printLine('没有需要清除的配置,当前已经是干净状态。');
20605
+ const removeBackups = true === options.all;
20606
+ const targets = collectResetTargets(configPath, {
20607
+ removeBackups
20608
+ });
20609
+ const kept = removeBackups ? null : backupsTarget(configPath);
20610
+ if (0 === targets.length) {
20611
+ printLine('没有需要清除的配置,当前已经是干净状态。');
20612
+ if (null !== kept) printLine(`备份仍保留:${kept.path}(如需一并删除,加 --all)`);
20613
+ return;
20614
+ }
18002
20615
  printLine('将要清除:');
18003
20616
  for (const target of targets)printLine(` - ${describeTarget(target)}`);
20617
+ if (null !== kept) {
20618
+ printLine('');
20619
+ printLine(`备份保留:${kept.path}(${countBackups(configPath)} 项)`);
20620
+ printLine(' 备份可用于回滚;如需一并删除,加 --all');
20621
+ }
18004
20622
  if (true === options.dryRun) return void printLine('\n(--dry-run:未执行任何删除)');
18005
20623
  if (true !== options.yes) {
18006
20624
  if (true !== process.stdin.isTTY) throw new errors_CliError('非交互环境需要显式加 --yes 才会执行删除', errors_EXIT.USAGE);
@@ -18012,15 +20630,16 @@ async function runReset(options) {
18012
20630
  }
18013
20631
  const removed = performReset(configPath, targets);
18014
20632
  printLine(`\n已清除 ${removed} 项。下次打开工作台会重新进入首次引导。`);
20633
+ if (null !== kept) printLine(`备份已保留:${kept.path}(如需一并清空,加 --all)`);
18015
20634
  }
18016
20635
  function registerReset(program) {
18017
- program.command('reset').description('清除本机配置(配置与备份),用于从零重新引导').option('-c, --config <path>', '指定配置文件路径').option('--yes', '跳过确认').option('--dry-run', '只列出将要删除的内容').action(async (options)=>{
20636
+ program.command('reset').description('清除本机配置(默认保留配置备份),用于从零重新引导').option('-c, --config <path>', '指定配置文件路径').option('--yes', '跳过确认').option('--dry-run', '只列出将要删除的内容').option('--all', '连配置备份一起删除(默认保留,可回滚)').action(async (options)=>{
18018
20637
  await runReset(options);
18019
20638
  });
18020
20639
  }
18021
20640
  function buildProgram() {
18022
20641
  const program = new command_Command();
18023
- program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与执行终端仓库映射').version("0.7.0", '-v, --version', '显示版本号').showHelpAfterError();
20642
+ program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与执行终端仓库映射').version("0.9.0", '-v, --version', '显示版本号').showHelpAfterError();
18024
20643
  registerInit(program);
18025
20644
  registerShow(program);
18026
20645
  registerGet(program);
@@ -18028,6 +20647,7 @@ function buildProgram() {
18028
20647
  registerTerminal(program);
18029
20648
  registerIteration(program);
18030
20649
  registerContext(program);
20650
+ registerGuide(program);
18031
20651
  registerRequirement(program);
18032
20652
  registerDoc(program);
18033
20653
  registerTask(program);
@@ -18037,6 +20657,7 @@ function buildProgram() {
18037
20657
  registerPath(program);
18038
20658
  registerServe(program);
18039
20659
  registerYapi(program);
20660
+ registerPrd(program);
18040
20661
  registerReset(program);
18041
20662
  return program;
18042
20663
  }
@@ -18090,7 +20711,7 @@ async function main() {
18090
20711
  main().catch((error)=>{
18091
20712
  const exitCode = error instanceof errors_CliError ? error.exitCode : errors_EXIT.INVALID;
18092
20713
  const message = error instanceof errors_CliError ? error.message : error instanceof Error ? error.message ?? String(error) : String(error);
18093
- if (jsonErrorsEnabled()) printJsonError(message, exitCode);
20714
+ if (jsonErrorsEnabled()) printJsonError(message, exitCode, error instanceof errors_CliError ? error.details : void 0);
18094
20715
  else error instanceof errors_CliError ? printError(message) : printError(error instanceof Error ? error.stack ?? message : message);
18095
20716
  process.exit(exitCode);
18096
20717
  });