ylcwf 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { EventEmitter } from "node:events";
2
- import node_child_process, { execFileSync, spawn } from "node:child_process";
3
- import node_path, { basename, dirname as external_node_path_dirname, extname, isAbsolute, join as external_node_path_join, relative as external_node_path_relative, resolve, sep } from "node:path";
2
+ import node_child_process, { execFile, execFileSync, spawn } from "node:child_process";
3
+ import node_path, { basename, dirname as external_node_path_dirname, extname, isAbsolute, join as external_node_path_join, relative as external_node_path_relative, resolve as external_node_path_resolve, sep } from "node:path";
4
4
  import node_fs, { appendFileSync, chmodSync, closeSync, copyFileSync, existsSync as external_node_fs_existsSync, mkdirSync, openSync, readFileSync, readdirSync as external_node_fs_readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
5
5
  import node_process, { stdin as external_node_process_stdin, stdout as external_node_process_stdout } from "node:process";
6
6
  import { stripVTControlCharacters as external_node_util_stripVTControlCharacters, styleText as external_node_util_styleText } from "node:util";
@@ -9234,9 +9234,9 @@ const CONFIG_DIR = external_node_path_join(homedir(), '.ylcwf');
9234
9234
  const DEFAULT_CONFIG_PATH = external_node_path_join(CONFIG_DIR, 'config.yaml');
9235
9235
  function paths_resolveConfigPath(explicit) {
9236
9236
  const fromFlag = explicit?.trim();
9237
- if (void 0 !== fromFlag && fromFlag.length > 0) return isAbsolute(fromFlag) ? fromFlag : resolve(process.cwd(), fromFlag);
9237
+ if (void 0 !== fromFlag && fromFlag.length > 0) return isAbsolute(fromFlag) ? fromFlag : external_node_path_resolve(process.cwd(), fromFlag);
9238
9238
  const fromEnv = process.env['YLCWF_CONFIG']?.trim();
9239
- if (void 0 !== fromEnv && fromEnv.length > 0) return isAbsolute(fromEnv) ? fromEnv : resolve(process.cwd(), fromEnv);
9239
+ if (void 0 !== fromEnv && fromEnv.length > 0) return isAbsolute(fromEnv) ? fromEnv : external_node_path_resolve(process.cwd(), fromEnv);
9240
9240
  return DEFAULT_CONFIG_PATH;
9241
9241
  }
9242
9242
  function serveTokenPath() {
@@ -9286,6 +9286,24 @@ function parsePathList(input) {
9286
9286
  function escapeRegExp(input) {
9287
9287
  return input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
9288
9288
  }
9289
+ function roundProgressPercent(done, total) {
9290
+ if (total <= 0) return 0;
9291
+ return roundHalfEven(done / total * 100);
9292
+ }
9293
+ function roundHalfEven(value) {
9294
+ const floor = Math.floor(value);
9295
+ const diff = value - floor;
9296
+ if (diff > 0.5) return floor + 1;
9297
+ if (diff < 0.5) return floor;
9298
+ return floor % 2 === 0 ? floor : floor + 1;
9299
+ }
9300
+ function isAbsolutePath(value) {
9301
+ const input = value.trim();
9302
+ if (0 === input.length) return false;
9303
+ if (/^[a-zA-Z]:[\\/]/.test(input)) return true;
9304
+ if (/^[\\/]{2}[^\\/]/.test(input)) return true;
9305
+ return input.startsWith('/');
9306
+ }
9289
9307
  const ROLES = [
9290
9308
  'frontend',
9291
9309
  'backend',
@@ -9306,7 +9324,11 @@ const PROFILE_KEYS = new Set([
9306
9324
  ]);
9307
9325
  const DOCS_KEYS = new Set([
9308
9326
  'root',
9309
- 'git'
9327
+ 'git',
9328
+ 'validator'
9329
+ ]);
9330
+ const VALIDATOR_KEYS = new Set([
9331
+ 'requireScript'
9310
9332
  ]);
9311
9333
  const GIT_KEYS = new Set([
9312
9334
  'cli',
@@ -9320,6 +9342,9 @@ const DEFAULT_GIT_POLICY = {
9320
9342
  commit: true,
9321
9343
  push: false
9322
9344
  };
9345
+ const DEFAULT_VALIDATOR_POLICY = {
9346
+ requireScript: true
9347
+ };
9323
9348
  const TERMINAL_KEYS = new Set([
9324
9349
  'aliases',
9325
9350
  'repos'
@@ -9363,7 +9388,7 @@ function checkAbsolutePath(value, where, issues, required) {
9363
9388
  issues.push(schema_error('FIELD_TYPE', '必须是绝对路径字符串', where));
9364
9389
  return null;
9365
9390
  }
9366
- if (!isAbsolute(value)) {
9391
+ if (!isAbsolutePath(value)) {
9367
9392
  issues.push(schema_error('PATH_NOT_ABSOLUTE', `必须是绝对路径:${value}`, where));
9368
9393
  return null;
9369
9394
  }
@@ -9427,9 +9452,33 @@ function parseDocs(raw, options, issues) {
9427
9452
  }
9428
9453
  const git = parseGitPolicy(raw['git'], issues);
9429
9454
  if (null === git) return null;
9455
+ const validator = parseValidatorPolicy(raw['validator'], issues);
9456
+ if (null === validator) return null;
9430
9457
  return {
9431
9458
  root,
9432
- git
9459
+ git,
9460
+ validator
9461
+ };
9462
+ }
9463
+ function parseValidatorPolicy(raw, issues) {
9464
+ if (null == raw) return {
9465
+ ...DEFAULT_VALIDATOR_POLICY
9466
+ };
9467
+ if (!utils_isRecord(raw)) {
9468
+ issues.push(schema_error('VALIDATOR_POLICY_INVALID', 'docs.validator 必须是对象', 'docs.validator'));
9469
+ return null;
9470
+ }
9471
+ issues.push(...unknownKeys(raw, VALIDATOR_KEYS, 'docs.validator'));
9472
+ const value = raw['requireScript'];
9473
+ if (void 0 === value) return {
9474
+ ...DEFAULT_VALIDATOR_POLICY
9475
+ };
9476
+ if ('boolean' != typeof value) {
9477
+ issues.push(schema_error('VALIDATOR_POLICY_INVALID', 'docs.validator.requireScript 必须是布尔值', 'docs.validator.requireScript'));
9478
+ return null;
9479
+ }
9480
+ return {
9481
+ requireScript: value
9433
9482
  };
9434
9483
  }
9435
9484
  function parseGitPolicy(raw, issues) {
@@ -9505,7 +9554,7 @@ function parseRepos(raw, where, issues) {
9505
9554
  valid = false;
9506
9555
  continue;
9507
9556
  }
9508
- if (!isAbsolute(item)) {
9557
+ if (!isAbsolutePath(item)) {
9509
9558
  issues.push(schema_error('PATH_NOT_ABSOLUTE', `仓库路径必须是绝对路径:${item}`, whereSide));
9510
9559
  valid = false;
9511
9560
  continue;
@@ -9649,6 +9698,7 @@ function checkConfig(raw, options = {}) {
9649
9698
  docs,
9650
9699
  terminals
9651
9700
  };
9701
+ if (0 === Object.keys(terminals).length) issues.push(warning('TERMINALS_EMPTY', "尚未配置任何终端映射:ylcwf resolve、任务「所属端」与仓库归属校验、doc migrate 回填都将不可用。\n 补配置:ylcwf terminal add <终端名> --frontend <仓库路径>\n (后端仓库用 --backend,两端都有就同时传;每端多个仓库可重复该选项)", 'terminals'));
9652
9702
  issues.push(...checkTerminalIdentity(terminals));
9653
9703
  if (true === options.checkFs) {
9654
9704
  checkFsOfDocs(config, issues);
@@ -10015,6 +10065,12 @@ async function runInit(options) {
10015
10065
  }
10016
10066
  assertWritable(doc, configPath);
10017
10067
  saveDocument(doc, configPath);
10068
+ const terminalCount = Object.keys(doc.toJS().terminals ?? {}).length;
10069
+ if (0 === terminalCount) {
10070
+ log.warn('未配置终端映射:ylcwf resolve、任务「所属端」与仓库归属校验、doc migrate 回填都会不可用。');
10071
+ log.info('稍后补配置:ylcwf terminal add <PRD 中的终端名> --frontend <仓库路径>');
10072
+ log.info('(后端仓库用 --backend;每端多个仓库可重复传该选项)');
10073
+ }
10018
10074
  outro(`已写入 ${configPath}\n下一步:ylcwf doctor 校验,ylcwf show 查看;后续追加仓库用 ylcwf terminal repo add`);
10019
10075
  printLine('');
10020
10076
  }
@@ -10137,6 +10193,10 @@ function renderHuman(path, config, issues) {
10137
10193
  [
10138
10194
  '默认角色',
10139
10195
  ROLE_LABEL[config.profile.role]
10196
+ ],
10197
+ [
10198
+ '文档校验',
10199
+ config.docs.validator.requireScript ? '强制由文档仓库脚本裁决(缺脚本或 python 时拒绝写入)' : '宽松:脚本不可用时仅告警'
10140
10200
  ]
10141
10201
  ]).join('\n'));
10142
10202
  const names = Object.keys(config.terminals);
@@ -10385,7 +10445,7 @@ const terminal_SIDE_LABEL = {
10385
10445
  frontend: '前端',
10386
10446
  backend: '后端'
10387
10447
  };
10388
- function collect(value, previous) {
10448
+ function terminal_collect(value, previous) {
10389
10449
  return [
10390
10450
  ...previous,
10391
10451
  value
@@ -10585,7 +10645,7 @@ function registerTerminal(program) {
10585
10645
  terminal.command('list').description('列出全部终端').option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
10586
10646
  runTerminalList(options);
10587
10647
  });
10588
- terminal.command('add <key>').description('新增终端(终端名用 PRD 中的取值,可为中文)').option('-c, --config <path>', '指定配置文件路径').option('--frontend <path>', '前端仓库绝对路径,可重复', collect, []).option('--backend <path>', '后端仓库绝对路径,可重复', collect, []).option('--alias <name>', '别名,可重复', collect, []).action((key, options)=>{
10648
+ terminal.command('add <key>').description('新增终端(终端名用 PRD 中的取值,可为中文)').option('-c, --config <path>', '指定配置文件路径').option('--frontend <path>', '前端仓库绝对路径,可重复', terminal_collect, []).option('--backend <path>', '后端仓库绝对路径,可重复', terminal_collect, []).option('--alias <name>', '别名,可重复', terminal_collect, []).action((key, options)=>{
10589
10649
  runTerminalAdd(key, options);
10590
10650
  });
10591
10651
  terminal.command('set <key>').description('修改终端别名(仓库增删用 terminal repo)').option('-c, --config <path>', '指定配置文件路径').option('--aliases <list>', '别名,逗号分隔(整体替换)').action((key, options)=>{
@@ -10605,6 +10665,78 @@ function registerTerminal(program) {
10605
10665
  runTerminalRepoRemove(key, options);
10606
10666
  });
10607
10667
  }
10668
+ function aggregateRequirement(statuses) {
10669
+ if (0 === statuses.length) return {
10670
+ status: '未开始',
10671
+ progress: 0
10672
+ };
10673
+ if (statuses.every((status)=>'未开始' === status)) return {
10674
+ status: '未开始',
10675
+ progress: 0
10676
+ };
10677
+ if (statuses.every((status)=>'已完成' === status)) return {
10678
+ status: '已完成',
10679
+ progress: 100
10680
+ };
10681
+ const done = statuses.filter((status)=>'已完成' === status).length;
10682
+ return {
10683
+ status: '进行中',
10684
+ progress: roundProgressPercent(done, statuses.length)
10685
+ };
10686
+ }
10687
+ function resolveAggregates(docsRoot, lists) {
10688
+ const fallback = ()=>{
10689
+ const result = new Map();
10690
+ for (const [requirementId, statuses] of lists)result.set(requirementId, aggregateRequirement(statuses));
10691
+ return result;
10692
+ };
10693
+ if (0 === lists.size) return new Map();
10694
+ const remote = aggregateViaPython(docsRoot, lists);
10695
+ if (null !== remote) return remote;
10696
+ process.stderr.write("警告:未调用文档仓库 validate_task_doc.py --aggregate,需求状态与进度由本地实现计算;请确认文档仓库脚本已更新且本机具备 python3\n");
10697
+ return fallback();
10698
+ }
10699
+ function aggregateViaPython(docsRoot, lists) {
10700
+ const script = external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py');
10701
+ if (!external_node_fs_existsSync(script)) return null;
10702
+ const payload = {};
10703
+ for (const [requirementId, statuses] of lists)payload[requirementId] = statuses;
10704
+ const input = JSON.stringify(payload);
10705
+ for (const bin of [
10706
+ 'python3',
10707
+ 'python',
10708
+ 'py'
10709
+ ])try {
10710
+ const stdout = execFileSync(bin, [
10711
+ script,
10712
+ '--aggregate'
10713
+ ], {
10714
+ input,
10715
+ encoding: 'utf8',
10716
+ timeout: 10000,
10717
+ maxBuffer: 4194304,
10718
+ stdio: [
10719
+ 'pipe',
10720
+ 'pipe',
10721
+ 'pipe'
10722
+ ]
10723
+ });
10724
+ const parsed = JSON.parse(stdout);
10725
+ if (true !== parsed.ok || void 0 === parsed.data) return null;
10726
+ const result = new Map();
10727
+ for (const [requirementId, value] of Object.entries(parsed.data)){
10728
+ if ('string' != typeof value.status || 'number' != typeof value.progress) return null;
10729
+ result.set(requirementId, {
10730
+ status: value.status,
10731
+ progress: value.progress
10732
+ });
10733
+ }
10734
+ return result;
10735
+ } catch {
10736
+ continue;
10737
+ }
10738
+ return null;
10739
+ }
10608
10740
  function normalizeIterationKey(value) {
10609
10741
  return value.trim().toLowerCase().replace(/[-_.\s]+/g, '-');
10610
10742
  }
@@ -10710,6 +10842,44 @@ function parseDocSchema(raw, docsRoot) {
10710
10842
  if (version > SUPPORTED_SCHEMA_VERSION) fail(docsRoot, `schemaVersion ${version} 高于当前 ylcwf 支持的 ${SUPPORTED_SCHEMA_VERSION},请升级 ylcwf`);
10711
10843
  const requirementTable = requireRecord(data.requirementTable, 'requirementTable', docsRoot);
10712
10844
  const taskTable = requireRecord(data.taskTable, 'taskTable', docsRoot);
10845
+ const REQUIRED_REQUIREMENT_KEYS = [
10846
+ 'id',
10847
+ 'status',
10848
+ 'progress',
10849
+ 'updatedAt'
10850
+ ];
10851
+ const REQUIRED_TASK_KEYS = [
10852
+ 'id',
10853
+ 'requirement',
10854
+ 'name',
10855
+ 'type',
10856
+ 'scope',
10857
+ 'terminal',
10858
+ 'dependencies',
10859
+ 'selfTest',
10860
+ 'acceptance',
10861
+ 'status',
10862
+ 'updatedAt'
10863
+ ];
10864
+ const readKeys = (table, headers, required, where)=>{
10865
+ const raw = table.keys;
10866
+ if (void 0 === raw) fail(docsRoot, `${where}.keys 必须声明列语义`);
10867
+ const record = requireRecord(raw, `${where}.keys`, docsRoot);
10868
+ const result = {};
10869
+ for (const semantic of required){
10870
+ const value = record[semantic];
10871
+ if ('string' != typeof value || 0 === value.trim().length) fail(docsRoot, `${where}.keys 缺少必需语义:${semantic}`);
10872
+ if (!headers.includes(value)) fail(docsRoot, `${where}.keys.${semantic} 指向的列「${value}」不在 headers 中`);
10873
+ result[semantic] = value;
10874
+ }
10875
+ for (const [semantic, value] of Object.entries(record))if (void 0 === result[semantic]) {
10876
+ if ('string' == typeof value && 0 !== value.trim().length) {
10877
+ if (!headers.includes(value)) fail(docsRoot, `${where}.keys.${semantic} 指向的列「${value}」不在 headers 中`);
10878
+ result[semantic] = value;
10879
+ }
10880
+ }
10881
+ return result;
10882
+ };
10713
10883
  const progressRaw = requirementTable.progressRange;
10714
10884
  let progressRange = [
10715
10885
  0,
@@ -10768,14 +10938,18 @@ function parseDocSchema(raw, docsRoot) {
10768
10938
  const owner = matched[0];
10769
10939
  if (void 0 === owner || 0 === owner[1].detailFields.length) fail(docsRoot, `roles.${owner?.[0] ?? '?'} 负责所属端「${value}」,必须声明 detailFields`);
10770
10940
  }
10941
+ const requirementHeaders = requireStringArray(requirementTable.headers, 'requirementTable.headers', docsRoot);
10942
+ const taskHeaders = requireStringArray(taskTable.headers, 'taskTable.headers', docsRoot);
10771
10943
  return {
10772
10944
  version,
10773
10945
  sections: requireStringArray(data.sections, 'sections', docsRoot),
10774
10946
  iterationFields: requireStringArray(data.iterationFields, 'iterationFields', docsRoot),
10775
- requirementHeaders: requireStringArray(requirementTable.headers, 'requirementTable.headers', docsRoot),
10947
+ requirementHeaders,
10948
+ requirementKeys: readKeys(requirementTable, requirementHeaders, REQUIRED_REQUIREMENT_KEYS, 'requirementTable'),
10776
10949
  requirementIdPattern: requireString(requirementTable.idPattern, 'requirementTable.idPattern', docsRoot),
10777
10950
  progressRange,
10778
- taskHeaders: requireStringArray(taskTable.headers, 'taskTable.headers', docsRoot),
10951
+ taskHeaders,
10952
+ taskKeys: readKeys(taskTable, taskHeaders, REQUIRED_TASK_KEYS, 'taskTable'),
10779
10953
  taskIdPattern: requireString(taskTable.idPattern, 'taskTable.idPattern', docsRoot),
10780
10954
  taskScopeEnum: requireStringArray(taskTable.scopeEnum, 'taskTable.scopeEnum', docsRoot),
10781
10955
  enums: {
@@ -10857,22 +11031,42 @@ function isKnownRepo(index, repoName) {
10857
11031
  }
10858
11032
  function validateTaskSides(options) {
10859
11033
  const issues = [];
11034
+ let checked = 0;
11035
+ let skipped = 0;
10860
11036
  for (const task of options.tasks){
10861
11037
  const expected = '前端' === task.scope ? 'frontend' : '后端' === task.scope ? 'backend' : null;
10862
- if (null === expected) continue;
11038
+ if (null === expected) {
11039
+ skipped += 1;
11040
+ continue;
11041
+ }
10863
11042
  const repoSide = sideOfRepo(options.index, task.terminal);
10864
- if (null !== repoSide) {
10865
- if (repoSide !== expected) issues.push({
11043
+ if (null === repoSide) {
11044
+ skipped += 1;
11045
+ if (options.index.byName.size > 0) issues.push({
10866
11046
  taskId: task.id,
10867
11047
  scope: task.scope,
10868
11048
  terminal: task.terminal,
10869
- repoSide,
11049
+ repoSide: null,
10870
11050
  level: 'warning',
10871
- message: `任务 ${task.id} 的所属端是「${task.scope}」,但终端「${task.terminal}」在本机配置里是${describeSide(repoSide)}仓库,请核对`
11051
+ message: isKnownRepo(options.index, task.terminal) ? `任务 ${task.id} 的终端「${task.terminal}」在本机配置中同时对应前后端仓库,无法校验归属` : `任务 ${task.id} 的终端「${task.terminal}」不在本机终端配置中,无法校验所属端与仓库是否一致`
10872
11052
  });
11053
+ continue;
10873
11054
  }
11055
+ checked += 1;
11056
+ if (repoSide !== expected) issues.push({
11057
+ taskId: task.id,
11058
+ scope: task.scope,
11059
+ terminal: task.terminal,
11060
+ repoSide,
11061
+ level: 'warning',
11062
+ message: `任务 ${task.id} 的所属端是「${task.scope}」,但终端「${task.terminal}」在本机配置里是${describeSide(repoSide)}仓库,请核对`
11063
+ });
10874
11064
  }
10875
- return issues;
11065
+ return {
11066
+ issues,
11067
+ checked,
11068
+ skipped
11069
+ };
10876
11070
  }
10877
11071
  function describeSide(side) {
10878
11072
  return 'backend' === side ? '后端' : '前端';
@@ -11033,8 +11227,9 @@ function validatePlanReferences(options) {
11033
11227
  const knownRepos = new Set();
11034
11228
  for (const [name] of options.index.byName)knownRepos.add(name);
11035
11229
  const requirementCodes = new Set(options.plan.requirements.map((item)=>item.code));
11230
+ const knownRequirements = new Set(options.knownRequirements ?? []);
11036
11231
  for (const task of options.plan.tasks){
11037
- if (!requirementCodes.has(task.requirement)) docplan_fail(`任务「${task.name}」关联的需求 ${task.requirement} 不在 requirements 中`);
11232
+ if (!requirementCodes.has(task.requirement) && !knownRequirements.has(task.requirement)) docplan_fail(`任务「${task.name}」关联的需求 ${task.requirement} 既不在 requirements 中,也不在文档现有需求里`);
11038
11233
  if (knownRepos.size > 0 && !isKnownRepo(options.index, task.terminal)) process.stderr.write(`提示:任务「${task.name}」的终端「${task.terminal}」不在本机终端配置中,跳过归属校验\n`);
11039
11234
  for (const dependency of task.dependsOn ?? []){
11040
11235
  const normalized = dependency.startsWith('#') ? dependency : `#${dependency}`;
@@ -11075,16 +11270,78 @@ function nextSequence(existingTasks) {
11075
11270
  }
11076
11271
  return counters;
11077
11272
  }
11078
- function aggregateRequirementStatus(statuses) {
11079
- if (0 === statuses.length) return '未开始';
11080
- if (statuses.every((status)=>'已完成' === status)) return '已完成';
11081
- if (statuses.every((status)=>status === PENDING_STATUS)) return '未开始';
11082
- return '进行中';
11273
+ function resolveExistingRequirement(requirements, code) {
11274
+ const found = requirements.find((item)=>item.id === code);
11275
+ if (void 0 === found) return;
11276
+ return {
11277
+ code: found.id,
11278
+ name: found.title,
11279
+ terminal: found.terminal,
11280
+ note: found.note
11281
+ };
11083
11282
  }
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);
11283
+ function splitRow(line) {
11284
+ return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell)=>cell.trim());
11285
+ }
11286
+ function refreshRequirementRows(options) {
11287
+ const { schema, statusesByCode, codes, stamp, aggregate } = options;
11288
+ const lines = [
11289
+ ...options.lines
11290
+ ];
11291
+ const changes = [];
11292
+ const header = schema.requirementHeaders;
11293
+ const idKey = schema.requirementKeys.id;
11294
+ const statusKey = schema.requirementKeys.status;
11295
+ const progressKey = schema.requirementKeys.progress;
11296
+ const updatedAtKey = schema.requirementKeys.updatedAt;
11297
+ if (void 0 === idKey || void 0 === statusKey || void 0 === progressKey) return {
11298
+ lines,
11299
+ changes
11300
+ };
11301
+ const idIndex = header.indexOf(idKey);
11302
+ const statusIndex = header.indexOf(statusKey);
11303
+ const progressIndex = header.indexOf(progressKey);
11304
+ const updatedAtIndex = void 0 === updatedAtKey ? -1 : header.indexOf(updatedAtKey);
11305
+ if (idIndex < 0 || statusIndex < 0 || progressIndex < 0) return {
11306
+ lines,
11307
+ changes
11308
+ };
11309
+ const headerLine = `| ${header.join(' | ')} |`;
11310
+ let inTable = false;
11311
+ for(let index = 0; index < lines.length; index++){
11312
+ const line = lines[index] ?? '';
11313
+ const trimmed = line.trim();
11314
+ if (trimmed === headerLine) {
11315
+ inTable = true;
11316
+ continue;
11317
+ }
11318
+ if (!inTable) continue;
11319
+ if (!trimmed.startsWith('|')) {
11320
+ inTable = false;
11321
+ continue;
11322
+ }
11323
+ if (/^\|[\s:|-]+\|$/.test(trimmed)) continue;
11324
+ const cells = splitRow(trimmed);
11325
+ const code = cells[idIndex] ?? '';
11326
+ if (!codes.has(code)) continue;
11327
+ const statuses = statusesByCode.get(code) ?? [];
11328
+ const result = aggregate(statuses);
11329
+ const nextStatus = result.status;
11330
+ const nextProgress = String(result.progress);
11331
+ if (cells[statusIndex] === nextStatus && cells[progressIndex] === nextProgress) continue;
11332
+ const updated = [
11333
+ ...cells
11334
+ ];
11335
+ updated[statusIndex] = nextStatus;
11336
+ updated[progressIndex] = nextProgress;
11337
+ if (updatedAtIndex >= 0) updated[updatedAtIndex] = stamp;
11338
+ lines[index] = joinRow(updated);
11339
+ changes.push(`更新需求:${code} 开发状态 ${cells[statusIndex] ?? ''} → ${nextStatus},进度 ${cells[progressIndex] ?? ''}% → ${nextProgress}%`);
11340
+ }
11341
+ return {
11342
+ lines,
11343
+ changes
11344
+ };
11088
11345
  }
11089
11346
  function renderDetail(options) {
11090
11347
  const { taskId, task, requirement } = options;
@@ -11262,6 +11519,7 @@ function buildSkeleton(options) {
11262
11519
  }
11263
11520
  function renderPlan(options) {
11264
11521
  const { schema, role, plan, existing, stamp, developer } = options;
11522
+ const aggregate = options.aggregate ?? aggregateRequirement;
11265
11523
  const changes = [];
11266
11524
  const assigned = [];
11267
11525
  const existingRequirementIds = new Set(existing.requirements.map((item)=>item.id));
@@ -11278,7 +11536,7 @@ function renderPlan(options) {
11278
11536
  const next = (counters.get(task.requirement) ?? 0) + 1;
11279
11537
  counters.set(task.requirement, next);
11280
11538
  const id = `${task.requirement}-T${next}`;
11281
- const requirement = plan.requirements.find((item)=>item.code === task.requirement);
11539
+ const requirement = plan.requirements.find((item)=>item.code === task.requirement) ?? resolveExistingRequirement(existing.requirements, task.requirement);
11282
11540
  if (void 0 !== requirement) {
11283
11541
  taskIdsByPlanName.set(task.name, id);
11284
11542
  newTasks.push({
@@ -11316,8 +11574,8 @@ function renderPlan(options) {
11316
11574
  requirement.code,
11317
11575
  requirement.name,
11318
11576
  requirement.terminal,
11319
- aggregateRequirementStatus(statuses),
11320
- String(progressOf(statuses)),
11577
+ aggregate(statuses).status,
11578
+ String(aggregate(statuses).progress),
11321
11579
  requirement.note ?? '',
11322
11580
  stamp
11323
11581
  ];
@@ -11352,6 +11610,22 @@ function renderPlan(options) {
11352
11610
  }) : [
11353
11611
  ...existing.lines
11354
11612
  ];
11613
+ const refreshedCodes = new Set([
11614
+ ...plan.requirements.filter((requirement)=>existingRequirementIds.has(requirement.code)).map((requirement)=>requirement.code),
11615
+ ...newTasks.map((entry)=>entry.task.requirement).filter((code)=>existingRequirementIds.has(code))
11616
+ ]);
11617
+ if (refreshedCodes.size > 0) {
11618
+ const refreshed = refreshRequirementRows({
11619
+ lines,
11620
+ schema,
11621
+ statusesByCode: requirementStatuses,
11622
+ codes: refreshedCodes,
11623
+ stamp,
11624
+ aggregate
11625
+ });
11626
+ lines = refreshed.lines;
11627
+ changes.push(...refreshed.changes);
11628
+ }
11355
11629
  lines = appendTableRows({
11356
11630
  lines,
11357
11631
  sectionHeading: head.requirement,
@@ -11391,6 +11665,7 @@ const RESERVED_FILES = new Set([
11391
11665
  const RESERVED_PREFIXES = [
11392
11666
  'skills/',
11393
11667
  "scripts/",
11668
+ 'docs/',
11394
11669
  '_prd/'
11395
11670
  ];
11396
11671
  const SAFE_SEGMENT = /^[A-Za-z0-9._\-\u4e00-\u9fa5]+$/;
@@ -11649,6 +11924,27 @@ function materializeRemote(docsRoot, ref) {
11649
11924
  });
11650
11925
  return dir;
11651
11926
  }
11927
+ function materializeScripts(docsRoot, ref, dir) {
11928
+ const listed = tryGit(docsRoot, [
11929
+ 'ls-tree',
11930
+ '-r',
11931
+ '--name-only',
11932
+ ref.sha,
11933
+ "scripts/"
11934
+ ]);
11935
+ if (null === listed) return;
11936
+ for (const path of listed.split('\n').map((line)=>line.trim())){
11937
+ if (0 === path.length) continue;
11938
+ const target = external_node_path_join(dir, path);
11939
+ const content = gitShow(docsRoot, ref.sha, path);
11940
+ if (null !== content) {
11941
+ mkdirSync(external_node_path_dirname(target), {
11942
+ recursive: true
11943
+ });
11944
+ writeFileSync(target, content, 'utf8');
11945
+ }
11946
+ }
11947
+ }
11652
11948
  function exportRemoteDoc(docsRoot, ref, iteration, developer) {
11653
11949
  const safeIteration = safeSegment(iteration, '迭代目录');
11654
11950
  const safeDeveloper = safeSegment(developer, '开发者标识');
@@ -11661,16 +11957,13 @@ function exportRemoteDoc(docsRoot, ref, iteration, developer) {
11661
11957
  recursive: true
11662
11958
  });
11663
11959
  writeFileSync(target, markdown, 'utf8');
11664
- const scriptPath = external_node_path_join(dir, "scripts", 'validate_task_doc.py');
11665
- if (!external_node_fs_existsSync(scriptPath)) {
11666
- const script = gitShow(docsRoot, ref.sha, "scripts/validate_task_doc.py");
11667
- if (null !== script) writeFileSync(scriptPath, script, 'utf8');
11668
- }
11960
+ materializeScripts(docsRoot, ref, dir);
11669
11961
  const schemaPath = external_node_path_join(dir, 'schema.json');
11670
11962
  if (!external_node_fs_existsSync(schemaPath)) {
11671
11963
  const schemaText = gitShow(docsRoot, ref.sha, 'schema.json');
11672
11964
  if (null !== schemaText) writeFileSync(schemaPath, schemaText, 'utf8');
11673
11965
  }
11966
+ const scriptPath = external_node_path_join(dir, "scripts", 'validate_task_doc.py');
11674
11967
  return {
11675
11968
  dir,
11676
11969
  markdown,
@@ -11693,52 +11986,52 @@ function isGitAvailable() {
11693
11986
  }
11694
11987
  function normalizeSelfTest(value) {
11695
11988
  const text = value.trim();
11696
- if (0 === text.length) return '未执行';
11697
- if (text.startsWith('免测')) return '免测';
11989
+ if (0 === text.length) return "未执行";
11990
+ if (text.startsWith("免测")) return "免测";
11698
11991
  return text;
11699
11992
  }
11700
11993
  function normalizeAcceptance(value) {
11701
11994
  const text = value.trim();
11702
- return 0 === text.length ? '待验收' : text;
11995
+ return 0 === text.length ? "待验收" : text;
11703
11996
  }
11704
11997
  function bump(target, key) {
11705
11998
  target[key] = (target[key] ?? 0) + 1;
11706
11999
  }
11707
12000
  const RESERVED_DIRS = new Set([
11708
- '_prd',
12001
+ "_prd",
11709
12002
  "scripts",
11710
- 'skills',
11711
- 'docs',
11712
- 'node_modules',
11713
- '.git',
11714
- '.idea',
11715
- '.vscode'
12003
+ "skills",
12004
+ "docs",
12005
+ "node_modules",
12006
+ ".git",
12007
+ ".idea",
12008
+ ".vscode"
11716
12009
  ]);
11717
12010
  const iterations_RESERVED_FILES = new Set([
11718
- 'README.md',
11719
- 'AGENTS.md',
11720
- 'CLAUDE.md'
12011
+ "README.md",
12012
+ "AGENTS.md",
12013
+ "CLAUDE.md"
11721
12014
  ]);
11722
12015
  const iterations_SAFE_SEGMENT = /^[A-Za-z0-9._\-\u4e00-\u9fa5]+$/;
11723
12016
  function iterations_safeSegment(value, label) {
11724
12017
  const trimmed = value.trim();
11725
- if (!iterations_SAFE_SEGMENT.test(trimmed) || '.' === trimmed || '..' === trimmed) throw new errors_CliError(`${label} 不合法:${value}`, errors_EXIT.USAGE);
12018
+ if (!iterations_SAFE_SEGMENT.test(trimmed) || "." === trimmed || ".." === trimmed) throw new errors_CliError(`${label} 不合法:${value}`, errors_EXIT.USAGE);
11726
12019
  return trimmed;
11727
12020
  }
11728
12021
  function joinWithin(root, ...segments) {
11729
- const target = resolve(root, ...segments);
11730
- const base = resolve(root) + sep;
12022
+ const target = external_node_path_resolve(root, ...segments);
12023
+ const base = external_node_path_resolve(root) + sep;
11731
12024
  if (!target.startsWith(base)) throw new errors_CliError(`路径越界:${target}`, errors_EXIT.USAGE);
11732
12025
  return target;
11733
12026
  }
11734
12027
  function inferRole(markdown) {
11735
12028
  const match = /\|\s*负责范围\s*\|\s*([^|]*)\|/.exec(markdown);
11736
- const scope = match?.[1]?.trim() ?? '';
11737
- const hasFrontend = scope.includes('前端');
11738
- const hasBackend = scope.includes('后端');
11739
- if (hasFrontend && hasBackend) return 'fullstack';
11740
- if (hasBackend) return 'backend';
11741
- return 'frontend';
12029
+ const scope = match?.[1]?.trim() ?? "";
12030
+ const hasFrontend = scope.includes("前端");
12031
+ const hasBackend = scope.includes("后端");
12032
+ if (hasFrontend && hasBackend) return "fullstack";
12033
+ if (hasBackend) return "backend";
12034
+ return "frontend";
11742
12035
  }
11743
12036
  function listMarkdownFiles(directory) {
11744
12037
  let entries;
@@ -11747,11 +12040,11 @@ function listMarkdownFiles(directory) {
11747
12040
  } catch {
11748
12041
  return [];
11749
12042
  }
11750
- return entries.filter((name)=>name.endsWith('.md') && !iterations_RESERVED_FILES.has(name)).map((name)=>{
12043
+ return entries.filter((name)=>name.endsWith(".md") && !iterations_RESERVED_FILES.has(name)).map((name)=>{
11751
12044
  const full = external_node_path_join(directory, name);
11752
12045
  const info = statSync(full);
11753
12046
  return {
11754
- id: name.replace(/\.md$/, ''),
12047
+ id: name.replace(/\.md$/, ""),
11755
12048
  file: name,
11756
12049
  mtime: info.mtime.toISOString(),
11757
12050
  size: info.size
@@ -11760,12 +12053,12 @@ function listMarkdownFiles(directory) {
11760
12053
  }
11761
12054
  function accessReason(error) {
11762
12055
  const code = error.code;
11763
- if ('EACCES' === code || 'EPERM' === code) return '没有访问权限,请联系管理员开通文档仓库访问权限';
11764
- if ('ENOENT' === code) return '文档仓库路径不存在';
12056
+ if ("EACCES" === code || "EPERM" === code) return "没有访问权限,请联系管理员开通文档仓库访问权限";
12057
+ if ("ENOENT" === code) return "文档仓库路径不存在";
11765
12058
  if (error instanceof Error) return error.message;
11766
12059
  return String(error);
11767
12060
  }
11768
- function listIterations(docsRoot, source = 'local', refName) {
12061
+ function listIterations(docsRoot, source = "local", refName) {
11769
12062
  const base = {
11770
12063
  docsRoot,
11771
12064
  configured: docsRoot.trim().length > 0,
@@ -11777,7 +12070,7 @@ function listIterations(docsRoot, source = 'local', refName) {
11777
12070
  };
11778
12071
  if (!base.configured) return {
11779
12072
  ...base,
11780
- reason: '尚未配置文档仓库'
12073
+ reason: "尚未配置文档仓库"
11781
12074
  };
11782
12075
  if (!external_node_fs_existsSync(docsRoot)) return {
11783
12076
  ...base,
@@ -11801,7 +12094,7 @@ function listIterations(docsRoot, source = 'local', refName) {
11801
12094
  }
11802
12095
  }
11803
12096
  function buildIterationList(docsRoot, source, base, refName) {
11804
- if ('remote' === source) {
12097
+ if ("remote" === source) {
11805
12098
  const ref = resolveRemoteRef(docsRoot, refName);
11806
12099
  const snapshot = listRemoteIterations(docsRoot, ref);
11807
12100
  return {
@@ -11817,7 +12110,7 @@ function buildIterationList(docsRoot, source, base, refName) {
11817
12110
  }
11818
12111
  const entries = external_node_fs_readdirSync(docsRoot, {
11819
12112
  withFileTypes: true
11820
- }).filter((entry)=>entry.isDirectory() && !RESERVED_DIRS.has(entry.name) && !entry.name.startsWith('.')).map((entry)=>{
12113
+ }).filter((entry)=>entry.isDirectory() && !RESERVED_DIRS.has(entry.name) && !entry.name.startsWith(".")).map((entry)=>{
11821
12114
  const directory = external_node_path_join(docsRoot, entry.name);
11822
12115
  const developers = listMarkdownFiles(directory);
11823
12116
  const info = statSync(directory);
@@ -11825,7 +12118,7 @@ function buildIterationList(docsRoot, source, base, refName) {
11825
12118
  name: entry.name,
11826
12119
  mtime: info.mtime.toISOString(),
11827
12120
  developers,
11828
- hasPrd: external_node_fs_existsSync(external_node_path_join(directory, '_prd', 'meta.json'))
12121
+ hasPrd: external_node_fs_existsSync(external_node_path_join(directory, "_prd", "meta.json"))
11829
12122
  };
11830
12123
  }).filter((entry)=>entry.developers.length > 0).sort((left, right)=>right.mtime.localeCompare(left.mtime));
11831
12124
  return {
@@ -11837,10 +12130,10 @@ function buildIterationList(docsRoot, source, base, refName) {
11837
12130
  }
11838
12131
  function coerceIssue(value) {
11839
12132
  if (!utils_isRecord(value)) return null;
11840
- const level = 'warning' === value['level'] ? 'warning' : 'error';
11841
- const code = 'string' == typeof value['code'] ? value['code'] : 'UNKNOWN';
11842
- const message = 'string' == typeof value['message'] ? value['message'] : '';
11843
- const ref = 'string' == typeof value['ref'] ? value['ref'] : void 0;
12133
+ const level = "warning" === value["level"] ? "warning" : "error";
12134
+ const code = "string" == typeof value["code"] ? value["code"] : "UNKNOWN";
12135
+ const message = "string" == typeof value["message"] ? value["message"] : "";
12136
+ const ref = "string" == typeof value["ref"] ? value["ref"] : void 0;
11844
12137
  return void 0 === ref ? {
11845
12138
  level,
11846
12139
  code,
@@ -11854,59 +12147,59 @@ function coerceIssue(value) {
11854
12147
  }
11855
12148
  function coerceRequirement(value) {
11856
12149
  if (!utils_isRecord(value)) return null;
11857
- const id = 'string' == typeof value['id'] ? value['id'] : '';
12150
+ const id = "string" == typeof value["id"] ? value["id"] : "";
11858
12151
  if (0 === id.length) return null;
11859
12152
  return {
11860
12153
  id,
11861
- title: 'string' == typeof value['title'] ? value['title'] : '',
11862
- terminal: 'string' == typeof value['terminal'] ? value['terminal'] : '',
11863
- status: 'string' == typeof value['status'] ? value['status'] : '',
11864
- progress: String(value['progress'] ?? ''),
11865
- note: 'string' == typeof value['note'] ? value['note'] : '',
11866
- updatedAt: 'string' == typeof value['updatedAt'] ? value['updatedAt'] : '',
11867
- taskIds: isStringArray(value['taskIds']) ? value['taskIds'] : []
12154
+ title: "string" == typeof value["title"] ? value["title"] : "",
12155
+ terminal: "string" == typeof value["terminal"] ? value["terminal"] : "",
12156
+ status: "string" == typeof value["status"] ? value["status"] : "",
12157
+ progress: String(value["progress"] ?? ""),
12158
+ note: "string" == typeof value["note"] ? value["note"] : "",
12159
+ updatedAt: "string" == typeof value["updatedAt"] ? value["updatedAt"] : "",
12160
+ taskIds: isStringArray(value["taskIds"]) ? value["taskIds"] : []
11868
12161
  };
11869
12162
  }
11870
12163
  function coerceTask(value) {
11871
12164
  if (!utils_isRecord(value)) return null;
11872
- const id = 'string' == typeof value['id'] ? value['id'] : '';
12165
+ const id = "string" == typeof value["id"] ? value["id"] : "";
11873
12166
  if (0 === id.length) return null;
11874
12167
  return {
11875
12168
  id,
11876
- requirementId: 'string' == typeof value['requirementId'] ? value['requirementId'] : '',
11877
- name: 'string' == typeof value['name'] ? value['name'] : '',
11878
- type: 'string' == typeof value['type'] ? value['type'] : '',
11879
- scope: 'string' == typeof value['scope'] ? value['scope'] : '',
11880
- terminal: 'string' == typeof value['terminal'] ? value['terminal'] : '',
11881
- dependencies: isStringArray(value['dependencies']) ? value['dependencies'] : [],
11882
- selfTest: 'string' == typeof value['selfTest'] ? value['selfTest'] : '',
11883
- acceptance: 'string' == typeof value['acceptance'] ? value['acceptance'] : '',
11884
- status: 'string' == typeof value['status'] ? value['status'] : '',
11885
- updatedAt: 'string' == typeof value['updatedAt'] ? value['updatedAt'] : ''
12169
+ requirementId: "string" == typeof value["requirementId"] ? value["requirementId"] : "",
12170
+ name: "string" == typeof value["name"] ? value["name"] : "",
12171
+ type: "string" == typeof value["type"] ? value["type"] : "",
12172
+ scope: "string" == typeof value["scope"] ? value["scope"] : "",
12173
+ terminal: "string" == typeof value["terminal"] ? value["terminal"] : "",
12174
+ dependencies: isStringArray(value["dependencies"]) ? value["dependencies"] : [],
12175
+ selfTest: "string" == typeof value["selfTest"] ? value["selfTest"] : "",
12176
+ acceptance: "string" == typeof value["acceptance"] ? value["acceptance"] : "",
12177
+ status: "string" == typeof value["status"] ? value["status"] : "",
12178
+ updatedAt: "string" == typeof value["updatedAt"] ? value["updatedAt"] : ""
11886
12179
  };
11887
12180
  }
11888
12181
  function coerceInfo(value) {
11889
12182
  if (!utils_isRecord(value)) return {};
11890
12183
  const info = {};
11891
- for (const [key, item] of Object.entries(value))if ('string' == typeof item) info[key] = item;
12184
+ for (const [key, item] of Object.entries(value))if ("string" == typeof item) info[key] = item;
11892
12185
  return info;
11893
12186
  }
11894
12187
  function coercePayload(raw) {
11895
12188
  if (!utils_isRecord(raw)) return null;
11896
- const stats = utils_isRecord(raw['stats']) ? raw['stats'] : {};
11897
- const requirements = Array.isArray(raw['requirements']) ? raw['requirements'].map(coerceRequirement).filter((item)=>null !== item) : [];
11898
- const tasks = Array.isArray(raw['tasks']) ? raw['tasks'].map(coerceTask).filter((item)=>null !== item) : [];
11899
- const errors = Array.isArray(raw['errors']) ? raw['errors'].map(coerceIssue).filter((item)=>null !== item) : [];
11900
- const warnings = Array.isArray(raw['warnings']) ? raw['warnings'].map(coerceIssue).filter((item)=>null !== item) : [];
11901
- const asNumber = (value, fallback)=>'number' == typeof value ? value : fallback;
12189
+ const stats = utils_isRecord(raw["stats"]) ? raw["stats"] : {};
12190
+ const requirements = Array.isArray(raw["requirements"]) ? raw["requirements"].map(coerceRequirement).filter((item)=>null !== item) : [];
12191
+ const tasks = Array.isArray(raw["tasks"]) ? raw["tasks"].map(coerceTask).filter((item)=>null !== item) : [];
12192
+ const errors = Array.isArray(raw["errors"]) ? raw["errors"].map(coerceIssue).filter((item)=>null !== item) : [];
12193
+ const warnings = Array.isArray(raw["warnings"]) ? raw["warnings"].map(coerceIssue).filter((item)=>null !== item) : [];
12194
+ const asNumber = (value, fallback)=>"number" == typeof value ? value : fallback;
11902
12195
  return {
11903
- valid: true === raw['valid'],
11904
- iterationInfo: coerceInfo(raw['iterationInfo']),
12196
+ valid: true === raw["valid"],
12197
+ iterationInfo: coerceInfo(raw["iterationInfo"]),
11905
12198
  stats: {
11906
- requirements: asNumber(stats['requirements'], requirements.length),
11907
- tasks: asNumber(stats['tasks'], tasks.length),
11908
- completedTasks: asNumber(stats['completedTasks'], tasks.filter((task)=>'已完成' === task.status).length),
11909
- details: asNumber(stats['details'], 0)
12199
+ requirements: asNumber(stats["requirements"], requirements.length),
12200
+ tasks: asNumber(stats["tasks"], tasks.length),
12201
+ completedTasks: asNumber(stats["completedTasks"], tasks.filter((task)=>"已完成" === task.status).length),
12202
+ details: asNumber(stats["details"], 0)
11910
12203
  },
11911
12204
  requirements,
11912
12205
  tasks,
@@ -11914,74 +12207,119 @@ function coercePayload(raw) {
11914
12207
  warnings
11915
12208
  };
11916
12209
  }
12210
+ const validatorFailureCache = new Map();
12211
+ const warnedValidatorFailures = new Set();
12212
+ function warnValidatorFailureOnce(key, reason) {
12213
+ if (warnedValidatorFailures.has(key)) return;
12214
+ warnedValidatorFailures.add(key);
12215
+ process.stderr.write(`警告:文档校验器未运行(${reason}),已改用降级解析\n`);
12216
+ }
11917
12217
  function runValidator(input) {
11918
12218
  const script = input.scriptPath;
11919
- if (null === script || !external_node_fs_existsSync(script)) return null;
12219
+ if (null === script || !external_node_fs_existsSync(script)) {
12220
+ const missing = "文档仓库缺少 scripts/validate_task_doc.py";
12221
+ warnValidatorFailureOnce(`missing|${input.docsRoot}`, missing);
12222
+ return {
12223
+ payload: null,
12224
+ error: missing
12225
+ };
12226
+ }
12227
+ const cacheKey = `${script}|${input.docsRoot}|${input.iteration}|${input.developer}|${input.role}`;
12228
+ const cachedFailure = validatorFailureCache.get(cacheKey);
12229
+ if (void 0 !== cachedFailure) return {
12230
+ payload: null,
12231
+ error: cachedFailure
12232
+ };
11920
12233
  const args = [
11921
12234
  script,
11922
- '--docs-root',
12235
+ "--docs-root",
11923
12236
  input.docsRoot,
11924
- '--iteration',
12237
+ "--iteration",
11925
12238
  input.iteration,
11926
- '--developer',
12239
+ "--developer",
11927
12240
  input.developer,
11928
- '--role',
12241
+ "--role",
11929
12242
  input.role,
11930
- '--format',
11931
- 'json'
12243
+ "--format",
12244
+ "json"
11932
12245
  ];
12246
+ let lastError = null;
12247
+ let interpreterMissing = true;
11933
12248
  for (const bin of [
11934
- 'python3',
11935
- 'python',
11936
- 'py'
12249
+ "python3",
12250
+ "python",
12251
+ "py"
11937
12252
  ])try {
11938
12253
  const stdout = execFileSync(bin, args, {
11939
- encoding: 'utf8',
12254
+ encoding: "utf8",
11940
12255
  timeout: 10000,
11941
- maxBuffer: 16777216
12256
+ maxBuffer: 16777216,
12257
+ stdio: [
12258
+ "ignore",
12259
+ "pipe",
12260
+ "pipe"
12261
+ ]
11942
12262
  });
11943
12263
  const parsed = coercePayload(JSON.parse(stdout));
11944
- if (null !== parsed) return parsed;
12264
+ if (null !== parsed) return {
12265
+ payload: parsed,
12266
+ error: null
12267
+ };
11945
12268
  } catch (error) {
11946
- const stdout = error.stdout;
11947
- if ('string' == typeof stdout && stdout.trim().length > 0) try {
12269
+ const failure = error;
12270
+ const stdout = failure.stdout;
12271
+ if ("string" == typeof stdout && stdout.trim().length > 0) try {
11948
12272
  const parsed = coercePayload(JSON.parse(stdout));
11949
- if (null !== parsed) return parsed;
12273
+ if (null !== parsed) return {
12274
+ payload: parsed,
12275
+ error: null
12276
+ };
11950
12277
  } catch {}
11951
- }
11952
- return null;
12278
+ if ("ENOENT" === failure.code || 127 === failure.code) continue;
12279
+ interpreterMissing = false;
12280
+ const stderr = "string" == typeof failure.stderr ? failure.stderr.trim().split("\n") : [];
12281
+ lastError = stderr.length > 0 ? (stderr[stderr.length - 1] ?? "").slice(0, 200) : "校验器执行失败";
12282
+ }
12283
+ const reason = interpreterMissing ? "未找到 python 解释器(需 python3 / python / py)" : lastError;
12284
+ const failure = reason ?? "校验器执行失败";
12285
+ validatorFailureCache.set(cacheKey, failure);
12286
+ warnValidatorFailureOnce(failure, failure);
12287
+ return {
12288
+ payload: null,
12289
+ error: failure
12290
+ };
11953
12291
  }
11954
12292
  function extractSection(markdown, heading) {
11955
12293
  const lines = markdown.split(/\r?\n/);
11956
12294
  let start = -1;
11957
- for(let index = 0; index < lines.length; index += 1)if ((lines[index] ?? '').trim() === heading) {
12295
+ for(let index = 0; index < lines.length; index += 1)if ((lines[index] ?? "").trim() === heading) {
11958
12296
  start = index + 1;
11959
12297
  break;
11960
12298
  }
11961
- if (start < 0) return '';
12299
+ if (start < 0) return "";
11962
12300
  const collected = [];
11963
12301
  for(let index = start; index < lines.length; index += 1){
11964
- const line = lines[index] ?? '';
12302
+ const line = lines[index] ?? "";
11965
12303
  if (/^##\s+/.test(line)) break;
11966
12304
  collected.push(line);
11967
12305
  }
11968
- return collected.join('\n').trim();
12306
+ return collected.join("\n").trim();
11969
12307
  }
11970
12308
  function splitDetails(markdown) {
11971
- const section = extractSection(markdown, '## 四、任务详情');
12309
+ const section = extractSection(markdown, "## 四、任务详情");
11972
12310
  if (0 === section.length) return [];
11973
12311
  const blocks = [];
11974
12312
  const parts = section.split(/^###\s+/m).slice(1);
11975
12313
  for (const part of parts){
11976
12314
  const [firstLine, ...rest] = part.split(/\r?\n/);
11977
- const heading = (firstLine ?? '').trim();
12315
+ const heading = (firstLine ?? "").trim();
11978
12316
  const match = /^\[?([#\w\-\u4e00-\u9fa5]+)\]?\s*(.*)$/.exec(heading);
11979
12317
  const id = match?.[1] ?? heading;
11980
- const name = match?.[2]?.trim() ?? '';
12318
+ const name = match?.[2]?.trim() ?? "";
11981
12319
  blocks.push({
11982
12320
  id,
11983
12321
  name,
11984
- markdown: rest.join('\n').trim()
12322
+ markdown: rest.join("\n").trim()
11985
12323
  });
11986
12324
  }
11987
12325
  return blocks;
@@ -11990,7 +12328,7 @@ function parseMarkdownDoc(markdown, schema) {
11990
12328
  const structureErrors = [];
11991
12329
  const readTable = (sectionHeading, required)=>{
11992
12330
  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));
12331
+ 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
12332
  const [header, ...body] = rows;
11995
12333
  if (void 0 === header) return {
11996
12334
  records: [],
@@ -12006,7 +12344,7 @@ function parseMarkdownDoc(markdown, schema) {
12006
12344
  const records = body.map((cells)=>{
12007
12345
  const record = {};
12008
12346
  header.forEach((name, index)=>{
12009
- record[name] = cells[index] ?? '';
12347
+ record[name] = cells[index] ?? "";
12010
12348
  });
12011
12349
  return record;
12012
12350
  });
@@ -12016,42 +12354,43 @@ function parseMarkdownDoc(markdown, schema) {
12016
12354
  };
12017
12355
  };
12018
12356
  const heading = (index, fallback)=>`## ${schema.sections[index] ?? fallback}`;
12019
- const requirementRead = readTable(heading(1, '二、需求清单'), schema.requirementHeaders);
12020
- const taskRead = readTable(heading(2, '三、任务清单'), schema.taskHeaders);
12357
+ const requirementRead = readTable(heading(1, "二、需求清单"), schema.requirementHeaders);
12358
+ const taskRead = readTable(heading(2, "三、任务清单"), schema.taskHeaders);
12021
12359
  if (requirementRead.missing.length > 0) structureErrors.push({
12022
- level: 'error',
12023
- code: 'REQUIREMENT_TABLE_MISMATCH',
12024
- message: `需求清单表头缺少列:${requirementRead.missing.join('、')},请按最新模板补齐`
12360
+ level: "error",
12361
+ code: "REQUIREMENT_TABLE_MISMATCH",
12362
+ message: `需求清单表头缺少列:${requirementRead.missing.join("、")},请按最新模板补齐`
12025
12363
  });
12026
12364
  if (taskRead.missing.length > 0) structureErrors.push({
12027
- level: 'error',
12028
- code: 'TASK_TABLE_MISMATCH',
12029
- message: `任务清单表头缺少列:${taskRead.missing.join('、')},请按最新模板补齐`
12365
+ level: "error",
12366
+ code: "TASK_TABLE_MISMATCH",
12367
+ message: `任务清单表头缺少列:${taskRead.missing.join("、")},请按最新模板补齐`
12030
12368
  });
12031
- const reqH = schema.requirementHeaders;
12369
+ const rk = schema.requirementKeys;
12370
+ const at = (record, keys, semantic)=>record[keys[semantic] ?? ""] ?? "";
12032
12371
  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] ?? ''] ?? '',
12372
+ id: at(record, rk, "id"),
12373
+ title: at(record, rk, "title"),
12374
+ terminal: at(record, rk, "terminal"),
12375
+ status: at(record, rk, "status"),
12376
+ progress: at(record, rk, "progress"),
12377
+ note: at(record, rk, "note"),
12378
+ updatedAt: at(record, rk, "updatedAt"),
12040
12379
  taskIds: []
12041
12380
  }));
12042
- const taskH = schema.taskHeaders;
12381
+ const tk = schema.taskKeys;
12043
12382
  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] ?? ''] ?? ''
12383
+ id: at(record, tk, "id"),
12384
+ requirementId: at(record, tk, "requirement"),
12385
+ name: at(record, tk, "name"),
12386
+ type: at(record, tk, "type"),
12387
+ scope: at(record, tk, "scope"),
12388
+ terminal: at(record, tk, "terminal"),
12389
+ dependencies: at(record, tk, "dependencies").split(/[,,]/).map((item)=>item.trim()).filter((item)=>item.length > 0),
12390
+ selfTest: at(record, tk, "selfTest"),
12391
+ acceptance: at(record, tk, "acceptance"),
12392
+ status: at(record, tk, "status"),
12393
+ updatedAt: at(record, tk, "updatedAt")
12055
12394
  }));
12056
12395
  for (const requirement of requirements)requirement.taskIds = tasks.filter((task)=>task.requirementId === requirement.id).map((task)=>task.id);
12057
12396
  const details = splitDetails(markdown);
@@ -12067,7 +12406,7 @@ function parseMarkdownDoc(markdown, schema) {
12067
12406
  stats: {
12068
12407
  requirements: requirements.length,
12069
12408
  tasks: tasks.length,
12070
- completedTasks: tasks.filter((task)=>'已完成' === task.status).length,
12409
+ completedTasks: tasks.filter((task)=>"已完成" === task.status).length,
12071
12410
  details: details.length
12072
12411
  },
12073
12412
  requirements,
@@ -12077,12 +12416,12 @@ function parseMarkdownDoc(markdown, schema) {
12077
12416
  };
12078
12417
  }
12079
12418
  function readMarkdown(target) {
12080
- return readFileSync(target, 'utf8');
12419
+ return readFileSync(target, "utf8");
12081
12420
  }
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) {
12421
+ function readIterationDoc(docsRoot, iteration, developer, source = "local", presetRef, refName) {
12422
+ const safeIteration = iterations_safeSegment(iteration, "迭代目录");
12423
+ const safeDeveloper = iterations_safeSegment(developer, "开发者标识");
12424
+ if ("remote" === source) {
12086
12425
  const ref = presetRef ?? resolveRemoteRef(docsRoot, refName);
12087
12426
  const exported = exportRemoteDoc(docsRoot, ref, safeIteration, safeDeveloper);
12088
12427
  const roleInferred = inferRole(exported.markdown);
@@ -12099,13 +12438,14 @@ function readIterationDoc(docsRoot, iteration, developer, source = 'local', pres
12099
12438
  file: `${safeIteration}/${safeDeveloper}.md`,
12100
12439
  mtime: exported.mtime,
12101
12440
  roleInferred,
12102
- parser: null === scripted ? 'fallback' : "script",
12103
- source: 'remote',
12441
+ parser: null === scripted.payload ? "fallback" : "script",
12442
+ parserError: scripted.error,
12443
+ source: "remote",
12104
12444
  ref: {
12105
12445
  name: ref.ref,
12106
12446
  sha: ref.sha
12107
12447
  },
12108
- validation: scripted ?? parseMarkdownDoc(exported.markdown, loadDocSchema(exported.dir)),
12448
+ validation: scripted.payload ?? parseMarkdownDoc(exported.markdown, loadDocSchema(exported.dir)),
12109
12449
  details: splitDetails(exported.markdown)
12110
12450
  };
12111
12451
  }
@@ -12117,13 +12457,13 @@ function readIterationDoc(docsRoot, iteration, developer, source = 'local', pres
12117
12457
  const roleInferred = inferRole(markdown);
12118
12458
  const scripted = runValidator({
12119
12459
  docsRoot,
12120
- scriptPath: external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py'),
12460
+ scriptPath: external_node_path_join(docsRoot, "scripts", "validate_task_doc.py"),
12121
12461
  iteration: safeIteration,
12122
12462
  developer: safeDeveloper,
12123
12463
  role: roleInferred
12124
12464
  });
12125
- const validation = scripted ?? parseMarkdownDoc(markdown, loadDocSchema(docsRoot));
12126
- const parser = null === scripted ? 'fallback' : "script";
12465
+ const validation = scripted.payload ?? parseMarkdownDoc(markdown, loadDocSchema(docsRoot));
12466
+ const parser = null === scripted.payload ? "fallback" : "script";
12127
12467
  return {
12128
12468
  iteration: safeIteration,
12129
12469
  developer: safeDeveloper,
@@ -12131,15 +12471,16 @@ function readIterationDoc(docsRoot, iteration, developer, source = 'local', pres
12131
12471
  mtime: statSync(file).mtime.toISOString(),
12132
12472
  roleInferred,
12133
12473
  parser,
12134
- source: 'local',
12474
+ parserError: scripted.error,
12475
+ source: "local",
12135
12476
  ref: null,
12136
12477
  validation,
12137
12478
  details: splitDetails(markdown)
12138
12479
  };
12139
12480
  }
12140
- function readIterationSummary(docsRoot, iteration, source = 'local', refName) {
12141
- const safeIteration = iterations_safeSegment(iteration, '迭代目录');
12142
- const remoteRef = 'remote' === source ? resolveRemoteRef(docsRoot, refName) : null;
12481
+ function readIterationSummary(docsRoot, iteration, source = "local", refName) {
12482
+ const safeIteration = iterations_safeSegment(iteration, "迭代目录");
12483
+ const remoteRef = "remote" === source ? resolveRemoteRef(docsRoot, refName) : null;
12143
12484
  let developers;
12144
12485
  if (null === remoteRef) {
12145
12486
  const directory = joinWithin(docsRoot, safeIteration);
@@ -12159,7 +12500,7 @@ function readIterationSummary(docsRoot, iteration, source = 'local', refName) {
12159
12500
  const selfTestCounts = {};
12160
12501
  const acceptanceCounts = {};
12161
12502
  for (const task of doc.validation.tasks){
12162
- bump(statusCounts, 0 === task.status.length ? '未知' : task.status);
12503
+ bump(statusCounts, 0 === task.status.length ? "未知" : task.status);
12163
12504
  bump(selfTestCounts, normalizeSelfTest(task.selfTest));
12164
12505
  bump(acceptanceCounts, normalizeAcceptance(task.acceptance));
12165
12506
  }
@@ -12168,14 +12509,14 @@ function readIterationSummary(docsRoot, iteration, source = 'local', refName) {
12168
12509
  task
12169
12510
  ]));
12170
12511
  for (const task of doc.validation.tasks){
12171
- if ('已完成' === task.status) continue;
12512
+ if ("已完成" === task.status) continue;
12172
12513
  const blocking = task.dependencies.map((dep)=>{
12173
12514
  const target = byId.get(dep);
12174
12515
  return void 0 === target ? null : {
12175
12516
  id: dep,
12176
12517
  status: target.status
12177
12518
  };
12178
- }).filter((item)=>null !== item && '已完成' !== item.status);
12519
+ }).filter((item)=>null !== item && "已完成" !== item.status);
12179
12520
  if (blocking.length > 0) blocked.push({
12180
12521
  developer: entry.id,
12181
12522
  taskId: task.id,
@@ -12185,7 +12526,7 @@ function readIterationSummary(docsRoot, iteration, source = 'local', refName) {
12185
12526
  });
12186
12527
  }
12187
12528
  const requirementStatusCounts = {};
12188
- for (const requirement of doc.validation.requirements)bump(requirementStatusCounts, 0 === requirement.status.length ? '未知' : requirement.status);
12529
+ for (const requirement of doc.validation.requirements)bump(requirementStatusCounts, 0 === requirement.status.length ? "未知" : requirement.status);
12189
12530
  summaries.push({
12190
12531
  id: entry.id,
12191
12532
  roleInferred: doc.roleInferred,
@@ -12231,7 +12572,7 @@ function readIterationSummary(docsRoot, iteration, source = 'local', refName) {
12231
12572
  },
12232
12573
  totals: {
12233
12574
  ...totals,
12234
- progress: 0 === totals.tasks ? 0 : Math.round(totals.completedTasks / totals.tasks * 100),
12575
+ progress: roundProgressPercent(totals.completedTasks, totals.tasks),
12235
12576
  taskStatusCounts: mergeCounts((item)=>item.statusCounts),
12236
12577
  requirementStatusCounts: mergeCounts((item)=>item.requirementStatusCounts),
12237
12578
  selfTestCounts: mergeCounts((item)=>item.selfTestCounts),
@@ -12424,22 +12765,29 @@ function readTaskHistory(options) {
12424
12765
  return entries;
12425
12766
  }
12426
12767
  function buildKeys(schema) {
12427
- const h = schema.taskHeaders;
12428
- const r = schema.requirementHeaders;
12768
+ const t = schema.taskKeys;
12769
+ const r = schema.requirementKeys;
12770
+ const pick = (keys, semantic)=>{
12771
+ const value = keys[semantic];
12772
+ if (void 0 === value) throw new errors_CliError(`schema.json 缺少列语义:${semantic}`, errors_EXIT.INVALID);
12773
+ return value;
12774
+ };
12429
12775
  return {
12430
12776
  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] ?? '最后更新'
12777
+ id: pick(t, 'id'),
12778
+ requirement: pick(t, 'requirement'),
12779
+ scope: pick(t, 'scope'),
12780
+ selfTest: pick(t, 'selfTest'),
12781
+ acceptance: pick(t, 'acceptance'),
12782
+ status: pick(t, 'status'),
12783
+ updatedAt: pick(t, 'updatedAt')
12437
12784
  },
12438
12785
  requirement: {
12439
- id: r[0] ?? '需求编号',
12440
- status: r[3] ?? '开发状态',
12441
- progress: r[4] ?? '开发进度(%)',
12442
- updatedAt: r[6] ?? '最后更新'
12786
+ id: pick(r, 'id'),
12787
+ status: pick(r, 'status'),
12788
+ progress: pick(r, 'progress'),
12789
+ note: r['note'] ?? '',
12790
+ updatedAt: pick(r, 'updatedAt')
12443
12791
  },
12444
12792
  taskSection: `## ${schema.sections[2] ?? '三、任务清单'}`,
12445
12793
  requirementSection: `## ${schema.sections[1] ?? '二、需求清单'}`
@@ -12450,7 +12798,7 @@ function columnIndex(headerCells, name) {
12450
12798
  if (index < 0) throw new errors_CliError(`表格缺少列「${name}」,无法安全写入`, errors_EXIT.INVALID);
12451
12799
  return index;
12452
12800
  }
12453
- function splitRow(line) {
12801
+ function taskdoc_splitRow(line) {
12454
12802
  const trimmed = line.trim();
12455
12803
  const inner = trimmed.startsWith('|') ? trimmed.slice(1) : trimmed;
12456
12804
  const withoutTail = inner.endsWith('|') ? inner.slice(0, -1) : inner;
@@ -12486,7 +12834,7 @@ function parseTaskRows(lines, keys) {
12486
12834
  for(let index = start; index < end; index += 1){
12487
12835
  const line = lines[index] ?? '';
12488
12836
  if (!line.trim().startsWith('|')) continue;
12489
- const cells = splitRow(line);
12837
+ const cells = taskdoc_splitRow(line);
12490
12838
  if (null === header) {
12491
12839
  if (cells.includes(keys.task.id)) header = cells;
12492
12840
  continue;
@@ -12516,7 +12864,7 @@ function parseRequirementRows(lines, keys) {
12516
12864
  for(let index = start; index < end; index += 1){
12517
12865
  const line = lines[index] ?? '';
12518
12866
  if (!line.trim().startsWith('|')) continue;
12519
- const cells = splitRow(line);
12867
+ const cells = taskdoc_splitRow(line);
12520
12868
  if (null === header) {
12521
12869
  if (cells.includes(keys.requirement.id)) header = cells;
12522
12870
  continue;
@@ -12535,12 +12883,6 @@ function parseRequirementRows(lines, keys) {
12535
12883
  rows
12536
12884
  };
12537
12885
  }
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
12886
  function updateDetailBlock(lines, taskId, updates) {
12545
12887
  const headingIndex = lines.findIndex((line)=>line.trim().startsWith(`### [${taskId}]`));
12546
12888
  if (headingIndex < 0) throw new errors_CliError(`任务 ${taskId} 缺少第四章详情区块,无法同步状态`, errors_EXIT.INVALID);
@@ -12584,7 +12926,7 @@ function loadDoc(docsRoot, iterationRaw, developerRaw) {
12584
12926
  lines: original.split('\n')
12585
12927
  };
12586
12928
  }
12587
- function computeUpdate(lines, taskId, action, keys) {
12929
+ function computeUpdate(lines, taskId, action, keys, docsRoot) {
12588
12930
  const { header, rows } = parseTaskRows(lines, keys);
12589
12931
  const target = rows.find((row)=>row.taskId === taskId);
12590
12932
  if (void 0 === target) throw new errors_CliError(`任务清单中未找到 ${taskId}`, errors_EXIT.NOT_FOUND);
@@ -12616,9 +12958,14 @@ function computeUpdate(lines, taskId, action, keys) {
12616
12958
  人工验收: nextAcceptance
12617
12959
  });
12618
12960
  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);
12961
+ const aggregate = resolveAggregates(docsRoot, new Map([
12962
+ [
12963
+ target.requirementId,
12964
+ requirementStatuses
12965
+ ]
12966
+ ])).get(target.requirementId) ?? aggregateRequirement(requirementStatuses);
12967
+ const requirementStatus = aggregate.status;
12968
+ const progress = aggregate.progress;
12622
12969
  const requirementParse = parseRequirementRows(withDetail, keys);
12623
12970
  const requirementTarget = requirementParse.rows.find((row)=>row.id === target.requirementId);
12624
12971
  if (void 0 === requirementTarget) throw new errors_CliError(`需求清单中未找到 ${target.requirementId}`, errors_EXIT.NOT_FOUND);
@@ -12648,10 +12995,15 @@ function commit(context, lines, changes, message, iteration, developer, action,
12648
12995
  file: context.file
12649
12996
  };
12650
12997
  writeFileSync(context.file, output, 'utf8');
12651
- const violation = validateAfterWrite(external_node_path_dirname(context.file), iteration, developer);
12652
- if (null !== violation) {
12998
+ const outcome = validateAfterWrite(options.docsRoot, iteration, developer);
12999
+ if ('violation' === outcome.kind) {
12653
13000
  writeFileSync(context.file, context.original, 'utf8');
12654
- throw new errors_CliError(`写入被校验器拒绝,已回滚:${violation}`, errors_EXIT.INVALID);
13001
+ throw new errors_CliError(`写入被校验器拒绝,已回滚:${outcome.message}`, errors_EXIT.INVALID);
13002
+ }
13003
+ if ('unavailable' === outcome.kind) {
13004
+ writeFileSync(context.file, context.original, 'utf8');
13005
+ if (requireValidatorScript()) throw new errors_CliError(`未执行文档校验,已回滚:${outcome.reason}\n文档校验必须由文档仓库 scripts/validate_task_doc.py 裁决;如确需跳过(不推荐),可配置 docs.validator.requireScript: false`, errors_EXIT.INVALID);
13006
+ process.stderr.write(`警告:${outcome.reason};本次写入未做文档校验(docs.validator.requireScript=false)\n`);
12655
13007
  }
12656
13008
  appendHistory({
12657
13009
  iteration,
@@ -12669,6 +13021,163 @@ function commit(context, lines, changes, message, iteration, developer, action,
12669
13021
  git
12670
13022
  };
12671
13023
  }
13024
+ function normalizeDetailField(name) {
13025
+ return name.replace(/[((][^))]*[))]/g, '').replace(/\s+/g, '').trim();
13026
+ }
13027
+ const DETAIL_FIELDS_LOCKED = new Set([
13028
+ '任务状态',
13029
+ '人工验收',
13030
+ '自测状态'
13031
+ ]);
13032
+ function readDetailField(lines, taskId, field) {
13033
+ const headingIndex = lines.findIndex((line)=>line.trim().startsWith(`### [${taskId}]`));
13034
+ if (headingIndex < 0) return null;
13035
+ let end = lines.length;
13036
+ for(let index = headingIndex + 1; index < lines.length; index += 1)if (/^###\s+/.test(lines[index] ?? '') || /^##\s+/.test(lines[index] ?? '')) {
13037
+ end = index;
13038
+ break;
13039
+ }
13040
+ const wanted = normalizeDetailField(field);
13041
+ for(let index = headingIndex + 1; index < end; index += 1){
13042
+ const match = /^(\s*-\s+\*\*(.+?)\*\*\s*[::])\s*(.*)$/.exec(lines[index] ?? '');
13043
+ if (null === match) continue;
13044
+ if (normalizeDetailField(match[2] ?? '') !== wanted) continue;
13045
+ const items = [];
13046
+ const inline = (match[3] ?? '').trim();
13047
+ if (inline.length > 0) items.push(inline);
13048
+ let cursor = index + 1;
13049
+ while(cursor < end && /^\s{2,}-\s+/.test(lines[cursor] ?? '')){
13050
+ items.push((lines[cursor] ?? '').replace(/^\s{2,}-\s+/, '').trim());
13051
+ cursor += 1;
13052
+ }
13053
+ return {
13054
+ index,
13055
+ prefix: match[1] ?? '',
13056
+ items: items.filter((item)=>item.length > 0 && '<待补充>' !== item),
13057
+ list: cursor > index + 1
13058
+ };
13059
+ }
13060
+ return null;
13061
+ }
13062
+ function applyTaskDetail(options) {
13063
+ if (0 === options.updates.length) throw new errors_CliError('未提供要更新的字段(--set / --append)', errors_EXIT.USAGE);
13064
+ assertWritableBranch(options.docsRoot);
13065
+ const schema = loadDocSchema(options.docsRoot);
13066
+ const keys = buildKeys(schema);
13067
+ const context = loadDoc(options.docsRoot, options.iteration, options.developer);
13068
+ const { header, rows } = parseTaskRows(context.lines, keys);
13069
+ const target = rows.find((row)=>row.taskId === options.taskId);
13070
+ if (void 0 === target) throw new errors_CliError(`任务清单中未找到 ${options.taskId}`, errors_EXIT.NOT_FOUND);
13071
+ const scope = target.cells[columnIndex(header, keys.task.scope)] ?? '';
13072
+ const allowedFields = detailFieldsOfScope(schema, scope);
13073
+ const allowed = new Map(allowedFields.map((field)=>[
13074
+ normalizeDetailField(field),
13075
+ field
13076
+ ]));
13077
+ const stamp = nowStamp();
13078
+ let lines = [
13079
+ ...context.lines
13080
+ ];
13081
+ const changes = [];
13082
+ const touched = [];
13083
+ for (const update of options.updates){
13084
+ const fieldName = allowed.get(normalizeDetailField(update.field));
13085
+ if (void 0 === fieldName) throw new errors_CliError(`字段「${update.field}」不可编辑(可改:${allowedFields.join(' / ')})`, errors_EXIT.USAGE);
13086
+ if (DETAIL_FIELDS_LOCKED.has(fieldName)) throw new errors_CliError(`字段「${fieldName}」由状态流转命令维护,请使用 task start/submit/accept/reject 或 task selftest`, errors_EXIT.USAGE);
13087
+ const parsed = readDetailField(lines, options.taskId, fieldName);
13088
+ if (null === parsed) throw new errors_CliError(`任务 ${options.taskId} 的详情区块缺少字段「${fieldName}」`, errors_EXIT.INVALID);
13089
+ const incoming = update.value.split('\n').map((item)=>item.trim()).filter((item)=>item.length > 0);
13090
+ const nextItems = update.append ? [
13091
+ ...parsed.items,
13092
+ ...incoming
13093
+ ] : incoming;
13094
+ if (0 === nextItems.length) throw new errors_CliError(`字段「${fieldName}」的新值不能为空`, errors_EXIT.USAGE);
13095
+ if (nextItems.join('\n') === parsed.items.join('\n')) continue;
13096
+ const removeCount = 1 + (parsed.list ? parsed.items.length : 0);
13097
+ const replacement = 1 === nextItems.length ? [
13098
+ `${parsed.prefix}${nextItems[0]}`
13099
+ ] : [
13100
+ `${parsed.prefix}`,
13101
+ ...nextItems.map((item)=>` - ${item}`)
13102
+ ];
13103
+ lines = [
13104
+ ...lines.slice(0, parsed.index),
13105
+ ...replacement,
13106
+ ...lines.slice(parsed.index + removeCount)
13107
+ ];
13108
+ touched.push(fieldName);
13109
+ changes.push(`${options.taskId} ${fieldName}:${parsed.items.length} 条 → ${nextItems.length} 条`);
13110
+ }
13111
+ if (0 === changes.length) return {
13112
+ ok: true,
13113
+ message: '详情内容未发生变化',
13114
+ changes: [],
13115
+ file: context.file
13116
+ };
13117
+ const { rows: refreshedRows } = parseTaskRows(lines, keys);
13118
+ const refreshed = refreshedRows.find((row)=>row.taskId === options.taskId);
13119
+ if (void 0 !== refreshed) {
13120
+ const cells = [
13121
+ ...refreshed.cells
13122
+ ];
13123
+ cells[columnIndex(header, keys.task.updatedAt)] = stamp;
13124
+ lines[refreshed.index] = taskdoc_joinRow(cells);
13125
+ }
13126
+ return commit(context, lines, changes, `已更新「${options.taskId}」详情:${touched.join('、')}`, taskdoc_safeSegment(options.iteration, '迭代目录'), taskdoc_safeSegment(options.developer, '开发者标识'), 'detail', [
13127
+ options.taskId
13128
+ ], {
13129
+ docsRoot: options.docsRoot,
13130
+ policy: options.policy,
13131
+ commitMessage: `docs(${options.iteration}): 更新任务详情 ${options.taskId}(${touched.join('、')})`
13132
+ });
13133
+ }
13134
+ function applySelfTest(options) {
13135
+ assertWritableBranch(options.docsRoot);
13136
+ const schema = loadDocSchema(options.docsRoot);
13137
+ const keys = buildKeys(schema);
13138
+ const context = loadDoc(options.docsRoot, options.iteration, options.developer);
13139
+ const { header, rows } = parseTaskRows(context.lines, keys);
13140
+ const target = rows.find((row)=>row.taskId === options.taskId);
13141
+ if (void 0 === target) throw new errors_CliError(`任务清单中未找到 ${options.taskId}`, errors_EXIT.NOT_FOUND);
13142
+ if ('已完成' === target.status) throw new errors_CliError(`任务 ${options.taskId} 已验收完成,不允许改写自测证据;如需重测请先验收驳回`, errors_EXIT.USAGE);
13143
+ const reason = (options.reason ?? '').trim();
13144
+ if ('免测' === options.result && 0 === reason.length) throw new errors_CliError('「免测」必须通过 --reason 说明免测理由', errors_EXIT.USAGE);
13145
+ if ('免测' !== options.result && reason.length > 0) throw new errors_CliError('只有「免测」需要 --reason;通过/失败请勿传理由', errors_EXIT.USAGE);
13146
+ const allowed = [
13147
+ ...schema.enums.selfTest,
13148
+ '免测'
13149
+ ];
13150
+ if (!allowed.includes(options.result)) throw new errors_CliError(`自测结果「${options.result}」不在允许值内(${allowed.join(' / ')})`, errors_EXIT.USAGE);
13151
+ const value = '免测' === options.result ? `免测 (${reason})` : options.result;
13152
+ if (target.selfTest === value) return {
13153
+ ok: true,
13154
+ message: '自测状态未发生变化',
13155
+ changes: [],
13156
+ file: context.file
13157
+ };
13158
+ const stamp = nowStamp();
13159
+ const updated = [
13160
+ ...context.lines
13161
+ ];
13162
+ const cells = [
13163
+ ...target.cells
13164
+ ];
13165
+ cells[columnIndex(header, keys.task.selfTest)] = value;
13166
+ cells[columnIndex(header, keys.task.updatedAt)] = stamp;
13167
+ updated[target.index] = taskdoc_joinRow(cells);
13168
+ const withDetail = updateDetailBlock(updated, options.taskId, {
13169
+ 自测状态: value
13170
+ });
13171
+ return commit(context, withDetail, [
13172
+ `${options.taskId} AI 自测状态:${target.selfTest || '未执行'} → ${value}`
13173
+ ], `已记录「${options.taskId}」AI 自测:${value}`, taskdoc_safeSegment(options.iteration, '迭代目录'), taskdoc_safeSegment(options.developer, '开发者标识'), 'selftest', [
13174
+ options.taskId
13175
+ ], {
13176
+ docsRoot: options.docsRoot,
13177
+ policy: options.policy,
13178
+ commitMessage: `docs(${options.iteration}): 记录自测 ${options.taskId}(${value})`
13179
+ });
13180
+ }
12672
13181
  function applyBatchAction(options) {
12673
13182
  if (0 === options.taskIds.length) throw new errors_CliError('未选择任务', errors_EXIT.USAGE);
12674
13183
  assertWritableBranch(options.docsRoot);
@@ -12677,7 +13186,7 @@ function applyBatchAction(options) {
12677
13186
  let lines = context.lines;
12678
13187
  const changes = [];
12679
13188
  for (const taskId of options.taskIds){
12680
- const result = computeUpdate(lines, taskId, options.action, keys);
13189
+ const result = computeUpdate(lines, taskId, options.action, keys, options.docsRoot);
12681
13190
  lines = result.lines;
12682
13191
  changes.push(...result.changes);
12683
13192
  }
@@ -12691,7 +13200,7 @@ function applyTaskAction(options) {
12691
13200
  assertWritableBranch(options.docsRoot);
12692
13201
  const keys = buildKeys(loadDocSchema(options.docsRoot));
12693
13202
  const context = loadDoc(options.docsRoot, options.iteration, options.developer);
12694
- const result = computeUpdate(context.lines, options.taskId, options.action, keys);
13203
+ const result = computeUpdate(context.lines, options.taskId, options.action, keys, options.docsRoot);
12695
13204
  return commit(context, result.lines, result.changes, `已执行「${ACTION_META[options.action].label}」`, taskdoc_safeSegment(options.iteration, '迭代目录'), taskdoc_safeSegment(options.developer, '开发者标识'), options.action, [
12696
13205
  options.taskId
12697
13206
  ], {
@@ -12704,7 +13213,10 @@ function applyTaskAction(options) {
12704
13213
  }
12705
13214
  function validateAfterWrite(docsRoot, iteration, developer) {
12706
13215
  const script = external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py');
12707
- if (!external_node_fs_existsSync(script)) return null;
13216
+ if (!external_node_fs_existsSync(script)) return {
13217
+ kind: 'unavailable',
13218
+ reason: `文档仓库缺少校验脚本 ${script}`
13219
+ };
12708
13220
  const targetFile = external_node_path_join(docsRoot, iteration, `${developer}.md`);
12709
13221
  let role = 'frontend';
12710
13222
  if (external_node_fs_existsSync(targetFile)) try {
@@ -12712,48 +13224,121 @@ function validateAfterWrite(docsRoot, iteration, developer) {
12712
13224
  } catch {
12713
13225
  role = 'frontend';
12714
13226
  }
13227
+ const args = [
13228
+ script,
13229
+ '--docs-root',
13230
+ docsRoot,
13231
+ '--iteration',
13232
+ iteration,
13233
+ '--developer',
13234
+ developer,
13235
+ '--role',
13236
+ role,
13237
+ '--format',
13238
+ 'json'
13239
+ ];
13240
+ let interpreterMissing = true;
12715
13241
  let scriptError = null;
12716
13242
  for (const bin of [
12717
13243
  'python3',
12718
13244
  'python',
12719
13245
  'py'
12720
13246
  ])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
- ], {
13247
+ const stdout = execFileSync(bin, args, {
12734
13248
  encoding: 'utf8',
12735
13249
  timeout: 15000,
12736
- maxBuffer: 16777216
13250
+ maxBuffer: 16777216,
13251
+ stdio: [
13252
+ 'ignore',
13253
+ 'pipe',
13254
+ 'pipe'
13255
+ ]
12737
13256
  });
12738
13257
  const payload = JSON.parse(stdout);
12739
13258
  const first = payload.errors?.[0];
12740
- return first?.message ?? null;
13259
+ return void 0 === first ? {
13260
+ kind: 'passed'
13261
+ } : {
13262
+ kind: 'violation',
13263
+ message: first.message ?? '校验器未通过'
13264
+ };
12741
13265
  } catch (error) {
12742
13266
  const { stdout, stderr, code } = error;
13267
+ if ('ENOENT' === code || 127 === code) continue;
13268
+ interpreterMissing = false;
12743
13269
  if ((stdout ?? '').trim().length > 0) try {
12744
13270
  const payload = JSON.parse(stdout ?? '');
12745
- return payload.errors?.[0]?.message ?? '校验器未通过';
13271
+ return {
13272
+ kind: 'violation',
13273
+ message: payload.errors?.[0]?.message ?? '校验器未通过'
13274
+ };
12746
13275
  } catch {
12747
13276
  scriptError = '校验器输出无法解析';
12748
13277
  continue;
12749
13278
  }
12750
- if ('ENOENT' === code || 127 === code) continue;
12751
13279
  const reason = (stderr ?? '').trim().split('\n')[0] ?? '';
12752
13280
  scriptError = reason.length > 0 ? `校验器执行失败:${reason}` : '校验器执行失败';
12753
13281
  continue;
12754
13282
  }
12755
- if (null !== scriptError) return scriptError;
12756
- return null;
13283
+ if (null !== scriptError) return {
13284
+ kind: 'unavailable',
13285
+ reason: scriptError
13286
+ };
13287
+ if (interpreterMissing) return {
13288
+ kind: 'unavailable',
13289
+ reason: '未找到 python 解释器(需 python3 / python / py)'
13290
+ };
13291
+ return {
13292
+ kind: 'unavailable',
13293
+ reason: '校验器无法执行'
13294
+ };
13295
+ }
13296
+ function requireValidatorScript() {
13297
+ try {
13298
+ const config = loadConfig().config;
13299
+ if (null === config) return true;
13300
+ return config.docs.validator.requireScript;
13301
+ } catch {
13302
+ return true;
13303
+ }
13304
+ }
13305
+ function applyRequirementNote(options) {
13306
+ assertWritableBranch(options.docsRoot);
13307
+ const keys = buildKeys(loadDocSchema(options.docsRoot));
13308
+ const context = loadDoc(options.docsRoot, options.iteration, options.developer);
13309
+ const requirementId = options.requirementId.trim().replace(/^#?/, '#');
13310
+ const requirementParse = parseRequirementRows(context.lines, keys);
13311
+ const target = requirementParse.rows.find((row)=>row.id === requirementId);
13312
+ if (void 0 === target) throw new errors_CliError(`需求清单中未找到 ${requirementId}`, errors_EXIT.NOT_FOUND);
13313
+ const note = options.note.trim();
13314
+ if (0 === note.length) throw new errors_CliError('备注不能为空;如需清空请写成「无」', errors_EXIT.USAGE);
13315
+ if (0 === keys.requirement.note.length) throw new errors_CliError('schema.json 未声明需求备注列语义(requirementTable.keys.note)', errors_EXIT.INVALID);
13316
+ const noteIndex = columnIndex(requirementParse.header, keys.requirement.note);
13317
+ const previous = target.cells[noteIndex] ?? '';
13318
+ if (previous === note) return {
13319
+ ok: true,
13320
+ message: '备注未发生变化',
13321
+ changes: [],
13322
+ file: context.file
13323
+ };
13324
+ const lines = [
13325
+ ...context.lines
13326
+ ];
13327
+ const cells = [
13328
+ ...target.cells
13329
+ ];
13330
+ cells[noteIndex] = note;
13331
+ cells[columnIndex(requirementParse.header, keys.requirement.updatedAt)] = nowStamp();
13332
+ lines[target.index] = taskdoc_joinRow(cells);
13333
+ return commit(context, lines, [
13334
+ `${requirementId} 备注:${previous || '(空)'} → ${note}`
13335
+ ], `已更新需求 ${requirementId} 的备注`, taskdoc_safeSegment(options.iteration, '迭代目录'), taskdoc_safeSegment(options.developer, '开发者标识'), 'detail', [
13336
+ requirementId
13337
+ ], {
13338
+ docsRoot: options.docsRoot,
13339
+ policy: options.policy,
13340
+ commitMessage: `docs(${options.iteration}): 更新需求备注 ${requirementId}`
13341
+ });
12757
13342
  }
12758
13343
  function recalcRequirements(options) {
12759
13344
  assertWritableBranch(options.docsRoot);
@@ -12765,11 +13350,17 @@ function recalcRequirements(options) {
12765
13350
  ...context.lines
12766
13351
  ];
12767
13352
  const changes = [];
13353
+ const aggregates = resolveAggregates(options.docsRoot, new Map(requirementParse.rows.map((requirement)=>[
13354
+ requirement.id,
13355
+ taskRows.filter((row)=>row.requirementId === requirement.id).map((row)=>row.status)
13356
+ ])));
12768
13357
  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);
13358
+ const aggregate = aggregates.get(requirement.id) ?? {
13359
+ status: '未开始',
13360
+ progress: 0
13361
+ };
13362
+ const status = aggregate.status;
13363
+ const progress = aggregate.progress;
12773
13364
  const cells = [
12774
13365
  ...requirement.cells
12775
13366
  ];
@@ -13099,10 +13690,15 @@ function runDocMigrate(options) {
13099
13690
  changedFiles.push(target);
13100
13691
  if (migrated.unresolved.length > 0) continue;
13101
13692
  const developer = basename(name, '.md');
13102
- const violation = validateAfterWrite(docsRoot, iteration, developer);
13103
- if (null !== violation) {
13693
+ const outcome = validateAfterWrite(docsRoot, iteration, developer);
13694
+ if ('passed' !== outcome.kind) {
13104
13695
  writeFileSync(target, original, 'utf8');
13105
- throw new errors_CliError(`迁移后校验未通过,已回滚 ${iteration}/${name}:${violation}`, errors_EXIT.INVALID);
13696
+ const reason = 'violation' === outcome.kind ? outcome.message : outcome.reason;
13697
+ if ('unavailable' === outcome.kind && !requireValidatorScript()) {
13698
+ process.stderr.write(`警告:${outcome.reason};${iteration}/${name} 未做迁移后校验(docs.validator.requireScript=false)\n`);
13699
+ continue;
13700
+ }
13701
+ throw new errors_CliError(`迁移后校验未通过,已回滚 ${iteration}/${name}:${reason}`, errors_EXIT.INVALID);
13106
13702
  }
13107
13703
  }
13108
13704
  }
@@ -13206,8 +13802,30 @@ function runDocApply(options, mode = 'apply') {
13206
13802
  schema,
13207
13803
  role,
13208
13804
  index: buildRepoSideIndex(config.terminals),
13209
- knownTaskIds: parsed.tasks.map((task)=>task.id)
13805
+ knownTaskIds: parsed.tasks.map((task)=>task.id),
13806
+ knownRequirements: parsed.requirements.map((item)=>item.id)
13210
13807
  });
13808
+ const statusesByRequirement = new Map();
13809
+ for (const item of parsed.tasks){
13810
+ const list = statusesByRequirement.get(item.requirementId) ?? [];
13811
+ statusesByRequirement.set(item.requirementId, [
13812
+ ...list,
13813
+ item.status
13814
+ ]);
13815
+ }
13816
+ for (const task of plan.tasks){
13817
+ const list = statusesByRequirement.get(task.requirement) ?? [];
13818
+ statusesByRequirement.set(task.requirement, [
13819
+ ...list,
13820
+ '未开始'
13821
+ ]);
13822
+ }
13823
+ const aggregates = resolveAggregates(docsRoot, statusesByRequirement);
13824
+ const aggregateByStatuses = new Map();
13825
+ for (const [requirementId, statuses] of statusesByRequirement){
13826
+ const value = aggregates.get(requirementId);
13827
+ if (void 0 !== value) aggregateByStatuses.set(statuses.join('\u0000'), value);
13828
+ }
13211
13829
  const stamp = doc_nowStamp();
13212
13830
  const rendered = renderPlan({
13213
13831
  schema,
@@ -13219,10 +13837,11 @@ function runDocApply(options, mode = 'apply') {
13219
13837
  lines: null === original ? null : original.split('\n')
13220
13838
  },
13221
13839
  stamp,
13222
- developer
13840
+ developer,
13841
+ aggregate: (statuses)=>aggregateByStatuses.get(statuses.join('\u0000')) ?? aggregateRequirement(statuses)
13223
13842
  });
13224
13843
  const sideIndex = buildRepoSideIndex(config.terminals);
13225
- const sideIssues = validateTaskSides({
13844
+ const sideReport = validateTaskSides({
13226
13845
  index: sideIndex,
13227
13846
  tasks: rendered.assigned.map((item)=>{
13228
13847
  const planned = plan.tasks.find((task)=>task.name === item.name);
@@ -13233,8 +13852,9 @@ function runDocApply(options, mode = 'apply') {
13233
13852
  };
13234
13853
  })
13235
13854
  });
13236
- const conflicts = sideIssues.filter((issue)=>'error' === issue.level);
13855
+ const conflicts = sideReport.issues.filter((issue)=>'error' === issue.level);
13237
13856
  if (conflicts.length > 0) throw new errors_CliError(`任务类型与终端归属不一致,已中止:\n${conflicts.map((issue)=>` · ${issue.message}`).join('\n')}`, errors_EXIT.INVALID);
13857
+ const sideSkippedNote = sideReport.skipped > 0 ? `本机终端配置未覆盖 ${sideReport.skipped} 个任务,其「所属端 vs 仓库」未校验` + (0 === Object.keys(config.terminals).length ? '(terminals 为空)' : '') : null;
13238
13858
  if (0 === rendered.assigned.length && rendered.markdown === original) {
13239
13859
  if ('json' === format) printJson({
13240
13860
  ok: true,
@@ -13270,19 +13890,25 @@ function runDocApply(options, mode = 'apply') {
13270
13890
  recursive: true
13271
13891
  });
13272
13892
  writeFileSync(targetFile, rendered.markdown, 'utf8');
13273
- const violation = validateAfterWrite(docsRoot, iteration, developer);
13274
- if (null !== violation) {
13893
+ const outcome = validateAfterWrite(docsRoot, iteration, developer);
13894
+ const rollback = (message)=>{
13275
13895
  if (null === original) unlinkSync(targetFile);
13276
13896
  else writeFileSync(targetFile, original, 'utf8');
13277
- throw new errors_CliError(`写入被校验器拒绝,已回滚:${violation}`, errors_EXIT.INVALID);
13897
+ throw new errors_CliError(message, errors_EXIT.INVALID);
13898
+ };
13899
+ if ('violation' === outcome.kind) rollback(`写入被校验器拒绝,已回滚:${outcome.message}`);
13900
+ if ('unavailable' === outcome.kind) {
13901
+ if (requireValidatorScript()) rollback(`未执行文档校验,已回滚:${outcome.reason}\n文档校验必须由文档仓库 scripts/validate_task_doc.py 裁决;如确需跳过(不推荐),可配置 docs.validator.requireScript: false`);
13902
+ process.stderr.write(`警告:${outcome.reason};本次写入未做文档校验(docs.validator.requireScript=false)\n`);
13278
13903
  }
13279
- const remaining = checkDocTaskSides({
13904
+ const remainingReport = checkDocTaskSides({
13280
13905
  docsRoot,
13281
13906
  iteration,
13282
13907
  developer,
13283
13908
  role,
13284
13909
  terminals: config.terminals
13285
- }).filter((issue)=>'error' === issue.level);
13910
+ });
13911
+ const remaining = remainingReport.issues.filter((issue)=>'error' === issue.level);
13286
13912
  const policy = config.docs.git.cli;
13287
13913
  const git = policy.commit ? commitInDocsRepo(docsRoot, targetFile, `docs: ${iteration} 新增 ${rendered.assigned.length} 个任务(${rendered.assigned.map((item)=>item.id).join('、')})`, policy.push) : void 0;
13288
13914
  if ('json' === format) printJson({
@@ -13292,11 +13918,17 @@ function runDocApply(options, mode = 'apply') {
13292
13918
  changes: rendered.changes,
13293
13919
  assigned: rendered.assigned,
13294
13920
  sideIssues: remaining.map((issue)=>issue.message),
13921
+ sideCheck: {
13922
+ checked: sideReport.checked,
13923
+ skipped: sideReport.skipped
13924
+ },
13925
+ sideWarning: sideSkippedNote,
13295
13926
  git
13296
13927
  });
13297
13928
  else {
13298
13929
  printLine(`已写入:${targetFile}`);
13299
13930
  for (const change of rendered.changes)printLine(` · ${change}`);
13931
+ if (null !== sideSkippedNote) printLine(`\n! ${sideSkippedNote}`);
13300
13932
  if (remaining.length > 0) {
13301
13933
  printLine('\n注意:以下任务的类型与终端归属不一致(请核对):');
13302
13934
  for (const issue of remaining)printLine(` · ${issue.message}`);
@@ -13314,6 +13946,31 @@ function registerDoc(program) {
13314
13946
  });
13315
13947
  registerDocMigrate(doc);
13316
13948
  }
13949
+ function resolveDeveloper(options, configured) {
13950
+ const explicit = options.developer?.trim();
13951
+ const target = void 0 !== explicit && explicit.length > 0 ? explicit : configured;
13952
+ if (target !== configured) throw new errors_CliError(`只能修改自己的任务文档(当前身份:${configured})`, errors_EXIT.USAGE);
13953
+ return target;
13954
+ }
13955
+ function requireWriteContext(options) {
13956
+ const ready = requireConfig(options.config);
13957
+ const config = ready.config;
13958
+ if (0 === config.docs.root.trim().length) throw new errors_CliError('未配置文档仓库:请先设置 docs.root', errors_EXIT.NOT_FOUND);
13959
+ const base = config.docs.git?.cli ?? {
13960
+ commit: true,
13961
+ push: false
13962
+ };
13963
+ const policy = {
13964
+ commit: options.commit ?? base.commit,
13965
+ push: options.push ?? base.push
13966
+ };
13967
+ if (policy.push) policy.commit = true;
13968
+ return {
13969
+ docsRoot: config.docs.root,
13970
+ developer: resolveDeveloper(options, config.profile.developer),
13971
+ policy
13972
+ };
13973
+ }
13317
13974
  function requireQueryContext(options) {
13318
13975
  const format = parseFormat(options.format);
13319
13976
  enableJsonErrors('json' === format);
@@ -13382,7 +14039,7 @@ function findIterationById(docsRoot, available, id) {
13382
14039
  const pattern = new RegExp(`^\\|\\s*${normalized.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*\\|`, 'm');
13383
14040
  const hits = [];
13384
14041
  for (const entry of available)for (const developer of entry.developers){
13385
- const target = resolve(docsRoot, entry.name, developer.file);
14042
+ const target = external_node_path_resolve(docsRoot, entry.name, developer.file);
13386
14043
  try {
13387
14044
  if (pattern.test(readFileSync(target, 'utf8'))) {
13388
14045
  hits.push(entry.name);
@@ -13532,6 +14189,11 @@ function filterDocs(docs, developer) {
13532
14189
  if (void 0 === target || 0 === target.length) return docs;
13533
14190
  return docs.filter((item)=>item.developer === target);
13534
14191
  }
14192
+ function switchActionLabel(action) {
14193
+ if ('selftest' === action) return '记录自测';
14194
+ if ('detail' === action) return '更新详情';
14195
+ return ACTION_META[action].label;
14196
+ }
13535
14197
  function collectSideIssues(options) {
13536
14198
  try {
13537
14199
  const loaded = requireConfig(options.config);
@@ -13541,36 +14203,11 @@ function collectSideIssues(options) {
13541
14203
  developer: options.developer,
13542
14204
  role: loaded.config.profile.role,
13543
14205
  terminals: loaded.config.terminals
13544
- }).filter((issue)=>'error' === issue.level).map((issue)=>issue.message);
14206
+ }).issues.filter((issue)=>'error' === issue.level).map((issue)=>issue.message);
13545
14207
  } catch {
13546
14208
  return [];
13547
14209
  }
13548
14210
  }
13549
- function resolveDeveloper(options, configured) {
13550
- const explicit = options.developer?.trim();
13551
- const target = void 0 !== explicit && explicit.length > 0 ? explicit : configured;
13552
- if (target !== configured) throw new errors_CliError(`只能修改自己的任务文档(当前身份:${configured})`, errors_EXIT.USAGE);
13553
- return target;
13554
- }
13555
- function requireWriteContext(options) {
13556
- const ready = requireConfig(options.config);
13557
- const config = ready.config;
13558
- if (0 === config.docs.root.trim().length) throw new errors_CliError('未配置文档仓库:请先设置 docs.root', errors_EXIT.NOT_FOUND);
13559
- const base = config.docs.git?.cli ?? {
13560
- commit: true,
13561
- push: false
13562
- };
13563
- const policy = {
13564
- commit: options.commit ?? base.commit,
13565
- push: options.push ?? base.push
13566
- };
13567
- if (policy.push) policy.commit = true;
13568
- return {
13569
- docsRoot: config.docs.root,
13570
- developer: resolveDeveloper(options, config.profile.developer),
13571
- policy
13572
- };
13573
- }
13574
14211
  function runAction(action, taskId, options) {
13575
14212
  const { docsRoot, developer, policy } = requireWriteContext(options);
13576
14213
  const iteration = options.iteration?.trim() ? resolveIterationName(options, docsRoot, loadIterations(docsRoot)) : resolveIterationName(options, docsRoot, loadIterations(docsRoot), {
@@ -13623,6 +14260,75 @@ function runAction(action, taskId, options) {
13623
14260
  for (const message of sideIssues)printLine(` · ${message}`);
13624
14261
  }
13625
14262
  }
14263
+ function parseDetailUpdates(sets, appends) {
14264
+ const updates = [];
14265
+ const collect = (values, append)=>{
14266
+ for (const raw of values ?? []){
14267
+ const separator = raw.indexOf('=');
14268
+ if (separator <= 0) throw new errors_CliError(`字段更新需写成「字段=值」:${raw}`, errors_EXIT.USAGE);
14269
+ const field = raw.slice(0, separator).trim();
14270
+ const value = raw.slice(separator + 1).trim();
14271
+ if (0 === field.length || 0 === value.length) throw new errors_CliError(`字段更新需写成「字段=值」:${raw}`, errors_EXIT.USAGE);
14272
+ updates.push({
14273
+ field,
14274
+ value,
14275
+ append
14276
+ });
14277
+ }
14278
+ };
14279
+ collect(sets, false);
14280
+ collect(appends, true);
14281
+ return updates;
14282
+ }
14283
+ function runDetail(taskId, options) {
14284
+ const { docsRoot, developer, policy } = requireWriteContext(options);
14285
+ const iteration = options.iteration?.trim() ? resolveIterationName(options, docsRoot, loadIterations(docsRoot)) : resolveIterationName(options, docsRoot, loadIterations(docsRoot), {
14286
+ taskId: taskId.trim().replace(/^#?/, '#')
14287
+ });
14288
+ const format = parseFormat(options.format);
14289
+ const updates = parseDetailUpdates(options.set, options.append);
14290
+ const applied = applyTaskDetail({
14291
+ docsRoot,
14292
+ iteration,
14293
+ developer,
14294
+ taskId: taskId.trim().replace(/^#?/, '#'),
14295
+ updates,
14296
+ policy
14297
+ });
14298
+ if ('json' === format) return void printJson({
14299
+ ...applied,
14300
+ iteration
14301
+ });
14302
+ printLine(applied.message);
14303
+ for (const change of applied.changes)printLine(` · ${change}`);
14304
+ printLine(`文档:${applied.file}`);
14305
+ if (void 0 !== applied.git) printLine(`git:${applied.git.message}`);
14306
+ }
14307
+ function runSelfTest(taskId, options) {
14308
+ const { docsRoot, developer, policy } = requireWriteContext(options);
14309
+ const iteration = options.iteration?.trim() ? resolveIterationName(options, docsRoot, loadIterations(docsRoot)) : resolveIterationName(options, docsRoot, loadIterations(docsRoot), {
14310
+ taskId: taskId.trim().replace(/^#?/, '#')
14311
+ });
14312
+ const format = parseFormat(options.format);
14313
+ const result = options.result.trim();
14314
+ const applied = applySelfTest({
14315
+ docsRoot,
14316
+ iteration,
14317
+ developer,
14318
+ taskId: taskId.trim().replace(/^#?/, '#'),
14319
+ result,
14320
+ reason: options.reason,
14321
+ policy
14322
+ });
14323
+ if ('json' === format) return void printJson({
14324
+ ...applied,
14325
+ iteration
14326
+ });
14327
+ printLine(applied.message);
14328
+ for (const change of applied.changes)printLine(` · ${change}`);
14329
+ printLine(`文档:${applied.file}`);
14330
+ if (void 0 !== applied.git) printLine(`git:${applied.git.message}`);
14331
+ }
13626
14332
  function runActions(options) {
13627
14333
  const { docsRoot, developer } = requireWriteContext(options);
13628
14334
  const iteration = resolveIterationName(options, docsRoot, loadIterations(docsRoot));
@@ -13673,7 +14379,8 @@ function runHistory(taskId, options) {
13673
14379
  if ('json' === parseFormat(options.format)) return void printJson(entries);
13674
14380
  if (0 === entries.length) return void printLine('暂无变更记录');
13675
14381
  for (const entry of entries){
13676
- printLine(`${new Date(entry.at).toLocaleString('zh-CN')} ${ACTION_META[entry.action].label}`);
14382
+ const label = switchActionLabel(entry.action);
14383
+ printLine(`${new Date(entry.at).toLocaleString('zh-CN')} ${label}`);
13677
14384
  for (const change of entry.changes)printLine(` · ${change}`);
13678
14385
  }
13679
14386
  }
@@ -13771,6 +14478,8 @@ function registerTask(program) {
13771
14478
  'accept',
13772
14479
  'reject'
13773
14480
  ])commonOptions(task.command(`${action} <taskId>`)).description(`执行「${ACTION_META[action].label}」:${ACTION_META[action].from} → ${ACTION_META[action].to}`).option('--dry-run', '只校验是否允许,不写入').option('--commit', '本次变更后提交(覆盖 docs.git.cli.commit)').option('--no-commit', '本次变更后不提交').option('--push', '提交后推送(隐含 --commit)').option('--no-push', '不推送').action((taskId, options)=>runAction(action, taskId, options));
14481
+ commonOptions(task.command('selftest <taskId>')).description('记录 AI 自测结果:通过 / 失败 / 免测(免测需 --reason)').requiredOption('--result <result>', '自测结果:通过 | 失败 | 免测').option('--reason <reason>', '免测理由(仅 --result 免测 时需要)').option('--commit', '本次变更后提交(覆盖 docs.git.cli.commit)').option('--no-commit', '本次变更后不提交').option('--push', '提交后推送(隐含 --commit)').option('--no-push', '不推送').action((taskId, options)=>runSelfTest(taskId, options));
14482
+ commonOptions(task.command('detail <taskId>')).description('局部更新任务详情字段:--set 替换、--append 追加,值内换行写成多条').option('--set <fieldValue...>', '替换字段内容,格式「字段=值」').option('--append <fieldValue...>', '追加到字段条目末尾,格式「字段=值」').option('--commit', '本次变更后提交(覆盖 docs.git.cli.commit)').option('--no-commit', '本次变更后不提交').option('--push', '提交后推送(隐含 --commit)').option('--no-push', '不推送').action((taskId, options)=>runDetail(taskId, options));
13774
14483
  commonOptions(task.command('batch <action> <taskIds...>')).description('批量执行同一动作,例如: ylcwf task batch accept "#2755-T1" "#2755-T2"').action((action, taskIds, options)=>{
13775
14484
  if (!(action in ACTION_META)) throw new errors_CliError(`未知动作:${action}(可选 ${Object.keys(ACTION_META).join(' / ')})`, errors_EXIT.USAGE);
13776
14485
  runBatch(action, taskIds, options);
@@ -13836,7 +14545,7 @@ function iteration_runShow(name, options) {
13836
14545
  printLine(`汇总:开发者 ${summary.totals.developers} 需求 ${summary.totals.requirements} 任务 ${summary.totals.tasks}(已完成 ${summary.totals.completedTasks}) 进度 ${summary.totals.progress}%`);
13837
14546
  printLine('');
13838
14547
  const rows = summary.developers.map((item)=>{
13839
- const progress = 0 === item.stats.tasks ? 0 : Math.round(item.stats.completedTasks / item.stats.tasks * 100);
14548
+ const progress = roundProgressPercent(item.stats.completedTasks, item.stats.tasks);
13840
14549
  return [
13841
14550
  item.id,
13842
14551
  item.roleInferred,
@@ -13907,7 +14616,7 @@ function runContext(options) {
13907
14616
  requirements: requirements.length,
13908
14617
  tasks: tasks.length,
13909
14618
  completedTasks,
13910
- progress: 0 === tasks.length ? 0 : Math.round(completedTasks / tasks.length * 100)
14619
+ progress: roundProgressPercent(completedTasks, tasks.length)
13911
14620
  },
13912
14621
  requirements,
13913
14622
  tasks,
@@ -14055,11 +14764,36 @@ function runRecalc(options) {
14055
14764
  for (const change of result.changes)printLine(` · ${change}`);
14056
14765
  if (true !== options.dryRun) printLine(`文档:${result.file}`);
14057
14766
  }
14767
+ function runNote(requirementId, options) {
14768
+ const { docsRoot, developer, policy } = requireWriteContext(options);
14769
+ const iteration = options.iteration?.trim() ? resolveIterationName(options, docsRoot, loadIterations(docsRoot)) : resolveIterationName(options, docsRoot, loadIterations(docsRoot), {
14770
+ requirementId: requirementId.trim().replace(/^#?/, '#')
14771
+ });
14772
+ const note = (options.set ?? '').trim();
14773
+ if (0 === note.length) throw new errors_CliError('请用 --set 提供备注内容', errors_EXIT.USAGE);
14774
+ const applied = applyRequirementNote({
14775
+ docsRoot,
14776
+ iteration,
14777
+ developer,
14778
+ requirementId,
14779
+ note,
14780
+ policy
14781
+ });
14782
+ if ('json' === options.format) return void printJson({
14783
+ ...applied,
14784
+ iteration
14785
+ });
14786
+ printLine(applied.message);
14787
+ for (const change of applied.changes)printLine(` · ${change}`);
14788
+ printLine(`文档:${applied.file}`);
14789
+ if (void 0 !== applied.git) printLine(`git:${applied.git.message}`);
14790
+ }
14058
14791
  function registerRequirement(program) {
14059
14792
  const requirement = program.command('requirement').description('查看需求与关联任务,并重算需求状态');
14060
14793
  const common = (command)=>command.option('-c, --config <path>', '指定配置文件路径').option('-i, --iteration <name>', '迭代目录名(可省略:在迭代目录内执行时自动推断)').option('-d, --developer <name>', '只看某位成员的需求').option('--format <format>', '输出格式:human | json', 'human');
14061
14794
  common(requirement.command('list')).description('列出迭代下的需求清单').action((options)=>requirement_runList(options));
14062
14795
  common(requirement.command('show <requirementId>')).description('查看需求详情与关联任务').action((requirementId, options)=>requirement_runShow(requirementId, options));
14796
+ common(requirement.command('note <requirementId>')).description('更新需求备注(只改本人文档)').option('--set <note>', '备注内容,例如 "19 个任务均已实现,待人工验收"').option('--commit', '本次变更后提交(覆盖 docs.git.cli.commit)').option('--no-commit', '本次变更后不提交').option('--push', '提交后推送(隐含 --commit)').option('--no-push', '不推送').action((requirementId, options)=>runNote(requirementId, options));
14063
14797
  common(requirement.command('recalc')).description('按任务状态重算需求开发状态与进度').option('--dry-run', '只输出差异,不写入').action((options)=>runRecalc(options));
14064
14798
  }
14065
14799
  let cache = null;
@@ -14083,9 +14817,9 @@ async function fetchManifest(url) {
14083
14817
  const payload = await response.json();
14084
14818
  if ('string' != typeof payload.version || 0 === payload.version.length) return null;
14085
14819
  return {
14086
- current: "0.5.0",
14820
+ current: "0.5.2",
14087
14821
  latest: payload.version,
14088
- hasUpdate: isNewer(payload.version, "0.5.0"),
14822
+ hasUpdate: isNewer(payload.version, "0.5.2"),
14089
14823
  downloadUrl: 'string' == typeof payload.downloadUrl ? payload.downloadUrl : null,
14090
14824
  source: 'manifest',
14091
14825
  checkedAt: new Date().toISOString(),
@@ -14097,7 +14831,7 @@ async function fetchManifest(url) {
14097
14831
  }
14098
14832
  async function fetchNpm() {
14099
14833
  const base = {
14100
- current: "0.5.0",
14834
+ current: "0.5.2",
14101
14835
  latest: null,
14102
14836
  hasUpdate: false,
14103
14837
  downloadUrl: null,
@@ -14124,7 +14858,7 @@ async function fetchNpm() {
14124
14858
  return {
14125
14859
  ...base,
14126
14860
  latest,
14127
- hasUpdate: isNewer(latest, "0.5.0"),
14861
+ hasUpdate: isNewer(latest, "0.5.2"),
14128
14862
  downloadUrl: null
14129
14863
  };
14130
14864
  } catch (error) {
@@ -14215,7 +14949,7 @@ async function runUpgrade(options) {
14215
14949
  const kind = detectInstallKind();
14216
14950
  const result = await checkUpdate(true);
14217
14951
  const target = options.to?.trim() ?? result.latest;
14218
- printLine("当前版本:0.5.0");
14952
+ printLine("当前版本:0.5.2");
14219
14953
  if (null !== result.error) printLine(`版本查询失败:${result.error}`);
14220
14954
  else if (null !== result.latest) printLine(`最新版本:${result.latest}(来源:${result.source})`);
14221
14955
  if (null === target) throw new errors_CliError('无法确定目标版本,请稍后重试或用 --to 指定', errors_EXIT.NOT_FOUND);
@@ -14388,18 +15122,28 @@ function checkDocsSides(config) {
14388
15122
  });
14389
15123
  } catch {
14390
15124
  return [
14391
- `无法读取文档仓库:${root}`
15125
+ {
15126
+ level: 'warning',
15127
+ message: `无法读取文档仓库:${root}`
15128
+ }
14392
15129
  ];
14393
15130
  }
14394
15131
  for (const iteration of iterations)try {
14395
- const issues = checkDocTaskSides({
15132
+ const report = checkDocTaskSides({
14396
15133
  docsRoot: root,
14397
15134
  iteration,
14398
15135
  developer: config.profile.developer,
14399
15136
  role: config.profile.role,
14400
15137
  terminals: config.terminals
14401
15138
  });
14402
- for (const issue of issues)messages.push(`[${iteration}] ${issue.message}`);
15139
+ for (const issue of report.issues)messages.push({
15140
+ level: issue.level,
15141
+ message: `[${iteration}] ${issue.message}`
15142
+ });
15143
+ if (report.skipped > 0) messages.push({
15144
+ level: 'warning',
15145
+ message: `[${iteration}] ${report.checked} 个任务完成归属校验,${report.skipped} 个因终端未配置/歧义被跳过(跳过≠通过)`
15146
+ });
14403
15147
  } catch {}
14404
15148
  return messages;
14405
15149
  }
@@ -14412,24 +15156,24 @@ function runDoctor(options) {
14412
15156
  });
14413
15157
  const errors = countIssues(checked.issues).errors;
14414
15158
  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;
15159
+ const sideIssues = [];
15160
+ if (true === options.docs && null !== checked.config && ok) sideIssues.push(...checkDocsSides(checked.config));
15161
+ const sideErrors = sideIssues.filter((item)=>'error' === item.level).length;
14418
15162
  const allOk = ok && 0 === sideErrors;
14419
15163
  if ('json' === format) printJson({
14420
15164
  ok: allOk,
14421
15165
  configPath: loaded.path,
14422
15166
  ...countIssues(checked.issues),
14423
15167
  issues: checked.issues,
14424
- docSideIssues: sideMessages
15168
+ docSideIssues: sideIssues.map((item)=>`[${item.level}] ${item.message}`)
14425
15169
  });
14426
15170
  else {
14427
15171
  printLine(`配置文件 ${loaded.path}`);
14428
15172
  printLine(formatIssues(checked.issues, '校验通过,未发现问题'));
14429
- if (sideMessages.length > 0) {
15173
+ if (sideIssues.length > 0) {
14430
15174
  printLine('');
14431
15175
  printLine('文档体检:');
14432
- for (const message of sideMessages)printLine(` · ${message}`);
15176
+ for (const item of sideIssues)printLine(` ${'error' === item.level ? '✗' : '!'} ${item.message}`);
14433
15177
  }
14434
15178
  if (!allOk) printLine(`\n校验失败:${errors} 项配置 error${sideErrors > 0 ? `,${sideErrors} 项文档问题` : ''}`);
14435
15179
  }
@@ -14501,6 +15245,11 @@ function syncDocument(doc, next) {
14501
15245
  'push'
14502
15246
  ], next.docs.git[side].push);
14503
15247
  }
15248
+ doc.setIn([
15249
+ 'docs',
15250
+ 'validator',
15251
+ 'requireScript'
15252
+ ], next.docs.validator.requireScript);
14504
15253
  const current = doc.toJS();
14505
15254
  const currentTerminals = utils_isRecord(current) && utils_isRecord(current['terminals']) ? Object.keys(current['terminals']) : [];
14506
15255
  for (const key of currentTerminals)if (!Object.hasOwn(next.terminals, key)) doc.deleteIn([
@@ -14599,7 +15348,7 @@ function readState(explicitPath) {
14599
15348
  issues: checked.issues,
14600
15349
  backups: listBackups(explicitPath),
14601
15350
  meta: {
14602
- version: "0.5.0",
15351
+ version: "0.5.2",
14603
15352
  features: SERVER_FEATURES
14604
15353
  }
14605
15354
  };
@@ -14749,7 +15498,7 @@ function completeOnboarding(draftRaw, configPath) {
14749
15498
  return inspectOnboarding(configPath);
14750
15499
  }
14751
15500
  function assertDirectory(target) {
14752
- const absolute = isAbsolute(target) ? resolve(target) : resolve(homedir(), target);
15501
+ const absolute = isAbsolute(target) ? external_node_path_resolve(target) : external_node_path_resolve(homedir(), target);
14753
15502
  if (!external_node_fs_existsSync(absolute)) throw new errors_CliError(`目录不存在:${absolute}`, errors_EXIT.NOT_FOUND);
14754
15503
  if (!statSync(absolute).isDirectory()) throw new errors_CliError(`不是目录:${absolute}`, errors_EXIT.USAGE);
14755
15504
  return absolute;
@@ -14782,27 +15531,217 @@ function listDirectories(target) {
14782
15531
  entries
14783
15532
  };
14784
15533
  }
14785
- function openInFileManager(target) {
14786
- try {
14787
- const absolute = assertDirectory(target);
14788
- const command = 'darwin' === process.platform ? 'open' : 'win32' === process.platform ? 'explorer' : 'xdg-open';
14789
- spawn(command, [
14790
- absolute
14791
- ], {
15534
+ function revealCommand(target) {
15535
+ switch(process.platform){
15536
+ case 'win32':
15537
+ return {
15538
+ command: 'cmd.exe',
15539
+ args: [
15540
+ '/c',
15541
+ 'start',
15542
+ '',
15543
+ 'explorer.exe',
15544
+ target
15545
+ ]
15546
+ };
15547
+ case 'darwin':
15548
+ return {
15549
+ command: 'open',
15550
+ args: [
15551
+ target
15552
+ ]
15553
+ };
15554
+ default:
15555
+ return {
15556
+ command: 'xdg-open',
15557
+ args: [
15558
+ target
15559
+ ]
15560
+ };
15561
+ }
15562
+ }
15563
+ function spawnDetached(command, args) {
15564
+ return new Promise((resolve, reject)=>{
15565
+ const child = spawn(command, args, {
14792
15566
  detached: true,
14793
15567
  stdio: 'ignore'
14794
- }).unref();
15568
+ });
15569
+ child.once('error', reject);
15570
+ child.once('spawn', ()=>{
15571
+ child.unref();
15572
+ resolve();
15573
+ });
15574
+ });
15575
+ }
15576
+ async function openInFileManager(target) {
15577
+ try {
15578
+ const absolute = assertDirectory(target);
15579
+ const { command, args } = revealCommand(absolute);
15580
+ await spawnDetached(command, args);
14795
15581
  return {
14796
15582
  ok: true,
14797
- message: `已打开 ${absolute}`
15583
+ message: `已在文件管理器中打开 ${absolute}`
14798
15584
  };
14799
15585
  } catch (error) {
14800
15586
  const message = error instanceof errors_CliError ? error.message : String(error);
14801
15587
  return {
14802
15588
  ok: false,
14803
- message
15589
+ message: `打开目录失败:${message}`
15590
+ };
15591
+ }
15592
+ }
15593
+ const PICK_TIMEOUT_MS = 300000;
15594
+ function runCapture(command, args) {
15595
+ return new Promise((resolve)=>{
15596
+ execFile(command, args, {
15597
+ timeout: PICK_TIMEOUT_MS,
15598
+ maxBuffer: 4194304,
15599
+ windowsHide: false
15600
+ }, (error, stdout, stderr)=>{
15601
+ const code = null === error ? 0 : error.code;
15602
+ resolve({
15603
+ code: 'number' == typeof code ? code : 1,
15604
+ stdout: String(stdout ?? ''),
15605
+ stderr: String(stderr ?? '')
15606
+ });
15607
+ });
15608
+ });
15609
+ }
15610
+ function escapeAppleScript(value) {
15611
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
15612
+ }
15613
+ function escapePowerShell(value) {
15614
+ return value.replace(/'/g, "''");
15615
+ }
15616
+ async function pickOnMac(title, defaultPath) {
15617
+ const prompt = escapeAppleScript(title);
15618
+ const location = null === defaultPath || 0 === defaultPath.length ? '' : ` default location POSIX file "${escapeAppleScript(defaultPath)}"`;
15619
+ const script = [
15620
+ 'try',
15621
+ ` set theFolder to choose folder with prompt "${prompt}"${location}`,
15622
+ ' return POSIX path of theFolder',
15623
+ 'on error number -128',
15624
+ ' return ""',
15625
+ 'end try'
15626
+ ].join('\n');
15627
+ const result = await runCapture("osascript", [
15628
+ '-e',
15629
+ script
15630
+ ]);
15631
+ if (0 !== result.code) return {
15632
+ ok: false,
15633
+ path: null,
15634
+ cancelled: false,
15635
+ message: (result.stderr.trim().split('\n').pop() ?? "osascript 执行失败").slice(0, 200)
15636
+ };
15637
+ const picked = result.stdout.trim();
15638
+ if (0 === picked.length) return {
15639
+ ok: true,
15640
+ path: null,
15641
+ cancelled: true,
15642
+ message: '已取消'
15643
+ };
15644
+ return {
15645
+ ok: true,
15646
+ path: picked.length > 1 ? picked.replace(/\/+$/, '') : picked,
15647
+ cancelled: false,
15648
+ message: picked
15649
+ };
15650
+ }
15651
+ async function pickOnWindows(title, defaultPath) {
15652
+ const description = escapePowerShell(title);
15653
+ const initial = null === defaultPath || 0 === defaultPath.length ? '' : `$dialog.SelectedPath = '${escapePowerShell(defaultPath)}';`;
15654
+ const script = [
15655
+ 'Add-Type -AssemblyName System.Windows.Forms',
15656
+ '$dialog = New-Object System.Windows.Forms.FolderBrowserDialog',
15657
+ `$dialog.Description = '${description}'`,
15658
+ '$dialog.ShowNewFolderButton = $true',
15659
+ initial,
15660
+ "if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {",
15661
+ ' Write-Output $dialog.SelectedPath',
15662
+ '} else {',
15663
+ " Write-Output ''",
15664
+ '}'
15665
+ ].filter((line)=>line.length > 0).join('; ');
15666
+ for (const shell of [
15667
+ 'powershell.exe',
15668
+ 'pwsh.exe'
15669
+ ]){
15670
+ const result = await runCapture(shell, [
15671
+ '-NoProfile',
15672
+ '-STA',
15673
+ '-Command',
15674
+ script
15675
+ ]);
15676
+ if (0 !== result.code) continue;
15677
+ const picked = result.stdout.trim();
15678
+ if (0 === picked.length) return {
15679
+ ok: true,
15680
+ path: null,
15681
+ cancelled: true,
15682
+ message: '已取消'
15683
+ };
15684
+ const trimmed = picked.replace(/\\+$/, '');
15685
+ const normalized = /^[a-zA-Z]:$/.test(trimmed) ? `${trimmed}\\` : trimmed;
15686
+ return {
15687
+ ok: true,
15688
+ path: normalized,
15689
+ cancelled: false,
15690
+ message: normalized
14804
15691
  };
14805
15692
  }
15693
+ return {
15694
+ ok: false,
15695
+ path: null,
15696
+ cancelled: false,
15697
+ message: '未找到可用的 PowerShell'
15698
+ };
15699
+ }
15700
+ async function pickOnLinux(title, defaultPath) {
15701
+ const args = [
15702
+ '--file-selection',
15703
+ '--directory',
15704
+ `--title=${title}`
15705
+ ];
15706
+ if (null !== defaultPath && defaultPath.length > 0) args.push(`--filename=${defaultPath.replace(/\/?$/, '/')}`);
15707
+ const result = await runCapture('zenity', args);
15708
+ if (1 === result.code) return {
15709
+ ok: true,
15710
+ path: null,
15711
+ cancelled: true,
15712
+ message: '已取消'
15713
+ };
15714
+ if (0 !== result.code) return {
15715
+ ok: false,
15716
+ path: null,
15717
+ cancelled: false,
15718
+ message: (result.stderr.trim().split('\n').pop() ?? 'zenity 执行失败').slice(0, 200)
15719
+ };
15720
+ const picked = result.stdout.trim();
15721
+ if (0 === picked.length) return {
15722
+ ok: true,
15723
+ path: null,
15724
+ cancelled: true,
15725
+ message: '已取消'
15726
+ };
15727
+ const trimmed = picked.replace(/\/+$/, '');
15728
+ const normalized = 0 === trimmed.length ? '/' : trimmed;
15729
+ return {
15730
+ ok: true,
15731
+ path: normalized,
15732
+ cancelled: false,
15733
+ message: normalized
15734
+ };
15735
+ }
15736
+ async function pickDirectoryNatively(options) {
15737
+ const title = options.title?.trim() ?? '';
15738
+ const prompt = 0 === title.length ? '选择目录' : title;
15739
+ let initial = options.defaultPath?.trim() ?? null;
15740
+ if (null !== initial && 0 === initial.length) initial = null;
15741
+ if (null !== initial && !external_node_fs_existsSync(initial)) initial = null;
15742
+ if ('darwin' === process.platform) return pickOnMac(prompt, initial);
15743
+ if ('win32' === process.platform) return pickOnWindows(prompt, initial);
15744
+ return pickOnLinux(prompt, initial);
14806
15745
  }
14807
15746
  function requireDocsRoot(configPath) {
14808
15747
  const loaded = loadConfig(configPath);
@@ -14877,8 +15816,8 @@ async function readJsonBody(request) {
14877
15816
  }
14878
15817
  function resolveStaticPath(uiDir, pathname) {
14879
15818
  const decoded = decodeURIComponent(pathname);
14880
- const target = resolve(uiDir, `.${'/' === decoded ? '/index.html' : decoded}`);
14881
- const root = resolve(uiDir) + sep;
15819
+ const target = external_node_path_resolve(uiDir, `.${'/' === decoded ? '/index.html' : decoded}`);
15820
+ const root = external_node_path_resolve(uiDir) + sep;
14882
15821
  return target.startsWith(root) ? target : null;
14883
15822
  }
14884
15823
  function serveStatic(response, uiDir, pathname) {
@@ -14956,10 +15895,20 @@ async function startServer(options) {
14956
15895
  if ('GET' === request.method && '/api/fs/list' === url.pathname) return void sendJson(response, 200, listDirectories(url.searchParams.get('path') ?? void 0));
14957
15896
  if ('POST' === request.method && '/api/fs/open' === url.pathname) {
14958
15897
  const body = await readJsonBody(request);
14959
- sendJson(response, 200, openInFileManager(pickString(body, 'path')));
15898
+ sendJson(response, 200, await openInFileManager(pickString(body, 'path')));
15899
+ return;
15900
+ }
15901
+ if ('POST' === request.method && '/api/fs/pick' === url.pathname) {
15902
+ const body = await readJsonBody(request);
15903
+ const title = pickString(body, 'title');
15904
+ const defaultPath = pickString(body, 'defaultPath');
15905
+ sendJson(response, 200, await pickDirectoryNatively({
15906
+ title: title.length > 0 ? title : void 0,
15907
+ defaultPath: defaultPath.length > 0 ? defaultPath : null
15908
+ }));
14960
15909
  return;
14961
15910
  }
14962
- if ('POST' === request.method && '/api/reveal' === url.pathname) return void sendJson(response, 200, openInFileManager(external_node_path_dirname(paths_resolveConfigPath(options.configPath))));
15911
+ if ('POST' === request.method && '/api/reveal' === url.pathname) return void sendJson(response, 200, await openInFileManager(external_node_path_dirname(paths_resolveConfigPath(options.configPath))));
14963
15912
  if ('GET' === request.method && '/api/task-actions' === url.pathname) {
14964
15913
  const loaded = loadConfig(options.configPath);
14965
15914
  const developer = url.searchParams.get('developer') ?? '';
@@ -15121,9 +16070,9 @@ function assertUiBuilt(uiDir) {
15121
16070
  function defaultUiDir() {
15122
16071
  const here = external_node_path_dirname(fileURLToPath(import.meta.url));
15123
16072
  const candidates = [
15124
- resolve(here, '..', 'ui-dist'),
15125
- resolve(here, '..', '..', 'ui-dist'),
15126
- resolve(process.cwd(), 'ui-dist')
16073
+ external_node_path_resolve(here, '..', 'ui-dist'),
16074
+ external_node_path_resolve(here, '..', '..', 'ui-dist'),
16075
+ external_node_path_resolve(process.cwd(), 'ui-dist')
15127
16076
  ];
15128
16077
  return candidates.find((dir)=>external_node_fs_existsSync(external_node_path_join(dir, 'index.html'))) ?? candidates[0] ?? 'ui-dist';
15129
16078
  }
@@ -15179,7 +16128,7 @@ async function findAvailablePort(desired, attempts = 20) {
15179
16128
  throw new errors_CliError(`端口 ${desired}–${desired + attempts - 1} 均被占用,请用 --port 指定其他端口`, errors_EXIT.USAGE);
15180
16129
  }
15181
16130
  async function runServe(options) {
15182
- const uiDir = void 0 !== options.uiDir ? resolve(options.uiDir) : defaultUiDir();
16131
+ const uiDir = void 0 !== options.uiDir ? external_node_path_resolve(options.uiDir) : defaultUiDir();
15183
16132
  assertUiBuilt(uiDir);
15184
16133
  const port = void 0 === options.port ? 4317 : Number.parseInt(options.port, 10);
15185
16134
  if (!Number.isInteger(port) || port < 0 || port > 65535) throw new errors_CliError(`--port 不是合法端口:${options.port ?? ''}`, errors_EXIT.USAGE);
@@ -15234,7 +16183,7 @@ function registerReset(program) {
15234
16183
  }
15235
16184
  function buildProgram() {
15236
16185
  const program = new command_Command();
15237
- program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与终端仓库映射').version("0.5.0", '-v, --version', '显示版本号').showHelpAfterError();
16186
+ program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与终端仓库映射').version("0.5.2", '-v, --version', '显示版本号').showHelpAfterError();
15238
16187
  registerInit(program);
15239
16188
  registerShow(program);
15240
16189
  registerGet(program);