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