ylcwf 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { EventEmitter } from "node:events";
2
2
  import node_child_process, { execFile, execFileSync, spawn } from "node:child_process";
3
3
  import node_path, { basename, dirname as external_node_path_dirname, extname, isAbsolute as external_node_path_isAbsolute, join as external_node_path_join, relative as external_node_path_relative, resolve as external_node_path_resolve, sep } from "node:path";
4
- import node_fs, { appendFileSync, chmodSync, closeSync, copyFileSync, existsSync as external_node_fs_existsSync, mkdirSync, openSync, readFileSync, readdirSync as external_node_fs_readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
4
+ import node_fs, { accessSync, appendFileSync, chmodSync, closeSync, constants, copyFileSync, existsSync as external_node_fs_existsSync, mkdirSync, openSync, readFileSync, readdirSync as external_node_fs_readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync, writeSync } from "node:fs";
5
5
  import node_process, { stdin as external_node_process_stdin, stdout as external_node_process_stdout } from "node:process";
6
6
  import { stripVTControlCharacters as external_node_util_stripVTControlCharacters, styleText as external_node_util_styleText } from "node:util";
7
7
  import node_readline from "node:readline";
@@ -8194,10 +8194,12 @@ const errors_EXIT = {
8194
8194
  };
8195
8195
  class errors_CliError extends Error {
8196
8196
  exitCode;
8197
- constructor(message, exitCode){
8197
+ details;
8198
+ constructor(message, exitCode, details){
8198
8199
  super(message);
8199
8200
  this.name = 'CliError';
8200
8201
  this.exitCode = exitCode;
8202
+ this.details = details;
8201
8203
  }
8202
8204
  }
8203
8205
  function printJson(value) {
@@ -8216,13 +8218,14 @@ function enableJsonErrors(value) {
8216
8218
  function jsonErrorsEnabled() {
8217
8219
  return jsonErrors;
8218
8220
  }
8219
- function printJsonError(message, exitCode) {
8221
+ function printJsonError(message, exitCode, details) {
8220
8222
  printJson({
8221
8223
  ok: false,
8222
8224
  exitCode,
8223
8225
  error: {
8224
8226
  message,
8225
- code: exitCode
8227
+ code: exitCode,
8228
+ ...details
8226
8229
  }
8227
8230
  });
8228
8231
  }
@@ -9248,6 +9251,85 @@ function historyPath() {
9248
9251
  function backupsDir(configPath) {
9249
9252
  return external_node_path_join(external_node_path_dirname(configPath), 'backups');
9250
9253
  }
9254
+ const HINTS = {
9255
+ EPERM: '策略拒绝(不是普通权限不足)。常见于 AI 会话只被授权写当前工作区,或文件带不可修改标记',
9256
+ EACCES: '权限不足。目标目录的属主或权限位不允许当前用户写入',
9257
+ EROFS: '目标位于只读文件系统或只读挂载上',
9258
+ EBUSY: '文件正被其它进程占用(IDE、同步盘、杀毒软件)',
9259
+ ETXTBSY: '文件正在被当作可执行文件使用',
9260
+ ENOSPC: '磁盘空间不足',
9261
+ EMFILE: '进程打开的文件数超过上限'
9262
+ };
9263
+ const READ_HINTS = {
9264
+ EPERM: '策略拒绝(不是普通权限不足)。当前会话可能未被授权访问该路径(会话文件访问范围限制)',
9265
+ EACCES: '权限不足。目标目录的属主或权限位不允许当前用户读取',
9266
+ EROFS: '目标位于只读文件系统或只读挂载上',
9267
+ EBUSY: '文件正被其它进程占用(IDE、同步盘、杀毒软件)'
9268
+ };
9269
+ function describeFsHint(code, kind = 'write') {
9270
+ if (void 0 === code) return null;
9271
+ return ('read' === kind ? READ_HINTS[code] : HINTS[code]) ?? null;
9272
+ }
9273
+ function fsError(kind, error, scope) {
9274
+ const errnoError = error;
9275
+ const code = errnoError.code;
9276
+ const syscall = errnoError.syscall;
9277
+ const paths = [
9278
+ scope.target,
9279
+ ...scope.others ?? []
9280
+ ];
9281
+ const verb = 'read' === kind ? '读取' : '写入';
9282
+ const lines = [
9283
+ `${verb}失败:${scope.action ?? ('read' === kind ? '读文件' : '写文件')}`
9284
+ ];
9285
+ lines.push(` · 目标:${scope.target}`);
9286
+ if (paths.length > 1) {
9287
+ lines.push(' · 本次还需要写:');
9288
+ for (const path of paths.slice(1))lines.push(` - ${path}`);
9289
+ }
9290
+ lines.push('');
9291
+ lines.push(`原因:${code ?? '未知错误'}(${errnoError.message.split('\n')[0] ?? String(error)})`);
9292
+ const hint = describeFsHint(code, kind);
9293
+ if (null !== hint) lines.push(`可能原因:${hint}`);
9294
+ if ('EPERM' === code || 'EACCES' === code) if ('read' === kind) {
9295
+ lines.push(' → 当前会话没有该目录的访问权限:让会话能访问文档仓库所在目录');
9296
+ lines.push(' (放宽会话的文件访问范围),或换一个有权限的终端执行');
9297
+ lines.push(' → 或把 docs.root 指到会话内的仓库');
9298
+ } else {
9299
+ lines.push(' → 当前会话没有该目录的写权限:让会话能写文档仓库所在目录');
9300
+ lines.push(' (放宽会话的文件写入范围),或换一个有权限的终端执行');
9301
+ lines.push(' → 或把 docs.root 指到会话内可写的位置');
9302
+ lines.push(' → 文件被加锁:确认没有同步盘/杀软占用(macOS 可用 ls -lO 看 uchg 标记)');
9303
+ }
9304
+ else if ('EROFS' === code) lines.push(' → 目标位于只读挂载:换到可写位置,或重新挂载为可写');
9305
+ else if ('EBUSY' === code || 'ETXTBSY' === code) lines.push(' → 关闭占用该文件的程序后重试');
9306
+ if (void 0 !== syscall) lines.push(` (syscall: ${syscall})`);
9307
+ const details = {
9308
+ kind: 'read' === kind ? 'read-failed' : 'write-failed',
9309
+ path: scope.target,
9310
+ paths,
9311
+ ...void 0 === code ? {} : {
9312
+ errno: code
9313
+ },
9314
+ ...void 0 === syscall ? {} : {
9315
+ syscall
9316
+ }
9317
+ };
9318
+ return new errors_CliError(lines.join('\n'), errors_EXIT.INVALID, details);
9319
+ }
9320
+ function writeError(error, scope) {
9321
+ return fsError('write', error, scope);
9322
+ }
9323
+ function readError(error, scope) {
9324
+ return fsError('read', error, scope);
9325
+ }
9326
+ function writeTextFile(scope, text) {
9327
+ try {
9328
+ writeFileSync(scope.target, text, 'utf8');
9329
+ } catch (error) {
9330
+ throw writeError(error, scope);
9331
+ }
9332
+ }
9251
9333
  const TERMINAL_CATALOG_FILE = 'execution_terminals.json';
9252
9334
  function terminals_error(code, message, where) {
9253
9335
  return void 0 === where ? {
@@ -9439,8 +9521,7 @@ const DOCS_KEYS = new Set([
9439
9521
  'validator'
9440
9522
  ]);
9441
9523
  const VALIDATOR_KEYS = new Set([
9442
- 'strict',
9443
- 'requireScript'
9524
+ 'strict'
9444
9525
  ]);
9445
9526
  const GIT_KEYS = new Set([
9446
9527
  'cli',
@@ -9451,7 +9532,7 @@ const POLICY_KEYS = new Set([
9451
9532
  'push'
9452
9533
  ]);
9453
9534
  const DEFAULT_GIT_POLICY = {
9454
- commit: true,
9535
+ commit: false,
9455
9536
  push: false
9456
9537
  };
9457
9538
  const DEFAULT_VALIDATOR_POLICY = {
@@ -9602,7 +9683,7 @@ function parseValidatorPolicy(raw, issues) {
9602
9683
  return null;
9603
9684
  }
9604
9685
  issues.push(...unknownKeys(raw, VALIDATOR_KEYS, 'docs.validator'));
9605
- const value = raw['strict'] ?? raw['requireScript'];
9686
+ const value = raw['strict'];
9606
9687
  if (void 0 === value) return {
9607
9688
  ...DEFAULT_VALIDATOR_POLICY
9608
9689
  };
@@ -9763,6 +9844,13 @@ function checkFsOfDocs(config, issues) {
9763
9844
  if ('' === root) return;
9764
9845
  if (!external_node_fs_existsSync(root)) return void issues.push(schema_error('DOCS_ROOT_MISSING', `文档仓库不存在:${root}`, 'docs.root'));
9765
9846
  if (!statSync(root).isDirectory()) return void issues.push(schema_error('DOCS_ROOT_NOT_DIR', `文档仓库不是目录:${root}`, 'docs.root'));
9847
+ try {
9848
+ accessSync(root, constants.R_OK);
9849
+ } catch (failure) {
9850
+ const code = failure.code;
9851
+ issues.push(schema_error('DOCS_ROOT_UNREADABLE', `文档仓库不可读:${root}(${code ?? '未知错误'})\n 当前会话可能未被授权访问该目录(会话文件访问范围限制),或目录权限位不允许读取\n → 把文档仓库所在目录授权给会话后重试`, 'docs.root'));
9852
+ return;
9853
+ }
9766
9854
  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'));
9767
9855
  }
9768
9856
  function checkFsOfTerminals(config, issues) {
@@ -9933,8 +10021,8 @@ profile:
9933
10021
  docs:
9934
10022
  root: ''
9935
10023
  git:
9936
- cli: { commit: true, push: false }
9937
- ui: { commit: true, push: false }
10024
+ cli: { commit: false, push: false }
10025
+ ui: { commit: false, push: false }
9938
10026
 
9939
10027
  terminals: {}
9940
10028
  `;
@@ -10053,8 +10141,19 @@ function saveDocument(doc, target) {
10053
10141
  withConfigLock(target, ()=>{
10054
10142
  if (external_node_fs_existsSync(target)) backup(target);
10055
10143
  const tmp = `${target}.tmp-${process.pid}`;
10056
- writeFileSync(tmp, text, 'utf8');
10057
- renameSync(tmp, target);
10144
+ try {
10145
+ writeFileSync(tmp, text, 'utf8');
10146
+ renameSync(tmp, target);
10147
+ } catch (error) {
10148
+ throw writeError(error, {
10149
+ action: '保存配置',
10150
+ target,
10151
+ others: [
10152
+ tmp,
10153
+ backupsDir(target)
10154
+ ]
10155
+ });
10156
+ }
10058
10157
  });
10059
10158
  }
10060
10159
  function backup(target) {
@@ -10996,13 +11095,40 @@ function resolveIterationFromBranch(docsRoot, iterations) {
10996
11095
  candidates: []
10997
11096
  };
10998
11097
  }
11098
+ function describeRepoAccessFailure(docsRoot) {
11099
+ try {
11100
+ execFileSync('git', [
11101
+ 'rev-parse',
11102
+ '--is-inside-work-tree'
11103
+ ], {
11104
+ cwd: docsRoot,
11105
+ encoding: 'utf8',
11106
+ stdio: [
11107
+ 'ignore',
11108
+ 'pipe',
11109
+ 'pipe'
11110
+ ]
11111
+ });
11112
+ return null;
11113
+ } catch (error) {
11114
+ const detail = error.stderr?.trim() ?? '';
11115
+ const firstLine = detail.split('\n')[0] ?? '';
11116
+ if (firstLine.includes('not a git repository')) return `文档仓库不是 git 仓库:${docsRoot}`;
11117
+ if (0 === firstLine.length) return `无法执行 git:${error instanceof Error ? error.message.split('\n')[0] : String(error)}\n 请确认已安装 git 并在 PATH 中`;
11118
+ return `无法访问文档仓库:${docsRoot}\n git 输出:${firstLine}\n 常见原因:当前会话没有该目录的访问权限(会话文件访问范围限制),或目录已被移动/删除`;
11119
+ }
11120
+ }
10999
11121
  const PROTECTED_BRANCHES = new Set([
11000
11122
  'main',
11001
11123
  'master'
11002
11124
  ]);
11003
11125
  function assertWritableBranch(docsRoot) {
11004
11126
  const branch = currentBranch(docsRoot);
11005
- if (null === branch) throw new errors_CliError("文档仓库处于 detached HEAD,无法确认所在分支,写操作已拒绝。\n请先切到迭代分支再重试:git switch <分支>", errors_EXIT.INVALID);
11127
+ if (null === branch) {
11128
+ const accessFailure = describeRepoAccessFailure(docsRoot);
11129
+ if (null !== accessFailure) throw new errors_CliError(accessFailure, errors_EXIT.INVALID);
11130
+ throw new errors_CliError("文档仓库处于 detached HEAD,无法确认所在分支,写操作已拒绝。\n请先切到迭代分支再重试:git switch <分支>", errors_EXIT.INVALID);
11131
+ }
11006
11132
  if (PROTECTED_BRANCHES.has(branch.toLowerCase())) throw new errors_CliError(`文档仓库当前在 ${branch} 分支,禁止直接修改文档。\n请先切到该迭代的分支再重试,例如:\n git switch -c feature_<迭代名>`, errors_EXIT.INVALID);
11007
11133
  }
11008
11134
  const TASK_TYPE_GROUPS = [
@@ -11362,8 +11488,14 @@ function loadDocSchema(docsRoot, options = {}) {
11362
11488
  let text;
11363
11489
  try {
11364
11490
  text = readFileSync(target, 'utf8');
11365
- } catch {
11366
- fail(docsRoot, '文件不存在或不可读');
11491
+ } catch (error) {
11492
+ const code = error.code;
11493
+ if ('ENOENT' === code) fail(docsRoot, '文件不存在或不可读');
11494
+ const failure = readError(error, {
11495
+ action: `读取文档仓库 ${SCHEMA_FILENAME}`,
11496
+ target
11497
+ });
11498
+ throw new errors_CliError(`${failure.message}\n\n该文件是文档格式的唯一来源,请确认文档仓库可访问后重试。`, errors_EXIT.NOT_FOUND);
11367
11499
  }
11368
11500
  let raw;
11369
11501
  try {
@@ -11374,7 +11506,7 @@ function loadDocSchema(docsRoot, options = {}) {
11374
11506
  const schema = parseDocSchema(raw, docsRoot);
11375
11507
  if (true !== options.allowTooOld && null !== schema.requiresYlcwf) {
11376
11508
  const required = parseMinVersion(schema.requiresYlcwf);
11377
- if (null !== required && compareVersions("0.8.0", `${required[0]}.${required[1]}.${required[2]}`) < 0) fail(docsRoot, `文档仓库要求 ylcwf ${schema.requiresYlcwf},当前版本是 0.8.0,请先升级 ylcwf:\n npm install -g ylcwf@latest`);
11509
+ if (null !== required && compareVersions("0.9.0", `${required[0]}.${required[1]}.${required[2]}`) < 0) fail(docsRoot, `文档仓库要求 ylcwf ${schema.requiresYlcwf},当前版本是 0.9.0,请先升级 ylcwf:\n npm install -g ylcwf@latest`);
11378
11510
  }
11379
11511
  return schema;
11380
11512
  }
@@ -11404,6 +11536,23 @@ function sideOfTypeName(schema, typeName) {
11404
11536
  if (sides.length > 1) return 'both';
11405
11537
  return sides[0] ?? null;
11406
11538
  }
11539
+ function toLf(text) {
11540
+ return text.replace(/\r\n/g, '\n');
11541
+ }
11542
+ function detectEol(text) {
11543
+ return text.includes('\r\n') ? '\r\n' : '\n';
11544
+ }
11545
+ function applyEol(text, eol) {
11546
+ const lf = toLf(text);
11547
+ return '\n' === eol ? lf : lf.replace(/\n/g, '\r\n');
11548
+ }
11549
+ function readTextFile(path) {
11550
+ const raw = readFileSync(path, 'utf8');
11551
+ return {
11552
+ text: toLf(raw),
11553
+ eol: detectEol(raw)
11554
+ };
11555
+ }
11407
11556
  function buildRepoSideIndex(terminals) {
11408
11557
  const byName = new Map();
11409
11558
  for (const terminal of Object.values(terminals))for (const side of [
@@ -12440,8 +12589,91 @@ function isDocMarkdown(path) {
12440
12589
  if (RESERVED_PREFIXES.some((prefix)=>path.startsWith(prefix) || path.includes(`/${prefix}`))) return false;
12441
12590
  return true;
12442
12591
  }
12592
+ class RecentCache {
12593
+ limit;
12594
+ entries = new Map();
12595
+ constructor(limit){
12596
+ this.limit = limit;
12597
+ }
12598
+ get(key) {
12599
+ const hit = this.entries.get(key);
12600
+ if (void 0 === hit) return;
12601
+ this.entries.delete(key);
12602
+ this.entries.set(key, hit);
12603
+ return hit;
12604
+ }
12605
+ set(key, value) {
12606
+ this.entries.delete(key);
12607
+ this.entries.set(key, value);
12608
+ while(this.entries.size > this.limit){
12609
+ const oldest = this.entries.keys().next();
12610
+ if (true === oldest.done) break;
12611
+ this.entries.delete(oldest.value);
12612
+ }
12613
+ }
12614
+ clear() {
12615
+ this.entries.clear();
12616
+ }
12617
+ }
12618
+ const treeCache = new RecentCache(4);
12619
+ const commitTimeCache = new RecentCache(512);
12620
+ const MATERIALIZE_MARKER = '.ylcwf-materialized';
12621
+ const REMOTE_CACHE_PREFIX = 'ylcwf-remote-';
12622
+ function remoteCacheRoot() {
12623
+ return external_node_os_tmpdir();
12624
+ }
12625
+ function listRemoteCacheDirs() {
12626
+ const base = remoteCacheRoot();
12627
+ let names;
12628
+ try {
12629
+ names = external_node_fs_readdirSync(base);
12630
+ } catch {
12631
+ return [];
12632
+ }
12633
+ return names.filter((name)=>name.startsWith(REMOTE_CACHE_PREFIX)).map((name)=>{
12634
+ const path = external_node_path_join(base, name);
12635
+ try {
12636
+ return {
12637
+ path,
12638
+ mtime: statSync(path).mtime.toISOString()
12639
+ };
12640
+ } catch {
12641
+ return null;
12642
+ }
12643
+ }).filter((item)=>null !== item).sort((left, right)=>right.mtime.localeCompare(left.mtime));
12644
+ }
12645
+ const PRUNE_INTERVAL_MS = 300000;
12646
+ let lastPruneAt = 0;
12647
+ function snapshotTree(docsRoot, sha) {
12648
+ const key = `${docsRoot}\u0000${sha}`;
12649
+ const cached = treeCache.get(key);
12650
+ if (void 0 !== cached) return cached;
12651
+ const output = tryGit(docsRoot, [
12652
+ 'ls-tree',
12653
+ '-r',
12654
+ '-l',
12655
+ '--full-tree',
12656
+ sha
12657
+ ]);
12658
+ if (null === output) throw new errors_CliError(`无法读取远程快照:${sha}`, errors_EXIT.NOT_FOUND);
12659
+ const sizes = new Map();
12660
+ for (const rawLine of output.split('\n')){
12661
+ const line = rawLine.replace(/\r$/, '');
12662
+ const tab = line.indexOf('\t');
12663
+ if (tab < 0) continue;
12664
+ const path = line.slice(tab + 1);
12665
+ const sizeText = line.slice(0, tab).trim().split(/\s+/)[3];
12666
+ const size = void 0 === sizeText || '-' === sizeText ? 0 : Number.parseInt(sizeText, 10);
12667
+ sizes.set(path, Number.isNaN(size) ? 0 : size);
12668
+ }
12669
+ treeCache.set(key, sizes);
12670
+ return sizes;
12671
+ }
12443
12672
  function lastCommitIso(docsRoot, sha, path) {
12444
- return tryGit(docsRoot, [
12673
+ const key = `${docsRoot}\u0000${sha}\u0000${path}`;
12674
+ const cached = commitTimeCache.get(key);
12675
+ if (void 0 !== cached) return cached;
12676
+ const value = tryGit(docsRoot, [
12445
12677
  'log',
12446
12678
  '-1',
12447
12679
  '--format=%cI',
@@ -12449,6 +12681,8 @@ function lastCommitIso(docsRoot, sha, path) {
12449
12681
  '--',
12450
12682
  path
12451
12683
  ]) ?? '';
12684
+ commitTimeCache.set(key, value);
12685
+ return value;
12452
12686
  }
12453
12687
  function getBranchInfo(docsRoot) {
12454
12688
  const current = tryGit(docsRoot, [
@@ -12480,18 +12714,21 @@ function getBranchInfo(docsRoot) {
12480
12714
  remote: branches.split('\n').map((line)=>line.trim().replace(/^refs\/remotes\//, '')).filter((line)=>line.length > 0 && line.includes('/') && !line.endsWith('/HEAD')).sort()
12481
12715
  };
12482
12716
  }
12717
+ const remoteListCache = new RecentCache(4);
12483
12718
  function listRemoteIterations(layout, ref) {
12719
+ const cacheKey = `${layout.root}\u0000${layout.iterationsRoot}\u0000${ref.sha}`;
12720
+ const cached = remoteListCache.get(cacheKey);
12721
+ if (void 0 !== cached) return {
12722
+ docsRoot: layout.root,
12723
+ source: 'remote',
12724
+ ref,
12725
+ iterations: structuredClone(cached)
12726
+ };
12484
12727
  const docsRoot = layout.root;
12485
- const listed = tryGit(docsRoot, [
12486
- 'ls-tree',
12487
- '-r',
12488
- '--name-only',
12489
- ref.sha
12490
- ]);
12491
- if (null === listed) throw new errors_CliError(`无法读取远程快照:${ref.ref}`, errors_EXIT.NOT_FOUND);
12728
+ const sizes = snapshotTree(docsRoot, ref.sha);
12492
12729
  const prefix = `${layout.iterationsRoot.replace(/\/+$/, '')}/`;
12493
12730
  const groups = new Map();
12494
- for (const path of listed.split('\n')){
12731
+ for (const path of sizes.keys()){
12495
12732
  if (!isDocMarkdown(path)) continue;
12496
12733
  if (!path.startsWith(prefix)) continue;
12497
12734
  const segments = path.slice(prefix.length).split('/');
@@ -12501,16 +12738,11 @@ function listRemoteIterations(layout, ref) {
12501
12738
  if (!isYearDirectory(yearText)) continue;
12502
12739
  const year = Number.parseInt(yearText, 10);
12503
12740
  const relPath = `${yearText}/${iteration}`;
12504
- const sizeText = tryGit(docsRoot, [
12505
- 'cat-file',
12506
- '-s',
12507
- `${ref.sha}:${path}`
12508
- ]) ?? '0';
12509
12741
  const entry = {
12510
12742
  id: file.replace(/\.md$/, ''),
12511
12743
  file,
12512
12744
  mtime: lastCommitIso(docsRoot, ref.sha, path),
12513
- size: Number.parseInt(sizeText, 10) || 0
12745
+ size: sizes.get(path) ?? 0
12514
12746
  };
12515
12747
  const bucket = groups.get(relPath) ?? {
12516
12748
  year,
@@ -12529,14 +12761,16 @@ function listRemoteIterations(layout, ref) {
12529
12761
  relPath: group.relPath,
12530
12762
  mtime: lastCommitIso(docsRoot, ref.sha, `${prefix}${group.relPath}`),
12531
12763
  developers: group.developers.sort((left, right)=>right.mtime.localeCompare(left.mtime)),
12532
- hasPrd: listed.includes(`${prefix}${group.relPath}/_prd/meta.json`)
12764
+ hasPrd: sizes.has(`${prefix}${group.relPath}/_prd/meta.json`)
12533
12765
  })).sort((left, right)=>left.year === right.year ? right.mtime.localeCompare(left.mtime) : right.year - left.year);
12534
- return {
12766
+ const snapshot = {
12535
12767
  docsRoot,
12536
12768
  source: 'remote',
12537
12769
  ref,
12538
12770
  iterations
12539
12771
  };
12772
+ remoteListCache.set(cacheKey, iterations);
12773
+ return structuredClone(snapshot);
12540
12774
  }
12541
12775
  function gitShow(docsRoot, sha, path) {
12542
12776
  return tryGit(docsRoot, [
@@ -12544,14 +12778,81 @@ function gitShow(docsRoot, sha, path) {
12544
12778
  `${sha}:${path}`
12545
12779
  ]);
12546
12780
  }
12781
+ const REMOTE_CACHE_KEEP = 20;
12782
+ function pruneRemoteCache(options = {}) {
12783
+ const keep = options.keep ?? REMOTE_CACHE_KEEP;
12784
+ const base = options.baseDir ?? external_node_os_tmpdir();
12785
+ let names;
12786
+ try {
12787
+ names = external_node_fs_readdirSync(base);
12788
+ } catch {
12789
+ return [];
12790
+ }
12791
+ const candidates = names.filter((name)=>name.startsWith(REMOTE_CACHE_PREFIX)).map((name)=>{
12792
+ const path = external_node_path_join(base, name);
12793
+ try {
12794
+ return {
12795
+ path,
12796
+ mtime: statSync(path).mtimeMs
12797
+ };
12798
+ } catch {
12799
+ return null;
12800
+ }
12801
+ }).filter((item)=>null !== item).sort((left, right)=>right.mtime - left.mtime);
12802
+ const removed = [];
12803
+ for (const [index, item] of candidates.entries())if (!(index < keep)) try {
12804
+ rmSync(item.path, {
12805
+ recursive: true,
12806
+ force: true
12807
+ });
12808
+ removed.push(item.path);
12809
+ } catch {}
12810
+ return removed;
12811
+ }
12812
+ function touchDir(dir) {
12813
+ try {
12814
+ const now = new Date();
12815
+ utimesSync(dir, now, now);
12816
+ } catch {}
12817
+ }
12818
+ function maybePruneRemoteCache() {
12819
+ const now = Date.now();
12820
+ if (now - lastPruneAt < PRUNE_INTERVAL_MS) return;
12821
+ lastPruneAt = now;
12822
+ pruneRemoteCache();
12823
+ }
12824
+ function writeFileAtomic(target, content) {
12825
+ const temp = `${target}.${process.pid}.tmp`;
12826
+ writeFileSync(temp, content, 'utf8');
12827
+ try {
12828
+ renameSync(temp, target);
12829
+ } catch (error) {
12830
+ const code = error.code;
12831
+ const occupied = 'EBUSY' === code || 'EPERM' === code || 'EACCES' === code;
12832
+ if (!occupied) {
12833
+ rmSync(temp, {
12834
+ force: true
12835
+ });
12836
+ throw error;
12837
+ }
12838
+ writeFileSync(target, content, 'utf8');
12839
+ rmSync(temp, {
12840
+ force: true
12841
+ });
12842
+ }
12843
+ }
12547
12844
  function materializeRemote(docsRoot, ref) {
12548
- const dir = external_node_path_join(external_node_os_tmpdir(), `ylcwf-remote-${ref.sha.slice(0, 12)}`);
12845
+ const dir = external_node_path_join(remoteCacheRoot(), `${REMOTE_CACHE_PREFIX}${ref.sha.slice(0, 12)}`);
12549
12846
  mkdirSync(external_node_path_join(dir, "scripts"), {
12550
12847
  recursive: true
12551
12848
  });
12849
+ touchDir(dir);
12850
+ maybePruneRemoteCache();
12552
12851
  return dir;
12553
12852
  }
12554
12853
  function materializeScripts(docsRoot, ref, dir) {
12854
+ const marker = external_node_path_join(dir, MATERIALIZE_MARKER);
12855
+ if (external_node_fs_existsSync(marker)) return;
12555
12856
  const listed = tryGit(docsRoot, [
12556
12857
  'ls-tree',
12557
12858
  '-r',
@@ -12568,9 +12869,10 @@ function materializeScripts(docsRoot, ref, dir) {
12568
12869
  mkdirSync(external_node_path_dirname(target), {
12569
12870
  recursive: true
12570
12871
  });
12571
- writeFileSync(target, content, 'utf8');
12872
+ writeFileAtomic(target, content);
12572
12873
  }
12573
12874
  }
12875
+ writeFileAtomic(marker, ref.sha);
12574
12876
  }
12575
12877
  function exportRemoteDoc(docsRoot, ref, year, iteration, developer, iterationsRoot = 'iterations') {
12576
12878
  const safeIteration = safeSegment(iteration, '迭代目录');
@@ -12583,12 +12885,12 @@ function exportRemoteDoc(docsRoot, ref, year, iteration, developer, iterationsRo
12583
12885
  mkdirSync(external_node_path_dirname(target), {
12584
12886
  recursive: true
12585
12887
  });
12586
- writeFileSync(target, markdown, 'utf8');
12888
+ writeFileAtomic(target, markdown);
12587
12889
  materializeScripts(docsRoot, ref, dir);
12588
12890
  const schemaPath = external_node_path_join(dir, 'schema.json');
12589
12891
  if (!external_node_fs_existsSync(schemaPath)) {
12590
12892
  const schemaText = gitShow(docsRoot, ref.sha, 'schema.json');
12591
- if (null !== schemaText) writeFileSync(schemaPath, schemaText, 'utf8');
12893
+ if (null !== schemaText) writeFileAtomic(schemaPath, schemaText);
12592
12894
  }
12593
12895
  const scriptPath = external_node_path_join(dir, "scripts", 'validate_task_doc.py');
12594
12896
  return {
@@ -13187,7 +13489,12 @@ function listMarkdownFiles(directory) {
13187
13489
  }
13188
13490
  function accessReason(error) {
13189
13491
  const code = error.code;
13190
- if ("EACCES" === code || "EPERM" === code) return "没有访问权限,请联系管理员开通文档仓库访问权限";
13492
+ const target = error.path;
13493
+ if ("EACCES" === code || "EPERM" === code) return [
13494
+ `没有访问权限:${target ?? ""}`,
13495
+ " 当前会话可能未被授权访问该目录(会话文件访问范围限制),或目录权限位不允许当前用户读取",
13496
+ " → 让会话能访问文档仓库所在目录(放宽会话的文件访问范围),或换一个有权限的终端执行"
13497
+ ].filter((line)=>line.length > 0).join("\n");
13191
13498
  if ("ENOENT" === code) return "文档仓库路径不存在";
13192
13499
  if (error instanceof Error) return error.message;
13193
13500
  return String(error);
@@ -13391,7 +13698,7 @@ function parseMarkdownDoc(markdown, schema) {
13391
13698
  };
13392
13699
  }
13393
13700
  function readMarkdown(target) {
13394
- return readFileSync(target, "utf8");
13701
+ return readTextFile(target).text;
13395
13702
  }
13396
13703
  function resolveIterationForRead(layout, iteration, source, presetRef, refName) {
13397
13704
  const safeIteration = iterations_safeSegment(iteration, "迭代目录");
@@ -13469,6 +13776,7 @@ function readIterationDoc(layout, iteration, developer, source = "local", preset
13469
13776
  name: ref.ref,
13470
13777
  sha: ref.sha
13471
13778
  },
13779
+ schemaFrom: "snapshot",
13472
13780
  validation: local.payload,
13473
13781
  details: splitDetails(exported.markdown)
13474
13782
  };
@@ -13495,6 +13803,7 @@ function readIterationDoc(layout, iteration, developer, source = "local", preset
13495
13803
  parserError: local.error,
13496
13804
  source: "local",
13497
13805
  ref: null,
13806
+ schemaFrom: "workspace",
13498
13807
  validation: local.payload,
13499
13808
  details: splitDetails(markdown)
13500
13809
  };
@@ -13605,11 +13914,33 @@ function readIterationSummary(layout, iteration, source = "local", refName) {
13605
13914
  blocked
13606
13915
  };
13607
13916
  }
13917
+ function readCurrentIteration(layout) {
13918
+ const listed = listIterations(layout, "local");
13919
+ if (!listed.accessible) return {
13920
+ accessible: false,
13921
+ reason: listed.reason,
13922
+ branch: null,
13923
+ iteration: null,
13924
+ candidates: [],
13925
+ available: []
13926
+ };
13927
+ const available = listed.iterations.map((item)=>({
13928
+ name: item.name,
13929
+ relPath: item.relPath
13930
+ }));
13931
+ const matched = resolveIterationFromBranch(layout.root, available.map((item)=>item.name));
13932
+ return {
13933
+ accessible: true,
13934
+ reason: null,
13935
+ ...matched,
13936
+ available
13937
+ };
13938
+ }
13608
13939
  function checkDocTaskSides(options) {
13609
13940
  const resolved = resolveIterationDir(options.docsRoot, options.iterationsRoot, options.iteration);
13610
13941
  const file = external_node_path_join(resolved.dir, `${options.developer}.md`);
13611
13942
  if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${resolved.relPath}/${options.developer}.md`, errors_EXIT.NOT_FOUND);
13612
- const markdown = readFileSync(file, 'utf8');
13943
+ const markdown = readTextFile(file).text;
13613
13944
  const schema = loadDocSchema(options.docsRoot);
13614
13945
  const payload = parseMarkdownDoc(markdown, schema);
13615
13946
  return validateTaskSides({
@@ -13778,6 +14109,27 @@ function commitInDocsRepo(docsRoot, file, message, push) {
13778
14109
  message: '已提交并推送'
13779
14110
  };
13780
14111
  }
14112
+ function hasPendingChange(docsRoot, file) {
14113
+ try {
14114
+ const output = execFileSync('git', [
14115
+ 'status',
14116
+ '--porcelain',
14117
+ '--',
14118
+ file
14119
+ ], {
14120
+ cwd: docsRoot,
14121
+ encoding: 'utf8',
14122
+ stdio: [
14123
+ 'ignore',
14124
+ 'pipe',
14125
+ 'pipe'
14126
+ ]
14127
+ });
14128
+ return output.trim().length > 0;
14129
+ } catch {
14130
+ return false;
14131
+ }
14132
+ }
13781
14133
  function appendHistory(entry) {
13782
14134
  try {
13783
14135
  const target = historyPath();
@@ -13794,7 +14146,7 @@ function readTaskHistory(options) {
13794
14146
  const target = historyPath();
13795
14147
  if (!external_node_fs_existsSync(target)) return [];
13796
14148
  const limit = options.limit ?? 5;
13797
- const lines = readFileSync(target, 'utf8').trim().split('\n').filter((line)=>line.length > 0);
14149
+ const lines = readTextFile(target).text.trim().split('\n').filter((line)=>line.length > 0);
13798
14150
  const entries = [];
13799
14151
  for(let index = lines.length - 1; index >= 0 && entries.length < limit; index -= 1){
13800
14152
  const line = lines[index];
@@ -13969,12 +14321,13 @@ function loadDoc(locator, iterationRaw, developerRaw) {
13969
14321
  const file = external_node_path_join(dir, `${developer}.md`);
13970
14322
  if (!external_node_fs_existsSync(file)) throw new errors_CliError(`文档不存在:${relPath}/${developer}.md`, errors_EXIT.NOT_FOUND);
13971
14323
  const mtime = statSync(file).mtimeMs;
13972
- const original = readFileSync(file, 'utf8');
14324
+ const { text, eol } = readTextFile(file);
13973
14325
  return {
13974
14326
  file,
13975
14327
  mtime,
13976
- original,
13977
- lines: original.split('\n')
14328
+ original: text,
14329
+ eol,
14330
+ lines: text.split('\n')
13978
14331
  };
13979
14332
  }
13980
14333
  function computeUpdate(lines, taskId, action, keys, docsRoot) {
@@ -14075,19 +14428,36 @@ function commit(context, lines, changes, message, iteration, developer, action,
14075
14428
  changes: [],
14076
14429
  file: context.file
14077
14430
  };
14078
- writeFileSync(context.file, output, 'utf8');
14431
+ const pendingBefore = options.policy.commit ? hasPendingChange(options.docsRoot, context.file) : false;
14432
+ const scope = {
14433
+ action: '写入任务文档',
14434
+ target: context.file,
14435
+ others: options.policy.commit ? [
14436
+ historyPath(),
14437
+ external_node_path_join(options.docsRoot, '.git')
14438
+ ] : [
14439
+ historyPath()
14440
+ ]
14441
+ };
14442
+ writeTextFile(scope, applyEol(output, context.eol));
14079
14443
  const outcome = validateAfterWrite(toLayout(options), iteration, developer);
14080
14444
  const strict = strictValidationEnabled();
14081
14445
  if ('violation' === outcome.kind) {
14082
14446
  if (strict) {
14083
- writeFileSync(context.file, context.original, 'utf8');
14084
- throw new errors_CliError(`写入未通过文档校验,已回滚:${outcome.message}`, errors_EXIT.INVALID);
14447
+ writeTextFile({
14448
+ action: '回滚任务文档',
14449
+ target: context.file
14450
+ }, applyEol(context.original, context.eol));
14451
+ throw new errors_CliError(`写入未通过文档校验,已回滚(文档未改变):${outcome.message}`, errors_EXIT.INVALID);
14085
14452
  }
14086
14453
  process.stderr.write(`警告:写入未通过文档校验(docs.validator.strict=false):${outcome.message}\n`);
14087
14454
  }
14088
14455
  if ('unavailable' === outcome.kind) {
14089
- writeFileSync(context.file, context.original, 'utf8');
14090
- if (strict) throw new errors_CliError(`未执行文档校验,已回滚:${outcome.reason}\n如需在无法校验时仍写入(不推荐),可配置 docs.validator.strict: false`, errors_EXIT.INVALID);
14456
+ writeTextFile({
14457
+ action: '回滚任务文档',
14458
+ target: context.file
14459
+ }, applyEol(context.original, context.eol));
14460
+ if (strict) throw new errors_CliError(`未执行文档校验,已回滚(文档未改变):${outcome.reason}\n如需在无法校验时仍写入(不推荐),可配置 docs.validator.strict: false`, errors_EXIT.INVALID);
14091
14461
  process.stderr.write(`警告:${outcome.reason};本次写入未做文档校验(docs.validator.strict=false)\n`);
14092
14462
  }
14093
14463
  appendHistory({
@@ -14098,12 +14468,16 @@ function commit(context, lines, changes, message, iteration, developer, action,
14098
14468
  changes
14099
14469
  });
14100
14470
  const git = options.policy.commit ? commitInDocsRepo(options.docsRoot, context.file, options.commitMessage, options.policy.push) : void 0;
14471
+ const warnings = [];
14472
+ if (pendingBefore) warnings.push(`该文档在本次操作前已有未提交改动,本次提交会一并包含:${context.file}\n 如需分开提交,请先提交(或 stash)遗留改动后重试`);
14473
+ if (void 0 !== git && !git.committed) warnings.push(`文档已写入,但未提交:${git.message}`);
14101
14474
  return {
14102
14475
  ok: true,
14103
14476
  message,
14104
14477
  changes,
14105
14478
  file: context.file,
14106
- git
14479
+ git,
14480
+ warnings
14107
14481
  };
14108
14482
  }
14109
14483
  function normalizeDetailField(name) {
@@ -14318,7 +14692,7 @@ function validateAfterWrite(layout, iteration, developer) {
14318
14692
  kind: 'unavailable',
14319
14693
  reason: `找不到个人任务文档:${targetFile}`
14320
14694
  };
14321
- const markdown = readFileSync(targetFile, 'utf8');
14695
+ const markdown = readTextFile(targetFile).text;
14322
14696
  const role = roleOfDocument(markdown, schema);
14323
14697
  if (null === role) return {
14324
14698
  kind: 'unavailable',
@@ -14446,7 +14820,7 @@ function availableActions(options) {
14446
14820
  }
14447
14821
  const file = external_node_path_join(dir, `${developer}.md`);
14448
14822
  if (!external_node_fs_existsSync(file)) return {};
14449
- const lines = readFileSync(file, 'utf8').split('\n');
14823
+ const lines = readTextFile(file).text.split('\n');
14450
14824
  const { rows } = parseTaskRows(lines, buildKeys(loadDocSchema(options.docsRoot)));
14451
14825
  const result = {};
14452
14826
  for (const row of rows){
@@ -14461,7 +14835,10 @@ function availableActions(options) {
14461
14835
  list.push({
14462
14836
  action: 'submit',
14463
14837
  enabled: ok,
14464
- reason: ok ? '' : `AI 自测为「${row.selfTest}」,需先通过自测`
14838
+ reason: ok ? '' : '需先自测通过',
14839
+ ...ok ? {} : {
14840
+ nextStep: `ylcwf task selftest --iteration ${options.iteration} ${row.taskId} --result 通过`
14841
+ }
14465
14842
  });
14466
14843
  }
14467
14844
  if ('待验收' === row.status) {
@@ -14880,7 +15257,7 @@ function runDocMigrate(options) {
14880
15257
  const files = external_node_fs_readdirSync(dir).filter((name)=>name.endsWith('.md') && !name.startsWith('_'));
14881
15258
  for (const name of files){
14882
15259
  const target = external_node_path_join(dir, name);
14883
- const original = readFileSync(target, 'utf8');
15260
+ const { text: original, eol } = readTextFile(target);
14884
15261
  const strippedResult = stripHashIds({
14885
15262
  lines: original.split('\n'),
14886
15263
  schema
@@ -14927,13 +15304,19 @@ function runDocMigrate(options) {
14927
15304
  unresolved: tableMigrated.unresolved
14928
15305
  });
14929
15306
  if (true === options.dryRun) continue;
14930
- writeFileSync(target, migrated.lines.join('\n'), 'utf8');
15307
+ writeTextFile({
15308
+ action: '迁移迭代任务文档',
15309
+ target
15310
+ }, applyEol(migrated.lines.join('\n'), eol));
14931
15311
  changedFiles.push(target);
14932
15312
  if (migrated.unresolved.length > 0) continue;
14933
15313
  const developer = basename(name, '.md');
14934
15314
  const outcome = validateAfterWrite(layout, iteration.relPath, developer);
14935
15315
  if ('passed' !== outcome.kind) {
14936
- writeFileSync(target, original, 'utf8');
15316
+ writeTextFile({
15317
+ action: '回滚迁移',
15318
+ target
15319
+ }, applyEol(original, eol));
14937
15320
  const reason = 'violation' === outcome.kind ? outcome.message : outcome.reason;
14938
15321
  if (!strictValidationEnabled()) {
14939
15322
  process.stderr.write(`警告:${reason};${iteration.relPath}/${name} 迁移后校验未通过(docs.validator.strict=false)\n`);
@@ -15111,7 +15494,7 @@ function validateIteration(options) {
15111
15494
  ],
15112
15495
  warnings: []
15113
15496
  };
15114
- const markdown = readFileSync(file, 'utf8');
15497
+ const markdown = readTextFile(file).text;
15115
15498
  const role = explicitRole.length > 0 ? explicitRole : roleOfDocument(markdown, schema);
15116
15499
  if (null === role) return {
15117
15500
  iteration: resolved.relPath,
@@ -15436,7 +15819,7 @@ function checkTemplates(docsRoot, schema) {
15436
15819
  result.problems.push(`${file}:文件不存在(${path})`);
15437
15820
  continue;
15438
15821
  }
15439
- const text = readFileSync(path, 'utf8');
15822
+ const text = readTextFile(path).text;
15440
15823
  const headings = new Set(text.split(/\r?\n/).filter((line)=>line.startsWith('## ')).map((line)=>line.slice(3).trim()));
15441
15824
  for (const section of schema.sections)if (!headings.has(section)) result.problems.push(`${file}:缺少必需章节「${section}」`);
15442
15825
  const present = findBlocks(text);
@@ -15467,7 +15850,7 @@ function checkTemplates(docsRoot, schema) {
15467
15850
  }
15468
15851
  const rulesPath = templatePath(docsRoot, STATUS_RULES);
15469
15852
  if (external_node_fs_existsSync(rulesPath)) {
15470
- const text = readFileSync(rulesPath, 'utf8');
15853
+ const text = readTextFile(rulesPath).text;
15471
15854
  const actual = extractBlock(text, 'enums-table-doc');
15472
15855
  if (null === actual) result.problems.push(`${STATUS_RULES}:缺少生成区「enums-table-doc」`);
15473
15856
  else if (actual.trim() !== renderBlock(schema, 'enums-table-doc', 'frontend').trim()) result.outdated.push(`${STATUS_RULES}#enums-table-doc`);
@@ -15496,7 +15879,7 @@ function writeTemplates(docsRoot, schema) {
15496
15879
  result.problems.push(`${file}:文件不存在(${path})`);
15497
15880
  continue;
15498
15881
  }
15499
- const original = readFileSync(path, 'utf8');
15882
+ const { text: original, eol } = readTextFile(path);
15500
15883
  const blocks = findBlocks(original);
15501
15884
  if (0 === blocks.length) {
15502
15885
  result.problems.push(`${file}:未找到任何生成区标记`);
@@ -15510,7 +15893,10 @@ function writeTemplates(docsRoot, schema) {
15510
15893
  }
15511
15894
  if (updated !== original) {
15512
15895
  result.written.push(file);
15513
- writeFileSync(path, updated, 'utf8');
15896
+ writeTextFile({
15897
+ action: '重写模板生成区',
15898
+ target: path
15899
+ }, applyEol(updated, eol));
15514
15900
  }
15515
15901
  }
15516
15902
  return result;
@@ -15586,7 +15972,9 @@ function runDocApply(options, mode = 'apply') {
15586
15972
  const targetDir = resolvedIteration.dir;
15587
15973
  const targetFile = external_node_path_join(targetDir, `${developer}.md`);
15588
15974
  const exists = external_node_fs_existsSync(targetFile);
15589
- const original = exists ? readFileSync(targetFile, 'utf8') : null;
15975
+ const existing = exists ? readTextFile(targetFile) : null;
15976
+ const original = null === existing ? null : existing.text;
15977
+ const eol = existing?.eol ?? '\n';
15590
15978
  const mtime = exists ? statSync(targetFile).mtimeMs : 0;
15591
15979
  const parsed = null === original ? {
15592
15980
  requirements: [],
@@ -15668,11 +16056,20 @@ function runDocApply(options, mode = 'apply') {
15668
16056
  mkdirSync(targetDir, {
15669
16057
  recursive: true
15670
16058
  });
15671
- writeFileSync(targetFile, rendered.markdown, 'utf8');
16059
+ writeTextFile({
16060
+ action: '写入迭代任务文档',
16061
+ target: targetFile,
16062
+ others: [
16063
+ `${docsRoot}/.git`
16064
+ ]
16065
+ }, applyEol(rendered.markdown, eol));
15672
16066
  const outcome = validateAfterWrite(layout, iteration, developer);
15673
16067
  const rollback = (message)=>{
15674
16068
  if (null === original) unlinkSync(targetFile);
15675
- else writeFileSync(targetFile, original, 'utf8');
16069
+ else writeTextFile({
16070
+ action: '回滚迭代任务文档',
16071
+ target: targetFile
16072
+ }, applyEol(original, eol));
15676
16073
  throw new errors_CliError(message, errors_EXIT.INVALID);
15677
16074
  };
15678
16075
  const strict = strictValidationEnabled();
@@ -15797,10 +16194,7 @@ function requireWriteContext(options) {
15797
16194
  const ready = requireConfig(options.config);
15798
16195
  const config = ready.config;
15799
16196
  if (0 === config.docs.root.trim().length) throw new errors_CliError('未配置文档仓库:请先设置 docs.root', errors_EXIT.NOT_FOUND);
15800
- const base = config.docs.git?.cli ?? {
15801
- commit: true,
15802
- push: false
15803
- };
16197
+ const base = config.docs.git?.cli ?? DEFAULT_GIT_POLICY;
15804
16198
  const policy = {
15805
16199
  commit: options.commit ?? base.commit,
15806
16200
  push: options.push ?? base.push
@@ -16116,6 +16510,7 @@ function runAction(action, taskId, options) {
16116
16510
  for (const change of result.changes)printLine(` · ${change}`);
16117
16511
  printLine(`文档:${result.file}`);
16118
16512
  if (void 0 !== result.git) printLine(`git:${result.git.message}`);
16513
+ for (const warning of result.warnings ?? [])printLine(`⚠ ${warning}`);
16119
16514
  if (sideIssues.length > 0) {
16120
16515
  printLine('\n注意:该文档存在任务类型与执行终端归属不一致(可用 ylcwf doctor --docs 复查):');
16121
16516
  for (const message of sideIssues)printLine(` · ${message}`);
@@ -16165,6 +16560,7 @@ function runDetail(taskId, options) {
16165
16560
  for (const change of applied.changes)printLine(` · ${change}`);
16166
16561
  printLine(`文档:${applied.file}`);
16167
16562
  if (void 0 !== applied.git) printLine(`git:${applied.git.message}`);
16563
+ for (const warning of applied.warnings ?? [])printLine(`⚠ ${warning}`);
16168
16564
  }
16169
16565
  function runSelfTest(taskId, options) {
16170
16566
  const { docsRoot, layout, developer, policy } = requireWriteContext(options);
@@ -16191,6 +16587,7 @@ function runSelfTest(taskId, options) {
16191
16587
  for (const change of applied.changes)printLine(` · ${change}`);
16192
16588
  printLine(`文档:${applied.file}`);
16193
16589
  if (void 0 !== applied.git) printLine(`git:${applied.git.message}`);
16590
+ for (const warning of applied.warnings ?? [])printLine(`⚠ ${warning}`);
16194
16591
  }
16195
16592
  function runActions(options) {
16196
16593
  const { docsRoot, layout, developer } = requireWriteContext(options);
@@ -16231,6 +16628,7 @@ function runBatch(action, taskIds, options) {
16231
16628
  printLine(result.message);
16232
16629
  for (const change of result.changes)printLine(` · ${change}`);
16233
16630
  if (void 0 !== result.git) printLine(`git:${result.git.message}`);
16631
+ for (const warning of result.warnings ?? [])printLine(`⚠ ${warning}`);
16234
16632
  }
16235
16633
  function runHistory(taskId, options) {
16236
16634
  const { layout, developer } = requireWriteContext(options);
@@ -16442,18 +16840,21 @@ function iteration_runShow(name, options) {
16442
16840
  function runCurrent(options) {
16443
16841
  const format = parseFormat(options.format);
16444
16842
  const ctx = requireQueryContext(options);
16445
- const iterations = loadIterations(ctx.layout).map((item)=>item.name);
16446
- const result = resolveIterationFromBranch(ctx.docsRoot, iterations);
16843
+ const result = readCurrentIteration(ctx.layout);
16844
+ if (!result.accessible) throw new errors_CliError(result.reason ?? '无法读取文档仓库', errors_EXIT.NOT_FOUND);
16845
+ const available = result.available.map((item)=>item.name);
16447
16846
  if ('json' === format) return void printJson({
16448
16847
  ok: true,
16449
- ...result,
16450
- available: iterations
16848
+ branch: result.branch,
16849
+ iteration: result.iteration,
16850
+ candidates: result.candidates,
16851
+ available
16451
16852
  });
16452
16853
  printLine(`分支:${result.branch ?? '(detached HEAD)'}`);
16453
16854
  if (null !== result.iteration) return void printLine(`迭代:${result.iteration}`);
16454
16855
  if (result.candidates.length > 0) return void printLine(`分支名同时匹配多个迭代,请显式指定 -i:${result.candidates.join('、')}`);
16455
16856
  printLine('迭代:未从分支名识别出迭代目录');
16456
- if (iterations.length > 0) printLine(`可用迭代:${iterations.join('、')}`);
16857
+ if (available.length > 0) printLine(`可用迭代:${available.join('、')}`);
16457
16858
  }
16458
16859
  function runCreate(name, options) {
16459
16860
  const ctx = requireQueryContext(options);
@@ -16910,9 +17311,9 @@ async function fetchManifest(url) {
16910
17311
  const payload = await response.json();
16911
17312
  if ('string' != typeof payload.version || 0 === payload.version.length) return null;
16912
17313
  return {
16913
- current: "0.8.0",
17314
+ current: "0.9.0",
16914
17315
  latest: payload.version,
16915
- hasUpdate: isNewer(payload.version, "0.8.0"),
17316
+ hasUpdate: isNewer(payload.version, "0.9.0"),
16916
17317
  downloadUrl: 'string' == typeof payload.downloadUrl ? payload.downloadUrl : null,
16917
17318
  source: 'manifest',
16918
17319
  checkedAt: new Date().toISOString(),
@@ -16924,7 +17325,7 @@ async function fetchManifest(url) {
16924
17325
  }
16925
17326
  async function fetchNpm() {
16926
17327
  const base = {
16927
- current: "0.8.0",
17328
+ current: "0.9.0",
16928
17329
  latest: null,
16929
17330
  hasUpdate: false,
16930
17331
  downloadUrl: null,
@@ -16951,7 +17352,7 @@ async function fetchNpm() {
16951
17352
  return {
16952
17353
  ...base,
16953
17354
  latest,
16954
- hasUpdate: isNewer(latest, "0.8.0"),
17355
+ hasUpdate: isNewer(latest, "0.9.0"),
16955
17356
  downloadUrl: null
16956
17357
  };
16957
17358
  } catch (error) {
@@ -17158,7 +17559,7 @@ async function runUpgrade(options) {
17158
17559
  const kind = detectInstallKind();
17159
17560
  const result = await checkUpdate(true);
17160
17561
  const target = void 0 === options.to ? result.latest : assertVersion(options.to.trim());
17161
- printLine("当前版本:0.8.0");
17562
+ printLine("当前版本:0.9.0");
17162
17563
  printLine(`安装方式:${installKindLabel(kind)}`);
17163
17564
  if (null !== result.error) printLine(`版本查询失败:${result.error}`);
17164
17565
  else if (null !== result.latest) printLine(`最新版本:${result.latest}(来源:${result.source})`);
@@ -17619,11 +18020,11 @@ function checkSchemaRequirement(config) {
17619
18020
  const required = parseMinVersion(schema.requiresYlcwf);
17620
18021
  if (null === required) return [];
17621
18022
  const floor = `${required[0]}.${required[1]}.${required[2]}`;
17622
- if (compareVersions("0.8.0", floor) >= 0) return [];
18023
+ if (compareVersions("0.9.0", floor) >= 0) return [];
17623
18024
  return [
17624
18025
  {
17625
18026
  level: 'error',
17626
- message: `文档仓库要求 ylcwf ${schema.requiresYlcwf},当前 0.8.0;请先升级:npm install -g ylcwf@latest`
18027
+ message: `文档仓库要求 ylcwf ${schema.requiresYlcwf},当前 0.9.0;请先升级:npm install -g ylcwf@latest`
17627
18028
  }
17628
18029
  ];
17629
18030
  } catch (error) {
@@ -17635,6 +18036,33 @@ function checkSchemaRequirement(config) {
17635
18036
  ];
17636
18037
  }
17637
18038
  }
18039
+ function checkWritability(config, configPath) {
18040
+ const issues = [];
18041
+ const probe = (target, label, hint)=>{
18042
+ try {
18043
+ accessSync(target, constants.W_OK);
18044
+ } catch (error) {
18045
+ const code = error.code;
18046
+ if ('ENOENT' === code) return void issues.push({
18047
+ level: 'error',
18048
+ message: `${label}不存在:${target}`
18049
+ });
18050
+ issues.push({
18051
+ level: 'error',
18052
+ message: `${label}不可写:${target}(${code ?? '未知错误'})${hint}`
18053
+ });
18054
+ }
18055
+ };
18056
+ const root = config.docs.root.trim();
18057
+ if (root.length > 0) {
18058
+ probe(root, '文档仓库', '写任务文档会失败;会话需能写该目录');
18059
+ const iterationsRoot = external_node_path_join(root, DEFAULT_ITERATIONS_ROOT);
18060
+ if (external_node_fs_existsSync(iterationsRoot)) probe(iterationsRoot, '文档仓库迭代目录', '写任务文档会失败;确认迭代目录可写');
18061
+ if (config.docs.git.cli.commit || config.docs.git.ui.commit) probe(external_node_path_join(root, '.git'), '文档仓库 .git', '已开启自动提交,提交会写 .git;可关闭 docs.git.*.commit');
18062
+ }
18063
+ probe(external_node_path_dirname(configPath), '配置目录', '变更历史与配置备份写不进去;确认家目录可写');
18064
+ return issues;
18065
+ }
17638
18066
  function runDoctor(options) {
17639
18067
  const format = parseFormat(options.format);
17640
18068
  const loaded = config_loadConfig(options.config);
@@ -17645,10 +18073,13 @@ function runDoctor(options) {
17645
18073
  const errors = countIssues(checked.issues).errors;
17646
18074
  const ok = !hasError(checked.issues);
17647
18075
  const sideIssues = [];
17648
- if (true === options.docs && null !== checked.config && ok) {
17649
- sideIssues.push(...checkSchemaRequirement(checked.config));
17650
- sideIssues.push(...doctor_checkTerminalCatalog(checked.config));
17651
- sideIssues.push(...checkDocsSides(checked.config));
18076
+ if (null !== checked.config) {
18077
+ sideIssues.push(...checkWritability(checked.config, loaded.path));
18078
+ if (true === options.docs && ok) {
18079
+ sideIssues.push(...checkSchemaRequirement(checked.config));
18080
+ sideIssues.push(...doctor_checkTerminalCatalog(checked.config));
18081
+ sideIssues.push(...checkDocsSides(checked.config));
18082
+ }
17652
18083
  }
17653
18084
  const sideErrors = sideIssues.filter((item)=>'error' === item.level).length;
17654
18085
  const allOk = ok && 0 === sideErrors;
@@ -17676,9 +18107,32 @@ function registerDoctor(program) {
17676
18107
  runDoctor(options);
17677
18108
  });
17678
18109
  }
18110
+ function runRemoteCache(options, format) {
18111
+ const root = remoteCacheRoot();
18112
+ const entries = listRemoteCacheDirs();
18113
+ if (true === options.exists) {
18114
+ const present = entries.length > 0;
18115
+ if ('json' === format) printJson({
18116
+ remoteCacheRoot: root,
18117
+ entries: entries.length,
18118
+ exists: present
18119
+ });
18120
+ else printLine(present ? 'true' : 'false');
18121
+ if (!present) process.exitCode = errors_EXIT.NOT_FOUND;
18122
+ return;
18123
+ }
18124
+ if ('json' === format) return void printJson({
18125
+ remoteCacheRoot: root,
18126
+ prefix: REMOTE_CACHE_PREFIX,
18127
+ entries
18128
+ });
18129
+ printLine(root);
18130
+ printLine(0 === entries.length ? '(当前没有远程快照缓存;在界面切到「远程」或调用 export 后才会生成)' : `快照缓存目录 ${entries.length} 个(${REMOTE_CACHE_PREFIX}*),保留最近 20 个`);
18131
+ }
17679
18132
  function runPath(options) {
17680
- const target = paths_resolveConfigPath(options.config);
17681
18133
  const format = parseFormat(options.format);
18134
+ if (true === options.remoteCache) return void runRemoteCache(options, format);
18135
+ const target = paths_resolveConfigPath(options.config);
17682
18136
  if (true === options.exists) {
17683
18137
  const present = external_node_fs_existsSync(target);
17684
18138
  if ('json' === format) printJson({
@@ -17692,7 +18146,7 @@ function runPath(options) {
17692
18146
  printLine(target);
17693
18147
  }
17694
18148
  function registerPath(program) {
17695
- program.command('path').description('输出配置文件绝对路径').option('-c, --config <path>', '指定配置文件路径').option('--exists', '改为输出配置文件是否存在(true/false)').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
18149
+ program.command('path').description('输出配置文件绝对路径,或远程快照缓存目录').option('-c, --config <path>', '指定配置文件路径').option('--exists', '改为输出目标是否存在(true/false)').option('--remote-cache', '改为输出远程快照缓存目录(系统临时目录)').option('--format <format>', '输出格式:human | json', 'human').action((options)=>{
17696
18150
  runPath(options);
17697
18151
  });
17698
18152
  }
@@ -17749,15 +18203,6 @@ function syncDocument(doc, next) {
17749
18203
  'validator',
17750
18204
  'strict'
17751
18205
  ], next.docs.validator.strict);
17752
- if (doc.hasIn([
17753
- 'docs',
17754
- 'validator',
17755
- 'requireScript'
17756
- ])) doc.deleteIn([
17757
- 'docs',
17758
- 'validator',
17759
- 'requireScript'
17760
- ]);
17761
18206
  const current = doc.toJS();
17762
18207
  const currentTerminals = utils_isRecord(current) && utils_isRecord(current['terminals']) ? Object.keys(current['terminals']) : [];
17763
18208
  for (const key of currentTerminals)if (!Object.hasOwn(next.terminals, key)) doc.deleteIn([
@@ -17788,7 +18233,15 @@ function syncDocument(doc, next) {
17788
18233
  ], terminal.repos.backend);
17789
18234
  }
17790
18235
  }
17791
- function collectResetTargets(configPath) {
18236
+ function backupsTarget(configPath) {
18237
+ const path = backupsDir(configPath);
18238
+ return external_node_fs_existsSync(path) ? {
18239
+ path,
18240
+ label: '配置备份',
18241
+ kind: 'dir'
18242
+ } : null;
18243
+ }
18244
+ function collectResetTargets(configPath, options = {}) {
17792
18245
  const targets = [
17793
18246
  {
17794
18247
  path: configPath,
@@ -17799,13 +18252,12 @@ function collectResetTargets(configPath) {
17799
18252
  path: `${configPath}.lock`,
17800
18253
  label: '锁文件',
17801
18254
  kind: 'file'
17802
- },
17803
- {
17804
- path: backupsDir(configPath),
17805
- label: '配置备份',
17806
- kind: 'dir'
17807
18255
  }
17808
18256
  ];
18257
+ if (true === options.removeBackups) {
18258
+ const backups = backupsTarget(configPath);
18259
+ if (null !== backups) targets.push(backups);
18260
+ }
17809
18261
  return targets.filter((target)=>external_node_fs_existsSync(target.path));
17810
18262
  }
17811
18263
  function describeTarget(target) {
@@ -17816,6 +18268,13 @@ function describeTarget(target) {
17816
18268
  const count = external_node_fs_readdirSync(target.path).length;
17817
18269
  return `${target.label}:${target.path}(${count} 项)`;
17818
18270
  }
18271
+ function countBackups(configPath) {
18272
+ try {
18273
+ return external_node_fs_readdirSync(backupsDir(configPath)).length;
18274
+ } catch {
18275
+ return 0;
18276
+ }
18277
+ }
17819
18278
  function performReset(configPath, targets) {
17820
18279
  for (const target of targets)rmSync(target.path, {
17821
18280
  recursive: true,
@@ -17860,7 +18319,7 @@ function readState(explicitPath) {
17860
18319
  issues: checked.issues,
17861
18320
  backups: listBackups(explicitPath),
17862
18321
  meta: {
17863
- version: "0.8.0",
18322
+ version: "0.9.0",
17864
18323
  features: SERVER_FEATURES
17865
18324
  }
17866
18325
  };
@@ -17933,13 +18392,17 @@ function resolveRequest(name, side, explicitPath) {
17933
18392
  repos
17934
18393
  };
17935
18394
  }
17936
- function resetConfig(explicitPath) {
18395
+ function resetConfig(explicitPath, options = {}) {
17937
18396
  const configPath = paths_resolveConfigPath(explicitPath);
17938
- const targets = collectResetTargets(configPath);
18397
+ const targets = collectResetTargets(configPath, {
18398
+ removeBackups: true === options.removeBackups
18399
+ });
17939
18400
  const removed = performReset(configPath, targets);
18401
+ const keptBackups = true === options.removeBackups ? 0 : countBackups(configPath);
17940
18402
  return {
17941
18403
  removed,
17942
- configPath
18404
+ configPath,
18405
+ keptBackups
17943
18406
  };
17944
18407
  }
17945
18408
  function inspectPath(target) {
@@ -18284,10 +18747,7 @@ function requireOwnDeveloper(input, configPath, options = {}) {
18284
18747
  if (developer !== loaded.config.profile.developer) throw new OperationError('只能修改自己的任务文档', options.forbidStatus ?? 403);
18285
18748
  return {
18286
18749
  developer,
18287
- policy: loaded.config.docs.git?.ui ?? {
18288
- commit: true,
18289
- push: false
18290
- }
18750
+ policy: loaded.config.docs.git?.ui ?? DEFAULT_GIT_POLICY
18291
18751
  };
18292
18752
  }
18293
18753
  function requireAction(input) {
@@ -18388,8 +18848,12 @@ const OPERATIONS = [
18388
18848
  path: '/api/reset'
18389
18849
  },
18390
18850
  ipc: 'ylcwf:reset',
18391
- ipcParams: [],
18392
- run: (_input, context)=>resetConfig(context.configPath)
18851
+ ipcParams: [
18852
+ 'all'
18853
+ ],
18854
+ run: (input, context)=>resetConfig(context.configPath, {
18855
+ removeBackups: input.bool('all')
18856
+ })
18393
18857
  },
18394
18858
  {
18395
18859
  name: 'onboarding-complete',
@@ -18624,6 +19088,16 @@ const OPERATIONS = [
18624
19088
  return listIterations(layoutOf(loaded.config), parseSource(input.text('source')), input.optionalText('ref'));
18625
19089
  }
18626
19090
  },
19091
+ {
19092
+ name: 'iteration-current',
19093
+ http: {
19094
+ method: 'GET',
19095
+ path: '/api/iteration-current'
19096
+ },
19097
+ ipc: 'ylcwf:iterationCurrent',
19098
+ ipcParams: [],
19099
+ run: (_input, context)=>readCurrentIteration(layoutOf(config_loadConfig(context.configPath).config))
19100
+ },
18627
19101
  {
18628
19102
  name: 'iteration-summary',
18629
19103
  http: {
@@ -20128,10 +20602,23 @@ function registerPrd(program) {
20128
20602
  }
20129
20603
  async function runReset(options) {
20130
20604
  const configPath = paths_resolveConfigPath(options.config);
20131
- const targets = collectResetTargets(configPath);
20132
- if (0 === targets.length) return void printLine('没有需要清除的配置,当前已经是干净状态。');
20605
+ const removeBackups = true === options.all;
20606
+ const targets = collectResetTargets(configPath, {
20607
+ removeBackups
20608
+ });
20609
+ const kept = removeBackups ? null : backupsTarget(configPath);
20610
+ if (0 === targets.length) {
20611
+ printLine('没有需要清除的配置,当前已经是干净状态。');
20612
+ if (null !== kept) printLine(`备份仍保留:${kept.path}(如需一并删除,加 --all)`);
20613
+ return;
20614
+ }
20133
20615
  printLine('将要清除:');
20134
20616
  for (const target of targets)printLine(` - ${describeTarget(target)}`);
20617
+ if (null !== kept) {
20618
+ printLine('');
20619
+ printLine(`备份保留:${kept.path}(${countBackups(configPath)} 项)`);
20620
+ printLine(' 备份可用于回滚;如需一并删除,加 --all');
20621
+ }
20135
20622
  if (true === options.dryRun) return void printLine('\n(--dry-run:未执行任何删除)');
20136
20623
  if (true !== options.yes) {
20137
20624
  if (true !== process.stdin.isTTY) throw new errors_CliError('非交互环境需要显式加 --yes 才会执行删除', errors_EXIT.USAGE);
@@ -20143,15 +20630,16 @@ async function runReset(options) {
20143
20630
  }
20144
20631
  const removed = performReset(configPath, targets);
20145
20632
  printLine(`\n已清除 ${removed} 项。下次打开工作台会重新进入首次引导。`);
20633
+ if (null !== kept) printLine(`备份已保留:${kept.path}(如需一并清空,加 --all)`);
20146
20634
  }
20147
20635
  function registerReset(program) {
20148
- program.command('reset').description('清除本机配置(配置与备份),用于从零重新引导').option('-c, --config <path>', '指定配置文件路径').option('--yes', '跳过确认').option('--dry-run', '只列出将要删除的内容').action(async (options)=>{
20636
+ program.command('reset').description('清除本机配置(默认保留配置备份),用于从零重新引导').option('-c, --config <path>', '指定配置文件路径').option('--yes', '跳过确认').option('--dry-run', '只列出将要删除的内容').option('--all', '连配置备份一起删除(默认保留,可回滚)').action(async (options)=>{
20149
20637
  await runReset(options);
20150
20638
  });
20151
20639
  }
20152
20640
  function buildProgram() {
20153
20641
  const program = new command_Command();
20154
- program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与执行终端仓库映射').version("0.8.0", '-v, --version', '显示版本号').showHelpAfterError();
20642
+ program.name('ylcwf').description('YLC 研发工作流配置:文档仓库、开发者标识、默认角色与执行终端仓库映射').version("0.9.0", '-v, --version', '显示版本号').showHelpAfterError();
20155
20643
  registerInit(program);
20156
20644
  registerShow(program);
20157
20645
  registerGet(program);
@@ -20223,7 +20711,7 @@ async function main() {
20223
20711
  main().catch((error)=>{
20224
20712
  const exitCode = error instanceof errors_CliError ? error.exitCode : errors_EXIT.INVALID;
20225
20713
  const message = error instanceof errors_CliError ? error.message : error instanceof Error ? error.message ?? String(error) : String(error);
20226
- if (jsonErrorsEnabled()) printJsonError(message, exitCode);
20714
+ if (jsonErrorsEnabled()) printJsonError(message, exitCode, error instanceof errors_CliError ? error.details : void 0);
20227
20715
  else error instanceof errors_CliError ? printError(message) : printError(error instanceof Error ? error.stack ?? message : message);
20228
20716
  process.exit(exitCode);
20229
20717
  });