ylcwf 0.6.0 → 0.6.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
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";
3
+ import node_path, { basename, dirname as external_node_path_dirname, extname, isAbsolute as external_node_path_isAbsolute, join as external_node_path_join, relative as external_node_path_relative, resolve as external_node_path_resolve, sep } from "node:path";
4
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 : external_node_path_resolve(process.cwd(), fromFlag);
9237
+ if (void 0 !== fromFlag && fromFlag.length > 0) return external_node_path_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 : external_node_path_resolve(process.cwd(), fromEnv);
9239
+ if (void 0 !== fromEnv && fromEnv.length > 0) return external_node_path_isAbsolute(fromEnv) ? fromEnv : external_node_path_resolve(process.cwd(), fromEnv);
9240
9240
  return DEFAULT_CONFIG_PATH;
9241
9241
  }
9242
9242
  function serveTokenPath() {
@@ -9248,184 +9248,97 @@ function historyPath() {
9248
9248
  function backupsDir(configPath) {
9249
9249
  return external_node_path_join(external_node_path_dirname(configPath), 'backups');
9250
9250
  }
9251
- const DEFAULT_ITERATIONS_ROOT = 'iterations';
9252
- const YEAR_PATTERN = /^\d{4}$/;
9253
- function currentIterationYear() {
9254
- return new Date().getFullYear();
9255
- }
9256
- function isYearDirectory(name) {
9257
- return YEAR_PATTERN.test(name);
9258
- }
9259
- function isIterationYear(value) {
9260
- return Number.isInteger(value) && YEAR_PATTERN.test(String(value));
9261
- }
9262
- function iterationsRootPath(docsRoot, iterationsRoot) {
9263
- const base = 0 === iterationsRoot.trim().length ? DEFAULT_ITERATIONS_ROOT : iterationsRoot.trim();
9264
- return external_node_path_join(docsRoot, base);
9265
- }
9266
- function yearDirPath(docsRoot, iterationsRoot, year) {
9267
- return external_node_path_join(iterationsRootPath(docsRoot, iterationsRoot), String(year));
9268
- }
9269
- function iterationRelPath(year, name) {
9270
- return `${year}/${name}`;
9271
- }
9272
- function listIterationYears(docsRoot, iterationsRoot) {
9273
- const root = iterationsRootPath(docsRoot, iterationsRoot);
9274
- if (!external_node_fs_existsSync(root)) return [];
9275
- try {
9276
- return external_node_fs_readdirSync(root, {
9277
- withFileTypes: true
9278
- }).filter((entry)=>entry.isDirectory() && isYearDirectory(entry.name)).map((entry)=>Number.parseInt(entry.name, 10)).sort((left, right)=>left - right);
9279
- } catch {
9280
- return [];
9281
- }
9282
- }
9283
- function listIterationDirs(docsRoot, iterationsRoot) {
9284
- const result = [];
9285
- for (const year of listIterationYears(docsRoot, iterationsRoot)){
9286
- const yearDir = yearDirPath(docsRoot, iterationsRoot, year);
9287
- let entries;
9288
- try {
9289
- entries = external_node_fs_readdirSync(yearDir, {
9290
- withFileTypes: true
9291
- }).filter((entry)=>entry.isDirectory() && !entry.name.startsWith('.')).map((entry)=>entry.name);
9292
- } catch {
9293
- continue;
9294
- }
9295
- for (const name of entries.sort())result.push({
9296
- name,
9297
- year,
9298
- dir: external_node_path_join(yearDir, name),
9299
- relPath: iterationRelPath(year, name)
9300
- });
9301
- }
9302
- return result;
9303
- }
9304
- function parseIterationRef(input) {
9305
- const text = input.trim().replace(/^\.\//, '');
9306
- const match = /^(\d{4})[/\\](.+)$/.exec(text);
9307
- if (null === match) return {
9308
- year: null,
9309
- name: text
9310
- };
9311
- const year = Number.parseInt(match[1] ?? '', 10);
9312
- const name = (match[2] ?? '').trim();
9313
- return Number.isInteger(year) ? {
9314
- year,
9315
- name
9251
+ const TERMINAL_CATALOG_FILE = 'execution_terminals.json';
9252
+ function terminals_error(code, message, where) {
9253
+ return void 0 === where ? {
9254
+ level: 'error',
9255
+ code,
9256
+ message
9316
9257
  } : {
9317
- year: null,
9318
- name: text
9258
+ level: 'error',
9259
+ code,
9260
+ message,
9261
+ where
9319
9262
  };
9320
9263
  }
9321
- function ambiguous(name, pool) {
9322
- const listed = pool.map((item)=>item.relPath).sort().join('、');
9323
- return new errors_CliError(`迭代名在多个年份下重复:${name}(${listed})。请用「年份/迭代名」显式指定,例如 -i ${pool[0]?.relPath ?? ''}`, errors_EXIT.USAGE);
9324
- }
9325
- function resolveIterationDir(docsRoot, iterationsRoot, input) {
9326
- const { year, name } = parseIterationRef(input);
9327
- if (0 === name.length) throw new errors_CliError('必须指定迭代目录', errors_EXIT.USAGE);
9328
- const all = listIterationDirs(docsRoot, iterationsRoot);
9329
- const scoped = null === year ? all : all.filter((item)=>item.year === year);
9330
- const exact = scoped.filter((item)=>item.name === name);
9331
- if (1 === exact.length && void 0 !== exact[0]) return exact[0];
9332
- if (exact.length > 1) throw ambiguous(name, exact);
9333
- const folded = scoped.filter((item)=>item.name.toLowerCase() === name.toLowerCase());
9334
- if (1 === folded.length && void 0 !== folded[0]) return folded[0];
9335
- if (folded.length > 1) throw ambiguous(name, folded);
9336
- const where = null === year ? '' : `(${year} 年)`;
9337
- const years = listIterationYears(docsRoot, iterationsRoot);
9338
- const hint = 0 === years.length ? `\n该文档仓库尚未建立迭代目录:${iterationsRootPath(docsRoot, iterationsRoot)}` : `\n已有年份:${years.join('、')}`;
9339
- throw new errors_CliError(`迭代目录不存在${where}:${name}${hint}`, errors_EXIT.NOT_FOUND);
9264
+ function terminals_isRecord(value) {
9265
+ return 'object' == typeof value && null !== value && !Array.isArray(value);
9340
9266
  }
9341
- function newIterationDir(docsRoot, iterationsRoot, writeYear, name, options = {}) {
9342
- const trimmed = name.trim();
9343
- if (0 === trimmed.length) throw new errors_CliError('迭代目录名不能为空', errors_EXIT.USAGE);
9344
- if (trimmed.includes('/') || trimmed.includes('\\') || trimmed.includes('..')) throw new errors_CliError(`迭代目录名不能包含路径分隔符:${name}`, errors_EXIT.USAGE);
9345
- if (!isIterationYear(writeYear)) throw new errors_CliError(`写入年份必须是 4 位数字:${writeYear}`, errors_EXIT.USAGE);
9346
- const dir = external_node_path_join(yearDirPath(docsRoot, iterationsRoot, writeYear), trimmed);
9347
- if (false !== options.create) mkdirSync(dir, {
9348
- recursive: true
9267
+ function checkTerminalCatalog(raw) {
9268
+ const issues = [];
9269
+ if (!terminals_isRecord(raw)) return {
9270
+ catalog: null,
9271
+ issues: [
9272
+ terminals_error('TERMINAL_CATALOG_TYPE', `${TERMINAL_CATALOG_FILE} 必须是对象`)
9273
+ ]
9274
+ };
9275
+ const list = raw['terminals'];
9276
+ if (!Array.isArray(list)) return {
9277
+ catalog: null,
9278
+ issues: [
9279
+ terminals_error('TERMINAL_CATALOG_INVALID', 'terminals 必须是数组', 'terminals')
9280
+ ]
9281
+ };
9282
+ const entries = [];
9283
+ const seen = new Set();
9284
+ list.forEach((item, index)=>{
9285
+ const where = `terminals[${index}]`;
9286
+ const name = terminals_isRecord(item) ? item['name'] : item;
9287
+ if ('string' != typeof name || 0 === name.trim().length) return void issues.push(terminals_error('TERMINAL_CATALOG_NAME_INVALID', `${where}.name 不能为空`, `${where}.name`));
9288
+ const trimmed = name.trim();
9289
+ if (seen.has(trimmed)) return void issues.push(terminals_error('TERMINAL_CATALOG_DUPLICATED', `执行终端「${trimmed}」重复声明`, `${where}.name`));
9290
+ seen.add(trimmed);
9291
+ const descRaw = terminals_isRecord(item) ? item['desc'] : void 0;
9292
+ entries.push({
9293
+ name: trimmed,
9294
+ desc: 'string' == typeof descRaw && descRaw.trim().length > 0 ? descRaw.trim() : null
9295
+ });
9349
9296
  });
9297
+ if (issues.some((issue)=>'error' === issue.level)) return {
9298
+ catalog: null,
9299
+ issues
9300
+ };
9350
9301
  return {
9351
- name: trimmed,
9352
- year: writeYear,
9353
- dir,
9354
- relPath: iterationRelPath(writeYear, trimmed)
9302
+ catalog: {
9303
+ terminals: entries
9304
+ },
9305
+ issues
9355
9306
  };
9356
9307
  }
9357
- function requireIterationDir(docsRoot, iterationsRoot, input) {
9308
+ function loadTerminalCatalog(docsRoot) {
9309
+ const path = external_node_path_join(docsRoot, TERMINAL_CATALOG_FILE);
9310
+ let text;
9358
9311
  try {
9359
- return resolveIterationDir(docsRoot, iterationsRoot, input);
9360
- } catch (error) {
9361
- if (error instanceof errors_CliError && error.exitCode === errors_EXIT.NOT_FOUND) {
9362
- const { name } = parseIterationRef(input);
9363
- throw new errors_CliError(`${error.message}\n新建迭代目录:ylcwf iteration create <年份>/${name}`, errors_EXIT.NOT_FOUND);
9364
- }
9365
- throw error;
9312
+ text = readFileSync(path, 'utf8');
9313
+ } catch {
9314
+ return {
9315
+ path,
9316
+ catalog: null,
9317
+ issues: []
9318
+ };
9366
9319
  }
9367
- }
9368
- function createIterationDir(docsRoot, iterationsRoot, input, options = {}) {
9369
- const { year: prefixYear, name } = parseIterationRef(input);
9370
- const trimmed = name.trim();
9371
- if (0 === trimmed.length) throw new errors_CliError('迭代目录名不能为空', errors_EXIT.USAGE);
9372
- if (trimmed.includes('/') || trimmed.includes('\\') || trimmed.includes('..')) throw new errors_CliError(`迭代目录名不能包含路径分隔符:${name}`, errors_EXIT.USAGE);
9373
- const year = prefixYear ?? options.year ?? currentIterationYear();
9374
- if (!isIterationYear(year)) throw new errors_CliError(`年份必须是 4 位数字:${String(year)}`, errors_EXIT.USAGE);
9375
- const target = newIterationDir(docsRoot, iterationsRoot, year, trimmed, {
9376
- create: false
9377
- });
9378
- if (external_node_fs_existsSync(target.dir)) return {
9379
- iteration: target,
9380
- created: false
9381
- };
9382
- const existing = listIterationDirs(docsRoot, iterationsRoot).filter((item)=>item.name.toLowerCase() === trimmed.toLowerCase());
9383
- if (null === prefixYear && existing.length > 0) {
9384
- const listed = existing.map((item)=>item.relPath).join('、');
9385
- throw new errors_CliError(`迭代名已存在于其他年份:${trimmed}(${listed})\n如需在新年份下再建一个同名迭代,请显式写年份:ylcwf iteration create ${year}/${trimmed}`, errors_EXIT.USAGE);
9320
+ let raw;
9321
+ try {
9322
+ raw = JSON.parse(text);
9323
+ } catch (caught) {
9324
+ const detail = caught instanceof Error ? caught.message : String(caught);
9325
+ return {
9326
+ path,
9327
+ catalog: null,
9328
+ issues: [
9329
+ terminals_error('TERMINAL_CATALOG_JSON', `${TERMINAL_CATALOG_FILE} 不是合法 JSON:${detail}`)
9330
+ ]
9331
+ };
9386
9332
  }
9387
- mkdirSync(target.dir, {
9388
- recursive: true
9389
- });
9390
9333
  return {
9391
- iteration: target,
9392
- created: true
9334
+ path,
9335
+ ...checkTerminalCatalog(raw)
9393
9336
  };
9394
9337
  }
9395
- function validateIterationsRoot(value) {
9396
- const text = value.trim();
9397
- if (0 === text.length) return null;
9398
- if (isAbsolute(text)) return '迭代根目录必须是相对 docs.root 的路径,不能是绝对路径';
9399
- const segments = text.split(/[/\\]+/).filter((segment)=>segment.length > 0);
9400
- if (0 === segments.length) return '迭代根目录不能为空';
9401
- if (segments.some((segment)=>'..' === segment || '.' === segment)) return '迭代根目录不能包含「..」或「.」';
9402
- return null;
9403
- }
9404
- const DASH_PATTERN = /[\u2010-\u2015\u2212\uFE58\uFE63\uFF0D_-]+/g;
9405
- function normalizeName(input) {
9406
- return input.normalize('NFKC').replace(/\s+/g, '').replace(DASH_PATTERN, '-').replace(/^-+/, '').replace(/-+$/, '').toLowerCase();
9407
- }
9408
- function normalize_editDistance(a, b) {
9409
- if (a === b) return 0;
9410
- if (0 === a.length) return b.length;
9411
- if (0 === b.length) return a.length;
9412
- let previous = Array.from({
9413
- length: b.length + 1
9414
- }, (_, index)=>index);
9415
- for(let i = 1; i <= a.length; i += 1){
9416
- const current = [
9417
- i
9418
- ];
9419
- for(let j = 1; j <= b.length; j += 1){
9420
- const cost = a.charAt(i - 1) === b.charAt(j - 1) ? 0 : 1;
9421
- const deletion = (previous[j] ?? 0) + 1;
9422
- const insertion = (current[j - 1] ?? 0) + 1;
9423
- const substitution = (previous[j - 1] ?? 0) + cost;
9424
- current[j] = Math.min(deletion, insertion, substitution);
9425
- }
9426
- previous = current;
9427
- }
9428
- return previous[b.length] ?? 0;
9338
+ function catalogNames(docsRoot) {
9339
+ const loaded = loadTerminalCatalog(docsRoot);
9340
+ if (null === loaded.catalog) return [];
9341
+ return loaded.catalog.terminals.map((entry)=>entry.name);
9429
9342
  }
9430
9343
  function utils_isRecord(value) {
9431
9344
  return 'object' == typeof value && null !== value && !Array.isArray(value);
@@ -9457,6 +9370,51 @@ function isAbsolutePath(value) {
9457
9370
  if (/^[\\/]{2}[^\\/]/.test(input)) return true;
9458
9371
  return input.startsWith('/');
9459
9372
  }
9373
+ function parseDotPath(input) {
9374
+ const parts = input.split('.').map((part)=>part.trim());
9375
+ if (0 === parts.length || parts.some((part)=>0 === part.length)) throw new errors_CliError(`路径不合法:${input}(应形如 docs.role)`, errors_EXIT.USAGE);
9376
+ return parts;
9377
+ }
9378
+ function getIn(root, path) {
9379
+ let current = root;
9380
+ for (const key of path){
9381
+ if (!utils_isRecord(current)) return;
9382
+ if (!Object.hasOwn(current, key)) return;
9383
+ current = current[key];
9384
+ }
9385
+ return current;
9386
+ }
9387
+ function renderScalar(value) {
9388
+ if ('string' == typeof value) return value;
9389
+ if (null === value) return 'null';
9390
+ return JSON.stringify(value);
9391
+ }
9392
+ const DASH_PATTERN = /[\u2010-\u2015\u2212\uFE58\uFE63\uFF0D_-]+/g;
9393
+ function normalizeName(input) {
9394
+ return input.normalize('NFKC').replace(/\s+/g, '').replace(DASH_PATTERN, '-').replace(/^-+/, '').replace(/-+$/, '').toLowerCase();
9395
+ }
9396
+ function normalize_editDistance(a, b) {
9397
+ if (a === b) return 0;
9398
+ if (0 === a.length) return b.length;
9399
+ if (0 === b.length) return a.length;
9400
+ let previous = Array.from({
9401
+ length: b.length + 1
9402
+ }, (_, index)=>index);
9403
+ for(let i = 1; i <= a.length; i += 1){
9404
+ const current = [
9405
+ i
9406
+ ];
9407
+ for(let j = 1; j <= b.length; j += 1){
9408
+ const cost = a.charAt(i - 1) === b.charAt(j - 1) ? 0 : 1;
9409
+ const deletion = (previous[j] ?? 0) + 1;
9410
+ const insertion = (current[j - 1] ?? 0) + 1;
9411
+ const substitution = (previous[j - 1] ?? 0) + cost;
9412
+ current[j] = Math.min(deletion, insertion, substitution);
9413
+ }
9414
+ previous = current;
9415
+ }
9416
+ return previous[b.length] ?? 0;
9417
+ }
9460
9418
  const ROLES = [
9461
9419
  'frontend',
9462
9420
  'backend',
@@ -9477,7 +9435,6 @@ const PROFILE_KEYS = new Set([
9477
9435
  ]);
9478
9436
  const DOCS_KEYS = new Set([
9479
9437
  'root',
9480
- 'iterationsRoot',
9481
9438
  'git',
9482
9439
  'validator'
9483
9440
  ]);
@@ -9528,7 +9485,8 @@ function warning(code, message, where) {
9528
9485
  };
9529
9486
  }
9530
9487
  const REMOVED_DOCS_KEYS = new Set([
9531
- 'iterationWriteYear'
9488
+ 'iterationWriteYear',
9489
+ 'iterationsRoot'
9532
9490
  ]);
9533
9491
  const REMOVED_TERMINAL_KEYS = new Set([
9534
9492
  'aliases'
@@ -9624,33 +9582,16 @@ function parseDocs(rawInput, options, issues) {
9624
9582
  if (null === parsed) return null;
9625
9583
  root = parsed;
9626
9584
  }
9627
- const iterationsRoot = parseIterationsRoot(raw['iterationsRoot'], issues);
9628
- if (null === iterationsRoot) return null;
9629
9585
  const git = parseGitPolicy(raw['git'], issues);
9630
9586
  if (null === git) return null;
9631
9587
  const validator = parseValidatorPolicy(raw['validator'], issues);
9632
9588
  if (null === validator) return null;
9633
9589
  return {
9634
9590
  root,
9635
- iterationsRoot,
9636
9591
  git,
9637
9592
  validator
9638
9593
  };
9639
9594
  }
9640
- function parseIterationsRoot(raw, issues) {
9641
- if (null == raw) return DEFAULT_ITERATIONS_ROOT;
9642
- if ('string' != typeof raw) {
9643
- issues.push(schema_error('ITERATIONS_ROOT_INVALID', 'docs.iterationsRoot 必须是字符串', 'docs.iterationsRoot'));
9644
- return null;
9645
- }
9646
- const problem = validateIterationsRoot(raw);
9647
- if (null !== problem) {
9648
- issues.push(schema_error('ITERATIONS_ROOT_INVALID', problem, 'docs.iterationsRoot'));
9649
- return null;
9650
- }
9651
- const text = raw.trim();
9652
- return 0 === text.length ? DEFAULT_ITERATIONS_ROOT : text;
9653
- }
9654
9595
  function parseValidatorPolicy(raw, issues) {
9655
9596
  if (null == raw) return {
9656
9597
  ...DEFAULT_VALIDATOR_POLICY
@@ -9761,15 +9702,21 @@ function parseRepos(raw, where, issues) {
9761
9702
  }
9762
9703
  return valid ? repos : null;
9763
9704
  }
9764
- function parseTerminals(raw, issues) {
9705
+ function parseTerminals(raw, issues, catalog = []) {
9765
9706
  if (!utils_isRecord(raw)) {
9766
9707
  issues.push(schema_error('TERMINALS_TYPE', 'terminals 必须是对象', 'terminals'));
9767
9708
  return null;
9768
9709
  }
9769
9710
  const terminals = {};
9770
9711
  let valid = true;
9712
+ const allowed = 0 === catalog.length ? null : catalog.map((name)=>normalizeName(name));
9771
9713
  for (const [name, value] of Object.entries(raw)){
9772
9714
  const where = `terminals.${name}`;
9715
+ if (null !== allowed && !allowed.includes(normalizeName(name))) {
9716
+ issues.push(schema_error('TERMINAL_NOT_IN_CATALOG', `执行终端「${name}」不在文档仓库 execution_terminals.json 中;可选:${catalog.join('、')}`, where));
9717
+ valid = false;
9718
+ continue;
9719
+ }
9773
9720
  if (name.includes('.')) {
9774
9721
  issues.push(schema_error('TERMINAL_KEY_DOT', `执行终端名不能包含「.」:${name}`, where));
9775
9722
  valid = false;
@@ -9862,7 +9809,7 @@ function checkConfig(raw, options = {}) {
9862
9809
  issues.push(...unknownKeys(normalized, TOP_LEVEL_KEYS, 'root'));
9863
9810
  const profile = parseProfile(normalized['profile'], options, issues);
9864
9811
  const docs = parseDocs(normalized['docs'], options, issues);
9865
- const terminals = parseTerminals(normalized['terminals'] ?? {}, issues);
9812
+ const terminals = parseTerminals(normalized['terminals'] ?? {}, issues, options.terminalCatalog);
9866
9813
  if (null === profile || null === docs || null === terminals) return {
9867
9814
  config: null,
9868
9815
  issues
@@ -9984,9 +9931,6 @@ profile:
9984
9931
 
9985
9932
  docs:
9986
9933
  root: ''
9987
- # 团队约定:迭代根目录(相对 root),其下按年份分组 iterations/2026/<迭代>/
9988
- # 通常不需要改;确需调整时用 ylcwf set docs.iterationsRoot <新值>
9989
- iterationsRoot: iterations
9990
9934
  git:
9991
9935
  cli: { commit: true, push: false }
9992
9936
  ui: { commit: true, push: false }
@@ -9996,6 +9940,17 @@ terminals: {}
9996
9940
  function createEmptyDocument() {
9997
9941
  return (0, dist_0.Tp)(TEMPLATE);
9998
9942
  }
9943
+ function checkConfigWithCatalog(raw, options = {}) {
9944
+ const docsRoot = getIn(raw, [
9945
+ 'docs',
9946
+ 'root'
9947
+ ]);
9948
+ const catalog = 'string' == typeof docsRoot && docsRoot.trim().length > 0 ? catalogNames(docsRoot.trim()) : [];
9949
+ return checkConfig(raw, {
9950
+ ...options,
9951
+ terminalCatalog: options.terminalCatalog ?? catalog
9952
+ });
9953
+ }
9999
9954
  function config_loadConfig(explicit) {
10000
9955
  const path = paths_resolveConfigPath(explicit);
10001
9956
  if (!external_node_fs_existsSync(path)) return {
@@ -10013,7 +9968,7 @@ function config_loadConfig(explicit) {
10013
9968
  throw new errors_CliError(`配置文件 YAML 语法错误:${path}\n${detail}`, errors_EXIT.INVALID);
10014
9969
  }
10015
9970
  const raw = doc.toJS();
10016
- const checked = checkConfig(raw, {
9971
+ const checked = checkConfigWithCatalog(raw, {
10017
9972
  allowIncomplete: true
10018
9973
  });
10019
9974
  return {
@@ -10049,7 +10004,7 @@ function obtainDocument(explicit) {
10049
10004
  }
10050
10005
  function assertWritable(doc, path) {
10051
10006
  const raw = doc.toJS();
10052
- const checked = checkConfig(raw, {
10007
+ const checked = checkConfigWithCatalog(raw, {
10053
10008
  allowIncomplete: true
10054
10009
  });
10055
10010
  if (null === checked.config || checked.issues.some((issue)=>'error' === issue.level)) throw new errors_CliError(`配置校验失败,已取消写入:${path}\n${formatIssues(checked.issues)}`, errors_EXIT.INVALID);
@@ -10073,13 +10028,23 @@ function saveDocument(doc, target) {
10073
10028
  mkdirSync(external_node_path_dirname(target), {
10074
10029
  recursive: true
10075
10030
  });
10076
- doc.deleteIn([
10077
- 'schemaVersion'
10078
- ]);
10079
- doc.deleteIn([
10080
- 'docs',
10081
- 'iterationWriteYear'
10082
- ]);
10031
+ for (const path of [
10032
+ [
10033
+ 'schemaVersion'
10034
+ ],
10035
+ [
10036
+ 'docs',
10037
+ 'iterationWriteYear'
10038
+ ],
10039
+ [
10040
+ 'docs',
10041
+ 'iterationsRoot'
10042
+ ],
10043
+ [
10044
+ 'docs',
10045
+ 'remote'
10046
+ ]
10047
+ ])if (doc.hasIn(path)) doc.deleteIn(path);
10083
10048
  toBlockStyle(doc.contents);
10084
10049
  const text = doc.toString({
10085
10050
  lineWidth: 0
@@ -10108,25 +10073,6 @@ function backup(target) {
10108
10073
  const stale = files.slice(0, Math.max(0, files.length - MAX_BACKUPS));
10109
10074
  for (const name of stale)unlinkSync(`${dir}/${name}`);
10110
10075
  }
10111
- function parseDotPath(input) {
10112
- const parts = input.split('.').map((part)=>part.trim());
10113
- if (0 === parts.length || parts.some((part)=>0 === part.length)) throw new errors_CliError(`路径不合法:${input}(应形如 docs.role)`, errors_EXIT.USAGE);
10114
- return parts;
10115
- }
10116
- function getIn(root, path) {
10117
- let current = root;
10118
- for (const key of path){
10119
- if (!utils_isRecord(current)) return;
10120
- if (!Object.hasOwn(current, key)) return;
10121
- current = current[key];
10122
- }
10123
- return current;
10124
- }
10125
- function renderScalar(value) {
10126
- if ('string' == typeof value) return value;
10127
- if (null === value) return 'null';
10128
- return JSON.stringify(value);
10129
- }
10130
10076
  function bail() {
10131
10077
  cancel('已取消');
10132
10078
  process.exit(errors_EXIT.OK);
@@ -10152,7 +10098,7 @@ async function askConfirm(message, initialValue) {
10152
10098
  function validateExistingDir(value) {
10153
10099
  const trimmed = (value ?? '').trim();
10154
10100
  if (0 === trimmed.length) return '不能为空';
10155
- if (!isAbsolute(trimmed)) return '必须是绝对路径';
10101
+ if (!external_node_path_isAbsolute(trimmed)) return '必须是绝对路径';
10156
10102
  if (!external_node_fs_existsSync(trimmed)) return '路径不存在';
10157
10103
  if (!statSync(trimmed).isDirectory()) return '不是目录';
10158
10104
  }
@@ -10318,7 +10264,7 @@ function showConfig(explicit, format) {
10318
10264
  printLine('运行 `ylcwf init` 完成首次配置,或 `ylcwf set <path> <value>` 精确修改。');
10319
10265
  return;
10320
10266
  }
10321
- const checked = checkConfig(loaded.raw, {
10267
+ const checked = checkConfigWithCatalog(loaded.raw, {
10322
10268
  checkFs: true
10323
10269
  });
10324
10270
  if ('json' === format) return void printJson({
@@ -10457,13 +10403,13 @@ function assertSettable(path) {
10457
10403
  if (4 === path.length && 'docs' === first && 'git' === second && ('cli' === third || 'ui' === third) && ('commit' === fourth || 'push' === fourth)) return;
10458
10404
  if (2 === path.length && 'profile' === first && ('developer' === second || 'role' === second)) return;
10459
10405
  if (4 === path.length && 'terminals' === first && void 0 !== second && 'repos' === third && void 0 !== fourth && SIDE_SET.has(fourth)) return;
10460
- throw new errors_CliError(`不支持通过 set 修改该路径:${path.join('.')}\n允许:docs.root / docs.iterationsRoot / docs.git.<cli|ui>.<commit|push> / profile.developer / profile.role / terminals.<执行终端>.repos.frontend|backend\n执行终端的新增与删除请用:ylcwf terminal add | rm`, errors_EXIT.USAGE);
10406
+ throw new errors_CliError(`不支持通过 set 修改该路径:${path.join('.')}\n允许:docs.root / docs.git.<cli|ui>.<commit|push> / profile.developer / profile.role / terminals.<执行终端>.repos.frontend|backend\n执行终端的新增与删除请用:ylcwf terminal add | rm`, errors_EXIT.USAGE);
10461
10407
  }
10462
10408
  function coerceValue(path, raw) {
10463
10409
  const key = path[path.length - 1];
10464
10410
  const trimmed = raw.trim();
10465
10411
  if ('root' === key) {
10466
- if (!isAbsolute(trimmed)) throw new errors_CliError(`文档仓库必须是绝对路径:${raw}`, errors_EXIT.USAGE);
10412
+ if (!external_node_path_isAbsolute(trimmed)) throw new errors_CliError(`文档仓库必须是绝对路径:${raw}`, errors_EXIT.USAGE);
10467
10413
  return trimmed;
10468
10414
  }
10469
10415
  if ('remote' === key) {
@@ -10481,7 +10427,7 @@ function coerceValue(path, raw) {
10481
10427
  }
10482
10428
  if ('frontend' === key || 'backend' === key) {
10483
10429
  const parts = parsePathList(trimmed);
10484
- for (const part of parts)if (!isAbsolute(part)) throw new errors_CliError(`仓库路径必须是绝对路径:${part}`, errors_EXIT.USAGE);
10430
+ for (const part of parts)if (!external_node_path_isAbsolute(part)) throw new errors_CliError(`仓库路径必须是绝对路径:${part}`, errors_EXIT.USAGE);
10485
10431
  return parts;
10486
10432
  }
10487
10433
  return raw;
@@ -10621,7 +10567,7 @@ function terminal_collect(value, previous) {
10621
10567
  function assertAbsolute(value, field) {
10622
10568
  const trimmed = value.trim();
10623
10569
  if (0 === trimmed.length) throw new errors_CliError(`${field} 不能为空`, errors_EXIT.USAGE);
10624
- if (!isAbsolute(trimmed)) throw new errors_CliError(`${field} 必须是绝对路径:${value}`, errors_EXIT.USAGE);
10570
+ if (!external_node_path_isAbsolute(trimmed)) throw new errors_CliError(`${field} 必须是绝对路径:${value}`, errors_EXIT.USAGE);
10625
10571
  return trimmed;
10626
10572
  }
10627
10573
  function parseSide(value) {
@@ -10668,11 +10614,21 @@ function runTerminalList(options) {
10668
10614
  }
10669
10615
  }
10670
10616
  }
10617
+ function assertInCatalog(name, configPath) {
10618
+ const loaded = config_loadConfig(configPath);
10619
+ const docsRoot = loaded.config?.docs.root ?? '';
10620
+ if (0 === docsRoot.length) return;
10621
+ const names = catalogNames(docsRoot);
10622
+ if (0 === names.length) return;
10623
+ if (names.includes(name)) return;
10624
+ throw new errors_CliError(`执行终端「${name}」不在文档仓库 execution_terminals.json 中\n可选:${names.join('、')}\n新增执行终端请先修改文档仓库的 execution_terminals.json`, errors_EXIT.USAGE);
10625
+ }
10671
10626
  function runTerminalAdd(key, options) {
10672
10627
  const trimmedKey = key.trim();
10673
10628
  if (0 === trimmedKey.length) throw new errors_CliError('执行终端名不能为空', errors_EXIT.USAGE);
10674
10629
  if (trimmedKey.includes('.')) throw new errors_CliError('执行终端名不能包含「.」(与配置路径语法冲突)', errors_EXIT.USAGE);
10675
10630
  const { path: configPath, doc } = obtainDocument(options.config);
10631
+ assertInCatalog(trimmedKey, configPath);
10676
10632
  if (void 0 !== getIn(doc.toJS(), [
10677
10633
  'terminals',
10678
10634
  trimmedKey
@@ -10821,69 +10777,213 @@ function aggregateRequirement(statuses) {
10821
10777
  status: '已完成',
10822
10778
  progress: 100
10823
10779
  };
10824
- const done = statuses.filter((status)=>'已完成' === status).length;
10780
+ const done = statuses.filter((status)=>'已完成' === status).length;
10781
+ return {
10782
+ status: '进行中',
10783
+ progress: roundProgressPercent(done, statuses.length)
10784
+ };
10785
+ }
10786
+ function resolveAggregates(docsRoot, lists) {
10787
+ const fallback = ()=>{
10788
+ const result = new Map();
10789
+ for (const [requirementId, statuses] of lists)result.set(requirementId, aggregateRequirement(statuses));
10790
+ return result;
10791
+ };
10792
+ if (0 === lists.size) return new Map();
10793
+ const remote = aggregateViaPython(docsRoot, lists);
10794
+ if (null !== remote) return remote;
10795
+ process.stderr.write("警告:未调用文档仓库 validate_task_doc.py --aggregate,需求状态与进度由本地实现计算;请确认文档仓库脚本已更新且本机具备 python3\n");
10796
+ return fallback();
10797
+ }
10798
+ function aggregateViaPython(docsRoot, lists) {
10799
+ const script = external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py');
10800
+ if (!external_node_fs_existsSync(script)) return null;
10801
+ const payload = {};
10802
+ for (const [requirementId, statuses] of lists)payload[requirementId] = statuses;
10803
+ const input = JSON.stringify(payload);
10804
+ for (const bin of [
10805
+ 'python3',
10806
+ 'python',
10807
+ 'py'
10808
+ ])try {
10809
+ const stdout = execFileSync(bin, [
10810
+ script,
10811
+ '--aggregate'
10812
+ ], {
10813
+ input,
10814
+ encoding: 'utf8',
10815
+ timeout: 10000,
10816
+ maxBuffer: 4194304,
10817
+ stdio: [
10818
+ 'pipe',
10819
+ 'pipe',
10820
+ 'pipe'
10821
+ ]
10822
+ });
10823
+ const parsed = JSON.parse(stdout);
10824
+ if (true !== parsed.ok || void 0 === parsed.data) return null;
10825
+ const result = new Map();
10826
+ for (const [requirementId, value] of Object.entries(parsed.data)){
10827
+ if ('string' != typeof value.status || 'number' != typeof value.progress) return null;
10828
+ result.set(requirementId, {
10829
+ status: value.status,
10830
+ progress: value.progress
10831
+ });
10832
+ }
10833
+ return result;
10834
+ } catch {
10835
+ continue;
10836
+ }
10837
+ return null;
10838
+ }
10839
+ const DEFAULT_ITERATIONS_ROOT = 'iterations';
10840
+ const YEAR_PATTERN = /^\d{4}$/;
10841
+ function currentIterationYear() {
10842
+ return new Date().getFullYear();
10843
+ }
10844
+ function isYearDirectory(name) {
10845
+ return YEAR_PATTERN.test(name);
10846
+ }
10847
+ function isIterationYear(value) {
10848
+ return Number.isInteger(value) && YEAR_PATTERN.test(String(value));
10849
+ }
10850
+ function iterationsRootPath(docsRoot, iterationsRoot) {
10851
+ const base = 0 === iterationsRoot.trim().length ? DEFAULT_ITERATIONS_ROOT : iterationsRoot.trim();
10852
+ return external_node_path_join(docsRoot, base);
10853
+ }
10854
+ function yearDirPath(docsRoot, iterationsRoot, year) {
10855
+ return external_node_path_join(iterationsRootPath(docsRoot, iterationsRoot), String(year));
10856
+ }
10857
+ function iterationRelPath(year, name) {
10858
+ return `${year}/${name}`;
10859
+ }
10860
+ function listIterationYears(docsRoot, iterationsRoot) {
10861
+ const root = iterationsRootPath(docsRoot, iterationsRoot);
10862
+ if (!external_node_fs_existsSync(root)) return [];
10863
+ try {
10864
+ return external_node_fs_readdirSync(root, {
10865
+ withFileTypes: true
10866
+ }).filter((entry)=>entry.isDirectory() && isYearDirectory(entry.name)).map((entry)=>Number.parseInt(entry.name, 10)).sort((left, right)=>left - right);
10867
+ } catch {
10868
+ return [];
10869
+ }
10870
+ }
10871
+ function listIterationDirs(docsRoot, iterationsRoot) {
10872
+ const result = [];
10873
+ for (const year of listIterationYears(docsRoot, iterationsRoot)){
10874
+ const yearDir = yearDirPath(docsRoot, iterationsRoot, year);
10875
+ let entries;
10876
+ try {
10877
+ entries = external_node_fs_readdirSync(yearDir, {
10878
+ withFileTypes: true
10879
+ }).filter((entry)=>entry.isDirectory() && !entry.name.startsWith('.')).map((entry)=>entry.name);
10880
+ } catch {
10881
+ continue;
10882
+ }
10883
+ for (const name of entries.sort())result.push({
10884
+ name,
10885
+ year,
10886
+ dir: external_node_path_join(yearDir, name),
10887
+ relPath: iterationRelPath(year, name)
10888
+ });
10889
+ }
10890
+ return result;
10891
+ }
10892
+ function parseIterationRef(input) {
10893
+ const text = input.trim().replace(/^\.\//, '');
10894
+ const match = /^(\d{4})[/\\](.+)$/.exec(text);
10895
+ if (null === match) return {
10896
+ year: null,
10897
+ name: text
10898
+ };
10899
+ const year = Number.parseInt(match[1] ?? '', 10);
10900
+ const name = (match[2] ?? '').trim();
10901
+ return Number.isInteger(year) ? {
10902
+ year,
10903
+ name
10904
+ } : {
10905
+ year: null,
10906
+ name: text
10907
+ };
10908
+ }
10909
+ function ambiguous(name, pool) {
10910
+ const listed = pool.map((item)=>item.relPath).sort().join('、');
10911
+ return new errors_CliError(`迭代名在多个年份下重复:${name}(${listed})。请用「年份/迭代名」显式指定,例如 -i ${pool[0]?.relPath ?? ''}`, errors_EXIT.USAGE);
10912
+ }
10913
+ function resolveIterationDir(docsRoot, iterationsRoot, input) {
10914
+ const { year, name } = parseIterationRef(input);
10915
+ if (0 === name.length) throw new errors_CliError('必须指定迭代目录', errors_EXIT.USAGE);
10916
+ const all = listIterationDirs(docsRoot, iterationsRoot);
10917
+ const scoped = null === year ? all : all.filter((item)=>item.year === year);
10918
+ const exact = scoped.filter((item)=>item.name === name);
10919
+ if (1 === exact.length && void 0 !== exact[0]) return exact[0];
10920
+ if (exact.length > 1) throw ambiguous(name, exact);
10921
+ const folded = scoped.filter((item)=>item.name.toLowerCase() === name.toLowerCase());
10922
+ if (1 === folded.length && void 0 !== folded[0]) return folded[0];
10923
+ if (folded.length > 1) throw ambiguous(name, folded);
10924
+ const where = null === year ? '' : `(${year} 年)`;
10925
+ const years = listIterationYears(docsRoot, iterationsRoot);
10926
+ const hint = 0 === years.length ? `\n该文档仓库尚未建立迭代目录:${iterationsRootPath(docsRoot, iterationsRoot)}` : `\n已有年份:${years.join('、')}`;
10927
+ throw new errors_CliError(`迭代目录不存在${where}:${name}${hint}`, errors_EXIT.NOT_FOUND);
10928
+ }
10929
+ function newIterationDir(docsRoot, iterationsRoot, writeYear, name, options = {}) {
10930
+ const trimmed = name.trim();
10931
+ if (0 === trimmed.length) throw new errors_CliError('迭代目录名不能为空', errors_EXIT.USAGE);
10932
+ if (trimmed.includes('/') || trimmed.includes('\\') || trimmed.includes('..')) throw new errors_CliError(`迭代目录名不能包含路径分隔符:${name}`, errors_EXIT.USAGE);
10933
+ if (!isIterationYear(writeYear)) throw new errors_CliError(`写入年份必须是 4 位数字:${writeYear}`, errors_EXIT.USAGE);
10934
+ const dir = external_node_path_join(yearDirPath(docsRoot, iterationsRoot, writeYear), trimmed);
10935
+ if (false !== options.create) mkdirSync(dir, {
10936
+ recursive: true
10937
+ });
10938
+ return {
10939
+ name: trimmed,
10940
+ year: writeYear,
10941
+ dir,
10942
+ relPath: iterationRelPath(writeYear, trimmed)
10943
+ };
10944
+ }
10945
+ function requireIterationDir(docsRoot, iterationsRoot, input) {
10946
+ try {
10947
+ return resolveIterationDir(docsRoot, iterationsRoot, input);
10948
+ } catch (error) {
10949
+ if (error instanceof errors_CliError && error.exitCode === errors_EXIT.NOT_FOUND) {
10950
+ const { name } = parseIterationRef(input);
10951
+ throw new errors_CliError(`${error.message}\n新建迭代目录:ylcwf iteration create <年份>/${name}`, errors_EXIT.NOT_FOUND);
10952
+ }
10953
+ throw error;
10954
+ }
10955
+ }
10956
+ function createIterationDir(docsRoot, iterationsRoot, input, options = {}) {
10957
+ const { year: prefixYear, name } = parseIterationRef(input);
10958
+ const trimmed = name.trim();
10959
+ if (0 === trimmed.length) throw new errors_CliError('迭代目录名不能为空', errors_EXIT.USAGE);
10960
+ if (trimmed.includes('/') || trimmed.includes('\\') || trimmed.includes('..')) throw new errors_CliError(`迭代目录名不能包含路径分隔符:${name}`, errors_EXIT.USAGE);
10961
+ const year = prefixYear ?? options.year ?? currentIterationYear();
10962
+ if (!isIterationYear(year)) throw new errors_CliError(`年份必须是 4 位数字:${String(year)}`, errors_EXIT.USAGE);
10963
+ const target = newIterationDir(docsRoot, iterationsRoot, year, trimmed, {
10964
+ create: false
10965
+ });
10966
+ if (external_node_fs_existsSync(target.dir)) return {
10967
+ iteration: target,
10968
+ created: false
10969
+ };
10970
+ const existing = listIterationDirs(docsRoot, iterationsRoot).filter((item)=>item.name.toLowerCase() === trimmed.toLowerCase());
10971
+ if (null === prefixYear && existing.length > 0) {
10972
+ const listed = existing.map((item)=>item.relPath).join('、');
10973
+ throw new errors_CliError(`迭代名已存在于其他年份:${trimmed}(${listed})\n如需在新年份下再建一个同名迭代,请显式写年份:ylcwf iteration create ${year}/${trimmed}`, errors_EXIT.USAGE);
10974
+ }
10975
+ mkdirSync(target.dir, {
10976
+ recursive: true
10977
+ });
10825
10978
  return {
10826
- status: '进行中',
10827
- progress: roundProgressPercent(done, statuses.length)
10828
- };
10829
- }
10830
- function resolveAggregates(docsRoot, lists) {
10831
- const fallback = ()=>{
10832
- const result = new Map();
10833
- for (const [requirementId, statuses] of lists)result.set(requirementId, aggregateRequirement(statuses));
10834
- return result;
10979
+ iteration: target,
10980
+ created: true
10835
10981
  };
10836
- if (0 === lists.size) return new Map();
10837
- const remote = aggregateViaPython(docsRoot, lists);
10838
- if (null !== remote) return remote;
10839
- process.stderr.write("警告:未调用文档仓库 validate_task_doc.py --aggregate,需求状态与进度由本地实现计算;请确认文档仓库脚本已更新且本机具备 python3\n");
10840
- return fallback();
10841
- }
10842
- function aggregateViaPython(docsRoot, lists) {
10843
- const script = external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py');
10844
- if (!external_node_fs_existsSync(script)) return null;
10845
- const payload = {};
10846
- for (const [requirementId, statuses] of lists)payload[requirementId] = statuses;
10847
- const input = JSON.stringify(payload);
10848
- for (const bin of [
10849
- 'python3',
10850
- 'python',
10851
- 'py'
10852
- ])try {
10853
- const stdout = execFileSync(bin, [
10854
- script,
10855
- '--aggregate'
10856
- ], {
10857
- input,
10858
- encoding: 'utf8',
10859
- timeout: 10000,
10860
- maxBuffer: 4194304,
10861
- stdio: [
10862
- 'pipe',
10863
- 'pipe',
10864
- 'pipe'
10865
- ]
10866
- });
10867
- const parsed = JSON.parse(stdout);
10868
- if (true !== parsed.ok || void 0 === parsed.data) return null;
10869
- const result = new Map();
10870
- for (const [requirementId, value] of Object.entries(parsed.data)){
10871
- if ('string' != typeof value.status || 'number' != typeof value.progress) return null;
10872
- result.set(requirementId, {
10873
- status: value.status,
10874
- progress: value.progress
10875
- });
10876
- }
10877
- return result;
10878
- } catch {
10879
- continue;
10880
- }
10881
- return null;
10882
10982
  }
10883
10983
  function layoutOf(config) {
10884
10984
  return {
10885
10985
  root: config?.docs.root ?? '',
10886
- iterationsRoot: config?.docs.iterationsRoot ?? DEFAULT_ITERATIONS_ROOT
10986
+ iterationsRoot: DEFAULT_ITERATIONS_ROOT
10887
10987
  };
10888
10988
  }
10889
10989
  function normalizeIterationKey(value) {
@@ -10962,7 +11062,59 @@ const TASK_TYPE_GROUPS = [
10962
11062
  'backend'
10963
11063
  ];
10964
11064
  const SUPPORTED_SCHEMA_VERSION = 1;
11065
+ const SCOPE_SEPARATOR = '、';
11066
+ const PLAN_SOURCE_FIELDS = [
11067
+ 'files',
11068
+ 'plan',
11069
+ 'selfTest',
11070
+ 'testForms',
11071
+ 'regression',
11072
+ 'notes'
11073
+ ];
11074
+ const RENDERER_BY_PLAN_FIELD = {
11075
+ files: 'code-change-list',
11076
+ selfTest: 'command-result-list',
11077
+ plan: 'list',
11078
+ testForms: 'list',
11079
+ regression: 'list',
11080
+ notes: 'inline'
11081
+ };
10965
11082
  const SCHEMA_FILENAME = 'schema.json';
11083
+ const REQUIRED_REQUIREMENT_KEYS = [
11084
+ 'id',
11085
+ 'title',
11086
+ 'terminal',
11087
+ 'status',
11088
+ 'progress',
11089
+ 'updatedAt'
11090
+ ];
11091
+ const REQUIRED_TASK_KEYS = [
11092
+ 'id',
11093
+ 'requirement',
11094
+ 'name',
11095
+ 'type',
11096
+ 'scope',
11097
+ 'terminal',
11098
+ 'dependencies',
11099
+ 'selfTest',
11100
+ 'acceptance',
11101
+ 'status',
11102
+ 'updatedAt'
11103
+ ];
11104
+ const REQUIRED_ENUMS = [
11105
+ 'requirementStatus',
11106
+ 'taskStatus',
11107
+ 'selfTest',
11108
+ 'acceptance'
11109
+ ];
11110
+ const ALLOWED_FORMATS = [
11111
+ 'percent',
11112
+ 'minute'
11113
+ ];
11114
+ const BUILTIN_ENUM_REFS = [
11115
+ 'taskTypes',
11116
+ 'scopes'
11117
+ ];
10966
11118
  function docSchemaPath(docsRoot) {
10967
11119
  return external_node_path_join(docsRoot, SCHEMA_FILENAME);
10968
11120
  }
@@ -10991,127 +11143,274 @@ function parseDocSchema(raw, docsRoot) {
10991
11143
  if (version > SUPPORTED_SCHEMA_VERSION) fail(docsRoot, `schemaVersion ${version} 高于当前 ylcwf 支持的 ${SUPPORTED_SCHEMA_VERSION},请升级 ylcwf`);
10992
11144
  const requirementTable = requireRecord(data.requirementTable, 'requirementTable', docsRoot);
10993
11145
  const taskTable = requireRecord(data.taskTable, 'taskTable', docsRoot);
10994
- const REQUIRED_REQUIREMENT_KEYS = [
10995
- 'id',
10996
- 'status',
10997
- 'progress',
10998
- 'updatedAt'
10999
- ];
11000
- const REQUIRED_TASK_KEYS = [
11001
- 'id',
11002
- 'requirement',
11003
- 'name',
11004
- 'type',
11005
- 'scope',
11006
- 'terminal',
11007
- 'dependencies',
11008
- 'selfTest',
11009
- 'acceptance',
11010
- 'status',
11011
- 'updatedAt'
11012
- ];
11013
- const readKeys = (table, headers, required, where)=>{
11014
- const raw = table.keys;
11015
- if (void 0 === raw) fail(docsRoot, `${where}.keys 必须声明列语义`);
11016
- const record = requireRecord(raw, `${where}.keys`, docsRoot);
11017
- const result = {};
11018
- for (const semantic of required){
11019
- const value = record[semantic];
11020
- if ('string' != typeof value || 0 === value.trim().length) fail(docsRoot, `${where}.keys 缺少必需语义:${semantic}`);
11021
- if (!headers.includes(value)) fail(docsRoot, `${where}.keys.${semantic} 指向的列「${value}」不在 headers 中`);
11022
- result[semantic] = value;
11023
- }
11024
- for (const [semantic, value] of Object.entries(record))if (void 0 === result[semantic]) {
11025
- if ('string' == typeof value && 0 !== value.trim().length) {
11026
- if (!headers.includes(value)) fail(docsRoot, `${where}.keys.${semantic} 指向的列「${value}」不在 headers 中`);
11027
- result[semantic] = value;
11028
- }
11029
- }
11030
- return result;
11031
- };
11032
- const progressRaw = requirementTable.progressRange;
11033
- let progressRange = [
11034
- 0,
11035
- 100
11036
- ];
11037
- if (void 0 !== progressRaw) {
11038
- if (!Array.isArray(progressRaw) || 2 !== progressRaw.length) fail(docsRoot, 'requirementTable.progressRange 必须是 [最小值, 最大值]');
11039
- const [low, high] = progressRaw;
11040
- if ('number' != typeof low || 'number' != typeof high) fail(docsRoot, 'requirementTable.progressRange 必须是数字');
11041
- progressRange = [
11042
- low,
11043
- high
11044
- ];
11045
- }
11046
- const enumsRaw = requireRecord(data.enums, 'enums', docsRoot);
11047
- const taskTypesRaw = requireRecord(data.taskTypes, 'taskTypes', docsRoot);
11048
- const taskTypes = {};
11049
- for (const group of TASK_TYPE_GROUPS){
11050
- const items = taskTypesRaw[group];
11051
- if (!Array.isArray(items) || 0 === items.length) fail(docsRoot, `taskTypes.${group} 必须是非空数组`);
11052
- taskTypes[group] = items.map((item, index)=>{
11053
- const entry = requireRecord(item, `taskTypes.${group}[${index}]`, docsRoot);
11054
- return {
11055
- name: requireString(entry.name, `taskTypes.${group}[${index}].name`, docsRoot),
11056
- desc: requireString(entry.desc, `taskTypes.${group}[${index}].desc`, docsRoot)
11057
- };
11058
- });
11059
- }
11060
- for (const group of TASK_TYPE_GROUPS){
11061
- const seenInGroup = new Set();
11062
- for (const item of taskTypes[group]){
11063
- if (seenInGroup.has(item.name)) fail(docsRoot, `taskTypes.${group} 内任务类型重复:${item.name}`);
11064
- seenInGroup.add(item.name);
11065
- }
11066
- }
11067
- const rolesRaw = requireRecord(data.roles, 'roles', docsRoot);
11068
- const roles = {};
11069
- for (const [role, value] of Object.entries(rolesRaw)){
11070
- const where = `roles.${role}`;
11071
- const entry = requireRecord(value, where, docsRoot);
11072
- const groups = requireStringArray(entry.taskTypeGroups, `${where}.taskTypeGroups`, docsRoot);
11073
- for (const group of groups)if (!TASK_TYPE_GROUPS.includes(group)) fail(docsRoot, `${where}.taskTypeGroups 引用了未知分组:${group}`);
11074
- roles[role] = {
11075
- scope: requireString(entry.scope, `${where}.scope`, docsRoot),
11076
- scopeRequires: requireStringArray(entry.scopeRequires, `${where}.scopeRequires`, docsRoot),
11077
- detailFields: void 0 === entry.detailFields ? [] : requireStringArray(entry.detailFields, `${where}.detailFields`, docsRoot),
11078
- taskTypeGroups: groups
11079
- };
11080
- }
11081
- if (0 === Object.keys(roles).length) fail(docsRoot, 'roles 不能为空');
11082
- const scopeEnumRaw = taskTable.scopeEnum;
11083
- const scopeEnum = requireStringArray(scopeEnumRaw, 'taskTable.scopeEnum', docsRoot);
11084
- for (const value of scopeEnum){
11085
- const matched = Object.entries(roles).filter(([, config])=>config.scope === value);
11086
- if (1 !== matched.length) fail(docsRoot, `所属端「${value}」需唯一对应一个 roles.* 角色,实际匹配:${matched.length} 个`);
11087
- const owner = matched[0];
11088
- if (void 0 === owner || 0 === owner[1].detailFields.length) fail(docsRoot, `roles.${owner?.[0] ?? '?'} 负责所属端「${value}」,必须声明 detailFields`);
11089
- }
11090
- const requirementHeaders = requireStringArray(requirementTable.headers, 'requirementTable.headers', docsRoot);
11091
- const taskHeaders = requireStringArray(taskTable.headers, 'taskTable.headers', docsRoot);
11146
+ const requirementTableColumns = readColumns(requirementTable, REQUIRED_REQUIREMENT_KEYS, 'requirementTable', docsRoot);
11147
+ const taskTableColumns = readColumns(taskTable, REQUIRED_TASK_KEYS, 'taskTable', docsRoot);
11148
+ const progressRange = readProgressRange(requirementTable, docsRoot);
11149
+ const enumItems = readEnums(data.enums, docsRoot);
11150
+ const taskTypeItems = readTaskTypes(data.taskTypes, docsRoot);
11151
+ const roles = readRoles(data.roles, taskTableColumns.keys, docsRoot);
11152
+ const taskScopeEnum = derivedScopeEnum(roles, docsRoot);
11092
11153
  return {
11093
11154
  version,
11094
11155
  sections: requireStringArray(data.sections, 'sections', docsRoot),
11095
- iterationFields: requireStringArray(data.iterationFields, 'iterationFields', docsRoot),
11096
- requirementHeaders,
11097
- requirementKeys: readKeys(requirementTable, requirementHeaders, REQUIRED_REQUIREMENT_KEYS, 'requirementTable'),
11156
+ iterationFields: readIterationFields(data.iterationFields, docsRoot).map((item)=>item.label),
11157
+ iterationFieldItems: readIterationFields(data.iterationFields, docsRoot),
11158
+ requirementColumns: requirementTableColumns.columns,
11159
+ requirementHeaders: requirementTableColumns.headers,
11160
+ requirementKeys: requirementTableColumns.keys,
11098
11161
  requirementIdPattern: requireString(requirementTable.idPattern, 'requirementTable.idPattern', docsRoot),
11099
11162
  progressRange,
11100
- taskHeaders,
11101
- taskKeys: readKeys(taskTable, taskHeaders, REQUIRED_TASK_KEYS, 'taskTable'),
11163
+ taskColumns: taskTableColumns.columns,
11164
+ taskHeaders: taskTableColumns.headers,
11165
+ taskKeys: taskTableColumns.keys,
11102
11166
  taskIdPattern: requireString(taskTable.idPattern, 'taskTable.idPattern', docsRoot),
11103
- taskScopeEnum: requireStringArray(taskTable.scopeEnum, 'taskTable.scopeEnum', docsRoot),
11167
+ taskScopeEnum,
11104
11168
  enums: {
11105
- requirementStatus: requireStringArray(enumsRaw.requirementStatus, 'enums.requirementStatus', docsRoot),
11106
- taskStatus: requireStringArray(enumsRaw.taskStatus, 'enums.taskStatus', docsRoot),
11107
- selfTest: requireStringArray(enumsRaw.selfTest, 'enums.selfTest', docsRoot),
11108
- acceptance: requireStringArray(enumsRaw.acceptance, 'enums.acceptance', docsRoot)
11169
+ requirementStatus: enumValues(enumItems, 'requirementStatus', docsRoot),
11170
+ taskStatus: enumValues(enumItems, 'taskStatus', docsRoot),
11171
+ selfTest: enumValues(enumItems, 'selfTest', docsRoot),
11172
+ acceptance: enumValues(enumItems, 'acceptance', docsRoot)
11173
+ },
11174
+ enumItems,
11175
+ taskTypes: {
11176
+ frontend: taskTypeItems.filter((item)=>item.sides.includes('frontend')),
11177
+ backend: taskTypeItems.filter((item)=>item.sides.includes('backend'))
11109
11178
  },
11110
- taskTypes,
11179
+ taskTypeItems,
11111
11180
  updatedAtFormat: requireString(data.updatedAtFormat, 'updatedAtFormat', docsRoot),
11112
11181
  roles
11113
11182
  };
11114
11183
  }
11184
+ function readColumns(table, requiredKeys, where, docsRoot) {
11185
+ const raw = table.columns;
11186
+ if (!Array.isArray(raw) || 0 === raw.length) fail(docsRoot, `${where}.columns 必须是非空数组`);
11187
+ const columns = [];
11188
+ const seenKeys = new Set();
11189
+ const seenLabels = new Set();
11190
+ raw.forEach((item, index)=>{
11191
+ const at = `${where}.columns[${index}]`;
11192
+ const entry = requireRecord(item, at, docsRoot);
11193
+ const key = requireString(entry.key, `${at}.key`, docsRoot);
11194
+ const label = requireString(entry.label, `${at}.label`, docsRoot);
11195
+ if (seenKeys.has(key)) fail(docsRoot, `${where}.columns 内 key 重复:${key}`);
11196
+ if (seenLabels.has(label)) fail(docsRoot, `${where}.columns 内 label 重复:${label}`);
11197
+ seenKeys.add(key);
11198
+ seenLabels.add(label);
11199
+ if (void 0 !== entry.required && 'boolean' != typeof entry.required) fail(docsRoot, `${at}.required 必须是布尔值`);
11200
+ if (void 0 !== entry.enum) {
11201
+ const ref = requireString(entry.enum, `${at}.enum`, docsRoot);
11202
+ const available = [
11203
+ ...REQUIRED_ENUMS,
11204
+ ...BUILTIN_ENUM_REFS
11205
+ ];
11206
+ if (!available.includes(ref)) fail(docsRoot, `${at}.enum 引用了未知枚举:${ref}(可选:${available.join('、')})`);
11207
+ }
11208
+ if (void 0 !== entry.format) {
11209
+ const format = requireString(entry.format, `${at}.format`, docsRoot);
11210
+ if (!ALLOWED_FORMATS.includes(format)) fail(docsRoot, `${at}.format 必须是 ${ALLOWED_FORMATS.join(' / ')}`);
11211
+ }
11212
+ columns.push({
11213
+ key,
11214
+ label,
11215
+ required: true === entry.required,
11216
+ enum: void 0 === entry.enum ? void 0 : String(entry.enum),
11217
+ format: void 0 === entry.format ? void 0 : String(entry.format),
11218
+ ui: readColumnUi(entry.ui, `${at}.ui`, docsRoot)
11219
+ });
11220
+ });
11221
+ const missing = requiredKeys.filter((key)=>!seenKeys.has(key));
11222
+ if (missing.length > 0) fail(docsRoot, `${where}.columns 缺少工具依赖的列语义:${missing.join('、')}(新增列可自由命名,但这几项语义必须保留)`);
11223
+ return {
11224
+ columns,
11225
+ headers: columns.map((column)=>column.label),
11226
+ keys: Object.fromEntries(columns.map((column)=>[
11227
+ column.key,
11228
+ column.label
11229
+ ]))
11230
+ };
11231
+ }
11232
+ function readColumnUi(value, where, docsRoot) {
11233
+ if (void 0 === value) return {};
11234
+ const entry = requireRecord(value, where, docsRoot);
11235
+ const ui = {};
11236
+ for (const [key, raw] of Object.entries(entry))if ('board' === key || 'editable' === key) {
11237
+ if ('boolean' != typeof raw) fail(docsRoot, `${where}.${key} 必须是布尔值`);
11238
+ ui[key] = raw;
11239
+ } else if ('width' === key) {
11240
+ if ('number' != typeof raw || !Number.isInteger(raw) || raw <= 0) fail(docsRoot, `${where}.width 必须是正整数`);
11241
+ ui.width = raw;
11242
+ } else fail(docsRoot, `${where} 含未知属性:${key}(可选:board / width / editable)`);
11243
+ return ui;
11244
+ }
11245
+ function readProgressRange(table, docsRoot) {
11246
+ const raw = table.progressRange;
11247
+ if (void 0 === raw) return [
11248
+ 0,
11249
+ 100
11250
+ ];
11251
+ if (!Array.isArray(raw) || 2 !== raw.length) fail(docsRoot, 'requirementTable.progressRange 必须是 [最小值, 最大值]');
11252
+ const [low, high] = raw;
11253
+ if ('number' != typeof low || 'number' != typeof high) fail(docsRoot, 'requirementTable.progressRange 必须是数字');
11254
+ return [
11255
+ low,
11256
+ high
11257
+ ];
11258
+ }
11259
+ function readIterationFields(value, docsRoot) {
11260
+ if (!Array.isArray(value) || 0 === value.length) fail(docsRoot, 'iterationFields 必须是非空数组');
11261
+ const seenKeys = new Set();
11262
+ const seenLabels = new Set();
11263
+ return value.map((item, index)=>{
11264
+ const where = `iterationFields[${index}]`;
11265
+ const entry = requireRecord(item, where, docsRoot);
11266
+ const key = requireString(entry.key, `${where}.key`, docsRoot);
11267
+ const label = requireString(entry.label, `${where}.label`, docsRoot);
11268
+ if (seenKeys.has(key)) fail(docsRoot, `iterationFields 内 key 重复:${key}`);
11269
+ if (seenLabels.has(label)) fail(docsRoot, `iterationFields 内 label 重复:${label}`);
11270
+ seenKeys.add(key);
11271
+ seenLabels.add(label);
11272
+ if (void 0 !== entry.required && 'boolean' != typeof entry.required) fail(docsRoot, `${where}.required 必须是布尔值`);
11273
+ return {
11274
+ key,
11275
+ label,
11276
+ required: false !== entry.required,
11277
+ placeholder: void 0 === entry.placeholder ? void 0 : requireString(entry.placeholder, `${where}.placeholder`, docsRoot)
11278
+ };
11279
+ });
11280
+ }
11281
+ function readEnums(value, docsRoot) {
11282
+ const record = requireRecord(value, 'enums', docsRoot);
11283
+ return REQUIRED_ENUMS.map((key)=>{
11284
+ const entry = requireRecord(record[key], `enums.${key}`, docsRoot);
11285
+ const values = requireStringArray(entry.values, `enums.${key}.values`, docsRoot);
11286
+ return {
11287
+ key,
11288
+ label: requireString(entry.label, `enums.${key}.label`, docsRoot),
11289
+ values,
11290
+ desc: requireString(entry.desc, `enums.${key}.desc`, docsRoot),
11291
+ display: void 0 === entry.display ? void 0 : requireString(entry.display, `enums.${key}.display`, docsRoot)
11292
+ };
11293
+ });
11294
+ }
11295
+ function enumValues(items, key, docsRoot) {
11296
+ const found = items.find((item)=>item.key === key);
11297
+ if (void 0 === found) fail(docsRoot, `enums 缺少 ${key}`);
11298
+ return found.values;
11299
+ }
11300
+ function readTaskTypes(value, docsRoot) {
11301
+ if (!Array.isArray(value) || 0 === value.length) fail(docsRoot, 'taskTypes 必须是非空数组');
11302
+ const seen = new Set();
11303
+ return value.map((item, index)=>{
11304
+ const where = `taskTypes[${index}]`;
11305
+ const entry = requireRecord(item, where, docsRoot);
11306
+ const name = requireString(entry.name, `${where}.name`, docsRoot);
11307
+ if (seen.has(name)) fail(docsRoot, `taskTypes 内任务类型重复:${name}`);
11308
+ seen.add(name);
11309
+ const sides = requireStringArray(entry.sides, `${where}.sides`, docsRoot);
11310
+ for (const side of sides)if (!TASK_TYPE_GROUPS.includes(side)) fail(docsRoot, `${where}.sides 含未知分组:${side}(可选:${TASK_TYPE_GROUPS.join('、')})`);
11311
+ return {
11312
+ name,
11313
+ desc: requireString(entry.desc, `${where}.desc`, docsRoot),
11314
+ sides: sides
11315
+ };
11316
+ });
11317
+ }
11318
+ function roleOfScope(schema, scope) {
11319
+ for (const [role, config] of Object.entries(schema.roles))if (config.scope === scope) return role;
11320
+ return null;
11321
+ }
11322
+ function scopeRequiresOf(scope) {
11323
+ return scope.split(SCOPE_SEPARATOR).map((part)=>part.trim()).filter((part)=>part.length > 0);
11324
+ }
11325
+ function scopeOwners(roles) {
11326
+ const owners = {};
11327
+ for (const [role, config] of Object.entries(roles))if (0 !== config.detailFields.length) for (const scope of scopeRequiresOf(config.scope))owners[scope] = role;
11328
+ return owners;
11329
+ }
11330
+ function readRoles(value, taskKeys, docsRoot) {
11331
+ const record = requireRecord(value, 'roles', docsRoot);
11332
+ if (0 === Object.keys(record).length) fail(docsRoot, 'roles 不能为空');
11333
+ const partial = {};
11334
+ for (const [role, raw] of Object.entries(record)){
11335
+ const where = `roles.${role}`;
11336
+ const entry = requireRecord(raw, where, docsRoot);
11337
+ const scope = requireString(entry.scope, `${where}.scope`, docsRoot);
11338
+ const detailFields = [];
11339
+ const detailFieldItems = [];
11340
+ const mirrorFields = {};
11341
+ if (void 0 !== entry.detailFields) {
11342
+ if (!Array.isArray(entry.detailFields) || 0 === entry.detailFields.length) fail(docsRoot, `${where}.detailFields 必须是非空数组`);
11343
+ entry.detailFields.forEach((item, index)=>{
11344
+ const at = `${where}.detailFields[${index}]`;
11345
+ const field = requireRecord(item, at, docsRoot);
11346
+ const name = requireString(field.name, `${at}.name`, docsRoot);
11347
+ if (detailFields.includes(name)) fail(docsRoot, `${where}.detailFields 内字段重复:${name}`);
11348
+ detailFields.push(name);
11349
+ const decl = {
11350
+ name
11351
+ };
11352
+ const hasSource = void 0 !== field.source;
11353
+ const hasFrom = void 0 !== field.from;
11354
+ if (hasSource && hasFrom) fail(docsRoot, `${at}:source(来自任务表列)与 from(来自 plan 字段)不能同时声明`);
11355
+ if (hasSource) {
11356
+ const source = requireString(field.source, `${at}.source`, docsRoot);
11357
+ if (!source.startsWith('task.')) fail(docsRoot, `${at}.source 必须形如 task.<列语义>`);
11358
+ const semantic = source.slice(5);
11359
+ if (void 0 === taskKeys[semantic]) fail(docsRoot, `${at}.source 指向的任务列语义不存在:${semantic}`);
11360
+ const match = void 0 === field.match ? 'exact' : String(field.match);
11361
+ if ('exact' !== match && 'contains' !== match) fail(docsRoot, `${at}.match 必须是 exact / contains`);
11362
+ decl.source = semantic;
11363
+ decl.match = match;
11364
+ mirrorFields[name] = {
11365
+ source: semantic,
11366
+ match
11367
+ };
11368
+ }
11369
+ if (hasFrom) {
11370
+ const from = requireString(field.from, `${at}.from`, docsRoot);
11371
+ const planFields = PLAN_SOURCE_FIELDS;
11372
+ if (!planFields.includes(from)) fail(docsRoot, `${at}.from 必须是 ${planFields.join(' / ')} 之一`);
11373
+ const renderer = RENDERER_BY_PLAN_FIELD[from];
11374
+ if (void 0 !== field.as) {
11375
+ const declared = requireString(field.as, `${at}.as`, docsRoot);
11376
+ if (declared !== renderer) fail(docsRoot, `${at}.as 与 from 不匹配:from=${from} 只能是 ${renderer}`);
11377
+ }
11378
+ decl.from = from;
11379
+ decl.as = renderer;
11380
+ }
11381
+ if (void 0 !== field.placeholder) decl.placeholder = Array.isArray(field.placeholder) ? requireStringArray(field.placeholder, `${at}.placeholder`, docsRoot) : requireString(field.placeholder, `${at}.placeholder`, docsRoot);
11382
+ detailFieldItems.push(decl);
11383
+ });
11384
+ }
11385
+ partial[role] = {
11386
+ scope,
11387
+ scopeRequires: scopeRequiresOf(scope),
11388
+ detailFields,
11389
+ detailFieldItems,
11390
+ mirrorFields,
11391
+ taskTypeGroups: []
11392
+ };
11393
+ }
11394
+ for (const [role, config] of Object.entries(partial)){
11395
+ const sides = new Set([
11396
+ role
11397
+ ]);
11398
+ for (const scope of config.scopeRequires){
11399
+ const owner = scopeOwners(partial)[scope];
11400
+ if (void 0 !== owner) sides.add(owner);
11401
+ }
11402
+ config.taskTypeGroups = TASK_TYPE_GROUPS.filter((group)=>sides.has(group));
11403
+ }
11404
+ return partial;
11405
+ }
11406
+ function derivedScopeEnum(roles, docsRoot) {
11407
+ const values = [];
11408
+ for (const config of Object.values(roles))if (0 !== config.detailFields.length) {
11409
+ for (const scope of scopeRequiresOf(config.scope))if (!values.includes(scope)) values.push(scope);
11410
+ }
11411
+ if (0 === values.length) fail(docsRoot, '未从 roles.*.scope 派生出任何「所属端」');
11412
+ return values;
11413
+ }
11115
11414
  function loadDocSchema(docsRoot) {
11116
11415
  const target = docSchemaPath(docsRoot);
11117
11416
  let text;
@@ -11131,26 +11430,33 @@ function loadDocSchema(docsRoot) {
11131
11430
  function taskTypesOf(schema, role) {
11132
11431
  const config = schema.roles[role];
11133
11432
  if (void 0 === config) return [];
11134
- const names = [];
11135
- for (const group of config.taskTypeGroups)for (const item of schema.taskTypes[group])if (!names.includes(item.name)) names.push(item.name);
11136
- return names;
11137
- }
11138
- function roleOfScope(schema, scope) {
11139
- for (const [role, config] of Object.entries(schema.roles))if (config.scope === scope) return role;
11140
- return null;
11433
+ const sides = new Set([
11434
+ role,
11435
+ ...config.scopeRequires.map((scope)=>scopeOwners(schema.roles)[scope] ?? '')
11436
+ ]);
11437
+ return schema.taskTypeItems.filter((item)=>item.sides.some((side)=>sides.has(side))).map((item)=>item.name);
11141
11438
  }
11142
11439
  function detailFieldsOfScope(schema, scope) {
11143
11440
  const role = roleOfScope(schema, scope);
11144
11441
  if (null === role) return [];
11145
11442
  return schema.roles[role]?.detailFields ?? [];
11146
11443
  }
11444
+ function detailFieldDeclsOfScope(schema, scope) {
11445
+ const role = roleOfScope(schema, scope);
11446
+ if (null === role) return [];
11447
+ return schema.roles[role]?.detailFieldItems ?? [];
11448
+ }
11449
+ function mirrorFieldsOfScope(schema, scope) {
11450
+ const role = roleOfScope(schema, scope);
11451
+ if (null === role) return {};
11452
+ return schema.roles[role]?.mirrorFields ?? {};
11453
+ }
11147
11454
  function sideOfTypeName(schema, typeName) {
11148
- const inFront = schema.taskTypes.frontend.some((item)=>item.name === typeName);
11149
- const inBack = schema.taskTypes.backend.some((item)=>item.name === typeName);
11150
- if (inFront && inBack) return 'both';
11151
- if (inFront) return 'frontend';
11152
- if (inBack) return 'backend';
11153
- return null;
11455
+ const found = schema.taskTypeItems.find((item)=>item.name === typeName);
11456
+ if (void 0 === found) return null;
11457
+ const sides = TASK_TYPE_GROUPS.filter((group)=>found.sides.includes(group));
11458
+ if (sides.length > 1) return 'both';
11459
+ return sides[0] ?? null;
11154
11460
  }
11155
11461
  function buildRepoSideIndex(terminals) {
11156
11462
  const byName = new Map();
@@ -11281,15 +11587,13 @@ function parseDocPlan(raw, schema, role) {
11281
11587
  if (seenRequirements.has(requirement.code)) docplan_fail(`需求编号重复:${requirement.code}`);
11282
11588
  seenRequirements.add(requirement.code);
11283
11589
  }
11284
- const allowedTypes = new Set(taskTypesOf(schema, role));
11285
11590
  const scopeEnum = schema.taskScopeEnum;
11591
+ const ownedScopes = new Set(schema.roles[role]?.scopeRequires ?? scopeEnum);
11286
11592
  const tasks = raw.tasks.map((item, index)=>{
11287
11593
  const where = `tasks[${index}]`;
11288
11594
  if (!docplan_isRecord(item)) docplan_fail(`${where} 必须是对象`);
11289
11595
  const type = docplan_requireString(item.type, `${where}.type`);
11290
- if (allowedTypes.size > 0 && !allowedTypes.has(type)) docplan_fail(`${where}.type 非法:${type}(角色 ${role} 允许:${[
11291
- ...allowedTypes
11292
- ].join('、')})`);
11596
+ if (!schema.taskTypeItems.some((entry)=>entry.name === type)) docplan_fail(`${where}.type 非法:${type}(不在 schema 的任务类型定义中;当前角色可用:${taskTypesOf(schema, role).join('、')})`);
11293
11597
  const filesRaw = item.files;
11294
11598
  let files = [];
11295
11599
  if (null != filesRaw) {
@@ -11316,13 +11620,24 @@ function parseDocPlan(raw, schema, role) {
11316
11620
  };
11317
11621
  });
11318
11622
  }
11623
+ const declaredScope = optionalString(item.scope, `${where}.scope`)?.trim();
11624
+ let scope;
11625
+ if (void 0 !== declaredScope && declaredScope.length > 0) {
11626
+ if (!scopeEnum.includes(declaredScope)) docplan_fail(`${where}.scope 非法:${declaredScope}(允许值:${scopeEnum.join('、')})`);
11627
+ scope = declaredScope;
11628
+ } else {
11629
+ const side = sideOfTypeName(schema, type);
11630
+ const inferred = 'frontend' === side ? '前端' : 'backend' === side ? '后端' : void 0;
11631
+ if (void 0 === inferred) docplan_fail(`${where}.scope 必须显式指定:类型「${type}」两端都可用,无法自动判断(允许值:${scopeEnum.join('、')})`);
11632
+ scope = inferred;
11633
+ }
11319
11634
  let detailFields;
11320
11635
  if (void 0 !== item.detailFields && null !== item.detailFields) {
11321
11636
  if (!docplan_isRecord(item.detailFields)) docplan_fail(`${where}.detailFields 必须是对象`);
11322
- const allowed = new Set(schema.roles[role]?.detailFields ?? []);
11637
+ const allowed = new Set(detailFieldsOfScope(schema, scope));
11323
11638
  detailFields = {};
11324
11639
  for (const [key, value] of Object.entries(item.detailFields)){
11325
- if (allowed.size > 0 && !allowed.has(key)) docplan_fail(`${where}.detailFields 含未知字段「${key}」(角色 ${role} 允许:${[
11640
+ if (allowed.size > 0 && !allowed.has(key)) docplan_fail(`${where}.detailFields 含未知字段「${key}」(「${scope}」端允许:${[
11326
11641
  ...allowed
11327
11642
  ].join('、')};新增字段请先改 schema.json 与模板)`);
11328
11643
  if ('string' == typeof value) {
@@ -11336,20 +11651,17 @@ function parseDocPlan(raw, schema, role) {
11336
11651
  docplan_fail(`${where}.detailFields.${key} 必须是字符串或字符串数组`);
11337
11652
  }
11338
11653
  }
11339
- const declaredScope = optionalString(item.scope, `${where}.scope`)?.trim();
11340
- let scope;
11341
- if (void 0 !== declaredScope && declaredScope.length > 0) {
11342
- if (!scopeEnum.includes(declaredScope)) docplan_fail(`${where}.scope 非法:${declaredScope}(允许值:${scopeEnum.join('、')})`);
11343
- scope = declaredScope;
11344
- } else {
11345
- const side = sideOfTypeName(schema, type);
11346
- const inferred = 'frontend' === side ? '前端' : 'backend' === side ? '后端' : void 0;
11347
- if (void 0 === inferred) docplan_fail(`${where}.scope 必须显式指定:类型「${type}」两端都可用,无法自动判断(允许值:${scopeEnum.join('、')})`);
11348
- scope = inferred;
11349
- }
11350
11654
  const typeSide = sideOfTypeName(schema, type);
11351
11655
  const expectedScope = 'frontend' === typeSide ? '前端' : 'backend' === typeSide ? '后端' : void 0;
11352
11656
  if (void 0 !== expectedScope && scope !== expectedScope) docplan_fail(`${where}.type「${type}」属于${expectedScope},但 scope 填的是「${scope}」`);
11657
+ if (!ownedScopes.has(scope)) docplan_fail(`${where}:任务属于「${scope}」,但当前角色「${role}」的负责范围是${[
11658
+ ...ownedScopes
11659
+ ].join('、') || '(空)'}。\n ${scope}任务请交给负责该端的同事,或把 profile.role 改为 fullstack 后重试。`);
11660
+ const scopeRole = roleOfScope(schema, scope);
11661
+ const allowedTypes = new Set(null === scopeRole ? [] : taskTypesOf(schema, scopeRole));
11662
+ if (allowedTypes.size > 0 && !allowedTypes.has(type)) docplan_fail(`${where}.type 非法:${type}(「${scope}」端允许:${[
11663
+ ...allowedTypes
11664
+ ].join('、')})`);
11353
11665
  return {
11354
11666
  requirement: normalizeCode(docplan_requireString(item.requirement, `${where}.requirement`)),
11355
11667
  name: docplan_requireString(item.name, `${where}.name`),
@@ -11492,65 +11804,88 @@ function refreshRequirementRows(options) {
11492
11804
  changes
11493
11805
  };
11494
11806
  }
11807
+ const DETAIL_RENDERERS = {
11808
+ inline: (value)=>{
11809
+ if ('string' == typeof value) return {
11810
+ items: [
11811
+ value
11812
+ ],
11813
+ list: false
11814
+ };
11815
+ if (Array.isArray(value) && value.length > 0) return {
11816
+ items: value.map((item)=>String(item)),
11817
+ list: false
11818
+ };
11819
+ },
11820
+ list: (value)=>{
11821
+ if (!Array.isArray(value) || 0 === value.length) return;
11822
+ return {
11823
+ items: value.map((item)=>String(item)),
11824
+ list: true
11825
+ };
11826
+ },
11827
+ 'code-change-list': (value)=>{
11828
+ if (!Array.isArray(value) || 0 === value.length) return;
11829
+ const items = value.map((entry)=>entry).filter((entry)=>'string' == typeof entry.path && entry.path.length > 0).map((entry)=>`\`${String(entry.path)}\`(${String(entry.change ?? '')})`);
11830
+ return 0 === items.length ? void 0 : {
11831
+ items,
11832
+ list: true
11833
+ };
11834
+ },
11835
+ 'command-result-list': (value)=>{
11836
+ if (!Array.isArray(value) || 0 === value.length) return;
11837
+ const items = value.map((entry)=>entry).filter((entry)=>'string' == typeof entry.cmd && entry.cmd.length > 0).map((entry)=>`\`${String(entry.cmd)}\`:${String(entry.result ?? '')}`);
11838
+ return 0 === items.length ? void 0 : {
11839
+ items,
11840
+ list: true
11841
+ };
11842
+ }
11843
+ };
11495
11844
  function renderDetail(options) {
11496
11845
  const { taskId, task, requirement } = options;
11497
11846
  const builtin = new Map();
11498
- builtin.set('任务状态', {
11499
- items: [
11500
- PENDING_STATUS
11501
- ],
11502
- list: false
11503
- });
11504
- builtin.set('自测状态', {
11505
- items: [
11506
- PENDING_SELF_TEST
11507
- ],
11508
- list: false
11509
- });
11510
- builtin.set('人工验收', {
11511
- items: [
11512
- PENDING_ACCEPTANCE
11513
- ],
11514
- list: false
11515
- });
11516
- builtin.set('所属需求', {
11517
- items: [
11518
- `${requirement.code} ${requirement.name}`
11519
- ],
11520
- list: false
11521
- });
11522
- builtin.set('任务类型', {
11523
- items: [
11524
- task.type
11525
- ],
11526
- list: false
11527
- });
11528
- builtin.set('核心文件清单', {
11529
- items: (task.files ?? []).map((file)=>`\`${file.path}\`(${file.change})`),
11530
- list: true
11531
- });
11532
- builtin.set('详细实现方案', {
11533
- items: task.plan ?? [],
11534
- list: true
11535
- });
11536
- builtin.set('AI 单测与自检证据', {
11537
- items: (task.selfTest ?? []).map((item)=>`\`${item.cmd}\`:${item.result}`),
11538
- list: true
11539
- });
11540
- builtin.set('自测形式', {
11541
- items: task.testForms ?? [],
11542
- list: true
11543
- });
11544
- builtin.set('QA 历史功能影响范围 (Regression Scope)', {
11545
- items: task.regression ?? [],
11546
- list: true
11547
- });
11548
- builtin.set('待联调/遗留事项', {
11549
- items: [
11550
- task.notes ?? '无'
11551
- ],
11552
- list: false
11553
- });
11847
+ const mirrorInitial = (source)=>{
11848
+ if ('status' === source) return {
11849
+ items: [
11850
+ PENDING_STATUS
11851
+ ],
11852
+ list: false
11853
+ };
11854
+ if ('selfTest' === source) return {
11855
+ items: [
11856
+ PENDING_SELF_TEST
11857
+ ],
11858
+ list: false
11859
+ };
11860
+ if ('acceptance' === source) return {
11861
+ items: [
11862
+ PENDING_ACCEPTANCE
11863
+ ],
11864
+ list: false
11865
+ };
11866
+ if ('requirement' === source) return {
11867
+ items: [
11868
+ `${requirement.code} ${requirement.name}`
11869
+ ],
11870
+ list: false
11871
+ };
11872
+ if ('type' === source) return {
11873
+ items: [
11874
+ task.type
11875
+ ],
11876
+ list: false
11877
+ };
11878
+ };
11879
+ for (const [field, mirror] of Object.entries(mirrorFieldsOfScope(options.schema, task.scope))){
11880
+ const value = mirrorInitial(mirror.source);
11881
+ if (void 0 !== value) builtin.set(field, value);
11882
+ }
11883
+ for (const decl of detailFieldDeclsOfScope(options.schema, task.scope)){
11884
+ if (void 0 === decl.from) continue;
11885
+ const renderer = DETAIL_RENDERERS[decl.as ?? 'inline'];
11886
+ const value = renderer(task[decl.from]);
11887
+ if (void 0 !== value) builtin.set(decl.name, value);
11888
+ }
11554
11889
  const lines = [
11555
11890
  `### [${taskId}] ${task.name}`,
11556
11891
  ''
@@ -11564,7 +11899,11 @@ function renderDetail(options) {
11564
11899
  list: Array.isArray(custom)
11565
11900
  });
11566
11901
  if (void 0 === value) {
11567
- lines.push(`- **${field}**:<待补充>`);
11902
+ const decl = detailFieldDeclsOfScope(options.schema, task.scope).find((item)=>item.name === field);
11903
+ if (decl?.as !== void 0 && 'inline' !== decl.as) {
11904
+ lines.push(`- **${field}**:`);
11905
+ lines.push(' - <待补充>');
11906
+ } else lines.push(`- **${field}**:<待补充>`);
11568
11907
  continue;
11569
11908
  }
11570
11909
  if (!value.list && 1 === value.items.length) {
@@ -11643,7 +11982,7 @@ function buildSkeleton(options) {
11643
11982
  lines.push(docrender_separator(2));
11644
11983
  for (const field of schema.iterationFields){
11645
11984
  const provided = plan.iteration[field];
11646
- const fallback = '负责人' === field ? developer : '负责范围' === field ? schema.roles[role]?.scope ?? '' : '';
11985
+ const fallback = '负责人' === field ? developer : '负责范围' === field ? role : '';
11647
11986
  lines.push(joinRow([
11648
11987
  field,
11649
11988
  provided ?? fallback
@@ -12146,6 +12485,19 @@ function isGitAvailable() {
12146
12485
  return false;
12147
12486
  }
12148
12487
  }
12488
+ function docViewMeta(schema) {
12489
+ return {
12490
+ requirementColumns: schema.requirementColumns,
12491
+ taskColumns: schema.taskColumns,
12492
+ enums: {
12493
+ ...schema.enums
12494
+ },
12495
+ enumLabels: Object.fromEntries(schema.enumItems.map((item)=>[
12496
+ item.key,
12497
+ item.display ?? item.values.join("、")
12498
+ ]))
12499
+ };
12500
+ }
12149
12501
  function normalizeSelfTest(value) {
12150
12502
  const text = value.trim();
12151
12503
  if (0 === text.length) return "未执行";
@@ -12188,9 +12540,10 @@ function joinWithin(root, ...segments) {
12188
12540
  }
12189
12541
  function inferRole(markdown) {
12190
12542
  const match = /\|\s*负责范围\s*\|\s*([^|]*)\|/.exec(markdown);
12191
- const scope = match?.[1]?.trim() ?? "";
12192
- const hasFrontend = scope.includes("前端");
12193
- const hasBackend = scope.includes("后端");
12543
+ const scope = (match?.[1] ?? "").trim().toLowerCase();
12544
+ if (scope.includes("fullstack")) return "fullstack";
12545
+ const hasFrontend = scope.includes("frontend") || scope.includes("前端");
12546
+ const hasBackend = scope.includes("backend") || scope.includes("后端");
12194
12547
  if (hasFrontend && hasBackend) return "fullstack";
12195
12548
  if (hasBackend) return "backend";
12196
12549
  return "frontend";
@@ -12347,7 +12700,7 @@ function coerceInfo(value) {
12347
12700
  for (const [key, item] of Object.entries(value))if ("string" == typeof item) info[key] = item;
12348
12701
  return info;
12349
12702
  }
12350
- function coercePayload(raw) {
12703
+ function coercePayload(raw, schema) {
12351
12704
  if (!utils_isRecord(raw)) return null;
12352
12705
  const stats = utils_isRecord(raw["stats"]) ? raw["stats"] : {};
12353
12706
  const requirements = Array.isArray(raw["requirements"]) ? raw["requirements"].map(coerceRequirement).filter((item)=>null !== item) : [];
@@ -12357,6 +12710,7 @@ function coercePayload(raw) {
12357
12710
  const asNumber = (value, fallback)=>"number" == typeof value ? value : fallback;
12358
12711
  return {
12359
12712
  valid: true === raw["valid"],
12713
+ view: docViewMeta(schema),
12360
12714
  iterationInfo: coerceInfo(raw["iterationInfo"]),
12361
12715
  stats: {
12362
12716
  requirements: asNumber(stats["requirements"], requirements.length),
@@ -12423,7 +12777,7 @@ function runValidator(input) {
12423
12777
  "pipe"
12424
12778
  ]
12425
12779
  });
12426
- const parsed = coercePayload(JSON.parse(stdout));
12780
+ const parsed = coercePayload(JSON.parse(stdout), input.schema);
12427
12781
  if (null !== parsed) return {
12428
12782
  payload: parsed,
12429
12783
  error: null
@@ -12432,7 +12786,7 @@ function runValidator(input) {
12432
12786
  const failure = error;
12433
12787
  const stdout = failure.stdout;
12434
12788
  if ("string" == typeof stdout && stdout.trim().length > 0) try {
12435
- const parsed = coercePayload(JSON.parse(stdout));
12789
+ const parsed = coercePayload(JSON.parse(stdout), input.schema);
12436
12790
  if (null !== parsed) return {
12437
12791
  payload: parsed,
12438
12792
  error: null
@@ -12565,6 +12919,7 @@ function parseMarkdownDoc(markdown, schema) {
12565
12919
  }
12566
12920
  return {
12567
12921
  valid: false,
12922
+ view: docViewMeta(schema),
12568
12923
  iterationInfo,
12569
12924
  stats: {
12570
12925
  requirements: requirements.length,
@@ -12614,6 +12969,7 @@ function readIterationDoc(layout, iteration, developer, source = "local", preset
12614
12969
  const exported = exportRemoteDoc(docsRoot, ref, resolved.year, safeIteration, safeDeveloper, layout.iterationsRoot);
12615
12970
  const roleInferred = inferRole(exported.markdown);
12616
12971
  const scripted = runValidator({
12972
+ schema: loadDocSchema(exported.dir),
12617
12973
  docsRoot: exported.dir,
12618
12974
  scriptPath: exported.scriptPath,
12619
12975
  iteration: safeIteration,
@@ -12644,6 +13000,7 @@ function readIterationDoc(layout, iteration, developer, source = "local", preset
12644
13000
  const markdown = readMarkdown(file);
12645
13001
  const roleInferred = inferRole(markdown);
12646
13002
  const scripted = runValidator({
13003
+ schema: loadDocSchema(docsRoot),
12647
13004
  docsRoot,
12648
13005
  scriptPath: external_node_path_join(docsRoot, "scripts", "validate_task_doc.py"),
12649
13006
  iteration: resolved.relPath,
@@ -12872,7 +13229,7 @@ function commitInDocsRepo(docsRoot, file, message, push) {
12872
13229
  realFile = realpathSync(item);
12873
13230
  } catch {}
12874
13231
  const relativePath = external_node_path_relative(realRoot, realFile);
12875
- if (relativePath.startsWith('..') || isAbsolute(relativePath)) return {
13232
+ if (relativePath.startsWith('..') || external_node_path_isAbsolute(relativePath)) return {
12876
13233
  committed: false,
12877
13234
  pushed: false,
12878
13235
  message: '目标文件不在文档仓库内,已跳过提交'
@@ -13258,11 +13615,16 @@ function commit(context, lines, changes, message, iteration, developer, action,
13258
13615
  function normalizeDetailField(name) {
13259
13616
  return name.replace(/[((][^))]*[))]/g, '').replace(/\s+/g, '').trim();
13260
13617
  }
13261
- const DETAIL_FIELDS_LOCKED = new Set([
13262
- '任务状态',
13263
- '人工验收',
13264
- '自测状态'
13618
+ const LOCKED_MIRROR_SOURCES = new Set([
13619
+ 'status',
13620
+ 'selfTest',
13621
+ 'acceptance'
13265
13622
  ]);
13623
+ function lockedDetailFields(schema, scope) {
13624
+ const locked = new Set();
13625
+ for (const [field, mirror] of Object.entries(mirrorFieldsOfScope(schema, scope)))if (LOCKED_MIRROR_SOURCES.has(mirror.source)) locked.add(field);
13626
+ return locked;
13627
+ }
13266
13628
  function readDetailField(lines, taskId, field) {
13267
13629
  const headingIndex = lines.findIndex((line)=>line.trim().startsWith(`### [${taskId}]`));
13268
13630
  if (headingIndex < 0) return null;
@@ -13317,7 +13679,7 @@ function applyTaskDetail(options) {
13317
13679
  for (const update of options.updates){
13318
13680
  const fieldName = allowed.get(normalizeDetailField(update.field));
13319
13681
  if (void 0 === fieldName) throw new errors_CliError(`字段「${update.field}」不可编辑(可改:${allowedFields.join(' / ')})`, errors_EXIT.USAGE);
13320
- if (DETAIL_FIELDS_LOCKED.has(fieldName)) throw new errors_CliError(`字段「${fieldName}」由状态流转命令维护,请使用 task start/submit/accept/reject 或 task selftest`, errors_EXIT.USAGE);
13682
+ if (lockedDetailFields(schema, scope).has(fieldName)) throw new errors_CliError(`字段「${fieldName}」由状态流转命令维护,请使用 task start/submit/accept/reject 或 task selftest`, errors_EXIT.USAGE);
13321
13683
  const parsed = readDetailField(lines, options.taskId, fieldName);
13322
13684
  if (null === parsed) throw new errors_CliError(`任务 ${options.taskId} 的详情区块缺少字段「${fieldName}」`, errors_EXIT.INVALID);
13323
13685
  const incoming = update.value.split('\n').map((item)=>item.trim()).filter((item)=>item.length > 0);
@@ -13669,28 +14031,12 @@ function availableActions(options) {
13669
14031
  list.push({
13670
14032
  action: 'reject',
13671
14033
  enabled: true,
13672
- reason: ''
13673
- });
13674
- }
13675
- result[row.taskId] = list;
13676
- }
13677
- return result;
13678
- }
13679
- const SYNC_DIRS = new Set([
13680
- "scripts",
13681
- 'skills',
13682
- 'docs',
13683
- '_prd',
13684
- 'node_modules'
13685
- ]);
13686
- function doc_migrate_listIterations(docsRoot) {
13687
- return external_node_fs_readdirSync(docsRoot).filter((name)=>!name.startsWith('.') && !SYNC_DIRS.has(name)).filter((name)=>{
13688
- try {
13689
- return statSync(external_node_path_join(docsRoot, name)).isDirectory();
13690
- } catch {
13691
- return false;
14034
+ reason: ''
14035
+ });
13692
14036
  }
13693
- });
14037
+ result[row.taskId] = list;
14038
+ }
14039
+ return result;
13694
14040
  }
13695
14041
  function doc_migrate_splitRow(line) {
13696
14042
  const trimmed = line.trim();
@@ -13704,6 +14050,57 @@ function doc_migrate_joinRow(cells) {
13704
14050
  function isSeparator(cells) {
13705
14051
  return cells.every((cell)=>/^:?-{2,}:?$/.test(cell));
13706
14052
  }
14053
+ function renameTaskColumns(options) {
14054
+ const { schema } = options;
14055
+ const table = locateTaskTable(options.lines, schema);
14056
+ if (null === table) return {
14057
+ lines: options.lines,
14058
+ renamed: []
14059
+ };
14060
+ const headerIndex = options.lines.findIndex((line, index)=>index > table.start && index < table.end && null !== doc_migrate_splitRow(line));
14061
+ if (headerIndex < 0) return {
14062
+ lines: options.lines,
14063
+ renamed: []
14064
+ };
14065
+ const header = doc_migrate_splitRow(options.lines[headerIndex] ?? '') ?? [];
14066
+ const wanted = new Set(schema.taskHeaders);
14067
+ const unknown = header.filter((name)=>name.length > 0 && !wanted.has(name));
14068
+ const missing = schema.taskHeaders.filter((name)=>!header.includes(name));
14069
+ if (0 === unknown.length || 0 === missing.length) return {
14070
+ lines: options.lines,
14071
+ renamed: []
14072
+ };
14073
+ const renames = new Map(options.renames);
14074
+ if (0 === renames.size) {
14075
+ if (unknown.length !== missing.length) throw new errors_CliError(`任务表有 ${unknown.length} 列不在 schema 中(${unknown.join('、')}),但有 ${missing.length} 列缺失(${missing.join('、')}),无法自动对应。\n请用 --rename 旧列名=新列名 明确指定,例如:\n ylcwf doc migrate --rename "${unknown[0] ?? '旧列名'}=${missing[0] ?? '新列名'}"`, errors_EXIT.USAGE);
14076
+ unknown.forEach((name, index)=>{
14077
+ const target = missing[index];
14078
+ if (void 0 !== target) renames.set(name, target);
14079
+ });
14080
+ }
14081
+ const renamed = [];
14082
+ const nextHeader = header.map((name)=>{
14083
+ const target = renames.get(name);
14084
+ if (void 0 === target) return name;
14085
+ renamed.push([
14086
+ name,
14087
+ target
14088
+ ]);
14089
+ return target;
14090
+ });
14091
+ if (0 === renamed.length) return {
14092
+ lines: options.lines,
14093
+ renamed: []
14094
+ };
14095
+ const lines = [
14096
+ ...options.lines
14097
+ ];
14098
+ lines[headerIndex] = doc_migrate_joinRow(nextHeader);
14099
+ return {
14100
+ lines,
14101
+ renamed
14102
+ };
14103
+ }
13707
14104
  function locateTaskTable(lines, schema) {
13708
14105
  const heading = `## ${schema.sections[2] ?? '三、任务清单'}`;
13709
14106
  const sectionStart = lines.findIndex((line)=>line.trim() === heading);
@@ -13763,9 +14160,12 @@ function migrateTaskTable(options) {
13763
14160
  }
13764
14161
  const unresolved = [];
13765
14162
  let added = 0;
13766
- const idIndex = header.indexOf('任务编号');
13767
- const typeIndex = header.indexOf('任务类型');
13768
- const terminalIndex = header.indexOf('执行终端');
14163
+ const labelOf = (semantic)=>schema.taskKeys[semantic] ?? '';
14164
+ const indexOf = (semantic)=>header.indexOf(labelOf(semantic));
14165
+ const idIndex = indexOf('id');
14166
+ const typeIndex = indexOf('type');
14167
+ const terminalIndex = indexOf('terminal');
14168
+ const scopeLabel = labelOf('scope');
13769
14169
  for(let index = headerIndex + 2; index < table.end; index += 1){
13770
14170
  const cells = doc_migrate_splitRow(options.lines[index] ?? '');
13771
14171
  if (null === cells || isSeparator(cells)) continue;
@@ -13773,7 +14173,7 @@ function migrateTaskTable(options) {
13773
14173
  header.forEach((name, position)=>{
13774
14174
  record[name] = cells[position] ?? '';
13775
14175
  });
13776
- for (const name of missing)if ('所属端' === name) {
14176
+ for (const name of missing)if (name === scopeLabel) {
13777
14177
  const taskId = cells[idIndex >= 0 ? idIndex : 0] ?? '';
13778
14178
  const type = cells[typeIndex >= 0 ? typeIndex : 0] ?? '';
13779
14179
  const terminal = cells[terminalIndex >= 0 ? terminalIndex : 0] ?? '';
@@ -13834,6 +14234,52 @@ function fieldSpans(lines, block) {
13834
14234
  }
13835
14235
  return spans;
13836
14236
  }
14237
+ function reorderDetailFields(options) {
14238
+ const blocks = locateDetailBlocks(options.lines, options.schema);
14239
+ let lines = [
14240
+ ...options.lines
14241
+ ];
14242
+ let reordered = 0;
14243
+ for (const block of [
14244
+ ...blocks
14245
+ ].reverse()){
14246
+ const spans = fieldSpans(lines, block);
14247
+ if (spans.length < 2) continue;
14248
+ const first = spans[0];
14249
+ const last = spans[spans.length - 1];
14250
+ if (void 0 === first || void 0 === last) continue;
14251
+ const outside = [
14252
+ ...lines.slice(block.headingIndex + 1, first.start),
14253
+ ...lines.slice(last.end, block.endIndex)
14254
+ ];
14255
+ if (outside.some((line)=>line.trim().length > 0)) continue;
14256
+ const scope = options.scopeByTaskId.get(block.taskId) ?? '';
14257
+ const expected = detailFieldsOfScope(options.schema, scope);
14258
+ const present = spans.map((span)=>span.name);
14259
+ const known = expected.filter((name)=>present.includes(name));
14260
+ const unknown = present.filter((name)=>!expected.includes(name));
14261
+ const wanted = [
14262
+ ...known,
14263
+ ...unknown
14264
+ ];
14265
+ if (wanted.every((name, index)=>name === present[index])) continue;
14266
+ const pieces = new Map(spans.map((span)=>[
14267
+ span.name,
14268
+ lines.slice(span.start, span.end)
14269
+ ]));
14270
+ const ordered = wanted.flatMap((name)=>pieces.get(name) ?? []);
14271
+ lines = [
14272
+ ...lines.slice(0, first.start),
14273
+ ...ordered,
14274
+ ...lines.slice(last.end)
14275
+ ];
14276
+ reordered += 1;
14277
+ }
14278
+ return {
14279
+ lines,
14280
+ reordered
14281
+ };
14282
+ }
13837
14283
  function migrateDetailFields(options) {
13838
14284
  const { schema } = options;
13839
14285
  const blocks = locateDetailBlocks(options.lines, schema);
@@ -13898,39 +14344,60 @@ function runDocMigrate(options) {
13898
14344
  const schema = loadDocSchema(docsRoot);
13899
14345
  const resolveScopeFromTerminal = makeTerminalResolver(config.terminals);
13900
14346
  const iterations = options.iteration?.trim() ? [
13901
- options.iteration.trim()
13902
- ] : doc_migrate_listIterations(docsRoot);
14347
+ requireIterationDir(docsRoot, layout.iterationsRoot, options.iteration.trim())
14348
+ ] : listIterationDirs(docsRoot, layout.iterationsRoot);
14349
+ const renames = new Map();
14350
+ for (const pair of options.rename ?? []){
14351
+ const [from, to] = pair.split('=');
14352
+ if (void 0 === from || void 0 === to || '' === from.trim() || '' === to.trim()) throw new errors_CliError(`--rename 的格式应为 旧列名=新列名,收到:${pair}`, errors_EXIT.USAGE);
14353
+ renames.set(from.trim(), to.trim());
14354
+ }
13903
14355
  const results = [];
13904
14356
  const changedFiles = [];
13905
14357
  for (const iteration of iterations){
13906
- const dir = external_node_path_join(docsRoot, iteration);
14358
+ const dir = iteration.dir;
13907
14359
  if (!external_node_fs_existsSync(dir)) continue;
13908
14360
  const files = external_node_fs_readdirSync(dir).filter((name)=>name.endsWith('.md') && !name.startsWith('_'));
13909
14361
  for (const name of files){
13910
14362
  const target = external_node_path_join(dir, name);
13911
14363
  const original = readFileSync(target, 'utf8');
13912
- const tableMigrated = migrateTaskTable({
14364
+ const renamedResult = renameTaskColumns({
13913
14365
  lines: original.split('\n'),
13914
14366
  schema,
14367
+ renames
14368
+ });
14369
+ const tableMigrated = migrateTaskTable({
14370
+ lines: renamedResult.lines,
14371
+ schema,
13915
14372
  resolveScopeFromTerminal
13916
14373
  });
14374
+ for (const [from, to] of renamedResult.renamed)printLine(`${'json' === format ? '' : '· '}${iteration.relPath}/${name}:列名「${from}」→「${to}」`);
13917
14375
  const scopeByTaskId = collectTaskScopes(tableMigrated.lines, schema);
13918
14376
  const detailMigrated = migrateDetailFields({
13919
14377
  lines: tableMigrated.lines,
13920
14378
  schema,
13921
14379
  scopeByTaskId
13922
14380
  });
14381
+ const reordered = reorderDetailFields({
14382
+ lines: detailMigrated.lines,
14383
+ schema,
14384
+ scopeByTaskId
14385
+ });
13923
14386
  const addedRows = tableMigrated.added;
13924
14387
  const addedFields = detailMigrated.added;
13925
- if (0 === addedRows && 0 === addedFields) continue;
14388
+ const renamedColumns = renamedResult.renamed.length;
14389
+ const reorderedBlocks = reordered.reordered;
14390
+ if (0 === addedRows && 0 === addedFields && 0 === renamedColumns && 0 === reorderedBlocks) continue;
13926
14391
  const migrated = {
13927
- lines: detailMigrated.lines,
14392
+ lines: reordered.lines,
13928
14393
  unresolved: tableMigrated.unresolved
13929
14394
  };
13930
14395
  results.push({
13931
- file: `${iteration}/${name}`,
14396
+ file: `${iteration.relPath}/${name}`,
13932
14397
  added: addedRows,
13933
14398
  addedFields,
14399
+ renamed: renamedColumns,
14400
+ reordered: reorderedBlocks,
13934
14401
  unresolved: tableMigrated.unresolved
13935
14402
  });
13936
14403
  if (true === options.dryRun) continue;
@@ -13938,15 +14405,15 @@ function runDocMigrate(options) {
13938
14405
  changedFiles.push(target);
13939
14406
  if (migrated.unresolved.length > 0) continue;
13940
14407
  const developer = basename(name, '.md');
13941
- const outcome = validateAfterWrite(layout, iteration, developer);
14408
+ const outcome = validateAfterWrite(layout, iteration.relPath, developer);
13942
14409
  if ('passed' !== outcome.kind) {
13943
14410
  writeFileSync(target, original, 'utf8');
13944
14411
  const reason = 'violation' === outcome.kind ? outcome.message : outcome.reason;
13945
14412
  if ('unavailable' === outcome.kind && !requireValidatorScript()) {
13946
- process.stderr.write(`警告:${outcome.reason};${iteration}/${name} 未做迁移后校验(docs.validator.requireScript=false)\n`);
14413
+ process.stderr.write(`警告:${outcome.reason};${iteration.relPath}/${name} 未做迁移后校验(docs.validator.requireScript=false)\n`);
13947
14414
  continue;
13948
14415
  }
13949
- throw new errors_CliError(`迁移后校验未通过,已回滚 ${iteration}/${name}:${reason}`, errors_EXIT.INVALID);
14416
+ throw new errors_CliError(`迁移后校验未通过,已回滚 ${iteration.relPath}/${name}:${reason}`, errors_EXIT.INVALID);
13950
14417
  }
13951
14418
  }
13952
14419
  }
@@ -13964,6 +14431,8 @@ function runDocMigrate(options) {
13964
14431
  const parts = [];
13965
14432
  if (item.added > 0) parts.push(`${item.added} 行任务`);
13966
14433
  if (item.addedFields > 0) parts.push(`${item.addedFields} 个详情字段`);
14434
+ if (item.renamed > 0) parts.push(`${item.renamed} 列改名`);
14435
+ if (item.reordered > 0) parts.push(`${item.reordered} 个详情区块重排`);
13967
14436
  printLine(` · ${item.file} ${parts.join(' + ')}${extra}`);
13968
14437
  }
13969
14438
  if (totalUnresolved.length > 0) {
@@ -13988,8 +14457,8 @@ function collectTaskScopes(lines, schema) {
13988
14457
  const headerIndex = lines.findIndex((line, index)=>index > table.start && index < table.end && null !== doc_migrate_splitRow(line));
13989
14458
  if (headerIndex < 0) return result;
13990
14459
  const header = doc_migrate_splitRow(lines[headerIndex] ?? '') ?? [];
13991
- const idIndex = header.indexOf('任务编号');
13992
- const scopeIndex = header.indexOf('所属端');
14460
+ const idIndex = header.indexOf(schema.taskKeys['id'] ?? '');
14461
+ const scopeIndex = header.indexOf(schema.taskKeys['scope'] ?? '');
13993
14462
  if (idIndex < 0 || scopeIndex < 0) return result;
13994
14463
  for(let index = headerIndex + 2; index < table.end; index += 1){
13995
14464
  const cells = doc_migrate_splitRow(lines[index] ?? '');
@@ -14001,7 +14470,10 @@ function collectTaskScopes(lines, schema) {
14001
14470
  return result;
14002
14471
  }
14003
14472
  function registerDocMigrate(doc) {
14004
- doc.command('migrate').description('按 schema.json 迁移存量文档(补缺失的任务列并回填)').option('-i, --iteration <name>', '只迁移指定迭代').option('--dry-run', '只打印将要迁移的文件,不写盘').option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
14473
+ doc.command('migrate').description('按 schema.json 迁移存量文档(列改名 + 补缺失列 + 补详情字段)').option('-i, --iteration <name>', '只迁移指定迭代').option('--dry-run', '只打印将要迁移的文件,不写盘').option('--rename <old=new>', '列名对应关系(可多次),如 --rename "任务编号=任务号";不给时按缺失/多余列自动推断', (value, previous)=>[
14474
+ ...previous ?? [],
14475
+ value
14476
+ ]).option('-c, --config <path>', '指定配置文件路径').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
14005
14477
  runDocMigrate(options);
14006
14478
  });
14007
14479
  }
@@ -14043,6 +14515,10 @@ function runDocApply(options, mode = 'apply') {
14043
14515
  requirements: [],
14044
14516
  tasks: []
14045
14517
  } : parseMarkdownDoc(original, schema);
14518
+ if (null !== original) {
14519
+ const documentRole = inferRole(original);
14520
+ if (documentRole !== role) process.stderr.write(`提示:${resolvedIteration.relPath}/${developer}.md 的负责范围是「${documentRole}」,与当前角色「${role}」不一致。\n 写入后的校验按文档为准(${documentRole});要让文档与本机角色一致,请手工修改「负责范围」为 ${role}。\n`);
14521
+ }
14046
14522
  validatePlanReferences({
14047
14523
  plan,
14048
14524
  schema,
@@ -14152,7 +14628,6 @@ function runDocApply(options, mode = 'apply') {
14152
14628
  iterationsRoot: layout.iterationsRoot,
14153
14629
  iteration,
14154
14630
  developer,
14155
- role,
14156
14631
  terminals: config.terminals
14157
14632
  });
14158
14633
  const remaining = remainingReport.issues.filter((issue)=>'error' === issue.level);
@@ -14466,7 +14941,6 @@ function collectSideIssues(options) {
14466
14941
  iterationsRoot: options.iterationsRoot,
14467
14942
  iteration: options.iteration,
14468
14943
  developer: options.developer,
14469
- role: loaded.config.profile.role,
14470
14944
  terminals: loaded.config.terminals
14471
14945
  }).issues.filter((issue)=>'error' === issue.level).map((issue)=>issue.message);
14472
14946
  } catch {
@@ -15115,9 +15589,9 @@ async function fetchManifest(url) {
15115
15589
  const payload = await response.json();
15116
15590
  if ('string' != typeof payload.version || 0 === payload.version.length) return null;
15117
15591
  return {
15118
- current: "0.6.0",
15592
+ current: "0.6.2",
15119
15593
  latest: payload.version,
15120
- hasUpdate: isNewer(payload.version, "0.6.0"),
15594
+ hasUpdate: isNewer(payload.version, "0.6.2"),
15121
15595
  downloadUrl: 'string' == typeof payload.downloadUrl ? payload.downloadUrl : null,
15122
15596
  source: 'manifest',
15123
15597
  checkedAt: new Date().toISOString(),
@@ -15129,7 +15603,7 @@ async function fetchManifest(url) {
15129
15603
  }
15130
15604
  async function fetchNpm() {
15131
15605
  const base = {
15132
- current: "0.6.0",
15606
+ current: "0.6.2",
15133
15607
  latest: null,
15134
15608
  hasUpdate: false,
15135
15609
  downloadUrl: null,
@@ -15156,7 +15630,7 @@ async function fetchNpm() {
15156
15630
  return {
15157
15631
  ...base,
15158
15632
  latest,
15159
- hasUpdate: isNewer(latest, "0.6.0"),
15633
+ hasUpdate: isNewer(latest, "0.6.2"),
15160
15634
  downloadUrl: null
15161
15635
  };
15162
15636
  } catch (error) {
@@ -15247,7 +15721,7 @@ async function runUpgrade(options) {
15247
15721
  const kind = detectInstallKind();
15248
15722
  const result = await checkUpdate(true);
15249
15723
  const target = options.to?.trim() ?? result.latest;
15250
- printLine("当前版本:0.6.0");
15724
+ printLine("当前版本:0.6.2");
15251
15725
  if (null !== result.error) printLine(`版本查询失败:${result.error}`);
15252
15726
  else if (null !== result.latest) printLine(`最新版本:${result.latest}(来源:${result.source})`);
15253
15727
  if (null === target) throw new errors_CliError('无法确定目标版本,请稍后重试或用 --to 指定', errors_EXIT.NOT_FOUND);
@@ -15380,32 +15854,233 @@ function runResolve(name, options) {
15380
15854
  if ('json' === format) return void printJson({
15381
15855
  input: name,
15382
15856
  matched: true,
15383
- matchedBy: result.matchedBy,
15384
- terminal,
15385
- repos
15386
- });
15387
- printLine(`执行终端:${terminal}(匹配方式:${result.matchedBy ?? 'exact'})`);
15388
- for (const item of SIDES){
15389
- const list = repos[item];
15390
- if (0 === list.length) {
15391
- printLine(` ${item} (未配置)`);
15392
- continue;
15393
- }
15394
- list.forEach((repo, index)=>{
15395
- const prefix = 1 === list.length ? ` ${item} ` : ` ${item} ${index + 1}) `;
15396
- printLine(`${prefix}${repo.path} ${repo.exists ? '✓' : '✗'}`);
15397
- });
15398
- }
15857
+ matchedBy: result.matchedBy,
15858
+ terminal,
15859
+ repos
15860
+ });
15861
+ printLine(`执行终端:${terminal}(匹配方式:${result.matchedBy ?? 'exact'})`);
15862
+ for (const item of SIDES){
15863
+ const list = repos[item];
15864
+ if (0 === list.length) {
15865
+ printLine(` ${item} (未配置)`);
15866
+ continue;
15867
+ }
15868
+ list.forEach((repo, index)=>{
15869
+ const prefix = 1 === list.length ? ` ${item} ` : ` ${item} ${index + 1}) `;
15870
+ printLine(`${prefix}${repo.path} ${repo.exists ? '✓' : '✗'}`);
15871
+ });
15872
+ }
15873
+ }
15874
+ function registerResolve(program) {
15875
+ program.command('resolve <name>').description('把执行终端名(支持中文)解析为本地仓库路径').option('-c, --config <path>', '指定配置文件路径').option('--side <side>', '限定端口:frontend | backend').option('--field <field>', '输出字段:path | exists | terminal | repos', 'repos').option('--pick <repo>', '该端存在多个仓库时显式指定:序号(1 起)、完整路径或目录名').option('--all', '输出该端全部仓库').option('--format <format>', '输出格式:human | json', 'human').action((name, options)=>{
15876
+ runResolve(name, options);
15877
+ });
15878
+ }
15879
+ const YAPI_PLATFORM_FILE = 'yapi_platform.json';
15880
+ function yapi_error(code, message, where) {
15881
+ return void 0 === where ? {
15882
+ level: 'error',
15883
+ code,
15884
+ message
15885
+ } : {
15886
+ level: 'error',
15887
+ code,
15888
+ message,
15889
+ where
15890
+ };
15891
+ }
15892
+ function yapi_warning(code, message, where) {
15893
+ return void 0 === where ? {
15894
+ level: 'warning',
15895
+ code,
15896
+ message
15897
+ } : {
15898
+ level: 'warning',
15899
+ code,
15900
+ message,
15901
+ where
15902
+ };
15903
+ }
15904
+ function yapi_isRecord(value) {
15905
+ return 'object' == typeof value && null !== value && !Array.isArray(value);
15906
+ }
15907
+ function yapi_isPositiveInteger(value) {
15908
+ return 'number' == typeof value && Number.isInteger(value) && value > 0;
15909
+ }
15910
+ function checkYapiCatalog(raw) {
15911
+ const issues = [];
15912
+ if (!yapi_isRecord(raw)) return {
15913
+ catalog: null,
15914
+ issues: [
15915
+ yapi_error('YAPI_TYPE', 'yapi_platform.json 必须是对象')
15916
+ ]
15917
+ };
15918
+ const groups = [];
15919
+ const groupsRaw = raw['groups'];
15920
+ if (Array.isArray(groupsRaw)) groupsRaw.forEach((item, index)=>{
15921
+ const where = `groups[${index}]`;
15922
+ if (!yapi_isRecord(item)) return void issues.push(yapi_error('YAPI_GROUP_INVALID', `${where} 必须是对象`, where));
15923
+ const groupId = item['groupId'];
15924
+ const name = item['name'];
15925
+ if (!yapi_isPositiveInteger(groupId)) return void issues.push(yapi_error('YAPI_GROUP_ID_INVALID', `${where}.groupId 必须是正整数`, `${where}.groupId`));
15926
+ if ('string' != typeof name || 0 === name.trim().length) return void issues.push(yapi_error('YAPI_GROUP_NAME_INVALID', `${where}.name 不能为空`, `${where}.name`));
15927
+ groups.push({
15928
+ groupId,
15929
+ name: name.trim()
15930
+ });
15931
+ });
15932
+ else issues.push(yapi_error('YAPI_GROUPS_INVALID', 'groups 必须是数组', 'groups'));
15933
+ const knownGroupIds = new Set(groups.map((group)=>group.groupId));
15934
+ const platforms = [];
15935
+ const seenTerminals = new Map();
15936
+ const platformsRaw = raw['platforms'];
15937
+ if (Array.isArray(platformsRaw)) platformsRaw.forEach((item, index)=>{
15938
+ const where = `platforms[${index}]`;
15939
+ if (!yapi_isRecord(item)) return void issues.push(yapi_error('YAPI_PLATFORM_INVALID', `${where} 必须是对象`, where));
15940
+ const terminal = item['terminal'];
15941
+ const groupId = item['groupId'];
15942
+ const projectIds = item['projectIds'];
15943
+ const platformRaw = item['platform'];
15944
+ if ('string' != typeof terminal || 0 === terminal.trim().length) return void issues.push(yapi_error('YAPI_TERMINAL_REQUIRED', `${where}.terminal 不能为空`, `${where}.terminal`));
15945
+ if (!yapi_isPositiveInteger(groupId)) return void issues.push(yapi_error('YAPI_GROUP_ID_INVALID', `${where}.groupId 必须是正整数`, `${where}.groupId`));
15946
+ if (!knownGroupIds.has(groupId)) issues.push(yapi_error('YAPI_GROUP_UNKNOWN', `${where}.groupId ${groupId} 未在 groups 中声明`, `${where}.groupId`));
15947
+ if (!Array.isArray(projectIds) || 0 === projectIds.length) return void issues.push(yapi_error('YAPI_PROJECT_IDS_INVALID', `${where}.projectIds 必须是非空数组`, `${where}.projectIds`));
15948
+ const invalidProject = projectIds.find((id)=>!yapi_isPositiveInteger(id));
15949
+ if (void 0 !== invalidProject) return void issues.push(yapi_error('YAPI_PROJECT_IDS_INVALID', `${where}.projectIds 只能包含正整数:${String(invalidProject)}`, `${where}.projectIds`));
15950
+ const key = normalizeName(terminal);
15951
+ const duplicate = seenTerminals.get(key);
15952
+ if (void 0 !== duplicate) issues.push(yapi_error('YAPI_TERMINAL_DUPLICATED', `执行终端「${terminal.trim()}」重复声明(另见「${duplicate}」),按归一化比较重复`, `${where}.terminal`));
15953
+ else seenTerminals.set(key, terminal.trim());
15954
+ platforms.push({
15955
+ platform: 'string' == typeof platformRaw && platformRaw.trim().length > 0 ? platformRaw.trim() : null,
15956
+ terminal: terminal.trim(),
15957
+ groupId,
15958
+ projectIds: [
15959
+ ...projectIds
15960
+ ].sort((left, right)=>left - right)
15961
+ });
15962
+ });
15963
+ else issues.push(yapi_error('YAPI_PLATFORMS_INVALID', 'platforms 必须是数组', 'platforms'));
15964
+ if (issues.some((issue)=>'error' === issue.level)) return {
15965
+ catalog: null,
15966
+ issues
15967
+ };
15968
+ return {
15969
+ catalog: {
15970
+ groups,
15971
+ platforms
15972
+ },
15973
+ issues
15974
+ };
15975
+ }
15976
+ function loadYapiCatalog(docsRoot) {
15977
+ const path = external_node_path_join(docsRoot, YAPI_PLATFORM_FILE);
15978
+ let text;
15979
+ try {
15980
+ text = readFileSync(path, 'utf8');
15981
+ } catch {
15982
+ return {
15983
+ path,
15984
+ catalog: null,
15985
+ issues: []
15986
+ };
15987
+ }
15988
+ let raw;
15989
+ try {
15990
+ raw = JSON.parse(text);
15991
+ } catch (caught) {
15992
+ const detail = caught instanceof Error ? caught.message : String(caught);
15993
+ return {
15994
+ path,
15995
+ catalog: null,
15996
+ issues: [
15997
+ yapi_error('YAPI_JSON_INVALID', `${YAPI_PLATFORM_FILE} 不是合法 JSON:${detail}`)
15998
+ ]
15999
+ };
16000
+ }
16001
+ return {
16002
+ path,
16003
+ ...checkYapiCatalog(raw)
16004
+ };
16005
+ }
16006
+ function terminalNameByRepo(terminals, input) {
16007
+ const target = normalizeName(input);
16008
+ const hits = [];
16009
+ for (const [name, terminal] of Object.entries(terminals)){
16010
+ const repos = [
16011
+ ...terminal.repos.frontend,
16012
+ ...terminal.repos.backend
16013
+ ];
16014
+ if (repos.some((repo)=>normalizeName(basename(repo)) === target)) hits.push(name);
16015
+ }
16016
+ return 1 === hits.length ? hits[0] ?? null : null;
16017
+ }
16018
+ function resolveConfigTerminal(terminals, input) {
16019
+ const target = normalizeName(input);
16020
+ for (const name of Object.keys(terminals))if (normalizeName(name) === target) return {
16021
+ terminalName: name,
16022
+ matchedBy: 'terminal'
16023
+ };
16024
+ const byRepo = terminalNameByRepo(terminals, input);
16025
+ if (null !== byRepo) return {
16026
+ terminalName: byRepo,
16027
+ matchedBy: 'repo'
16028
+ };
16029
+ return {
16030
+ terminalName: null,
16031
+ matchedBy: null
16032
+ };
16033
+ }
16034
+ function describePlatform(item) {
16035
+ return null === item.platform ? item.terminal : `${item.terminal}(${item.platform})`;
16036
+ }
16037
+ function matchYapiPlatform(options) {
16038
+ const { catalog, terminals, input } = options;
16039
+ const trimmed = input.trim();
16040
+ const empty = {
16041
+ matched: false,
16042
+ terminalName: null,
16043
+ matchedBy: null,
16044
+ platform: null,
16045
+ group: null,
16046
+ candidates: catalog.platforms.map(describePlatform)
16047
+ };
16048
+ if (0 === trimmed.length) return empty;
16049
+ const resolved = resolveConfigTerminal(terminals, trimmed);
16050
+ const target = normalizeName(resolved.terminalName ?? trimmed);
16051
+ const byTerminal = catalog.platforms.filter((item)=>normalizeName(item.terminal) === target);
16052
+ if (1 === byTerminal.length && void 0 !== byTerminal[0]) return buildMatch(byTerminal[0], resolved.terminalName, resolved.matchedBy ?? 'terminal', catalog);
16053
+ if (byTerminal.length > 1) return {
16054
+ ...empty,
16055
+ terminalName: resolved.terminalName,
16056
+ candidates: byTerminal.map(describePlatform)
16057
+ };
16058
+ return {
16059
+ ...empty,
16060
+ terminalName: resolved.terminalName
16061
+ };
16062
+ }
16063
+ function buildMatch(item, terminalName, matchedBy, catalog) {
16064
+ return {
16065
+ matched: true,
16066
+ terminalName,
16067
+ matchedBy,
16068
+ platform: item,
16069
+ group: catalog.groups.find((group)=>group.groupId === item.groupId) ?? null,
16070
+ candidates: []
16071
+ };
15399
16072
  }
15400
- function registerResolve(program) {
15401
- program.command('resolve <name>').description('把执行终端名(支持中文)解析为本地仓库路径').option('-c, --config <path>', '指定配置文件路径').option('--side <side>', '限定端口:frontend | backend').option('--field <field>', '输出字段:path | exists | terminal | repos', 'repos').option('--pick <repo>', '该端存在多个仓库时显式指定:序号(1 起)、完整路径或目录名').option('--all', '输出该端全部仓库').option('--format <format>', '输出格式:human | json', 'human').action((name, options)=>{
15402
- runResolve(name, options);
15403
- });
16073
+ function checkYapiAgainstTerminalCatalog(catalog, terminalNames) {
16074
+ if (0 === terminalNames.length) return [];
16075
+ const allowed = terminalNames.map((name)=>normalizeName(name));
16076
+ const issues = [];
16077
+ for (const item of catalog.platforms)if (!allowed.includes(normalizeName(item.terminal))) issues.push(yapi_warning('YAPI_TERMINAL_NOT_IN_CATALOG', `${YAPI_PLATFORM_FILE} 中的执行终端「${item.terminal}」不在 execution_terminals.json 里;可选:${terminalNames.join('、')}(以清单为准,请改 yapi 文件)`, `platforms.${item.terminal}`));
16078
+ return issues;
15404
16079
  }
15405
16080
  function checkDocsSides(config) {
15406
16081
  const messages = [];
15407
16082
  const root = config.docs.root;
15408
- const iterationsRoot = config.docs.iterationsRoot ?? 'iterations';
16083
+ const iterationsRoot = DEFAULT_ITERATIONS_ROOT;
15409
16084
  let iterations;
15410
16085
  try {
15411
16086
  iterations = listIterationDirs(root, iterationsRoot);
@@ -15423,7 +16098,6 @@ function checkDocsSides(config) {
15423
16098
  iterationsRoot,
15424
16099
  iteration,
15425
16100
  developer: config.profile.developer,
15426
- role: config.profile.role,
15427
16101
  terminals: config.terminals
15428
16102
  });
15429
16103
  for (const issue of report.issues)messages.push({
@@ -15437,17 +16111,43 @@ function checkDocsSides(config) {
15437
16111
  } catch {}
15438
16112
  return messages;
15439
16113
  }
16114
+ function doctor_checkTerminalCatalog(config) {
16115
+ const root = config.docs.root;
16116
+ if (0 === root.trim().length) return [];
16117
+ const loaded = loadTerminalCatalog(root);
16118
+ const issues = loaded.issues.map((issue)=>({
16119
+ level: issue.level,
16120
+ message: issue.message
16121
+ }));
16122
+ const names = loaded.catalog?.terminals.map((entry)=>entry.name) ?? [];
16123
+ if (null === loaded.catalog && 0 === loaded.issues.length) {
16124
+ issues.push({
16125
+ level: 'warning',
16126
+ message: `文档仓库缺少 ${TERMINAL_CATALOG_FILE}:本次不限制执行终端名。需要统一命名为合法值请补该文件`
16127
+ });
16128
+ return issues;
16129
+ }
16130
+ const yapi = loadYapiCatalog(root);
16131
+ if (null !== yapi.catalog) issues.push(...checkYapiAgainstTerminalCatalog(yapi.catalog, names).map((issue)=>({
16132
+ level: issue.level,
16133
+ message: issue.message
16134
+ })));
16135
+ return issues;
16136
+ }
15440
16137
  function runDoctor(options) {
15441
16138
  const format = parseFormat(options.format);
15442
16139
  const loaded = config_loadConfig(options.config);
15443
16140
  if (!loaded.exists) throw new errors_CliError(`配置未初始化:${loaded.path}\n请先运行:ylcwf init`, errors_EXIT.NOT_FOUND);
15444
- const checked = checkConfig(loaded.raw, {
16141
+ const checked = checkConfigWithCatalog(loaded.raw, {
15445
16142
  checkFs: true
15446
16143
  });
15447
16144
  const errors = countIssues(checked.issues).errors;
15448
16145
  const ok = !hasError(checked.issues);
15449
16146
  const sideIssues = [];
15450
- if (true === options.docs && null !== checked.config && ok) sideIssues.push(...checkDocsSides(checked.config));
16147
+ if (true === options.docs && null !== checked.config && ok) {
16148
+ sideIssues.push(...doctor_checkTerminalCatalog(checked.config));
16149
+ sideIssues.push(...checkDocsSides(checked.config));
16150
+ }
15451
16151
  const sideErrors = sideIssues.filter((item)=>'error' === item.level).length;
15452
16152
  const allOk = ok && 0 === sideErrors;
15453
16153
  if ('json' === format) printJson({
@@ -15518,10 +16218,13 @@ function syncDocument(doc, next) {
15518
16218
  'docs',
15519
16219
  'root'
15520
16220
  ], next.docs.root);
15521
- doc.setIn([
16221
+ if (doc.hasIn([
15522
16222
  'docs',
15523
16223
  'iterationsRoot'
15524
- ], next.docs.iterationsRoot);
16224
+ ])) doc.deleteIn([
16225
+ 'docs',
16226
+ 'iterationsRoot'
16227
+ ]);
15525
16228
  for (const side of [
15526
16229
  'cli',
15527
16230
  'ui'
@@ -15551,7 +16254,11 @@ function syncDocument(doc, next) {
15551
16254
  key
15552
16255
  ]);
15553
16256
  for (const [key, terminal] of Object.entries(next.terminals)){
15554
- doc.deleteIn([
16257
+ if (doc.hasIn([
16258
+ 'terminals',
16259
+ key,
16260
+ 'aliases'
16261
+ ])) doc.deleteIn([
15555
16262
  'terminals',
15556
16263
  key,
15557
16264
  'aliases'
@@ -15629,7 +16336,7 @@ function repoView(path) {
15629
16336
  function readState(explicitPath) {
15630
16337
  const configPath = paths_resolveConfigPath(explicitPath);
15631
16338
  const loaded = config_loadConfig(explicitPath);
15632
- const checked = loaded.exists ? checkConfig(loaded.raw, {
16339
+ const checked = loaded.exists ? checkConfigWithCatalog(loaded.raw, {
15633
16340
  checkFs: true
15634
16341
  }) : {
15635
16342
  config: null,
@@ -15642,14 +16349,14 @@ function readState(explicitPath) {
15642
16349
  issues: checked.issues,
15643
16350
  backups: listBackups(explicitPath),
15644
16351
  meta: {
15645
- version: "0.6.0",
16352
+ version: "0.6.2",
15646
16353
  features: SERVER_FEATURES
15647
16354
  }
15648
16355
  };
15649
16356
  }
15650
16357
  function saveConfig(raw, explicitPath) {
15651
16358
  const configPath = paths_resolveConfigPath(explicitPath);
15652
- const structural = checkConfig(raw, {
16359
+ const structural = checkConfigWithCatalog(raw, {
15653
16360
  allowIncomplete: false,
15654
16361
  checkFs: false
15655
16362
  });
@@ -15724,13 +16431,13 @@ function resetConfig(explicitPath) {
15724
16431
  configPath
15725
16432
  };
15726
16433
  }
15727
- function inspectPath(target, iterationsRoot = DEFAULT_ITERATIONS_ROOT) {
16434
+ function inspectPath(target) {
15728
16435
  const view = repoView(target);
15729
16436
  const hasDocsSkill = view.exists && external_node_fs_existsSync(external_node_path_join(target, 'skills', 'iteration-task-docs', 'SKILL.md'));
15730
16437
  return {
15731
16438
  ...view,
15732
16439
  hasDocsSkill,
15733
- iterationYears: view.exists ? listIterationYears(target, iterationsRoot) : []
16440
+ iterationYears: view.exists ? listIterationYears(target, DEFAULT_ITERATIONS_ROOT) : []
15734
16441
  };
15735
16442
  }
15736
16443
  function inspectOnboarding(configPath) {
@@ -15779,7 +16486,7 @@ function inspectOnboarding(configPath) {
15779
16486
  };
15780
16487
  }
15781
16488
  function completeOnboarding(draftRaw, configPath) {
15782
- const structural = checkConfig(draftRaw, {
16489
+ const structural = checkConfigWithCatalog(draftRaw, {
15783
16490
  allowIncomplete: true,
15784
16491
  checkFs: false
15785
16492
  });
@@ -15794,7 +16501,7 @@ function completeOnboarding(draftRaw, configPath) {
15794
16501
  return inspectOnboarding(configPath);
15795
16502
  }
15796
16503
  function assertDirectory(target) {
15797
- const absolute = isAbsolute(target) ? external_node_path_resolve(target) : external_node_path_resolve(homedir(), target);
16504
+ const absolute = external_node_path_isAbsolute(target) ? external_node_path_resolve(target) : external_node_path_resolve(homedir(), target);
15798
16505
  if (!external_node_fs_existsSync(absolute)) throw new errors_CliError(`目录不存在:${absolute}`, errors_EXIT.NOT_FOUND);
15799
16506
  if (!statSync(absolute).isDirectory()) throw new errors_CliError(`不是目录:${absolute}`, errors_EXIT.USAGE);
15800
16507
  return absolute;
@@ -16125,13 +16832,32 @@ const OPERATIONS = [
16125
16832
  },
16126
16833
  ipc: 'ylcwf:inspect',
16127
16834
  ipcParams: [
16128
- 'path',
16129
- 'iterationsRoot'
16835
+ 'path'
16130
16836
  ],
16131
- run: (input)=>{
16132
- const loaded = config_loadConfig();
16133
- const iterationsRoot = input.optionalText('iterationsRoot') ?? layoutOf(loaded.config).iterationsRoot;
16134
- return inspectPath(input.text('path'), iterationsRoot);
16837
+ run: (input)=>inspectPath(input.text('path'))
16838
+ },
16839
+ {
16840
+ name: 'terminal-catalog',
16841
+ http: {
16842
+ method: 'GET',
16843
+ path: '/api/terminal-catalog'
16844
+ },
16845
+ ipc: 'ylcwf:terminalCatalog',
16846
+ ipcParams: [],
16847
+ run: (_input, context)=>{
16848
+ const loaded = config_loadConfig(context.configPath);
16849
+ const layout = layoutOf(loaded.config);
16850
+ if (0 === layout.root.length) return {
16851
+ path: null,
16852
+ terminals: [],
16853
+ issues: []
16854
+ };
16855
+ const loadedCatalog = loadTerminalCatalog(layout.root);
16856
+ return {
16857
+ path: loadedCatalog.path,
16858
+ terminals: loadedCatalog.catalog?.terminals ?? [],
16859
+ issues: loadedCatalog.issues
16860
+ };
16135
16861
  }
16136
16862
  },
16137
16863
  {
@@ -16703,188 +17429,6 @@ function registerServe(program) {
16703
17429
  await runServe(options);
16704
17430
  });
16705
17431
  }
16706
- const YAPI_PLATFORM_FILE = 'yapi_platform.json';
16707
- function yapi_error(code, message, where) {
16708
- return void 0 === where ? {
16709
- level: 'error',
16710
- code,
16711
- message
16712
- } : {
16713
- level: 'error',
16714
- code,
16715
- message,
16716
- where
16717
- };
16718
- }
16719
- function yapi_isRecord(value) {
16720
- return 'object' == typeof value && null !== value && !Array.isArray(value);
16721
- }
16722
- function yapi_isPositiveInteger(value) {
16723
- return 'number' == typeof value && Number.isInteger(value) && value > 0;
16724
- }
16725
- function checkYapiCatalog(raw) {
16726
- const issues = [];
16727
- if (!yapi_isRecord(raw)) return {
16728
- catalog: null,
16729
- issues: [
16730
- yapi_error('YAPI_TYPE', 'yapi_platform.json 必须是对象')
16731
- ]
16732
- };
16733
- const groups = [];
16734
- const groupsRaw = raw['groups'];
16735
- if (Array.isArray(groupsRaw)) groupsRaw.forEach((item, index)=>{
16736
- const where = `groups[${index}]`;
16737
- if (!yapi_isRecord(item)) return void issues.push(yapi_error('YAPI_GROUP_INVALID', `${where} 必须是对象`, where));
16738
- const groupId = item['groupId'];
16739
- const name = item['name'];
16740
- if (!yapi_isPositiveInteger(groupId)) return void issues.push(yapi_error('YAPI_GROUP_ID_INVALID', `${where}.groupId 必须是正整数`, `${where}.groupId`));
16741
- if ('string' != typeof name || 0 === name.trim().length) return void issues.push(yapi_error('YAPI_GROUP_NAME_INVALID', `${where}.name 不能为空`, `${where}.name`));
16742
- groups.push({
16743
- groupId,
16744
- name: name.trim()
16745
- });
16746
- });
16747
- else issues.push(yapi_error('YAPI_GROUPS_INVALID', 'groups 必须是数组', 'groups'));
16748
- const knownGroupIds = new Set(groups.map((group)=>group.groupId));
16749
- const platforms = [];
16750
- const seenTerminals = new Map();
16751
- const platformsRaw = raw['platforms'];
16752
- if (Array.isArray(platformsRaw)) platformsRaw.forEach((item, index)=>{
16753
- const where = `platforms[${index}]`;
16754
- if (!yapi_isRecord(item)) return void issues.push(yapi_error('YAPI_PLATFORM_INVALID', `${where} 必须是对象`, where));
16755
- const terminal = item['terminal'];
16756
- const groupId = item['groupId'];
16757
- const projectIds = item['projectIds'];
16758
- const platformRaw = item['platform'];
16759
- if ('string' != typeof terminal || 0 === terminal.trim().length) return void issues.push(yapi_error('YAPI_TERMINAL_REQUIRED', `${where}.terminal 不能为空`, `${where}.terminal`));
16760
- if (!yapi_isPositiveInteger(groupId)) return void issues.push(yapi_error('YAPI_GROUP_ID_INVALID', `${where}.groupId 必须是正整数`, `${where}.groupId`));
16761
- if (!knownGroupIds.has(groupId)) issues.push(yapi_error('YAPI_GROUP_UNKNOWN', `${where}.groupId ${groupId} 未在 groups 中声明`, `${where}.groupId`));
16762
- if (!Array.isArray(projectIds) || 0 === projectIds.length) return void issues.push(yapi_error('YAPI_PROJECT_IDS_INVALID', `${where}.projectIds 必须是非空数组`, `${where}.projectIds`));
16763
- const invalidProject = projectIds.find((id)=>!yapi_isPositiveInteger(id));
16764
- if (void 0 !== invalidProject) return void issues.push(yapi_error('YAPI_PROJECT_IDS_INVALID', `${where}.projectIds 只能包含正整数:${String(invalidProject)}`, `${where}.projectIds`));
16765
- const key = normalizeName(terminal);
16766
- const duplicate = seenTerminals.get(key);
16767
- if (void 0 !== duplicate) issues.push(yapi_error('YAPI_TERMINAL_DUPLICATED', `执行终端「${terminal.trim()}」重复声明(另见「${duplicate}」),按归一化比较重复`, `${where}.terminal`));
16768
- else seenTerminals.set(key, terminal.trim());
16769
- platforms.push({
16770
- platform: 'string' == typeof platformRaw && platformRaw.trim().length > 0 ? platformRaw.trim() : null,
16771
- terminal: terminal.trim(),
16772
- groupId,
16773
- projectIds: [
16774
- ...projectIds
16775
- ].sort((left, right)=>left - right)
16776
- });
16777
- });
16778
- else issues.push(yapi_error('YAPI_PLATFORMS_INVALID', 'platforms 必须是数组', 'platforms'));
16779
- if (issues.some((issue)=>'error' === issue.level)) return {
16780
- catalog: null,
16781
- issues
16782
- };
16783
- return {
16784
- catalog: {
16785
- groups,
16786
- platforms
16787
- },
16788
- issues
16789
- };
16790
- }
16791
- function loadYapiCatalog(docsRoot) {
16792
- const path = external_node_path_join(docsRoot, YAPI_PLATFORM_FILE);
16793
- let text;
16794
- try {
16795
- text = readFileSync(path, 'utf8');
16796
- } catch {
16797
- return {
16798
- path,
16799
- catalog: null,
16800
- issues: []
16801
- };
16802
- }
16803
- let raw;
16804
- try {
16805
- raw = JSON.parse(text);
16806
- } catch (caught) {
16807
- const detail = caught instanceof Error ? caught.message : String(caught);
16808
- return {
16809
- path,
16810
- catalog: null,
16811
- issues: [
16812
- yapi_error('YAPI_JSON_INVALID', `${YAPI_PLATFORM_FILE} 不是合法 JSON:${detail}`)
16813
- ]
16814
- };
16815
- }
16816
- return {
16817
- path,
16818
- ...checkYapiCatalog(raw)
16819
- };
16820
- }
16821
- function terminalNameByRepo(terminals, input) {
16822
- const target = normalizeName(input);
16823
- const hits = [];
16824
- for (const [name, terminal] of Object.entries(terminals)){
16825
- const repos = [
16826
- ...terminal.repos.frontend,
16827
- ...terminal.repos.backend
16828
- ];
16829
- if (repos.some((repo)=>normalizeName(basename(repo)) === target)) hits.push(name);
16830
- }
16831
- return 1 === hits.length ? hits[0] ?? null : null;
16832
- }
16833
- function resolveConfigTerminal(terminals, input) {
16834
- const target = normalizeName(input);
16835
- for (const name of Object.keys(terminals))if (normalizeName(name) === target) return {
16836
- terminalName: name,
16837
- matchedBy: 'terminal'
16838
- };
16839
- const byRepo = terminalNameByRepo(terminals, input);
16840
- if (null !== byRepo) return {
16841
- terminalName: byRepo,
16842
- matchedBy: 'repo'
16843
- };
16844
- return {
16845
- terminalName: null,
16846
- matchedBy: null
16847
- };
16848
- }
16849
- function describePlatform(item) {
16850
- return null === item.platform ? item.terminal : `${item.terminal}(${item.platform})`;
16851
- }
16852
- function matchYapiPlatform(options) {
16853
- const { catalog, terminals, input } = options;
16854
- const trimmed = input.trim();
16855
- const empty = {
16856
- matched: false,
16857
- terminalName: null,
16858
- matchedBy: null,
16859
- platform: null,
16860
- group: null,
16861
- candidates: catalog.platforms.map(describePlatform)
16862
- };
16863
- if (0 === trimmed.length) return empty;
16864
- const resolved = resolveConfigTerminal(terminals, trimmed);
16865
- const target = normalizeName(resolved.terminalName ?? trimmed);
16866
- const byTerminal = catalog.platforms.filter((item)=>normalizeName(item.terminal) === target);
16867
- if (1 === byTerminal.length && void 0 !== byTerminal[0]) return buildMatch(byTerminal[0], resolved.terminalName, resolved.matchedBy ?? 'terminal', catalog);
16868
- if (byTerminal.length > 1) return {
16869
- ...empty,
16870
- terminalName: resolved.terminalName,
16871
- candidates: byTerminal.map(describePlatform)
16872
- };
16873
- return {
16874
- ...empty,
16875
- terminalName: resolved.terminalName
16876
- };
16877
- }
16878
- function buildMatch(item, terminalName, matchedBy, catalog) {
16879
- return {
16880
- matched: true,
16881
- terminalName,
16882
- matchedBy,
16883
- platform: item,
16884
- group: catalog.groups.find((group)=>group.groupId === item.groupId) ?? null,
16885
- candidates: []
16886
- };
16887
- }
16888
17432
  function requireCatalog(docsRoot) {
16889
17433
  const loaded = loadYapiCatalog(docsRoot);
16890
17434
  if (null !== loaded.catalog) return loaded.catalog;
@@ -17034,7 +17578,7 @@ function registerReset(program) {
17034
17578
  }
17035
17579
  function buildProgram() {
17036
17580
  const program = new command_Command();
17037
- program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与执行终端仓库映射').version("0.6.0", '-v, --version', '显示版本号').showHelpAfterError();
17581
+ program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与执行终端仓库映射').version("0.6.2", '-v, --version', '显示版本号').showHelpAfterError();
17038
17582
  registerInit(program);
17039
17583
  registerShow(program);
17040
17584
  registerGet(program);