shoplazza-ai-dev-cli 0.1.14 → 0.1.16

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.
@@ -1,6 +1,5 @@
1
1
  import { loadConfig, runLogin } from "../cli.mjs";
2
2
  import { readFileSync } from "fs";
3
- import * as readline from "readline";
4
3
  function parseGlobalFlags(args) {
5
4
  const flags = { json: false };
6
5
  const rest = [];
@@ -185,7 +184,11 @@ var TestPlatformClient = class TestPlatformClient {
185
184
  let payload = null;
186
185
  if (contentType.includes("application/json")) try {
187
186
  payload = await resp.json();
188
- } catch {
187
+ } catch (e) {
188
+ if (resp.ok) {
189
+ const detail = e instanceof Error ? e.message : String(e);
190
+ throw new ApiError(resp.status, "RESPONSE_BODY_INVALID", `响应声明 JSON 但解析失败(响应体不完整?): ${detail}`);
191
+ }
189
192
  payload = null;
190
193
  }
191
194
  if (!resp.ok) {
@@ -273,58 +276,47 @@ async function runTaxonomy(client, args, json) {
273
276
  process.exitCode = 2;
274
277
  }
275
278
  }
276
- function askConfirm(prompt) {
277
- const rl = readline.createInterface({
278
- input: process.stdin,
279
- output: process.stderr
280
- });
281
- return new Promise((resolve) => {
282
- rl.question(prompt, (answer) => {
283
- rl.close();
284
- resolve(answer.trim().toLowerCase());
285
- });
286
- });
279
+ const FEISHU_DETAIL_RE = /^https:\/\/project\.feishu\.cn\/[A-Za-z0-9_]+\/(?:work_items\/)?[A-Za-z0-9_]+\/detail\/(\d+)\/?$/;
280
+ function parseFeishuWorkItemId(raw) {
281
+ const clean = (raw.split("#")[0] ?? "").split("?")[0]?.trim() ?? "";
282
+ const m = FEISHU_DETAIL_RE.exec(clean);
283
+ return m ? m[1] : null;
287
284
  }
288
- async function syncWithGuard(client, url, payload, json, confirmUnlink) {
289
- try {
290
- return await client.post(url, payload);
291
- } catch (err) {
292
- if (!(err instanceof ApiError) || err.status !== 409 || err.code !== "SYNC_UNLINK_GUARD") throw err;
293
- const preview = err.data?.["unlink_preview"] ?? [];
294
- const msg = err.message;
295
- console.error(`\n⚠ ${msg}`);
296
- console.error("将被移除的用例:");
297
- for (const cid of preview) console.error(` - ${cid}`);
298
- if (!confirmUnlink) {
299
- console.error("\n如确认移除,请加 --confirm-unlink 重试。");
300
- process.exitCode = 1;
301
- return null;
302
- }
303
- if (json || !process.stdin.isTTY) {
304
- console.error("\n非交互模式,不自动重发。请在交互终端使用 --confirm-unlink。");
305
- process.exitCode = 1;
306
- return null;
307
- }
308
- if (await askConfirm(`确认移除 ${preview.length} 条用例?(y/N) `) !== "y") {
309
- console.error("已取消。");
310
- process.exitCode = 1;
311
- return null;
312
- }
313
- if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
314
- printError("Sync payload must be a JSON object (not array or primitive)");
315
- process.exitCode = 1;
316
- return null;
317
- }
318
- const body = {
319
- ...payload,
320
- force_unlink: true
321
- };
322
- return await client.post(url, body);
285
+ const SYNC_REPLACE_REMOVED_MSG = "--mode replace 已下线:解绑语义已废弃(2026-07-24),删除用例请在 Web 页面操作";
286
+ const GOVERNANCE_KEYS = [
287
+ "mode",
288
+ "confirm_unlink",
289
+ "force_unlink"
290
+ ];
291
+ function validateSyncModeFlag(mode) {
292
+ if (mode === void 0 || mode === "merge") return null;
293
+ return SYNC_REPLACE_REMOVED_MSG;
294
+ }
295
+ function validateSyncFlags(named) {
296
+ if (named["confirm-unlink"] !== void 0 || named["force-unlink"] !== void 0) return SYNC_REPLACE_REMOVED_MSG;
297
+ return validateSyncModeFlag(named["mode"]);
298
+ }
299
+ function buildMergeSyncBody(payload) {
300
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) throw new Error("Sync payload must be a JSON object (not array or primitive)");
301
+ const obj = payload;
302
+ if (obj["mode"] !== void 0 && obj["mode"] !== "merge") throw new Error(`payload 内嵌 mode="${String(obj["mode"])}" 已下线:sync 仅支持 merge,删除用例请在 Web 页面操作`);
303
+ if (obj["confirm_unlink"] !== void 0 || obj["force_unlink"] !== void 0) throw new Error("payload 内嵌 confirm_unlink/force_unlink 已下线:解绑语义已废弃,删除用例请在 Web 页面操作");
304
+ const body = {};
305
+ for (const [k, v] of Object.entries(obj)) {
306
+ if (GOVERNANCE_KEYS.includes(k)) continue;
307
+ body[k] = v;
323
308
  }
309
+ body["mode"] = "merge";
310
+ return body;
324
311
  }
325
- async function create$4(client, args, json) {
312
+ async function create$2(client, args, json) {
326
313
  const { named } = parseNamedArgs(args);
327
- const reqId = requireArg(named, "req-id", "req_id");
314
+ const feishuUrl = requireArg(named, "feishu-url", "feishu_ticket_url");
315
+ if (!parseFeishuWorkItemId(feishuUrl)) {
316
+ printError("--feishu-url 需为飞书需求详情页 URL(…/detail/<数字ID>),请从工单页面复制");
317
+ process.exitCode = 2;
318
+ return;
319
+ }
328
320
  const title = requireArg(named, "title", "title");
329
321
  const bl = requireArg(named, "bl", "business_line");
330
322
  const modulePaths = asArray(named["module-paths"]);
@@ -333,14 +325,12 @@ async function create$4(client, args, json) {
333
325
  process.exitCode = 2;
334
326
  return;
335
327
  }
336
- const feishuUrl = typeof named["feishu-url"] === "string" ? named["feishu-url"] : void 0;
337
328
  const body = {
338
- req_id: reqId,
339
329
  title,
340
330
  business_line: bl,
341
- module_paths: modulePaths
331
+ module_paths: modulePaths,
332
+ feishu_ticket_url: feishuUrl
342
333
  };
343
- if (feishuUrl) body["feishu_ticket_url"] = feishuUrl;
344
334
  const data = await client.post("/api/test/requirements", body);
345
335
  if (json) {
346
336
  printJson(data);
@@ -348,8 +338,11 @@ async function create$4(client, args, json) {
348
338
  }
349
339
  if (data["created"]) {
350
340
  printSuccess(`Requirement created: ${data["req_id"]}`);
351
- printKV([["Title", data["title"]], ["Status", data["status"]]]);
352
- console.log(" (case set auto-created)");
341
+ printKV([
342
+ ["Title", data["title"]],
343
+ ["Status", data["status"]],
344
+ ["Case Set ID", data["case_set_id"] ?? "—"]
345
+ ]);
353
346
  } else console.log(`ℹ Requirement already exists: ${data["req_id"]} (not modified)`);
354
347
  }
355
348
  async function sync$1(client, args, json) {
@@ -361,9 +354,21 @@ async function sync$1(client, args, json) {
361
354
  return;
362
355
  }
363
356
  const payload = readFileInput(requireArg(named, "file", "path"));
364
- const confirmUnlink = named["confirm-unlink"] !== void 0;
365
- const data = await syncWithGuard(client, `/api/test/requirements/${encodeURIComponent(reqId)}/cases:sync`, payload, json, confirmUnlink);
366
- if (!data) return;
357
+ const flagErr = validateSyncFlags(named);
358
+ if (flagErr) {
359
+ printError(flagErr);
360
+ process.exitCode = 2;
361
+ return;
362
+ }
363
+ let body;
364
+ try {
365
+ body = buildMergeSyncBody(payload);
366
+ } catch (e) {
367
+ printError(e.message);
368
+ process.exitCode = 2;
369
+ return;
370
+ }
371
+ const data = await client.post(`/api/test/requirements/${encodeURIComponent(reqId)}/cases:sync`, body);
367
372
  if (json) {
368
373
  printJson(data);
369
374
  return;
@@ -376,7 +381,6 @@ async function sync$1(client, args, json) {
376
381
  ["Referenced", s["referenced"] ?? 0],
377
382
  ["Updated", s["updated"] ?? 0],
378
383
  ["Existing (linked)", s["skipped"] ?? 0],
379
- ["Unlinked", s["unlinked"] ?? 0],
380
384
  ["Failed", s["failed"] ?? 0]
381
385
  ]);
382
386
  for (const r of results.filter((r) => r.action === "failed")) printError(` ${r.client_ref}: ${(r.errors ?? []).join(", ")}`);
@@ -470,7 +474,7 @@ async function runRequirements(client, args, json) {
470
474
  const action = args[0];
471
475
  const subArgs = args.slice(1);
472
476
  switch (action) {
473
- case "create": return create$4(client, subArgs, json);
477
+ case "create": return create$2(client, subArgs, json);
474
478
  case "get": return get$2(client, subArgs, json);
475
479
  case "sync": return sync$1(client, subArgs, json);
476
480
  case "list": return list$2(client, subArgs, json);
@@ -497,17 +501,10 @@ const VALID_PLAN_TYPES = [
497
501
  "smoke"
498
502
  ];
499
503
  const VALID_ENVS = [
500
- "local",
501
504
  "dev",
505
+ "sandbox",
502
506
  "stg",
503
- "prod",
504
- "auto"
505
- ];
506
- const VALID_MARK_STATUSES = [
507
- "passed",
508
- "failed",
509
- "skipped",
510
- "blocked"
507
+ "prod"
511
508
  ];
512
509
  const VALID_USER_KINDS = [
513
510
  "regression",
@@ -515,63 +512,6 @@ const VALID_USER_KINDS = [
515
512
  "baseline",
516
513
  "custom"
517
514
  ];
518
- async function create$3(client, args, json) {
519
- const { named } = parseNamedArgs(args);
520
- const body = {
521
- title: requireArg(named, "title", "title"),
522
- business_line: requireArg(named, "bl", "business_line"),
523
- module_path: requireArg(named, "module-path", "module_path"),
524
- case_type: requireArg(named, "type", "case_type"),
525
- steps: (() => {
526
- const raw = requireArg(named, "steps", "steps");
527
- try {
528
- const parsed = JSON.parse(raw);
529
- if (!Array.isArray(parsed) || parsed.length === 0) throw new Error("steps must be a non-empty JSON array");
530
- for (let i = 0; i < parsed.length; i++) {
531
- const s = parsed[i];
532
- if (!s.step?.trim()) throw new Error(`steps[${i}].step is empty`);
533
- if (!s.expected?.trim()) throw new Error(`steps[${i}].expected is empty`);
534
- }
535
- return parsed;
536
- } catch (e) {
537
- printError(`Invalid --steps: ${e.message}`);
538
- process.exitCode = 2;
539
- return null;
540
- }
541
- })()
542
- };
543
- if (body["steps"] === null) return;
544
- const caseType = body["case_type"];
545
- if (!VALID_CASE_TYPES.includes(caseType)) {
546
- printError(`Invalid --type "${caseType}": must be ${VALID_CASE_TYPES.join("|")}`);
547
- process.exitCode = 2;
548
- return;
549
- }
550
- if (typeof named["priority"] === "string") {
551
- if (!VALID_PRIORITIES.includes(named["priority"])) {
552
- printError(`Invalid --priority "${named["priority"]}": must be ${VALID_PRIORITIES.join("|")}`);
553
- process.exitCode = 2;
554
- return;
555
- }
556
- body["priority"] = named["priority"];
557
- }
558
- body["precondition"] = requireArg(named, "precondition", "precondition");
559
- if (typeof named["source"] === "string") body["source"] = named["source"];
560
- const tags = asArray(named["tags"]);
561
- if (tags.length) body["tags"] = tags;
562
- const data = await client.post("/api/test/cases", body);
563
- if (json) {
564
- printJson(data);
565
- return;
566
- }
567
- printSuccess(`Case created: ${data["case_id"]}`);
568
- printKV([
569
- ["Title", data["title"]],
570
- ["Module", `${data["module_path"] ?? `id=${data["module_id"]}`}`],
571
- ["Type", data["case_type"]],
572
- ["Priority", data["priority"] || "—"]
573
- ]);
574
- }
575
515
  async function list$1(client, args, json) {
576
516
  const { named } = parseNamedArgs(args);
577
517
  const params = {};
@@ -620,46 +560,11 @@ async function list$1(client, args, json) {
620
560
  ]);
621
561
  printPagination(data.total);
622
562
  }
623
- async function batch$1(client, args, json) {
624
- const { named } = parseNamedArgs(args);
625
- const payload = readFileInput(requireArg(named, "file", "path"));
626
- const data = await client.post("/api/test/cases/batch", payload);
627
- if (json) {
628
- printJson(data);
629
- return;
630
- }
631
- const s = data.summary;
632
- printSuccess(`Batch created ${s["created"] ?? 0} cases`);
633
- printKV([
634
- ["Created", s["created"] ?? 0],
635
- ["Skipped (dup)", s["skipped"] ?? 0],
636
- ["Failed", s["failed"] ?? 0]
637
- ]);
638
- for (const r of data.results.filter((r) => r.action === "created")) console.log(` ${r.case_id} ${r.client_ref || ""}`);
639
- for (const r of data.results.filter((r) => r.action === "failed")) printError(` ${r.client_ref}: ${(r.errors ?? []).join(", ")}`);
640
- }
641
- async function remove$1(client, args, json) {
642
- if (args.length === 0) {
643
- printError("Usage: test cases delete <case_id...>");
644
- process.exitCode = 2;
645
- return;
646
- }
647
- const data = await client.post("/api/test/cases:delete", { case_ids: args });
648
- if (json) {
649
- printJson(data);
650
- return;
651
- }
652
- if (data.deleted.length) printSuccess(`Deleted: ${data.deleted.join(", ")}`);
653
- for (const item of data.blocked ?? []) printError(`${item.case_id}: referenced by plan(s) ${item.plan_ids.join(", ")}`);
654
- if (data.not_found?.length) printError(`Not found: ${data.not_found.join(", ")}`);
655
- if (data.already?.length) printError(`Already deleted: ${data.already.join(", ")}`);
656
- }
657
563
  const UPDATE_FIELDS = [
658
564
  "title",
659
565
  "precondition",
660
566
  "steps",
661
567
  "priority",
662
- "tags",
663
568
  "status",
664
569
  "case_type",
665
570
  "module_path",
@@ -683,7 +588,6 @@ function namedArgsToRaw(named) {
683
588
  const val = Array.isArray(v) ? v[v.length - 1] : v;
684
589
  if (typeof val === "string") raw[field] = val;
685
590
  }
686
- if (named["tags"] !== void 0) raw["tags"] = asArray(named["tags"]);
687
591
  if (typeof named["steps"] === "string") {
688
592
  let parsed;
689
593
  try {
@@ -720,10 +624,6 @@ function buildCaseUpdatePayload(raw) {
720
624
  if (!VALID_CASE_TYPES.includes(t)) throw new Error(`Invalid case_type "${t}": must be ${VALID_CASE_TYPES.join("|")}`);
721
625
  body["case_type"] = t;
722
626
  }
723
- if (raw["tags"] !== void 0) {
724
- if (!Array.isArray(raw["tags"])) throw new Error("tags must be an array of strings");
725
- body["tags"] = raw["tags"].map((x) => String(x));
726
- }
727
627
  if (raw["steps"] !== void 0) {
728
628
  const steps = raw["steps"];
729
629
  if (!Array.isArray(steps) || steps.length === 0) throw new Error("steps must be a non-empty array");
@@ -749,7 +649,6 @@ function resolveUpdateInput(positional, named) {
749
649
  "module-path",
750
650
  "bl",
751
651
  "module-id",
752
- "tags",
753
652
  "steps"
754
653
  ].filter((f) => named[f] !== void 0);
755
654
  const useFile = typeof named["file"] === "string";
@@ -802,22 +701,19 @@ async function runCases(client, args, json) {
802
701
  const action = args[0];
803
702
  const subArgs = args.slice(1);
804
703
  switch (action) {
805
- case "create": return create$3(client, subArgs, json);
806
704
  case "list": return list$1(client, subArgs, json);
807
- case "batch": return batch$1(client, subArgs, json);
808
- case "delete": return remove$1(client, subArgs, json);
809
705
  case "update": return update(client, subArgs, json);
810
706
  case "--help":
811
707
  case "-h":
812
708
  case void 0:
813
- console.log(`cases commands:\n create Create a standalone case\n list List cases with filters\n batch Batch create cases from JSON (--file <path>)\n update Patch a case by id (pointer semantics: only pass fields to change; --file <path|-> for JSON body)\n delete Soft-delete case assets by id`);
709
+ console.log(`cases commands:\n list List cases with filters\n update Patch a case by id (pointer semantics: only pass fields to change; --file <path|-> for JSON body)`);
814
710
  return;
815
711
  default:
816
712
  printError(`Unknown cases action: ${action}`);
817
713
  process.exitCode = 2;
818
714
  }
819
715
  }
820
- async function create$2(client, args, json) {
716
+ async function create$1(client, args, json) {
821
717
  const { named } = parseNamedArgs(args);
822
718
  const name = requireArg(named, "name", "name");
823
719
  const kind = requireArg(named, "kind", "regression|flow|baseline|custom");
@@ -841,29 +737,6 @@ async function create$2(client, args, json) {
841
737
  printSuccess(`Case set created: ${data["id"]}`);
842
738
  printKV([["Name", data["name"]], ["Kind", data["kind"]]]);
843
739
  }
844
- async function members(client, args, json) {
845
- const { positional, named } = parseNamedArgs(args);
846
- const setId = positional[0];
847
- if (!setId) {
848
- printError("Usage: test case-sets members <set_id> --add ...");
849
- process.exitCode = 2;
850
- return;
851
- }
852
- const add = asArray(named["add"]);
853
- if (!add.length) {
854
- printError("Provide --add");
855
- process.exitCode = 2;
856
- return;
857
- }
858
- const body = {};
859
- if (add.length) body["add"] = add;
860
- const data = await client.post(`/api/test/case-sets/${setId}/members:batch`, body);
861
- if (json) {
862
- printJson(data);
863
- return;
864
- }
865
- printSuccess(`Added ${data.added}, invalid: ${(data.invalid ?? []).length}`);
866
- }
867
740
  async function get$1(client, args, json) {
868
741
  const { positional } = parseNamedArgs(args);
869
742
  const setId = positional[0];
@@ -908,6 +781,15 @@ async function get$1(client, args, json) {
908
781
  }
909
782
  ]);
910
783
  }
784
+ function preflightGroupFields(payload) {
785
+ const cases = payload?.cases;
786
+ if (!Array.isArray(cases)) return null;
787
+ for (let i = 0; i < cases.length; i++) {
788
+ const item = cases[i];
789
+ if (item && item.group !== void 0 && item.group_segments !== void 0) return `cases[${i}] 同时携带 group 与 group_segments(二选一),请只保留一种形态`;
790
+ }
791
+ return null;
792
+ }
911
793
  async function sync(client, args, json) {
912
794
  const { positional, named } = parseNamedArgs(args);
913
795
  const setId = positional[0];
@@ -917,9 +799,27 @@ async function sync(client, args, json) {
917
799
  return;
918
800
  }
919
801
  const payload = readFileInput(requireArg(named, "file", "path"));
920
- const confirmUnlink = named["confirm-unlink"] !== void 0;
921
- const data = await syncWithGuard(client, `/api/test/case-sets/${setId}/cases:sync`, payload, json, confirmUnlink);
922
- if (!data) return;
802
+ const groupConflict = preflightGroupFields(payload);
803
+ if (groupConflict) {
804
+ printError(groupConflict);
805
+ process.exitCode = 2;
806
+ return;
807
+ }
808
+ const flagErr = validateSyncFlags(named);
809
+ if (flagErr) {
810
+ printError(flagErr);
811
+ process.exitCode = 2;
812
+ return;
813
+ }
814
+ let body;
815
+ try {
816
+ body = buildMergeSyncBody(payload);
817
+ } catch (e) {
818
+ printError(e.message);
819
+ process.exitCode = 2;
820
+ return;
821
+ }
822
+ const data = await client.post(`/api/test/case-sets/${setId}/cases:sync`, body);
923
823
  if (json) {
924
824
  printJson(data);
925
825
  return;
@@ -932,7 +832,6 @@ async function sync(client, args, json) {
932
832
  ["Referenced", s["referenced"] ?? 0],
933
833
  ["Updated", s["updated"] ?? 0],
934
834
  ["Existing (linked)", s["skipped"] ?? 0],
935
- ["Unlinked", s["unlinked"] ?? 0],
936
835
  ["Failed", s["failed"] ?? 0]
937
836
  ]);
938
837
  for (const r of results.filter((r) => r.action === "failed")) printError(` ${r.client_ref}: ${(r.errors ?? []).join(", ")}`);
@@ -941,21 +840,20 @@ async function runCaseSets(client, args, json) {
941
840
  const action = args[0];
942
841
  const subArgs = args.slice(1);
943
842
  switch (action) {
944
- case "create": return create$2(client, subArgs, json);
843
+ case "create": return create$1(client, subArgs, json);
945
844
  case "get": return get$1(client, subArgs, json);
946
- case "members": return members(client, subArgs, json);
947
845
  case "sync": return sync(client, subArgs, json);
948
846
  case "--help":
949
847
  case "-h":
950
848
  case void 0:
951
- console.log(`case-sets commands:\n create Create a case set (--name, --kind [--module <id>])\n get Get case set detail with members\n members Batch add members (--add)\n sync Sync cases to a set (--file <path>)`);
849
+ console.log(`case-sets commands:\n create Create a case set (--name, --kind [--module <id>])\n get Get case set detail with members\n sync Sync cases to a set (--file <path>)`);
952
850
  return;
953
851
  default:
954
852
  printError(`Unknown case-sets action: ${action}`);
955
853
  process.exitCode = 2;
956
854
  }
957
855
  }
958
- async function create$1(client, args, json) {
856
+ async function create(client, args, json) {
959
857
  const { named } = parseNamedArgs(args);
960
858
  const planType = requireArg(named, "type", "requirement|regression|smoke");
961
859
  if (!VALID_PLAN_TYPES.includes(planType)) {
@@ -978,23 +876,27 @@ async function create$1(client, args, json) {
978
876
  }
979
877
  const tags = asArray(named["tags"]);
980
878
  if (tags.length) body["tags"] = tags;
981
- const sources = [
982
- body["case_ids"] ? "case-ids" : null,
983
- body["from_case_set"] !== void 0 ? "from-set" : null,
984
- body["req_id"] ? "req-id" : null
985
- ].filter(Boolean);
986
- if (sources.length === 0) {
987
- printError("Must specify one of --case-ids, --from-set, or --req-id");
879
+ const matrixError = validatePlanCreateMatrix(planType, {
880
+ reqId: typeof body["req_id"] === "string" && body["req_id"] !== "",
881
+ caseIds: Array.isArray(body["case_ids"]) && body["case_ids"].length > 0,
882
+ fromSet: body["from_case_set"] !== void 0
883
+ });
884
+ if (matrixError) {
885
+ printError(matrixError);
988
886
  process.exitCode = 2;
989
887
  return;
990
888
  }
991
- if (sources.length > 1) {
992
- printError(`--${sources.join(", --")} are mutually exclusive`);
993
- process.exitCode = 2;
889
+ const data = await client.post("/api/test/test-plans", body);
890
+ const problems = reconcilePlanCreateResponse(planType, {
891
+ reqId: body["req_id"],
892
+ caseIds: body["case_ids"]
893
+ }, data);
894
+ if (problems.length) {
895
+ printError(`创建对账失败(计划 ${String(data["plan_id"] ?? "?")} 可能已创建,请人工核查,勿直接重试创建): ${problems.join("; ")}`);
896
+ if (json) printJson(data);
897
+ process.exitCode = 1;
994
898
  return;
995
899
  }
996
- if (body["case_ids"]) console.error("⚠ 建议使用 --req-id 或 --from-set 从用例集拉取,避免手工枚举遗漏");
997
- const data = await client.post("/api/test/test-plans", body);
998
900
  if (json) {
999
901
  printJson(data);
1000
902
  return;
@@ -1003,11 +905,42 @@ async function create$1(client, args, json) {
1003
905
  printKV([
1004
906
  ["Title", data["title"]],
1005
907
  ["Type", data["type"]],
908
+ ["Req", data["req_id"] ?? "—"],
1006
909
  ["Env", data["env"]],
1007
910
  ["Cases", data["case_count"]],
1008
911
  ["Status", data["status"]]
1009
912
  ]);
1010
913
  }
914
+ function validatePlanCreateMatrix(planType, src) {
915
+ switch (planType) {
916
+ case "requirement":
917
+ if (!src.reqId || src.caseIds || src.fromSet) return "type=requirement 只接受 --req-id(需求全量计划)";
918
+ return null;
919
+ case "smoke":
920
+ if (!src.reqId || !src.caseIds || src.fromSet) return "type=smoke 必须同时提供 --req-id 与 --case-ids(测试员手选),不接受 --from-set";
921
+ return null;
922
+ case "regression":
923
+ if (!src.fromSet || src.reqId) return "type=regression 只接受 --from-set(全局用例集),可选 --case-ids 建子集回归,不接受 --req-id";
924
+ return null;
925
+ default: return `Invalid type "${planType}"`;
926
+ }
927
+ }
928
+ function reconcilePlanCreateResponse(planType, requested, data) {
929
+ const problems = [];
930
+ if (data["type"] !== planType) problems.push(`type=${String(data["type"])} ≠ ${planType}`);
931
+ const respCaseIds = Array.isArray(data["case_ids"]) ? data["case_ids"] : null;
932
+ if (!respCaseIds || respCaseIds.length === 0) problems.push("响应缺少冻结 case_ids");
933
+ else if (data["case_count"] !== respCaseIds.length) problems.push(`case_count=${String(data["case_count"])} ≠ len(case_ids)=${respCaseIds.length}`);
934
+ const respReqId = data["req_id"] ?? null;
935
+ if (planType === "regression") {
936
+ if (respReqId !== null) problems.push(`全局回归 req_id 应为 null,实际 ${String(respReqId)}`);
937
+ } else if (respReqId !== requested.reqId) problems.push(`req_id=${String(respReqId)} ≠ ${String(requested.reqId)}`);
938
+ if (respCaseIds && requested.caseIds && requested.caseIds.length > 0) {
939
+ const want = new Set(requested.caseIds);
940
+ if (respCaseIds.length !== want.size || respCaseIds.some((id) => !want.has(id))) problems.push("冻结 case_ids 与请求选集不一致");
941
+ }
942
+ return problems;
943
+ }
1011
944
  async function get(client, args, json) {
1012
945
  const { positional } = parseNamedArgs(args);
1013
946
  const planId = positional[0];
@@ -1026,14 +959,22 @@ async function get(client, args, json) {
1026
959
  ["Title", data["title"]],
1027
960
  ["Type", data["type"]],
1028
961
  ["Env", data["env"]],
1029
- ["Status", data["status"]]
962
+ ["Status", data["status"]],
963
+ ["Source set", data["source_case_set_id"] ?? "—"],
964
+ ["Addable from source", data["addable_from_source_count"] ?? 0]
1030
965
  ]);
1031
966
  const progress = data["progress"];
1032
967
  if (progress) console.log(` Progress: ${progress["passed"]}p / ${progress["failed"]}f / ${progress["pending"]} pending (total ${progress["total"]})`);
1033
968
  const cases = data["cases"];
1034
969
  if (cases && cases.length) {
1035
970
  console.log(`\n Cases (${cases.length}):`);
1036
- for (const c of cases) console.log(` [${c["case_id"]}] ${c["title"]} (${c["priority"] || "—"})`);
971
+ for (const c of cases) {
972
+ const marks = [];
973
+ if (c["in_source_set"] === false) marks.push("已离开来源集");
974
+ if (c["content_updated"] === true) marks.push(`正文已更新 v${c["case_version_at_add"]}→v${c["current_version"]}`);
975
+ const suffix = marks.length ? ` [${marks.join(" · ")}]` : "";
976
+ console.log(` [${c["case_id"]}] ${c["title"]} (${c["priority"] || "—"})${suffix}`);
977
+ }
1037
978
  }
1038
979
  }
1039
980
  async function list(client, args, json) {
@@ -1085,85 +1026,49 @@ async function list(client, args, json) {
1085
1026
  ]);
1086
1027
  printPagination(data.total);
1087
1028
  }
1088
- async function remove(client, args, json) {
1029
+ async function add(client, args, json) {
1089
1030
  const { positional } = parseNamedArgs(args);
1090
1031
  const [planId, ...caseIDs] = positional;
1091
1032
  if (!planId || caseIDs.length === 0) {
1092
- printError("Usage: test plans remove <plan_id> <case_id> [case_id...]");
1033
+ printError("Usage: test plans add <plan_id> <case_id> [case_id...]");
1093
1034
  process.exitCode = 2;
1094
1035
  return;
1095
1036
  }
1096
- const data = await client.post(`/api/test/test-plans/${encodeURIComponent(planId)}/cases:remove`, { case_ids: caseIDs });
1037
+ const data = await client.post(`/api/test/test-plans/${encodeURIComponent(planId)}/cases`, { case_ids: caseIDs });
1097
1038
  if (json) {
1098
1039
  printJson(data);
1099
1040
  return;
1100
1041
  }
1101
- const removed = Array.isArray(data["removed"]) ? data["removed"] : [];
1102
- const blocked = Array.isArray(data["blocked"]) ? data["blocked"] : [];
1103
- const notInPlan = Array.isArray(data["not_in_plan"]) ? data["not_in_plan"] : [];
1104
- if (removed.length) printSuccess(`Removed ${removed.length} case(s) from ${planId}`);
1105
- if (blocked.length) printKV([["Blocked", JSON.stringify(blocked)]]);
1106
- if (notInPlan.length) printKV([["Not in plan", notInPlan.join(", ")]]);
1042
+ const added = Array.isArray(data["added"]) ? data["added"] : [];
1043
+ const already = Array.isArray(data["already_in_plan"]) ? data["already_in_plan"] : [];
1044
+ const rejected = Array.isArray(data["rejected"]) ? data["rejected"] : [];
1045
+ if (added.length) printSuccess(`Added ${added.length} case(s) to ${planId}: ${added.join(", ")}`);
1046
+ printKV([
1047
+ ["Already in plan", already.length ? already.join(", ") : "—"],
1048
+ ["Rejected", rejected.length ? rejected.map((r) => `${r.case_id}(${r.reason})`).join(", ") : "—"],
1049
+ ["Case count", data["case_count"]],
1050
+ ["Status", data["status"]]
1051
+ ]);
1052
+ if (rejected.length) process.exitCode = 1;
1107
1053
  }
1108
1054
  async function runPlans(client, args, json) {
1109
1055
  const action = args[0];
1110
1056
  const subArgs = args.slice(1);
1111
1057
  switch (action) {
1112
- case "create": return create$1(client, subArgs, json);
1058
+ case "create": return create(client, subArgs, json);
1113
1059
  case "get": return get(client, subArgs, json);
1114
1060
  case "list": return list(client, subArgs, json);
1115
- case "remove": return remove(client, subArgs, json);
1061
+ case "add": return add(client, subArgs, json);
1116
1062
  case "--help":
1117
1063
  case "-h":
1118
1064
  case void 0:
1119
- console.log(`plans commands:\n create Create a test plan\n get Get plan detail (--json for full case content)\n list List plans\n remove Remove case(s) from an unreported plan`);
1065
+ console.log(`plans commands:\n create Create a test plan\n get Get plan detail (--json for full case content)\n list List plans\n add Append source-set case(s) to an unreported plan`);
1120
1066
  return;
1121
1067
  default:
1122
1068
  printError(`Unknown plans action: ${action}`);
1123
1069
  process.exitCode = 2;
1124
1070
  }
1125
1071
  }
1126
- async function mark(client, args, json) {
1127
- const { positional, named } = parseNamedArgs(args);
1128
- const planId = positional[0];
1129
- const caseId = positional[1];
1130
- if (!planId || !caseId) {
1131
- printError("Usage: test results mark <plan_id> <case_id> --status <status>");
1132
- process.exitCode = 2;
1133
- return;
1134
- }
1135
- const status = requireArg(named, "status", "passed|failed|skipped|blocked");
1136
- if (!VALID_MARK_STATUSES.includes(status)) {
1137
- printError(`Invalid --status "${status}": must be ${VALID_MARK_STATUSES.join("|")}`);
1138
- process.exitCode = 2;
1139
- return;
1140
- }
1141
- const body = {
1142
- plan_id: planId,
1143
- case_id: caseId,
1144
- status
1145
- };
1146
- if (typeof named["remark"] === "string") body["remark"] = named["remark"];
1147
- if (typeof named["evidence-url"] === "string") body["evidence_url"] = named["evidence-url"];
1148
- if (typeof named["duration-ms"] === "string") {
1149
- const n = Number(named["duration-ms"]);
1150
- if (Number.isNaN(n) || n < 0 || n > 36e5) {
1151
- printError("--duration-ms must be a number in range 0~3600000");
1152
- process.exitCode = 2;
1153
- return;
1154
- }
1155
- body["duration_ms"] = n;
1156
- }
1157
- const data = await client.post("/api/test/case-results", body);
1158
- if (json) {
1159
- printJson(data);
1160
- return;
1161
- }
1162
- printSuccess(`Marked ${caseId} as ${body["status"]} in ${planId}`);
1163
- const p = data["progress"];
1164
- if (p) console.log(` Progress: ${p["passed"]}/${p["total"]} passed, ${p["failed"]} failed, ${p["error"]} error, ${p["blocked"]} blocked, ${p["skipped"]} skipped, ${p["pending"]} pending`);
1165
- console.log(` Plan status: ${data["plan_status"]}`);
1166
- }
1167
1072
  async function batch(client, args, json) {
1168
1073
  const { positional, named } = parseNamedArgs(args);
1169
1074
  const planId = positional[0];
@@ -1189,73 +1094,24 @@ async function runResults(client, args, json) {
1189
1094
  const action = args[0];
1190
1095
  const subArgs = args.slice(1);
1191
1096
  switch (action) {
1192
- case "mark": return mark(client, subArgs, json);
1193
1097
  case "batch": return batch(client, subArgs, json);
1194
1098
  case "--help":
1195
1099
  case "-h":
1196
1100
  case void 0:
1197
- console.log(`results commands:\n mark Mark a single case result (Scenario A)\n batch Batch submit results from file (Scenario B)`);
1101
+ console.log(`results commands:\n batch Batch submit results from file (Scenario B)`);
1198
1102
  return;
1199
1103
  default:
1200
1104
  printError(`Unknown results action: ${action}`);
1201
1105
  process.exitCode = 2;
1202
1106
  }
1203
1107
  }
1204
- async function create(client, args, json) {
1205
- const { positional, named } = parseNamedArgs(args);
1206
- const planId = positional[0];
1207
- if (!planId) {
1208
- printError("Usage: test reports create <plan_id> [--conclusion <text>]");
1209
- process.exitCode = 2;
1210
- return;
1211
- }
1212
- const body = { plan_id: planId };
1213
- if (typeof named["type"] === "string") {
1214
- if (!VALID_PLAN_TYPES.includes(named["type"])) {
1215
- printError(`Invalid --type "${named["type"]}": must be ${VALID_PLAN_TYPES.join("|")}`);
1216
- process.exitCode = 2;
1217
- return;
1218
- }
1219
- body["type"] = named["type"];
1220
- }
1221
- if (typeof named["conclusion"] === "string") body["conclusion"] = named["conclusion"];
1222
- if (typeof named["risk-notes"] === "string") body["risk_notes"] = named["risk-notes"];
1223
- const data = await client.post("/api/test/reports", body);
1224
- if (json) {
1225
- printJson(data);
1226
- return;
1227
- }
1228
- printSuccess(`Report issued: ${data["report_id"]} (version ${data["version"]})`);
1229
- console.log(` Plan: ${data["plan_id"]}`);
1230
- const snap = data["summary_snapshot"];
1231
- if (snap) {
1232
- const counts = snap["counts"];
1233
- if (counts) console.log(` Summary: ${counts["passed"]} passed, ${counts["failed"]} failed (total ${counts["total"]})`);
1234
- }
1235
- }
1236
- async function runReports(client, args, json) {
1237
- const action = args[0];
1238
- const subArgs = args.slice(1);
1239
- switch (action) {
1240
- case "create": return create(client, subArgs, json);
1241
- case "--help":
1242
- case "-h":
1243
- case void 0:
1244
- console.log(`reports commands:\n create Issue a report for a plan`);
1245
- return;
1246
- default:
1247
- printError(`Unknown reports action: ${action}`);
1248
- process.exitCode = 2;
1249
- }
1250
- }
1251
1108
  const RESOURCES = {
1252
1109
  taxonomy: runTaxonomy,
1253
1110
  requirements: runRequirements,
1254
1111
  cases: runCases,
1255
1112
  "case-sets": runCaseSets,
1256
1113
  plans: runPlans,
1257
- results: runResults,
1258
- reports: runReports
1114
+ results: runResults
1259
1115
  };
1260
1116
  const HELP = `Testing platform commands (Scenario A & B).
1261
1117
 
@@ -1265,8 +1121,7 @@ Resources:
1265
1121
  requirements Requirements & channel 1 sync
1266
1122
  case-sets Case set member management
1267
1123
  plans Test plans & execution
1268
- results Test results (mark / batch)
1269
- reports Test reports
1124
+ results Test results (batch)
1270
1125
 
1271
1126
  Run: shoplazza-ai-dev-cli test <resource> --help`;
1272
1127
  async function runTest(rawArgs) {
package/dist/cli.mjs CHANGED
@@ -7238,5 +7238,12 @@ main().catch((err) => {
7238
7238
  const msg = err instanceof Error ? err.stack ?? err.message : String(err);
7239
7239
  console.error(`\n${BOLD}✗${RESET} ${msg}`);
7240
7240
  process.exitCode = 1;
7241
- }).finally(() => flushTelemetry().then(() => process.exit(process.exitCode ?? 0)));
7241
+ }).finally(() => flushTelemetry().then(() => new Promise((resolve) => {
7242
+ let pending = 2;
7243
+ const done = () => {
7244
+ if (--pending === 0) resolve();
7245
+ };
7246
+ process.stdout.write("", done);
7247
+ process.stderr.write("", done);
7248
+ })).then(() => process.exit(process.exitCode ?? 0)));
7242
7249
  export { loadConfig, runLogin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shoplazza-ai-dev-cli",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
4
4
  "description": "Shoplazza AI Dev CLI: install, publish and manage AI agent skills/rules",
5
5
  "type": "module",
6
6
  "bin": {
@@ -22,7 +22,8 @@
22
22
  "format:check": "prettier --check \"src/**/*.ts\" \"scripts/**/*.ts\"",
23
23
  "test": "vitest",
24
24
  "type-check": "tsc --noEmit",
25
- "publish:snapshot": "npm version prerelease --preid=snapshot --no-git-tag-version && npm publish --tag snapshot"
25
+ "publish:snapshot": "npm version prerelease --preid=snapshot --no-git-tag-version && npm publish --tag snapshot",
26
+ "publish:latest": "npm ci && npm version patch --no-git-tag-version && npm publish --tag latest"
26
27
  },
27
28
  "keywords": [
28
29
  "cli",