@lyra-ai/toolkit 0.2.3 → 0.2.4

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/zentao.mjs +175 -109
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lyra-ai/toolkit",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "面向 AI agent 的零依赖开发工具集",
5
5
  "type": "module",
6
6
  "bin": {
package/src/zentao.mjs CHANGED
@@ -46,19 +46,21 @@ const HELP = `zentao-cli —— 面向 AI agent 的禅道 CLI
46
46
  命令:
47
47
  project list [--status active|closed|all] [--limit N] [--offset N] [--pretty]
48
48
  product list [--status active|closed|all] [--limit N] [--offset N] [--pretty]
49
+ build list [--project <ID|名称前缀>] [--limit N] [--offset N] [--pretty] # 列出项目版本(builds)
49
50
  bug list [--title <kw>] [--status S] [--severity 1-4] [--priority 1-4]
50
51
  [--assigned-to U] [--opened-by U] [--mine]
51
52
  [--product <ID|名称前缀>] [--project ID] [--start YYYY-MM-DD] [--end YYYY-MM-DD]
52
53
  [--order id_desc|openedDate_desc|severity_desc|priority_desc|...]
53
54
  [--limit N] [--offset N] [--pretty]
54
- # 本地缓存检索(需先 bug sync);bug search 等价别名;--product 支持名称前缀
55
+ # 仅在本地工作集内检索(需先 bug sync);bug search 等价别名
55
56
  bug get <bugId> [--pretty|--raw]
56
57
  bug create --title T [--product ID] [--severity 1-4] [--priority 1-4]
57
- [--assigned-to U] [--type code] [--steps ...] [--pretty]
58
+ [--assigned-to U] [--type code] [--build B] [--steps ...] [--pretty]
58
59
  bug resolve <bugId> --resolution <r> [--build B] [--comment ...]
59
60
  r ∈ {${RESOLUTIONS.join(',')}}
60
61
  bug assign <bugId> --to <user>
61
- bug sync [--product <ID|名称前缀>] [--status <browseType>] [--mine] # 同步产品 bug 到本地索引(默认 unclosed)
62
+ bug confirm <bugId> [--comment ...] [--assigned-to U] [--priority 1-4] [--type T] # 确认 Bug
63
+ bug sync [--product <ID|名称前缀>] [--status <browseType>] [--mine] # 同步产品 bug 到本地工作集(整体替换,默认 unclosed)
62
64
  bug browse-types # 列出 sync --status 的合法 browseType
63
65
  config 列出所有配置(密码脱敏)
64
66
  config get <key> 取单个配置值(ZENTAO_PASSWORD 需 --raw 才显原文)
@@ -307,6 +309,16 @@ export function shapeProduct(p) {
307
309
  };
308
310
  }
309
311
 
312
+ // 版本(build):依据 禅道APIv1.0.md §2.11 GET /projects/{id}/builds
313
+ export function shapeBuild(b) {
314
+ return {
315
+ id: b.id, name: b.name,
316
+ project: b.project ?? '', product: b.product ?? '',
317
+ execution: b.execution ?? '', branch: b.branch ?? '',
318
+ date: b.date ?? '', builder: b.builder ?? '', desc: b.desc ?? '',
319
+ };
320
+ }
321
+
310
322
  export function shapeBugListItem(b) {
311
323
  return {
312
324
  id: b.id, title: b.title, severity: b.severity, priority: b.pri,
@@ -345,6 +357,15 @@ export function productsToMarkdown({ total, count, products }) {
345
357
  return lines.join('\n');
346
358
  }
347
359
 
360
+ export function buildsToMarkdown({ total, count, builds }) {
361
+ const lines = ['# Builds List', '', `Found ${total} builds (showing ${count})`, '',
362
+ '| ID | Name | Project | Product | Date | Builder | Desc |', '|---|---|---|---|---|---|---|'];
363
+ for (const b of builds) {
364
+ lines.push(`| ${b.id} | ${b.name} | ${b.project} | ${b.product} | ${b.date} | ${b.builder} | ${b.desc} |`);
365
+ }
366
+ return lines.join('\n');
367
+ }
368
+
348
369
  export function bugListToMarkdown({ total, count, bugs }) {
349
370
  const lines = ['# Bug List', '', `Found ${total} bugs (showing ${count})`, '',
350
371
  '| ID | Title | Sev | Pri | Status | AssignedTo | OpenedBy | OpenedDate |', '|---|---|---|---|---|---|---|---|'];
@@ -704,43 +725,49 @@ async function cmdProductList(parsed, client) {
704
725
  return { stdout: JSON.stringify(out, null, 2) };
705
726
  }
706
727
 
707
- // 统一 bug 列表 全走本地缓存(先 sync 后查)
708
- // bug list / bug search 两者等价,search 为隐藏别名
709
- async function cmdBugList(parsed, config, deps) {
710
- const { cacheDir, fs, now } = deps;
711
- // 解析 --product:非数字按产品名前缀匹配
712
- let wantProduct = parsed.flags.product;
713
- if (wantProduct && !/^\d+$/.test(String(wantProduct))) {
714
- const client = deps.client || createClient(config, deps);
715
- const data = await client.request('GET', '/api.php/v1/products');
716
- const matches = (data.products || []).filter((p) => p.name && String(p.name).startsWith(wantProduct));
728
+ // 列出项目版本(builds):依据 禅道APIv1.0.md §2.11.1 GET /projects/{id}/builds
729
+ async function cmdBuildList(parsed, client, config) {
730
+ let projectId = parsed.flags.project || config.defaultProject;
731
+ if (!projectId) throw new ZentaoError('INVALID_PARAMETER', '未指定 --project 且无 ZENTAO_DEFAULT_PROJECT');
732
+ // 名称前缀解析 + 存在性校验(与 sync/create 一致)
733
+ const projectList = await client.request('GET', '/api.php/v1/projects');
734
+ const projects = projectList.projects || [];
735
+ const knownIds = new Set(projects.map((p) => String(p.id)));
736
+ if (!/^\d+$/.test(String(projectId))) {
737
+ const matches = projects.filter((p) => p.name && String(p.name).startsWith(projectId));
717
738
  if (!matches.length) {
718
- const names = (data.products || []).slice(0, 20).map((p) => p.name).filter(Boolean).join(', ');
719
- return { stderr: `未找到名前缀匹配 "${wantProduct}" 的产品。已知产品: ${names || '(无)'}`, exitCode: 2 };
739
+ const names = projects.slice(0, 20).map((p) => p.name).filter(Boolean).join(', ');
740
+ throw new ZentaoError('INVALID_PARAMETER', `未找到名前缀匹配 "${projectId}" 的项目。已知项目: ${names || '(无)'}`);
720
741
  }
721
- wantProduct = matches[0].id; // 优先取第一个匹配
742
+ projectId = matches[0].id;
722
743
  }
723
- const products = wantProduct ? [String(wantProduct)] : listCacheProducts(fs, cacheDir);
724
- if (!products.length) {
725
- return { stderr: '无本地缓存,请先:zentao bug sync --product <ID>', exitCode: 2 };
744
+ if (!knownIds.has(String(projectId))) {
745
+ throw new ZentaoError('INVALID_PARAMETER', `项目 ${projectId} 在当前服务器不存在。可用项目 ID: ${[...knownIds].slice(0, 20).join(', ') || '(无)'}`);
726
746
  }
727
- const nowMs = typeof now === 'function' ? now() : (now ?? Date.now());
728
- let merged = [];
729
- let oldestSync = Infinity;
730
- let missing = false;
731
- for (const pid of products) {
732
- const cache = readBugCache(cacheDir, pid, fs);
733
- if (!cache) { missing = true; continue; }
734
- oldestSync = Math.min(oldestSync, cache.syncedAt);
735
- for (const b of cache.bugs) merged.push({ ...b, productId: cache.product });
736
- }
737
- if (!merged.length && missing) {
738
- return { stderr: `产品 ${wantProduct} 无本地缓存,请先:zentao bug sync --product ${wantProduct}`, exitCode: 2 };
747
+ const data = await client.request('GET', `/api.php/v1/projects/${projectId}/builds`);
748
+ const builds = (data.builds || []).map(shapeBuild);
749
+ const limit = Number(parsed.flags.limit) || 20;
750
+ const offset = Number(parsed.flags.offset) || 0;
751
+ const page = paginate(builds, limit, offset);
752
+ const out = { total: page.total, count: page.count, offset: page.offset, has_more: page.has_more, next_offset: page.next_offset, builds: page.items };
753
+ if (parsed.flags.pretty) return { stdout: buildsToMarkdown({ ...out, builds: page.items }) };
754
+ return { stdout: JSON.stringify(out, null, 2) };
755
+ }
756
+
757
+ // 统一 bug 列表 → 只在本地【工作集】内查(先 sync 后查,list 不访问服务端)
758
+ // bug list / bug search 两者等价,search 为隐藏别名
759
+ async function cmdBugList(parsed, config, deps) {
760
+ const { cacheDir, fs, now } = deps;
761
+ const set = readWorkingSet(cacheDir, config, fs);
762
+ if (!set) {
763
+ return { stderr: '无本地工作集(或已切换服务器/账号),请先:zentao bug sync --product <ID|名称前缀>', exitCode: 2 };
739
764
  }
765
+ const nowMs = typeof now === 'function' ? now() : (now ?? Date.now());
766
+ let out = set.bugs.map((b) => ({ ...b }));
740
767
 
741
- // ---- 本地过滤 ----
742
- let out = merged;
768
+ // ---- 本地过滤 ----(--product 退化为本地 productId 过滤,不再访问服务端)
743
769
  if (parsed.flags.mine) out = out.filter((b) => b.assignedTo === config.username);
770
+ if (parsed.flags.product) out = out.filter((b) => String(b.productId) === String(parsed.flags.product));
744
771
  if (parsed.flags.title) {
745
772
  const kw = String(parsed.flags.title).toLowerCase();
746
773
  out = out.filter((b) => String(b.title || '').toLowerCase().includes(kw));
@@ -775,14 +802,14 @@ async function cmdBugList(parsed, config, deps) {
775
802
 
776
803
  // staleness 提示
777
804
  let stderr;
778
- if (isFinite(oldestSync) && nowMs - oldestSync > CACHE_STALE_MS) {
779
- const hrs = ((nowMs - oldestSync) / 3600000).toFixed(1);
780
- stderr = `⚠ 缓存可能过期(${hrs}h 前同步),关键判断请 'bug get <id>' 或重新 'bug sync'`;
805
+ if (nowMs - set.syncedAt > CACHE_STALE_MS) {
806
+ const hrs = ((nowMs - set.syncedAt) / 3600000).toFixed(1);
807
+ stderr = `⚠ 工作集可能过期(${hrs}h 前同步),关键判断请 'bug get <id>' 或重新 'bug sync'`;
781
808
  }
782
809
  if (parsed.flags.pretty) {
783
810
  return { stdout: bugListToMarkdown({ total: out.length, count: page.length, bugs: page }), stderr };
784
811
  }
785
- const body = { syncedAt: isFinite(oldestSync) ? oldestSync : null, total: out.length, count: page.length, offset, has_more: end < out.length, bugs: page };
812
+ const body = { syncedAt: set.syncedAt, product: set.product, total: out.length, count: page.length, offset, has_more: end < out.length, bugs: page };
786
813
  return { stdout: JSON.stringify(body, null, 2), stderr };
787
814
  }
788
815
 
@@ -798,21 +825,39 @@ async function cmdBugGet(parsed, client) {
798
825
 
799
826
  // 创建 Bug
800
827
  // 依据 禅道APIv1.0.md §创建Bug:POST /products/id/bugs(brief 原写 /projects/id/bugs 为误,文档以产品为作用域)
801
- // TODO 依据 禅道APIv1.0.md §创建Bug,实测受限(只读环境)未做活体验证
802
- async function cmdBugCreate(parsed, client, defaultProject) {
803
- // 文档作用域为 product;保留 --project 旗标与 defaultProject 配置以兼容现有 cfg,语义等同 productId
804
- const productId = parsed.flags.project || parsed.flags.product || defaultProject;
805
- if (!productId) throw new ZentaoError('INVALID_PARAMETER', '未指定 --project 且无 ZENTAO_DEFAULT_PROJECT');
828
+ async function cmdBugCreate(parsed, client, config) {
829
+ // 文档作用域为 product;保留 --project/--product 旗标与 defaultProject 配置,语义等同 productId
830
+ const defaultProject = config?.defaultProject;
831
+ let productId = parsed.flags.project || parsed.flags.product || defaultProject;
832
+ if (!productId) throw new ZentaoError('INVALID_PARAMETER', '未指定 --project/--product 且无 ZENTAO_DEFAULT_PROJECT');
806
833
  if (!parsed.flags.title) return { stderr: '错误:缺少 --title', exitCode: 2 };
834
+ // 名称前缀解析 + 存在性校验(与 sync 一致,防 defaultProject 指向不存在产品时静默出错)
835
+ const productList = await client.request('GET', '/api.php/v1/products');
836
+ const products = productList.products || [];
837
+ const knownIds = new Set(products.map((p) => String(p.id)));
838
+ if (!/^\d+$/.test(String(productId))) {
839
+ const matches = products.filter((p) => p.name && String(p.name).startsWith(productId));
840
+ if (!matches.length) {
841
+ const names = products.slice(0, 20).map((p) => p.name).filter(Boolean).join(', ');
842
+ throw new ZentaoError('INVALID_PARAMETER', `未找到名前缀匹配 "${productId}" 的产品。已知产品: ${names || '(无)'}`);
843
+ }
844
+ productId = matches[0].id;
845
+ }
846
+ if (!knownIds.has(String(productId))) {
847
+ throw new ZentaoError('INVALID_PARAMETER', `产品 ${productId} 在当前服务器不存在。可用产品 ID: ${[...knownIds].slice(0, 20).join(', ') || '(无)'}`);
848
+ }
807
849
  const body = {
808
850
  title: parsed.flags.title,
809
- // severity/pri/type 文档标为必填;这里仅透传,缺失时由后端校验
810
- ...(parsed.flags.severity ? { severity: parsed.flags.severity } : {}),
811
- ...(parsed.flags.priority ? { pri: parsed.flags.priority } : {}),
812
- ...(parsed.flags['assigned-to'] ? { assignedTo: parsed.flags['assigned-to'] } : {}),
813
- ...(parsed.flags.type ? { type: parsed.flags.type } : {}),
851
+ // openedBuild(影响版本):多数 zentao 版本必填,默认 trunk(主线)可在无 build 记录时创建;--build 可覆盖
852
+ openedBuild: parsed.flags.build || 'trunk',
853
+ // type(Bug类型):文档标必填,默认 code;--type 可覆盖(codeerror/interface/config/security/...)
854
+ type: parsed.flags.type || 'code',
855
+ // 默认指派给当前用户(自己),--assigned-to 可覆盖
856
+ assignedTo: parsed.flags['assigned-to'] || config?.username || '',
857
+ // severity/pri 文档标必填,默认 3(次要/中);--severity/--priority 可覆盖
858
+ severity: parsed.flags.severity || '3',
859
+ pri: parsed.flags.priority || '3',
814
860
  ...(parsed.flags.steps ? { steps: parsed.flags.steps } : {}),
815
- // openedBuild 在部分版本必填,留 TODO:实测后补默认值
816
861
  };
817
862
  const data = await client.request('POST', `/api.php/v1/products/${productId}/bugs`, { body });
818
863
  return { stdout: JSON.stringify({ id: data.id ?? data.bugId ?? null }, null, 2) };
@@ -820,19 +865,20 @@ async function cmdBugCreate(parsed, client, defaultProject) {
820
865
 
821
866
  // 解决 Bug
822
867
  // 依据 禅道APIv1.0.md §解决Bug:POST /bugs/id/resolve,body resolution 必填
823
- async function cmdBugResolve(parsed, client, deps) {
868
+ async function cmdBugResolve(parsed, client, deps, config) {
824
869
  const bugId = parsed.positional[0];
825
870
  if (!bugId) return { stderr: '错误:缺少 bugId', exitCode: 2 };
826
871
  if (!parsed.flags.resolution) return { stderr: `错误:缺少 --resolution(可选:${RESOLUTIONS.join(',')})`, exitCode: 2 };
827
872
  const body = {
828
873
  resolution: parsed.flags.resolution,
829
- ...(parsed.flags.build ? { resolvedBuild: parsed.flags.build } : {}),
874
+ // resolvedBuild(解决版本):21.x 起必填,默认 trunk(主线);--build 可覆盖
875
+ resolvedBuild: parsed.flags.build || 'trunk',
830
876
  ...(parsed.flags.comment ? { comment: parsed.flags.comment } : {}),
831
877
  };
832
878
  const data = await client.request('POST', `/api.php/v1/bugs/${bugId}/resolve`, { body });
833
- // best-effort 更新本地索引(不阻断)
834
- if (deps?.cacheDir && deps?.fs) {
835
- updateCachedBugAnywhere(deps.cacheDir, bugId, { status: 'resolved', resolution: parsed.flags.resolution }, deps.fs);
879
+ // best-effort 更新本地工作集(不阻断)
880
+ if (deps?.cacheDir && deps?.fs && config) {
881
+ updateWorkingSetBug(deps.cacheDir, config, bugId, { status: 'resolved', resolution: parsed.flags.resolution }, deps.fs);
836
882
  }
837
883
  return { stdout: JSON.stringify({ id: bugId, resolved: true, raw: data?.id ?? null }, null, 2) };
838
884
  }
@@ -842,19 +888,37 @@ async function cmdBugResolve(parsed, client, deps) {
842
888
  // 亦无独立 comment 端点)。指派复用「修改 Bug」通道,body 仅传 assignedTo 字段。
843
889
  // 字段名 assignedTo 为禅道各动作体(confirm/active/task 等)通用指派字段,与文档一致。
844
890
  // TODO 实测受限(只读环境)未做活体验证。
845
- async function cmdBugAssign(parsed, client, deps) {
891
+ async function cmdBugAssign(parsed, client, deps, config) {
846
892
  const bugId = parsed.positional[0];
847
893
  if (!bugId) return { stderr: '错误:缺少 bugId', exitCode: 2 };
848
894
  if (!parsed.flags.to) return { stderr: '错误:缺少 --to <user>', exitCode: 2 };
849
895
  const body = { assignedTo: parsed.flags.to };
850
896
  const data = await client.request('PUT', `/api.php/v1/bugs/${bugId}`, { body });
851
- // best-effort 更新本地索引(不阻断)
852
- if (deps?.cacheDir && deps?.fs) {
853
- updateCachedBugAnywhere(deps.cacheDir, bugId, { assignedTo: parsed.flags.to }, deps.fs);
897
+ // best-effort 更新本地工作集(不阻断)
898
+ if (deps?.cacheDir && deps?.fs && config) {
899
+ updateWorkingSetBug(deps.cacheDir, config, bugId, { assignedTo: parsed.flags.to }, deps.fs);
854
900
  }
855
901
  return { stdout: JSON.stringify({ id: bugId, assignedTo: parsed.flags.to, raw: data?.id ?? null }, null, 2) };
856
902
  }
857
903
 
904
+ // 确认 Bug:依据 禅道APIv1.0.md §2.14.6 POST /bugs/{id}/confirm(body 字段全可选)
905
+ async function cmdBugConfirm(parsed, client, deps, config) {
906
+ const bugId = parsed.positional[0];
907
+ if (!bugId) return { stderr: '错误:缺少 bugId', exitCode: 2 };
908
+ const body = {
909
+ ...(parsed.flags['assigned-to'] ? { assignedTo: parsed.flags['assigned-to'] } : {}),
910
+ ...(parsed.flags.type ? { type: parsed.flags.type } : {}),
911
+ ...(parsed.flags.priority ? { pri: parsed.flags.priority } : {}),
912
+ ...(parsed.flags.comment ? { comment: parsed.flags.comment } : {}),
913
+ };
914
+ const data = await client.request('POST', `/api.php/v1/bugs/${bugId}/confirm`, { body });
915
+ // best-effort:若改了优先级,同步到本地工作集(confirmed 标志不在列表 shape 内,不更新)
916
+ if (deps?.cacheDir && deps?.fs && config && parsed.flags.priority) {
917
+ updateWorkingSetBug(deps.cacheDir, config, bugId, { priority: parsed.flags.priority }, deps.fs);
918
+ }
919
+ return { stdout: JSON.stringify({ id: bugId, confirmed: true, raw: data?.id ?? null }, null, 2) };
920
+ }
921
+
858
922
  // ============ 本地 Bug 索引(sync / search) ============
859
923
 
860
924
  // bug 列表服务端 browseType 合法值(源码 module/bug/model.php getBugs 398-414)
@@ -880,71 +944,62 @@ export const BUG_BROWSE_TYPES = [
880
944
  // 缓存过期阈值(ms),默认 1h,可由 ZENTAO_CACHE_STALE_MS 覆盖
881
945
  const CACHE_STALE_MS = Number(process.env.ZENTAO_CACHE_STALE_MS) || 3600 * 1000;
882
946
 
883
- // 本地 bug 索引缓存 I/O(注入 fs 便于测试)
884
- export function cacheFilePath(dir, productId) {
885
- return `${dir}/bugs-${productId}.json`;
947
+ // ============ 本地工作集(单文件,绑 url+account) ============
948
+ // 设计:sync 定义工作集(整体替换),list 只在工作集内查,不再跨产品/跨服务器合并。
949
+ // 工作集文件盖 url/account 戳:切服务器/切账号后,旧工作集 url/account 不匹配 → 视为未 sync,
950
+ // 天然隔离,无需主动清理。
951
+
952
+ // 工作集文件名(整个本地只有一个工作集)
953
+ export function workingSetPath(dir) {
954
+ return `${dir}/working-set.json`;
955
+ }
956
+
957
+ // 身份戳:工作集归属哪个服务器+账号
958
+ function stampOf(config) {
959
+ return { url: config.zentaoUrl, account: config.username };
886
960
  }
887
961
 
888
- export function readBugCache(dir, productId, fs) {
962
+ // 读工作集;url/account 与当前配置不匹配 返回 null(视为未 sync)。注入 fs 便于测试。
963
+ export function readWorkingSet(dir, config, fs) {
889
964
  try {
890
- const raw = fs.readFileSync(cacheFilePath(dir, productId), 'utf8');
965
+ const raw = fs.readFileSync(workingSetPath(dir), 'utf8');
891
966
  const obj = JSON.parse(raw);
892
- if (obj && Array.isArray(obj.bugs)) return obj;
893
- return null; // 结构不符当作无缓存
894
- } catch (e) {
895
- if (e && e.code === 'ENOENT') return null;
896
- return null; // 损坏缓存当作无缓存
967
+ if (!obj || !Array.isArray(obj.bugs)) return null; // 结构不符当作无工作集
968
+ if (obj.url !== config.zentaoUrl || obj.account !== config.username) return null; // 跨服务器/账号 → 不可见
969
+ return obj;
970
+ } catch {
971
+ return null; // ENOENT / 损坏都当无工作集
897
972
  }
898
973
  }
899
974
 
900
- // 原子写:先写 .tmprename,避免崩溃损坏;目录自动建;权限收紧
901
- export function writeBugCache(dir, productId, data, fs) {
902
- const final = cacheFilePath(dir, productId);
975
+ // 原子写:盖身份戳 + tmprename,避免崩溃损坏;目录自动建;权限收紧
976
+ export function writeWorkingSet(dir, config, data, fs) {
977
+ const final = workingSetPath(dir);
903
978
  const tmp = `${final}.tmp`;
979
+ const stamped = { ...data, ...stampOf(config) }; // 戳最后写,始终反映当前身份
904
980
  try { fs.mkdirSync(dir, { recursive: true }); } catch { /* 已存在或不可建 */ }
905
- fs.writeFileSync(tmp, JSON.stringify(data), { mode: 0o600 });
981
+ fs.writeFileSync(tmp, JSON.stringify(stamped), { mode: 0o600 });
906
982
  try { if (typeof fs.chmodSync === 'function') fs.chmodSync(tmp, 0o600); } catch { /* Windows no-op */ }
907
983
  fs.renameSync(tmp, final);
908
984
  }
909
985
 
910
- // 列出已缓存的产品 id(扫描 cacheDir bugs-<id>.json)
911
- export function listCacheProducts(fs, cacheDir) {
912
- let entries = [];
913
- try { entries = fs.readdirSync(cacheDir); } catch { return []; }
914
- const out = [];
915
- for (const name of entries) {
916
- const m = name.match(/^bugs-(.+)\.json$/);
917
- if (m) out.push(m[1]);
918
- }
919
- return out;
920
- }
921
-
922
- // best-effort 更新某产品缓存中指定 bug;命中并写入返回 true,否则 false;失败静默
923
- export function updateCachedBug(cacheDir, productId, bugId, patch, fs) {
986
+ // best-effort:在工作集内就地更新某 bug(写命令 resolve/assign 后),命中并写入返回 true;失败静默
987
+ export function updateWorkingSetBug(cacheDir, config, bugId, patch, fs) {
924
988
  try {
925
- const cache = readBugCache(cacheDir, productId, fs);
926
- if (!cache) return false;
989
+ const set = readWorkingSet(cacheDir, config, fs);
990
+ if (!set) return false;
927
991
  let hit = false;
928
- cache.bugs = cache.bugs.map((b) => {
992
+ set.bugs = set.bugs.map((b) => {
929
993
  if (String(b.id) === String(bugId)) { hit = true; return { ...b, ...patch }; }
930
994
  return b;
931
995
  });
932
- if (hit) writeBugCache(cacheDir, productId, cache, fs);
996
+ if (hit) writeWorkingSet(cacheDir, config, set, fs);
933
997
  return hit;
934
998
  } catch {
935
999
  return false;
936
1000
  }
937
1001
  }
938
1002
 
939
- // 扫描所有已缓存产品,更新命中 bug(写命令后 best-effort)
940
- export function updateCachedBugAnywhere(cacheDir, bugId, patch, fs) {
941
- let hit = false;
942
- for (const pid of listCacheProducts(fs, cacheDir)) {
943
- if (updateCachedBug(cacheDir, pid, bugId, patch, fs)) hit = true;
944
- }
945
- return hit;
946
- }
947
-
948
1003
  // 输出 browseType 合法值
949
1004
  function cmdBugBrowseTypes(parsed) {
950
1005
  const rows = BUG_BROWSE_TYPES;
@@ -956,20 +1011,28 @@ function cmdBugBrowseTypes(parsed) {
956
1011
  return { stdout: JSON.stringify({ browseTypes: rows.map((r) => r.value) }, null, 2) };
957
1012
  }
958
1013
 
959
- // 一次性同步某产品 bug 到本地索引
1014
+ // 一次性同步某产品 bug 到本地【工作集】(整体替换,不再按产品分文件累加)
960
1015
  async function cmdBugSync(parsed, client, config, { cacheDir, fs }) {
961
1016
  let productId = parsed.flags.product || config.defaultProject;
1017
+ // 拉一次产品列表:名称前缀解析 + 存在性校验共用,避免重复请求
1018
+ const productList = await client.request('GET', '/api.php/v1/products');
1019
+ const products = productList.products || [];
1020
+ const knownIds = new Set(products.map((p) => String(p.id)));
962
1021
  // --product 非数字 → 产品名前缀匹配
963
1022
  if (productId && !/^\d+$/.test(String(productId))) {
964
- const data = await client.request('GET', '/api.php/v1/products');
965
- const matches = (data.products || []).filter((p) => p.name && String(p.name).startsWith(productId));
1023
+ const matches = products.filter((p) => p.name && String(p.name).startsWith(productId));
966
1024
  if (!matches.length) {
967
- const names = (data.products || []).slice(0, 20).map((p) => p.name).filter(Boolean).join(', ');
1025
+ const names = products.slice(0, 20).map((p) => p.name).filter(Boolean).join(', ');
968
1026
  throw new ZentaoError('INVALID_PARAMETER', `未找到名前缀匹配 "${productId}" 的产品。已知产品: ${names || '(无)'}`);
969
1027
  }
970
1028
  productId = matches[0].id;
971
1029
  }
972
1030
  if (!productId) throw new ZentaoError('INVALID_PARAMETER', '未指定 --product 且无 ZENTAO_DEFAULT_PROJECT');
1031
+ // 存在性校验:禅道对不存在的 product id 会【静默回退】到别的产品吐数据,
1032
+ // 不校验就会把 A 产品的请求错当成 B 产品并缓存(曾导致切本地后仍显示老数据)。
1033
+ if (!knownIds.has(String(productId))) {
1034
+ throw new ZentaoError('INVALID_PARAMETER', `产品 ${productId} 在当前服务器不存在。可用产品 ID: ${[...knownIds].slice(0, 20).join(', ') || '(无)'}`);
1035
+ }
973
1036
  const browseType = parsed.flags.status || 'unclosed'; // sync 的 --status = 服务端 browseType,默认 unclosed
974
1037
  const limit = 100;
975
1038
  const all = [];
@@ -980,10 +1043,11 @@ async function cmdBugSync(parsed, client, config, { cacheDir, fs }) {
980
1043
  if (!data.bugs || data.bugs.length < limit) break; // 不足一页 = 取完
981
1044
  }
982
1045
  // --mine:本地按 assignedTo === 当前账号 过滤(可与任意 browseType 叠加)
983
- const final = parsed.flags.mine ? all.filter((b) => b.assignedTo === config.username) : all;
984
- const cache = { product: String(productId), status: browseType, syncedAt: Date.now(), count: final.length, bugs: final };
985
- writeBugCache(cacheDir, productId, cache, fs); // 仅成功后写,失败不破坏旧缓存
986
- return { stdout: JSON.stringify({ product: String(productId), status: browseType, syncedAt: cache.syncedAt, count: final.length, cached: final.length }, null, 2) };
1046
+ const mine = !!parsed.flags.mine;
1047
+ const final = mine ? all.filter((b) => b.assignedTo === config.username) : all;
1048
+ const set = { product: String(productId), status: browseType, mine, syncedAt: Date.now(), count: final.length, bugs: final };
1049
+ writeWorkingSet(cacheDir, config, set, fs); // 整体替换工作集(盖 url/account 戳);仅成功后写,失败不破坏旧工作集
1050
+ return { stdout: JSON.stringify({ product: String(productId), status: browseType, mine, syncedAt: set.syncedAt, count: final.length }, null, 2) };
987
1051
  }
988
1052
 
989
1053
  // 命令分发:根据 parsed 派发到对应 cmd,捕获 ZentaoError 转 exitCode
@@ -999,11 +1063,13 @@ export async function runCommand(parsed, { config, deps }) {
999
1063
  else if (parsed.command === 'init') res = await cmdInit(parsed, config, deps);
1000
1064
  else if (parsed.command === 'project' && parsed.sub === 'list') res = await cmdProjectList(parsed, client);
1001
1065
  else if (parsed.command === 'product' && parsed.sub === 'list') res = await cmdProductList(parsed, client);
1066
+ else if (parsed.command === 'build' && parsed.sub === 'list') res = await cmdBuildList(parsed, client, config);
1002
1067
  else if (parsed.command === 'bug' && (parsed.sub === 'list' || parsed.sub === 'search')) res = await cmdBugList(parsed, config, deps);
1003
1068
  else if (parsed.command === 'bug' && parsed.sub === 'get') res = await cmdBugGet(parsed, client);
1004
- else if (parsed.command === 'bug' && parsed.sub === 'create') res = await cmdBugCreate(parsed, client, config.defaultProject);
1005
- else if (parsed.command === 'bug' && parsed.sub === 'resolve') res = await cmdBugResolve(parsed, client, deps);
1006
- else if (parsed.command === 'bug' && parsed.sub === 'assign') res = await cmdBugAssign(parsed, client, deps);
1069
+ else if (parsed.command === 'bug' && parsed.sub === 'create') res = await cmdBugCreate(parsed, client, config);
1070
+ else if (parsed.command === 'bug' && parsed.sub === 'resolve') res = await cmdBugResolve(parsed, client, deps, config);
1071
+ else if (parsed.command === 'bug' && parsed.sub === 'assign') res = await cmdBugAssign(parsed, client, deps, config);
1072
+ else if (parsed.command === 'bug' && parsed.sub === 'confirm') res = await cmdBugConfirm(parsed, client, deps, config);
1007
1073
  else if (parsed.command === 'bug' && parsed.sub === 'sync') res = await cmdBugSync(parsed, client, config, deps);
1008
1074
  else if (parsed.command === 'bug' && parsed.sub === 'browse-types') res = cmdBugBrowseTypes(parsed);
1009
1075
  else if (parsed.command === 'ping') res = await cmdPing(parsed, client, config);