ylcwf 0.4.0 → 0.5.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
@@ -9283,6 +9283,9 @@ function isStringArray(value) {
9283
9283
  function parsePathList(input) {
9284
9284
  return input.split(/[,,;;]/).map((item)=>item.trim()).filter((item)=>item.length > 0);
9285
9285
  }
9286
+ function escapeRegExp(input) {
9287
+ return input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
9288
+ }
9286
9289
  const ROLES = [
9287
9290
  'frontend',
9288
9291
  'backend',
@@ -10602,566 +10605,800 @@ function registerTerminal(program) {
10602
10605
  runTerminalRepoRemove(key, options);
10603
10606
  });
10604
10607
  }
10605
- const SAFE_SEGMENT = /^[A-Za-z0-9._\-\u4e00-\u9fa5]+$/;
10606
- function safeSegment(value, label) {
10607
- const trimmed = value.trim();
10608
- if (!SAFE_SEGMENT.test(trimmed) || '.' === trimmed || '..' === trimmed) throw new errors_CliError(`${label} 不合法:${value}`, errors_EXIT.USAGE);
10609
- return trimmed;
10610
- }
10611
- function buildCommitMessage(iteration, action, taskIds, _action) {
10612
- const meta = ACTION_META[action];
10613
- return `docs(${iteration}): ${meta.label} ${taskIds.join(',')}(${meta.from}→${meta.to})`;
10614
- }
10615
- function nowStamp() {
10616
- const now = new Date();
10617
- const pad = (value)=>String(value).padStart(2, '0');
10618
- return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
10608
+ function normalizeIterationKey(value) {
10609
+ return value.trim().toLowerCase().replace(/[-_.\s]+/g, '-');
10619
10610
  }
10620
- const ACTION_META = {
10621
- start: {
10622
- label: '开始实施',
10623
- from: '未开始',
10624
- to: '进行中'
10625
- },
10626
- submit: {
10627
- label: '提交验收',
10628
- from: '进行中',
10629
- to: '待验收'
10630
- },
10631
- accept: {
10632
- label: '验收通过',
10633
- from: '待验收',
10634
- to: '已完成'
10635
- },
10636
- reject: {
10637
- label: '验收驳回',
10638
- from: '待验收',
10639
- to: '进行中'
10611
+ function currentBranch(docsRoot) {
10612
+ try {
10613
+ const output = execFileSync('git', [
10614
+ 'rev-parse',
10615
+ '--abbrev-ref',
10616
+ 'HEAD'
10617
+ ], {
10618
+ cwd: docsRoot,
10619
+ encoding: 'utf8',
10620
+ stdio: [
10621
+ 'ignore',
10622
+ 'pipe',
10623
+ 'pipe'
10624
+ ]
10625
+ });
10626
+ const branch = output.trim();
10627
+ if (0 === branch.length || 'HEAD' === branch) return null;
10628
+ return branch;
10629
+ } catch (error) {
10630
+ const message = error instanceof Error ? error.message.split('\n')[0] ?? '' : String(error);
10631
+ if (message.includes('not a git repository')) throw new errors_CliError(`${docsRoot} 不是 git 仓库,无法读取当前分支`, errors_EXIT.NOT_FOUND);
10632
+ return null;
10640
10633
  }
10641
- };
10642
- function commitInDocsRepo(docsRoot, file, message, push) {
10643
- const run = (args)=>{
10644
- try {
10645
- const output = execFileSync('git', args, {
10646
- cwd: docsRoot,
10647
- encoding: 'utf8',
10648
- stdio: [
10649
- 'ignore',
10650
- 'pipe',
10651
- 'pipe'
10652
- ]
10653
- });
10654
- return {
10655
- ok: true,
10656
- output
10657
- };
10658
- } catch (error) {
10659
- const stderr = error.stderr ?? '';
10660
- return {
10661
- ok: false,
10662
- output: stderr.trim() || String(error)
10663
- };
10664
- }
10634
+ }
10635
+ function resolveIterationFromBranch(docsRoot, iterations) {
10636
+ const branch = currentBranch(docsRoot);
10637
+ if (null === branch) return {
10638
+ branch: null,
10639
+ iteration: null,
10640
+ candidates: []
10665
10641
  };
10666
- const inside = run([
10667
- 'rev-parse',
10668
- '--is-inside-work-tree'
10669
- ]);
10670
- if (!inside.ok || 'true' !== inside.output.trim()) return {
10671
- committed: false,
10672
- pushed: false,
10673
- message: '文档仓库不是 git 仓库,已跳过提交'
10642
+ const key = normalizeIterationKey(branch);
10643
+ const all = iterations.map((name)=>({
10644
+ name,
10645
+ key: normalizeIterationKey(name)
10646
+ })).filter((item)=>item.key.length > 0).filter((item)=>key === item.key || key.endsWith(`-${item.key}`) || key.endsWith(`/${item.key}`)).sort((left, right)=>right.key.length - left.key.length);
10647
+ if (0 === all.length) return {
10648
+ branch,
10649
+ iteration: null,
10650
+ candidates: []
10674
10651
  };
10675
- let realRoot = docsRoot;
10676
- let realFile = file;
10677
- try {
10678
- realRoot = realpathSync(docsRoot);
10679
- realFile = realpathSync(file);
10680
- } catch {}
10681
- const relativePath = external_node_path_relative(realRoot, realFile);
10682
- if (relativePath.startsWith('..') || isAbsolute(relativePath)) return {
10683
- committed: false,
10684
- pushed: false,
10685
- message: '目标文件不在文档仓库内,已跳过提交'
10652
+ const best = all[0];
10653
+ if (void 0 === best) return {
10654
+ branch,
10655
+ iteration: null,
10656
+ candidates: []
10686
10657
  };
10687
- const added = run([
10688
- 'add',
10689
- '--',
10690
- relativePath
10691
- ]);
10692
- if (!added.ok) return {
10693
- committed: false,
10694
- pushed: false,
10695
- message: `git add 失败:${added.output.split('\n')[0] ?? ''}`
10658
+ const tied = all.filter((item)=>item.key.length === best.key.length).map((item)=>item.name);
10659
+ if (tied.length > 1) return {
10660
+ branch,
10661
+ iteration: null,
10662
+ candidates: tied
10696
10663
  };
10697
- const committed = run([
10698
- 'commit',
10699
- '-m',
10700
- message,
10701
- '--',
10702
- relativePath
10703
- ]);
10704
- if (!committed.ok) {
10705
- const firstLine = committed.output.split('\n')[0] ?? '';
10706
- return {
10707
- committed: false,
10708
- pushed: false,
10709
- message: `提交未完成:${firstLine}`
10664
+ return {
10665
+ branch,
10666
+ iteration: best.name,
10667
+ candidates: []
10668
+ };
10669
+ }
10670
+ const PROTECTED_BRANCHES = new Set([
10671
+ 'main',
10672
+ 'master'
10673
+ ]);
10674
+ function assertWritableBranch(docsRoot) {
10675
+ const branch = currentBranch(docsRoot);
10676
+ if (null === branch) throw new errors_CliError("文档仓库处于 detached HEAD,无法确认所在分支,写操作已拒绝。\n请先切到迭代分支再重试:git switch <分支>", errors_EXIT.INVALID);
10677
+ if (PROTECTED_BRANCHES.has(branch.toLowerCase())) throw new errors_CliError(`文档仓库当前在 ${branch} 分支,禁止直接修改文档。\n请先切到该迭代的分支再重试,例如:\n git switch -c feature_<迭代名>`, errors_EXIT.INVALID);
10678
+ }
10679
+ const TASK_TYPE_GROUPS = [
10680
+ 'frontend',
10681
+ 'backend'
10682
+ ];
10683
+ const SUPPORTED_SCHEMA_VERSION = 1;
10684
+ const SCHEMA_FILENAME = 'schema.json';
10685
+ function docSchemaPath(docsRoot) {
10686
+ return external_node_path_join(docsRoot, SCHEMA_FILENAME);
10687
+ }
10688
+ function fail(docsRoot, reason) {
10689
+ throw new errors_CliError(`文档仓库的 ${SCHEMA_FILENAME} 不可用:${reason}\n路径:${docSchemaPath(docsRoot)}\n该文件是文档格式的唯一来源,请拉取文档仓库最新版本后重试。`, errors_EXIT.NOT_FOUND);
10690
+ }
10691
+ function requireStringArray(value, where, docsRoot) {
10692
+ if (!Array.isArray(value) || 0 === value.length) fail(docsRoot, `${where} 必须是非空字符串数组`);
10693
+ return value.map((item, index)=>{
10694
+ if ('string' != typeof item || 0 === item.trim().length) fail(docsRoot, `${where}[${index}] 必须是非空字符串`);
10695
+ return item;
10696
+ });
10697
+ }
10698
+ function requireString(value, where, docsRoot) {
10699
+ if ('string' != typeof value || 0 === value.trim().length) fail(docsRoot, `${where} 必须是非空字符串`);
10700
+ return value;
10701
+ }
10702
+ function requireRecord(value, where, docsRoot) {
10703
+ if ('object' != typeof value || null === value || Array.isArray(value)) fail(docsRoot, `${where} 必须是对象`);
10704
+ return value;
10705
+ }
10706
+ function parseDocSchema(raw, docsRoot) {
10707
+ const data = requireRecord(raw, 'schema', docsRoot);
10708
+ const version = data.schemaVersion;
10709
+ if ('number' != typeof version || !Number.isInteger(version)) fail(docsRoot, 'schemaVersion 必须是整数');
10710
+ if (version > SUPPORTED_SCHEMA_VERSION) fail(docsRoot, `schemaVersion ${version} 高于当前 ylcwf 支持的 ${SUPPORTED_SCHEMA_VERSION},请升级 ylcwf`);
10711
+ const requirementTable = requireRecord(data.requirementTable, 'requirementTable', docsRoot);
10712
+ const taskTable = requireRecord(data.taskTable, 'taskTable', docsRoot);
10713
+ const progressRaw = requirementTable.progressRange;
10714
+ let progressRange = [
10715
+ 0,
10716
+ 100
10717
+ ];
10718
+ if (void 0 !== progressRaw) {
10719
+ if (!Array.isArray(progressRaw) || 2 !== progressRaw.length) fail(docsRoot, 'requirementTable.progressRange 必须是 [最小值, 最大值]');
10720
+ const [low, high] = progressRaw;
10721
+ if ('number' != typeof low || 'number' != typeof high) fail(docsRoot, 'requirementTable.progressRange 必须是数字');
10722
+ progressRange = [
10723
+ low,
10724
+ high
10725
+ ];
10726
+ }
10727
+ const enumsRaw = requireRecord(data.enums, 'enums', docsRoot);
10728
+ const taskTypesRaw = requireRecord(data.taskTypes, 'taskTypes', docsRoot);
10729
+ const taskTypes = {};
10730
+ for (const group of TASK_TYPE_GROUPS){
10731
+ const items = taskTypesRaw[group];
10732
+ if (!Array.isArray(items) || 0 === items.length) fail(docsRoot, `taskTypes.${group} 必须是非空数组`);
10733
+ taskTypes[group] = items.map((item, index)=>{
10734
+ const entry = requireRecord(item, `taskTypes.${group}[${index}]`, docsRoot);
10735
+ return {
10736
+ name: requireString(entry.name, `taskTypes.${group}[${index}].name`, docsRoot),
10737
+ desc: requireString(entry.desc, `taskTypes.${group}[${index}].desc`, docsRoot)
10738
+ };
10739
+ });
10740
+ }
10741
+ for (const group of TASK_TYPE_GROUPS){
10742
+ const seenInGroup = new Set();
10743
+ for (const item of taskTypes[group]){
10744
+ if (seenInGroup.has(item.name)) fail(docsRoot, `taskTypes.${group} 内任务类型重复:${item.name}`);
10745
+ seenInGroup.add(item.name);
10746
+ }
10747
+ }
10748
+ const rolesRaw = requireRecord(data.roles, 'roles', docsRoot);
10749
+ const roles = {};
10750
+ for (const [role, value] of Object.entries(rolesRaw)){
10751
+ const where = `roles.${role}`;
10752
+ const entry = requireRecord(value, where, docsRoot);
10753
+ const groups = requireStringArray(entry.taskTypeGroups, `${where}.taskTypeGroups`, docsRoot);
10754
+ for (const group of groups)if (!TASK_TYPE_GROUPS.includes(group)) fail(docsRoot, `${where}.taskTypeGroups 引用了未知分组:${group}`);
10755
+ roles[role] = {
10756
+ scope: requireString(entry.scope, `${where}.scope`, docsRoot),
10757
+ scopeRequires: requireStringArray(entry.scopeRequires, `${where}.scopeRequires`, docsRoot),
10758
+ detailFields: void 0 === entry.detailFields ? [] : requireStringArray(entry.detailFields, `${where}.detailFields`, docsRoot),
10759
+ taskTypeGroups: groups
10710
10760
  };
10711
10761
  }
10712
- if (!push) return {
10713
- committed: true,
10714
- pushed: false,
10715
- message: '已提交(未推送)'
10716
- };
10717
- const pushed = run([
10718
- 'push'
10719
- ]);
10720
- if (!pushed.ok) return {
10721
- committed: true,
10722
- pushed: false,
10723
- message: `已提交但推送失败,请手动处理:${pushed.output.split('\n')[0] ?? ''}`
10724
- };
10762
+ if (0 === Object.keys(roles).length) fail(docsRoot, 'roles 不能为空');
10763
+ const scopeEnumRaw = taskTable.scopeEnum;
10764
+ const scopeEnum = requireStringArray(scopeEnumRaw, 'taskTable.scopeEnum', docsRoot);
10765
+ for (const value of scopeEnum){
10766
+ const matched = Object.entries(roles).filter(([, config])=>config.scope === value);
10767
+ if (1 !== matched.length) fail(docsRoot, `所属端「${value}」需唯一对应一个 roles.* 角色,实际匹配:${matched.length} 个`);
10768
+ const owner = matched[0];
10769
+ if (void 0 === owner || 0 === owner[1].detailFields.length) fail(docsRoot, `roles.${owner?.[0] ?? '?'} 负责所属端「${value}」,必须声明 detailFields`);
10770
+ }
10725
10771
  return {
10726
- committed: true,
10727
- pushed: true,
10728
- message: '已提交并推送'
10772
+ version,
10773
+ sections: requireStringArray(data.sections, 'sections', docsRoot),
10774
+ iterationFields: requireStringArray(data.iterationFields, 'iterationFields', docsRoot),
10775
+ requirementHeaders: requireStringArray(requirementTable.headers, 'requirementTable.headers', docsRoot),
10776
+ requirementIdPattern: requireString(requirementTable.idPattern, 'requirementTable.idPattern', docsRoot),
10777
+ progressRange,
10778
+ taskHeaders: requireStringArray(taskTable.headers, 'taskTable.headers', docsRoot),
10779
+ taskIdPattern: requireString(taskTable.idPattern, 'taskTable.idPattern', docsRoot),
10780
+ taskScopeEnum: requireStringArray(taskTable.scopeEnum, 'taskTable.scopeEnum', docsRoot),
10781
+ enums: {
10782
+ requirementStatus: requireStringArray(enumsRaw.requirementStatus, 'enums.requirementStatus', docsRoot),
10783
+ taskStatus: requireStringArray(enumsRaw.taskStatus, 'enums.taskStatus', docsRoot),
10784
+ selfTest: requireStringArray(enumsRaw.selfTest, 'enums.selfTest', docsRoot),
10785
+ acceptance: requireStringArray(enumsRaw.acceptance, 'enums.acceptance', docsRoot)
10786
+ },
10787
+ taskTypes,
10788
+ updatedAtFormat: requireString(data.updatedAtFormat, 'updatedAtFormat', docsRoot),
10789
+ roles
10729
10790
  };
10730
10791
  }
10731
- function appendHistory(entry) {
10792
+ function loadDocSchema(docsRoot) {
10793
+ const target = docSchemaPath(docsRoot);
10794
+ let text;
10732
10795
  try {
10733
- const target = historyPath();
10734
- mkdirSync(external_node_path_dirname(target), {
10735
- recursive: true
10736
- });
10737
- appendFileSync(target, `${JSON.stringify({
10738
- at: new Date().toISOString(),
10739
- ...entry
10740
- })}\n`, 'utf8');
10741
- } catch {}
10742
- }
10743
- function readTaskHistory(options) {
10744
- const target = historyPath();
10745
- if (!external_node_fs_existsSync(target)) return [];
10746
- const limit = options.limit ?? 5;
10747
- const lines = readFileSync(target, 'utf8').trim().split('\n').filter((line)=>line.length > 0);
10748
- const entries = [];
10749
- for(let index = lines.length - 1; index >= 0 && entries.length < limit; index -= 1){
10750
- const line = lines[index];
10751
- if (void 0 !== line) try {
10752
- const parsed = JSON.parse(line);
10753
- if (parsed.iteration.toLowerCase() !== options.iteration.toLowerCase()) continue;
10754
- if (parsed.developer !== options.developer) continue;
10755
- if (void 0 !== options.taskId && parsed.taskId !== options.taskId) continue;
10756
- entries.push(parsed);
10757
- } catch {
10758
- continue;
10759
- }
10796
+ text = readFileSync(target, 'utf8');
10797
+ } catch {
10798
+ fail(docsRoot, '文件不存在或不可读');
10760
10799
  }
10761
- return entries;
10762
- }
10763
- const TASK_HEADERS = {
10764
- id: '任务编号',
10765
- requirement: '关联需求编号',
10766
- selfTest: 'AI自测状态',
10767
- acceptance: '开发人工验收',
10768
- status: '任务状态',
10769
- updatedAt: '最后更新'
10770
- };
10771
- const REQUIREMENT_HEADERS = {
10772
- id: '需求编号',
10773
- status: '开发状态',
10774
- progress: '开发进度(%)',
10775
- updatedAt: '最后更新'
10776
- };
10777
- function columnIndex(headerCells, name) {
10778
- const index = headerCells.findIndex((cell)=>cell.trim() === name);
10779
- if (index < 0) throw new errors_CliError(`表格缺少列「${name}」,无法安全写入`, errors_EXIT.INVALID);
10780
- return index;
10800
+ let raw;
10801
+ try {
10802
+ raw = JSON.parse(text);
10803
+ } catch (error) {
10804
+ fail(docsRoot, `不是合法 JSON:${error instanceof Error ? error.message : String(error)}`);
10805
+ }
10806
+ return parseDocSchema(raw, docsRoot);
10781
10807
  }
10782
- function splitRow(line) {
10783
- const trimmed = line.trim();
10784
- const inner = trimmed.startsWith('|') ? trimmed.slice(1) : trimmed;
10785
- const withoutTail = inner.endsWith('|') ? inner.slice(0, -1) : inner;
10786
- return withoutTail.split('|').map((cell)=>cell.trim());
10808
+ function taskTypesOf(schema, role) {
10809
+ const config = schema.roles[role];
10810
+ if (void 0 === config) return [];
10811
+ const names = [];
10812
+ for (const group of config.taskTypeGroups)for (const item of schema.taskTypes[group])if (!names.includes(item.name)) names.push(item.name);
10813
+ return names;
10787
10814
  }
10788
- function joinRow(cells) {
10789
- return `| ${cells.join(' | ')} |`;
10815
+ function roleOfScope(schema, scope) {
10816
+ for (const [role, config] of Object.entries(schema.roles))if (config.scope === scope) return role;
10817
+ return null;
10790
10818
  }
10791
- function canSubmit(selfTest) {
10792
- const text = selfTest.trim();
10793
- return '通过' === text || text.startsWith('免测');
10819
+ function detailFieldsOfScope(schema, scope) {
10820
+ const role = roleOfScope(schema, scope);
10821
+ if (null === role) return [];
10822
+ return schema.roles[role]?.detailFields ?? [];
10823
+ }
10824
+ function sideOfTypeName(schema, typeName) {
10825
+ const inFront = schema.taskTypes.frontend.some((item)=>item.name === typeName);
10826
+ const inBack = schema.taskTypes.backend.some((item)=>item.name === typeName);
10827
+ if (inFront && inBack) return 'both';
10828
+ if (inFront) return 'frontend';
10829
+ if (inBack) return 'backend';
10830
+ return null;
10794
10831
  }
10795
- function sectionRange(lines, heading) {
10796
- const start = lines.findIndex((line)=>line.trim() === heading);
10797
- if (start < 0) throw new errors_CliError(`文档缺少章节「${heading}」,无法安全写入`, errors_EXIT.INVALID);
10798
- let end = lines.length;
10799
- for(let index = start + 1; index < lines.length; index += 1){
10800
- const line = lines[index] ?? '';
10801
- if (/^##\s+/.test(line) || /^#\s+/.test(line)) {
10802
- end = index;
10803
- break;
10804
- }
10832
+ function buildRepoSideIndex(terminals) {
10833
+ const byName = new Map();
10834
+ for (const terminal of Object.values(terminals))for (const side of [
10835
+ 'frontend',
10836
+ 'backend'
10837
+ ])for (const repoPath of terminal.repos[side]){
10838
+ const name = basename(repoPath);
10839
+ if (0 === name.length) continue;
10840
+ const existing = byName.get(name) ?? new Set();
10841
+ existing.add(side);
10842
+ byName.set(name, existing);
10805
10843
  }
10844
+ return {
10845
+ byName
10846
+ };
10847
+ }
10848
+ function sideOfRepo(index, repoName) {
10849
+ const sides = index.byName.get(repoName.trim());
10850
+ if (void 0 === sides || 1 !== sides.size) return null;
10806
10851
  return [
10807
- start,
10808
- end
10809
- ];
10852
+ ...sides
10853
+ ][0] ?? null;
10810
10854
  }
10811
- function parseTaskRows(lines) {
10812
- const [start, end] = sectionRange(lines, '## 三、任务清单');
10813
- let header = null;
10814
- const rows = [];
10815
- for(let index = start; index < end; index += 1){
10816
- const line = lines[index] ?? '';
10817
- if (!line.trim().startsWith('|')) continue;
10818
- const cells = splitRow(line);
10819
- if (null === header) {
10820
- if (cells.includes(TASK_HEADERS.id)) header = cells;
10821
- continue;
10855
+ function isKnownRepo(index, repoName) {
10856
+ return index.byName.has(repoName.trim());
10857
+ }
10858
+ function validateTaskSides(options) {
10859
+ const issues = [];
10860
+ for (const task of options.tasks){
10861
+ const expected = '前端' === task.scope ? 'frontend' : '后端' === task.scope ? 'backend' : null;
10862
+ if (null === expected) continue;
10863
+ const repoSide = sideOfRepo(options.index, task.terminal);
10864
+ if (null !== repoSide) {
10865
+ if (repoSide !== expected) issues.push({
10866
+ taskId: task.id,
10867
+ scope: task.scope,
10868
+ terminal: task.terminal,
10869
+ repoSide,
10870
+ level: 'warning',
10871
+ message: `任务 ${task.id} 的所属端是「${task.scope}」,但终端「${task.terminal}」在本机配置里是${describeSide(repoSide)}仓库,请核对`
10872
+ });
10822
10873
  }
10823
- if (cells.every((cell)=>/^:?-{2,}:?$/.test(cell))) continue;
10824
- const taskId = cells[columnIndex(header, TASK_HEADERS.id)] ?? '';
10825
- if (/^#\d{3,6}-T\d+$/.test(taskId)) rows.push({
10826
- index,
10827
- cells,
10828
- taskId,
10829
- status: cells[columnIndex(header, TASK_HEADERS.status)] ?? '',
10830
- acceptance: cells[columnIndex(header, TASK_HEADERS.acceptance)] ?? '',
10831
- selfTest: cells[columnIndex(header, TASK_HEADERS.selfTest)] ?? '',
10832
- requirementId: cells[columnIndex(header, TASK_HEADERS.requirement)] ?? ''
10833
- });
10834
10874
  }
10835
- if (null === header) throw new errors_CliError('未找到任务清单表头,无法安全写入', errors_EXIT.INVALID);
10836
- return {
10837
- header,
10838
- rows
10839
- };
10875
+ return issues;
10840
10876
  }
10841
- function parseRequirementRows(lines) {
10842
- const [start, end] = sectionRange(lines, '## 二、需求清单');
10843
- let header = null;
10844
- const rows = [];
10845
- for(let index = start; index < end; index += 1){
10846
- const line = lines[index] ?? '';
10847
- if (!line.trim().startsWith('|')) continue;
10848
- const cells = splitRow(line);
10849
- if (null === header) {
10850
- if (cells.includes(REQUIREMENT_HEADERS.id)) header = cells;
10851
- continue;
10852
- }
10853
- if (cells.every((cell)=>/^:?-{2,}:?$/.test(cell))) continue;
10854
- const id = cells[columnIndex(header, REQUIREMENT_HEADERS.id)] ?? '';
10855
- if (/^#\d{3,6}$/.test(id)) rows.push({
10856
- index,
10857
- cells,
10858
- id
10859
- });
10877
+ function describeSide(side) {
10878
+ return 'backend' === side ? '后端' : '前端';
10879
+ }
10880
+ const FILE_CHANGES = [
10881
+ '新增',
10882
+ '修改',
10883
+ '删除'
10884
+ ];
10885
+ function docplan_fail(message) {
10886
+ throw new errors_CliError(`plan 校验失败:${message}`, errors_EXIT.INVALID);
10887
+ }
10888
+ function docplan_isRecord(value) {
10889
+ return 'object' == typeof value && null !== value && !Array.isArray(value);
10890
+ }
10891
+ function optionalString(value, where) {
10892
+ if (null == value) return;
10893
+ if ('string' != typeof value) docplan_fail(`${where} 必须是字符串`);
10894
+ return value;
10895
+ }
10896
+ function docplan_requireString(value, where) {
10897
+ if ('string' != typeof value || 0 === value.trim().length) docplan_fail(`${where} 必须是非空字符串`);
10898
+ return value.trim();
10899
+ }
10900
+ function optionalStringArray(value, where) {
10901
+ if (null == value) return [];
10902
+ if (!Array.isArray(value)) docplan_fail(`${where} 必须是字符串数组`);
10903
+ return value.map((item, index)=>docplan_requireString(item, `${where}[${index}]`));
10904
+ }
10905
+ function normalizeCode(raw) {
10906
+ const trimmed = raw.trim();
10907
+ const withoutHash = trimmed.startsWith('#') ? trimmed.slice(1) : trimmed;
10908
+ if (!/^\d{3,6}$/.test(withoutHash)) docplan_fail(`需求编号格式非法(应为 2755 或 #2755):${raw}`);
10909
+ return `#${withoutHash}`;
10910
+ }
10911
+ function parseDocPlan(raw, schema, role) {
10912
+ if (!docplan_isRecord(raw)) docplan_fail('顶层必须是对象');
10913
+ const iterationRaw = raw.iteration;
10914
+ let iteration = {};
10915
+ if (null != iterationRaw) {
10916
+ if (!docplan_isRecord(iterationRaw)) docplan_fail('iteration 必须是对象');
10917
+ const collected = {};
10918
+ for (const field of schema.iterationFields){
10919
+ const value = optionalString(iterationRaw[field], `iteration.${field}`);
10920
+ if (void 0 !== value && value.trim().length > 0) collected[field] = value.trim();
10921
+ }
10922
+ iteration = collected;
10923
+ }
10924
+ if (!Array.isArray(raw.requirements)) docplan_fail('requirements 必须是数组');
10925
+ if (!Array.isArray(raw.tasks)) docplan_fail('tasks 必须是数组');
10926
+ if (0 === raw.tasks.length) docplan_fail('tasks 不能为空');
10927
+ const requirements = raw.requirements.map((item, index)=>{
10928
+ if (!docplan_isRecord(item)) docplan_fail(`requirements[${index}] 必须是对象`);
10929
+ return {
10930
+ code: normalizeCode(docplan_requireString(item.code, `requirements[${index}].code`)),
10931
+ name: docplan_requireString(item.name, `requirements[${index}].name`),
10932
+ terminal: docplan_requireString(item.terminal, `requirements[${index}].terminal`),
10933
+ note: optionalString(item.note, `requirements[${index}].note`) ?? ''
10934
+ };
10935
+ });
10936
+ const seenRequirements = new Set();
10937
+ for (const requirement of requirements){
10938
+ if (seenRequirements.has(requirement.code)) docplan_fail(`需求编号重复:${requirement.code}`);
10939
+ seenRequirements.add(requirement.code);
10940
+ }
10941
+ const allowedTypes = new Set(taskTypesOf(schema, role));
10942
+ const scopeEnum = schema.taskScopeEnum;
10943
+ const tasks = raw.tasks.map((item, index)=>{
10944
+ const where = `tasks[${index}]`;
10945
+ if (!docplan_isRecord(item)) docplan_fail(`${where} 必须是对象`);
10946
+ const type = docplan_requireString(item.type, `${where}.type`);
10947
+ if (allowedTypes.size > 0 && !allowedTypes.has(type)) docplan_fail(`${where}.type 非法:${type}(角色 ${role} 允许:${[
10948
+ ...allowedTypes
10949
+ ].join('、')})`);
10950
+ const filesRaw = item.files;
10951
+ let files = [];
10952
+ if (null != filesRaw) {
10953
+ if (!Array.isArray(filesRaw)) docplan_fail(`${where}.files 必须是数组`);
10954
+ files = filesRaw.map((entry, fileIndex)=>{
10955
+ if (!docplan_isRecord(entry)) docplan_fail(`${where}.files[${fileIndex}] 必须是对象`);
10956
+ const change = docplan_requireString(entry.change, `${where}.files[${fileIndex}].change`);
10957
+ if (!FILE_CHANGES.includes(change)) docplan_fail(`${where}.files[${fileIndex}].change 只能是 ${FILE_CHANGES.join(' / ')}`);
10958
+ return {
10959
+ path: docplan_requireString(entry.path, `${where}.files[${fileIndex}].path`),
10960
+ change: change
10961
+ };
10962
+ });
10963
+ }
10964
+ const selfTestRaw = item.selfTest;
10965
+ let selfTest = [];
10966
+ if (null != selfTestRaw) {
10967
+ if (!Array.isArray(selfTestRaw)) docplan_fail(`${where}.selfTest 必须是数组`);
10968
+ selfTest = selfTestRaw.map((entry, testIndex)=>{
10969
+ if (!docplan_isRecord(entry)) docplan_fail(`${where}.selfTest[${testIndex}] 必须是对象`);
10970
+ return {
10971
+ cmd: docplan_requireString(entry.cmd, `${where}.selfTest[${testIndex}].cmd`),
10972
+ result: docplan_requireString(entry.result, `${where}.selfTest[${testIndex}].result`)
10973
+ };
10974
+ });
10975
+ }
10976
+ let detailFields;
10977
+ if (void 0 !== item.detailFields && null !== item.detailFields) {
10978
+ if (!docplan_isRecord(item.detailFields)) docplan_fail(`${where}.detailFields 必须是对象`);
10979
+ const allowed = new Set(schema.roles[role]?.detailFields ?? []);
10980
+ detailFields = {};
10981
+ for (const [key, value] of Object.entries(item.detailFields)){
10982
+ if (allowed.size > 0 && !allowed.has(key)) docplan_fail(`${where}.detailFields 含未知字段「${key}」(角色 ${role} 允许:${[
10983
+ ...allowed
10984
+ ].join('、')};新增字段请先改 schema.json 与模板)`);
10985
+ if ('string' == typeof value) {
10986
+ detailFields[key] = value;
10987
+ continue;
10988
+ }
10989
+ if (Array.isArray(value)) {
10990
+ detailFields[key] = value.map((entry, index)=>docplan_requireString(entry, `${where}.detailFields.${key}[${index}]`));
10991
+ continue;
10992
+ }
10993
+ docplan_fail(`${where}.detailFields.${key} 必须是字符串或字符串数组`);
10994
+ }
10995
+ }
10996
+ const declaredScope = optionalString(item.scope, `${where}.scope`)?.trim();
10997
+ let scope;
10998
+ if (void 0 !== declaredScope && declaredScope.length > 0) {
10999
+ if (!scopeEnum.includes(declaredScope)) docplan_fail(`${where}.scope 非法:${declaredScope}(允许值:${scopeEnum.join('、')})`);
11000
+ scope = declaredScope;
11001
+ } else {
11002
+ const side = sideOfTypeName(schema, type);
11003
+ const inferred = 'frontend' === side ? '前端' : 'backend' === side ? '后端' : void 0;
11004
+ if (void 0 === inferred) docplan_fail(`${where}.scope 必须显式指定:类型「${type}」两端都可用,无法自动判断(允许值:${scopeEnum.join('、')})`);
11005
+ scope = inferred;
11006
+ }
11007
+ const typeSide = sideOfTypeName(schema, type);
11008
+ const expectedScope = 'frontend' === typeSide ? '前端' : 'backend' === typeSide ? '后端' : void 0;
11009
+ if (void 0 !== expectedScope && scope !== expectedScope) docplan_fail(`${where}.type「${type}」属于${expectedScope},但 scope 填的是「${scope}」`);
11010
+ return {
11011
+ requirement: normalizeCode(docplan_requireString(item.requirement, `${where}.requirement`)),
11012
+ name: docplan_requireString(item.name, `${where}.name`),
11013
+ type,
11014
+ scope,
11015
+ terminal: docplan_requireString(item.terminal, `${where}.terminal`),
11016
+ dependsOn: optionalStringArray(item.dependsOn, `${where}.dependsOn`),
11017
+ files,
11018
+ plan: optionalStringArray(item.plan, `${where}.plan`),
11019
+ selfTest,
11020
+ testForms: optionalStringArray(item.testForms, `${where}.testForms`),
11021
+ regression: optionalStringArray(item.regression, `${where}.regression`),
11022
+ notes: optionalString(item.notes, `${where}.notes`) ?? '无',
11023
+ detailFields
11024
+ };
11025
+ });
11026
+ return {
11027
+ iteration,
11028
+ requirements,
11029
+ tasks
11030
+ };
11031
+ }
11032
+ function validatePlanReferences(options) {
11033
+ const knownRepos = new Set();
11034
+ for (const [name] of options.index.byName)knownRepos.add(name);
11035
+ const requirementCodes = new Set(options.plan.requirements.map((item)=>item.code));
11036
+ for (const task of options.plan.tasks){
11037
+ if (!requirementCodes.has(task.requirement)) docplan_fail(`任务「${task.name}」关联的需求 ${task.requirement} 不在 requirements 中`);
11038
+ if (knownRepos.size > 0 && !isKnownRepo(options.index, task.terminal)) process.stderr.write(`提示:任务「${task.name}」的终端「${task.terminal}」不在本机终端配置中,跳过归属校验\n`);
11039
+ for (const dependency of task.dependsOn ?? []){
11040
+ const normalized = dependency.startsWith('#') ? dependency : `#${dependency}`;
11041
+ if (!options.knownTaskIds.includes(normalized)) {
11042
+ if (!options.plan.tasks.some((item)=>item.name === dependency)) docplan_fail(`任务「${task.name}」的前置依赖 ${dependency} 既不在文档中,也不在本次计划中`);
11043
+ }
11044
+ }
10860
11045
  }
10861
- if (null === header) throw new errors_CliError('未找到需求清单表头,无法安全写入', errors_EXIT.INVALID);
11046
+ }
11047
+ const PENDING_STATUS = '未开始';
11048
+ const PENDING_SELF_TEST = '未执行';
11049
+ const PENDING_ACCEPTANCE = '待验收';
11050
+ function headings(schema) {
10862
11051
  return {
10863
- header,
10864
- rows
11052
+ info: `## ${schema.sections[0] ?? '一、迭代信息'}`,
11053
+ requirement: `## ${schema.sections[1] ?? '二、需求清单'}`,
11054
+ task: `## ${schema.sections[2] ?? '三、任务清单'}`,
11055
+ detail: `## ${schema.sections[3] ?? '四、任务详情'}`
10865
11056
  };
10866
11057
  }
11058
+ function joinRow(cells) {
11059
+ return `| ${cells.join(' | ')} |`;
11060
+ }
11061
+ function docrender_separator(count) {
11062
+ return joinRow(Array.from({
11063
+ length: count
11064
+ }, ()=>'---'));
11065
+ }
11066
+ function nextSequence(existingTasks) {
11067
+ const counters = new Map();
11068
+ for (const task of existingTasks){
11069
+ const matched = /^#(\d{3,6})-T(\d+)$/.exec(task.id);
11070
+ if (null === matched) continue;
11071
+ const requirementId = `#${matched[1] ?? ''}`;
11072
+ const sequence = Number(matched[2] ?? '0');
11073
+ const current = counters.get(requirementId) ?? 0;
11074
+ if (sequence > current) counters.set(requirementId, sequence);
11075
+ }
11076
+ return counters;
11077
+ }
10867
11078
  function aggregateRequirementStatus(statuses) {
10868
11079
  if (0 === statuses.length) return '未开始';
10869
- if (statuses.every((status)=>'未开始' === status)) return '未开始';
10870
11080
  if (statuses.every((status)=>'已完成' === status)) return '已完成';
11081
+ if (statuses.every((status)=>status === PENDING_STATUS)) return '未开始';
10871
11082
  return '进行中';
10872
11083
  }
10873
- function updateDetailBlock(lines, taskId, updates) {
10874
- const headingIndex = lines.findIndex((line)=>line.trim().startsWith(`### [${taskId}]`));
10875
- if (headingIndex < 0) throw new errors_CliError(`任务 ${taskId} 缺少第四章详情区块,无法同步状态`, errors_EXIT.INVALID);
10876
- let end = lines.length;
10877
- for(let index = headingIndex + 1; index < lines.length; index += 1)if (/^###\s+/.test(lines[index] ?? '') || /^##\s+/.test(lines[index] ?? '')) {
10878
- end = index;
10879
- break;
10880
- }
10881
- const next = [
10882
- ...lines
11084
+ function progressOf(statuses) {
11085
+ if (0 === statuses.length) return 0;
11086
+ const done = statuses.filter((status)=>'已完成' === status).length;
11087
+ return Math.round(done / statuses.length * 100);
11088
+ }
11089
+ function renderDetail(options) {
11090
+ const { taskId, task, requirement } = options;
11091
+ const builtin = new Map();
11092
+ builtin.set('任务状态', {
11093
+ items: [
11094
+ PENDING_STATUS
11095
+ ],
11096
+ list: false
11097
+ });
11098
+ builtin.set('自测状态', {
11099
+ items: [
11100
+ PENDING_SELF_TEST
11101
+ ],
11102
+ list: false
11103
+ });
11104
+ builtin.set('人工验收', {
11105
+ items: [
11106
+ PENDING_ACCEPTANCE
11107
+ ],
11108
+ list: false
11109
+ });
11110
+ builtin.set('所属需求', {
11111
+ items: [
11112
+ `${requirement.code} ${requirement.name}`
11113
+ ],
11114
+ list: false
11115
+ });
11116
+ builtin.set('任务类型', {
11117
+ items: [
11118
+ task.type
11119
+ ],
11120
+ list: false
11121
+ });
11122
+ builtin.set('核心文件清单', {
11123
+ items: (task.files ?? []).map((file)=>`\`${file.path}\`(${file.change})`),
11124
+ list: true
11125
+ });
11126
+ builtin.set('详细实现方案', {
11127
+ items: task.plan ?? [],
11128
+ list: true
11129
+ });
11130
+ builtin.set('AI 单测与自检证据', {
11131
+ items: (task.selfTest ?? []).map((item)=>`\`${item.cmd}\`:${item.result}`),
11132
+ list: true
11133
+ });
11134
+ builtin.set('自测形式', {
11135
+ items: task.testForms ?? [],
11136
+ list: true
11137
+ });
11138
+ builtin.set('QA 历史功能影响范围 (Regression Scope)', {
11139
+ items: task.regression ?? [],
11140
+ list: true
11141
+ });
11142
+ builtin.set('待联调/遗留事项', {
11143
+ items: [
11144
+ task.notes ?? '无'
11145
+ ],
11146
+ list: false
11147
+ });
11148
+ const lines = [
11149
+ `### [${taskId}] ${task.name}`,
11150
+ ''
10883
11151
  ];
10884
- for(let index = headingIndex; index < end; index += 1){
11152
+ for (const field of detailFieldsOfScope(options.schema, task.scope)){
11153
+ const custom = task.detailFields?.[field];
11154
+ const value = builtin.get(field) ?? (void 0 === custom ? void 0 : {
11155
+ items: Array.isArray(custom) ? custom : [
11156
+ custom
11157
+ ],
11158
+ list: Array.isArray(custom)
11159
+ });
11160
+ if (void 0 === value) {
11161
+ lines.push(`- **${field}**:<待补充>`);
11162
+ continue;
11163
+ }
11164
+ if (!value.list && 1 === value.items.length) {
11165
+ lines.push(`- **${field}**:${value.items[0]}`);
11166
+ continue;
11167
+ }
11168
+ lines.push(`- **${field}**:`);
11169
+ for (const item of 0 === value.items.length ? [
11170
+ '<待补充>'
11171
+ ] : value.items)lines.push(` - ${item}`);
11172
+ }
11173
+ lines.push('');
11174
+ return lines;
11175
+ }
11176
+ function appendTableRows(options) {
11177
+ const { lines, sectionHeading, headers, rows } = options;
11178
+ if (0 === rows.length) return lines;
11179
+ const start = lines.findIndex((line)=>line.trim() === sectionHeading);
11180
+ if (start < 0) {
11181
+ const block = [
11182
+ sectionHeading,
11183
+ '',
11184
+ joinRow([
11185
+ ...headers
11186
+ ]),
11187
+ docrender_separator(headers.length),
11188
+ ...rows,
11189
+ ''
11190
+ ];
11191
+ return [
11192
+ ...lines,
11193
+ ...block
11194
+ ];
11195
+ }
11196
+ let tableEnd = -1;
11197
+ let tableStart = -1;
11198
+ for(let index = start + 1; index < lines.length; index += 1){
10885
11199
  const line = lines[index] ?? '';
10886
- const match = /^(\s*-\s+\*\*(.+?)\*\*\s*[::]\s*)(.*)$/.exec(line);
10887
- if (null === match) continue;
10888
- const field = match[2] ?? '';
10889
- const replacement = updates[field];
10890
- if (void 0 !== replacement) next[index] = `${match[1] ?? ''}${replacement}`;
11200
+ if (/^##\s+/.test(line)) break;
11201
+ if (line.trim().startsWith('|')) {
11202
+ if (tableStart < 0) tableStart = index;
11203
+ tableEnd = index;
11204
+ }
11205
+ }
11206
+ if (tableStart < 0) {
11207
+ const block = [
11208
+ '',
11209
+ joinRow([
11210
+ ...headers
11211
+ ]),
11212
+ docrender_separator(headers.length),
11213
+ ...rows
11214
+ ];
11215
+ return [
11216
+ ...lines.slice(0, start + 1),
11217
+ ...block,
11218
+ ...lines.slice(start + 1)
11219
+ ];
10891
11220
  }
10892
- return next;
11221
+ return [
11222
+ ...lines.slice(0, tableEnd + 1),
11223
+ ...rows,
11224
+ ...lines.slice(tableEnd + 1)
11225
+ ];
10893
11226
  }
10894
- function realIterationName(docsRoot, iteration) {
10895
- try {
10896
- const match = external_node_fs_readdirSync(docsRoot).find((entry)=>entry.toLowerCase() === iteration.toLowerCase());
10897
- return match ?? iteration;
10898
- } catch {
10899
- return iteration;
11227
+ function buildSkeleton(options) {
11228
+ const { schema, role, plan, developer } = options;
11229
+ const head = headings(schema);
11230
+ const lines = [];
11231
+ lines.push(`# ${developer}`, '');
11232
+ lines.push(head.info, '');
11233
+ lines.push(joinRow([
11234
+ '项',
11235
+ '内容'
11236
+ ]));
11237
+ lines.push(docrender_separator(2));
11238
+ for (const field of schema.iterationFields){
11239
+ const provided = plan.iteration[field];
11240
+ const fallback = '负责人' === field ? developer : '负责范围' === field ? schema.roles[role]?.scope ?? '' : '';
11241
+ lines.push(joinRow([
11242
+ field,
11243
+ provided ?? fallback
11244
+ ]));
10900
11245
  }
10901
- }
10902
- function loadDoc(docsRoot, iterationRaw, developerRaw) {
10903
- const iteration = realIterationName(docsRoot, safeSegment(iterationRaw, '迭代目录'));
10904
- const developer = safeSegment(developerRaw, '开发者标识');
10905
- const file = external_node_path_join(docsRoot, iteration, `${developer}.md`);
10906
- if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${iteration}/${developer}.md`, errors_EXIT.NOT_FOUND);
10907
- const mtime = statSync(file).mtimeMs;
10908
- const original = readFileSync(file, 'utf8');
10909
- return {
10910
- file,
10911
- mtime,
10912
- original,
10913
- lines: original.split('\n')
10914
- };
10915
- }
10916
- function computeUpdate(lines, taskId, action) {
10917
- const { header, rows } = parseTaskRows(lines);
10918
- const target = rows.find((row)=>row.taskId === taskId);
10919
- if (void 0 === target) throw new errors_CliError(`任务清单中未找到 ${taskId}`, errors_EXIT.NOT_FOUND);
10920
- const statusIndex = columnIndex(header, TASK_HEADERS.status);
10921
- const acceptanceIndex = columnIndex(header, TASK_HEADERS.acceptance);
10922
- const currentStatus = target.status;
10923
- const currentAcceptance = target.acceptance;
10924
- const meta = ACTION_META[action];
10925
- if (currentStatus !== meta.from) throw new errors_CliError(`任务 ${taskId} 当前状态为「${currentStatus}」,无法执行「${meta.label}」(要求「${meta.from}」)`, errors_EXIT.USAGE);
10926
- if ('submit' === action && !canSubmit(target.selfTest)) throw new errors_CliError(`任务 ${taskId} 的 AI 自测状态为「${target.selfTest}」,未通过自测不能提交验收`, errors_EXIT.USAGE);
10927
- const nextStatus = meta.to;
10928
- const nextAcceptance = 'accept' === action ? '验收通过' : 'reject' === action ? '验收驳回' : currentAcceptance;
11246
+ lines.push('');
11247
+ lines.push(head.requirement, '');
11248
+ lines.push(joinRow([
11249
+ ...schema.requirementHeaders
11250
+ ]));
11251
+ lines.push(docrender_separator(schema.requirementHeaders.length));
11252
+ lines.push('');
11253
+ lines.push(head.task, '');
11254
+ lines.push(joinRow([
11255
+ ...schema.taskHeaders
11256
+ ]));
11257
+ lines.push(docrender_separator(schema.taskHeaders.length));
11258
+ lines.push('');
11259
+ lines.push(head.detail, '');
11260
+ lines.push('');
11261
+ return lines;
11262
+ }
11263
+ function renderPlan(options) {
11264
+ const { schema, role, plan, existing, stamp, developer } = options;
10929
11265
  const changes = [];
10930
- if (nextStatus !== currentStatus) changes.push(`${taskId} 任务状态:${currentStatus} → ${nextStatus}`);
10931
- if (nextAcceptance !== currentAcceptance) changes.push(`${taskId} 开发人工验收:${currentAcceptance} → ${nextAcceptance}`);
10932
- const stamp = nowStamp();
10933
- const updated = [
10934
- ...lines
10935
- ];
10936
- const taskCells = [
10937
- ...target.cells
10938
- ];
10939
- taskCells[statusIndex] = nextStatus;
10940
- taskCells[acceptanceIndex] = nextAcceptance;
10941
- taskCells[columnIndex(header, TASK_HEADERS.updatedAt)] = stamp;
10942
- updated[target.index] = joinRow(taskCells);
10943
- const withDetail = updateDetailBlock(updated, taskId, {
10944
- 任务状态: nextStatus,
10945
- 人工验收: nextAcceptance
10946
- });
10947
- const requirementStatuses = rows.filter((row)=>row.requirementId === target.requirementId).map((row)=>row.taskId === taskId ? nextStatus : row.status);
10948
- const requirementStatus = aggregateRequirementStatus(requirementStatuses);
10949
- const completed = requirementStatuses.filter((status)=>'已完成' === status).length;
10950
- const progress = 0 === requirementStatuses.length ? 0 : Math.round(completed / requirementStatuses.length * 100);
10951
- const requirementParse = parseRequirementRows(withDetail);
10952
- const requirementTarget = requirementParse.rows.find((row)=>row.id === target.requirementId);
10953
- if (void 0 === requirementTarget) throw new errors_CliError(`需求清单中未找到 ${target.requirementId}`, errors_EXIT.NOT_FOUND);
10954
- const requirementCells = [
10955
- ...requirementTarget.cells
10956
- ];
10957
- const previousStatus = requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.status)] ?? '';
10958
- const previousProgress = requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.progress)] ?? '';
10959
- requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.status)] = requirementStatus;
10960
- requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.progress)] = String(progress);
10961
- if (previousStatus !== requirementStatus || previousProgress !== String(progress)) requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.updatedAt)] = stamp;
10962
- withDetail[requirementTarget.index] = joinRow(requirementCells);
10963
- if (previousStatus !== requirementStatus) changes.push(`需求 ${target.requirementId} 开发状态:${previousStatus} → ${requirementStatus}`);
10964
- if (previousProgress !== String(progress)) changes.push(`需求 ${target.requirementId} 开发进度:${previousProgress}% → ${progress}%`);
10965
- return {
10966
- lines: withDetail,
10967
- changes
10968
- };
10969
- }
10970
- function commit(context, lines, changes, message, iteration, developer, action, taskIds, options) {
10971
- if (statSync(context.file).mtimeMs !== context.mtime) throw new errors_CliError('文件已被外部修改,请刷新后重试', errors_EXIT.INVALID);
10972
- const output = lines.join('\n');
10973
- if (output === context.original) return {
10974
- ok: true,
10975
- message: '状态未发生变化',
10976
- changes: [],
10977
- file: context.file
10978
- };
10979
- writeFileSync(context.file, output, 'utf8');
10980
- const violation = validateAfterWrite(external_node_path_dirname(context.file), iteration, developer);
10981
- if (null !== violation) {
10982
- writeFileSync(context.file, context.original, 'utf8');
10983
- throw new errors_CliError(`写入被校验器拒绝,已回滚:${violation}`, errors_EXIT.INVALID);
11266
+ const assigned = [];
11267
+ const existingRequirementIds = new Set(existing.requirements.map((item)=>item.id));
11268
+ const existingTaskNames = new Set(existing.tasks.map((item)=>`${item.requirementId}/${item.name}`));
11269
+ const counters = nextSequence(existing.tasks);
11270
+ const taskIdsByPlanName = new Map();
11271
+ const newTasks = [];
11272
+ for (const task of plan.tasks){
11273
+ const key = `${task.requirement}/${task.name}`;
11274
+ if (existingTaskNames.has(key)) {
11275
+ changes.push(`跳过已存在的任务:${task.requirement} ${task.name}`);
11276
+ continue;
11277
+ }
11278
+ const next = (counters.get(task.requirement) ?? 0) + 1;
11279
+ counters.set(task.requirement, next);
11280
+ const id = `${task.requirement}-T${next}`;
11281
+ const requirement = plan.requirements.find((item)=>item.code === task.requirement);
11282
+ if (void 0 !== requirement) {
11283
+ taskIdsByPlanName.set(task.name, id);
11284
+ newTasks.push({
11285
+ id,
11286
+ task,
11287
+ requirement
11288
+ });
11289
+ assigned.push({
11290
+ name: task.name,
11291
+ id
11292
+ });
11293
+ }
10984
11294
  }
10985
- appendHistory({
10986
- iteration,
11295
+ const requirementRows = [];
11296
+ const requirementStatuses = new Map();
11297
+ for (const item of existing.tasks){
11298
+ const list = requirementStatuses.get(item.requirementId) ?? [];
11299
+ list.push(item.status);
11300
+ requirementStatuses.set(item.requirementId, list);
11301
+ }
11302
+ for (const entry of newTasks){
11303
+ const list = requirementStatuses.get(entry.task.requirement) ?? [];
11304
+ list.push(PENDING_STATUS);
11305
+ requirementStatuses.set(entry.task.requirement, list);
11306
+ }
11307
+ const newRequirementCodes = new Set();
11308
+ for (const requirement of plan.requirements){
11309
+ if (existingRequirementIds.has(requirement.code)) {
11310
+ changes.push(`跳过已存在的需求:${requirement.code} ${requirement.name}`);
11311
+ continue;
11312
+ }
11313
+ newRequirementCodes.add(requirement.code);
11314
+ const statuses = requirementStatuses.get(requirement.code) ?? [];
11315
+ const cells = [
11316
+ requirement.code,
11317
+ requirement.name,
11318
+ requirement.terminal,
11319
+ aggregateRequirementStatus(statuses),
11320
+ String(progressOf(statuses)),
11321
+ requirement.note ?? '',
11322
+ stamp
11323
+ ];
11324
+ requirementRows.push(joinRow(cells));
11325
+ changes.push(`新增需求:${requirement.code} ${requirement.name}`);
11326
+ }
11327
+ const taskRows = newTasks.map(({ id, task })=>{
11328
+ const dependencies = (task.dependsOn ?? []).map((dependency)=>taskIdsByPlanName.get(dependency) ?? dependency).join(',');
11329
+ const cells = [
11330
+ id,
11331
+ task.requirement,
11332
+ task.name,
11333
+ task.type,
11334
+ task.scope,
11335
+ task.terminal,
11336
+ dependencies,
11337
+ PENDING_SELF_TEST,
11338
+ PENDING_ACCEPTANCE,
11339
+ PENDING_STATUS,
11340
+ stamp
11341
+ ];
11342
+ changes.push(`新增任务:${id} ${task.name}`);
11343
+ return joinRow(cells);
11344
+ });
11345
+ const head = headings(schema);
11346
+ let lines = null === existing.lines ? buildSkeleton({
11347
+ schema,
11348
+ role,
11349
+ plan,
10987
11350
  developer,
10988
- taskId: taskIds.join(','),
10989
- action,
10990
- changes
11351
+ stamp
11352
+ }) : [
11353
+ ...existing.lines
11354
+ ];
11355
+ lines = appendTableRows({
11356
+ lines,
11357
+ sectionHeading: head.requirement,
11358
+ headers: schema.requirementHeaders,
11359
+ rows: requirementRows
10991
11360
  });
10992
- const git = options.policy.commit ? commitInDocsRepo(options.docsRoot, context.file, options.commitMessage, options.policy.push) : void 0;
11361
+ lines = appendTableRows({
11362
+ lines,
11363
+ sectionHeading: head.task,
11364
+ headers: schema.taskHeaders,
11365
+ rows: taskRows
11366
+ });
11367
+ if (newTasks.length > 0) {
11368
+ const detailLines = newTasks.flatMap(({ id, task, requirement })=>renderDetail({
11369
+ schema,
11370
+ role,
11371
+ taskId: id,
11372
+ task,
11373
+ requirement
11374
+ }));
11375
+ while(lines.length > 0 && '' === (lines[lines.length - 1] ?? '').trim())lines.pop();
11376
+ lines.push('');
11377
+ lines.push(...detailLines);
11378
+ }
11379
+ while(lines.length > 0 && '' === (lines[lines.length - 1] ?? '').trim())lines.pop();
10993
11380
  return {
10994
- ok: true,
10995
- message,
11381
+ markdown: lines.join('\n') + '\n',
10996
11382
  changes,
10997
- file: context.file,
10998
- git
11383
+ assigned
10999
11384
  };
11000
11385
  }
11001
- function applyBatchAction(options) {
11002
- if (0 === options.taskIds.length) throw new errors_CliError('未选择任务', errors_EXIT.USAGE);
11003
- const context = loadDoc(options.docsRoot, options.iteration, options.developer);
11004
- let lines = context.lines;
11005
- const changes = [];
11006
- for (const taskId of options.taskIds){
11007
- const result = computeUpdate(lines, taskId, options.action);
11008
- lines = result.lines;
11009
- changes.push(...result.changes);
11010
- }
11011
- return commit(context, lines, changes, `已对 ${options.taskIds.length} 个任务执行「${ACTION_META[options.action].label}」`, safeSegment(options.iteration, '迭代目录'), safeSegment(options.developer, '开发者标识'), options.action, options.taskIds, {
11012
- docsRoot: options.docsRoot,
11013
- policy: options.policy,
11014
- commitMessage: buildCommitMessage(options.iteration, options.action, options.taskIds, options.action)
11015
- });
11016
- }
11017
- function applyTaskAction(options) {
11018
- const context = loadDoc(options.docsRoot, options.iteration, options.developer);
11019
- const result = computeUpdate(context.lines, options.taskId, options.action);
11020
- return commit(context, result.lines, result.changes, `已执行「${ACTION_META[options.action].label}」`, safeSegment(options.iteration, '迭代目录'), safeSegment(options.developer, '开发者标识'), options.action, [
11021
- options.taskId
11022
- ], {
11023
- docsRoot: options.docsRoot,
11024
- policy: options.policy,
11025
- commitMessage: buildCommitMessage(options.iteration, options.action, [
11026
- options.taskId
11027
- ], options.action)
11028
- });
11029
- }
11030
- function validateAfterWrite(docsRoot, iteration, developer) {
11031
- const script = external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py');
11032
- if (!external_node_fs_existsSync(script)) return null;
11033
- for (const bin of [
11034
- 'python3',
11035
- 'python',
11036
- 'py'
11037
- ])try {
11038
- const stdout = execFileSync(bin, [
11039
- script,
11040
- '--docs-root',
11041
- docsRoot,
11042
- '--iteration',
11043
- iteration,
11044
- '--developer',
11045
- developer,
11046
- '--format',
11047
- 'json'
11048
- ], {
11049
- encoding: 'utf8',
11050
- timeout: 15000,
11051
- maxBuffer: 16777216
11052
- });
11053
- const payload = JSON.parse(stdout);
11054
- const first = payload.errors?.[0];
11055
- return first?.message ?? null;
11056
- } catch (error) {
11057
- const stdout = error.stdout ?? '';
11058
- if (0 === stdout.trim().length) continue;
11059
- try {
11060
- const payload = JSON.parse(stdout);
11061
- return payload.errors?.[0]?.message ?? '校验器未通过';
11062
- } catch {
11063
- break;
11064
- }
11065
- }
11066
- return null;
11067
- }
11068
- function recalcRequirements(options) {
11069
- const context = loadDoc(options.docsRoot, options.iteration, options.developer);
11070
- const { rows: taskRows } = parseTaskRows(context.lines);
11071
- const requirementParse = parseRequirementRows(context.lines);
11072
- const lines = [
11073
- ...context.lines
11074
- ];
11075
- const changes = [];
11076
- for (const requirement of requirementParse.rows){
11077
- const own = taskRows.filter((row)=>row.requirementId === requirement.id);
11078
- const status = aggregateRequirementStatus(own.map((row)=>row.status));
11079
- const completed = own.filter((row)=>'已完成' === row.status).length;
11080
- const progress = 0 === own.length ? 0 : Math.round(completed / own.length * 100);
11081
- const cells = [
11082
- ...requirement.cells
11083
- ];
11084
- const previousStatus = cells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.status)] ?? '';
11085
- const previousProgress = cells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.progress)] ?? '';
11086
- if (previousStatus !== status || previousProgress !== String(progress)) {
11087
- cells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.status)] = status;
11088
- cells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.progress)] = String(progress);
11089
- lines[requirement.index] = joinRow(cells);
11090
- if (previousStatus !== status) changes.push(`${requirement.id} 开发状态:${previousStatus} → ${status}`);
11091
- if (previousProgress !== String(progress)) changes.push(`${requirement.id} 开发进度:${previousProgress}% → ${progress}%`);
11092
- }
11093
- }
11094
- if (true === options.dryRun || 0 === changes.length) return {
11095
- changes,
11096
- file: context.file
11097
- };
11098
- return {
11099
- changes,
11100
- file: commit(context, lines, changes, `已重算 ${requirementParse.rows.length} 个需求的状态与进度`, safeSegment(options.iteration, '迭代目录'), safeSegment(options.developer, '开发者标识'), 'start', [], {
11101
- docsRoot: options.docsRoot,
11102
- policy: {
11103
- commit: false,
11104
- push: false
11105
- },
11106
- commitMessage: `docs(${options.iteration}): 重算需求状态与进度`
11107
- }).file
11108
- };
11109
- }
11110
- function availableActions(options) {
11111
- const iteration = safeSegment(options.iteration, '迭代目录');
11112
- const developer = safeSegment(options.developer, '开发者标识');
11113
- const file = external_node_path_join(options.docsRoot, iteration, `${developer}.md`);
11114
- if (!external_node_fs_existsSync(file)) return {};
11115
- const lines = readFileSync(file, 'utf8').split('\n');
11116
- const { rows } = parseTaskRows(lines);
11117
- const result = {};
11118
- for (const row of rows){
11119
- const list = [];
11120
- if ('未开始' === row.status) list.push({
11121
- action: 'start',
11122
- enabled: true,
11123
- reason: ''
11124
- });
11125
- if ('进行中' === row.status) {
11126
- const ok = canSubmit(row.selfTest);
11127
- list.push({
11128
- action: 'submit',
11129
- enabled: ok,
11130
- reason: ok ? '' : `AI 自测为「${row.selfTest}」,需先通过自测`
11131
- });
11132
- }
11133
- if ('待验收' === row.status) {
11134
- list.push({
11135
- action: 'accept',
11136
- enabled: true,
11137
- reason: ''
11138
- });
11139
- list.push({
11140
- action: 'reject',
11141
- enabled: true,
11142
- reason: ''
11143
- });
11144
- }
11145
- result[row.taskId] = list;
11146
- }
11147
- return result;
11148
- }
11149
- const RESERVED_FILES = new Set([
11150
- 'README.md',
11151
- 'AGENTS.md',
11152
- 'CLAUDE.md'
11153
- ]);
11154
- const RESERVED_PREFIXES = [
11155
- 'skills/',
11156
- "scripts/",
11157
- '_prd/'
11158
- ];
11159
- const git_SAFE_SEGMENT = /^[A-Za-z0-9._\-\u4e00-\u9fa5]+$/;
11160
- function git_git(docsRoot, args, timeoutMs = 15000) {
11161
- return execFileSync('git', [
11162
- '-C',
11163
- docsRoot,
11164
- ...args
11386
+ const RESERVED_FILES = new Set([
11387
+ 'README.md',
11388
+ 'AGENTS.md',
11389
+ 'CLAUDE.md'
11390
+ ]);
11391
+ const RESERVED_PREFIXES = [
11392
+ 'skills/',
11393
+ "scripts/",
11394
+ '_prd/'
11395
+ ];
11396
+ const SAFE_SEGMENT = /^[A-Za-z0-9._\-\u4e00-\u9fa5]+$/;
11397
+ function git_git(docsRoot, args, timeoutMs = 15000) {
11398
+ return execFileSync('git', [
11399
+ '-C',
11400
+ docsRoot,
11401
+ ...args
11165
11402
  ], {
11166
11403
  encoding: 'utf8',
11167
11404
  timeout: timeoutMs,
@@ -11180,9 +11417,9 @@ function tryGit(docsRoot, args, timeoutMs) {
11180
11417
  return null;
11181
11418
  }
11182
11419
  }
11183
- function git_safeSegment(value, label) {
11420
+ function safeSegment(value, label) {
11184
11421
  const trimmed = value.trim();
11185
- if (!git_SAFE_SEGMENT.test(trimmed) || '.' === trimmed || '..' === trimmed) throw new errors_CliError(`${label} 不合法:${value}`, errors_EXIT.USAGE);
11422
+ if (!SAFE_SEGMENT.test(trimmed) || '.' === trimmed || '..' === trimmed) throw new errors_CliError(`${label} 不合法:${value}`, errors_EXIT.USAGE);
11186
11423
  return trimmed;
11187
11424
  }
11188
11425
  function getGitStatus(docsRoot) {
@@ -11413,8 +11650,8 @@ function materializeRemote(docsRoot, ref) {
11413
11650
  return dir;
11414
11651
  }
11415
11652
  function exportRemoteDoc(docsRoot, ref, iteration, developer) {
11416
- const safeIteration = git_safeSegment(iteration, '迭代目录');
11417
- const safeDeveloper = git_safeSegment(developer, '开发者标识');
11653
+ const safeIteration = safeSegment(iteration, '迭代目录');
11654
+ const safeDeveloper = safeSegment(developer, '开发者标识');
11418
11655
  const relative = `${safeIteration}/${safeDeveloper}.md`;
11419
11656
  const markdown = gitShow(docsRoot, ref.sha, relative);
11420
11657
  if (null === markdown) throw new errors_CliError(`远程快照中不存在该文档:${relative}`, errors_EXIT.NOT_FOUND);
@@ -11429,6 +11666,11 @@ function exportRemoteDoc(docsRoot, ref, iteration, developer) {
11429
11666
  const script = gitShow(docsRoot, ref.sha, "scripts/validate_task_doc.py");
11430
11667
  if (null !== script) writeFileSync(scriptPath, script, 'utf8');
11431
11668
  }
11669
+ const schemaPath = external_node_path_join(dir, 'schema.json');
11670
+ if (!external_node_fs_existsSync(schemaPath)) {
11671
+ const schemaText = gitShow(docsRoot, ref.sha, 'schema.json');
11672
+ if (null !== schemaText) writeFileSync(schemaPath, schemaText, 'utf8');
11673
+ }
11432
11674
  return {
11433
11675
  dir,
11434
11676
  markdown,
@@ -11466,6 +11708,7 @@ const RESERVED_DIRS = new Set([
11466
11708
  '_prd',
11467
11709
  "scripts",
11468
11710
  'skills',
11711
+ 'docs',
11469
11712
  'node_modules',
11470
11713
  '.git',
11471
11714
  '.idea',
@@ -11633,6 +11876,7 @@ function coerceTask(value) {
11633
11876
  requirementId: 'string' == typeof value['requirementId'] ? value['requirementId'] : '',
11634
11877
  name: 'string' == typeof value['name'] ? value['name'] : '',
11635
11878
  type: 'string' == typeof value['type'] ? value['type'] : '',
11879
+ scope: 'string' == typeof value['scope'] ? value['scope'] : '',
11636
11880
  terminal: 'string' == typeof value['terminal'] ? value['terminal'] : '',
11637
11881
  dependencies: isStringArray(value['dependencies']) ? value['dependencies'] : [],
11638
11882
  selfTest: 'string' == typeof value['selfTest'] ? value['selfTest'] : '',
@@ -11691,316 +11935,1384 @@ function runValidator(input) {
11691
11935
  'python',
11692
11936
  'py'
11693
11937
  ])try {
11694
- const stdout = execFileSync(bin, args, {
11938
+ const stdout = execFileSync(bin, args, {
11939
+ encoding: 'utf8',
11940
+ timeout: 10000,
11941
+ maxBuffer: 16777216
11942
+ });
11943
+ const parsed = coercePayload(JSON.parse(stdout));
11944
+ if (null !== parsed) return parsed;
11945
+ } catch (error) {
11946
+ const stdout = error.stdout;
11947
+ if ('string' == typeof stdout && stdout.trim().length > 0) try {
11948
+ const parsed = coercePayload(JSON.parse(stdout));
11949
+ if (null !== parsed) return parsed;
11950
+ } catch {}
11951
+ }
11952
+ return null;
11953
+ }
11954
+ function extractSection(markdown, heading) {
11955
+ const lines = markdown.split(/\r?\n/);
11956
+ let start = -1;
11957
+ for(let index = 0; index < lines.length; index += 1)if ((lines[index] ?? '').trim() === heading) {
11958
+ start = index + 1;
11959
+ break;
11960
+ }
11961
+ if (start < 0) return '';
11962
+ const collected = [];
11963
+ for(let index = start; index < lines.length; index += 1){
11964
+ const line = lines[index] ?? '';
11965
+ if (/^##\s+/.test(line)) break;
11966
+ collected.push(line);
11967
+ }
11968
+ return collected.join('\n').trim();
11969
+ }
11970
+ function splitDetails(markdown) {
11971
+ const section = extractSection(markdown, '## 四、任务详情');
11972
+ if (0 === section.length) return [];
11973
+ const blocks = [];
11974
+ const parts = section.split(/^###\s+/m).slice(1);
11975
+ for (const part of parts){
11976
+ const [firstLine, ...rest] = part.split(/\r?\n/);
11977
+ const heading = (firstLine ?? '').trim();
11978
+ const match = /^\[?([#\w\-\u4e00-\u9fa5]+)\]?\s*(.*)$/.exec(heading);
11979
+ const id = match?.[1] ?? heading;
11980
+ const name = match?.[2]?.trim() ?? '';
11981
+ blocks.push({
11982
+ id,
11983
+ name,
11984
+ markdown: rest.join('\n').trim()
11985
+ });
11986
+ }
11987
+ return blocks;
11988
+ }
11989
+ function parseMarkdownDoc(markdown, schema) {
11990
+ const structureErrors = [];
11991
+ const readTable = (sectionHeading, required)=>{
11992
+ const section = extractSection(markdown, sectionHeading);
11993
+ const rows = section.split(/\r?\n/).map((line)=>line.trim()).filter((line)=>line.startsWith('|')).map((line)=>line.replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell)=>cell.trim())).filter((cells)=>!cells.every((cell)=>/^:?-{2,}:?$/.test(cell) || 0 === cell.length));
11994
+ const [header, ...body] = rows;
11995
+ if (void 0 === header) return {
11996
+ records: [],
11997
+ missing: [
11998
+ ...required
11999
+ ]
12000
+ };
12001
+ const missing = required.filter((name)=>!header.includes(name));
12002
+ if (missing.length > 0) return {
12003
+ records: [],
12004
+ missing
12005
+ };
12006
+ const records = body.map((cells)=>{
12007
+ const record = {};
12008
+ header.forEach((name, index)=>{
12009
+ record[name] = cells[index] ?? '';
12010
+ });
12011
+ return record;
12012
+ });
12013
+ return {
12014
+ records,
12015
+ missing: []
12016
+ };
12017
+ };
12018
+ const heading = (index, fallback)=>`## ${schema.sections[index] ?? fallback}`;
12019
+ const requirementRead = readTable(heading(1, '二、需求清单'), schema.requirementHeaders);
12020
+ const taskRead = readTable(heading(2, '三、任务清单'), schema.taskHeaders);
12021
+ if (requirementRead.missing.length > 0) structureErrors.push({
12022
+ level: 'error',
12023
+ code: 'REQUIREMENT_TABLE_MISMATCH',
12024
+ message: `需求清单表头缺少列:${requirementRead.missing.join('、')},请按最新模板补齐`
12025
+ });
12026
+ if (taskRead.missing.length > 0) structureErrors.push({
12027
+ level: 'error',
12028
+ code: 'TASK_TABLE_MISMATCH',
12029
+ message: `任务清单表头缺少列:${taskRead.missing.join('、')},请按最新模板补齐`
12030
+ });
12031
+ const reqH = schema.requirementHeaders;
12032
+ const requirements = requirementRead.records.map((record)=>({
12033
+ id: record[reqH[0] ?? ''] ?? '',
12034
+ title: record[reqH[1] ?? ''] ?? '',
12035
+ terminal: record[reqH[2] ?? ''] ?? '',
12036
+ status: record[reqH[3] ?? ''] ?? '',
12037
+ progress: record[reqH[4] ?? ''] ?? '',
12038
+ note: record[reqH[5] ?? ''] ?? '',
12039
+ updatedAt: record[reqH[6] ?? ''] ?? '',
12040
+ taskIds: []
12041
+ }));
12042
+ const taskH = schema.taskHeaders;
12043
+ const tasks = taskRead.records.map((record)=>({
12044
+ id: record[taskH[0] ?? ''] ?? '',
12045
+ requirementId: record[taskH[1] ?? ''] ?? '',
12046
+ name: record[taskH[2] ?? ''] ?? '',
12047
+ type: record[taskH[3] ?? ''] ?? '',
12048
+ scope: record[taskH[4] ?? ''] ?? '',
12049
+ terminal: record[taskH[5] ?? ''] ?? '',
12050
+ dependencies: (record[taskH[6] ?? ''] ?? '').split(/[,,]/).map((item)=>item.trim()).filter((item)=>item.length > 0),
12051
+ selfTest: record[taskH[7] ?? ''] ?? '',
12052
+ acceptance: record[taskH[8] ?? ''] ?? '',
12053
+ status: record[taskH[9] ?? ''] ?? '',
12054
+ updatedAt: record[taskH[10] ?? ''] ?? ''
12055
+ }));
12056
+ for (const requirement of requirements)requirement.taskIds = tasks.filter((task)=>task.requirementId === requirement.id).map((task)=>task.id);
12057
+ const details = splitDetails(markdown);
12058
+ const iterationInfo = {};
12059
+ for (const field of schema.iterationFields){
12060
+ const matched = new RegExp(`\\|\\s*${escapeRegExp(field)}\\s*\\|\\s*([^|]*)\\|`).exec(markdown);
12061
+ const value = matched?.[1]?.trim();
12062
+ if (void 0 !== value && value.length > 0) iterationInfo[field] = value;
12063
+ }
12064
+ return {
12065
+ valid: false,
12066
+ iterationInfo,
12067
+ stats: {
12068
+ requirements: requirements.length,
12069
+ tasks: tasks.length,
12070
+ completedTasks: tasks.filter((task)=>'已完成' === task.status).length,
12071
+ details: details.length
12072
+ },
12073
+ requirements,
12074
+ tasks,
12075
+ errors: structureErrors,
12076
+ warnings: []
12077
+ };
12078
+ }
12079
+ function readMarkdown(target) {
12080
+ return readFileSync(target, 'utf8');
12081
+ }
12082
+ function readIterationDoc(docsRoot, iteration, developer, source = 'local', presetRef, refName) {
12083
+ const safeIteration = iterations_safeSegment(iteration, '迭代目录');
12084
+ const safeDeveloper = iterations_safeSegment(developer, '开发者标识');
12085
+ if ('remote' === source) {
12086
+ const ref = presetRef ?? resolveRemoteRef(docsRoot, refName);
12087
+ const exported = exportRemoteDoc(docsRoot, ref, safeIteration, safeDeveloper);
12088
+ const roleInferred = inferRole(exported.markdown);
12089
+ const scripted = runValidator({
12090
+ docsRoot: exported.dir,
12091
+ scriptPath: exported.scriptPath,
12092
+ iteration: safeIteration,
12093
+ developer: safeDeveloper,
12094
+ role: roleInferred
12095
+ });
12096
+ return {
12097
+ iteration: safeIteration,
12098
+ developer: safeDeveloper,
12099
+ file: `${safeIteration}/${safeDeveloper}.md`,
12100
+ mtime: exported.mtime,
12101
+ roleInferred,
12102
+ parser: null === scripted ? 'fallback' : "script",
12103
+ source: 'remote',
12104
+ ref: {
12105
+ name: ref.ref,
12106
+ sha: ref.sha
12107
+ },
12108
+ validation: scripted ?? parseMarkdownDoc(exported.markdown, loadDocSchema(exported.dir)),
12109
+ details: splitDetails(exported.markdown)
12110
+ };
12111
+ }
12112
+ const directory = joinWithin(docsRoot, safeIteration);
12113
+ if (!external_node_fs_existsSync(directory)) throw new errors_CliError(`迭代目录不存在:${safeIteration}`, errors_EXIT.NOT_FOUND);
12114
+ const file = joinWithin(directory, `${safeDeveloper}.md`);
12115
+ if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${safeIteration}/${safeDeveloper}.md`, errors_EXIT.NOT_FOUND);
12116
+ const markdown = readMarkdown(file);
12117
+ const roleInferred = inferRole(markdown);
12118
+ const scripted = runValidator({
12119
+ docsRoot,
12120
+ scriptPath: external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py'),
12121
+ iteration: safeIteration,
12122
+ developer: safeDeveloper,
12123
+ role: roleInferred
12124
+ });
12125
+ const validation = scripted ?? parseMarkdownDoc(markdown, loadDocSchema(docsRoot));
12126
+ const parser = null === scripted ? 'fallback' : "script";
12127
+ return {
12128
+ iteration: safeIteration,
12129
+ developer: safeDeveloper,
12130
+ file,
12131
+ mtime: statSync(file).mtime.toISOString(),
12132
+ roleInferred,
12133
+ parser,
12134
+ source: 'local',
12135
+ ref: null,
12136
+ validation,
12137
+ details: splitDetails(markdown)
12138
+ };
12139
+ }
12140
+ function readIterationSummary(docsRoot, iteration, source = 'local', refName) {
12141
+ const safeIteration = iterations_safeSegment(iteration, '迭代目录');
12142
+ const remoteRef = 'remote' === source ? resolveRemoteRef(docsRoot, refName) : null;
12143
+ let developers;
12144
+ if (null === remoteRef) {
12145
+ const directory = joinWithin(docsRoot, safeIteration);
12146
+ if (!external_node_fs_existsSync(directory)) throw new errors_CliError(`迭代目录不存在:${safeIteration}`, errors_EXIT.NOT_FOUND);
12147
+ developers = listMarkdownFiles(directory);
12148
+ } else {
12149
+ const snapshot = listRemoteIterations(docsRoot, remoteRef);
12150
+ const found = snapshot.iterations.find((item)=>item.name === safeIteration);
12151
+ if (void 0 === found) throw new errors_CliError(`远程快照中不存在迭代:${safeIteration}`, errors_EXIT.NOT_FOUND);
12152
+ developers = found.developers;
12153
+ }
12154
+ const summaries = [];
12155
+ const blocked = [];
12156
+ for (const entry of developers){
12157
+ const doc = readIterationDoc(docsRoot, safeIteration, entry.id, source, remoteRef ?? void 0);
12158
+ const statusCounts = {};
12159
+ const selfTestCounts = {};
12160
+ const acceptanceCounts = {};
12161
+ for (const task of doc.validation.tasks){
12162
+ bump(statusCounts, 0 === task.status.length ? '未知' : task.status);
12163
+ bump(selfTestCounts, normalizeSelfTest(task.selfTest));
12164
+ bump(acceptanceCounts, normalizeAcceptance(task.acceptance));
12165
+ }
12166
+ const byId = new Map(doc.validation.tasks.map((task)=>[
12167
+ task.id,
12168
+ task
12169
+ ]));
12170
+ for (const task of doc.validation.tasks){
12171
+ if ('已完成' === task.status) continue;
12172
+ const blocking = task.dependencies.map((dep)=>{
12173
+ const target = byId.get(dep);
12174
+ return void 0 === target ? null : {
12175
+ id: dep,
12176
+ status: target.status
12177
+ };
12178
+ }).filter((item)=>null !== item && '已完成' !== item.status);
12179
+ if (blocking.length > 0) blocked.push({
12180
+ developer: entry.id,
12181
+ taskId: task.id,
12182
+ name: task.name,
12183
+ dependencies: task.dependencies,
12184
+ blocking
12185
+ });
12186
+ }
12187
+ const requirementStatusCounts = {};
12188
+ for (const requirement of doc.validation.requirements)bump(requirementStatusCounts, 0 === requirement.status.length ? '未知' : requirement.status);
12189
+ summaries.push({
12190
+ id: entry.id,
12191
+ roleInferred: doc.roleInferred,
12192
+ parser: doc.parser,
12193
+ stats: doc.validation.stats,
12194
+ statusCounts,
12195
+ requirementStatusCounts,
12196
+ selfTestCounts,
12197
+ acceptanceCounts,
12198
+ errors: doc.validation.errors.length,
12199
+ warnings: doc.validation.warnings.length,
12200
+ mtime: doc.mtime
12201
+ });
12202
+ }
12203
+ const mergeCounts = (pick)=>{
12204
+ const merged = {};
12205
+ for (const item of summaries)for (const [status, count] of Object.entries(pick(item)))merged[status] = (merged[status] ?? 0) + count;
12206
+ return merged;
12207
+ };
12208
+ const totals = summaries.reduce((acc, item)=>({
12209
+ developers: acc.developers + 1,
12210
+ requirements: acc.requirements + item.stats.requirements,
12211
+ tasks: acc.tasks + item.stats.tasks,
12212
+ completedTasks: acc.completedTasks + item.stats.completedTasks,
12213
+ errors: acc.errors + item.errors,
12214
+ warnings: acc.warnings + item.warnings
12215
+ }), {
12216
+ developers: 0,
12217
+ requirements: 0,
12218
+ tasks: 0,
12219
+ completedTasks: 0,
12220
+ errors: 0,
12221
+ warnings: 0
12222
+ });
12223
+ return {
12224
+ iteration: safeIteration,
12225
+ docsRoot,
12226
+ source,
12227
+ ref: null === remoteRef ? null : {
12228
+ name: remoteRef.ref,
12229
+ sha: remoteRef.sha,
12230
+ committedAt: remoteRef.committedAt
12231
+ },
12232
+ totals: {
12233
+ ...totals,
12234
+ progress: 0 === totals.tasks ? 0 : Math.round(totals.completedTasks / totals.tasks * 100),
12235
+ taskStatusCounts: mergeCounts((item)=>item.statusCounts),
12236
+ requirementStatusCounts: mergeCounts((item)=>item.requirementStatusCounts),
12237
+ selfTestCounts: mergeCounts((item)=>item.selfTestCounts),
12238
+ acceptanceCounts: mergeCounts((item)=>item.acceptanceCounts)
12239
+ },
12240
+ developers: summaries,
12241
+ blocked
12242
+ };
12243
+ }
12244
+ function checkDocTaskSides(options) {
12245
+ const file = external_node_path_join(options.docsRoot, options.iteration, `${options.developer}.md`);
12246
+ if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${options.iteration}/${options.developer}.md`, errors_EXIT.NOT_FOUND);
12247
+ const markdown = readFileSync(file, 'utf8');
12248
+ const schema = loadDocSchema(options.docsRoot);
12249
+ const payload = parseMarkdownDoc(markdown, schema);
12250
+ return validateTaskSides({
12251
+ index: buildRepoSideIndex(options.terminals),
12252
+ tasks: payload.tasks.map((task)=>({
12253
+ id: task.id,
12254
+ scope: task.scope,
12255
+ terminal: task.terminal
12256
+ }))
12257
+ });
12258
+ }
12259
+ const taskdoc_SAFE_SEGMENT = /^[A-Za-z0-9._\-\u4e00-\u9fa5]+$/;
12260
+ function taskdoc_safeSegment(value, label) {
12261
+ const trimmed = value.trim();
12262
+ if (!taskdoc_SAFE_SEGMENT.test(trimmed) || '.' === trimmed || '..' === trimmed) throw new errors_CliError(`${label} 不合法:${value}`, errors_EXIT.USAGE);
12263
+ return trimmed;
12264
+ }
12265
+ function buildCommitMessage(iteration, action, taskIds, _action) {
12266
+ const meta = ACTION_META[action];
12267
+ return `docs(${iteration}): ${meta.label} ${taskIds.join(',')}(${meta.from}→${meta.to})`;
12268
+ }
12269
+ function nowStamp() {
12270
+ const now = new Date();
12271
+ const pad = (value)=>String(value).padStart(2, '0');
12272
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
12273
+ }
12274
+ const ACTION_META = {
12275
+ start: {
12276
+ label: '开始实施',
12277
+ from: '未开始',
12278
+ to: '进行中'
12279
+ },
12280
+ submit: {
12281
+ label: '提交验收',
12282
+ from: '进行中',
12283
+ to: '待验收'
12284
+ },
12285
+ accept: {
12286
+ label: '验收通过',
12287
+ from: '待验收',
12288
+ to: '已完成'
12289
+ },
12290
+ reject: {
12291
+ label: '验收驳回',
12292
+ from: '待验收',
12293
+ to: '进行中'
12294
+ }
12295
+ };
12296
+ function commitInDocsRepo(docsRoot, file, message, push) {
12297
+ const run = (args)=>{
12298
+ try {
12299
+ const output = execFileSync('git', args, {
12300
+ cwd: docsRoot,
12301
+ encoding: 'utf8',
12302
+ stdio: [
12303
+ 'ignore',
12304
+ 'pipe',
12305
+ 'pipe'
12306
+ ]
12307
+ });
12308
+ return {
12309
+ ok: true,
12310
+ output
12311
+ };
12312
+ } catch (error) {
12313
+ const stderr = error.stderr ?? '';
12314
+ return {
12315
+ ok: false,
12316
+ output: stderr.trim() || String(error)
12317
+ };
12318
+ }
12319
+ };
12320
+ const inside = run([
12321
+ 'rev-parse',
12322
+ '--is-inside-work-tree'
12323
+ ]);
12324
+ if (!inside.ok || 'true' !== inside.output.trim()) return {
12325
+ committed: false,
12326
+ pushed: false,
12327
+ message: '文档仓库不是 git 仓库,已跳过提交'
12328
+ };
12329
+ let realRoot = docsRoot;
12330
+ try {
12331
+ realRoot = realpathSync(docsRoot);
12332
+ } catch {}
12333
+ const targets = Array.isArray(file) ? file : [
12334
+ file
12335
+ ];
12336
+ const relativePaths = [];
12337
+ for (const item of targets){
12338
+ let realFile = item;
12339
+ try {
12340
+ realFile = realpathSync(item);
12341
+ } catch {}
12342
+ const relativePath = external_node_path_relative(realRoot, realFile);
12343
+ if (relativePath.startsWith('..') || isAbsolute(relativePath)) return {
12344
+ committed: false,
12345
+ pushed: false,
12346
+ message: '目标文件不在文档仓库内,已跳过提交'
12347
+ };
12348
+ relativePaths.push(relativePath);
12349
+ }
12350
+ const added = run([
12351
+ 'add',
12352
+ '--',
12353
+ ...relativePaths
12354
+ ]);
12355
+ if (!added.ok) return {
12356
+ committed: false,
12357
+ pushed: false,
12358
+ message: `git add 失败:${added.output.split('\n')[0] ?? ''}`
12359
+ };
12360
+ const committed = run([
12361
+ 'commit',
12362
+ '-m',
12363
+ message,
12364
+ '--',
12365
+ ...relativePaths
12366
+ ]);
12367
+ if (!committed.ok) {
12368
+ const firstLine = committed.output.split('\n')[0] ?? '';
12369
+ return {
12370
+ committed: false,
12371
+ pushed: false,
12372
+ message: `提交未完成:${firstLine}`
12373
+ };
12374
+ }
12375
+ if (!push) return {
12376
+ committed: true,
12377
+ pushed: false,
12378
+ message: '已提交(未推送)'
12379
+ };
12380
+ const pushed = run([
12381
+ 'push'
12382
+ ]);
12383
+ if (!pushed.ok) return {
12384
+ committed: true,
12385
+ pushed: false,
12386
+ message: `已提交但推送失败,请手动处理:${pushed.output.split('\n')[0] ?? ''}`
12387
+ };
12388
+ return {
12389
+ committed: true,
12390
+ pushed: true,
12391
+ message: '已提交并推送'
12392
+ };
12393
+ }
12394
+ function appendHistory(entry) {
12395
+ try {
12396
+ const target = historyPath();
12397
+ mkdirSync(external_node_path_dirname(target), {
12398
+ recursive: true
12399
+ });
12400
+ appendFileSync(target, `${JSON.stringify({
12401
+ at: new Date().toISOString(),
12402
+ ...entry
12403
+ })}\n`, 'utf8');
12404
+ } catch {}
12405
+ }
12406
+ function readTaskHistory(options) {
12407
+ const target = historyPath();
12408
+ if (!external_node_fs_existsSync(target)) return [];
12409
+ const limit = options.limit ?? 5;
12410
+ const lines = readFileSync(target, 'utf8').trim().split('\n').filter((line)=>line.length > 0);
12411
+ const entries = [];
12412
+ for(let index = lines.length - 1; index >= 0 && entries.length < limit; index -= 1){
12413
+ const line = lines[index];
12414
+ if (void 0 !== line) try {
12415
+ const parsed = JSON.parse(line);
12416
+ if (parsed.iteration.toLowerCase() !== options.iteration.toLowerCase()) continue;
12417
+ if (parsed.developer !== options.developer) continue;
12418
+ if (void 0 !== options.taskId && parsed.taskId !== options.taskId) continue;
12419
+ entries.push(parsed);
12420
+ } catch {
12421
+ continue;
12422
+ }
12423
+ }
12424
+ return entries;
12425
+ }
12426
+ function buildKeys(schema) {
12427
+ const h = schema.taskHeaders;
12428
+ const r = schema.requirementHeaders;
12429
+ return {
12430
+ task: {
12431
+ id: h[0] ?? '任务编号',
12432
+ requirement: h[1] ?? '关联需求编号',
12433
+ selfTest: h[6] ?? 'AI自测状态',
12434
+ acceptance: h[7] ?? '开发人工验收',
12435
+ status: h[8] ?? '任务状态',
12436
+ updatedAt: h[9] ?? '最后更新'
12437
+ },
12438
+ requirement: {
12439
+ id: r[0] ?? '需求编号',
12440
+ status: r[3] ?? '开发状态',
12441
+ progress: r[4] ?? '开发进度(%)',
12442
+ updatedAt: r[6] ?? '最后更新'
12443
+ },
12444
+ taskSection: `## ${schema.sections[2] ?? '三、任务清单'}`,
12445
+ requirementSection: `## ${schema.sections[1] ?? '二、需求清单'}`
12446
+ };
12447
+ }
12448
+ function columnIndex(headerCells, name) {
12449
+ const index = headerCells.findIndex((cell)=>cell.trim() === name);
12450
+ if (index < 0) throw new errors_CliError(`表格缺少列「${name}」,无法安全写入`, errors_EXIT.INVALID);
12451
+ return index;
12452
+ }
12453
+ function splitRow(line) {
12454
+ const trimmed = line.trim();
12455
+ const inner = trimmed.startsWith('|') ? trimmed.slice(1) : trimmed;
12456
+ const withoutTail = inner.endsWith('|') ? inner.slice(0, -1) : inner;
12457
+ return withoutTail.split('|').map((cell)=>cell.trim());
12458
+ }
12459
+ function taskdoc_joinRow(cells) {
12460
+ return `| ${cells.join(' | ')} |`;
12461
+ }
12462
+ function canSubmit(selfTest) {
12463
+ const text = selfTest.trim();
12464
+ return '通过' === text || text.startsWith('免测');
12465
+ }
12466
+ function sectionRange(lines, heading) {
12467
+ const start = lines.findIndex((line)=>line.trim() === heading);
12468
+ if (start < 0) throw new errors_CliError(`文档缺少章节「${heading}」,无法安全写入`, errors_EXIT.INVALID);
12469
+ let end = lines.length;
12470
+ for(let index = start + 1; index < lines.length; index += 1){
12471
+ const line = lines[index] ?? '';
12472
+ if (/^##\s+/.test(line) || /^#\s+/.test(line)) {
12473
+ end = index;
12474
+ break;
12475
+ }
12476
+ }
12477
+ return [
12478
+ start,
12479
+ end
12480
+ ];
12481
+ }
12482
+ function parseTaskRows(lines, keys) {
12483
+ const [start, end] = sectionRange(lines, keys.taskSection);
12484
+ let header = null;
12485
+ const rows = [];
12486
+ for(let index = start; index < end; index += 1){
12487
+ const line = lines[index] ?? '';
12488
+ if (!line.trim().startsWith('|')) continue;
12489
+ const cells = splitRow(line);
12490
+ if (null === header) {
12491
+ if (cells.includes(keys.task.id)) header = cells;
12492
+ continue;
12493
+ }
12494
+ if (cells.every((cell)=>/^:?-{2,}:?$/.test(cell))) continue;
12495
+ const taskId = cells[columnIndex(header, keys.task.id)] ?? '';
12496
+ if (/^#\d{3,6}-T\d+$/.test(taskId)) rows.push({
12497
+ index,
12498
+ cells,
12499
+ taskId,
12500
+ status: cells[columnIndex(header, keys.task.status)] ?? '',
12501
+ acceptance: cells[columnIndex(header, keys.task.acceptance)] ?? '',
12502
+ selfTest: cells[columnIndex(header, keys.task.selfTest)] ?? '',
12503
+ requirementId: cells[columnIndex(header, keys.task.requirement)] ?? ''
12504
+ });
12505
+ }
12506
+ if (null === header) throw new errors_CliError('未找到任务清单表头,无法安全写入', errors_EXIT.INVALID);
12507
+ return {
12508
+ header,
12509
+ rows
12510
+ };
12511
+ }
12512
+ function parseRequirementRows(lines, keys) {
12513
+ const [start, end] = sectionRange(lines, keys.requirementSection);
12514
+ let header = null;
12515
+ const rows = [];
12516
+ for(let index = start; index < end; index += 1){
12517
+ const line = lines[index] ?? '';
12518
+ if (!line.trim().startsWith('|')) continue;
12519
+ const cells = splitRow(line);
12520
+ if (null === header) {
12521
+ if (cells.includes(keys.requirement.id)) header = cells;
12522
+ continue;
12523
+ }
12524
+ if (cells.every((cell)=>/^:?-{2,}:?$/.test(cell))) continue;
12525
+ const id = cells[columnIndex(header, keys.requirement.id)] ?? '';
12526
+ if (/^#\d{3,6}$/.test(id)) rows.push({
12527
+ index,
12528
+ cells,
12529
+ id
12530
+ });
12531
+ }
12532
+ if (null === header) throw new errors_CliError('未找到需求清单表头,无法安全写入', errors_EXIT.INVALID);
12533
+ return {
12534
+ header,
12535
+ rows
12536
+ };
12537
+ }
12538
+ function taskdoc_aggregateRequirementStatus(statuses) {
12539
+ if (0 === statuses.length) return '未开始';
12540
+ if (statuses.every((status)=>'未开始' === status)) return '未开始';
12541
+ if (statuses.every((status)=>'已完成' === status)) return '已完成';
12542
+ return '进行中';
12543
+ }
12544
+ function updateDetailBlock(lines, taskId, updates) {
12545
+ const headingIndex = lines.findIndex((line)=>line.trim().startsWith(`### [${taskId}]`));
12546
+ if (headingIndex < 0) throw new errors_CliError(`任务 ${taskId} 缺少第四章详情区块,无法同步状态`, errors_EXIT.INVALID);
12547
+ let end = lines.length;
12548
+ for(let index = headingIndex + 1; index < lines.length; index += 1)if (/^###\s+/.test(lines[index] ?? '') || /^##\s+/.test(lines[index] ?? '')) {
12549
+ end = index;
12550
+ break;
12551
+ }
12552
+ const next = [
12553
+ ...lines
12554
+ ];
12555
+ for(let index = headingIndex; index < end; index += 1){
12556
+ const line = lines[index] ?? '';
12557
+ const match = /^(\s*-\s+\*\*(.+?)\*\*\s*[::]\s*)(.*)$/.exec(line);
12558
+ if (null === match) continue;
12559
+ const field = match[2] ?? '';
12560
+ const replacement = updates[field];
12561
+ if (void 0 !== replacement) next[index] = `${match[1] ?? ''}${replacement}`;
12562
+ }
12563
+ return next;
12564
+ }
12565
+ function realIterationName(docsRoot, iteration) {
12566
+ try {
12567
+ const match = external_node_fs_readdirSync(docsRoot).find((entry)=>entry.toLowerCase() === iteration.toLowerCase());
12568
+ return match ?? iteration;
12569
+ } catch {
12570
+ return iteration;
12571
+ }
12572
+ }
12573
+ function loadDoc(docsRoot, iterationRaw, developerRaw) {
12574
+ const iteration = realIterationName(docsRoot, taskdoc_safeSegment(iterationRaw, '迭代目录'));
12575
+ const developer = taskdoc_safeSegment(developerRaw, '开发者标识');
12576
+ const file = external_node_path_join(docsRoot, iteration, `${developer}.md`);
12577
+ if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${iteration}/${developer}.md`, errors_EXIT.NOT_FOUND);
12578
+ const mtime = statSync(file).mtimeMs;
12579
+ const original = readFileSync(file, 'utf8');
12580
+ return {
12581
+ file,
12582
+ mtime,
12583
+ original,
12584
+ lines: original.split('\n')
12585
+ };
12586
+ }
12587
+ function computeUpdate(lines, taskId, action, keys) {
12588
+ const { header, rows } = parseTaskRows(lines, keys);
12589
+ const target = rows.find((row)=>row.taskId === taskId);
12590
+ if (void 0 === target) throw new errors_CliError(`任务清单中未找到 ${taskId}`, errors_EXIT.NOT_FOUND);
12591
+ const statusIndex = columnIndex(header, keys.task.status);
12592
+ const acceptanceIndex = columnIndex(header, keys.task.acceptance);
12593
+ const currentStatus = target.status;
12594
+ const currentAcceptance = target.acceptance;
12595
+ const meta = ACTION_META[action];
12596
+ if (currentStatus !== meta.from) throw new errors_CliError(`任务 ${taskId} 当前状态为「${currentStatus}」,无法执行「${meta.label}」(要求「${meta.from}」)`, errors_EXIT.USAGE);
12597
+ if ('submit' === action && !canSubmit(target.selfTest)) throw new errors_CliError(`任务 ${taskId} 的 AI 自测状态为「${target.selfTest}」,未通过自测不能提交验收`, errors_EXIT.USAGE);
12598
+ const nextStatus = meta.to;
12599
+ const nextAcceptance = 'accept' === action ? '验收通过' : 'reject' === action ? '验收驳回' : currentAcceptance;
12600
+ const changes = [];
12601
+ if (nextStatus !== currentStatus) changes.push(`${taskId} 任务状态:${currentStatus} → ${nextStatus}`);
12602
+ if (nextAcceptance !== currentAcceptance) changes.push(`${taskId} 开发人工验收:${currentAcceptance} → ${nextAcceptance}`);
12603
+ const stamp = nowStamp();
12604
+ const updated = [
12605
+ ...lines
12606
+ ];
12607
+ const taskCells = [
12608
+ ...target.cells
12609
+ ];
12610
+ taskCells[statusIndex] = nextStatus;
12611
+ taskCells[acceptanceIndex] = nextAcceptance;
12612
+ taskCells[columnIndex(header, keys.task.updatedAt)] = stamp;
12613
+ updated[target.index] = taskdoc_joinRow(taskCells);
12614
+ const withDetail = updateDetailBlock(updated, taskId, {
12615
+ 任务状态: nextStatus,
12616
+ 人工验收: nextAcceptance
12617
+ });
12618
+ const requirementStatuses = rows.filter((row)=>row.requirementId === target.requirementId).map((row)=>row.taskId === taskId ? nextStatus : row.status);
12619
+ const requirementStatus = taskdoc_aggregateRequirementStatus(requirementStatuses);
12620
+ const completed = requirementStatuses.filter((status)=>'已完成' === status).length;
12621
+ const progress = 0 === requirementStatuses.length ? 0 : Math.round(completed / requirementStatuses.length * 100);
12622
+ const requirementParse = parseRequirementRows(withDetail, keys);
12623
+ const requirementTarget = requirementParse.rows.find((row)=>row.id === target.requirementId);
12624
+ if (void 0 === requirementTarget) throw new errors_CliError(`需求清单中未找到 ${target.requirementId}`, errors_EXIT.NOT_FOUND);
12625
+ const requirementCells = [
12626
+ ...requirementTarget.cells
12627
+ ];
12628
+ const previousStatus = requirementCells[columnIndex(requirementParse.header, keys.requirement.status)] ?? '';
12629
+ const previousProgress = requirementCells[columnIndex(requirementParse.header, keys.requirement.progress)] ?? '';
12630
+ requirementCells[columnIndex(requirementParse.header, keys.requirement.status)] = requirementStatus;
12631
+ requirementCells[columnIndex(requirementParse.header, keys.requirement.progress)] = String(progress);
12632
+ if (previousStatus !== requirementStatus || previousProgress !== String(progress)) requirementCells[columnIndex(requirementParse.header, keys.requirement.updatedAt)] = stamp;
12633
+ withDetail[requirementTarget.index] = taskdoc_joinRow(requirementCells);
12634
+ if (previousStatus !== requirementStatus) changes.push(`需求 ${target.requirementId} 开发状态:${previousStatus} → ${requirementStatus}`);
12635
+ if (previousProgress !== String(progress)) changes.push(`需求 ${target.requirementId} 开发进度:${previousProgress}% → ${progress}%`);
12636
+ return {
12637
+ lines: withDetail,
12638
+ changes
12639
+ };
12640
+ }
12641
+ function commit(context, lines, changes, message, iteration, developer, action, taskIds, options) {
12642
+ if (statSync(context.file).mtimeMs !== context.mtime) throw new errors_CliError('文件已被外部修改,请刷新后重试', errors_EXIT.INVALID);
12643
+ const output = lines.join('\n');
12644
+ if (output === context.original) return {
12645
+ ok: true,
12646
+ message: '状态未发生变化',
12647
+ changes: [],
12648
+ file: context.file
12649
+ };
12650
+ writeFileSync(context.file, output, 'utf8');
12651
+ const violation = validateAfterWrite(external_node_path_dirname(context.file), iteration, developer);
12652
+ if (null !== violation) {
12653
+ writeFileSync(context.file, context.original, 'utf8');
12654
+ throw new errors_CliError(`写入被校验器拒绝,已回滚:${violation}`, errors_EXIT.INVALID);
12655
+ }
12656
+ appendHistory({
12657
+ iteration,
12658
+ developer,
12659
+ taskId: taskIds.join(','),
12660
+ action,
12661
+ changes
12662
+ });
12663
+ const git = options.policy.commit ? commitInDocsRepo(options.docsRoot, context.file, options.commitMessage, options.policy.push) : void 0;
12664
+ return {
12665
+ ok: true,
12666
+ message,
12667
+ changes,
12668
+ file: context.file,
12669
+ git
12670
+ };
12671
+ }
12672
+ function applyBatchAction(options) {
12673
+ if (0 === options.taskIds.length) throw new errors_CliError('未选择任务', errors_EXIT.USAGE);
12674
+ assertWritableBranch(options.docsRoot);
12675
+ const keys = buildKeys(loadDocSchema(options.docsRoot));
12676
+ const context = loadDoc(options.docsRoot, options.iteration, options.developer);
12677
+ let lines = context.lines;
12678
+ const changes = [];
12679
+ for (const taskId of options.taskIds){
12680
+ const result = computeUpdate(lines, taskId, options.action, keys);
12681
+ lines = result.lines;
12682
+ changes.push(...result.changes);
12683
+ }
12684
+ return commit(context, lines, changes, `已对 ${options.taskIds.length} 个任务执行「${ACTION_META[options.action].label}」`, taskdoc_safeSegment(options.iteration, '迭代目录'), taskdoc_safeSegment(options.developer, '开发者标识'), options.action, options.taskIds, {
12685
+ docsRoot: options.docsRoot,
12686
+ policy: options.policy,
12687
+ commitMessage: buildCommitMessage(options.iteration, options.action, options.taskIds, options.action)
12688
+ });
12689
+ }
12690
+ function applyTaskAction(options) {
12691
+ assertWritableBranch(options.docsRoot);
12692
+ const keys = buildKeys(loadDocSchema(options.docsRoot));
12693
+ const context = loadDoc(options.docsRoot, options.iteration, options.developer);
12694
+ const result = computeUpdate(context.lines, options.taskId, options.action, keys);
12695
+ return commit(context, result.lines, result.changes, `已执行「${ACTION_META[options.action].label}」`, taskdoc_safeSegment(options.iteration, '迭代目录'), taskdoc_safeSegment(options.developer, '开发者标识'), options.action, [
12696
+ options.taskId
12697
+ ], {
12698
+ docsRoot: options.docsRoot,
12699
+ policy: options.policy,
12700
+ commitMessage: buildCommitMessage(options.iteration, options.action, [
12701
+ options.taskId
12702
+ ], options.action)
12703
+ });
12704
+ }
12705
+ function validateAfterWrite(docsRoot, iteration, developer) {
12706
+ const script = external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py');
12707
+ if (!external_node_fs_existsSync(script)) return null;
12708
+ const targetFile = external_node_path_join(docsRoot, iteration, `${developer}.md`);
12709
+ let role = 'frontend';
12710
+ if (external_node_fs_existsSync(targetFile)) try {
12711
+ role = inferRole(readFileSync(targetFile, 'utf8'));
12712
+ } catch {
12713
+ role = 'frontend';
12714
+ }
12715
+ let scriptError = null;
12716
+ for (const bin of [
12717
+ 'python3',
12718
+ 'python',
12719
+ 'py'
12720
+ ])try {
12721
+ const stdout = execFileSync(bin, [
12722
+ script,
12723
+ '--docs-root',
12724
+ docsRoot,
12725
+ '--iteration',
12726
+ iteration,
12727
+ '--developer',
12728
+ developer,
12729
+ '--role',
12730
+ role,
12731
+ '--format',
12732
+ 'json'
12733
+ ], {
11695
12734
  encoding: 'utf8',
11696
- timeout: 10000,
12735
+ timeout: 15000,
11697
12736
  maxBuffer: 16777216
11698
12737
  });
11699
- const parsed = coercePayload(JSON.parse(stdout));
11700
- if (null !== parsed) return parsed;
12738
+ const payload = JSON.parse(stdout);
12739
+ const first = payload.errors?.[0];
12740
+ return first?.message ?? null;
11701
12741
  } catch (error) {
11702
- const stdout = error.stdout;
11703
- if ('string' == typeof stdout && stdout.trim().length > 0) try {
11704
- const parsed = coercePayload(JSON.parse(stdout));
11705
- if (null !== parsed) return parsed;
11706
- } catch {}
12742
+ const { stdout, stderr, code } = error;
12743
+ if ((stdout ?? '').trim().length > 0) try {
12744
+ const payload = JSON.parse(stdout ?? '');
12745
+ return payload.errors?.[0]?.message ?? '校验器未通过';
12746
+ } catch {
12747
+ scriptError = '校验器输出无法解析';
12748
+ continue;
12749
+ }
12750
+ if ('ENOENT' === code || 127 === code) continue;
12751
+ const reason = (stderr ?? '').trim().split('\n')[0] ?? '';
12752
+ scriptError = reason.length > 0 ? `校验器执行失败:${reason}` : '校验器执行失败';
12753
+ continue;
11707
12754
  }
12755
+ if (null !== scriptError) return scriptError;
11708
12756
  return null;
11709
12757
  }
11710
- function extractSection(markdown, heading) {
11711
- const lines = markdown.split(/\r?\n/);
11712
- let start = -1;
11713
- for(let index = 0; index < lines.length; index += 1)if ((lines[index] ?? '').trim() === heading) {
11714
- start = index + 1;
11715
- break;
11716
- }
11717
- if (start < 0) return '';
11718
- const collected = [];
11719
- for(let index = start; index < lines.length; index += 1){
11720
- const line = lines[index] ?? '';
11721
- if (/^##\s+/.test(line)) break;
11722
- collected.push(line);
12758
+ function recalcRequirements(options) {
12759
+ assertWritableBranch(options.docsRoot);
12760
+ const keys = buildKeys(loadDocSchema(options.docsRoot));
12761
+ const context = loadDoc(options.docsRoot, options.iteration, options.developer);
12762
+ const { rows: taskRows } = parseTaskRows(context.lines, keys);
12763
+ const requirementParse = parseRequirementRows(context.lines, keys);
12764
+ const lines = [
12765
+ ...context.lines
12766
+ ];
12767
+ const changes = [];
12768
+ for (const requirement of requirementParse.rows){
12769
+ const own = taskRows.filter((row)=>row.requirementId === requirement.id);
12770
+ const status = taskdoc_aggregateRequirementStatus(own.map((row)=>row.status));
12771
+ const completed = own.filter((row)=>'已完成' === row.status).length;
12772
+ const progress = 0 === own.length ? 0 : Math.round(completed / own.length * 100);
12773
+ const cells = [
12774
+ ...requirement.cells
12775
+ ];
12776
+ const previousStatus = cells[columnIndex(requirementParse.header, keys.requirement.status)] ?? '';
12777
+ const previousProgress = cells[columnIndex(requirementParse.header, keys.requirement.progress)] ?? '';
12778
+ if (previousStatus !== status || previousProgress !== String(progress)) {
12779
+ cells[columnIndex(requirementParse.header, keys.requirement.status)] = status;
12780
+ cells[columnIndex(requirementParse.header, keys.requirement.progress)] = String(progress);
12781
+ lines[requirement.index] = taskdoc_joinRow(cells);
12782
+ if (previousStatus !== status) changes.push(`${requirement.id} 开发状态:${previousStatus} → ${status}`);
12783
+ if (previousProgress !== String(progress)) changes.push(`${requirement.id} 开发进度:${previousProgress}% → ${progress}%`);
12784
+ }
11723
12785
  }
11724
- return collected.join('\n').trim();
12786
+ if (true === options.dryRun || 0 === changes.length) return {
12787
+ changes,
12788
+ file: context.file
12789
+ };
12790
+ return {
12791
+ changes,
12792
+ file: commit(context, lines, changes, `已重算 ${requirementParse.rows.length} 个需求的状态与进度`, taskdoc_safeSegment(options.iteration, '迭代目录'), taskdoc_safeSegment(options.developer, '开发者标识'), 'start', [], {
12793
+ docsRoot: options.docsRoot,
12794
+ policy: {
12795
+ commit: false,
12796
+ push: false
12797
+ },
12798
+ commitMessage: `docs(${options.iteration}): 重算需求状态与进度`
12799
+ }).file
12800
+ };
11725
12801
  }
11726
- function splitDetails(markdown) {
11727
- const section = extractSection(markdown, '## 四、任务详情');
11728
- if (0 === section.length) return [];
11729
- const blocks = [];
11730
- const parts = section.split(/^###\s+/m).slice(1);
11731
- for (const part of parts){
11732
- const [firstLine, ...rest] = part.split(/\r?\n/);
11733
- const heading = (firstLine ?? '').trim();
11734
- const match = /^\[?([#\w\-\u4e00-\u9fa5]+)\]?\s*(.*)$/.exec(heading);
11735
- const id = match?.[1] ?? heading;
11736
- const name = match?.[2]?.trim() ?? '';
11737
- blocks.push({
11738
- id,
11739
- name,
11740
- markdown: rest.join('\n').trim()
12802
+ function availableActions(options) {
12803
+ const iteration = taskdoc_safeSegment(options.iteration, '迭代目录');
12804
+ const developer = taskdoc_safeSegment(options.developer, '开发者标识');
12805
+ const file = external_node_path_join(options.docsRoot, iteration, `${developer}.md`);
12806
+ if (!external_node_fs_existsSync(file)) return {};
12807
+ const lines = readFileSync(file, 'utf8').split('\n');
12808
+ const { rows } = parseTaskRows(lines, buildKeys(loadDocSchema(options.docsRoot)));
12809
+ const result = {};
12810
+ for (const row of rows){
12811
+ const list = [];
12812
+ if ('未开始' === row.status) list.push({
12813
+ action: 'start',
12814
+ enabled: true,
12815
+ reason: ''
11741
12816
  });
12817
+ if ('进行中' === row.status) {
12818
+ const ok = canSubmit(row.selfTest);
12819
+ list.push({
12820
+ action: 'submit',
12821
+ enabled: ok,
12822
+ reason: ok ? '' : `AI 自测为「${row.selfTest}」,需先通过自测`
12823
+ });
12824
+ }
12825
+ if ('待验收' === row.status) {
12826
+ list.push({
12827
+ action: 'accept',
12828
+ enabled: true,
12829
+ reason: ''
12830
+ });
12831
+ list.push({
12832
+ action: 'reject',
12833
+ enabled: true,
12834
+ reason: ''
12835
+ });
12836
+ }
12837
+ result[row.taskId] = list;
11742
12838
  }
11743
- return blocks;
12839
+ return result;
11744
12840
  }
11745
- function parseMarkdownDoc(markdown) {
11746
- const structureErrors = [];
11747
- const readTable = (sectionHeading, headers)=>{
11748
- const section = extractSection(markdown, sectionHeading);
11749
- const rows = section.split(/\r?\n/).map((line)=>line.trim()).filter((line)=>line.startsWith('|')).map((line)=>line.replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell)=>cell.trim())).filter((cells)=>!cells.every((cell)=>/^:?-{2,}:?$/.test(cell) || 0 === cell.length));
11750
- const [header, ...body] = rows;
11751
- if (void 0 === header) return [];
11752
- const matched = headers.every((name, index)=>(header[index] ?? '') === name);
11753
- return matched ? body : [];
11754
- };
11755
- const requirementRows = readTable('## 二、需求清单', [
11756
- '需求编号',
11757
- '需求名称',
11758
- '终端',
11759
- '开发状态',
11760
- '开发进度(%)',
11761
- '备注',
11762
- '最后更新'
11763
- ]);
11764
- const taskRows = readTable('## 三、任务清单', [
11765
- '任务编号',
11766
- '关联需求编号',
11767
- '任务名称',
11768
- '任务类型',
11769
- '终端',
11770
- '前置依赖任务编号',
11771
- 'AI自测状态',
11772
- '开发人工验收',
11773
- '任务状态',
11774
- '最后更新'
11775
- ]);
11776
- if (0 === requirementRows.length) structureErrors.push({
11777
- level: 'error',
11778
- code: 'REQUIREMENT_TABLE_MISMATCH',
11779
- message: '需求清单表头与模板不符(需包含「最后更新」列),请按最新模板补齐'
11780
- });
11781
- if (0 === taskRows.length) structureErrors.push({
11782
- level: 'error',
11783
- code: 'TASK_TABLE_MISMATCH',
11784
- message: '任务清单表头与模板不符(需包含「最后更新」列),请按最新模板补齐'
12841
+ const SYNC_DIRS = new Set([
12842
+ "scripts",
12843
+ 'skills',
12844
+ 'docs',
12845
+ '_prd',
12846
+ 'node_modules'
12847
+ ]);
12848
+ function doc_migrate_listIterations(docsRoot) {
12849
+ return external_node_fs_readdirSync(docsRoot).filter((name)=>!name.startsWith('.') && !SYNC_DIRS.has(name)).filter((name)=>{
12850
+ try {
12851
+ return statSync(external_node_path_join(docsRoot, name)).isDirectory();
12852
+ } catch {
12853
+ return false;
12854
+ }
11785
12855
  });
11786
- const requirements = requirementRows.map((row)=>({
11787
- id: row[0] ?? '',
11788
- title: row[1] ?? '',
11789
- terminal: row[2] ?? '',
11790
- status: row[3] ?? '',
11791
- progress: row[4] ?? '',
11792
- note: row[5] ?? '',
11793
- updatedAt: row[6] ?? '',
11794
- taskIds: []
11795
- }));
11796
- const tasks = taskRows.map((row)=>({
11797
- id: row[0] ?? '',
11798
- requirementId: row[1] ?? '',
11799
- name: row[2] ?? '',
11800
- type: row[3] ?? '',
11801
- terminal: row[4] ?? '',
11802
- dependencies: (row[5] ?? '').split(/[,,]/).map((item)=>item.trim()).filter((item)=>item.length > 0),
11803
- selfTest: row[6] ?? '',
11804
- acceptance: row[7] ?? '',
11805
- status: row[8] ?? '',
11806
- updatedAt: row[9] ?? ''
11807
- }));
11808
- for (const requirement of requirements)requirement.taskIds = tasks.filter((task)=>task.requirementId === requirement.id).map((task)=>task.id);
11809
- const details = splitDetails(markdown);
11810
- const infoMatch = /\|\s*迭代版本\s*\|\s*([^|]*)\|/.exec(markdown);
11811
- const prdMatch = /\|\s*PRD 来源\s*\|\s*([^|]*)\|/.exec(markdown);
11812
- const planMatch = /\|\s*排期计划\s*\|\s*([^|]*)\|/.exec(markdown);
11813
- const ownerMatch = /\|\s*负责人\s*\|\s*([^|]*)\|/.exec(markdown);
11814
- const scopeMatch = /\|\s*负责范围\s*\|\s*([^|]*)\|/.exec(markdown);
11815
- const iterationInfo = {};
11816
- const put = (key, match)=>{
11817
- const value = match?.[1]?.trim();
11818
- if (void 0 !== value && value.length > 0) iterationInfo[key] = value;
11819
- };
11820
- put('迭代版本', infoMatch);
11821
- put('PRD 来源', prdMatch);
11822
- put('排期计划', planMatch);
11823
- put('负责人', ownerMatch);
11824
- put('负责范围', scopeMatch);
12856
+ }
12857
+ function doc_migrate_splitRow(line) {
12858
+ const trimmed = line.trim();
12859
+ if (!trimmed.startsWith('|')) return null;
12860
+ const inner = trimmed.endsWith('|') ? trimmed.slice(1, -1) : trimmed.slice(1);
12861
+ return inner.split('|').map((cell)=>cell.trim());
12862
+ }
12863
+ function doc_migrate_joinRow(cells) {
12864
+ return `| ${cells.join(' | ')} |`;
12865
+ }
12866
+ function isSeparator(cells) {
12867
+ return cells.every((cell)=>/^:?-{2,}:?$/.test(cell));
12868
+ }
12869
+ function locateTaskTable(lines, schema) {
12870
+ const heading = `## ${schema.sections[2] ?? '三、任务清单'}`;
12871
+ const sectionStart = lines.findIndex((line)=>line.trim() === heading);
12872
+ if (sectionStart < 0) return null;
12873
+ let headerIndex = -1;
12874
+ let endIndex = lines.length;
12875
+ for(let index = sectionStart + 1; index < lines.length; index += 1){
12876
+ const line = lines[index] ?? '';
12877
+ if (/^##\s+/.test(line)) {
12878
+ endIndex = index;
12879
+ break;
12880
+ }
12881
+ const cells = doc_migrate_splitRow(line);
12882
+ if (null !== cells) {
12883
+ if (headerIndex < 0) headerIndex = index;
12884
+ }
12885
+ }
12886
+ if (headerIndex < 0) return null;
12887
+ const header = doc_migrate_splitRow(lines[headerIndex] ?? '') ?? [];
11825
12888
  return {
11826
- valid: false,
11827
- iterationInfo,
11828
- stats: {
11829
- requirements: requirements.length,
11830
- tasks: tasks.length,
11831
- completedTasks: tasks.filter((task)=>'已完成' === task.status).length,
11832
- details: details.length
11833
- },
11834
- requirements,
11835
- tasks,
11836
- errors: structureErrors,
11837
- warnings: []
12889
+ start: sectionStart,
12890
+ end: endIndex,
12891
+ header
11838
12892
  };
11839
12893
  }
11840
- function readMarkdown(target) {
11841
- return readFileSync(target, 'utf8');
11842
- }
11843
- function readIterationDoc(docsRoot, iteration, developer, source = 'local', presetRef, refName) {
11844
- const safeIteration = iterations_safeSegment(iteration, '迭代目录');
11845
- const safeDeveloper = iterations_safeSegment(developer, '开发者标识');
11846
- if ('remote' === source) {
11847
- const ref = presetRef ?? resolveRemoteRef(docsRoot, refName);
11848
- const exported = exportRemoteDoc(docsRoot, ref, safeIteration, safeDeveloper);
11849
- const roleInferred = inferRole(exported.markdown);
11850
- const scripted = runValidator({
11851
- docsRoot: exported.dir,
11852
- scriptPath: exported.scriptPath,
11853
- iteration: safeIteration,
11854
- developer: safeDeveloper,
11855
- role: roleInferred
12894
+ function migrateTaskTable(options) {
12895
+ const { schema } = options;
12896
+ const table = locateTaskTable(options.lines, schema);
12897
+ if (null === table) return {
12898
+ lines: options.lines,
12899
+ added: 0,
12900
+ unresolved: []
12901
+ };
12902
+ const headerIndex = options.lines.findIndex((line, index)=>index > table.start && index < table.end && null !== doc_migrate_splitRow(line));
12903
+ if (headerIndex < 0) return {
12904
+ lines: options.lines,
12905
+ added: 0,
12906
+ unresolved: []
12907
+ };
12908
+ const header = doc_migrate_splitRow(options.lines[headerIndex] ?? '') ?? [];
12909
+ const missing = schema.taskHeaders.filter((name)=>!header.includes(name));
12910
+ if (0 === missing.length) return {
12911
+ lines: options.lines,
12912
+ added: 0,
12913
+ unresolved: []
12914
+ };
12915
+ const nextHeader = [
12916
+ ...schema.taskHeaders
12917
+ ];
12918
+ const lines = [
12919
+ ...options.lines
12920
+ ];
12921
+ lines[headerIndex] = doc_migrate_joinRow(nextHeader);
12922
+ if (headerIndex + 1 < options.lines.length) {
12923
+ const separator = doc_migrate_splitRow(options.lines[headerIndex + 1] ?? '');
12924
+ if (null !== separator && isSeparator(separator)) lines[headerIndex + 1] = doc_migrate_joinRow(nextHeader.map(()=>'---'));
12925
+ }
12926
+ const unresolved = [];
12927
+ let added = 0;
12928
+ const idIndex = header.indexOf('任务编号');
12929
+ const typeIndex = header.indexOf('任务类型');
12930
+ const terminalIndex = header.indexOf('终端');
12931
+ for(let index = headerIndex + 2; index < table.end; index += 1){
12932
+ const cells = doc_migrate_splitRow(options.lines[index] ?? '');
12933
+ if (null === cells || isSeparator(cells)) continue;
12934
+ const record = {};
12935
+ header.forEach((name, position)=>{
12936
+ record[name] = cells[position] ?? '';
11856
12937
  });
11857
- return {
11858
- iteration: safeIteration,
11859
- developer: safeDeveloper,
11860
- file: `${safeIteration}/${safeDeveloper}.md`,
11861
- mtime: exported.mtime,
11862
- roleInferred,
11863
- parser: null === scripted ? 'fallback' : "script",
11864
- source: 'remote',
11865
- ref: {
11866
- name: ref.ref,
11867
- sha: ref.sha
11868
- },
11869
- validation: scripted ?? parseMarkdownDoc(exported.markdown),
11870
- details: splitDetails(exported.markdown)
11871
- };
12938
+ for (const name of missing)if ('所属端' === name) {
12939
+ const taskId = cells[idIndex >= 0 ? idIndex : 0] ?? '';
12940
+ const type = cells[typeIndex >= 0 ? typeIndex : 0] ?? '';
12941
+ const terminal = cells[terminalIndex >= 0 ? terminalIndex : 0] ?? '';
12942
+ let value = '';
12943
+ if (0 === value.length) {
12944
+ const side = sideOfTypeName(schema, type);
12945
+ value = 'frontend' === side ? '前端' : 'backend' === side ? '后端' : '';
12946
+ }
12947
+ if (0 === value.length) value = options.resolveScopeFromTerminal(terminal);
12948
+ if (0 === value.length) unresolved.push(taskId);
12949
+ record[name] = value;
12950
+ } else record[name] = '';
12951
+ lines[index] = doc_migrate_joinRow(nextHeader.map((name)=>record[name] ?? ''));
12952
+ added += 1;
11872
12953
  }
11873
- const directory = joinWithin(docsRoot, safeIteration);
11874
- if (!external_node_fs_existsSync(directory)) throw new errors_CliError(`迭代目录不存在:${safeIteration}`, errors_EXIT.NOT_FOUND);
11875
- const file = joinWithin(directory, `${safeDeveloper}.md`);
11876
- if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${safeIteration}/${safeDeveloper}.md`, errors_EXIT.NOT_FOUND);
11877
- const markdown = readMarkdown(file);
11878
- const roleInferred = inferRole(markdown);
11879
- const scripted = runValidator({
11880
- docsRoot,
11881
- scriptPath: external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py'),
11882
- iteration: safeIteration,
11883
- developer: safeDeveloper,
11884
- role: roleInferred
11885
- });
11886
- const validation = scripted ?? parseMarkdownDoc(markdown);
11887
- const parser = null === scripted ? 'fallback' : "script";
11888
12954
  return {
11889
- iteration: safeIteration,
11890
- developer: safeDeveloper,
11891
- file,
11892
- mtime: statSync(file).mtime.toISOString(),
11893
- roleInferred,
11894
- parser,
11895
- source: 'local',
11896
- ref: null,
11897
- validation,
11898
- details: splitDetails(markdown)
12955
+ lines,
12956
+ added,
12957
+ unresolved
11899
12958
  };
11900
12959
  }
11901
- function readIterationSummary(docsRoot, iteration, source = 'local', refName) {
11902
- const safeIteration = iterations_safeSegment(iteration, '迭代目录');
11903
- const remoteRef = 'remote' === source ? resolveRemoteRef(docsRoot, refName) : null;
11904
- let developers;
11905
- if (null === remoteRef) {
11906
- const directory = joinWithin(docsRoot, safeIteration);
11907
- if (!external_node_fs_existsSync(directory)) throw new errors_CliError(`迭代目录不存在:${safeIteration}`, errors_EXIT.NOT_FOUND);
11908
- developers = listMarkdownFiles(directory);
11909
- } else {
11910
- const snapshot = listRemoteIterations(docsRoot, remoteRef);
11911
- const found = snapshot.iterations.find((item)=>item.name === safeIteration);
11912
- if (void 0 === found) throw new errors_CliError(`远程快照中不存在迭代:${safeIteration}`, errors_EXIT.NOT_FOUND);
11913
- developers = found.developers;
12960
+ function locateDetailBlocks(lines, schema) {
12961
+ const heading = `## ${schema.sections[3] ?? '四、任务详情'}`;
12962
+ const sectionStart = lines.findIndex((line)=>line.trim() === heading);
12963
+ if (sectionStart < 0) return [];
12964
+ const blocks = [];
12965
+ let current = null;
12966
+ for(let index = sectionStart + 1; index < lines.length; index += 1){
12967
+ const line = lines[index] ?? '';
12968
+ if (/^##\s+/.test(line)) break;
12969
+ const matched = /^###\s+\[(#[^\]]+)\]/.exec(line.trim());
12970
+ if (null !== matched) {
12971
+ if (null !== current) current.endIndex = index;
12972
+ current = {
12973
+ taskId: matched[1] ?? '',
12974
+ headingIndex: index,
12975
+ endIndex: lines.length
12976
+ };
12977
+ blocks.push(current);
12978
+ }
12979
+ }
12980
+ return blocks;
12981
+ }
12982
+ function fieldSpans(lines, block) {
12983
+ const spans = [];
12984
+ for(let index = block.headingIndex + 1; index < block.endIndex; index += 1){
12985
+ const line = lines[index] ?? '';
12986
+ const matched = /^\s*-\s+\*\*(.+?)\*\*\s*[::]/.exec(line);
12987
+ if (null !== matched) {
12988
+ const previous = spans[spans.length - 1];
12989
+ if (void 0 !== previous) previous.end = index;
12990
+ spans.push({
12991
+ name: (matched[1] ?? '').trim(),
12992
+ start: index,
12993
+ end: block.endIndex
12994
+ });
12995
+ }
11914
12996
  }
11915
- const summaries = [];
11916
- const blocked = [];
11917
- for (const entry of developers){
11918
- const doc = readIterationDoc(docsRoot, safeIteration, entry.id, source, remoteRef ?? void 0);
11919
- const statusCounts = {};
11920
- const selfTestCounts = {};
11921
- const acceptanceCounts = {};
11922
- for (const task of doc.validation.tasks){
11923
- bump(statusCounts, 0 === task.status.length ? '未知' : task.status);
11924
- bump(selfTestCounts, normalizeSelfTest(task.selfTest));
11925
- bump(acceptanceCounts, normalizeAcceptance(task.acceptance));
12997
+ return spans;
12998
+ }
12999
+ function migrateDetailFields(options) {
13000
+ const { schema } = options;
13001
+ const blocks = locateDetailBlocks(options.lines, schema);
13002
+ let lines = [
13003
+ ...options.lines
13004
+ ];
13005
+ let added = 0;
13006
+ for (const block of [
13007
+ ...blocks
13008
+ ].reverse()){
13009
+ const scope = options.scopeByTaskId.get(block.taskId) ?? '';
13010
+ const required = scope.length > 0 ? detailFieldsOfScope(schema, scope) : [];
13011
+ if (0 === required.length) continue;
13012
+ const spans = fieldSpans(lines, block);
13013
+ const present = new Set(spans.map((span)=>span.name));
13014
+ const missing = required.filter((name)=>!present.has(name));
13015
+ if (0 !== missing.length) for (const name of missing){
13016
+ const requiredIndex = required.indexOf(name);
13017
+ let insertAt = block.headingIndex + 2;
13018
+ for(let cursor = requiredIndex - 1; cursor >= 0; cursor -= 1){
13019
+ const previousName = required[cursor];
13020
+ if (void 0 === previousName) continue;
13021
+ const span = spans.find((item)=>item.name === previousName);
13022
+ if (void 0 !== span) {
13023
+ insertAt = span.end;
13024
+ break;
13025
+ }
13026
+ }
13027
+ lines = [
13028
+ ...lines.slice(0, insertAt),
13029
+ `- **${name}**:<待补充>`,
13030
+ ...lines.slice(insertAt)
13031
+ ];
13032
+ const refreshed = fieldSpans(lines, block);
13033
+ spans.length = 0;
13034
+ spans.push(...refreshed);
13035
+ added += 1;
11926
13036
  }
11927
- const byId = new Map(doc.validation.tasks.map((task)=>[
11928
- task.id,
11929
- task
11930
- ]));
11931
- for (const task of doc.validation.tasks){
11932
- if ('已完成' === task.status) continue;
11933
- const blocking = task.dependencies.map((dep)=>{
11934
- const target = byId.get(dep);
11935
- return void 0 === target ? null : {
11936
- id: dep,
11937
- status: target.status
11938
- };
11939
- }).filter((item)=>null !== item && '已完成' !== item.status);
11940
- if (blocking.length > 0) blocked.push({
11941
- developer: entry.id,
11942
- taskId: task.id,
11943
- name: task.name,
11944
- dependencies: task.dependencies,
11945
- blocking
13037
+ }
13038
+ return {
13039
+ lines,
13040
+ added
13041
+ };
13042
+ }
13043
+ function makeTerminalResolver(terminals) {
13044
+ const index = buildRepoSideIndex(terminals);
13045
+ return (repoName)=>{
13046
+ const side = sideOfRepo(index, repoName);
13047
+ if ('frontend' === side) return '前端';
13048
+ if ('backend' === side) return '后端';
13049
+ return '';
13050
+ };
13051
+ }
13052
+ function runDocMigrate(options) {
13053
+ const format = parseFormat(options.format);
13054
+ const loaded = loadConfig(options.config);
13055
+ if (!loaded.exists || null === loaded.config) throw new errors_CliError(`配置未初始化:${loaded.path}\n请先运行:ylcwf init`, errors_EXIT.NOT_FOUND);
13056
+ const config = loaded.config;
13057
+ const docsRoot = config.docs.root;
13058
+ if (true !== options.dryRun) assertWritableBranch(docsRoot);
13059
+ const schema = loadDocSchema(docsRoot);
13060
+ const resolveScopeFromTerminal = makeTerminalResolver(config.terminals);
13061
+ const iterations = options.iteration?.trim() ? [
13062
+ options.iteration.trim()
13063
+ ] : doc_migrate_listIterations(docsRoot);
13064
+ const results = [];
13065
+ const changedFiles = [];
13066
+ for (const iteration of iterations){
13067
+ const dir = external_node_path_join(docsRoot, iteration);
13068
+ if (!external_node_fs_existsSync(dir)) continue;
13069
+ const files = external_node_fs_readdirSync(dir).filter((name)=>name.endsWith('.md') && !name.startsWith('_'));
13070
+ for (const name of files){
13071
+ const target = external_node_path_join(dir, name);
13072
+ const original = readFileSync(target, 'utf8');
13073
+ const tableMigrated = migrateTaskTable({
13074
+ lines: original.split('\n'),
13075
+ schema,
13076
+ resolveScopeFromTerminal
11946
13077
  });
13078
+ const scopeByTaskId = collectTaskScopes(tableMigrated.lines, schema);
13079
+ const detailMigrated = migrateDetailFields({
13080
+ lines: tableMigrated.lines,
13081
+ schema,
13082
+ scopeByTaskId
13083
+ });
13084
+ const addedRows = tableMigrated.added;
13085
+ const addedFields = detailMigrated.added;
13086
+ if (0 === addedRows && 0 === addedFields) continue;
13087
+ const migrated = {
13088
+ lines: detailMigrated.lines,
13089
+ unresolved: tableMigrated.unresolved
13090
+ };
13091
+ results.push({
13092
+ file: `${iteration}/${name}`,
13093
+ added: addedRows,
13094
+ addedFields,
13095
+ unresolved: tableMigrated.unresolved
13096
+ });
13097
+ if (true === options.dryRun) continue;
13098
+ writeFileSync(target, migrated.lines.join('\n'), 'utf8');
13099
+ changedFiles.push(target);
13100
+ if (migrated.unresolved.length > 0) continue;
13101
+ const developer = basename(name, '.md');
13102
+ const violation = validateAfterWrite(docsRoot, iteration, developer);
13103
+ if (null !== violation) {
13104
+ writeFileSync(target, original, 'utf8');
13105
+ throw new errors_CliError(`迁移后校验未通过,已回滚 ${iteration}/${name}:${violation}`, errors_EXIT.INVALID);
13106
+ }
11947
13107
  }
11948
- const requirementStatusCounts = {};
11949
- for (const requirement of doc.validation.requirements)bump(requirementStatusCounts, 0 === requirement.status.length ? '未知' : requirement.status);
11950
- summaries.push({
11951
- id: entry.id,
11952
- roleInferred: doc.roleInferred,
11953
- parser: doc.parser,
11954
- stats: doc.validation.stats,
11955
- statusCounts,
11956
- requirementStatusCounts,
11957
- selfTestCounts,
11958
- acceptanceCounts,
11959
- errors: doc.validation.errors.length,
11960
- warnings: doc.validation.warnings.length,
11961
- mtime: doc.mtime
13108
+ }
13109
+ const totalUnresolved = results.flatMap((item)=>item.unresolved);
13110
+ if ('json' === format) return void printJson({
13111
+ ok: true,
13112
+ dryRun: true === options.dryRun,
13113
+ files: results,
13114
+ unresolved: totalUnresolved
13115
+ });
13116
+ if (0 === results.length) return void printLine('所有文档已符合 schema 的列结构,无需迁移');
13117
+ printLine(true === options.dryRun ? '将迁移:' : '已迁移:');
13118
+ for (const item of results){
13119
+ const extra = item.unresolved.length > 0 ? `(待人工补 ${item.unresolved.join('、')})` : '';
13120
+ const parts = [];
13121
+ if (item.added > 0) parts.push(`${item.added} 行任务`);
13122
+ if (item.addedFields > 0) parts.push(`${item.addedFields} 个详情字段`);
13123
+ printLine(` · ${item.file} ${parts.join(' + ')}${extra}`);
13124
+ }
13125
+ if (totalUnresolved.length > 0) {
13126
+ printLine('\n以下任务的「所属端」无法自动判定(终端未配置或类型两端通用),请手工补齐:');
13127
+ printLine(` ${totalUnresolved.join('、')}`);
13128
+ printLine('补齐后运行校验:');
13129
+ printLine(" python3 <文档仓库>/scripts/validate_task_doc.py --docs-root <文档仓库> \\");
13130
+ printLine(' --iteration <迭代> --developer <标识> --role <frontend|backend|fullstack>');
13131
+ }
13132
+ if (true !== options.dryRun) {
13133
+ const policy = config.docs.git.cli;
13134
+ if (policy.commit) {
13135
+ const git = commitInDocsRepo(docsRoot, changedFiles, "docs: 迁移任务表结构(按 schema.json)", policy.push);
13136
+ printLine(`\n${git.message}`);
13137
+ }
13138
+ }
13139
+ }
13140
+ function collectTaskScopes(lines, schema) {
13141
+ const result = new Map();
13142
+ const table = locateTaskTable(lines, schema);
13143
+ if (null === table) return result;
13144
+ const headerIndex = lines.findIndex((line, index)=>index > table.start && index < table.end && null !== doc_migrate_splitRow(line));
13145
+ if (headerIndex < 0) return result;
13146
+ const header = doc_migrate_splitRow(lines[headerIndex] ?? '') ?? [];
13147
+ const idIndex = header.indexOf('任务编号');
13148
+ const scopeIndex = header.indexOf('所属端');
13149
+ if (idIndex < 0 || scopeIndex < 0) return result;
13150
+ for(let index = headerIndex + 2; index < table.end; index += 1){
13151
+ const cells = doc_migrate_splitRow(lines[index] ?? '');
13152
+ if (null === cells || isSeparator(cells)) continue;
13153
+ const id = cells[idIndex] ?? '';
13154
+ const scope = cells[scopeIndex] ?? '';
13155
+ if (id.length > 0 && scope.length > 0) result.set(id, scope);
13156
+ }
13157
+ return result;
13158
+ }
13159
+ function registerDocMigrate(doc) {
13160
+ doc.command('migrate').description('按 schema.json 迁移存量文档(补缺失的任务列并回填)').option('-i, --iteration <name>', '只迁移指定迭代').option('--dry-run', '只打印将要迁移的文件,不写盘').option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
13161
+ runDocMigrate(options);
13162
+ });
13163
+ }
13164
+ function doc_nowStamp() {
13165
+ const now = new Date();
13166
+ const pad = (value)=>String(value).padStart(2, '0');
13167
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
13168
+ }
13169
+ function readPlanFile(path) {
13170
+ if (!external_node_fs_existsSync(path)) throw new errors_CliError(`plan 文件不存在:${path}`, errors_EXIT.NOT_FOUND);
13171
+ const text = readFileSync(path, 'utf8');
13172
+ try {
13173
+ return JSON.parse(text);
13174
+ } catch (error) {
13175
+ throw new errors_CliError(`plan 文件不是合法 JSON:${error instanceof Error ? error.message : String(error)}`, errors_EXIT.INVALID);
13176
+ }
13177
+ }
13178
+ function doc_realIterationName(docsRoot, iteration) {
13179
+ const direct = external_node_path_join(docsRoot, iteration);
13180
+ external_node_fs_existsSync(direct);
13181
+ return iteration;
13182
+ }
13183
+ function runDocApply(options, mode = 'apply') {
13184
+ const format = parseFormat(options.format);
13185
+ const loaded = loadConfig(options.config);
13186
+ if (!loaded.exists || null === loaded.config) throw new errors_CliError(`配置未初始化:${loaded.path}\n请先运行:ylcwf init`, errors_EXIT.NOT_FOUND);
13187
+ const config = loaded.config;
13188
+ const docsRoot = config.docs.root;
13189
+ const developer = config.profile.developer;
13190
+ const role = config.profile.role;
13191
+ const iteration = doc_realIterationName(docsRoot, options.iteration.trim());
13192
+ if (0 === iteration.length) throw new errors_CliError('必须指定迭代目录:--iteration <迭代>', errors_EXIT.USAGE);
13193
+ const schema = loadDocSchema(docsRoot);
13194
+ const plan = parseDocPlan(readPlanFile(options.input), schema, role);
13195
+ const targetDir = external_node_path_join(docsRoot, iteration);
13196
+ const targetFile = external_node_path_join(targetDir, `${developer}.md`);
13197
+ const exists = external_node_fs_existsSync(targetFile);
13198
+ const original = exists ? readFileSync(targetFile, 'utf8') : null;
13199
+ const mtime = exists ? statSync(targetFile).mtimeMs : 0;
13200
+ const parsed = null === original ? {
13201
+ requirements: [],
13202
+ tasks: []
13203
+ } : parseMarkdownDoc(original, schema);
13204
+ validatePlanReferences({
13205
+ plan,
13206
+ schema,
13207
+ role,
13208
+ index: buildRepoSideIndex(config.terminals),
13209
+ knownTaskIds: parsed.tasks.map((task)=>task.id)
13210
+ });
13211
+ const stamp = doc_nowStamp();
13212
+ const rendered = renderPlan({
13213
+ schema,
13214
+ role,
13215
+ plan,
13216
+ existing: {
13217
+ requirements: parsed.requirements,
13218
+ tasks: parsed.tasks,
13219
+ lines: null === original ? null : original.split('\n')
13220
+ },
13221
+ stamp,
13222
+ developer
13223
+ });
13224
+ const sideIndex = buildRepoSideIndex(config.terminals);
13225
+ const sideIssues = validateTaskSides({
13226
+ index: sideIndex,
13227
+ tasks: rendered.assigned.map((item)=>{
13228
+ const planned = plan.tasks.find((task)=>task.name === item.name);
13229
+ return {
13230
+ id: item.id,
13231
+ scope: planned?.scope ?? '',
13232
+ terminal: planned?.terminal ?? ''
13233
+ };
13234
+ })
13235
+ });
13236
+ const conflicts = sideIssues.filter((issue)=>'error' === issue.level);
13237
+ if (conflicts.length > 0) throw new errors_CliError(`任务类型与终端归属不一致,已中止:\n${conflicts.map((issue)=>` · ${issue.message}`).join('\n')}`, errors_EXIT.INVALID);
13238
+ if (0 === rendered.assigned.length && rendered.markdown === original) {
13239
+ if ('json' === format) printJson({
13240
+ ok: true,
13241
+ changed: false,
13242
+ file: targetFile,
13243
+ changes: [],
13244
+ assigned: []
11962
13245
  });
13246
+ else printLine('计划中的需求与任务都已存在,未做修改');
13247
+ return;
11963
13248
  }
11964
- const mergeCounts = (pick)=>{
11965
- const merged = {};
11966
- for (const item of summaries)for (const [status, count] of Object.entries(pick(item)))merged[status] = (merged[status] ?? 0) + count;
11967
- return merged;
11968
- };
11969
- const totals = summaries.reduce((acc, item)=>({
11970
- developers: acc.developers + 1,
11971
- requirements: acc.requirements + item.stats.requirements,
11972
- tasks: acc.tasks + item.stats.tasks,
11973
- completedTasks: acc.completedTasks + item.stats.completedTasks,
11974
- errors: acc.errors + item.errors,
11975
- warnings: acc.warnings + item.warnings
11976
- }), {
11977
- developers: 0,
11978
- requirements: 0,
11979
- tasks: 0,
11980
- completedTasks: 0,
11981
- errors: 0,
11982
- warnings: 0
13249
+ if ('diff' === mode || true === options.dryRun) {
13250
+ if ('json' === format) printJson({
13251
+ ok: true,
13252
+ dryRun: true,
13253
+ mode,
13254
+ file: targetFile,
13255
+ changes: rendered.changes,
13256
+ assigned: rendered.assigned,
13257
+ preview: rendered.markdown
13258
+ });
13259
+ else {
13260
+ printLine(`将写入:${targetFile}`);
13261
+ for (const change of rendered.changes)printLine(` · ${change}`);
13262
+ if (!exists) printLine('(文件不存在,将新建完整文档)');
13263
+ printLine('diff' === mode ? '\n(diff:未实际写入)' : '\n(--dry-run,未实际写入)');
13264
+ }
13265
+ return;
13266
+ }
13267
+ if (exists && statSync(targetFile).mtimeMs !== mtime) throw new errors_CliError('文件已被外部修改,请重试', errors_EXIT.INVALID);
13268
+ assertWritableBranch(docsRoot);
13269
+ mkdirSync(targetDir, {
13270
+ recursive: true
11983
13271
  });
11984
- return {
11985
- iteration: safeIteration,
13272
+ writeFileSync(targetFile, rendered.markdown, 'utf8');
13273
+ const violation = validateAfterWrite(docsRoot, iteration, developer);
13274
+ if (null !== violation) {
13275
+ if (null === original) unlinkSync(targetFile);
13276
+ else writeFileSync(targetFile, original, 'utf8');
13277
+ throw new errors_CliError(`写入被校验器拒绝,已回滚:${violation}`, errors_EXIT.INVALID);
13278
+ }
13279
+ const remaining = checkDocTaskSides({
11986
13280
  docsRoot,
11987
- source,
11988
- ref: null === remoteRef ? null : {
11989
- name: remoteRef.ref,
11990
- sha: remoteRef.sha,
11991
- committedAt: remoteRef.committedAt
11992
- },
11993
- totals: {
11994
- ...totals,
11995
- progress: 0 === totals.tasks ? 0 : Math.round(totals.completedTasks / totals.tasks * 100),
11996
- taskStatusCounts: mergeCounts((item)=>item.statusCounts),
11997
- requirementStatusCounts: mergeCounts((item)=>item.requirementStatusCounts),
11998
- selfTestCounts: mergeCounts((item)=>item.selfTestCounts),
11999
- acceptanceCounts: mergeCounts((item)=>item.acceptanceCounts)
12000
- },
12001
- developers: summaries,
12002
- blocked
12003
- };
13281
+ iteration,
13282
+ developer,
13283
+ role,
13284
+ terminals: config.terminals
13285
+ }).filter((issue)=>'error' === issue.level);
13286
+ const policy = config.docs.git.cli;
13287
+ const git = policy.commit ? commitInDocsRepo(docsRoot, targetFile, `docs: ${iteration} 新增 ${rendered.assigned.length} 个任务(${rendered.assigned.map((item)=>item.id).join('、')})`, policy.push) : void 0;
13288
+ if ('json' === format) printJson({
13289
+ ok: true,
13290
+ changed: true,
13291
+ file: targetFile,
13292
+ changes: rendered.changes,
13293
+ assigned: rendered.assigned,
13294
+ sideIssues: remaining.map((issue)=>issue.message),
13295
+ git
13296
+ });
13297
+ else {
13298
+ printLine(`已写入:${targetFile}`);
13299
+ for (const change of rendered.changes)printLine(` · ${change}`);
13300
+ if (remaining.length > 0) {
13301
+ printLine('\n注意:以下任务的类型与终端归属不一致(请核对):');
13302
+ for (const issue of remaining)printLine(` · ${issue.message}`);
13303
+ }
13304
+ if (void 0 !== git) printLine(`\n${git.message}`);
13305
+ }
13306
+ }
13307
+ function registerDoc(program) {
13308
+ const doc = program.command('doc').description('按结构化计划生成/追加迭代任务文档');
13309
+ 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)=>{
13310
+ runDocApply(options, 'diff');
13311
+ });
13312
+ 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)=>{
13313
+ runDocApply(options);
13314
+ });
13315
+ registerDocMigrate(doc);
12004
13316
  }
12005
13317
  function requireQueryContext(options) {
12006
13318
  const format = parseFormat(options.format);
@@ -12015,32 +13327,54 @@ function requireQueryContext(options) {
12015
13327
  format
12016
13328
  };
12017
13329
  }
12018
- function resolveIterationName(options, docsRoot, available, hints = {}) {
13330
+ function resolveIteration(options, docsRoot, available, hints = {}) {
12019
13331
  const explicit = options.iteration?.trim();
12020
13332
  if (void 0 !== explicit && explicit.length > 0) {
12021
13333
  const exact = available.find((item)=>item.name === explicit);
12022
- if (void 0 !== exact) return exact.name;
13334
+ if (void 0 !== exact) return {
13335
+ name: exact.name,
13336
+ source: 'explicit'
13337
+ };
12023
13338
  const loose = available.find((item)=>item.name.toLowerCase() === explicit.toLowerCase());
12024
- if (void 0 !== loose) return loose.name;
13339
+ if (void 0 !== loose) return {
13340
+ name: loose.name,
13341
+ source: 'explicit'
13342
+ };
12025
13343
  throw new errors_CliError(`迭代不存在:${explicit}\n可用迭代:${available.map((item)=>item.name).join('、') || '(无)'}`, errors_EXIT.NOT_FOUND);
12026
13344
  }
13345
+ const key = hints.taskId ?? hints.requirementId;
13346
+ if (void 0 !== key) {
13347
+ const found = findIterationById(docsRoot, available, key);
13348
+ if (null !== found) return {
13349
+ name: found,
13350
+ source: 'id'
13351
+ };
13352
+ const list = available.map((item)=>item.name).join('、') || '(无)';
13353
+ throw new errors_CliError(`在所有迭代中都未找到 ${key}\n已检索:${list}\n请确认编号是否正确,或用 -i 指定迭代`, errors_EXIT.NOT_FOUND);
13354
+ }
13355
+ const byBranch = resolveIterationFromBranch(docsRoot, available.map((item)=>item.name));
13356
+ if (null !== byBranch.iteration) return {
13357
+ name: byBranch.iteration,
13358
+ source: 'branch',
13359
+ branch: byBranch.branch ?? void 0
13360
+ };
12027
13361
  const cwd = process.cwd();
12028
13362
  if (cwd.startsWith(docsRoot)) {
12029
13363
  const first = cwd.slice(docsRoot.length).split('/').filter((item)=>item.length > 0)[0];
12030
13364
  if (void 0 !== first) {
12031
13365
  const hit = available.find((item)=>item.name.toLowerCase() === first.toLowerCase());
12032
- if (void 0 !== hit) return hit.name;
13366
+ if (void 0 !== hit) return {
13367
+ name: hit.name,
13368
+ source: 'cwd'
13369
+ };
12033
13370
  }
12034
13371
  }
12035
- const key = hints.taskId ?? hints.requirementId;
12036
- if (void 0 !== key) {
12037
- const found = findIterationById(docsRoot, available, key);
12038
- if (null !== found) return found;
12039
- const list = available.map((item)=>item.name).join('、') || '(无)';
12040
- throw new errors_CliError(`在所有迭代中都未找到 ${key}\n已检索:${list}\n请确认编号是否正确,或用 -i 指定迭代`, errors_EXIT.NOT_FOUND);
12041
- }
12042
13372
  const list = available.map((item)=>item.name).join('、') || '(无)';
12043
- throw new errors_CliError(`无法确定迭代目录\n可用迭代:${list}\n请在对话中明确迭代版本,或用 -i 指定;也可用 ylcwf iteration list 查看`, errors_EXIT.USAGE);
13373
+ const branchHint = byBranch.candidates.length > 0 ? `\n当前分支 ${byBranch.branch ?? ''} 同时匹配多个迭代:${byBranch.candidates.join('、')}` : null !== byBranch.branch ? `\n当前分支 ${byBranch.branch} 未匹配到任何迭代` : '';
13374
+ throw new errors_CliError(`无法确定迭代目录,请用 -i 指定。${branchHint}\n可用迭代:${list}`, errors_EXIT.NOT_FOUND);
13375
+ }
13376
+ function resolveIterationName(options, docsRoot, available, hints = {}) {
13377
+ return resolveIteration(options, docsRoot, available, hints).name;
12044
13378
  }
12045
13379
  function findIterationById(docsRoot, available, id) {
12046
13380
  const normalized = id.trim();
@@ -12075,6 +13409,18 @@ function loadDeveloperDocs(docsRoot, iteration) {
12075
13409
  doc: readIterationDoc(docsRoot, entry.name, item.id, 'local')
12076
13410
  }));
12077
13411
  }
13412
+ function describeIterationSource(resolved) {
13413
+ switch(resolved.source){
13414
+ case 'explicit':
13415
+ return '-i 指定';
13416
+ case 'id':
13417
+ return '编号反查';
13418
+ case 'branch':
13419
+ return `当前分支 ${resolved.branch ?? ''}`;
13420
+ case 'cwd':
13421
+ return '当前目录';
13422
+ }
13423
+ }
12078
13424
  function evaluateReadiness(tasks) {
12079
13425
  const byId = new Map(tasks.map((task)=>[
12080
13426
  task.id,
@@ -12111,6 +13457,7 @@ function buildTaskRows(docs) {
12111
13457
  requirementId: task.requirementId,
12112
13458
  type: task.type,
12113
13459
  terminal: task.terminal,
13460
+ scope: task.scope,
12114
13461
  status: task.status,
12115
13462
  selfTest: task.selfTest,
12116
13463
  acceptance: task.acceptance,
@@ -12134,12 +13481,48 @@ function mergeRequirements(docs) {
12134
13481
  note: requirement.note,
12135
13482
  updatedAt: requirement.updatedAt,
12136
13483
  developers: [],
12137
- taskIds: []
13484
+ taskIds: [],
13485
+ sides: {
13486
+ frontend: {
13487
+ done: 0,
13488
+ total: 0
13489
+ },
13490
+ backend: {
13491
+ done: 0,
13492
+ total: 0
13493
+ }
13494
+ }
12138
13495
  };
12139
13496
  if (!entry.developers.includes(developer)) entry.developers.push(developer);
12140
13497
  for (const taskId of requirement.taskIds)if (!entry.taskIds.includes(taskId)) entry.taskIds.push(taskId);
12141
13498
  map.set(requirement.id, entry);
12142
13499
  }
13500
+ const byTaskId = new Map();
13501
+ for (const row of buildTaskRows(docs))byTaskId.set(row.id, {
13502
+ scope: row.scope,
13503
+ done: '已完成' === row.status
13504
+ });
13505
+ for (const entry of map.values()){
13506
+ entry.sides = {
13507
+ frontend: {
13508
+ done: 0,
13509
+ total: 0
13510
+ },
13511
+ backend: {
13512
+ done: 0,
13513
+ total: 0
13514
+ }
13515
+ };
13516
+ for (const taskId of entry.taskIds){
13517
+ const info = byTaskId.get(taskId);
13518
+ if (void 0 === info) continue;
13519
+ const bucket = '前端' === info.scope ? entry.sides.frontend : '后端' === info.scope ? entry.sides.backend : null;
13520
+ if (null !== bucket) {
13521
+ bucket.total += 1;
13522
+ if (info.done) bucket.done += 1;
13523
+ }
13524
+ }
13525
+ }
12143
13526
  return [
12144
13527
  ...map.values()
12145
13528
  ].sort((left, right)=>left.id.localeCompare(right.id));
@@ -12149,16 +13532,19 @@ function filterDocs(docs, developer) {
12149
13532
  if (void 0 === target || 0 === target.length) return docs;
12150
13533
  return docs.filter((item)=>item.developer === target);
12151
13534
  }
12152
- function resolveIteration(options, docsRoot) {
12153
- const explicit = options.iteration?.trim();
12154
- if (void 0 !== explicit && explicit.length > 0) return explicit;
12155
- const cwd = process.cwd();
12156
- if (cwd.startsWith(docsRoot)) {
12157
- const relative = cwd.slice(docsRoot.length).split('/').filter((item)=>item.length > 0);
12158
- const first = relative[0];
12159
- if (void 0 !== first) return first;
13535
+ function collectSideIssues(options) {
13536
+ try {
13537
+ const loaded = requireConfig(options.config);
13538
+ return checkDocTaskSides({
13539
+ docsRoot: options.docsRoot,
13540
+ iteration: options.iteration,
13541
+ developer: options.developer,
13542
+ role: loaded.config.profile.role,
13543
+ terminals: loaded.config.terminals
13544
+ }).filter((issue)=>'error' === issue.level).map((issue)=>issue.message);
13545
+ } catch {
13546
+ return [];
12160
13547
  }
12161
- throw new errors_CliError('缺少 --iteration(迭代目录名),或在文档仓库的迭代目录内执行', errors_EXIT.USAGE);
12162
13548
  }
12163
13549
  function resolveDeveloper(options, configured) {
12164
13550
  const explicit = options.developer?.trim();
@@ -12187,7 +13573,7 @@ function requireWriteContext(options) {
12187
13573
  }
12188
13574
  function runAction(action, taskId, options) {
12189
13575
  const { docsRoot, developer, policy } = requireWriteContext(options);
12190
- const iteration = options.iteration?.trim() ? resolveIteration(options, docsRoot) : resolveIterationName(options, docsRoot, loadIterations(docsRoot), {
13576
+ const iteration = options.iteration?.trim() ? resolveIterationName(options, docsRoot, loadIterations(docsRoot)) : resolveIterationName(options, docsRoot, loadIterations(docsRoot), {
12191
13577
  taskId: taskId.trim().replace(/^#?/, '#')
12192
13578
  });
12193
13579
  const format = parseFormat(options.format);
@@ -12218,15 +13604,28 @@ function runAction(action, taskId, options) {
12218
13604
  action,
12219
13605
  policy
12220
13606
  });
12221
- if ('json' === format) return void printJson(result);
13607
+ const sideIssues = collectSideIssues({
13608
+ docsRoot,
13609
+ iteration,
13610
+ developer,
13611
+ config: options.config
13612
+ });
13613
+ if ('json' === format) return void printJson({
13614
+ ...result,
13615
+ sideIssues
13616
+ });
12222
13617
  printLine(result.message);
12223
13618
  for (const change of result.changes)printLine(` · ${change}`);
12224
13619
  printLine(`文档:${result.file}`);
12225
13620
  if (void 0 !== result.git) printLine(`git:${result.git.message}`);
13621
+ if (sideIssues.length > 0) {
13622
+ printLine('\n注意:该文档存在任务类型与终端归属不一致(可用 ylcwf doctor --docs 复查):');
13623
+ for (const message of sideIssues)printLine(` · ${message}`);
13624
+ }
12226
13625
  }
12227
13626
  function runActions(options) {
12228
13627
  const { docsRoot, developer } = requireWriteContext(options);
12229
- const iteration = resolveIteration(options, docsRoot);
13628
+ const iteration = resolveIterationName(options, docsRoot, loadIterations(docsRoot));
12230
13629
  const actions = availableActions({
12231
13630
  docsRoot,
12232
13631
  iteration,
@@ -12247,7 +13646,7 @@ function runActions(options) {
12247
13646
  }
12248
13647
  function runBatch(action, taskIds, options) {
12249
13648
  const { docsRoot, developer, policy } = requireWriteContext(options);
12250
- const iteration = resolveIteration(options, docsRoot);
13649
+ const iteration = resolveIterationName(options, docsRoot, loadIterations(docsRoot));
12251
13650
  const format = parseFormat(options.format);
12252
13651
  const result = applyBatchAction({
12253
13652
  docsRoot,
@@ -12264,7 +13663,7 @@ function runBatch(action, taskIds, options) {
12264
13663
  }
12265
13664
  function runHistory(taskId, options) {
12266
13665
  const { docsRoot, developer } = requireWriteContext(options);
12267
- const iteration = resolveIteration(options, docsRoot);
13666
+ const iteration = resolveIterationName(options, docsRoot, loadIterations(docsRoot));
12268
13667
  const entries = readTaskHistory({
12269
13668
  iteration,
12270
13669
  developer,
@@ -12280,16 +13679,19 @@ function runHistory(taskId, options) {
12280
13679
  }
12281
13680
  function runList(options) {
12282
13681
  const ctx = requireQueryContext(options);
12283
- const iteration = resolveIterationName(options, ctx.docsRoot, loadIterations(ctx.docsRoot));
13682
+ const resolved = resolveIteration(options, ctx.docsRoot, loadIterations(ctx.docsRoot));
13683
+ const iteration = resolved.name;
12284
13684
  const docs = loadDeveloperDocs(ctx.docsRoot, iteration);
12285
13685
  const developerFilter = options.developer?.trim();
12286
13686
  const statusFilter = options.status?.trim();
12287
13687
  const tasks = buildTaskRows(filterDocs(docs, developerFilter)).filter((task)=>void 0 === statusFilter ? true : task.status === statusFilter);
12288
13688
  if ('json' === ctx.format) return void printJson({
12289
13689
  iteration,
13690
+ iterationSource: describeIterationSource(resolved),
12290
13691
  tasks
12291
13692
  });
12292
13693
  if (0 === tasks.length) return void printLine(`迭代 ${iteration} 没有符合条件的任务`);
13694
+ if ('explicit' !== resolved.source) printLine(`迭代:${iteration}(来自${describeIterationSource(resolved)})`);
12293
13695
  const rows = tasks.map((task)=>[
12294
13696
  task.id,
12295
13697
  task.name,
@@ -12461,9 +13863,26 @@ function iteration_runShow(name, options) {
12461
13863
  }
12462
13864
  }
12463
13865
  }
13866
+ function runCurrent(options) {
13867
+ const format = parseFormat(options.format);
13868
+ const ctx = requireQueryContext(options);
13869
+ const iterations = loadIterations(ctx.docsRoot).map((item)=>item.name);
13870
+ const result = resolveIterationFromBranch(ctx.docsRoot, iterations);
13871
+ if ('json' === format) return void printJson({
13872
+ ok: true,
13873
+ ...result,
13874
+ available: iterations
13875
+ });
13876
+ printLine(`分支:${result.branch ?? '(detached HEAD)'}`);
13877
+ if (null !== result.iteration) return void printLine(`迭代:${result.iteration}`);
13878
+ if (result.candidates.length > 0) return void printLine(`分支名同时匹配多个迭代,请显式指定 -i:${result.candidates.join('、')}`);
13879
+ printLine('迭代:未从分支名识别出迭代目录');
13880
+ if (iterations.length > 0) printLine(`可用迭代:${iterations.join('、')}`);
13881
+ }
12464
13882
  function registerIteration(program) {
12465
13883
  const iteration = program.command('iteration').description('查看文档仓库中的迭代');
12466
13884
  iteration.command('list').description('列出全部迭代(目录名即迭代名)').option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').action((options)=>iteration_runList(options));
13885
+ iteration.command('current').description('从文档仓库当前分支推导迭代名(团队约定:一迭代一分支)').option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').action((options)=>runCurrent(options));
12467
13886
  iteration.command('show [name]').description('查看迭代汇总:成员进度与阻塞任务').option('-c, --config <path>', '指定配置文件路径').option('-i, --iteration <name>', '迭代目录名(也可作为位置参数)').option('--format <format>', '输出格式:human | json', 'human').action((name, options)=>iteration_runShow(name, options));
12468
13887
  }
12469
13888
  function runContext(options) {
@@ -12664,9 +14083,9 @@ async function fetchManifest(url) {
12664
14083
  const payload = await response.json();
12665
14084
  if ('string' != typeof payload.version || 0 === payload.version.length) return null;
12666
14085
  return {
12667
- current: "0.4.0",
14086
+ current: "0.5.0",
12668
14087
  latest: payload.version,
12669
- hasUpdate: isNewer(payload.version, "0.4.0"),
14088
+ hasUpdate: isNewer(payload.version, "0.5.0"),
12670
14089
  downloadUrl: 'string' == typeof payload.downloadUrl ? payload.downloadUrl : null,
12671
14090
  source: 'manifest',
12672
14091
  checkedAt: new Date().toISOString(),
@@ -12678,7 +14097,7 @@ async function fetchManifest(url) {
12678
14097
  }
12679
14098
  async function fetchNpm() {
12680
14099
  const base = {
12681
- current: "0.4.0",
14100
+ current: "0.5.0",
12682
14101
  latest: null,
12683
14102
  hasUpdate: false,
12684
14103
  downloadUrl: null,
@@ -12705,8 +14124,8 @@ async function fetchNpm() {
12705
14124
  return {
12706
14125
  ...base,
12707
14126
  latest,
12708
- hasUpdate: isNewer(latest, "0.4.0"),
12709
- downloadUrl: 'https://www.npmjs.com/package/ylcwf'
14127
+ hasUpdate: isNewer(latest, "0.5.0"),
14128
+ downloadUrl: null
12710
14129
  };
12711
14130
  } catch (error) {
12712
14131
  const message = error instanceof Error ? error.message : String(error);
@@ -12796,7 +14215,7 @@ async function runUpgrade(options) {
12796
14215
  const kind = detectInstallKind();
12797
14216
  const result = await checkUpdate(true);
12798
14217
  const target = options.to?.trim() ?? result.latest;
12799
- printLine("当前版本:0.4.0");
14218
+ printLine("当前版本:0.5.0");
12800
14219
  if (null !== result.error) printLine(`版本查询失败:${result.error}`);
12801
14220
  else if (null !== result.latest) printLine(`最新版本:${result.latest}(来源:${result.source})`);
12802
14221
  if (null === target) throw new errors_CliError('无法确定目标版本,请稍后重试或用 --to 指定', errors_EXIT.NOT_FOUND);
@@ -12951,6 +14370,39 @@ function registerResolve(program) {
12951
14370
  runResolve(name, options);
12952
14371
  });
12953
14372
  }
14373
+ function checkDocsSides(config) {
14374
+ const messages = [];
14375
+ const root = config.docs.root;
14376
+ let iterations;
14377
+ try {
14378
+ iterations = external_node_fs_readdirSync(root).filter((name)=>!name.startsWith('.') && ![
14379
+ "scripts",
14380
+ 'skills',
14381
+ '_prd'
14382
+ ].includes(name)).filter((name)=>{
14383
+ try {
14384
+ return statSync(external_node_path_join(root, name)).isDirectory();
14385
+ } catch {
14386
+ return false;
14387
+ }
14388
+ });
14389
+ } catch {
14390
+ return [
14391
+ `无法读取文档仓库:${root}`
14392
+ ];
14393
+ }
14394
+ for (const iteration of iterations)try {
14395
+ const issues = checkDocTaskSides({
14396
+ docsRoot: root,
14397
+ iteration,
14398
+ developer: config.profile.developer,
14399
+ role: config.profile.role,
14400
+ terminals: config.terminals
14401
+ });
14402
+ for (const issue of issues)messages.push(`[${iteration}] ${issue.message}`);
14403
+ } catch {}
14404
+ return messages;
14405
+ }
12954
14406
  function runDoctor(options) {
12955
14407
  const format = parseFormat(options.format);
12956
14408
  const loaded = loadConfig(options.config);
@@ -12960,21 +14412,31 @@ function runDoctor(options) {
12960
14412
  });
12961
14413
  const errors = countIssues(checked.issues).errors;
12962
14414
  const ok = !hasError(checked.issues);
14415
+ const sideMessages = [];
14416
+ if (true === options.docs && null !== checked.config && ok) sideMessages.push(...checkDocsSides(checked.config));
14417
+ const sideErrors = sideMessages.length;
14418
+ const allOk = ok && 0 === sideErrors;
12963
14419
  if ('json' === format) printJson({
12964
- ok,
14420
+ ok: allOk,
12965
14421
  configPath: loaded.path,
12966
14422
  ...countIssues(checked.issues),
12967
- issues: checked.issues
14423
+ issues: checked.issues,
14424
+ docSideIssues: sideMessages
12968
14425
  });
12969
14426
  else {
12970
14427
  printLine(`配置文件 ${loaded.path}`);
12971
14428
  printLine(formatIssues(checked.issues, '校验通过,未发现问题'));
12972
- if (!ok) printLine(`\n校验失败:${errors} 项 error`);
14429
+ if (sideMessages.length > 0) {
14430
+ printLine('');
14431
+ printLine('文档体检:');
14432
+ for (const message of sideMessages)printLine(` · ${message}`);
14433
+ }
14434
+ if (!allOk) printLine(`\n校验失败:${errors} 项配置 error${sideErrors > 0 ? `,${sideErrors} 项文档问题` : ''}`);
12973
14435
  }
12974
- if (!ok) process.exitCode = errors_EXIT.INVALID;
14436
+ if (!allOk) process.exitCode = errors_EXIT.INVALID;
12975
14437
  }
12976
14438
  function registerDoctor(program) {
12977
- program.command('doctor').description('严格校验配置(schema、路径存在性、终端唯一性)').option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
14439
+ program.command('doctor').description('严格校验配置(schema、路径存在性、终端唯一性)').option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').option('--docs', '同时体检文档:检查任务类型与终端归属是否一致').action((options)=>{
12978
14440
  runDoctor(options);
12979
14441
  });
12980
14442
  }
@@ -13137,7 +14599,7 @@ function readState(explicitPath) {
13137
14599
  issues: checked.issues,
13138
14600
  backups: listBackups(explicitPath),
13139
14601
  meta: {
13140
- version: "0.4.0",
14602
+ version: "0.5.0",
13141
14603
  features: SERVER_FEATURES
13142
14604
  }
13143
14605
  };
@@ -13772,7 +15234,7 @@ function registerReset(program) {
13772
15234
  }
13773
15235
  function buildProgram() {
13774
15236
  const program = new command_Command();
13775
- program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与终端仓库映射').version("0.4.0", '-v, --version', '显示版本号').showHelpAfterError();
15237
+ program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与终端仓库映射').version("0.5.0", '-v, --version', '显示版本号').showHelpAfterError();
13776
15238
  registerInit(program);
13777
15239
  registerShow(program);
13778
15240
  registerGet(program);
@@ -13781,6 +15243,7 @@ function buildProgram() {
13781
15243
  registerIteration(program);
13782
15244
  registerContext(program);
13783
15245
  registerRequirement(program);
15246
+ registerDoc(program);
13784
15247
  registerTask(program);
13785
15248
  registerUpgrade(program);
13786
15249
  registerResolve(program);