ylcwf 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,14 @@
1
1
  import { Command } from "commander";
2
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
- import { basename, dirname, isAbsolute, join, resolve } from "node:path";
2
+ import { appendFileSync, chmodSync, closeSync, copyFileSync, existsSync as external_node_fs_existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
3
+ import { execFileSync, spawn } from "node:child_process";
4
+ import { basename, dirname, extname, isAbsolute, join as external_node_path_join, relative as external_node_path_relative, resolve, sep } from "node:path";
4
5
  import { isMap, isSeq, parseDocument } from "yaml";
5
- import { homedir } from "node:os";
6
+ import { homedir, tmpdir as external_node_os_tmpdir } from "node:os";
6
7
  import picocolors from "picocolors";
8
+ import { randomBytes } from "node:crypto";
9
+ import { createServer } from "node:net";
10
+ import { fileURLToPath } from "node:url";
11
+ import { createServer as external_node_http_createServer } from "node:http";
7
12
  import * as __rspack_external__clack_prompts_d2d5c36d from "@clack/prompts";
8
13
  const errors_EXIT = {
9
14
  OK: 0,
@@ -28,17 +33,27 @@ function printLine(text = '') {
28
33
  function printError(text) {
29
34
  writeFileSync(process.stderr.fd, `${text}\n`);
30
35
  }
31
- const CONFIG_DIR = join(homedir(), '.ylcwf');
32
- const DEFAULT_CONFIG_PATH = join(CONFIG_DIR, 'config.yaml');
33
- function resolveConfigPath(explicit) {
36
+ const CONFIG_DIR = external_node_path_join(homedir(), '.ylcwf');
37
+ const DEFAULT_CONFIG_PATH = external_node_path_join(CONFIG_DIR, 'config.yaml');
38
+ function paths_resolveConfigPath(explicit) {
34
39
  const fromFlag = explicit?.trim();
35
40
  if (void 0 !== fromFlag && fromFlag.length > 0) return isAbsolute(fromFlag) ? fromFlag : resolve(process.cwd(), fromFlag);
36
41
  const fromEnv = process.env['YLCWF_CONFIG']?.trim();
37
42
  if (void 0 !== fromEnv && fromEnv.length > 0) return isAbsolute(fromEnv) ? fromEnv : resolve(process.cwd(), fromEnv);
38
43
  return DEFAULT_CONFIG_PATH;
39
44
  }
45
+ function serveTokenPath() {
46
+ return external_node_path_join(CONFIG_DIR, 'serve.token');
47
+ }
48
+ function historyPath() {
49
+ return external_node_path_join(CONFIG_DIR, 'history', 'task-actions.jsonl');
50
+ }
51
+ const DEFAULT_DOCS_REMOTE = 'https://code.seevin.com/tools/iteration-task-repo';
52
+ function managedReposDir() {
53
+ return external_node_path_join(CONFIG_DIR, 'repos');
54
+ }
40
55
  function backupsDir(configPath) {
41
- return join(dirname(configPath), 'backups');
56
+ return external_node_path_join(dirname(configPath), 'backups');
42
57
  }
43
58
  const DASH_PATTERN = /[\u2010-\u2015\u2212\uFE58\uFE63\uFF0D_-]+/g;
44
59
  function normalizeName(input) {
@@ -75,7 +90,6 @@ function isStringArray(value) {
75
90
  function parsePathList(input) {
76
91
  return input.split(/[,,;;]/).map((item)=>item.trim()).filter((item)=>item.length > 0);
77
92
  }
78
- const SCHEMA_VERSION = 2;
79
93
  const ROLES = [
80
94
  'frontend',
81
95
  'backend',
@@ -85,19 +99,37 @@ const SIDES = [
85
99
  'frontend',
86
100
  'backend'
87
101
  ];
102
+ const MODES = [
103
+ 'developer',
104
+ 'stakeholder'
105
+ ];
88
106
  const TOP_LEVEL_KEYS = new Set([
89
- 'schemaVersion',
90
107
  'profile',
91
108
  'docs',
92
109
  'terminals'
93
110
  ]);
94
111
  const PROFILE_KEYS = new Set([
95
112
  'developer',
96
- 'role'
113
+ 'role',
114
+ 'mode'
97
115
  ]);
98
116
  const DOCS_KEYS = new Set([
99
- 'root'
117
+ 'root',
118
+ 'remote',
119
+ 'git'
120
+ ]);
121
+ const GIT_KEYS = new Set([
122
+ 'cli',
123
+ 'ui'
100
124
  ]);
125
+ const POLICY_KEYS = new Set([
126
+ 'commit',
127
+ 'push'
128
+ ]);
129
+ const DEFAULT_GIT_POLICY = {
130
+ commit: true,
131
+ push: false
132
+ };
101
133
  const TERMINAL_KEYS = new Set([
102
134
  'aliases',
103
135
  'repos'
@@ -107,6 +139,9 @@ const DEVELOPER_PATTERN = /^[a-z][a-z0-9]*$/;
107
139
  function isRole(value) {
108
140
  return 'string' == typeof value && ROLES.some((role)=>role === value);
109
141
  }
142
+ function isMode(value) {
143
+ return 'string' == typeof value && MODES.some((mode)=>mode === value);
144
+ }
110
145
  function schema_error(code, message, where) {
111
146
  return {
112
147
  level: 'error',
@@ -155,11 +190,19 @@ function parseProfile(raw, options, issues) {
155
190
  issues.push(...unknownKeys(raw, PROFILE_KEYS, 'profile'));
156
191
  const incomplete = true === options.allowIncomplete;
157
192
  let valid = true;
193
+ const modeRaw = raw['mode'];
194
+ let mode = 'developer';
195
+ if (void 0 !== modeRaw) if (isMode(modeRaw)) mode = modeRaw;
196
+ else {
197
+ issues.push(schema_error('MODE_INVALID', `使用模式必须是 ${MODES.join(' / ')} 之一:${String(modeRaw)}`, 'profile.mode'));
198
+ valid = false;
199
+ }
200
+ const developerRequired = 'developer' === mode;
158
201
  const developerRaw = raw['developer'];
159
202
  let developer = '';
160
203
  if (void 0 === developerRaw || 'string' == typeof developerRaw && '' === developerRaw.trim()) {
161
- if (!incomplete) {
162
- issues.push(schema_error('FIELD_REQUIRED', 'profile.developer 未配置', 'profile.developer'));
204
+ if (!incomplete && developerRequired) {
205
+ issues.push(schema_error('FIELD_REQUIRED', 'profile.developer 未配置(干系人可不填)', 'profile.developer'));
163
206
  valid = false;
164
207
  }
165
208
  } else if ('string' == typeof developerRaw && DEVELOPER_PATTERN.test(developerRaw)) developer = developerRaw;
@@ -170,7 +213,7 @@ function parseProfile(raw, options, issues) {
170
213
  const roleRaw = raw['role'];
171
214
  let role = 'frontend';
172
215
  if (void 0 === roleRaw) {
173
- if (!incomplete) {
216
+ if (!incomplete && developerRequired) {
174
217
  issues.push(schema_error('FIELD_REQUIRED', 'profile.role 未配置', 'profile.role'));
175
218
  valid = false;
176
219
  }
@@ -182,7 +225,8 @@ function parseProfile(raw, options, issues) {
182
225
  if (!valid) return null;
183
226
  return {
184
227
  developer,
185
- role
228
+ role,
229
+ mode
186
230
  };
187
231
  }
188
232
  function parseDocs(raw, options, issues) {
@@ -191,17 +235,85 @@ function parseDocs(raw, options, issues) {
191
235
  return null;
192
236
  }
193
237
  issues.push(...unknownKeys(raw, DOCS_KEYS, 'docs'));
238
+ let root = '';
194
239
  const rootRaw = raw['root'];
195
240
  if (void 0 === rootRaw || 'string' == typeof rootRaw && '' === rootRaw.trim()) {
196
- if (true === options.allowIncomplete) return {
197
- root: ''
198
- };
199
- issues.push(schema_error('FIELD_REQUIRED', 'docs.root 未配置', 'docs.root'));
241
+ if (true !== options.allowIncomplete) {
242
+ issues.push(schema_error('FIELD_REQUIRED', 'docs.root 未配置', 'docs.root'));
243
+ return null;
244
+ }
245
+ } else {
246
+ const parsed = checkAbsolutePath(rootRaw, 'docs.root', issues, true);
247
+ if (null === parsed) return null;
248
+ root = parsed;
249
+ }
250
+ let remote = null;
251
+ const remoteRaw = raw['remote'];
252
+ if (null != remoteRaw) {
253
+ if ('string' != typeof remoteRaw || 0 === remoteRaw.trim().length) {
254
+ issues.push(schema_error('REMOTE_INVALID', 'docs.remote 必须是非空字符串', 'docs.remote'));
255
+ return null;
256
+ }
257
+ const trimmed = remoteRaw.trim();
258
+ const looksLikeGit = /^(https?:\/\/|ssh:\/\/|git@)/.test(trimmed);
259
+ if (!looksLikeGit) {
260
+ issues.push(schema_error('REMOTE_INVALID', `docs.remote 不是合法的仓库地址:${trimmed}`, 'docs.remote'));
261
+ return null;
262
+ }
263
+ remote = trimmed;
264
+ }
265
+ const git = parseGitPolicy(raw['git'], issues);
266
+ if (null === git) return null;
267
+ return {
268
+ root,
269
+ remote,
270
+ git
271
+ };
272
+ }
273
+ function parseGitPolicy(raw, issues) {
274
+ if (null == raw) return {
275
+ cli: {
276
+ ...DEFAULT_GIT_POLICY
277
+ },
278
+ ui: {
279
+ ...DEFAULT_GIT_POLICY
280
+ }
281
+ };
282
+ if (!utils_isRecord(raw)) {
283
+ issues.push(schema_error('GIT_POLICY_INVALID', 'docs.git 必须是对象', 'docs.git'));
200
284
  return null;
201
285
  }
202
- const root = checkAbsolutePath(rootRaw, 'docs.root', issues, true);
203
- return null === root ? null : {
204
- root
286
+ issues.push(...unknownKeys(raw, GIT_KEYS, 'docs.git'));
287
+ const read = (key)=>{
288
+ const value = raw[key];
289
+ if (null == value) return {
290
+ ...DEFAULT_GIT_POLICY
291
+ };
292
+ if (!utils_isRecord(value)) {
293
+ issues.push(schema_error('GIT_POLICY_INVALID', `docs.git.${key} 必须是对象`, `docs.git.${key}`));
294
+ return null;
295
+ }
296
+ issues.push(...unknownKeys(value, POLICY_KEYS, `docs.git.${key}`));
297
+ const pick = (field, fallback)=>{
298
+ const item = value[field];
299
+ if (void 0 === item) return fallback;
300
+ if ('boolean' != typeof item) {
301
+ issues.push(schema_error('GIT_POLICY_INVALID', `docs.git.${key}.${field} 必须是布尔值`, `docs.git.${key}.${field}`));
302
+ return fallback;
303
+ }
304
+ return item;
305
+ };
306
+ return {
307
+ commit: pick('commit', DEFAULT_GIT_POLICY.commit),
308
+ push: pick('push', DEFAULT_GIT_POLICY.push)
309
+ };
310
+ };
311
+ const cli = read('cli');
312
+ const ui = read('ui');
313
+ if (null === cli || null === ui) return null;
314
+ return {
315
+ cli,
316
+ ui
205
317
  };
206
318
  }
207
319
  function parseRepos(raw, where, issues) {
@@ -316,9 +428,9 @@ function checkTerminalIdentity(terminals) {
316
428
  function checkFsOfDocs(config, issues) {
317
429
  const { root } = config.docs;
318
430
  if ('' === root) return;
319
- if (!existsSync(root)) return void issues.push(schema_error('DOCS_ROOT_MISSING', `文档仓库不存在:${root}`, 'docs.root'));
431
+ if (!external_node_fs_existsSync(root)) return void issues.push(schema_error('DOCS_ROOT_MISSING', `文档仓库不存在:${root}`, 'docs.root'));
320
432
  if (!statSync(root).isDirectory()) return void issues.push(schema_error('DOCS_ROOT_NOT_DIR', `文档仓库不是目录:${root}`, 'docs.root'));
321
- if (!existsSync(join(root, 'skills', 'iteration-task-docs', 'SKILL.md'))) issues.push(schema_error('DOCS_ROOT_NO_SKILL', `文档仓库缺少 skills/iteration-task-docs/SKILL.md:${root}`, 'docs.root'));
433
+ if (!external_node_fs_existsSync(external_node_path_join(root, 'skills', 'iteration-task-docs', 'SKILL.md'))) issues.push(schema_error('DOCS_ROOT_NO_SKILL', `文档仓库缺少 skills/iteration-task-docs/SKILL.md:${root}`, 'docs.root'));
322
434
  }
323
435
  function checkFsOfTerminals(config, issues) {
324
436
  const pathOwners = new Map();
@@ -330,7 +442,7 @@ function checkFsOfTerminals(config, issues) {
330
442
  continue;
331
443
  }
332
444
  for (const target of targets){
333
- if (!existsSync(target)) {
445
+ if (!external_node_fs_existsSync(target)) {
334
446
  issues.push(schema_error('REPO_PATH_MISSING', `仓库路径不存在:${target}`, where));
335
447
  continue;
336
448
  }
@@ -338,7 +450,7 @@ function checkFsOfTerminals(config, issues) {
338
450
  issues.push(schema_error('REPO_PATH_NOT_DIR', `仓库路径不是目录:${target}`, where));
339
451
  continue;
340
452
  }
341
- if (!existsSync(join(target, '.git'))) issues.push(warning('REPO_NOT_GIT', `路径不是 git 仓库:${target}`, where));
453
+ if (!external_node_fs_existsSync(external_node_path_join(target, '.git'))) issues.push(warning('REPO_NOT_GIT', `路径不是 git 仓库:${target}`, where));
342
454
  const entry = pathOwners.get(`${side}:${target}`) ?? {
343
455
  side,
344
456
  target,
@@ -358,25 +470,19 @@ function checkConfig(raw, options = {}) {
358
470
  schema_error('CONFIG_ROOT', '配置文件根节点必须是对象')
359
471
  ]
360
472
  };
361
- issues.push(...unknownKeys(raw, TOP_LEVEL_KEYS, 'root'));
362
- const version = raw['schemaVersion'];
363
- let versionValid = true;
364
- if (void 0 === version) {
365
- issues.push(schema_error('SCHEMA_VERSION_MISSING', `缺少 schemaVersion,应为 ${SCHEMA_VERSION}`, 'schemaVersion'));
366
- versionValid = false;
367
- } else if (version !== SCHEMA_VERSION) {
368
- issues.push(schema_error('SCHEMA_VERSION_UNSUPPORTED', `不支持的 schemaVersion:${String(version)}(当前 CLI 支持 ${SCHEMA_VERSION})`, 'schemaVersion'));
369
- versionValid = false;
370
- }
371
- const profile = parseProfile(raw['profile'], options, issues);
372
- const docs = parseDocs(raw['docs'], options, issues);
373
- const terminals = parseTerminals(raw['terminals'] ?? {}, issues);
374
- if (null === profile || null === docs || null === terminals || !versionValid) return {
473
+ const normalized = {
474
+ ...raw
475
+ };
476
+ delete normalized['schemaVersion'];
477
+ issues.push(...unknownKeys(normalized, TOP_LEVEL_KEYS, 'root'));
478
+ const profile = parseProfile(normalized['profile'], options, issues);
479
+ const docs = parseDocs(normalized['docs'], options, issues);
480
+ const terminals = parseTerminals(normalized['terminals'] ?? {}, issues);
481
+ if (null === profile || null === docs || null === terminals) return {
375
482
  config: null,
376
483
  issues
377
484
  };
378
485
  const config = {
379
- schemaVersion: SCHEMA_VERSION,
380
486
  profile,
381
487
  docs,
382
488
  terminals
@@ -416,10 +522,72 @@ function countIssues(issues) {
416
522
  function existsMark(exists) {
417
523
  return exists ? picocolors.green('✓') : picocolors.red('✗');
418
524
  }
525
+ function isProcessAlive(pid) {
526
+ if (!Number.isInteger(pid) || pid <= 0) return false;
527
+ try {
528
+ process.kill(pid, 0);
529
+ return true;
530
+ } catch (error) {
531
+ const code = error.code;
532
+ return 'EPERM' === code;
533
+ }
534
+ }
535
+ function isStale(lockPath, staleMs) {
536
+ try {
537
+ const info = statSync(lockPath);
538
+ if (Date.now() - info.mtimeMs > staleMs) return true;
539
+ const raw = readFileSync(lockPath, 'utf8').trim();
540
+ const pid = Number.parseInt(raw.split(/\s+/)[0] ?? '', 10);
541
+ if (!Number.isFinite(pid)) return true;
542
+ return !isProcessAlive(pid);
543
+ } catch {
544
+ return true;
545
+ }
546
+ }
547
+ const DEFAULT_TIMEOUT_MS = 5000;
548
+ const DEFAULT_STALE_MS = 30000;
549
+ const DEFAULT_RETRY_MS = 50;
550
+ function sleepSync(ms) {
551
+ const shared = new SharedArrayBuffer(4);
552
+ Atomics.wait(new Int32Array(shared), 0, 0, ms);
553
+ }
554
+ function withConfigLock(configPath, run, options = {}) {
555
+ const lockPath = `${configPath}.lock`;
556
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
557
+ const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
558
+ const retryMs = options.retryMs ?? DEFAULT_RETRY_MS;
559
+ const deadline = Date.now() + timeoutMs;
560
+ let fd = null;
561
+ for(;;)try {
562
+ fd = openSync(lockPath, 'wx');
563
+ writeSync(fd, `${process.pid} ${new Date().toISOString()}\n`);
564
+ break;
565
+ } catch (error) {
566
+ const code = error.code;
567
+ if ('EEXIST' !== code) throw error;
568
+ if (isStale(lockPath, staleMs)) {
569
+ try {
570
+ unlinkSync(lockPath);
571
+ } catch {}
572
+ continue;
573
+ }
574
+ if (Date.now() >= deadline) throw new errors_CliError(`配置文件正被其他进程写入:${lockPath}\n请等待当前操作完成,或删除该锁文件后重试`, errors_EXIT.INVALID);
575
+ sleepSync(retryMs);
576
+ }
577
+ try {
578
+ return run();
579
+ } finally{
580
+ if (null !== fd) try {
581
+ closeSync(fd);
582
+ } catch {}
583
+ if (external_node_fs_existsSync(lockPath)) try {
584
+ unlinkSync(lockPath);
585
+ } catch {}
586
+ }
587
+ }
419
588
  const MAX_BACKUPS = 10;
420
- const TEMPLATE = `# ylcwf 配置(schemaVersion 2)
589
+ const TEMPLATE = `# ylcwf 配置
421
590
  # 由 ylcwf CLI 管理;手改后请运行 \`ylcwf doctor\` 校验。
422
- schemaVersion: 2
423
591
 
424
592
  profile:
425
593
  developer: ''
@@ -427,6 +595,9 @@ profile:
427
595
 
428
596
  docs:
429
597
  root: ''
598
+ git:
599
+ cli: { commit: true, push: false }
600
+ ui: { commit: true, push: false }
430
601
 
431
602
  terminals: {}
432
603
  `;
@@ -434,8 +605,8 @@ function createEmptyDocument() {
434
605
  return parseDocument(TEMPLATE);
435
606
  }
436
607
  function loadConfig(explicit) {
437
- const path = resolveConfigPath(explicit);
438
- if (!existsSync(path)) return {
608
+ const path = paths_resolveConfigPath(explicit);
609
+ if (!external_node_fs_existsSync(path)) return {
439
610
  path,
440
611
  exists: false,
441
612
  doc: null,
@@ -510,14 +681,19 @@ function saveDocument(doc, target) {
510
681
  mkdirSync(dirname(target), {
511
682
  recursive: true
512
683
  });
513
- if (existsSync(target)) backup(target);
684
+ doc.deleteIn([
685
+ 'schemaVersion'
686
+ ]);
514
687
  toBlockStyle(doc.contents);
515
688
  const text = doc.toString({
516
689
  lineWidth: 0
517
690
  });
518
- const tmp = `${target}.tmp-${process.pid}`;
519
- writeFileSync(tmp, text, 'utf8');
520
- renameSync(tmp, target);
691
+ withConfigLock(target, ()=>{
692
+ if (external_node_fs_existsSync(target)) backup(target);
693
+ const tmp = `${target}.tmp-${process.pid}`;
694
+ writeFileSync(tmp, text, 'utf8');
695
+ renameSync(tmp, target);
696
+ });
521
697
  }
522
698
  function backup(target) {
523
699
  const dir = backupsDir(target);
@@ -525,10 +701,10 @@ function backup(target) {
525
701
  recursive: true
526
702
  });
527
703
  const stamp = new Date().toISOString().replace(/[:.]/g, '-');
528
- let destination = join(dir, `config-${stamp}.yaml`);
704
+ let destination = external_node_path_join(dir, `config-${stamp}.yaml`);
529
705
  let index = 1;
530
- while(existsSync(destination)){
531
- destination = join(dir, `config-${stamp}-${index}.yaml`);
706
+ while(external_node_fs_existsSync(destination)){
707
+ destination = external_node_path_join(dir, `config-${stamp}-${index}.yaml`);
532
708
  index += 1;
533
709
  }
534
710
  copyFileSync(target, destination);
@@ -581,7 +757,7 @@ function validateExistingDir(value) {
581
757
  const trimmed = (value ?? '').trim();
582
758
  if (0 === trimmed.length) return '不能为空';
583
759
  if (!isAbsolute(trimmed)) return '必须是绝对路径';
584
- if (!existsSync(trimmed)) return '路径不存在';
760
+ if (!external_node_fs_existsSync(trimmed)) return '路径不存在';
585
761
  if (!statSync(trimmed).isDirectory()) return '不是目录';
586
762
  }
587
763
  function validateDeveloper(value) {
@@ -598,9 +774,31 @@ function validatePathList(value) {
598
774
  if (void 0 !== message) return `${part}:${message}`;
599
775
  }
600
776
  }
777
+ function detectGitRemote(root) {
778
+ try {
779
+ const out = execFileSync('git', [
780
+ '-C',
781
+ root,
782
+ 'remote',
783
+ 'get-url',
784
+ 'origin'
785
+ ], {
786
+ encoding: 'utf8',
787
+ timeout: 5000
788
+ }).trim();
789
+ return out.length > 0 ? out : null;
790
+ } catch {
791
+ return null;
792
+ }
793
+ }
794
+ function validateRemote(value) {
795
+ const trimmed = (value ?? '').trim();
796
+ if (0 === trimmed.length) return '不能为空';
797
+ if (!/^(https?:\/\/|ssh:\/\/|git@)/.test(trimmed)) return '必须是 https:// 或 git@ 形式的地址';
798
+ }
601
799
  async function runInit(options) {
602
800
  if (true !== process.stdin.isTTY) throw new errors_CliError('init 需要交互式终端;无 TTY 时请改用:ylcwf set / ylcwf terminal add', errors_EXIT.USAGE);
603
- const configPath = resolveConfigPath(options.config);
801
+ const configPath = paths_resolveConfigPath(options.config);
604
802
  const existing = loadConfig(options.config);
605
803
  if (existing.exists && true !== options.force) {
606
804
  const proceed = await askConfirm(`配置已存在(${configPath}),继续将覆盖全部字段。是否继续?`, false);
@@ -608,67 +806,103 @@ async function runInit(options) {
608
806
  }
609
807
  __rspack_external__clack_prompts_d2d5c36d.intro(`ylcwf 初始化 → ${configPath}`);
610
808
  const doc = createEmptyDocument();
611
- const root = await askText('迭代任务文档仓库绝对路径', '/Users/you/develop/iteration-task-repo', validateExistingDir);
612
- doc.setIn([
613
- 'docs',
614
- 'root'
615
- ], root.trim());
616
- const developer = await askText('开发者标识(姓名小写全拼)', 'yourname', validateDeveloper);
617
- doc.setIn([
618
- 'profile',
619
- 'developer'
620
- ], developer.trim());
621
- const role = await __rspack_external__clack_prompts_d2d5c36d.select({
622
- message: '默认角色',
809
+ const mode = await __rspack_external__clack_prompts_d2d5c36d.select({
810
+ message: '使用模式',
623
811
  options: [
624
812
  {
625
- value: 'frontend',
626
- label: '前端'
627
- },
628
- {
629
- value: 'backend',
630
- label: '后端'
813
+ value: 'developer',
814
+ label: '开发者(全功能:配置 + 迭代看板)'
631
815
  },
632
816
  {
633
- value: 'fullstack',
634
- label: '全栈(前端 + 后端)'
817
+ value: 'stakeholder',
818
+ label: '干系人(产品 / 项目经理 / 测试,只看迭代看板)'
635
819
  }
636
820
  ],
637
- initialValue: 'frontend'
821
+ initialValue: 'developer'
638
822
  });
639
- if (__rspack_external__clack_prompts_d2d5c36d.isCancel(role)) bail();
823
+ if (__rspack_external__clack_prompts_d2d5c36d.isCancel(mode)) bail();
640
824
  doc.setIn([
641
825
  'profile',
642
- 'role'
643
- ], role);
644
- __rspack_external__clack_prompts_d2d5c36d.log.info('接下来逐项录入终端 → 本地仓库映射;终端名留空即结束。每端多个仓库用逗号或分号分隔。');
645
- let index = 0;
646
- for(;;){
647
- index += 1;
648
- const name = await askText(`终端 #${index}:PRD 中的终端名(留空结束)`, '示例终端-A', ()=>void 0);
649
- const trimmedName = name.trim();
650
- if (0 === trimmedName.length) break;
651
- if (void 0 !== getIn(doc.toJS(), [
652
- 'terminals',
653
- trimmedName
654
- ])) {
655
- __rspack_external__clack_prompts_d2d5c36d.log.warn(`终端「${trimmedName}」已存在,跳过`);
656
- index -= 1;
657
- continue;
658
- }
659
- const aliases = await askText('别名(逗号分隔,可留空)', '别名1, 别名2', ()=>void 0);
660
- const frontendRaw = await askText('前端仓库绝对路径(多个用逗号或分号分隔,可留空)', '/Users/you/develop/ylc/xxx', validatePathList);
661
- const backendRaw = await askText('后端仓库绝对路径(多个用逗号或分号分隔,可留空)', '/Users/you/develop/java/xxx', validatePathList);
826
+ 'mode'
827
+ ], mode);
828
+ if ('developer' === mode) {
829
+ const developer = await askText('开发者标识(姓名小写全拼)', 'yourname', validateDeveloper);
662
830
  doc.setIn([
663
- 'terminals',
664
- trimmedName
665
- ], {
666
- aliases: splitAliases(aliases),
667
- repos: {
668
- frontend: parsePathList(frontendRaw),
669
- backend: parsePathList(backendRaw)
670
- }
831
+ 'profile',
832
+ 'developer'
833
+ ], developer.trim());
834
+ const role = await __rspack_external__clack_prompts_d2d5c36d.select({
835
+ message: '默认角色',
836
+ options: [
837
+ {
838
+ value: 'frontend',
839
+ label: '前端'
840
+ },
841
+ {
842
+ value: 'backend',
843
+ label: '后端'
844
+ },
845
+ {
846
+ value: 'fullstack',
847
+ label: '全栈(前端 + 后端)'
848
+ }
849
+ ],
850
+ initialValue: 'frontend'
671
851
  });
852
+ if (__rspack_external__clack_prompts_d2d5c36d.isCancel(role)) bail();
853
+ doc.setIn([
854
+ 'profile',
855
+ 'role'
856
+ ], role);
857
+ const root = await askText('迭代任务文档仓库绝对路径', '/Users/you/develop/iteration-task-repo', validateExistingDir);
858
+ doc.setIn([
859
+ 'docs',
860
+ 'root'
861
+ ], root.trim());
862
+ doc.setIn([
863
+ 'docs',
864
+ 'remote'
865
+ ], detectGitRemote(root.trim()) ?? DEFAULT_DOCS_REMOTE);
866
+ __rspack_external__clack_prompts_d2d5c36d.log.info('接下来逐项录入终端 → 本地仓库映射;终端名留空即结束。每端多个仓库用逗号或分号分隔。');
867
+ let index = 0;
868
+ for(;;){
869
+ index += 1;
870
+ const name = await askText(`终端 #${index}:PRD 中的终端名(留空结束)`, '示例终端-A', ()=>void 0);
871
+ const trimmedName = name.trim();
872
+ if (0 === trimmedName.length) break;
873
+ if (void 0 !== getIn(doc.toJS(), [
874
+ 'terminals',
875
+ trimmedName
876
+ ])) {
877
+ __rspack_external__clack_prompts_d2d5c36d.log.warn(`终端「${trimmedName}」已存在,跳过`);
878
+ index -= 1;
879
+ continue;
880
+ }
881
+ const aliases = await askText('别名(逗号分隔,可留空)', '别名1, 别名2', ()=>void 0);
882
+ const frontendRaw = await askText('前端仓库绝对路径(多个用逗号或分号分隔,可留空)', '/Users/you/develop/ylc/xxx', validatePathList);
883
+ const backendRaw = await askText('后端仓库绝对路径(多个用逗号或分号分隔,可留空)', '/Users/you/develop/java/xxx', validatePathList);
884
+ doc.setIn([
885
+ 'terminals',
886
+ trimmedName
887
+ ], {
888
+ aliases: splitAliases(aliases),
889
+ repos: {
890
+ frontend: parsePathList(frontendRaw),
891
+ backend: parsePathList(backendRaw)
892
+ }
893
+ });
894
+ }
895
+ } else {
896
+ doc.setIn([
897
+ 'profile',
898
+ 'developer'
899
+ ], '');
900
+ const remote = await askText('文档仓库远程地址', DEFAULT_DOCS_REMOTE, validateRemote);
901
+ doc.setIn([
902
+ 'docs',
903
+ 'remote'
904
+ ], remote.trim());
905
+ __rspack_external__clack_prompts_d2d5c36d.log.info('干系人模式不配置本地路径:打开工作台后会自动准备只读副本。');
672
906
  }
673
907
  assertWritable(doc, configPath);
674
908
  saveDocument(doc, configPath);
@@ -725,6 +959,10 @@ const ROLE_LABEL = {
725
959
  backend: '后端',
726
960
  fullstack: '全栈(前端 + 后端)'
727
961
  };
962
+ const MODE_LABEL = {
963
+ developer: '开发者(全功能)',
964
+ stakeholder: '干系人(只看文档看板)'
965
+ };
728
966
  const SIDE_LABEL = {
729
967
  frontend: '前端',
730
968
  backend: '后端'
@@ -733,7 +971,6 @@ function showConfig(explicit, format) {
733
971
  const loaded = loadConfig(explicit);
734
972
  if (!loaded.exists) {
735
973
  if ('json' === format) return void printJson({
736
- schemaVersion: null,
737
974
  configPath: loaded.path,
738
975
  exists: false,
739
976
  config: null,
@@ -748,7 +985,6 @@ function showConfig(explicit, format) {
748
985
  checkFs: true
749
986
  });
750
987
  if ('json' === format) return void printJson({
751
- schemaVersion: checked.config?.schemaVersion ?? null,
752
988
  configPath: loaded.path,
753
989
  exists: true,
754
990
  config: checked.config,
@@ -787,7 +1023,11 @@ function renderHuman(path, config, issues) {
787
1023
  ],
788
1024
  [
789
1025
  '文档仓库',
790
- `${config.docs.root} ${existsMark(existsSync(config.docs.root))}`
1026
+ `${config.docs.root} ${existsMark(external_node_fs_existsSync(config.docs.root))}`
1027
+ ],
1028
+ [
1029
+ '远程地址',
1030
+ config.docs.remote ?? picocolors.dim('(内置默认值)')
791
1031
  ],
792
1032
  [
793
1033
  '开发者标识',
@@ -796,6 +1036,10 @@ function renderHuman(path, config, issues) {
796
1036
  [
797
1037
  '默认角色',
798
1038
  ROLE_LABEL[config.profile.role]
1039
+ ],
1040
+ [
1041
+ '使用模式',
1042
+ MODE_LABEL[config.profile.mode]
799
1043
  ]
800
1044
  ]).join('\n'));
801
1045
  const names = Object.keys(config.terminals);
@@ -828,7 +1072,7 @@ function renderHuman(path, config, issues) {
828
1072
  printedName ? '' : aliases,
829
1073
  0 === index ? SIDE_LABEL[side] : '',
830
1074
  target,
831
- existsMark(existsSync(target))
1075
+ existsMark(external_node_fs_existsSync(target))
832
1076
  ]);
833
1077
  printedName = true;
834
1078
  });
@@ -877,14 +1121,16 @@ function registerGet(program) {
877
1121
  });
878
1122
  }
879
1123
  const ROLE_SET = new Set(ROLES);
1124
+ const MODE_SET = new Set(MODES);
880
1125
  const SIDE_SET = new Set(SIDES);
881
1126
  function assertSettable(path) {
882
1127
  const [first, second, third, fourth] = path;
883
- if (2 === path.length && 'docs' === first && 'root' === second) return;
884
- if (2 === path.length && 'profile' === first && ('developer' === second || 'role' === second)) return;
1128
+ if (2 === path.length && 'docs' === first && ('root' === second || 'remote' === second)) return;
1129
+ if (4 === path.length && 'docs' === first && 'git' === second && ('cli' === third || 'ui' === third) && ('commit' === fourth || 'push' === fourth)) return;
1130
+ if (2 === path.length && 'profile' === first && ('developer' === second || 'role' === second || 'mode' === second)) return;
885
1131
  if (4 === path.length && 'terminals' === first && void 0 !== second && 'repos' === third && void 0 !== fourth && SIDE_SET.has(fourth)) return;
886
1132
  if (3 === path.length && 'terminals' === first && void 0 !== second && 'aliases' === third) return;
887
- throw new errors_CliError(`不支持通过 set 修改该路径:${path.join('.')}\n允许:docs.root / profile.developer / profile.role / terminals.<终端>.aliases / terminals.<终端>.repos.frontend|backend\n终端的新增与删除请用:ylcwf terminal add | rm`, errors_EXIT.USAGE);
1133
+ throw new errors_CliError(`不支持通过 set 修改该路径:${path.join('.')}\n允许:docs.root / docs.remote / docs.git.<cli|ui>.<commit|push> / profile.developer / profile.role / profile.mode / terminals.<终端>.aliases / terminals.<终端>.repos.frontend|backend\n终端的新增与删除请用:ylcwf terminal add | rm`, errors_EXIT.USAGE);
888
1134
  }
889
1135
  function coerceValue(path, raw) {
890
1136
  const key = path[path.length - 1];
@@ -893,6 +1139,11 @@ function coerceValue(path, raw) {
893
1139
  if (!isAbsolute(trimmed)) throw new errors_CliError(`文档仓库必须是绝对路径:${raw}`, errors_EXIT.USAGE);
894
1140
  return trimmed;
895
1141
  }
1142
+ if ('remote' === key) {
1143
+ const looksLikeGit = /^(https?:\/\/|ssh:\/\/|git@)/.test(trimmed);
1144
+ if (!looksLikeGit) throw new errors_CliError(`远程地址不合法:${raw}`, errors_EXIT.USAGE);
1145
+ return trimmed;
1146
+ }
896
1147
  if ('developer' === key) {
897
1148
  if (!/^[a-z][a-z0-9]*$/.test(trimmed)) throw new errors_CliError(`开发者标识必须是小写字母开头的字母数字串:${raw}`, errors_EXIT.USAGE);
898
1149
  return trimmed;
@@ -901,6 +1152,10 @@ function coerceValue(path, raw) {
901
1152
  if (!ROLE_SET.has(trimmed)) throw new errors_CliError(`角色必须是 ${ROLES.join(' / ')} 之一:${raw}`, errors_EXIT.USAGE);
902
1153
  return trimmed;
903
1154
  }
1155
+ if ('mode' === key) {
1156
+ if (!MODE_SET.has(trimmed)) throw new errors_CliError(`使用模式必须是 ${MODES.join(' / ')} 之一:${raw}`, errors_EXIT.USAGE);
1157
+ return trimmed;
1158
+ }
904
1159
  if ('aliases' === key) return trimmed.split(',').map((item)=>item.trim()).filter((item)=>item.length > 0);
905
1160
  if ('frontend' === key || 'backend' === key) {
906
1161
  const parts = parsePathList(trimmed);
@@ -948,6 +1203,92 @@ function registerSet(program) {
948
1203
  runSet(dotPath, value, options);
949
1204
  });
950
1205
  }
1206
+ function terminal_matched(config, name, kind) {
1207
+ const entry = config.terminals[name] ?? null;
1208
+ return {
1209
+ input: name,
1210
+ matched: null !== entry,
1211
+ matchedBy: null === entry ? null : kind,
1212
+ terminal: null === entry ? null : name,
1213
+ entry,
1214
+ candidates: []
1215
+ };
1216
+ }
1217
+ const SUGGEST_DISTANCE = 3;
1218
+ function suggest(config, target) {
1219
+ if (0 === target.length) return [];
1220
+ const scored = [];
1221
+ for (const [name, entry] of Object.entries(config.terminals)){
1222
+ const pool = [
1223
+ normalizeName(name),
1224
+ ...entry.aliases.map((alias)=>normalizeName(alias))
1225
+ ].filter((item)=>item.length > 0);
1226
+ let best = 1 / 0;
1227
+ for (const candidate of pool){
1228
+ if (candidate.includes(target) || target.includes(candidate)) {
1229
+ best = Math.min(best, 1);
1230
+ continue;
1231
+ }
1232
+ best = Math.min(best, editDistance(candidate, target));
1233
+ }
1234
+ if (best <= SUGGEST_DISTANCE) scored.push({
1235
+ name,
1236
+ score: best
1237
+ });
1238
+ }
1239
+ return scored.sort((left, right)=>left.score - right.score).slice(0, 3).map((item)=>item.name);
1240
+ }
1241
+ function resolveTerminalName(terminals, input) {
1242
+ const raw = input.trim();
1243
+ const names = Object.keys(terminals);
1244
+ const target = normalizeName(raw);
1245
+ const wrap = (name, matchedBy)=>({
1246
+ input: raw,
1247
+ name,
1248
+ matchedBy,
1249
+ candidates: []
1250
+ });
1251
+ if (Object.hasOwn(terminals, raw)) return wrap(raw, 'exact');
1252
+ for (const name of names)if (terminals[name]?.aliases.includes(raw) === true) return wrap(name, 'alias');
1253
+ if (target.length > 0) {
1254
+ const byKey = names.find((name)=>normalizeName(name) === target);
1255
+ if (void 0 !== byKey) return wrap(byKey, 'normalized');
1256
+ for (const name of names)if (terminals[name]?.aliases.some((alias)=>normalizeName(alias) === target) === true) return wrap(name, 'normalized');
1257
+ }
1258
+ return {
1259
+ input: raw,
1260
+ name: null,
1261
+ matchedBy: null,
1262
+ candidates: suggest({
1263
+ terminals
1264
+ }, target)
1265
+ };
1266
+ }
1267
+ function resolveTerminal(config, input) {
1268
+ const match = resolveTerminalName(config.terminals, input);
1269
+ if (null === match.name) return {
1270
+ input: match.input,
1271
+ matched: false,
1272
+ matchedBy: null,
1273
+ terminal: null,
1274
+ entry: null,
1275
+ candidates: match.candidates
1276
+ };
1277
+ return terminal_matched(config, match.name, match.matchedBy ?? 'exact');
1278
+ }
1279
+ function resolveKey(terminals, input) {
1280
+ const match = resolveTerminalName(terminals, input);
1281
+ if (null !== match.name) return match.name;
1282
+ const hint = 0 === match.candidates.length ? '' : `\n最接近:${match.candidates.join('、')}`;
1283
+ throw new errors_CliError(`终端不存在:${input.trim()}${hint}\n查看全部:ylcwf terminal list`, errors_EXIT.NOT_FOUND);
1284
+ }
1285
+ function readTerminals(doc) {
1286
+ const raw = doc.toJS();
1287
+ const section = getIn(raw, [
1288
+ 'terminals'
1289
+ ]);
1290
+ return 'object' == typeof section && null !== section ? section : {};
1291
+ }
951
1292
  const terminal_SIDE_LABEL = {
952
1293
  frontend: '前端',
953
1294
  backend: '后端'
@@ -1006,7 +1347,7 @@ function runTerminalList(options) {
1006
1347
  continue;
1007
1348
  }
1008
1349
  targets.forEach((target, index)=>{
1009
- const mark = existsSync(target) ? picocolors.green(' ✓') : picocolors.red(' ✗');
1350
+ const mark = external_node_fs_existsSync(target) ? picocolors.green(' ✓') : picocolors.red(' ✗');
1010
1351
  const label = 0 === index ? terminal_SIDE_LABEL[side] : ' '.repeat(terminal_SIDE_LABEL[side].length);
1011
1352
  printLine(` ${label} ${target}${mark}`);
1012
1353
  });
@@ -1016,6 +1357,7 @@ function runTerminalList(options) {
1016
1357
  function runTerminalAdd(key, options) {
1017
1358
  const trimmedKey = key.trim();
1018
1359
  if (0 === trimmedKey.length) throw new errors_CliError('终端名不能为空', errors_EXIT.USAGE);
1360
+ if (trimmedKey.includes('.')) throw new errors_CliError('终端名不能包含「.」(与配置路径语法冲突)', errors_EXIT.USAGE);
1019
1361
  const { path: configPath, doc } = obtainDocument(options.config);
1020
1362
  if (void 0 !== getIn(doc.toJS(), [
1021
1363
  'terminals',
@@ -1039,19 +1381,16 @@ function runTerminalAdd(key, options) {
1039
1381
  function runTerminalSetAliases(key, options) {
1040
1382
  const trimmedKey = key.trim();
1041
1383
  const { path: configPath, doc } = obtainDocument(options.config);
1042
- if (void 0 === getIn(doc.toJS(), [
1043
- 'terminals',
1044
- trimmedKey
1045
- ])) throw new errors_CliError(`终端不存在:${trimmedKey}\n新增请用:ylcwf terminal add`, errors_EXIT.NOT_FOUND);
1384
+ const resolvedKey = resolveKey(readTerminals(doc), trimmedKey);
1046
1385
  if (void 0 === options.aliases) throw new errors_CliError('需要指定 --aliases(逗号分隔,整体替换)', errors_EXIT.USAGE);
1047
1386
  doc.setIn([
1048
1387
  'terminals',
1049
- trimmedKey,
1388
+ resolvedKey,
1050
1389
  'aliases'
1051
1390
  ], terminal_splitAliases(options.aliases));
1052
1391
  assertWritable(doc, configPath);
1053
1392
  saveDocument(doc, configPath);
1054
- printLine(`已更新终端别名:${trimmedKey}`);
1393
+ printLine(`已更新终端别名:${resolvedKey}`);
1055
1394
  printLine(`配置文件:${configPath}`);
1056
1395
  }
1057
1396
  function runTerminalRepoAdd(key, options) {
@@ -1059,15 +1398,13 @@ function runTerminalRepoAdd(key, options) {
1059
1398
  const side = parseSide(options.side);
1060
1399
  const target = assertAbsolute(options.path ?? '', '--path');
1061
1400
  const { path: configPath, doc } = obtainDocument(options.config);
1062
- if (void 0 === getIn(doc.toJS(), [
1063
- 'terminals',
1064
- trimmedKey
1065
- ])) throw new errors_CliError(`终端不存在:${trimmedKey}\n新增请用:ylcwf terminal add`, errors_EXIT.NOT_FOUND);
1066
- const list = readSideList(doc, trimmedKey, side);
1401
+ const resolvedKey = resolveKey(readTerminals(doc), trimmedKey);
1402
+ if (resolvedKey !== trimmedKey) printLine(`(按别名匹配到终端:${resolvedKey})`);
1403
+ const list = readSideList(doc, resolvedKey, side);
1067
1404
  if (list.includes(target)) throw new errors_CliError(`${side} 端已存在该仓库:${target}`, errors_EXIT.USAGE);
1068
1405
  doc.setIn([
1069
1406
  'terminals',
1070
- trimmedKey,
1407
+ resolvedKey,
1071
1408
  'repos',
1072
1409
  side
1073
1410
  ], [
@@ -1076,33 +1413,35 @@ function runTerminalRepoAdd(key, options) {
1076
1413
  ]);
1077
1414
  assertWritable(doc, configPath);
1078
1415
  saveDocument(doc, configPath);
1079
- printLine(`已为「${trimmedKey}」的 ${side} 端添加仓库:${target}(共 ${list.length + 1} 个)`);
1416
+ printLine(`已为「${resolvedKey}」的 ${side} 端添加仓库:${target}(共 ${list.length + 1} 个)`);
1080
1417
  }
1081
1418
  function runTerminalRepoRemove(key, options) {
1082
1419
  const trimmedKey = key.trim();
1083
1420
  const side = parseSide(options.side);
1084
1421
  const target = assertAbsolute(options.path ?? '', '--path');
1085
1422
  const { path: configPath, doc } = obtainDocument(options.config);
1086
- const list = readSideList(doc, trimmedKey, side);
1087
- if (0 === list.length) throw new errors_CliError(`终端「${trimmedKey}」的 ${side} 端没有仓库`, errors_EXIT.NOT_FOUND);
1423
+ const resolvedKey = resolveKey(readTerminals(doc), trimmedKey);
1424
+ const list = readSideList(doc, resolvedKey, side);
1425
+ if (0 === list.length) throw new errors_CliError(`终端「${resolvedKey}」的 ${side} 端没有仓库`, errors_EXIT.NOT_FOUND);
1088
1426
  if (!list.includes(target)) throw new errors_CliError(`${side} 端不存在该仓库:${target}\n现有:\n${list.map((item, index)=>` ${index + 1}) ${item}`).join('\n')}`, errors_EXIT.NOT_FOUND);
1089
1427
  const next = list.filter((item)=>item !== target);
1090
1428
  doc.setIn([
1091
1429
  'terminals',
1092
- trimmedKey,
1430
+ resolvedKey,
1093
1431
  'repos',
1094
1432
  side
1095
1433
  ], next);
1096
1434
  assertWritable(doc, configPath);
1097
1435
  saveDocument(doc, configPath);
1098
- printLine(`已移除「${trimmedKey}」的 ${side} 端仓库:${target}(剩余 ${next.length} 个)`);
1436
+ printLine(`已移除「${resolvedKey}」的 ${side} 端仓库:${target}(剩余 ${next.length} 个)`);
1099
1437
  }
1100
1438
  function runTerminalRepoList(key, options) {
1101
1439
  const trimmedKey = key.trim();
1102
1440
  const format = parseFormat(options.format);
1103
1441
  const ready = requireConfig(options.config);
1104
- const terminal = ready.config.terminals[trimmedKey];
1105
- if (void 0 === terminal) throw new errors_CliError(`终端不存在:${trimmedKey}`, errors_EXIT.NOT_FOUND);
1442
+ const resolvedKey = resolveKey(ready.config.terminals, trimmedKey);
1443
+ const terminal = ready.config.terminals[resolvedKey];
1444
+ if (void 0 === terminal) throw new errors_CliError(`终端不存在:${resolvedKey}`, errors_EXIT.NOT_FOUND);
1106
1445
  const sides = void 0 === options.side ? [
1107
1446
  ...SIDES
1108
1447
  ] : [
@@ -1112,7 +1451,7 @@ function runTerminalRepoList(key, options) {
1112
1451
  const payload = {};
1113
1452
  for (const side of sides)payload[side] = terminal.repos[side];
1114
1453
  printJson({
1115
- terminal: trimmedKey,
1454
+ terminal: resolvedKey,
1116
1455
  repos: payload
1117
1456
  });
1118
1457
  return;
@@ -1124,30 +1463,30 @@ function runTerminalRepoList(key, options) {
1124
1463
  continue;
1125
1464
  }
1126
1465
  targets.forEach((target, index)=>{
1127
- printLine(`${side} ${index + 1}) ${target}${existsSync(target) ? '' : ' (路径不存在)'}`);
1466
+ printLine(`${side} ${index + 1}) ${target}${external_node_fs_existsSync(target) ? '' : ' (路径不存在)'}`);
1128
1467
  });
1129
1468
  }
1130
1469
  }
1131
1470
  async function runTerminalRemove(key, options) {
1132
1471
  const trimmedKey = key.trim();
1133
1472
  const ready = requireConfig(options.config);
1134
- if (void 0 === ready.config.terminals[trimmedKey]) throw new errors_CliError(`终端不存在:${trimmedKey}`, errors_EXIT.NOT_FOUND);
1473
+ const resolvedKey = resolveKey(ready.config.terminals, trimmedKey);
1135
1474
  if (true !== options.yes) {
1136
1475
  if (true !== process.stdin.isTTY) throw new errors_CliError('非交互环境删除终端需要显式加 --yes', errors_EXIT.USAGE);
1137
1476
  const { confirm } = await import("@clack/prompts");
1138
1477
  const answer = await confirm({
1139
- message: `确认删除终端「${trimmedKey}」?`,
1478
+ message: `确认删除终端「${resolvedKey}」?`,
1140
1479
  initialValue: false
1141
1480
  });
1142
1481
  if (true !== answer) return void printLine('已取消');
1143
1482
  }
1144
1483
  ready.doc.deleteIn([
1145
1484
  'terminals',
1146
- trimmedKey
1485
+ resolvedKey
1147
1486
  ]);
1148
1487
  assertWritable(ready.doc, ready.path);
1149
1488
  saveDocument(ready.doc, ready.path);
1150
- printLine(`已删除终端:${trimmedKey}`);
1489
+ printLine(`已删除终端:${resolvedKey}`);
1151
1490
  }
1152
1491
  function registerTerminal(program) {
1153
1492
  const terminal = program.command('terminal').description('维护 PRD 终端 → 本地仓库映射');
@@ -1174,92 +1513,731 @@ function registerTerminal(program) {
1174
1513
  runTerminalRepoRemove(key, options);
1175
1514
  });
1176
1515
  }
1177
- function matched(config, name, kind) {
1178
- const entry = config.terminals[name] ?? null;
1516
+ const SAFE_SEGMENT = /^[A-Za-z0-9._\-\u4e00-\u9fa5]+$/;
1517
+ function safeSegment(value, label) {
1518
+ const trimmed = value.trim();
1519
+ if (!SAFE_SEGMENT.test(trimmed) || '.' === trimmed || '..' === trimmed) throw new errors_CliError(`${label} 不合法:${value}`, errors_EXIT.USAGE);
1520
+ return trimmed;
1521
+ }
1522
+ function buildCommitMessage(iteration, action, taskIds, _action) {
1523
+ const meta = ACTION_META[action];
1524
+ return `docs(${iteration}): ${meta.label} ${taskIds.join(',')}(${meta.from}→${meta.to})`;
1525
+ }
1526
+ function nowStamp() {
1527
+ const now = new Date();
1528
+ const pad = (value)=>String(value).padStart(2, '0');
1529
+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
1530
+ }
1531
+ const ACTION_META = {
1532
+ start: {
1533
+ label: '开始实施',
1534
+ from: '未开始',
1535
+ to: '进行中'
1536
+ },
1537
+ submit: {
1538
+ label: '提交验收',
1539
+ from: '进行中',
1540
+ to: '待验收'
1541
+ },
1542
+ accept: {
1543
+ label: '验收通过',
1544
+ from: '待验收',
1545
+ to: '已完成'
1546
+ },
1547
+ reject: {
1548
+ label: '验收驳回',
1549
+ from: '待验收',
1550
+ to: '进行中'
1551
+ }
1552
+ };
1553
+ function commitInDocsRepo(docsRoot, file, message, push) {
1554
+ const run = (args)=>{
1555
+ try {
1556
+ const output = execFileSync('git', args, {
1557
+ cwd: docsRoot,
1558
+ encoding: 'utf8',
1559
+ stdio: [
1560
+ 'ignore',
1561
+ 'pipe',
1562
+ 'pipe'
1563
+ ]
1564
+ });
1565
+ return {
1566
+ ok: true,
1567
+ output
1568
+ };
1569
+ } catch (error) {
1570
+ const stderr = error.stderr ?? '';
1571
+ return {
1572
+ ok: false,
1573
+ output: stderr.trim() || String(error)
1574
+ };
1575
+ }
1576
+ };
1577
+ const inside = run([
1578
+ 'rev-parse',
1579
+ '--is-inside-work-tree'
1580
+ ]);
1581
+ if (!inside.ok || 'true' !== inside.output.trim()) return {
1582
+ committed: false,
1583
+ pushed: false,
1584
+ message: '文档仓库不是 git 仓库,已跳过提交'
1585
+ };
1586
+ let realRoot = docsRoot;
1587
+ let realFile = file;
1588
+ try {
1589
+ realRoot = realpathSync(docsRoot);
1590
+ realFile = realpathSync(file);
1591
+ } catch {}
1592
+ const relativePath = external_node_path_relative(realRoot, realFile);
1593
+ if (relativePath.startsWith('..') || isAbsolute(relativePath)) return {
1594
+ committed: false,
1595
+ pushed: false,
1596
+ message: '目标文件不在文档仓库内,已跳过提交'
1597
+ };
1598
+ const added = run([
1599
+ 'add',
1600
+ '--',
1601
+ relativePath
1602
+ ]);
1603
+ if (!added.ok) return {
1604
+ committed: false,
1605
+ pushed: false,
1606
+ message: `git add 失败:${added.output.split('\n')[0] ?? ''}`
1607
+ };
1608
+ const committed = run([
1609
+ 'commit',
1610
+ '-m',
1611
+ message,
1612
+ '--',
1613
+ relativePath
1614
+ ]);
1615
+ if (!committed.ok) {
1616
+ const firstLine = committed.output.split('\n')[0] ?? '';
1617
+ return {
1618
+ committed: false,
1619
+ pushed: false,
1620
+ message: `提交未完成:${firstLine}`
1621
+ };
1622
+ }
1623
+ if (!push) return {
1624
+ committed: true,
1625
+ pushed: false,
1626
+ message: '已提交(未推送)'
1627
+ };
1628
+ const pushed = run([
1629
+ 'push'
1630
+ ]);
1631
+ if (!pushed.ok) return {
1632
+ committed: true,
1633
+ pushed: false,
1634
+ message: `已提交但推送失败,请手动处理:${pushed.output.split('\n')[0] ?? ''}`
1635
+ };
1179
1636
  return {
1180
- input: name,
1181
- matched: null !== entry,
1182
- matchedBy: null === entry ? null : kind,
1183
- terminal: null === entry ? null : name,
1184
- entry,
1185
- candidates: []
1637
+ committed: true,
1638
+ pushed: true,
1639
+ message: '已提交并推送'
1186
1640
  };
1187
1641
  }
1188
- const SUGGEST_DISTANCE = 3;
1189
- function suggest(config, target) {
1190
- if (0 === target.length) return [];
1191
- const scored = [];
1192
- for (const [name, entry] of Object.entries(config.terminals)){
1193
- const pool = [
1194
- normalizeName(name),
1195
- ...entry.aliases.map((alias)=>normalizeName(alias))
1196
- ].filter((item)=>item.length > 0);
1197
- let best = 1 / 0;
1198
- for (const candidate of pool){
1199
- if (candidate.includes(target) || target.includes(candidate)) {
1200
- best = Math.min(best, 1);
1201
- continue;
1202
- }
1203
- best = Math.min(best, editDistance(candidate, target));
1204
- }
1205
- if (best <= SUGGEST_DISTANCE) scored.push({
1206
- name,
1207
- score: best
1642
+ function appendHistory(entry) {
1643
+ try {
1644
+ const target = historyPath();
1645
+ mkdirSync(dirname(target), {
1646
+ recursive: true
1208
1647
  });
1648
+ appendFileSync(target, `${JSON.stringify({
1649
+ at: new Date().toISOString(),
1650
+ ...entry
1651
+ })}\n`, 'utf8');
1652
+ } catch {}
1653
+ }
1654
+ function readTaskHistory(options) {
1655
+ const target = historyPath();
1656
+ if (!external_node_fs_existsSync(target)) return [];
1657
+ const limit = options.limit ?? 5;
1658
+ const lines = readFileSync(target, 'utf8').trim().split('\n').filter((line)=>line.length > 0);
1659
+ const entries = [];
1660
+ for(let index = lines.length - 1; index >= 0 && entries.length < limit; index -= 1){
1661
+ const line = lines[index];
1662
+ if (void 0 !== line) try {
1663
+ const parsed = JSON.parse(line);
1664
+ if (parsed.iteration.toLowerCase() !== options.iteration.toLowerCase()) continue;
1665
+ if (parsed.developer !== options.developer) continue;
1666
+ if (void 0 !== options.taskId && parsed.taskId !== options.taskId) continue;
1667
+ entries.push(parsed);
1668
+ } catch {
1669
+ continue;
1670
+ }
1209
1671
  }
1210
- return scored.sort((left, right)=>left.score - right.score).slice(0, 3).map((item)=>item.name);
1672
+ return entries;
1211
1673
  }
1212
- function resolveTerminal(config, input) {
1213
- const raw = input.trim();
1214
- const names = Object.keys(config.terminals);
1215
- if (Object.hasOwn(config.terminals, raw)) return matched(config, raw, 'exact');
1216
- for (const name of names){
1217
- const entry = config.terminals[name];
1218
- if (void 0 !== entry) {
1219
- if (entry.aliases.includes(raw)) return matched(config, name, 'alias');
1674
+ const TASK_HEADERS = {
1675
+ id: '任务编号',
1676
+ requirement: '关联需求编号',
1677
+ selfTest: 'AI自测状态',
1678
+ acceptance: '开发人工验收',
1679
+ status: '任务状态',
1680
+ updatedAt: '最后更新'
1681
+ };
1682
+ const REQUIREMENT_HEADERS = {
1683
+ id: '需求编号',
1684
+ status: '开发状态',
1685
+ progress: '开发进度(%)',
1686
+ updatedAt: '最后更新'
1687
+ };
1688
+ function columnIndex(headerCells, name) {
1689
+ const index = headerCells.findIndex((cell)=>cell.trim() === name);
1690
+ if (index < 0) throw new errors_CliError(`表格缺少列「${name}」,无法安全写入`, errors_EXIT.INVALID);
1691
+ return index;
1692
+ }
1693
+ function splitRow(line) {
1694
+ const trimmed = line.trim();
1695
+ const inner = trimmed.startsWith('|') ? trimmed.slice(1) : trimmed;
1696
+ const withoutTail = inner.endsWith('|') ? inner.slice(0, -1) : inner;
1697
+ return withoutTail.split('|').map((cell)=>cell.trim());
1698
+ }
1699
+ function joinRow(cells) {
1700
+ return `| ${cells.join(' | ')} |`;
1701
+ }
1702
+ function canSubmit(selfTest) {
1703
+ const text = selfTest.trim();
1704
+ return '通过' === text || text.startsWith('免测');
1705
+ }
1706
+ function sectionRange(lines, heading) {
1707
+ const start = lines.findIndex((line)=>line.trim() === heading);
1708
+ if (start < 0) throw new errors_CliError(`文档缺少章节「${heading}」,无法安全写入`, errors_EXIT.INVALID);
1709
+ let end = lines.length;
1710
+ for(let index = start + 1; index < lines.length; index += 1){
1711
+ const line = lines[index] ?? '';
1712
+ if (/^##\s+/.test(line) || /^#\s+/.test(line)) {
1713
+ end = index;
1714
+ break;
1220
1715
  }
1221
1716
  }
1222
- const target = normalizeName(raw);
1223
- if (target.length > 0) {
1224
- const byKey = names.find((name)=>normalizeName(name) === target);
1225
- if (void 0 !== byKey) return matched(config, byKey, 'normalized');
1226
- for (const name of names){
1227
- const entry = config.terminals[name];
1228
- if (void 0 !== entry) {
1229
- if (entry.aliases.some((alias)=>normalizeName(alias) === target)) return matched(config, name, 'normalized');
1230
- }
1717
+ return [
1718
+ start,
1719
+ end
1720
+ ];
1721
+ }
1722
+ function parseTaskRows(lines) {
1723
+ const [start, end] = sectionRange(lines, '## 三、任务清单');
1724
+ let header = null;
1725
+ const rows = [];
1726
+ for(let index = start; index < end; index += 1){
1727
+ const line = lines[index] ?? '';
1728
+ if (!line.trim().startsWith('|')) continue;
1729
+ const cells = splitRow(line);
1730
+ if (null === header) {
1731
+ if (cells.includes(TASK_HEADERS.id)) header = cells;
1732
+ continue;
1231
1733
  }
1734
+ if (cells.every((cell)=>/^:?-{2,}:?$/.test(cell))) continue;
1735
+ const taskId = cells[columnIndex(header, TASK_HEADERS.id)] ?? '';
1736
+ if (/^#\d{3,6}-T\d+$/.test(taskId)) rows.push({
1737
+ index,
1738
+ cells,
1739
+ taskId,
1740
+ status: cells[columnIndex(header, TASK_HEADERS.status)] ?? '',
1741
+ acceptance: cells[columnIndex(header, TASK_HEADERS.acceptance)] ?? '',
1742
+ selfTest: cells[columnIndex(header, TASK_HEADERS.selfTest)] ?? '',
1743
+ requirementId: cells[columnIndex(header, TASK_HEADERS.requirement)] ?? ''
1744
+ });
1232
1745
  }
1746
+ if (null === header) throw new errors_CliError('未找到任务清单表头,无法安全写入', errors_EXIT.INVALID);
1233
1747
  return {
1234
- input: raw,
1235
- matched: false,
1236
- matchedBy: null,
1237
- terminal: null,
1238
- entry: null,
1239
- candidates: suggest(config, target)
1748
+ header,
1749
+ rows
1240
1750
  };
1241
1751
  }
1242
- const FIELDS = [
1243
- 'path',
1244
- 'exists',
1245
- 'terminal',
1246
- 'repos'
1247
- ];
1248
- function isSide(value) {
1249
- return SIDES.some((side)=>side === value);
1752
+ function parseRequirementRows(lines) {
1753
+ const [start, end] = sectionRange(lines, '## 二、需求清单');
1754
+ let header = null;
1755
+ const rows = [];
1756
+ for(let index = start; index < end; index += 1){
1757
+ const line = lines[index] ?? '';
1758
+ if (!line.trim().startsWith('|')) continue;
1759
+ const cells = splitRow(line);
1760
+ if (null === header) {
1761
+ if (cells.includes(REQUIREMENT_HEADERS.id)) header = cells;
1762
+ continue;
1763
+ }
1764
+ if (cells.every((cell)=>/^:?-{2,}:?$/.test(cell))) continue;
1765
+ const id = cells[columnIndex(header, REQUIREMENT_HEADERS.id)] ?? '';
1766
+ if (/^#\d{3,6}$/.test(id)) rows.push({
1767
+ index,
1768
+ cells,
1769
+ id
1770
+ });
1771
+ }
1772
+ if (null === header) throw new errors_CliError('未找到需求清单表头,无法安全写入', errors_EXIT.INVALID);
1773
+ return {
1774
+ header,
1775
+ rows
1776
+ };
1250
1777
  }
1251
- function isField(value) {
1252
- return FIELDS.some((field)=>field === value);
1778
+ function aggregateRequirementStatus(statuses) {
1779
+ if (0 === statuses.length) return '未开始';
1780
+ if (statuses.every((status)=>'未开始' === status)) return '未开始';
1781
+ if (statuses.every((status)=>'已完成' === status)) return '已完成';
1782
+ return '进行中';
1253
1783
  }
1254
- function buildRepoView(terminal) {
1255
- const view = {
1256
- frontend: [],
1257
- backend: []
1258
- };
1259
- for (const side of SIDES)view[side] = terminal.repos[side].map((path)=>({
1260
- path,
1261
- exists: existsSync(path)
1262
- }));
1784
+ function updateDetailBlock(lines, taskId, updates) {
1785
+ const headingIndex = lines.findIndex((line)=>line.trim().startsWith(`### [${taskId}]`));
1786
+ if (headingIndex < 0) throw new errors_CliError(`任务 ${taskId} 缺少第四章详情区块,无法同步状态`, errors_EXIT.INVALID);
1787
+ let end = lines.length;
1788
+ for(let index = headingIndex + 1; index < lines.length; index += 1)if (/^###\s+/.test(lines[index] ?? '') || /^##\s+/.test(lines[index] ?? '')) {
1789
+ end = index;
1790
+ break;
1791
+ }
1792
+ const next = [
1793
+ ...lines
1794
+ ];
1795
+ for(let index = headingIndex; index < end; index += 1){
1796
+ const line = lines[index] ?? '';
1797
+ const match = /^(\s*-\s+\*\*(.+?)\*\*\s*[::]\s*)(.*)$/.exec(line);
1798
+ if (null === match) continue;
1799
+ const field = match[2] ?? '';
1800
+ const replacement = updates[field];
1801
+ if (void 0 !== replacement) next[index] = `${match[1] ?? ''}${replacement}`;
1802
+ }
1803
+ return next;
1804
+ }
1805
+ function realIterationName(docsRoot, iteration) {
1806
+ try {
1807
+ const match = readdirSync(docsRoot).find((entry)=>entry.toLowerCase() === iteration.toLowerCase());
1808
+ return match ?? iteration;
1809
+ } catch {
1810
+ return iteration;
1811
+ }
1812
+ }
1813
+ function loadDoc(docsRoot, iterationRaw, developerRaw) {
1814
+ const iteration = realIterationName(docsRoot, safeSegment(iterationRaw, '迭代目录'));
1815
+ const developer = safeSegment(developerRaw, '开发者标识');
1816
+ const file = external_node_path_join(docsRoot, iteration, `${developer}.md`);
1817
+ if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${iteration}/${developer}.md`, errors_EXIT.NOT_FOUND);
1818
+ const mtime = statSync(file).mtimeMs;
1819
+ const original = readFileSync(file, 'utf8');
1820
+ return {
1821
+ file,
1822
+ mtime,
1823
+ original,
1824
+ lines: original.split('\n')
1825
+ };
1826
+ }
1827
+ function computeUpdate(lines, taskId, action) {
1828
+ const { header, rows } = parseTaskRows(lines);
1829
+ const target = rows.find((row)=>row.taskId === taskId);
1830
+ if (void 0 === target) throw new errors_CliError(`任务清单中未找到 ${taskId}`, errors_EXIT.NOT_FOUND);
1831
+ const statusIndex = columnIndex(header, TASK_HEADERS.status);
1832
+ const acceptanceIndex = columnIndex(header, TASK_HEADERS.acceptance);
1833
+ const currentStatus = target.status;
1834
+ const currentAcceptance = target.acceptance;
1835
+ const meta = ACTION_META[action];
1836
+ if (currentStatus !== meta.from) throw new errors_CliError(`任务 ${taskId} 当前状态为「${currentStatus}」,无法执行「${meta.label}」(要求「${meta.from}」)`, errors_EXIT.USAGE);
1837
+ if ('submit' === action && !canSubmit(target.selfTest)) throw new errors_CliError(`任务 ${taskId} 的 AI 自测状态为「${target.selfTest}」,未通过自测不能提交验收`, errors_EXIT.USAGE);
1838
+ const nextStatus = meta.to;
1839
+ const nextAcceptance = 'accept' === action ? '验收通过' : 'reject' === action ? '验收驳回' : currentAcceptance;
1840
+ const changes = [];
1841
+ if (nextStatus !== currentStatus) changes.push(`${taskId} 任务状态:${currentStatus} → ${nextStatus}`);
1842
+ if (nextAcceptance !== currentAcceptance) changes.push(`${taskId} 开发人工验收:${currentAcceptance} → ${nextAcceptance}`);
1843
+ const stamp = nowStamp();
1844
+ const updated = [
1845
+ ...lines
1846
+ ];
1847
+ const taskCells = [
1848
+ ...target.cells
1849
+ ];
1850
+ taskCells[statusIndex] = nextStatus;
1851
+ taskCells[acceptanceIndex] = nextAcceptance;
1852
+ taskCells[columnIndex(header, TASK_HEADERS.updatedAt)] = stamp;
1853
+ updated[target.index] = joinRow(taskCells);
1854
+ const withDetail = updateDetailBlock(updated, taskId, {
1855
+ 任务状态: nextStatus,
1856
+ 人工验收: nextAcceptance
1857
+ });
1858
+ const requirementStatuses = rows.filter((row)=>row.requirementId === target.requirementId).map((row)=>row.taskId === taskId ? nextStatus : row.status);
1859
+ const requirementStatus = aggregateRequirementStatus(requirementStatuses);
1860
+ const completed = requirementStatuses.filter((status)=>'已完成' === status).length;
1861
+ const progress = 0 === requirementStatuses.length ? 0 : Math.round(completed / requirementStatuses.length * 100);
1862
+ const requirementParse = parseRequirementRows(withDetail);
1863
+ const requirementTarget = requirementParse.rows.find((row)=>row.id === target.requirementId);
1864
+ if (void 0 === requirementTarget) throw new errors_CliError(`需求清单中未找到 ${target.requirementId}`, errors_EXIT.NOT_FOUND);
1865
+ const requirementCells = [
1866
+ ...requirementTarget.cells
1867
+ ];
1868
+ const previousStatus = requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.status)] ?? '';
1869
+ const previousProgress = requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.progress)] ?? '';
1870
+ requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.status)] = requirementStatus;
1871
+ requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.progress)] = String(progress);
1872
+ if (previousStatus !== requirementStatus || previousProgress !== String(progress)) requirementCells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.updatedAt)] = stamp;
1873
+ withDetail[requirementTarget.index] = joinRow(requirementCells);
1874
+ if (previousStatus !== requirementStatus) changes.push(`需求 ${target.requirementId} 开发状态:${previousStatus} → ${requirementStatus}`);
1875
+ if (previousProgress !== String(progress)) changes.push(`需求 ${target.requirementId} 开发进度:${previousProgress}% → ${progress}%`);
1876
+ return {
1877
+ lines: withDetail,
1878
+ changes
1879
+ };
1880
+ }
1881
+ function commit(context, lines, changes, message, iteration, developer, action, taskIds, options) {
1882
+ if (statSync(context.file).mtimeMs !== context.mtime) throw new errors_CliError('文件已被外部修改,请刷新后重试', errors_EXIT.INVALID);
1883
+ const output = lines.join('\n');
1884
+ if (output === context.original) return {
1885
+ ok: true,
1886
+ message: '状态未发生变化',
1887
+ changes: [],
1888
+ file: context.file
1889
+ };
1890
+ writeFileSync(context.file, output, 'utf8');
1891
+ const violation = validateAfterWrite(dirname(context.file), iteration, developer);
1892
+ if (null !== violation) {
1893
+ writeFileSync(context.file, context.original, 'utf8');
1894
+ throw new errors_CliError(`写入被校验器拒绝,已回滚:${violation}`, errors_EXIT.INVALID);
1895
+ }
1896
+ appendHistory({
1897
+ iteration,
1898
+ developer,
1899
+ taskId: taskIds.join(','),
1900
+ action,
1901
+ changes
1902
+ });
1903
+ const git = options.policy.commit ? commitInDocsRepo(options.docsRoot, context.file, options.commitMessage, options.policy.push) : void 0;
1904
+ return {
1905
+ ok: true,
1906
+ message,
1907
+ changes,
1908
+ file: context.file,
1909
+ git
1910
+ };
1911
+ }
1912
+ function applyBatchAction(options) {
1913
+ if (0 === options.taskIds.length) throw new errors_CliError('未选择任务', errors_EXIT.USAGE);
1914
+ const context = loadDoc(options.docsRoot, options.iteration, options.developer);
1915
+ let lines = context.lines;
1916
+ const changes = [];
1917
+ for (const taskId of options.taskIds){
1918
+ const result = computeUpdate(lines, taskId, options.action);
1919
+ lines = result.lines;
1920
+ changes.push(...result.changes);
1921
+ }
1922
+ return commit(context, lines, changes, `已对 ${options.taskIds.length} 个任务执行「${ACTION_META[options.action].label}」`, safeSegment(options.iteration, '迭代目录'), safeSegment(options.developer, '开发者标识'), options.action, options.taskIds, {
1923
+ docsRoot: options.docsRoot,
1924
+ policy: options.policy,
1925
+ commitMessage: buildCommitMessage(options.iteration, options.action, options.taskIds, options.action)
1926
+ });
1927
+ }
1928
+ function applyTaskAction(options) {
1929
+ const context = loadDoc(options.docsRoot, options.iteration, options.developer);
1930
+ const result = computeUpdate(context.lines, options.taskId, options.action);
1931
+ return commit(context, result.lines, result.changes, `已执行「${ACTION_META[options.action].label}」`, safeSegment(options.iteration, '迭代目录'), safeSegment(options.developer, '开发者标识'), options.action, [
1932
+ options.taskId
1933
+ ], {
1934
+ docsRoot: options.docsRoot,
1935
+ policy: options.policy,
1936
+ commitMessage: buildCommitMessage(options.iteration, options.action, [
1937
+ options.taskId
1938
+ ], options.action)
1939
+ });
1940
+ }
1941
+ function validateAfterWrite(docsRoot, iteration, developer) {
1942
+ const script = external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py');
1943
+ if (!external_node_fs_existsSync(script)) return null;
1944
+ const bin = external_node_fs_existsSync('/usr/bin/python3') ? '/usr/bin/python3' : 'python3';
1945
+ try {
1946
+ const stdout = execFileSync(bin, [
1947
+ script,
1948
+ '--docs-root',
1949
+ docsRoot,
1950
+ '--iteration',
1951
+ iteration,
1952
+ '--developer',
1953
+ developer,
1954
+ '--format',
1955
+ 'json'
1956
+ ], {
1957
+ encoding: 'utf8',
1958
+ timeout: 15000,
1959
+ maxBuffer: 16777216
1960
+ });
1961
+ const payload = JSON.parse(stdout);
1962
+ const first = payload.errors?.[0];
1963
+ return first?.message ?? null;
1964
+ } catch (error) {
1965
+ const stdout = error.stdout ?? '';
1966
+ try {
1967
+ const payload = JSON.parse(stdout);
1968
+ return payload.errors?.[0]?.message ?? '校验器未通过';
1969
+ } catch {
1970
+ return null;
1971
+ }
1972
+ }
1973
+ }
1974
+ function recalcRequirements(options) {
1975
+ const context = loadDoc(options.docsRoot, options.iteration, options.developer);
1976
+ const { rows: taskRows } = parseTaskRows(context.lines);
1977
+ const requirementParse = parseRequirementRows(context.lines);
1978
+ const lines = [
1979
+ ...context.lines
1980
+ ];
1981
+ const changes = [];
1982
+ for (const requirement of requirementParse.rows){
1983
+ const own = taskRows.filter((row)=>row.requirementId === requirement.id);
1984
+ const status = aggregateRequirementStatus(own.map((row)=>row.status));
1985
+ const completed = own.filter((row)=>'已完成' === row.status).length;
1986
+ const progress = 0 === own.length ? 0 : Math.round(completed / own.length * 100);
1987
+ const cells = [
1988
+ ...requirement.cells
1989
+ ];
1990
+ const previousStatus = cells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.status)] ?? '';
1991
+ const previousProgress = cells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.progress)] ?? '';
1992
+ if (previousStatus !== status || previousProgress !== String(progress)) {
1993
+ cells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.status)] = status;
1994
+ cells[columnIndex(requirementParse.header, REQUIREMENT_HEADERS.progress)] = String(progress);
1995
+ lines[requirement.index] = joinRow(cells);
1996
+ if (previousStatus !== status) changes.push(`${requirement.id} 开发状态:${previousStatus} → ${status}`);
1997
+ if (previousProgress !== String(progress)) changes.push(`${requirement.id} 开发进度:${previousProgress}% → ${progress}%`);
1998
+ }
1999
+ }
2000
+ if (true === options.dryRun || 0 === changes.length) return {
2001
+ changes,
2002
+ file: context.file
2003
+ };
2004
+ return {
2005
+ changes,
2006
+ file: commit(context, lines, changes, `已重算 ${requirementParse.rows.length} 个需求的状态与进度`, safeSegment(options.iteration, '迭代目录'), safeSegment(options.developer, '开发者标识'), 'start', [], {
2007
+ docsRoot: options.docsRoot,
2008
+ policy: {
2009
+ commit: false,
2010
+ push: false
2011
+ },
2012
+ commitMessage: `docs(${options.iteration}): 重算需求状态与进度`
2013
+ }).file
2014
+ };
2015
+ }
2016
+ function availableActions(options) {
2017
+ const iteration = safeSegment(options.iteration, '迭代目录');
2018
+ const developer = safeSegment(options.developer, '开发者标识');
2019
+ const file = external_node_path_join(options.docsRoot, iteration, `${developer}.md`);
2020
+ if (!external_node_fs_existsSync(file)) return {};
2021
+ const lines = readFileSync(file, 'utf8').split('\n');
2022
+ const { rows } = parseTaskRows(lines);
2023
+ const result = {};
2024
+ for (const row of rows){
2025
+ const list = [];
2026
+ if ('未开始' === row.status) list.push({
2027
+ action: 'start',
2028
+ enabled: true,
2029
+ reason: ''
2030
+ });
2031
+ if ('进行中' === row.status) {
2032
+ const ok = canSubmit(row.selfTest);
2033
+ list.push({
2034
+ action: 'submit',
2035
+ enabled: ok,
2036
+ reason: ok ? '' : `AI 自测为「${row.selfTest}」,需先通过自测`
2037
+ });
2038
+ }
2039
+ if ('待验收' === row.status) {
2040
+ list.push({
2041
+ action: 'accept',
2042
+ enabled: true,
2043
+ reason: ''
2044
+ });
2045
+ list.push({
2046
+ action: 'reject',
2047
+ enabled: true,
2048
+ reason: ''
2049
+ });
2050
+ }
2051
+ result[row.taskId] = list;
2052
+ }
2053
+ return result;
2054
+ }
2055
+ function resolveIteration(options, docsRoot) {
2056
+ const explicit = options.iteration?.trim();
2057
+ if (void 0 !== explicit && explicit.length > 0) return explicit;
2058
+ const cwd = process.cwd();
2059
+ if (cwd.startsWith(docsRoot)) {
2060
+ const relative = cwd.slice(docsRoot.length).split('/').filter((item)=>item.length > 0);
2061
+ const first = relative[0];
2062
+ if (void 0 !== first) return first;
2063
+ }
2064
+ throw new errors_CliError('缺少 --iteration(迭代目录名),或在文档仓库的迭代目录内执行', errors_EXIT.USAGE);
2065
+ }
2066
+ function resolveDeveloper(options, configured) {
2067
+ const explicit = options.developer?.trim();
2068
+ const target = void 0 !== explicit && explicit.length > 0 ? explicit : configured;
2069
+ if (target !== configured) throw new errors_CliError(`只能修改自己的任务文档(当前身份:${configured})`, errors_EXIT.USAGE);
2070
+ return target;
2071
+ }
2072
+ function requireWriteContext(options) {
2073
+ const ready = requireConfig(options.config);
2074
+ const config = ready.config;
2075
+ if ('developer' !== config.profile.mode) throw new errors_CliError('干系人模式不支持修改任务状态', errors_EXIT.USAGE);
2076
+ if (0 === config.docs.root.trim().length) throw new errors_CliError('未配置文档仓库:请先设置 docs.root', errors_EXIT.NOT_FOUND);
2077
+ const base = config.docs.git?.cli ?? {
2078
+ commit: true,
2079
+ push: false
2080
+ };
2081
+ const policy = {
2082
+ commit: options.commit ?? base.commit,
2083
+ push: options.push ?? base.push
2084
+ };
2085
+ if (policy.push) policy.commit = true;
2086
+ return {
2087
+ docsRoot: config.docs.root,
2088
+ developer: resolveDeveloper(options, config.profile.developer),
2089
+ policy
2090
+ };
2091
+ }
2092
+ function runAction(action, taskId, options) {
2093
+ const { docsRoot, developer, policy } = requireWriteContext(options);
2094
+ const iteration = resolveIteration(options, docsRoot);
2095
+ const format = parseFormat(options.format);
2096
+ if (true === options.dryRun) {
2097
+ const actions = availableActions({
2098
+ docsRoot,
2099
+ iteration,
2100
+ developer
2101
+ });
2102
+ const available = actions[taskId] ?? [];
2103
+ const option = available.find((item)=>item.action === action);
2104
+ if (void 0 === option) throw new errors_CliError(`任务 ${taskId} 当前不可执行「${ACTION_META[action].label}」`, errors_EXIT.USAGE);
2105
+ if (!option.enabled) throw new errors_CliError(option.reason, errors_EXIT.USAGE);
2106
+ if ('json' === format) return void printJson({
2107
+ dryRun: true,
2108
+ taskId,
2109
+ action,
2110
+ allowed: true
2111
+ });
2112
+ printLine(`将执行:${taskId} ${ACTION_META[action].label}(未写入,--dry-run)`);
2113
+ return;
2114
+ }
2115
+ const result = applyTaskAction({
2116
+ docsRoot,
2117
+ iteration,
2118
+ developer,
2119
+ taskId,
2120
+ action,
2121
+ policy
2122
+ });
2123
+ if ('json' === format) return void printJson(result);
2124
+ printLine(result.message);
2125
+ for (const change of result.changes)printLine(` · ${change}`);
2126
+ printLine(`文档:${result.file}`);
2127
+ if (void 0 !== result.git) printLine(`git:${result.git.message}`);
2128
+ }
2129
+ function runActions(options) {
2130
+ const { docsRoot, developer } = requireWriteContext(options);
2131
+ const iteration = resolveIteration(options, docsRoot);
2132
+ const actions = availableActions({
2133
+ docsRoot,
2134
+ iteration,
2135
+ developer
2136
+ });
2137
+ const format = parseFormat(options.format);
2138
+ if ('json' === format) return void printJson({
2139
+ iteration,
2140
+ developer,
2141
+ actions
2142
+ });
2143
+ const entries = Object.entries(actions);
2144
+ if (0 === entries.length) return void printLine('没有可操作的任务');
2145
+ for (const [taskId, list] of entries){
2146
+ const labels = 0 === list.length ? '—' : list.map((item)=>`${ACTION_META[item.action].label}${item.enabled ? '' : `(不可用:${item.reason})`}`).join('、');
2147
+ printLine(`${taskId} ${labels}`);
2148
+ }
2149
+ }
2150
+ function runBatch(action, taskIds, options) {
2151
+ const { docsRoot, developer, policy } = requireWriteContext(options);
2152
+ const iteration = resolveIteration(options, docsRoot);
2153
+ const format = parseFormat(options.format);
2154
+ const result = applyBatchAction({
2155
+ docsRoot,
2156
+ iteration,
2157
+ developer,
2158
+ taskIds,
2159
+ action,
2160
+ policy
2161
+ });
2162
+ if ('json' === format) return void printJson(result);
2163
+ printLine(result.message);
2164
+ for (const change of result.changes)printLine(` · ${change}`);
2165
+ if (void 0 !== result.git) printLine(`git:${result.git.message}`);
2166
+ }
2167
+ function runHistory(taskId, options) {
2168
+ const { docsRoot, developer } = requireWriteContext(options);
2169
+ const iteration = resolveIteration(options, docsRoot);
2170
+ const entries = readTaskHistory({
2171
+ iteration,
2172
+ developer,
2173
+ taskId,
2174
+ limit: 10
2175
+ });
2176
+ if ('json' === parseFormat(options.format)) return void printJson(entries);
2177
+ if (0 === entries.length) return void printLine('暂无变更记录');
2178
+ for (const entry of entries){
2179
+ printLine(`${new Date(entry.at).toLocaleString('zh-CN')} ${ACTION_META[entry.action].label}`);
2180
+ for (const change of entry.changes)printLine(` · ${change}`);
2181
+ }
2182
+ }
2183
+ function runRecalc(options) {
2184
+ const { docsRoot, developer } = requireWriteContext(options);
2185
+ const iteration = resolveIteration(options, docsRoot);
2186
+ const format = parseFormat(options.format);
2187
+ const result = recalcRequirements({
2188
+ docsRoot,
2189
+ iteration,
2190
+ developer,
2191
+ dryRun: true === options.dryRun
2192
+ });
2193
+ if ('json' === format) return void printJson({
2194
+ dryRun: true === options.dryRun,
2195
+ ...result
2196
+ });
2197
+ if (0 === result.changes.length) return void printLine('需求状态已与任务一致,无需重算');
2198
+ printLine(true === options.dryRun ? '将更新(未写入,--dry-run):' : '已重算需求状态:');
2199
+ for (const change of result.changes)printLine(` · ${change}`);
2200
+ if (true !== options.dryRun) printLine(`文档:${result.file}`);
2201
+ }
2202
+ function registerTask(program) {
2203
+ const task = program.command('task').description('修改本人任务状态(供界面与 Agent 共用)');
2204
+ const commonOptions = (command)=>command.option('-c, --config <path>', '指定配置文件路径').option('-i, --iteration <name>', '迭代目录名(在迭代目录内执行时可省略)').option('-d, --developer <name>', '开发者标识(默认取配置身份)').option('--format <format>', '输出格式:human | json', 'human');
2205
+ commonOptions(task.command('actions')).description('列出每个任务当前可执行的动作').action((options)=>runActions(options));
2206
+ for (const action of [
2207
+ 'start',
2208
+ 'submit',
2209
+ 'accept',
2210
+ 'reject'
2211
+ ])commonOptions(task.command(`${action} <taskId>`)).description(`执行「${ACTION_META[action].label}」:${ACTION_META[action].from} → ${ACTION_META[action].to}`).option('--dry-run', '只校验是否允许,不写入').option('--commit', '本次变更后提交(覆盖 docs.git.cli.commit)').option('--no-commit', '本次变更后不提交').option('--push', '提交后推送(隐含 --commit)').option('--no-push', '不推送').action((taskId, options)=>runAction(action, taskId, options));
2212
+ commonOptions(task.command('batch <action> <taskIds...>')).description('批量执行同一动作,例如: ylcwf task batch accept "#2755-T1" "#2755-T2"').action((action, taskIds, options)=>{
2213
+ if (!(action in ACTION_META)) throw new errors_CliError(`未知动作:${action}(可选 ${Object.keys(ACTION_META).join(' / ')})`, errors_EXIT.USAGE);
2214
+ runBatch(action, taskIds, options);
2215
+ });
2216
+ commonOptions(task.command('history <taskId>')).description('查看任务的最近变更记录').action((taskId, options)=>runHistory(taskId, options));
2217
+ const requirement = program.command('requirement').description('需求维度的只读查询与状态重算');
2218
+ commonOptions(requirement.command('recalc')).description('按任务状态重算需求开发状态与进度').option('--dry-run', '只输出差异,不写入').action((options)=>runRecalc(options));
2219
+ }
2220
+ const FIELDS = [
2221
+ 'path',
2222
+ 'exists',
2223
+ 'terminal',
2224
+ 'repos'
2225
+ ];
2226
+ function isSide(value) {
2227
+ return SIDES.some((side)=>side === value);
2228
+ }
2229
+ function isField(value) {
2230
+ return FIELDS.some((field)=>field === value);
2231
+ }
2232
+ function buildRepoView(terminal) {
2233
+ const view = {
2234
+ frontend: [],
2235
+ backend: []
2236
+ };
2237
+ for (const side of SIDES)view[side] = terminal.repos[side].map((path)=>({
2238
+ path,
2239
+ exists: external_node_fs_existsSync(path)
2240
+ }));
1263
2241
  return view;
1264
2242
  }
1265
2243
  function formatCandidates(items) {
@@ -1346,7 +2324,6 @@ function runResolve(name, options) {
1346
2324
  return;
1347
2325
  }
1348
2326
  if ('json' === format) return void printJson({
1349
- schemaVersion: ready.config.schemaVersion,
1350
2327
  input: name,
1351
2328
  matched: true,
1352
2329
  matchedBy: result.matchedBy,
@@ -1399,10 +2376,10 @@ function registerDoctor(program) {
1399
2376
  });
1400
2377
  }
1401
2378
  function runPath(options) {
1402
- const target = resolveConfigPath(options.config);
2379
+ const target = paths_resolveConfigPath(options.config);
1403
2380
  const format = parseFormat(options.format);
1404
2381
  if (true === options.exists) {
1405
- const present = existsSync(target);
2382
+ const present = external_node_fs_existsSync(target);
1406
2383
  if ('json' === format) printJson({
1407
2384
  configPath: target,
1408
2385
  exists: present
@@ -1418,56 +2395,2064 @@ function registerPath(program) {
1418
2395
  runPath(options);
1419
2396
  });
1420
2397
  }
1421
- function buildProgram() {
1422
- const program = new Command();
1423
- program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与终端仓库映射').version("0.1.0", '-v, --version', '显示版本号').showHelpAfterError();
1424
- registerInit(program);
1425
- registerShow(program);
1426
- registerGet(program);
1427
- registerSet(program);
1428
- registerTerminal(program);
1429
- registerResolve(program);
1430
- registerDoctor(program);
1431
- registerPath(program);
1432
- return program;
2398
+ function syncDocument(doc, next) {
2399
+ doc.deleteIn([
2400
+ 'schemaVersion'
2401
+ ]);
2402
+ doc.setIn([
2403
+ 'profile',
2404
+ 'developer'
2405
+ ], next.profile.developer);
2406
+ doc.setIn([
2407
+ 'profile',
2408
+ 'role'
2409
+ ], next.profile.role);
2410
+ doc.setIn([
2411
+ 'profile',
2412
+ 'mode'
2413
+ ], next.profile.mode);
2414
+ doc.setIn([
2415
+ 'docs',
2416
+ 'root'
2417
+ ], next.docs.root);
2418
+ if (null === next.docs.remote) doc.deleteIn([
2419
+ 'docs',
2420
+ 'remote'
2421
+ ]);
2422
+ else doc.setIn([
2423
+ 'docs',
2424
+ 'remote'
2425
+ ], next.docs.remote);
2426
+ for (const side of [
2427
+ 'cli',
2428
+ 'ui'
2429
+ ]){
2430
+ doc.setIn([
2431
+ 'docs',
2432
+ 'git',
2433
+ side,
2434
+ 'commit'
2435
+ ], next.docs.git[side].commit);
2436
+ doc.setIn([
2437
+ 'docs',
2438
+ 'git',
2439
+ side,
2440
+ 'push'
2441
+ ], next.docs.git[side].push);
2442
+ }
2443
+ const current = doc.toJS();
2444
+ const currentTerminals = utils_isRecord(current) && utils_isRecord(current['terminals']) ? Object.keys(current['terminals']) : [];
2445
+ for (const key of currentTerminals)if (!Object.hasOwn(next.terminals, key)) doc.deleteIn([
2446
+ 'terminals',
2447
+ key
2448
+ ]);
2449
+ for (const [key, terminal] of Object.entries(next.terminals)){
2450
+ doc.setIn([
2451
+ 'terminals',
2452
+ key,
2453
+ 'aliases'
2454
+ ], terminal.aliases);
2455
+ doc.setIn([
2456
+ 'terminals',
2457
+ key,
2458
+ 'repos',
2459
+ 'frontend'
2460
+ ], terminal.repos.frontend);
2461
+ doc.setIn([
2462
+ 'terminals',
2463
+ key,
2464
+ 'repos',
2465
+ 'backend'
2466
+ ], terminal.repos.backend);
2467
+ }
1433
2468
  }
1434
- function runBare(configPath) {
1435
- showConfig(configPath, process.stdout.isTTY ? 'human' : 'json');
2469
+ function collectResetTargets(configPath, includeRepos) {
2470
+ const targets = [
2471
+ {
2472
+ path: configPath,
2473
+ label: '配置文件',
2474
+ kind: 'file'
2475
+ },
2476
+ {
2477
+ path: `${configPath}.lock`,
2478
+ label: '锁文件',
2479
+ kind: 'file'
2480
+ },
2481
+ {
2482
+ path: backupsDir(configPath),
2483
+ label: '配置备份',
2484
+ kind: 'dir'
2485
+ }
2486
+ ];
2487
+ if (includeRepos) targets.push({
2488
+ path: managedReposDir(),
2489
+ label: '托管文档仓库副本',
2490
+ kind: 'dir'
2491
+ });
2492
+ return targets.filter((target)=>external_node_fs_existsSync(target.path));
1436
2493
  }
1437
- function splitGlobalArgs(argv) {
1438
- const rest = [];
1439
- let config;
1440
- for(let index = 0; index < argv.length; index += 1){
1441
- const arg = argv[index] ?? '';
1442
- if ('-c' === arg || '--config' === arg) {
1443
- const value = argv[index + 1];
1444
- if (void 0 !== value) config = value;
1445
- index += 1;
1446
- continue;
2494
+ function describeTarget(target) {
2495
+ if ('file' === target.kind) {
2496
+ const size = statSync(target.path).size;
2497
+ return `${target.label}:${target.path}(${size} B)`;
2498
+ }
2499
+ const count = readdirSync(target.path).length;
2500
+ return `${target.label}:${target.path}(${count} 项)`;
2501
+ }
2502
+ function performReset(configPath, targets) {
2503
+ for (const target of targets)rmSync(target.path, {
2504
+ recursive: true,
2505
+ force: true
2506
+ });
2507
+ const parent = dirname(configPath);
2508
+ try {
2509
+ if (external_node_fs_existsSync(parent) && 0 === readdirSync(parent).length) rmSync(parent, {
2510
+ recursive: true,
2511
+ force: true
2512
+ });
2513
+ } catch {}
2514
+ return targets.length;
2515
+ }
2516
+ const SERVER_FEATURES = [
2517
+ 'status-breakdown',
2518
+ 'branch-switch',
2519
+ 'fs-browse',
2520
+ 'dir-picker'
2521
+ ];
2522
+ function repoView(path) {
2523
+ const exists = external_node_fs_existsSync(path);
2524
+ return {
2525
+ path,
2526
+ exists,
2527
+ isGit: exists && external_node_fs_existsSync(external_node_path_join(path, '.git'))
2528
+ };
2529
+ }
2530
+ function readState(explicitPath) {
2531
+ const configPath = paths_resolveConfigPath(explicitPath);
2532
+ const loaded = loadConfig(explicitPath);
2533
+ const checked = loaded.exists ? checkConfig(loaded.raw, {
2534
+ checkFs: true
2535
+ }) : {
2536
+ config: null,
2537
+ issues: []
2538
+ };
2539
+ return {
2540
+ configPath,
2541
+ exists: loaded.exists,
2542
+ config: checked.config,
2543
+ issues: checked.issues,
2544
+ backups: listBackups(explicitPath),
2545
+ meta: {
2546
+ version: "0.3.0",
2547
+ features: SERVER_FEATURES
1447
2548
  }
1448
- if (arg.startsWith('--config=')) {
1449
- config = arg.slice(9);
1450
- continue;
2549
+ };
2550
+ }
2551
+ function saveConfig(raw, explicitPath) {
2552
+ const configPath = paths_resolveConfigPath(explicitPath);
2553
+ const structural = checkConfig(raw, {
2554
+ allowIncomplete: false,
2555
+ checkFs: false
2556
+ });
2557
+ if (null === structural.config || structural.issues.some((issue)=>'error' === issue.level)) {
2558
+ const detail = structural.issues.filter((issue)=>'error' === issue.level).map((issue)=>`- ${issue.message}`).join('\n');
2559
+ throw new errors_CliError(`配置校验未通过,已取消保存:\n${detail}`, errors_EXIT.INVALID);
2560
+ }
2561
+ const loaded = loadConfig(explicitPath);
2562
+ const doc = loaded.doc ?? createEmptyDocument();
2563
+ syncDocument(doc, structural.config);
2564
+ assertWritable(doc, configPath);
2565
+ saveDocument(doc, configPath);
2566
+ return readState(explicitPath);
2567
+ }
2568
+ function listBackups(explicitPath) {
2569
+ const configPath = paths_resolveConfigPath(explicitPath);
2570
+ const dir = backupsDir(configPath);
2571
+ if (!external_node_fs_existsSync(dir)) return [];
2572
+ return readdirSync(dir).filter((name)=>name.endsWith('.yaml')).map((name)=>{
2573
+ const full = external_node_path_join(dir, name);
2574
+ const info = statSync(full);
2575
+ return {
2576
+ name,
2577
+ mtime: info.mtime.toISOString(),
2578
+ size: info.size
2579
+ };
2580
+ }).sort((left, right)=>right.mtime.localeCompare(left.mtime));
2581
+ }
2582
+ function restoreBackup(name, explicitPath) {
2583
+ const configPath = paths_resolveConfigPath(explicitPath);
2584
+ const dir = backupsDir(configPath);
2585
+ const source = external_node_path_join(dir, basename(name));
2586
+ if (!external_node_fs_existsSync(source)) throw new errors_CliError(`备份不存在:${name}`, errors_EXIT.NOT_FOUND);
2587
+ mkdirSync(dir, {
2588
+ recursive: true
2589
+ });
2590
+ if (external_node_fs_existsSync(configPath)) {
2591
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
2592
+ copyFileSync(configPath, external_node_path_join(dir, `config-${stamp}-before-restore.yaml`));
2593
+ }
2594
+ copyFileSync(source, configPath);
2595
+ const loaded = loadConfig(explicitPath);
2596
+ if (null === loaded.config) throw new errors_CliError(`备份内容不合法,已写入但需要人工修复:${configPath}`, errors_EXIT.INVALID);
2597
+ return readState(explicitPath);
2598
+ }
2599
+ function resolveRequest(name, side, explicitPath) {
2600
+ const loaded = loadConfig(explicitPath);
2601
+ if (null === loaded.config) throw new errors_CliError(`配置未初始化或不合法:${loaded.path}`, errors_EXIT.NOT_FOUND);
2602
+ const result = resolveTerminal(loaded.config, name);
2603
+ const repos = {
2604
+ frontend: [],
2605
+ backend: []
2606
+ };
2607
+ if (result.matched && null !== result.entry) {
2608
+ for (const item of SIDES)if (void 0 === side || item === side) repos[item] = result.entry.repos[item].map(repoView);
2609
+ }
2610
+ return {
2611
+ input: name,
2612
+ matched: result.matched,
2613
+ matchedBy: result.matchedBy,
2614
+ terminal: result.terminal,
2615
+ candidates: result.candidates,
2616
+ repos
2617
+ };
2618
+ }
2619
+ function resetConfig(includeRepos, explicitPath) {
2620
+ const configPath = paths_resolveConfigPath(explicitPath);
2621
+ const targets = collectResetTargets(configPath, includeRepos);
2622
+ const removed = performReset(configPath, targets);
2623
+ return {
2624
+ removed,
2625
+ configPath
2626
+ };
2627
+ }
2628
+ function inspectPath(target) {
2629
+ const view = repoView(target);
2630
+ return {
2631
+ ...view,
2632
+ hasDocsSkill: view.exists && external_node_fs_existsSync(external_node_path_join(target, 'skills', 'iteration-task-docs', 'SKILL.md'))
2633
+ };
2634
+ }
2635
+ const RESERVED_FILES = new Set([
2636
+ 'README.md',
2637
+ 'AGENTS.md',
2638
+ 'CLAUDE.md'
2639
+ ]);
2640
+ const RESERVED_PREFIXES = [
2641
+ 'skills/',
2642
+ "scripts/",
2643
+ '_prd/'
2644
+ ];
2645
+ const git_SAFE_SEGMENT = /^[A-Za-z0-9._\-\u4e00-\u9fa5]+$/;
2646
+ function git_git(docsRoot, args, timeoutMs = 15000) {
2647
+ return execFileSync('git', [
2648
+ '-C',
2649
+ docsRoot,
2650
+ ...args
2651
+ ], {
2652
+ encoding: 'utf8',
2653
+ timeout: timeoutMs,
2654
+ maxBuffer: 33554432,
2655
+ env: {
2656
+ ...process.env,
2657
+ GIT_TERMINAL_PROMPT: '0',
2658
+ GIT_SSH_COMMAND: process.env['GIT_SSH_COMMAND'] ?? 'ssh -o BatchMode=yes -o ConnectTimeout=8'
1451
2659
  }
1452
- rest.push(arg);
2660
+ }).trim();
2661
+ }
2662
+ function tryGit(docsRoot, args, timeoutMs) {
2663
+ try {
2664
+ return git_git(docsRoot, args, timeoutMs);
2665
+ } catch {
2666
+ return null;
1453
2667
  }
1454
- return void 0 === config ? {
1455
- rest
1456
- } : {
1457
- config,
1458
- rest
2668
+ }
2669
+ function git_safeSegment(value, label) {
2670
+ const trimmed = value.trim();
2671
+ if (!git_SAFE_SEGMENT.test(trimmed) || '.' === trimmed || '..' === trimmed) throw new errors_CliError(`${label} 不合法:${value}`, errors_EXIT.USAGE);
2672
+ return trimmed;
2673
+ }
2674
+ function getGitStatus(docsRoot) {
2675
+ const empty = {
2676
+ available: false,
2677
+ hasRemote: false,
2678
+ remoteUrl: null,
2679
+ branch: null,
2680
+ upstream: null,
2681
+ head: null,
2682
+ ahead: 0,
2683
+ behind: 0,
2684
+ dirty: false,
2685
+ error: null
2686
+ };
2687
+ if (!external_node_fs_existsSync(external_node_path_join(docsRoot, '.git'))) return {
2688
+ ...empty,
2689
+ error: '文档仓库不是 git 仓库,仅支持本地模式'
2690
+ };
2691
+ const inside = tryGit(docsRoot, [
2692
+ 'rev-parse',
2693
+ '--is-inside-work-tree'
2694
+ ]);
2695
+ if ('true' !== inside) return {
2696
+ ...empty,
2697
+ error: '无法读取 git 仓库(可能缺少 git 命令)'
2698
+ };
2699
+ const remoteUrl = tryGit(docsRoot, [
2700
+ 'remote',
2701
+ 'get-url',
2702
+ 'origin'
2703
+ ]);
2704
+ const branch = tryGit(docsRoot, [
2705
+ 'rev-parse',
2706
+ '--abbrev-ref',
2707
+ 'HEAD'
2708
+ ]);
2709
+ const head = tryGit(docsRoot, [
2710
+ 'rev-parse',
2711
+ '--short',
2712
+ 'HEAD'
2713
+ ]);
2714
+ const upstream = tryGit(docsRoot, [
2715
+ 'rev-parse',
2716
+ '--abbrev-ref',
2717
+ '--symbolic-full-name',
2718
+ '@{u}'
2719
+ ]);
2720
+ const dirty = (tryGit(docsRoot, [
2721
+ 'status',
2722
+ '--porcelain'
2723
+ ]) ?? '').length > 0;
2724
+ let ahead = 0;
2725
+ let behind = 0;
2726
+ if (null !== upstream) {
2727
+ const counts = tryGit(docsRoot, [
2728
+ 'rev-list',
2729
+ '--left-right',
2730
+ '--count',
2731
+ `HEAD...${upstream}`
2732
+ ]);
2733
+ if (null !== counts) {
2734
+ const [left, right] = counts.split(/\s+/);
2735
+ ahead = Number.parseInt(left ?? '0', 10) || 0;
2736
+ behind = Number.parseInt(right ?? '0', 10) || 0;
2737
+ }
2738
+ }
2739
+ return {
2740
+ available: true,
2741
+ hasRemote: null !== remoteUrl,
2742
+ remoteUrl,
2743
+ branch,
2744
+ upstream,
2745
+ head,
2746
+ ahead,
2747
+ behind,
2748
+ dirty,
2749
+ error: null
1459
2750
  };
1460
2751
  }
1461
- async function main() {
1462
- const { config, rest } = splitGlobalArgs(process.argv.slice(2));
1463
- const wantsMeta = rest.some((arg)=>[
1464
- '-h',
1465
- '--help',
1466
- '-v',
1467
- '--version'
1468
- ].includes(arg));
2752
+ function fetchRemote(docsRoot) {
2753
+ try {
2754
+ git_git(docsRoot, [
2755
+ 'fetch',
2756
+ '--prune',
2757
+ 'origin'
2758
+ ], 30000);
2759
+ return {
2760
+ ok: true,
2761
+ message: '已同步远程引用(未改动工作区)'
2762
+ };
2763
+ } catch (error) {
2764
+ const message = error instanceof Error ? error.message : String(error);
2765
+ return {
2766
+ ok: false,
2767
+ message: `同步失败:${message.split('\n')[0] ?? message}`
2768
+ };
2769
+ }
2770
+ }
2771
+ function resolveRemoteRef(docsRoot, refName) {
2772
+ const explicit = refName?.trim();
2773
+ const upstream = void 0 !== explicit && explicit.length > 0 ? explicit : tryGit(docsRoot, [
2774
+ 'rev-parse',
2775
+ '--abbrev-ref',
2776
+ '--symbolic-full-name',
2777
+ '@{u}'
2778
+ ]);
2779
+ if (null === upstream) throw new errors_CliError('当前分支没有上游分支,无法读取远程快照', errors_EXIT.NOT_FOUND);
2780
+ const sha = tryGit(docsRoot, [
2781
+ 'rev-parse',
2782
+ upstream
2783
+ ]);
2784
+ if (null === sha) throw new errors_CliError(`无法解析远程引用:${upstream}`, errors_EXIT.NOT_FOUND);
2785
+ const committedAt = tryGit(docsRoot, [
2786
+ 'log',
2787
+ '-1',
2788
+ '--format=%cI',
2789
+ sha
2790
+ ]) ?? '';
2791
+ return {
2792
+ ref: upstream,
2793
+ sha,
2794
+ committedAt
2795
+ };
2796
+ }
2797
+ function isDocMarkdown(path) {
2798
+ if (!path.endsWith('.md')) return false;
2799
+ if (RESERVED_FILES.has(basename(path))) return false;
2800
+ if (RESERVED_PREFIXES.some((prefix)=>path.startsWith(prefix) || path.includes(`/${prefix}`))) return false;
2801
+ return true;
2802
+ }
2803
+ function lastCommitIso(docsRoot, sha, path) {
2804
+ return tryGit(docsRoot, [
2805
+ 'log',
2806
+ '-1',
2807
+ '--format=%cI',
2808
+ sha,
2809
+ '--',
2810
+ path
2811
+ ]) ?? '';
2812
+ }
2813
+ function getBranchInfo(docsRoot) {
2814
+ const current = tryGit(docsRoot, [
2815
+ 'rev-parse',
2816
+ '--abbrev-ref',
2817
+ 'HEAD'
2818
+ ]);
2819
+ const detached = null === current || 'HEAD' === current;
2820
+ const upstream = detached ? null : tryGit(docsRoot, [
2821
+ 'rev-parse',
2822
+ '--abbrev-ref',
2823
+ '--symbolic-full-name',
2824
+ '@{u}'
2825
+ ]);
2826
+ const status = tryGit(docsRoot, [
2827
+ 'status',
2828
+ '--porcelain'
2829
+ ]);
2830
+ const branches = tryGit(docsRoot, [
2831
+ 'for-each-ref',
2832
+ '--format=%(refname)',
2833
+ 'refs/remotes'
2834
+ ]) ?? '';
2835
+ return {
2836
+ current: detached ? null : current,
2837
+ detached,
2838
+ upstream,
2839
+ dirty: null !== status && status.length > 0,
2840
+ remote: branches.split('\n').map((line)=>line.trim().replace(/^refs\/remotes\//, '')).filter((line)=>line.length > 0 && line.includes('/') && !line.endsWith('/HEAD')).sort()
2841
+ };
2842
+ }
2843
+ function listRemoteIterations(docsRoot, ref) {
2844
+ const listed = tryGit(docsRoot, [
2845
+ 'ls-tree',
2846
+ '-r',
2847
+ '--name-only',
2848
+ ref.sha
2849
+ ]);
2850
+ if (null === listed) throw new errors_CliError(`无法读取远程快照:${ref.ref}`, errors_EXIT.NOT_FOUND);
2851
+ const groups = new Map();
2852
+ for (const path of listed.split('\n')){
2853
+ if (!isDocMarkdown(path)) continue;
2854
+ const segments = path.split('/');
2855
+ if (2 !== segments.length) continue;
2856
+ const [iteration, file] = segments;
2857
+ if (void 0 === iteration || void 0 === file) continue;
2858
+ const sizeText = tryGit(docsRoot, [
2859
+ 'cat-file',
2860
+ '-s',
2861
+ `${ref.sha}:${path}`
2862
+ ]) ?? '0';
2863
+ const entry = {
2864
+ id: file.replace(/\.md$/, ''),
2865
+ file,
2866
+ mtime: lastCommitIso(docsRoot, ref.sha, path),
2867
+ size: Number.parseInt(sizeText, 10) || 0
2868
+ };
2869
+ const bucket = groups.get(iteration) ?? [];
2870
+ bucket.push(entry);
2871
+ groups.set(iteration, bucket);
2872
+ }
2873
+ const iterations = [
2874
+ ...groups.entries()
2875
+ ].map(([name, developers])=>({
2876
+ name,
2877
+ mtime: lastCommitIso(docsRoot, ref.sha, name),
2878
+ developers: developers.sort((left, right)=>right.mtime.localeCompare(left.mtime)),
2879
+ hasPrd: listed.includes(`${name}/_prd/meta.json`)
2880
+ })).sort((left, right)=>right.mtime.localeCompare(left.mtime));
2881
+ return {
2882
+ docsRoot,
2883
+ source: 'remote',
2884
+ ref,
2885
+ iterations
2886
+ };
2887
+ }
2888
+ function gitShow(docsRoot, sha, path) {
2889
+ return tryGit(docsRoot, [
2890
+ 'show',
2891
+ `${sha}:${path}`
2892
+ ]);
2893
+ }
2894
+ function materializeRemote(docsRoot, ref) {
2895
+ const dir = external_node_path_join(external_node_os_tmpdir(), `ylcwf-remote-${ref.sha.slice(0, 12)}`);
2896
+ mkdirSync(external_node_path_join(dir, "scripts"), {
2897
+ recursive: true
2898
+ });
2899
+ return dir;
2900
+ }
2901
+ function exportRemoteDoc(docsRoot, ref, iteration, developer) {
2902
+ const safeIteration = git_safeSegment(iteration, '迭代目录');
2903
+ const safeDeveloper = git_safeSegment(developer, '开发者标识');
2904
+ const relative = `${safeIteration}/${safeDeveloper}.md`;
2905
+ const markdown = gitShow(docsRoot, ref.sha, relative);
2906
+ if (null === markdown) throw new errors_CliError(`远程快照中不存在该文档:${relative}`, errors_EXIT.NOT_FOUND);
2907
+ const dir = materializeRemote(docsRoot, ref);
2908
+ const target = external_node_path_join(dir, safeIteration, `${safeDeveloper}.md`);
2909
+ mkdirSync(dirname(target), {
2910
+ recursive: true
2911
+ });
2912
+ writeFileSync(target, markdown, 'utf8');
2913
+ const scriptPath = external_node_path_join(dir, "scripts", 'validate_task_doc.py');
2914
+ if (!external_node_fs_existsSync(scriptPath)) {
2915
+ const script = gitShow(docsRoot, ref.sha, "scripts/validate_task_doc.py");
2916
+ if (null !== script) writeFileSync(scriptPath, script, 'utf8');
2917
+ }
2918
+ return {
2919
+ dir,
2920
+ markdown,
2921
+ scriptPath: external_node_fs_existsSync(scriptPath) ? scriptPath : null,
2922
+ mtime: lastCommitIso(docsRoot, ref.sha, relative) || ref.committedAt
2923
+ };
2924
+ }
2925
+ function isGitAvailable() {
2926
+ try {
2927
+ execFileSync('git', [
2928
+ '--version'
2929
+ ], {
2930
+ timeout: 5000,
2931
+ encoding: 'utf8'
2932
+ });
2933
+ return true;
2934
+ } catch {
2935
+ return false;
2936
+ }
2937
+ }
2938
+ function probeRemote(remote) {
2939
+ if (!isGitAvailable()) return {
2940
+ gitAvailable: false,
2941
+ reachable: false,
2942
+ authorized: false,
2943
+ reason: '未检测到 git 命令,请先安装 Git'
2944
+ };
2945
+ try {
2946
+ execFileSync('git', [
2947
+ 'ls-remote',
2948
+ '--heads',
2949
+ remote
2950
+ ], {
2951
+ timeout: 20000,
2952
+ encoding: 'utf8',
2953
+ maxBuffer: 8388608,
2954
+ env: {
2955
+ ...process.env,
2956
+ GIT_TERMINAL_PROMPT: '0',
2957
+ GIT_SSH_COMMAND: process.env['GIT_SSH_COMMAND'] ?? 'ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new'
2958
+ }
2959
+ });
2960
+ return {
2961
+ gitAvailable: true,
2962
+ reachable: true,
2963
+ authorized: true,
2964
+ reason: null
2965
+ };
2966
+ } catch (error) {
2967
+ const stderr = String(error.stderr ?? '');
2968
+ const lower = stderr.toLowerCase();
2969
+ if (lower.includes('authentication failed') || lower.includes('permission denied') || lower.includes('could not read username') || lower.includes('terminal prompts disabled') || lower.includes('access denied') || lower.includes('401') || lower.includes('403') || lower.includes('not found') || lower.includes('repository not found')) return {
2970
+ gitAvailable: true,
2971
+ reachable: true,
2972
+ authorized: false,
2973
+ reason: '没有访问权限或未配置 Git 凭据,请联系管理员开通文档仓库访问权限'
2974
+ };
2975
+ if (lower.includes('could not resolve host') || lower.includes('connection timed out') || lower.includes('connection refused') || lower.includes("couldn't connect") || lower.includes('network is unreachable')) return {
2976
+ gitAvailable: true,
2977
+ reachable: false,
2978
+ authorized: false,
2979
+ reason: '无法连接远程仓库,请检查网络或代理'
2980
+ };
2981
+ return {
2982
+ gitAvailable: true,
2983
+ reachable: false,
2984
+ authorized: false,
2985
+ reason: stderr.split('\n')[0]?.trim() || '无法访问远程仓库'
2986
+ };
2987
+ }
2988
+ }
2989
+ function repoNameFromRemote(remote) {
2990
+ const cleaned = remote.replace(/\/+$/, '').replace(/\.git$/, '');
2991
+ const last = cleaned.split(/[/:]/).pop() ?? 'docs';
2992
+ return last.replace(/[^\w.\-\u4e00-\u9fa5]/g, '-') || 'docs';
2993
+ }
2994
+ function mostRecentRemoteBranch(docsRoot) {
2995
+ const listed = tryGit(docsRoot, [
2996
+ 'for-each-ref',
2997
+ '--sort=-committerdate',
2998
+ '--count=5',
2999
+ '--format=%(refname:short)',
3000
+ 'refs/remotes/origin/'
3001
+ ]);
3002
+ if (null === listed) return null;
3003
+ const candidate = listed.split('\n').map((line)=>line.trim()).find((name)=>name.length > 0 && !name.endsWith('/HEAD'));
3004
+ return candidate ?? null;
3005
+ }
3006
+ function ensureManagedClone(remote) {
3007
+ const dir = external_node_path_join(managedReposDir(), repoNameFromRemote(remote));
3008
+ const gitDir = external_node_path_join(dir, '.git');
3009
+ if (external_node_fs_existsSync(gitDir)) {
3010
+ const fetched = tryGit(dir, [
3011
+ 'fetch',
3012
+ '--prune',
3013
+ '--all'
3014
+ ], 60000);
3015
+ if (null === fetched) throw new errors_CliError('同步远程仓库失败,请检查网络或权限', errors_EXIT.INVALID);
3016
+ const branch = mostRecentRemoteBranch(dir);
3017
+ if (null !== branch) {
3018
+ const local = branch.replace(/^origin\//, '');
3019
+ const checked = tryGit(dir, [
3020
+ 'checkout',
3021
+ '-B',
3022
+ local,
3023
+ branch
3024
+ ]);
3025
+ if (null === checked) throw new errors_CliError(`无法检出分支:${branch}`, errors_EXIT.INVALID);
3026
+ }
3027
+ return {
3028
+ dir,
3029
+ created: false,
3030
+ branch: branch ?? ''
3031
+ };
3032
+ }
3033
+ mkdirSync(dirname(dir), {
3034
+ recursive: true
3035
+ });
3036
+ try {
3037
+ execFileSync('git', [
3038
+ 'clone',
3039
+ remote,
3040
+ dir
3041
+ ], {
3042
+ timeout: 180000,
3043
+ encoding: 'utf8',
3044
+ maxBuffer: 16777216,
3045
+ env: {
3046
+ ...process.env,
3047
+ GIT_TERMINAL_PROMPT: '0',
3048
+ GIT_SSH_COMMAND: process.env['GIT_SSH_COMMAND'] ?? 'ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new'
3049
+ }
3050
+ });
3051
+ } catch (error) {
3052
+ const stderr = String(error.stderr ?? '');
3053
+ throw new errors_CliError(`克隆文档仓库失败:${stderr.split('\n')[0]?.trim() ?? '未知错误'}`, errors_EXIT.INVALID);
3054
+ }
3055
+ const branch = mostRecentRemoteBranch(dir);
3056
+ if (null !== branch) tryGit(dir, [
3057
+ 'checkout',
3058
+ '-B',
3059
+ branch.replace(/^origin\//, ''),
3060
+ branch
3061
+ ]);
3062
+ return {
3063
+ dir,
3064
+ created: true,
3065
+ branch: branch ?? ''
3066
+ };
3067
+ }
3068
+ function syncManagedRepo(dir) {
3069
+ try {
3070
+ git_git(dir, [
3071
+ 'fetch',
3072
+ '--prune',
3073
+ '--all'
3074
+ ], 60000);
3075
+ const upstream = tryGit(dir, [
3076
+ 'rev-parse',
3077
+ '--abbrev-ref',
3078
+ '--symbolic-full-name',
3079
+ '@{u}'
3080
+ ]);
3081
+ if (null !== upstream) {
3082
+ git_git(dir, [
3083
+ 'reset',
3084
+ '--hard',
3085
+ upstream
3086
+ ]);
3087
+ return {
3088
+ ok: true,
3089
+ message: `已同步到 ${upstream}`,
3090
+ branch: upstream
3091
+ };
3092
+ }
3093
+ return {
3094
+ ok: true,
3095
+ message: '已同步远程引用',
3096
+ branch: ''
3097
+ };
3098
+ } catch (error) {
3099
+ const message = error instanceof Error ? error.message : String(error);
3100
+ return {
3101
+ ok: false,
3102
+ message: `同步失败:${message.split('\n')[0] ?? message}`,
3103
+ branch: ''
3104
+ };
3105
+ }
3106
+ }
3107
+ function normalizeSelfTest(value) {
3108
+ const text = value.trim();
3109
+ if (0 === text.length) return '未执行';
3110
+ if (text.startsWith('免测')) return '免测';
3111
+ return text;
3112
+ }
3113
+ function normalizeAcceptance(value) {
3114
+ const text = value.trim();
3115
+ return 0 === text.length ? '待验收' : text;
3116
+ }
3117
+ function bump(target, key) {
3118
+ target[key] = (target[key] ?? 0) + 1;
3119
+ }
3120
+ const RESERVED_DIRS = new Set([
3121
+ '_prd',
3122
+ "scripts",
3123
+ 'skills',
3124
+ 'node_modules',
3125
+ '.git',
3126
+ '.idea',
3127
+ '.vscode'
3128
+ ]);
3129
+ const iterations_RESERVED_FILES = new Set([
3130
+ 'README.md',
3131
+ 'AGENTS.md',
3132
+ 'CLAUDE.md'
3133
+ ]);
3134
+ const iterations_SAFE_SEGMENT = /^[A-Za-z0-9._\-\u4e00-\u9fa5]+$/;
3135
+ function iterations_safeSegment(value, label) {
3136
+ const trimmed = value.trim();
3137
+ if (!iterations_SAFE_SEGMENT.test(trimmed) || '.' === trimmed || '..' === trimmed) throw new errors_CliError(`${label} 不合法:${value}`, errors_EXIT.USAGE);
3138
+ return trimmed;
3139
+ }
3140
+ function joinWithin(root, ...segments) {
3141
+ const target = resolve(root, ...segments);
3142
+ const base = resolve(root) + sep;
3143
+ if (!target.startsWith(base)) throw new errors_CliError(`路径越界:${target}`, errors_EXIT.USAGE);
3144
+ return target;
3145
+ }
3146
+ function inferRole(markdown) {
3147
+ const match = /\|\s*负责范围\s*\|\s*([^|]*)\|/.exec(markdown);
3148
+ const scope = match?.[1]?.trim() ?? '';
3149
+ const hasFrontend = scope.includes('前端');
3150
+ const hasBackend = scope.includes('后端');
3151
+ if (hasFrontend && hasBackend) return 'fullstack';
3152
+ if (hasBackend) return 'backend';
3153
+ return 'frontend';
3154
+ }
3155
+ function listMarkdownFiles(directory) {
3156
+ let entries;
3157
+ try {
3158
+ entries = readdirSync(directory);
3159
+ } catch {
3160
+ return [];
3161
+ }
3162
+ return entries.filter((name)=>name.endsWith('.md') && !iterations_RESERVED_FILES.has(name)).map((name)=>{
3163
+ const full = external_node_path_join(directory, name);
3164
+ const info = statSync(full);
3165
+ return {
3166
+ id: name.replace(/\.md$/, ''),
3167
+ file: name,
3168
+ mtime: info.mtime.toISOString(),
3169
+ size: info.size
3170
+ };
3171
+ }).sort((left, right)=>right.mtime.localeCompare(left.mtime));
3172
+ }
3173
+ function accessReason(error) {
3174
+ const code = error.code;
3175
+ if ('EACCES' === code || 'EPERM' === code) return '没有访问权限,请联系管理员开通文档仓库访问权限';
3176
+ if ('ENOENT' === code) return '文档仓库路径不存在';
3177
+ if (error instanceof Error) return error.message;
3178
+ return String(error);
3179
+ }
3180
+ function listIterations(docsRoot, source = 'local', refName) {
3181
+ const base = {
3182
+ docsRoot,
3183
+ configured: docsRoot.trim().length > 0,
3184
+ accessible: false,
3185
+ reason: null,
3186
+ source,
3187
+ ref: null,
3188
+ iterations: []
3189
+ };
3190
+ if (!base.configured) return {
3191
+ ...base,
3192
+ reason: '尚未配置文档仓库'
3193
+ };
3194
+ if (!external_node_fs_existsSync(docsRoot)) return {
3195
+ ...base,
3196
+ reason: `文档仓库路径不存在:${docsRoot}`
3197
+ };
3198
+ try {
3199
+ readdirSync(docsRoot);
3200
+ } catch (error) {
3201
+ return {
3202
+ ...base,
3203
+ reason: accessReason(error)
3204
+ };
3205
+ }
3206
+ try {
3207
+ return buildIterationList(docsRoot, source, base, refName);
3208
+ } catch (error) {
3209
+ return {
3210
+ ...base,
3211
+ reason: accessReason(error)
3212
+ };
3213
+ }
3214
+ }
3215
+ function buildIterationList(docsRoot, source, base, refName) {
3216
+ if ('remote' === source) {
3217
+ const ref = resolveRemoteRef(docsRoot, refName);
3218
+ const snapshot = listRemoteIterations(docsRoot, ref);
3219
+ return {
3220
+ ...base,
3221
+ accessible: true,
3222
+ ref: {
3223
+ name: ref.ref,
3224
+ sha: ref.sha,
3225
+ committedAt: ref.committedAt
3226
+ },
3227
+ iterations: snapshot.iterations
3228
+ };
3229
+ }
3230
+ const entries = readdirSync(docsRoot, {
3231
+ withFileTypes: true
3232
+ }).filter((entry)=>entry.isDirectory() && !RESERVED_DIRS.has(entry.name) && !entry.name.startsWith('.')).map((entry)=>{
3233
+ const directory = external_node_path_join(docsRoot, entry.name);
3234
+ const developers = listMarkdownFiles(directory);
3235
+ const info = statSync(directory);
3236
+ return {
3237
+ name: entry.name,
3238
+ mtime: info.mtime.toISOString(),
3239
+ developers,
3240
+ hasPrd: external_node_fs_existsSync(external_node_path_join(directory, '_prd', 'meta.json'))
3241
+ };
3242
+ }).filter((entry)=>entry.developers.length > 0).sort((left, right)=>right.mtime.localeCompare(left.mtime));
3243
+ return {
3244
+ ...base,
3245
+ accessible: true,
3246
+ ref: null,
3247
+ iterations: entries
3248
+ };
3249
+ }
3250
+ function coerceIssue(value) {
3251
+ if (!utils_isRecord(value)) return null;
3252
+ const level = 'warning' === value['level'] ? 'warning' : 'error';
3253
+ const code = 'string' == typeof value['code'] ? value['code'] : 'UNKNOWN';
3254
+ const message = 'string' == typeof value['message'] ? value['message'] : '';
3255
+ const ref = 'string' == typeof value['ref'] ? value['ref'] : void 0;
3256
+ return void 0 === ref ? {
3257
+ level,
3258
+ code,
3259
+ message
3260
+ } : {
3261
+ level,
3262
+ code,
3263
+ message,
3264
+ ref
3265
+ };
3266
+ }
3267
+ function coerceRequirement(value) {
3268
+ if (!utils_isRecord(value)) return null;
3269
+ const id = 'string' == typeof value['id'] ? value['id'] : '';
3270
+ if (0 === id.length) return null;
3271
+ return {
3272
+ id,
3273
+ title: 'string' == typeof value['title'] ? value['title'] : '',
3274
+ terminal: 'string' == typeof value['terminal'] ? value['terminal'] : '',
3275
+ status: 'string' == typeof value['status'] ? value['status'] : '',
3276
+ progress: String(value['progress'] ?? ''),
3277
+ note: 'string' == typeof value['note'] ? value['note'] : '',
3278
+ updatedAt: 'string' == typeof value['updatedAt'] ? value['updatedAt'] : '',
3279
+ taskIds: isStringArray(value['taskIds']) ? value['taskIds'] : []
3280
+ };
3281
+ }
3282
+ function coerceTask(value) {
3283
+ if (!utils_isRecord(value)) return null;
3284
+ const id = 'string' == typeof value['id'] ? value['id'] : '';
3285
+ if (0 === id.length) return null;
3286
+ return {
3287
+ id,
3288
+ requirementId: 'string' == typeof value['requirementId'] ? value['requirementId'] : '',
3289
+ name: 'string' == typeof value['name'] ? value['name'] : '',
3290
+ type: 'string' == typeof value['type'] ? value['type'] : '',
3291
+ terminal: 'string' == typeof value['terminal'] ? value['terminal'] : '',
3292
+ dependencies: isStringArray(value['dependencies']) ? value['dependencies'] : [],
3293
+ selfTest: 'string' == typeof value['selfTest'] ? value['selfTest'] : '',
3294
+ acceptance: 'string' == typeof value['acceptance'] ? value['acceptance'] : '',
3295
+ status: 'string' == typeof value['status'] ? value['status'] : '',
3296
+ updatedAt: 'string' == typeof value['updatedAt'] ? value['updatedAt'] : ''
3297
+ };
3298
+ }
3299
+ function coerceInfo(value) {
3300
+ if (!utils_isRecord(value)) return {};
3301
+ const info = {};
3302
+ for (const [key, item] of Object.entries(value))if ('string' == typeof item) info[key] = item;
3303
+ return info;
3304
+ }
3305
+ function coercePayload(raw) {
3306
+ if (!utils_isRecord(raw)) return null;
3307
+ const stats = utils_isRecord(raw['stats']) ? raw['stats'] : {};
3308
+ const requirements = Array.isArray(raw['requirements']) ? raw['requirements'].map(coerceRequirement).filter((item)=>null !== item) : [];
3309
+ const tasks = Array.isArray(raw['tasks']) ? raw['tasks'].map(coerceTask).filter((item)=>null !== item) : [];
3310
+ const errors = Array.isArray(raw['errors']) ? raw['errors'].map(coerceIssue).filter((item)=>null !== item) : [];
3311
+ const warnings = Array.isArray(raw['warnings']) ? raw['warnings'].map(coerceIssue).filter((item)=>null !== item) : [];
3312
+ const asNumber = (value, fallback)=>'number' == typeof value ? value : fallback;
3313
+ return {
3314
+ valid: true === raw['valid'],
3315
+ iterationInfo: coerceInfo(raw['iterationInfo']),
3316
+ stats: {
3317
+ requirements: asNumber(stats['requirements'], requirements.length),
3318
+ tasks: asNumber(stats['tasks'], tasks.length),
3319
+ completedTasks: asNumber(stats['completedTasks'], tasks.filter((task)=>'已完成' === task.status).length),
3320
+ details: asNumber(stats['details'], 0)
3321
+ },
3322
+ requirements,
3323
+ tasks,
3324
+ errors,
3325
+ warnings
3326
+ };
3327
+ }
3328
+ function runValidator(input) {
3329
+ const script = input.scriptPath;
3330
+ if (null === script || !external_node_fs_existsSync(script)) return null;
3331
+ const args = [
3332
+ script,
3333
+ '--docs-root',
3334
+ input.docsRoot,
3335
+ '--iteration',
3336
+ input.iteration,
3337
+ '--developer',
3338
+ input.developer,
3339
+ '--role',
3340
+ input.role,
3341
+ '--format',
3342
+ 'json'
3343
+ ];
3344
+ for (const bin of [
3345
+ 'python3',
3346
+ 'python'
3347
+ ])try {
3348
+ const stdout = execFileSync(bin, args, {
3349
+ encoding: 'utf8',
3350
+ timeout: 10000,
3351
+ maxBuffer: 16777216
3352
+ });
3353
+ const parsed = coercePayload(JSON.parse(stdout));
3354
+ if (null !== parsed) return parsed;
3355
+ } catch (error) {
3356
+ const stdout = error.stdout;
3357
+ if ('string' == typeof stdout && stdout.trim().length > 0) try {
3358
+ const parsed = coercePayload(JSON.parse(stdout));
3359
+ if (null !== parsed) return parsed;
3360
+ } catch {}
3361
+ }
3362
+ return null;
3363
+ }
3364
+ function extractSection(markdown, heading) {
3365
+ const lines = markdown.split(/\r?\n/);
3366
+ let start = -1;
3367
+ for(let index = 0; index < lines.length; index += 1)if ((lines[index] ?? '').trim() === heading) {
3368
+ start = index + 1;
3369
+ break;
3370
+ }
3371
+ if (start < 0) return '';
3372
+ const collected = [];
3373
+ for(let index = start; index < lines.length; index += 1){
3374
+ const line = lines[index] ?? '';
3375
+ if (/^##\s+/.test(line)) break;
3376
+ collected.push(line);
3377
+ }
3378
+ return collected.join('\n').trim();
3379
+ }
3380
+ function splitDetails(markdown) {
3381
+ const section = extractSection(markdown, '## 四、任务详情');
3382
+ if (0 === section.length) return [];
3383
+ const blocks = [];
3384
+ const parts = section.split(/^###\s+/m).slice(1);
3385
+ for (const part of parts){
3386
+ const [firstLine, ...rest] = part.split(/\r?\n/);
3387
+ const heading = (firstLine ?? '').trim();
3388
+ const match = /^\[?([#\w\-\u4e00-\u9fa5]+)\]?\s*(.*)$/.exec(heading);
3389
+ const id = match?.[1] ?? heading;
3390
+ const name = match?.[2]?.trim() ?? '';
3391
+ blocks.push({
3392
+ id,
3393
+ name,
3394
+ markdown: rest.join('\n').trim()
3395
+ });
3396
+ }
3397
+ return blocks;
3398
+ }
3399
+ function parseMarkdownDoc(markdown) {
3400
+ const structureErrors = [];
3401
+ const readTable = (sectionHeading, headers)=>{
3402
+ const section = extractSection(markdown, sectionHeading);
3403
+ const rows = section.split(/\r?\n/).map((line)=>line.trim()).filter((line)=>line.startsWith('|')).map((line)=>line.replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell)=>cell.trim())).filter((cells)=>!cells.every((cell)=>/^:?-{2,}:?$/.test(cell) || 0 === cell.length));
3404
+ const [header, ...body] = rows;
3405
+ if (void 0 === header) return [];
3406
+ const matched = headers.every((name, index)=>(header[index] ?? '') === name);
3407
+ return matched ? body : [];
3408
+ };
3409
+ const requirementRows = readTable('## 二、需求清单', [
3410
+ '需求编号',
3411
+ '需求名称',
3412
+ '终端',
3413
+ '开发状态',
3414
+ '开发进度(%)',
3415
+ '备注',
3416
+ '最后更新'
3417
+ ]);
3418
+ const taskRows = readTable('## 三、任务清单', [
3419
+ '任务编号',
3420
+ '关联需求编号',
3421
+ '任务名称',
3422
+ '任务类型',
3423
+ '终端',
3424
+ '前置依赖任务编号',
3425
+ 'AI自测状态',
3426
+ '开发人工验收',
3427
+ '任务状态',
3428
+ '最后更新'
3429
+ ]);
3430
+ if (0 === requirementRows.length) structureErrors.push({
3431
+ level: 'error',
3432
+ code: 'REQUIREMENT_TABLE_MISMATCH',
3433
+ message: '需求清单表头与模板不符(需包含「最后更新」列),请按最新模板补齐'
3434
+ });
3435
+ if (0 === taskRows.length) structureErrors.push({
3436
+ level: 'error',
3437
+ code: 'TASK_TABLE_MISMATCH',
3438
+ message: '任务清单表头与模板不符(需包含「最后更新」列),请按最新模板补齐'
3439
+ });
3440
+ const requirements = requirementRows.map((row)=>({
3441
+ id: row[0] ?? '',
3442
+ title: row[1] ?? '',
3443
+ terminal: row[2] ?? '',
3444
+ status: row[3] ?? '',
3445
+ progress: row[4] ?? '',
3446
+ note: row[5] ?? '',
3447
+ updatedAt: row[6] ?? '',
3448
+ taskIds: []
3449
+ }));
3450
+ const tasks = taskRows.map((row)=>({
3451
+ id: row[0] ?? '',
3452
+ requirementId: row[1] ?? '',
3453
+ name: row[2] ?? '',
3454
+ type: row[3] ?? '',
3455
+ terminal: row[4] ?? '',
3456
+ dependencies: (row[5] ?? '').split(/[,,]/).map((item)=>item.trim()).filter((item)=>item.length > 0),
3457
+ selfTest: row[6] ?? '',
3458
+ acceptance: row[7] ?? '',
3459
+ status: row[8] ?? '',
3460
+ updatedAt: row[9] ?? ''
3461
+ }));
3462
+ for (const requirement of requirements)requirement.taskIds = tasks.filter((task)=>task.requirementId === requirement.id).map((task)=>task.id);
3463
+ const details = splitDetails(markdown);
3464
+ const infoMatch = /\|\s*迭代版本\s*\|\s*([^|]*)\|/.exec(markdown);
3465
+ const prdMatch = /\|\s*PRD 来源\s*\|\s*([^|]*)\|/.exec(markdown);
3466
+ const planMatch = /\|\s*排期计划\s*\|\s*([^|]*)\|/.exec(markdown);
3467
+ const ownerMatch = /\|\s*负责人\s*\|\s*([^|]*)\|/.exec(markdown);
3468
+ const scopeMatch = /\|\s*负责范围\s*\|\s*([^|]*)\|/.exec(markdown);
3469
+ const iterationInfo = {};
3470
+ const put = (key, match)=>{
3471
+ const value = match?.[1]?.trim();
3472
+ if (void 0 !== value && value.length > 0) iterationInfo[key] = value;
3473
+ };
3474
+ put('迭代版本', infoMatch);
3475
+ put('PRD 来源', prdMatch);
3476
+ put('排期计划', planMatch);
3477
+ put('负责人', ownerMatch);
3478
+ put('负责范围', scopeMatch);
3479
+ return {
3480
+ valid: false,
3481
+ iterationInfo,
3482
+ stats: {
3483
+ requirements: requirements.length,
3484
+ tasks: tasks.length,
3485
+ completedTasks: tasks.filter((task)=>'已完成' === task.status).length,
3486
+ details: details.length
3487
+ },
3488
+ requirements,
3489
+ tasks,
3490
+ errors: structureErrors,
3491
+ warnings: []
3492
+ };
3493
+ }
3494
+ function readMarkdown(target) {
3495
+ return readFileSync(target, 'utf8');
3496
+ }
3497
+ function readIterationDoc(docsRoot, iteration, developer, source = 'local', presetRef, refName) {
3498
+ const safeIteration = iterations_safeSegment(iteration, '迭代目录');
3499
+ const safeDeveloper = iterations_safeSegment(developer, '开发者标识');
3500
+ if ('remote' === source) {
3501
+ const ref = presetRef ?? resolveRemoteRef(docsRoot, refName);
3502
+ const exported = exportRemoteDoc(docsRoot, ref, safeIteration, safeDeveloper);
3503
+ const roleInferred = inferRole(exported.markdown);
3504
+ const scripted = runValidator({
3505
+ docsRoot: exported.dir,
3506
+ scriptPath: exported.scriptPath,
3507
+ iteration: safeIteration,
3508
+ developer: safeDeveloper,
3509
+ role: roleInferred
3510
+ });
3511
+ return {
3512
+ iteration: safeIteration,
3513
+ developer: safeDeveloper,
3514
+ file: `${safeIteration}/${safeDeveloper}.md`,
3515
+ mtime: exported.mtime,
3516
+ roleInferred,
3517
+ parser: null === scripted ? 'fallback' : "script",
3518
+ source: 'remote',
3519
+ ref: {
3520
+ name: ref.ref,
3521
+ sha: ref.sha
3522
+ },
3523
+ validation: scripted ?? parseMarkdownDoc(exported.markdown),
3524
+ details: splitDetails(exported.markdown)
3525
+ };
3526
+ }
3527
+ const directory = joinWithin(docsRoot, safeIteration);
3528
+ if (!external_node_fs_existsSync(directory)) throw new errors_CliError(`迭代目录不存在:${safeIteration}`, errors_EXIT.NOT_FOUND);
3529
+ const file = joinWithin(directory, `${safeDeveloper}.md`);
3530
+ if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${safeIteration}/${safeDeveloper}.md`, errors_EXIT.NOT_FOUND);
3531
+ const markdown = readMarkdown(file);
3532
+ const roleInferred = inferRole(markdown);
3533
+ const scripted = runValidator({
3534
+ docsRoot,
3535
+ scriptPath: external_node_path_join(docsRoot, "scripts", 'validate_task_doc.py'),
3536
+ iteration: safeIteration,
3537
+ developer: safeDeveloper,
3538
+ role: roleInferred
3539
+ });
3540
+ const validation = scripted ?? parseMarkdownDoc(markdown);
3541
+ const parser = null === scripted ? 'fallback' : "script";
3542
+ return {
3543
+ iteration: safeIteration,
3544
+ developer: safeDeveloper,
3545
+ file,
3546
+ mtime: statSync(file).mtime.toISOString(),
3547
+ roleInferred,
3548
+ parser,
3549
+ source: 'local',
3550
+ ref: null,
3551
+ validation,
3552
+ details: splitDetails(markdown)
3553
+ };
3554
+ }
3555
+ function readIterationSummary(docsRoot, iteration, source = 'local', refName) {
3556
+ const safeIteration = iterations_safeSegment(iteration, '迭代目录');
3557
+ const remoteRef = 'remote' === source ? resolveRemoteRef(docsRoot, refName) : null;
3558
+ let developers;
3559
+ if (null === remoteRef) {
3560
+ const directory = joinWithin(docsRoot, safeIteration);
3561
+ if (!external_node_fs_existsSync(directory)) throw new errors_CliError(`迭代目录不存在:${safeIteration}`, errors_EXIT.NOT_FOUND);
3562
+ developers = listMarkdownFiles(directory);
3563
+ } else {
3564
+ const snapshot = listRemoteIterations(docsRoot, remoteRef);
3565
+ const found = snapshot.iterations.find((item)=>item.name === safeIteration);
3566
+ if (void 0 === found) throw new errors_CliError(`远程快照中不存在迭代:${safeIteration}`, errors_EXIT.NOT_FOUND);
3567
+ developers = found.developers;
3568
+ }
3569
+ const summaries = [];
3570
+ const blocked = [];
3571
+ for (const entry of developers){
3572
+ const doc = readIterationDoc(docsRoot, safeIteration, entry.id, source, remoteRef ?? void 0);
3573
+ const statusCounts = {};
3574
+ const selfTestCounts = {};
3575
+ const acceptanceCounts = {};
3576
+ for (const task of doc.validation.tasks){
3577
+ bump(statusCounts, 0 === task.status.length ? '未知' : task.status);
3578
+ bump(selfTestCounts, normalizeSelfTest(task.selfTest));
3579
+ bump(acceptanceCounts, normalizeAcceptance(task.acceptance));
3580
+ }
3581
+ const byId = new Map(doc.validation.tasks.map((task)=>[
3582
+ task.id,
3583
+ task
3584
+ ]));
3585
+ for (const task of doc.validation.tasks){
3586
+ if ('已完成' === task.status) continue;
3587
+ const blocking = task.dependencies.map((dep)=>{
3588
+ const target = byId.get(dep);
3589
+ return void 0 === target ? null : {
3590
+ id: dep,
3591
+ status: target.status
3592
+ };
3593
+ }).filter((item)=>null !== item && '已完成' !== item.status);
3594
+ if (blocking.length > 0) blocked.push({
3595
+ developer: entry.id,
3596
+ taskId: task.id,
3597
+ name: task.name,
3598
+ dependencies: task.dependencies,
3599
+ blocking
3600
+ });
3601
+ }
3602
+ const requirementStatusCounts = {};
3603
+ for (const requirement of doc.validation.requirements)bump(requirementStatusCounts, 0 === requirement.status.length ? '未知' : requirement.status);
3604
+ summaries.push({
3605
+ id: entry.id,
3606
+ roleInferred: doc.roleInferred,
3607
+ parser: doc.parser,
3608
+ stats: doc.validation.stats,
3609
+ statusCounts,
3610
+ requirementStatusCounts,
3611
+ selfTestCounts,
3612
+ acceptanceCounts,
3613
+ errors: doc.validation.errors.length,
3614
+ warnings: doc.validation.warnings.length,
3615
+ mtime: doc.mtime
3616
+ });
3617
+ }
3618
+ const mergeCounts = (pick)=>{
3619
+ const merged = {};
3620
+ for (const item of summaries)for (const [status, count] of Object.entries(pick(item)))merged[status] = (merged[status] ?? 0) + count;
3621
+ return merged;
3622
+ };
3623
+ const totals = summaries.reduce((acc, item)=>({
3624
+ developers: acc.developers + 1,
3625
+ requirements: acc.requirements + item.stats.requirements,
3626
+ tasks: acc.tasks + item.stats.tasks,
3627
+ completedTasks: acc.completedTasks + item.stats.completedTasks,
3628
+ errors: acc.errors + item.errors,
3629
+ warnings: acc.warnings + item.warnings
3630
+ }), {
3631
+ developers: 0,
3632
+ requirements: 0,
3633
+ tasks: 0,
3634
+ completedTasks: 0,
3635
+ errors: 0,
3636
+ warnings: 0
3637
+ });
3638
+ return {
3639
+ iteration: safeIteration,
3640
+ docsRoot,
3641
+ source,
3642
+ ref: null === remoteRef ? null : {
3643
+ name: remoteRef.ref,
3644
+ sha: remoteRef.sha,
3645
+ committedAt: remoteRef.committedAt
3646
+ },
3647
+ totals: {
3648
+ ...totals,
3649
+ progress: 0 === totals.tasks ? 0 : Math.round(totals.completedTasks / totals.tasks * 100),
3650
+ taskStatusCounts: mergeCounts((item)=>item.statusCounts),
3651
+ requirementStatusCounts: mergeCounts((item)=>item.requirementStatusCounts),
3652
+ selfTestCounts: mergeCounts((item)=>item.selfTestCounts),
3653
+ acceptanceCounts: mergeCounts((item)=>item.acceptanceCounts)
3654
+ },
3655
+ developers: summaries,
3656
+ blocked
3657
+ };
3658
+ }
3659
+ const probeCache = new Map();
3660
+ const PROBE_TTL_MS = 60000;
3661
+ function cachedProbe(remote) {
3662
+ const hit = probeCache.get(remote);
3663
+ if (void 0 !== hit && Date.now() - hit.at < PROBE_TTL_MS) return hit.result;
3664
+ const result = probeRemote(remote);
3665
+ probeCache.set(remote, {
3666
+ at: Date.now(),
3667
+ result
3668
+ });
3669
+ return result;
3670
+ }
3671
+ function isManagedPath(root) {
3672
+ return root.includes('/.ylcwf/repos/');
3673
+ }
3674
+ function inspectOnboarding(configPath) {
3675
+ const loaded = loadConfig(configPath);
3676
+ const config = loaded.config;
3677
+ const mode = config?.profile.mode ?? 'developer';
3678
+ const role = config?.profile.role ?? 'frontend';
3679
+ const root = config?.docs.root ?? '';
3680
+ const remote = config?.docs.remote ?? DEFAULT_DOCS_REMOTE;
3681
+ const remoteIsDefault = config?.docs.remote === null || config?.docs.remote === void 0;
3682
+ const base = {
3683
+ hasConfig: loaded.exists,
3684
+ configValid: null !== config,
3685
+ mode,
3686
+ developer: config?.profile.developer ?? '',
3687
+ role,
3688
+ docsRoot: root,
3689
+ docsRemote: remote,
3690
+ remoteIsDefault,
3691
+ gitAvailable: isGitAvailable(),
3692
+ docsConfigured: root.trim().length > 0,
3693
+ docsAccessible: false,
3694
+ docsManaged: root.trim().length > 0 && isManagedPath(root),
3695
+ iterationCount: 0,
3696
+ reason: null,
3697
+ nextStep: 'ready'
3698
+ };
3699
+ if (!base.hasConfig) return {
3700
+ ...base,
3701
+ nextStep: 'create-config'
3702
+ };
3703
+ if (!base.configValid) return {
3704
+ ...base,
3705
+ nextStep: 'fix-config',
3706
+ reason: '配置文件结构不合法,请用 ylcwf doctor 查看详情'
3707
+ };
3708
+ if ('stakeholder' === mode) {
3709
+ if (!base.gitAvailable) return {
3710
+ ...base,
3711
+ nextStep: 'install-git',
3712
+ reason: '未检测到 git 命令,请先安装 Git'
3713
+ };
3714
+ const probe = cachedProbe(remote);
3715
+ if (!probe.authorized) return {
3716
+ ...base,
3717
+ nextStep: 'auth-remote',
3718
+ reason: probe.reason ?? '没有文档仓库访问权限,请联系管理员开通'
3719
+ };
3720
+ if (base.docsConfigured) {
3721
+ const listed = listIterations(root, 'local');
3722
+ if (listed.accessible) return {
3723
+ ...base,
3724
+ docsAccessible: true,
3725
+ iterationCount: listed.iterations.length,
3726
+ nextStep: 'ready'
3727
+ };
3728
+ return {
3729
+ ...base,
3730
+ reason: listed.reason,
3731
+ nextStep: 'prepare-cache'
3732
+ };
3733
+ }
3734
+ return {
3735
+ ...base,
3736
+ nextStep: 'prepare-cache',
3737
+ reason: '需要在本地准备只读副本'
3738
+ };
3739
+ }
3740
+ if (!base.docsConfigured) return {
3741
+ ...base,
3742
+ nextStep: 'set-docs-root',
3743
+ reason: '尚未选择本地文档仓库'
3744
+ };
3745
+ const listed = listIterations(root, 'local');
3746
+ if (listed.accessible) return {
3747
+ ...base,
3748
+ docsAccessible: true,
3749
+ iterationCount: listed.iterations.length,
3750
+ nextStep: 'ready'
3751
+ };
3752
+ return {
3753
+ ...base,
3754
+ reason: listed.reason,
3755
+ nextStep: 'set-docs-root'
3756
+ };
3757
+ }
3758
+ function prepareManagedDocs(configPath) {
3759
+ const loaded = loadConfig(configPath);
3760
+ if (null === loaded.config) throw new errors_CliError('配置未初始化或结构不合法,无法准备文档仓库', errors_EXIT.INVALID);
3761
+ if ('stakeholder' !== loaded.config.profile.mode) throw new errors_CliError('只有干系人模式会自动准备文档仓库;开发者请选择本地仓库路径', errors_EXIT.USAGE);
3762
+ const remote = loaded.config.docs.remote ?? DEFAULT_DOCS_REMOTE;
3763
+ const clone = ensureManagedClone(remote);
3764
+ const next = {
3765
+ ...loaded.config,
3766
+ docs: {
3767
+ root: clone.dir,
3768
+ remote,
3769
+ git: loaded.config.docs.git
3770
+ }
3771
+ };
3772
+ saveConfig(next, configPath);
3773
+ return inspectOnboarding(configPath);
3774
+ }
3775
+ function completeOnboarding(draftRaw, configPath) {
3776
+ const structural = checkConfig(draftRaw, {
3777
+ allowIncomplete: true,
3778
+ checkFs: false
3779
+ });
3780
+ if (null === structural.config || structural.issues.some((issue)=>'error' === issue.level)) {
3781
+ const detail = structural.issues.filter((issue)=>'error' === issue.level).map((issue)=>`- ${issue.message}`).join('\n');
3782
+ throw new errors_CliError(`配置校验未通过:\n${detail}`, errors_EXIT.INVALID);
3783
+ }
3784
+ const draft = structural.config;
3785
+ if ('developer' === draft.profile.mode && 0 === draft.profile.developer.trim().length) throw new errors_CliError('开发者标识不能为空', errors_EXIT.USAGE);
3786
+ let root = draft.docs.root;
3787
+ const remote = draft.docs.remote ?? DEFAULT_DOCS_REMOTE;
3788
+ if (0 === root.trim().length) {
3789
+ if ('stakeholder' !== draft.profile.mode) throw new errors_CliError('开发者必须选择本地文档仓库路径', errors_EXIT.USAGE);
3790
+ const clone = ensureManagedClone(remote);
3791
+ root = clone.dir;
3792
+ }
3793
+ saveConfig({
3794
+ ...draft,
3795
+ docs: {
3796
+ root,
3797
+ remote,
3798
+ git: draft.docs.git
3799
+ }
3800
+ }, configPath);
3801
+ return inspectOnboarding(configPath);
3802
+ }
3803
+ function assertDirectory(target) {
3804
+ const absolute = isAbsolute(target) ? resolve(target) : resolve(homedir(), target);
3805
+ if (!external_node_fs_existsSync(absolute)) throw new errors_CliError(`目录不存在:${absolute}`, errors_EXIT.NOT_FOUND);
3806
+ if (!statSync(absolute).isDirectory()) throw new errors_CliError(`不是目录:${absolute}`, errors_EXIT.USAGE);
3807
+ return absolute;
3808
+ }
3809
+ function listDirectories(target) {
3810
+ const start = void 0 === target || 0 === target.trim().length ? homedir() : target;
3811
+ const absolute = assertDirectory(start);
3812
+ const parentCandidate = dirname(absolute);
3813
+ const entries = [];
3814
+ for (const name of readdirSync(absolute)){
3815
+ const full = external_node_path_join(absolute, name);
3816
+ try {
3817
+ if (!statSync(full).isDirectory()) continue;
3818
+ } catch {
3819
+ continue;
3820
+ }
3821
+ entries.push({
3822
+ name,
3823
+ path: full,
3824
+ hidden: name.startsWith('.')
3825
+ });
3826
+ }
3827
+ entries.sort((left, right)=>{
3828
+ if (left.hidden !== right.hidden) return left.hidden ? 1 : -1;
3829
+ return left.name.localeCompare(right.name, 'zh-CN');
3830
+ });
3831
+ return {
3832
+ path: absolute,
3833
+ parent: parentCandidate === absolute ? null : parentCandidate,
3834
+ entries
3835
+ };
3836
+ }
3837
+ function openInFileManager(target) {
3838
+ try {
3839
+ const absolute = assertDirectory(target);
3840
+ const command = 'darwin' === process.platform ? 'open' : 'win32' === process.platform ? 'explorer' : 'xdg-open';
3841
+ spawn(command, [
3842
+ absolute
3843
+ ], {
3844
+ detached: true,
3845
+ stdio: 'ignore'
3846
+ }).unref();
3847
+ return {
3848
+ ok: true,
3849
+ message: `已打开 ${absolute}`
3850
+ };
3851
+ } catch (error) {
3852
+ const message = error instanceof errors_CliError ? error.message : String(error);
3853
+ return {
3854
+ ok: false,
3855
+ message
3856
+ };
3857
+ }
3858
+ }
3859
+ let cache = null;
3860
+ const CACHE_TTL_MS = 600000;
3861
+ function isNewer(a, b) {
3862
+ const parse = (text)=>text.replace(/^v/, '').split('-')[0]?.split('.').map((part)=>Number.parseInt(part, 10) || 0) ?? [];
3863
+ const left = parse(a);
3864
+ const right = parse(b);
3865
+ for(let index = 0; index < Math.max(left.length, right.length); index += 1){
3866
+ const diff = (left[index] ?? 0) - (right[index] ?? 0);
3867
+ if (0 !== diff) return diff > 0;
3868
+ }
3869
+ return false;
3870
+ }
3871
+ async function fetchManifest(url) {
3872
+ try {
3873
+ const response = await fetch(url, {
3874
+ signal: AbortSignal.timeout(5000)
3875
+ });
3876
+ if (!response.ok) return null;
3877
+ const payload = await response.json();
3878
+ if ('string' != typeof payload.version || 0 === payload.version.length) return null;
3879
+ return {
3880
+ current: "0.3.0",
3881
+ latest: payload.version,
3882
+ hasUpdate: isNewer(payload.version, "0.3.0"),
3883
+ downloadUrl: 'string' == typeof payload.downloadUrl ? payload.downloadUrl : null,
3884
+ source: 'manifest',
3885
+ checkedAt: new Date().toISOString(),
3886
+ error: null
3887
+ };
3888
+ } catch {
3889
+ return null;
3890
+ }
3891
+ }
3892
+ async function fetchNpm() {
3893
+ const base = {
3894
+ current: "0.3.0",
3895
+ latest: null,
3896
+ hasUpdate: false,
3897
+ downloadUrl: null,
3898
+ source: 'npm',
3899
+ checkedAt: new Date().toISOString(),
3900
+ error: null
3901
+ };
3902
+ try {
3903
+ const response = await fetch('https://registry.npmjs.org/ylcwf/latest', {
3904
+ signal: AbortSignal.timeout(5000)
3905
+ });
3906
+ if (!response.ok) return {
3907
+ ...base,
3908
+ source: 'none',
3909
+ error: `版本服务不可用(HTTP ${response.status})`
3910
+ };
3911
+ const payload = await response.json();
3912
+ const latest = 'string' == typeof payload.version ? payload.version : null;
3913
+ if (null === latest) return {
3914
+ ...base,
3915
+ source: 'none',
3916
+ error: '版本服务返回内容异常'
3917
+ };
3918
+ return {
3919
+ ...base,
3920
+ latest,
3921
+ hasUpdate: isNewer(latest, "0.3.0"),
3922
+ downloadUrl: 'https://www.npmjs.com/package/ylcwf'
3923
+ };
3924
+ } catch (error) {
3925
+ const message = error instanceof Error ? error.message : String(error);
3926
+ return {
3927
+ ...base,
3928
+ source: 'none',
3929
+ error: `无法连接版本服务:${message.split('\n')[0]}`
3930
+ };
3931
+ }
3932
+ }
3933
+ async function checkUpdate(force = false) {
3934
+ if (!force && null !== cache && Date.now() - cache.at < CACHE_TTL_MS) return cache.result;
3935
+ const manifestUrl = process.env['YLCWF_UPDATE_MANIFEST']?.trim() ?? '';
3936
+ let result = manifestUrl.length > 0 ? await fetchManifest(manifestUrl) : null;
3937
+ result ??= await fetchNpm();
3938
+ cache = {
3939
+ at: Date.now(),
3940
+ result
3941
+ };
3942
+ return result;
3943
+ }
3944
+ function requireDocsRoot(configPath) {
3945
+ const loaded = loadConfig(configPath);
3946
+ const root = loaded.config?.docs.root ?? '';
3947
+ if (0 === root.length) throw new errors_CliError('未配置文档仓库:请先在「文档仓库」页填写 docs.root 并保存', errors_EXIT.NOT_FOUND);
3948
+ return root;
3949
+ }
3950
+ function parseSource(value) {
3951
+ return 'remote' === value ? 'remote' : 'local';
3952
+ }
3953
+ function pickString(body, key) {
3954
+ if ('object' != typeof body || null === body) return '';
3955
+ const value = Reflect.get(body, key);
3956
+ return 'string' == typeof value ? value : '';
3957
+ }
3958
+ function pickOptionalString(body, key) {
3959
+ const value = pickString(body, key).trim();
3960
+ return 0 === value.length ? void 0 : value;
3961
+ }
3962
+ const MIME = {
3963
+ '.html': 'text/html; charset=utf-8',
3964
+ '.js': "text/javascript; charset=utf-8",
3965
+ '.mjs': "text/javascript; charset=utf-8",
3966
+ '.css': 'text/css; charset=utf-8',
3967
+ '.json': 'application/json; charset=utf-8',
3968
+ '.svg': 'image/svg+xml',
3969
+ '.png': 'image/png',
3970
+ '.jpg': 'image/jpeg',
3971
+ '.webp': 'image/webp',
3972
+ '.woff2': 'font/woff2',
3973
+ '.ico': 'image/x-icon'
3974
+ };
3975
+ const MAX_BODY = 2097152;
3976
+ function sendJson(response, status, payload) {
3977
+ const body = JSON.stringify(payload);
3978
+ response.writeHead(status, {
3979
+ 'content-type': 'application/json; charset=utf-8',
3980
+ 'content-length': Buffer.byteLength(body),
3981
+ 'cache-control': 'no-store'
3982
+ });
3983
+ response.end(body);
3984
+ }
3985
+ function sendError(response, error) {
3986
+ if (error instanceof errors_CliError) return void sendJson(response, error.exitCode === errors_EXIT.NOT_FOUND ? 404 : 400, {
3987
+ error: {
3988
+ code: error.exitCode,
3989
+ message: error.message
3990
+ }
3991
+ });
3992
+ sendJson(response, 500, {
3993
+ error: {
3994
+ code: 500,
3995
+ message: error instanceof Error ? error.message : String(error)
3996
+ }
3997
+ });
3998
+ }
3999
+ async function readJsonBody(request) {
4000
+ const chunks = [];
4001
+ let size = 0;
4002
+ for await (const chunk of request){
4003
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
4004
+ size += buffer.length;
4005
+ if (size > MAX_BODY) throw new errors_CliError('请求体过大', errors_EXIT.USAGE);
4006
+ chunks.push(buffer);
4007
+ }
4008
+ if (0 === size) return;
4009
+ try {
4010
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
4011
+ } catch {
4012
+ throw new errors_CliError('请求体不是合法 JSON', errors_EXIT.USAGE);
4013
+ }
4014
+ }
4015
+ function resolveStaticPath(uiDir, pathname) {
4016
+ const decoded = decodeURIComponent(pathname);
4017
+ const target = resolve(uiDir, `.${'/' === decoded ? '/index.html' : decoded}`);
4018
+ const root = resolve(uiDir) + sep;
4019
+ return target.startsWith(root) ? target : null;
4020
+ }
4021
+ function serveStatic(response, uiDir, pathname) {
4022
+ const target = resolveStaticPath(uiDir, pathname);
4023
+ if (null === target || !external_node_fs_existsSync(target) || !statSync(target).isFile()) return void sendJson(response, 404, {
4024
+ error: {
4025
+ code: 404,
4026
+ message: `未找到静态资源:${pathname}`
4027
+ }
4028
+ });
4029
+ const body = readFileSync(target);
4030
+ const cacheControl = pathname.startsWith('/assets/') ? 'public, max-age=31536000, immutable' : 'no-cache, must-revalidate';
4031
+ response.writeHead(200, {
4032
+ 'content-type': MIME[extname(target)] ?? 'application/octet-stream',
4033
+ 'content-length': body.length,
4034
+ 'cache-control': cacheControl
4035
+ });
4036
+ response.end(body);
4037
+ }
4038
+ async function startServer(options) {
4039
+ const host = options.host ?? '127.0.0.1';
4040
+ const token = options.token;
4041
+ const server = external_node_http_createServer((request, response)=>{
4042
+ (async ()=>{
4043
+ try {
4044
+ const url = new URL(request.url ?? '/', `http://${host}`);
4045
+ const hostHeader = (request.headers.host ?? '').split(':')[0] ?? '';
4046
+ if ('127.0.0.1' !== hostHeader && 'localhost' !== hostHeader) return void sendJson(response, 403, {
4047
+ error: {
4048
+ code: 403,
4049
+ message: '仅允许本地访问'
4050
+ }
4051
+ });
4052
+ if (!url.pathname.startsWith('/api/')) return void serveStatic(response, options.uiDir, url.pathname);
4053
+ const provided = request.headers['x-ylcwf-token'] ?? url.searchParams.get('token');
4054
+ if (provided !== token) return void sendJson(response, 401, {
4055
+ error: {
4056
+ code: 401,
4057
+ message: '令牌无效,请从启动时打开的地址访问'
4058
+ }
4059
+ });
4060
+ if ('GET' === request.method && '/api/state' === url.pathname) return void sendJson(response, 200, readState(options.configPath));
4061
+ if ('PUT' === request.method && '/api/config' === url.pathname) {
4062
+ const body = await readJsonBody(request);
4063
+ const raw = null !== body && 'object' == typeof body && 'config' in body ? body.config : body;
4064
+ sendJson(response, 200, saveConfig(raw, options.configPath));
4065
+ return;
4066
+ }
4067
+ if ('POST' === request.method && '/api/resolve' === url.pathname) {
4068
+ const body = await readJsonBody(request);
4069
+ const payload = body ?? {};
4070
+ const name = 'string' == typeof payload.name ? payload.name : '';
4071
+ const side = 'frontend' === payload.side || 'backend' === payload.side ? payload.side : void 0;
4072
+ sendJson(response, 200, resolveRequest(name, side, options.configPath));
4073
+ return;
4074
+ }
4075
+ if ('GET' === request.method && '/api/inspect' === url.pathname) {
4076
+ const target = url.searchParams.get('path') ?? '';
4077
+ sendJson(response, 200, inspectPath(target));
4078
+ return;
4079
+ }
4080
+ if ('GET' === request.method && '/api/onboarding' === url.pathname) return void sendJson(response, 200, inspectOnboarding(options.configPath));
4081
+ if ('POST' === request.method && '/api/reset' === url.pathname) {
4082
+ const body = await readJsonBody(request);
4083
+ const all = 'object' == typeof body && null !== body && true === Reflect.get(body, 'all');
4084
+ sendJson(response, 200, resetConfig(all, options.configPath));
4085
+ return;
4086
+ }
4087
+ if ('POST' === request.method && '/api/onboarding/prepare' === url.pathname) return void sendJson(response, 200, prepareManagedDocs(options.configPath));
4088
+ if ('POST' === request.method && '/api/onboarding/complete' === url.pathname) {
4089
+ const body = await readJsonBody(request);
4090
+ const payload = body ?? {};
4091
+ sendJson(response, 200, completeOnboarding(payload.config, options.configPath));
4092
+ return;
4093
+ }
4094
+ if ('POST' === request.method && '/api/git/probe' === url.pathname) {
4095
+ const body = await readJsonBody(request);
4096
+ sendJson(response, 200, probeRemote(pickString(body, 'remote')));
4097
+ return;
4098
+ }
4099
+ if ('POST' === request.method && '/api/docs/sync' === url.pathname) {
4100
+ const body = await readJsonBody(request);
4101
+ sendJson(response, 200, syncManagedRepo(pickString(body, 'dir')));
4102
+ return;
4103
+ }
4104
+ if ('GET' === request.method && '/api/fs/list' === url.pathname) return void sendJson(response, 200, listDirectories(url.searchParams.get('path') ?? void 0));
4105
+ if ('POST' === request.method && '/api/fs/open' === url.pathname) {
4106
+ const body = await readJsonBody(request);
4107
+ sendJson(response, 200, openInFileManager(pickString(body, 'path')));
4108
+ return;
4109
+ }
4110
+ if ('POST' === request.method && '/api/reveal' === url.pathname) return void sendJson(response, 200, openInFileManager(dirname(paths_resolveConfigPath(options.configPath))));
4111
+ if ('GET' === request.method && '/api/task-actions' === url.pathname) {
4112
+ const loaded = loadConfig(options.configPath);
4113
+ const developer = url.searchParams.get('developer') ?? '';
4114
+ if (null === loaded.config || developer !== loaded.config.profile.developer) return void sendJson(response, 200, {
4115
+ actions: {},
4116
+ editable: false
4117
+ });
4118
+ const root = requireDocsRoot(options.configPath);
4119
+ sendJson(response, 200, {
4120
+ editable: 'developer' === loaded.config.profile.mode,
4121
+ actions: availableActions({
4122
+ docsRoot: root,
4123
+ iteration: url.searchParams.get('iteration') ?? '',
4124
+ developer
4125
+ })
4126
+ });
4127
+ return;
4128
+ }
4129
+ if ('POST' === request.method && '/api/task-action' === url.pathname) {
4130
+ const body = await readJsonBody(request);
4131
+ const loaded = loadConfig(options.configPath);
4132
+ if (null === loaded.config) return void sendJson(response, 400, {
4133
+ error: {
4134
+ code: 400,
4135
+ message: '配置未初始化'
4136
+ }
4137
+ });
4138
+ const developer = pickString(body, 'developer');
4139
+ if ('developer' !== loaded.config.profile.mode) return void sendJson(response, 403, {
4140
+ error: {
4141
+ code: 403,
4142
+ message: '干系人模式不支持修改状态'
4143
+ }
4144
+ });
4145
+ if (developer !== loaded.config.profile.developer) return void sendJson(response, 403, {
4146
+ error: {
4147
+ code: 403,
4148
+ message: '只能修改自己的任务文档'
4149
+ }
4150
+ });
4151
+ const action = pickString(body, 'action');
4152
+ if (!(action in ACTION_META)) return void sendJson(response, 400, {
4153
+ error: {
4154
+ code: 400,
4155
+ message: `未知动作:${action}`
4156
+ }
4157
+ });
4158
+ const root = requireDocsRoot(options.configPath);
4159
+ sendJson(response, 200, applyTaskAction({
4160
+ docsRoot: root,
4161
+ iteration: pickString(body, 'iteration'),
4162
+ developer,
4163
+ taskId: pickString(body, 'taskId'),
4164
+ action: action,
4165
+ policy: loaded.config.docs.git?.ui ?? {
4166
+ commit: true,
4167
+ push: false
4168
+ }
4169
+ }));
4170
+ return;
4171
+ }
4172
+ if ('POST' === request.method && '/api/task-batch' === url.pathname) {
4173
+ const body = await readJsonBody(request);
4174
+ const loaded = loadConfig(options.configPath);
4175
+ if (null === loaded.config) return void sendJson(response, 400, {
4176
+ error: {
4177
+ code: 400,
4178
+ message: '配置未初始化'
4179
+ }
4180
+ });
4181
+ const developer = pickString(body, 'developer');
4182
+ if ('developer' !== loaded.config.profile.mode) return void sendJson(response, 403, {
4183
+ error: {
4184
+ code: 403,
4185
+ message: '干系人模式不支持修改状态'
4186
+ }
4187
+ });
4188
+ if (developer !== loaded.config.profile.developer) return void sendJson(response, 403, {
4189
+ error: {
4190
+ code: 403,
4191
+ message: '只能修改自己的任务文档'
4192
+ }
4193
+ });
4194
+ const action = pickString(body, 'action');
4195
+ if (!(action in ACTION_META)) return void sendJson(response, 400, {
4196
+ error: {
4197
+ code: 400,
4198
+ message: `未知动作:${action}`
4199
+ }
4200
+ });
4201
+ const payload = body ?? {};
4202
+ const taskIds = Array.isArray(payload.taskIds) ? payload.taskIds.filter((item)=>'string' == typeof item) : [];
4203
+ sendJson(response, 200, applyBatchAction({
4204
+ docsRoot: requireDocsRoot(options.configPath),
4205
+ iteration: pickString(body, 'iteration'),
4206
+ developer,
4207
+ taskIds,
4208
+ action: action,
4209
+ policy: loaded.config.docs.git?.ui ?? {
4210
+ commit: true,
4211
+ push: false
4212
+ }
4213
+ }));
4214
+ return;
4215
+ }
4216
+ if ('GET' === request.method && '/api/task-history' === url.pathname) return void sendJson(response, 200, readTaskHistory({
4217
+ iteration: url.searchParams.get('iteration') ?? '',
4218
+ developer: url.searchParams.get('developer') ?? '',
4219
+ taskId: url.searchParams.get('taskId') ?? void 0,
4220
+ limit: 5
4221
+ }));
4222
+ if ('GET' === request.method && '/api/update/check' === url.pathname) return void sendJson(response, 200, await checkUpdate('1' === url.searchParams.get('force')));
4223
+ if ('GET' === request.method && '/api/git/branches' === url.pathname) return void sendJson(response, 200, getBranchInfo(requireDocsRoot(options.configPath)));
4224
+ if ('GET' === request.method && '/api/git/status' === url.pathname) return void sendJson(response, 200, getGitStatus(requireDocsRoot(options.configPath)));
4225
+ if ('POST' === request.method && '/api/git/fetch' === url.pathname) return void sendJson(response, 200, fetchRemote(requireDocsRoot(options.configPath)));
4226
+ if ('GET' === request.method && '/api/iterations' === url.pathname) {
4227
+ const source = parseSource(url.searchParams.get('source'));
4228
+ const loaded = loadConfig(options.configPath);
4229
+ const ref = url.searchParams.get('ref') ?? void 0;
4230
+ sendJson(response, 200, listIterations(loaded.config?.docs.root ?? '', source, ref));
4231
+ return;
4232
+ }
4233
+ if ('POST' === request.method && '/api/iteration-summary' === url.pathname) {
4234
+ const body = await readJsonBody(request);
4235
+ const root = requireDocsRoot(options.configPath);
4236
+ sendJson(response, 200, readIterationSummary(root, pickString(body, 'iteration'), parseSource(pickString(body, 'source')), pickOptionalString(body, 'ref')));
4237
+ return;
4238
+ }
4239
+ if ('POST' === request.method && '/api/iteration-doc' === url.pathname) {
4240
+ const body = await readJsonBody(request);
4241
+ const root = requireDocsRoot(options.configPath);
4242
+ sendJson(response, 200, readIterationDoc(root, pickString(body, 'iteration'), pickString(body, 'developer'), parseSource(pickString(body, 'source')), void 0, pickOptionalString(body, 'ref')));
4243
+ return;
4244
+ }
4245
+ if ('POST' === request.method && '/api/backups/restore' === url.pathname) {
4246
+ const body = await readJsonBody(request);
4247
+ const payload = body ?? {};
4248
+ sendJson(response, 200, restoreBackup(String(payload.name ?? ''), options.configPath));
4249
+ return;
4250
+ }
4251
+ sendJson(response, 404, {
4252
+ error: {
4253
+ code: 404,
4254
+ message: `未知接口:${url.pathname}`
4255
+ }
4256
+ });
4257
+ } catch (error) {
4258
+ sendError(response, error);
4259
+ }
4260
+ })();
4261
+ });
4262
+ await new Promise((resolveListen, rejectListen)=>{
4263
+ server.once('error', rejectListen);
4264
+ server.listen(options.port ?? 4317, host, ()=>resolveListen());
4265
+ });
4266
+ const address = server.address();
4267
+ const port = 'object' == typeof address && null !== address ? address.port : options.port ?? 4317;
4268
+ const url = `http://${host}:${port}/?token=${token}`;
4269
+ return {
4270
+ server,
4271
+ url,
4272
+ port,
4273
+ close: ()=>new Promise((resolveClose, rejectClose)=>{
4274
+ server.close((error)=>error ? rejectClose(error) : resolveClose());
4275
+ })
4276
+ };
4277
+ }
4278
+ function assertUiBuilt(uiDir) {
4279
+ if (!external_node_fs_existsSync(external_node_path_join(uiDir, 'index.html'))) throw new errors_CliError(`前端资源未构建:${uiDir}\n请先运行:pnpm build:ui(开发时用 pnpm dev:ui)`, errors_EXIT.INVALID);
4280
+ }
4281
+ function defaultUiDir() {
4282
+ const here = dirname(fileURLToPath(import.meta.url));
4283
+ const candidates = [
4284
+ resolve(here, '..', 'ui-dist'),
4285
+ resolve(here, '..', '..', 'ui-dist'),
4286
+ resolve(process.cwd(), 'ui-dist')
4287
+ ];
4288
+ return candidates.find((dir)=>external_node_fs_existsSync(external_node_path_join(dir, 'index.html'))) ?? candidates[0] ?? 'ui-dist';
4289
+ }
4290
+ function openBrowser(url) {
4291
+ const command = 'darwin' === process.platform ? 'open' : 'win32' === process.platform ? 'cmd' : 'xdg-open';
4292
+ const args = 'win32' === process.platform ? [
4293
+ '/c',
4294
+ 'start',
4295
+ '',
4296
+ url
4297
+ ] : [
4298
+ url
4299
+ ];
4300
+ try {
4301
+ spawn(command, args, {
4302
+ detached: true,
4303
+ stdio: 'ignore'
4304
+ }).unref();
4305
+ } catch {}
4306
+ }
4307
+ function loadOrCreateToken() {
4308
+ const path = serveTokenPath();
4309
+ try {
4310
+ const existing = readFileSync(path, 'utf8').trim();
4311
+ if (/^[a-f0-9]{32}$/.test(existing)) return existing;
4312
+ } catch {}
4313
+ const token = randomBytes(16).toString('hex');
4314
+ try {
4315
+ mkdirSync(CONFIG_DIR, {
4316
+ recursive: true
4317
+ });
4318
+ writeFileSync(path, `${token}\n`, {
4319
+ mode: 384
4320
+ });
4321
+ chmodSync(path, 384);
4322
+ } catch {}
4323
+ return token;
4324
+ }
4325
+ function isPortFree(port) {
4326
+ return new Promise((resolveFree)=>{
4327
+ const probe = createServer();
4328
+ probe.once('error', ()=>resolveFree(false));
4329
+ probe.once('listening', ()=>probe.close(()=>resolveFree(true)));
4330
+ probe.listen(port, '127.0.0.1');
4331
+ });
4332
+ }
4333
+ async function findAvailablePort(desired, attempts = 20) {
4334
+ for(let offset = 0; offset < attempts; offset += 1){
4335
+ const candidate = desired + offset;
4336
+ if (candidate > 65535) break;
4337
+ if (await isPortFree(candidate)) return candidate;
4338
+ }
4339
+ throw new errors_CliError(`端口 ${desired}–${desired + attempts - 1} 均被占用,请用 --port 指定其他端口`, errors_EXIT.USAGE);
4340
+ }
4341
+ async function runServe(options) {
4342
+ const uiDir = void 0 !== options.uiDir ? resolve(options.uiDir) : defaultUiDir();
4343
+ assertUiBuilt(uiDir);
4344
+ const port = void 0 === options.port ? 4317 : Number.parseInt(options.port, 10);
4345
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new errors_CliError(`--port 不是合法端口:${options.port ?? ''}`, errors_EXIT.USAGE);
4346
+ const token = loadOrCreateToken();
4347
+ const actualPort = await findAvailablePort(port);
4348
+ const running = await startServer({
4349
+ configPath: options.config,
4350
+ uiDir,
4351
+ token,
4352
+ port: actualPort
4353
+ });
4354
+ if (actualPort !== port) printLine(`端口 ${port} 已被占用,已自动改用 ${actualPort}`);
4355
+ printLine(`ylcwf 工作台已启动:${running.url}`);
4356
+ printLine(`配置文件:${paths_resolveConfigPath(options.config)}`);
4357
+ printLine('按 Ctrl+C 停止服务');
4358
+ if (false !== options.open) openBrowser(running.url);
4359
+ await new Promise((resolveStop)=>{
4360
+ const stop = ()=>{
4361
+ running.close().finally(()=>resolveStop());
4362
+ };
4363
+ process.once('SIGINT', stop);
4364
+ process.once('SIGTERM', stop);
4365
+ });
4366
+ }
4367
+ function registerServe(program) {
4368
+ program.command('serve').description('启动本地可视化配置控制台(仅监听 127.0.0.1)').option('-c, --config <path>', '指定配置文件路径').option('--port <port>', '监听端口,默认 4317').option('--ui-dir <dir>', '前端静态资源目录(默认随包发布)').option('--no-open', '不自动打开浏览器').action(async (options)=>{
4369
+ await runServe(options);
4370
+ });
4371
+ }
4372
+ async function runReset(options) {
4373
+ const configPath = paths_resolveConfigPath(options.config);
4374
+ const targets = collectResetTargets(configPath, true === options.all);
4375
+ if (0 === targets.length) return void printLine('没有需要清除的配置,当前已经是干净状态。');
4376
+ printLine('将要清除:');
4377
+ for (const target of targets)printLine(` - ${describeTarget(target)}`);
4378
+ if (true === options.dryRun) return void printLine('\n(--dry-run:未执行任何删除)');
4379
+ if (true !== options.yes) {
4380
+ if (true !== process.stdin.isTTY) throw new errors_CliError('非交互环境需要显式加 --yes 才会执行删除', errors_EXIT.USAGE);
4381
+ const confirmed = await __rspack_external__clack_prompts_d2d5c36d.confirm({
4382
+ message: '确认清除以上内容?此操作不可撤销',
4383
+ initialValue: false
4384
+ });
4385
+ if (__rspack_external__clack_prompts_d2d5c36d.isCancel(confirmed) || true !== confirmed) return void __rspack_external__clack_prompts_d2d5c36d.cancel('已取消');
4386
+ }
4387
+ const removed = performReset(configPath, targets);
4388
+ printLine(`\n已清除 ${removed} 项。下次打开工作台会重新进入首次引导。`);
4389
+ }
4390
+ function registerReset(program) {
4391
+ program.command('reset').description('清除本机配置(配置、备份、可选托管副本),用于从零重新引导').option('-c, --config <path>', '指定配置文件路径').option('--all', '同时清除 ~/.ylcwf/repos 下的托管文档仓库副本').option('--yes', '跳过确认').option('--dry-run', '只列出将要删除的内容').action(async (options)=>{
4392
+ await runReset(options);
4393
+ });
4394
+ }
4395
+ function buildProgram() {
4396
+ const program = new Command();
4397
+ program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与终端仓库映射').version("0.3.0", '-v, --version', '显示版本号').showHelpAfterError();
4398
+ registerInit(program);
4399
+ registerShow(program);
4400
+ registerGet(program);
4401
+ registerSet(program);
4402
+ registerTerminal(program);
4403
+ registerTask(program);
4404
+ registerResolve(program);
4405
+ registerDoctor(program);
4406
+ registerPath(program);
4407
+ registerServe(program);
4408
+ registerReset(program);
4409
+ return program;
4410
+ }
4411
+ function runBare(configPath) {
4412
+ showConfig(configPath, process.stdout.isTTY ? 'human' : 'json');
4413
+ }
4414
+ function splitGlobalArgs(argv) {
4415
+ const rest = [];
4416
+ let config;
4417
+ for(let index = 0; index < argv.length; index += 1){
4418
+ const arg = argv[index] ?? '';
4419
+ if ('-c' === arg || '--config' === arg) {
4420
+ const value = argv[index + 1];
4421
+ if (void 0 !== value) config = value;
4422
+ index += 1;
4423
+ continue;
4424
+ }
4425
+ if (arg.startsWith('--config=')) {
4426
+ config = arg.slice(9);
4427
+ continue;
4428
+ }
4429
+ rest.push(arg);
4430
+ }
4431
+ return void 0 === config ? {
4432
+ rest
4433
+ } : {
4434
+ config,
4435
+ rest
4436
+ };
4437
+ }
4438
+ async function main() {
4439
+ const { config, rest } = splitGlobalArgs(process.argv.slice(2));
4440
+ const wantsMeta = rest.some((arg)=>[
4441
+ '-h',
4442
+ '--help',
4443
+ '-v',
4444
+ '--version'
4445
+ ].includes(arg));
1469
4446
  const hasSubcommand = rest.some((arg)=>!arg.startsWith('-'));
1470
- if (!hasSubcommand && !wantsMeta) return void runBare(config);
4447
+ if (!hasSubcommand && !wantsMeta) {
4448
+ const unknown = rest.find((arg)=>arg.startsWith('-'));
4449
+ if (void 0 !== unknown) {
4450
+ printError(`error: unknown option '${unknown}'`);
4451
+ process.exit(1);
4452
+ }
4453
+ runBare(config);
4454
+ return;
4455
+ }
1471
4456
  await buildProgram().parseAsync(process.argv);
1472
4457
  }
1473
4458
  main().catch((error)=>{