simplify3x-connect 0.31.2 → 0.31.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 (70) hide show
  1. package/dist/adapters/simplifyqa/adapter.d.ts +173 -46
  2. package/dist/adapters/simplifyqa/adapter.d.ts.map +1 -1
  3. package/dist/adapters/simplifyqa/adapter.js +858 -210
  4. package/dist/adapters/simplifyqa/adapter.js.map +1 -1
  5. package/dist/adapters/simplifyqa/mapper.d.ts +18 -0
  6. package/dist/adapters/simplifyqa/mapper.d.ts.map +1 -1
  7. package/dist/adapters/simplifyqa/mapper.js +85 -1
  8. package/dist/adapters/simplifyqa/mapper.js.map +1 -1
  9. package/dist/adapters/simplifyqa/stackSetup.d.ts +60 -0
  10. package/dist/adapters/simplifyqa/stackSetup.d.ts.map +1 -0
  11. package/dist/adapters/simplifyqa/stackSetup.js +135 -0
  12. package/dist/adapters/simplifyqa/stackSetup.js.map +1 -0
  13. package/dist/adapters/types.d.ts +16 -4
  14. package/dist/adapters/types.d.ts.map +1 -1
  15. package/dist/domain/types.d.ts +11 -0
  16. package/dist/domain/types.d.ts.map +1 -1
  17. package/dist/domain/types.js.map +1 -1
  18. package/dist/initAgents.d.ts.map +1 -1
  19. package/dist/initAgents.js +6 -4
  20. package/dist/initAgents.js.map +1 -1
  21. package/dist/server.d.ts.map +1 -1
  22. package/dist/server.js +13 -2
  23. package/dist/server.js.map +1 -1
  24. package/dist/tools/actionBackup.tools.d.ts +26 -0
  25. package/dist/tools/actionBackup.tools.d.ts.map +1 -0
  26. package/dist/tools/actionBackup.tools.js +144 -0
  27. package/dist/tools/actionBackup.tools.js.map +1 -0
  28. package/dist/tools/attachment.tools.d.ts +14 -0
  29. package/dist/tools/attachment.tools.d.ts.map +1 -1
  30. package/dist/tools/attachment.tools.js +46 -38
  31. package/dist/tools/attachment.tools.js.map +1 -1
  32. package/dist/tools/autoDefectLog.d.ts +5 -0
  33. package/dist/tools/autoDefectLog.d.ts.map +1 -1
  34. package/dist/tools/autoDefectLog.js +29 -0
  35. package/dist/tools/autoDefectLog.js.map +1 -1
  36. package/dist/tools/backlog.tools.d.ts.map +1 -1
  37. package/dist/tools/backlog.tools.js +7 -5
  38. package/dist/tools/backlog.tools.js.map +1 -1
  39. package/dist/tools/defectUpdate.tools.d.ts +3 -2
  40. package/dist/tools/defectUpdate.tools.d.ts.map +1 -1
  41. package/dist/tools/defectUpdate.tools.js +106 -20
  42. package/dist/tools/defectUpdate.tools.js.map +1 -1
  43. package/dist/tools/discovery.tools.d.ts.map +1 -1
  44. package/dist/tools/discovery.tools.js +51 -20
  45. package/dist/tools/discovery.tools.js.map +1 -1
  46. package/dist/tools/executionPlan.tools.d.ts.map +1 -1
  47. package/dist/tools/executionPlan.tools.js +38 -20
  48. package/dist/tools/executionPlan.tools.js.map +1 -1
  49. package/dist/tools/pipeline.tools.js +1 -1
  50. package/dist/tools/pipeline.tools.js.map +1 -1
  51. package/dist/tools/releaseSprint.tools.d.ts +1 -1
  52. package/dist/tools/releaseSprint.tools.d.ts.map +1 -1
  53. package/dist/tools/releaseSprint.tools.js +67 -1
  54. package/dist/tools/releaseSprint.tools.js.map +1 -1
  55. package/dist/tools/run.tools.d.ts.map +1 -1
  56. package/dist/tools/run.tools.js +44 -15
  57. package/dist/tools/run.tools.js.map +1 -1
  58. package/dist/tools/stackSetupTool.d.ts +21 -0
  59. package/dist/tools/stackSetupTool.d.ts.map +1 -0
  60. package/dist/tools/stackSetupTool.js +28 -0
  61. package/dist/tools/stackSetupTool.js.map +1 -0
  62. package/dist/tools/suiteManage.tools.d.ts.map +1 -1
  63. package/dist/tools/suiteManage.tools.js +14 -13
  64. package/dist/tools/suiteManage.tools.js.map +1 -1
  65. package/dist/tools/testcase.tools.d.ts.map +1 -1
  66. package/dist/tools/testcase.tools.js +34 -9
  67. package/dist/tools/testcase.tools.js.map +1 -1
  68. package/dist/version.d.ts +1 -1
  69. package/dist/version.js +1 -1
  70. package/package.json +1 -1
@@ -15,10 +15,11 @@ import { mergeApiPatch } from '../../drafts/apiPatch.js';
15
15
  import { matchStepNumbers } from '../../drafts/bulk.js';
16
16
  import { resolveCollection } from './searchRegistry.js';
17
17
  import { mapLimit } from './mapLimit.js';
18
+ import { distributeCases, firstEmptyStack, pickBrowser, resolveStacks } from './stackSetup.js';
18
19
  import { ExecutionFailureAnalysis, fetchFailureImage } from './executionFailures.js';
19
20
  import { log } from '../../log.js';
20
21
  import { applyHealPlan as applyHealPlanCore } from './heal/apply.js';
21
- import { applyCollectionSteps, buildTestcasePayload, deriveTcType, extractApiParamNames, extractParamNames, extractValueParamNames, fromSqaStep, isApiRequestStep, runtimeSlotValue, looksSensitive, normalizeSuiteEntry, notDeleted, numericId, paramDefault, pickArray, str, SUITE_UPDATE_ALLOWED_KEYS, TECH_BY_STEPTYPE, toDefectSummary, toEpic, toEpicSummary, toFeature, toFeatureSummary, toFunction, toFunctionSummary, toModuleSaved, toModuleSummary, toObject, toImageUrl, toReleaseSummary, toSavedRef, toSprintSummary, toStory, toStorySummary, toSuite, toSuiteSummary, toTaskSummary, toTcSummary, toTestCase, toVersionEntries, withTotal, } from './mapper.js';
22
+ import { applyCollectionSteps, buildTestcasePayload, deriveTcType, extractApiParamNames, extractParamNames, extractValueParamNames, fromSqaStep, isApiRequestStep, isBlankStep, runtimeSlotValue, looksSensitive, normalizeSuiteEntry, notDeleted, numericId, paramDefault, pickArray, str, withoutBlankSteps, SUITE_UPDATE_ALLOWED_KEYS, TECH_BY_STEPTYPE, toDefectSummary, toEpic, toEpicSummary, toFeature, toFeatureSummary, toFunction, toFunctionSummary, toModuleSaved, toModuleSummary, toObject, toImageUrl, toReleaseSummary, toSavedRef, toSprintSummary, toStory, toStorySummary, toSuite, toSuiteSummary, toTaskSummary, toTcSummary, toTestCase, toVersionEntries, withTotal, } from './mapper.js';
22
23
  /** A DESKTOP save reuses only DESKTOP objects. Matching by name alone merged desktop locators into an iOS object
23
24
  * that happened to share the name ("Login"); a new DESKTOP object is created instead. Every other technology
24
25
  * keeps matching by name alone. */
@@ -402,6 +403,7 @@ const BACKLOG_ATTACHMENT_SPECS = {
402
403
  epic: { path: '/pm/epic', objKey: 'epicObj', parentType: 'EP', keys: EPIC_FORM_KEYS },
403
404
  feature: { path: '/pm/feature', objKey: 'featureObj', parentType: 'FT', keys: FEATURE_FORM_KEYS },
404
405
  userstory: { path: '/pm/userstory', objKey: 'userstoryObj', parentType: 'US', keys: STORY_FORM_KEYS },
406
+ defect: { path: '/pm/defect', objKey: 'defectObj', parentType: 'DE', keys: [] },
405
407
  };
406
408
  const STEP_ALLOWED_KEYS = ['projectId', 'sharedFnProjectId', 'moduleId', 'apiData', 'lastActiveTab', 'userstoryId',
407
409
  'updateVersion', 'type', 'parentId', 'objectId', 'stepType', 'functionId', 'actionId',
@@ -565,6 +567,46 @@ function testcaseVersion(raw, optional = false) {
565
567
  throw new Error(`${str(raw, 'code') ?? `TC-${raw?.id}`} has no version to add.`);
566
568
  return { versionId: versionId ?? '', versionName: versionName ?? 'v1.0' };
567
569
  }
570
+ /** Reject a planned end date that is before the planned start date. The SQA web form blocks this, but
571
+ * the backend happily saves it (US-2564 saved 2026-12-10 → 2026-12-01), so the MCP must enforce it on
572
+ * every backlog write that takes planned dates. Only checks when both are present in the same call. */
573
+ export function assertPlannedDates(start, end) {
574
+ const s = (start ?? '').trim();
575
+ const e = (end ?? '').trim();
576
+ if (!s || !e)
577
+ return;
578
+ const day = (v) => {
579
+ if (!/^\d{4}-\d{2}-\d{2}/.test(v) || Number.isNaN(new Date(v).getTime())) {
580
+ throw new Error(`Planned dates must look like 2026-12-10 (got "${v}").`);
581
+ }
582
+ return v.slice(0, 10);
583
+ };
584
+ const [ds, de] = [day(s), day(e)];
585
+ if (de <= ds)
586
+ throw new Error(`Planned end date (${de}) must be after the planned start date (${ds}).`);
587
+ }
588
+ /** Version for a plan/suite entry: the requested one (id or name), else the test case's current one.
589
+ * A requested version that does not exist FAILS — silently falling back to v1.0 turned a request for
590
+ * v2.0 into a duplicate v1.0 row. */
591
+ export function pickTestcaseVersion(raw, wantId, wantName) {
592
+ const id = (wantId ?? '').trim();
593
+ const name = (wantName ?? '').trim();
594
+ if (!id && !name)
595
+ return testcaseVersion(raw);
596
+ const versions = Array.isArray(raw?.versions) ? raw.versions : [];
597
+ const hit = versions.find((v) => {
598
+ const vid = str(v, 'id', '_id', 'versionId') ?? '';
599
+ const vname = str(v, 'name', 'versionName') ?? '';
600
+ return (id && vid === id) || (name && vname.trim().toLowerCase() === name.toLowerCase());
601
+ });
602
+ if (!hit) {
603
+ const code = str(raw, 'code') ?? `TC-${raw?.id}`;
604
+ const available = versions.map((v) => `${str(v, 'name') ?? '?'} (${str(v, 'id', '_id', 'versionId') ?? '?'})`).join(', ');
605
+ throw new Error(`${code} has no version ${id ? `"${id}"` : `"${name}"`}. Available versions: ${available || '(none)'}. ` +
606
+ `Read them with sqa_query({ op:"get", collection:"testcases", id:"${code}" }).`);
607
+ }
608
+ return { versionId: str(hit, 'id', '_id', 'versionId') ?? '', versionName: str(hit, 'name', 'versionName') ?? '' };
609
+ }
568
610
  /** Refused suite delete: something still uses it (the caller lists `blockers`). */
569
611
  export class SuiteBlockedError extends Error {
570
612
  constructor(suite, blockers) {
@@ -574,6 +616,15 @@ export class SuiteBlockedError extends Error {
574
616
  this.name = 'SuiteBlockedError';
575
617
  }
576
618
  }
619
+ export class PmBlockedError extends Error {
620
+ constructor(kind, record, blockers) {
621
+ super(`${record.code ?? record.id} is still in use and was not deleted.`);
622
+ this.kind = kind;
623
+ this.record = record;
624
+ this.blockers = blockers;
625
+ this.name = 'PmBlockedError';
626
+ }
627
+ }
577
628
  const toRef = (r) => {
578
629
  const code = str(r, 'code');
579
630
  const name = str(r, 'name');
@@ -628,9 +679,10 @@ function sqaRecurrence(type, start, end, timeZone, extra = {}) {
628
679
  const given = Object.keys(extra);
629
680
  if (given.length) {
630
681
  if (once)
631
- throw new Error(`A Once schedule has no recurrence settings (${given.join(', ')}) — pick hourly / daily / weekly / monthly.`);
632
- if (type === 'every_5_minutes') {
633
- throw new Error('Every 5 Minutes is fixed at 5 minutes — SimplifyQA has no other minute interval. For another cadence use hourly / daily / weekly / monthly with `interval` N (e.g. hourly, interval 2 = every 2 hours).');
682
+ throw new Error(`A Once schedule has no recurrence settings (${given.join(', ')}) — pick every_n_minutes / hourly / daily / weekly / monthly.`);
683
+ if (type === 'every_5_minutes' && extra.interval !== undefined) {
684
+ // "Every N minutes" — the Scheduler stores it as EVERY_5_MINUTES + interval N; interval 1 = 5 minutes.
685
+ // (Kept permissive: the product's picker is fixed at 5, but the record accepts N.)
634
686
  }
635
687
  }
636
688
  let interval = 1;
@@ -695,16 +747,30 @@ function sqaBrowser(browser) {
695
747
  if (!browser)
696
748
  return 'CHROME';
697
749
  const id = SQA_BROWSERS[browser.trim().toLowerCase()];
698
- if (!id)
699
- throw new Error(`Unknown browser "${browser}" — use chrome, edge, firefox or safari.`);
700
- return id;
750
+ if (id)
751
+ return id;
752
+ // a UI picker key as the Scheduler stores it (CHROME_HEADLESS, FIREFOX_PRIVATE …)
753
+ try {
754
+ return pickBrowser(browser, 'LOCAL').key;
755
+ }
756
+ catch { /* fall through to the plain message */ }
757
+ throw new Error(`Unknown browser "${browser}" — use chrome, edge, firefox or safari.`);
758
+ }
759
+ /** A CLOUD run / schedule is headless: the UI's cloud picker offers only Chrome, Firefox and Edge Headless. "chrome" there means Chrome
760
+ * Headless; a browser the picker does not offer (Safari …) is refused with the three that exist. */
761
+ export const CLOUD_BROWSER_NAMES = ['Chrome Headless', 'Firefox Headless', 'Edge Headless'];
762
+ function cloudBrowserEntry(browser) {
763
+ const b = pickBrowser(browser, 'CLOUD');
764
+ return { name: b.key, id: b.key, technologyType: 'WEB', type: 'NONE' }; // the UI binds key → id AND name
701
765
  }
702
766
  /** The platform a test case runs on, as the scheduler form derives it from `tcType`: its browser for
703
767
  * WEB, its own technology for API / MAINFRAME / SAP / DESKTOP / DATABASE. Mobile needs a device the
704
768
  * MCP can't pick, so it is refused. */
705
- function tcPlatform(tc, browser) {
769
+ function tcPlatform(tc, browser, cloud = false) {
706
770
  const tech = String(tc?.tcType ?? 'WEB').toUpperCase();
707
771
  if (tech === 'WEB') {
772
+ if (cloud)
773
+ return [cloudBrowserEntry(browser)];
708
774
  const b = sqaBrowser(browser);
709
775
  return [{ id: b, name: b, type: 'NONE', technologyType: 'WEB' }];
710
776
  }
@@ -716,7 +782,7 @@ function tcPlatform(tc, browser) {
716
782
  * technology among the suite's live test cases (the scheduler keys it by technologyType at run time) —
717
783
  * the browser for WEB, the technology itself for API / MAINFRAME / SAP / DESKTOP / DATABASE. A suite
718
784
  * doc has no platform of its own. Mobile needs a device the MCP can't pick, so it is refused. */
719
- function suitePlatform(suite, browser, verb) {
785
+ function suitePlatform(suite, browser, verb, cloud = false) {
720
786
  const code = suite?.code ?? `SU-${suite?.id}`;
721
787
  const rows = (Array.isArray(suite?.testCases) ? suite.testCases : []).filter((r) => r && r.deleted !== true);
722
788
  if (!rows.length)
@@ -728,6 +794,8 @@ function suitePlatform(suite, browser, verb) {
728
794
  return techs.map((t) => {
729
795
  if (t !== 'WEB')
730
796
  return { id: t, name: t, type: 'NONE', technologyType: t };
797
+ if (cloud)
798
+ return cloudBrowserEntry(browser);
731
799
  const b = sqaBrowser(browser);
732
800
  return { id: b, name: b, type: 'NONE', technologyType: 'WEB' };
733
801
  });
@@ -1558,8 +1626,8 @@ export class SimplifyQaAdapter {
1558
1626
  : [];
1559
1627
  }
1560
1628
  /** `GET /pm/auth/me` → `{ userDetails: { id, username, email, … }, userPreference, … }`.
1561
- * Only `userDetails.id` is read: the payload also carries an agent token and the full
1562
- * preference/privilege set, which must never be logged or persisted. */
1629
+ * Only `userDetails.id` is read: the payload also carries an agent token and the full
1630
+ * preference/privilege set, which must never be logged or persisted. */
1563
1631
  async fetchUserIdFromMe() {
1564
1632
  try {
1565
1633
  const raw = await this.http.getJson('/pm/auth/me');
@@ -2175,6 +2243,7 @@ export class SimplifyQaAdapter {
2175
2243
  * (type / state / priority from the project's own default values; dates from the sprint, else the release, else today)
2176
2244
  * and the result says so. */
2177
2245
  async createTask(input) {
2246
+ assertPlannedDates(input.plannedStartDate, input.plannedEndDate);
2178
2247
  const projectId = this.requireProjectId();
2179
2248
  const canon = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
2180
2249
  const name = String(input.name ?? '').trim();
@@ -2410,6 +2479,98 @@ export class SimplifyQaAdapter {
2410
2479
  ...(versionNote ? { versionNote } : {}),
2411
2480
  };
2412
2481
  }
2482
+ /** A value of the defect form's Environment / Type (Execution Type) dropdown. The project's own list wins when it defines one; the form
2483
+ * otherwise offers a fixed list (Development / QA / UAT, Manual / Automation). A value outside it is refused with the valid ones. */
2484
+ async defectChoice(key, want) {
2485
+ const canon = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
2486
+ const fixed = { environment: ['Development', 'QA', 'UAT'], executionType: ['Manual', 'Automation'] };
2487
+ const project = await this.defaultFieldValues(9, key);
2488
+ const values = project.length ? project : fixed[key].map((v) => ({ key: v, value: v }));
2489
+ const hit = values.find((v) => canon(v.key) === canon(want) || canon(v.value) === canon(want));
2490
+ if (!hit) {
2491
+ throw new Error(`"${want}" is not a defect ${key === 'executionType' ? 'type (execution type)' : key} in this project. Valid: ${values.map((v) => v.key).join(', ')}.`);
2492
+ }
2493
+ return hit.key;
2494
+ }
2495
+ /** A planned date of the defect form as the backend takes it (a date); only YYYY-MM-DD is accepted so a typo is not guessed at. */
2496
+ defectDate(label, v) {
2497
+ const day = String(v).trim().slice(0, 10);
2498
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day) || Number.isNaN(new Date(`${day}T00:00:00Z`).getTime())) {
2499
+ throw new Error(`${label} must be a date like 2026-11-20 (got "${v}").`);
2500
+ }
2501
+ return `${day}T00:00:00.000Z`;
2502
+ }
2503
+ /** The form's Feature field: a feature of THIS project, by id, business key (FT-248) or exact name. */
2504
+ async resolveDefectFeature(ref) {
2505
+ const projectId = this.requireProjectId();
2506
+ const raw = String(ref).trim();
2507
+ const attempts = [];
2508
+ if (/^\d+$/.test(raw))
2509
+ attempts.push({ column: 'id', value: Number.parseInt(raw, 10) });
2510
+ for (const c of SimplifyQaAdapter.codeVariants(raw))
2511
+ attempts.push({ column: 'code', value: c });
2512
+ attempts.push({ column: 'name', value: raw });
2513
+ for (const a of attempts) {
2514
+ const res = await this.http.postJson('/pm/feature/search', this.searchBody([{ column: 'projectIds', value: projectId }, { column: a.column, value: a.value }], { startIndex: 0, limit: 5, selectFields: ['id', 'code', 'name'] }));
2515
+ const hit = pickArray(res, 'data', 'content', 'features').find((r) => a.column === 'id' ? String(str(r, 'id', '_id')) === String(a.value) : String(str(r, a.column) ?? '').toLowerCase() === String(a.value).toLowerCase());
2516
+ const id = hit ? Number.parseInt(str(hit, 'id', '_id') ?? '', 10) : NaN;
2517
+ if (Number.isFinite(id))
2518
+ return { id, label: [str(hit, 'code'), str(hit, 'name')].filter(Boolean).join(' ') || String(id) };
2519
+ }
2520
+ throw new Error(`No feature "${ref}" in this project. Pass its id, business key (e.g. FT-248) or exact name.`);
2521
+ }
2522
+ /** The extra form fields of a create / update, checked and turned into the wire fields — before anything is written, so one bad value
2523
+ * refuses the whole call. `clearable` (update): 'none' empties a field. `before` carries the dates already on the defect so that a
2524
+ * new end date is compared with the stored start date and the other way round. */
2525
+ async defectFormFields(input, clearable, before = {}) {
2526
+ const wire = {};
2527
+ const labels = {};
2528
+ const isNone = (v) => clearable && v.trim().toLowerCase() === 'none';
2529
+ for (const key of ['environment', 'executionType']) {
2530
+ const want = input[key];
2531
+ if (want === undefined)
2532
+ continue;
2533
+ if (isNone(want)) {
2534
+ wire[key] = '';
2535
+ labels[key] = 'none';
2536
+ continue;
2537
+ }
2538
+ const v = await this.defectChoice(key, want);
2539
+ wire[key] = v;
2540
+ labels[key] = v;
2541
+ }
2542
+ if (input.featureId !== undefined) {
2543
+ if (isNone(input.featureId)) {
2544
+ wire['featureId'] = null;
2545
+ labels['featureId'] = 'none';
2546
+ }
2547
+ else {
2548
+ const f = await this.resolveDefectFeature(input.featureId);
2549
+ wire['featureId'] = f.id;
2550
+ labels['featureId'] = f.label;
2551
+ }
2552
+ }
2553
+ for (const [key, label] of [['plannedStartDate', 'Planned start date'], ['plannedEndDate', 'Planned end date']]) {
2554
+ const want = input[key];
2555
+ if (want === undefined)
2556
+ continue;
2557
+ if (isNone(want)) {
2558
+ wire[key] = null;
2559
+ labels[key] = 'none';
2560
+ continue;
2561
+ }
2562
+ wire[key] = this.defectDate(label, want);
2563
+ labels[key] = String(wire[key]).slice(0, 10);
2564
+ }
2565
+ const day = (k) => {
2566
+ const v = k in wire ? wire[k] : before[k];
2567
+ return v ? String(v).slice(0, 10) : undefined;
2568
+ };
2569
+ const [start, end] = [day('plannedStartDate'), day('plannedEndDate')];
2570
+ if (start && end && end <= start)
2571
+ throw new Error(`Planned end date (${end}) must be after the planned start date (${start}).`);
2572
+ return { wire, labels };
2573
+ }
2413
2574
  /** Change a defect the way the SimplifyQA defect form does (a partial `PUT /pm/defect/:id` carrying the project and the version it
2414
2575
  * read), then read it back. USER STORY is `userstoryId`; TEST CASE is `selectedTestCase` — entries with the test case's id, code,
2415
2576
  * name and chosen version — which the backend also writes onto the test case's own linked-defects list; that last step swallows its
@@ -2444,6 +2605,16 @@ export class SimplifyQaAdapter {
2444
2605
  if (v !== doc[key])
2445
2606
  change(key, key, v, String(doc[key] ?? '(none)'), v);
2446
2607
  }
2608
+ // Environment, Type (execution type), Feature, planned dates
2609
+ const extra = await this.defectFormFields(patch, true, doc);
2610
+ const FORM_LABELS = { environment: 'environment', executionType: 'type', featureId: 'feature', plannedStartDate: 'planned start date', plannedEndDate: 'planned end date' };
2611
+ for (const [key, to] of Object.entries(extra.wire)) {
2612
+ const dateKey = key === 'plannedStartDate' || key === 'plannedEndDate';
2613
+ const was = dateKey ? String(doc[key] ?? '').slice(0, 10) : String(doc[key] ?? '');
2614
+ const now = dateKey ? String(to ?? '').slice(0, 10) : String(to ?? '');
2615
+ if (was !== now)
2616
+ change(FORM_LABELS[key] ?? key, key, to, was || '(none)', extra.labels[key] ?? now);
2617
+ }
2447
2618
  if (patch.name !== undefined && patch.name.trim() !== name) {
2448
2619
  if (patch.name.trim().length < 3)
2449
2620
  throw new Error('A defect name needs at least 3 characters.');
@@ -2547,41 +2718,48 @@ export class SimplifyQaAdapter {
2547
2718
  warnings.push('SimplifyQA does not remove the defect from the removed test case\'s own linked-defects list when it is unlinked here.');
2548
2719
  }
2549
2720
  }
2550
- if (!shown.length)
2721
+ const wantLinks = patch.linkages ?? [];
2722
+ if (!shown.length && !wantLinks.length)
2551
2723
  return { id: String(defectId), code, name, changes: [], written: false, warnings };
2552
- // save (a stale version is retried once with the fresh one)
2553
- const send = (d) => this.http.putJson(`/pm/defect/${defectId}`, { projectId, updateVersion: typeof d['updateVersion'] === 'number' ? d['updateVersion'] : 0, ...changes });
2554
- try {
2724
+ let nameNow = name;
2725
+ if (shown.length) {
2726
+ // save (a stale version is retried once with the fresh one)
2727
+ const send = (d) => this.http.putJson(`/pm/defect/${defectId}`, { projectId, updateVersion: typeof d['updateVersion'] === 'number' ? d['updateVersion'] : 0, ...changes });
2555
2728
  try {
2556
- await send(doc);
2729
+ try {
2730
+ await send(doc);
2731
+ }
2732
+ catch (e) {
2733
+ if (!/CONCURRENCY/i.test(e instanceof Error ? e.message : String(e)))
2734
+ throw e;
2735
+ await send((await this.readDefectDoc(defectId)) ?? doc);
2736
+ }
2557
2737
  }
2558
2738
  catch (e) {
2559
- if (!/CONCURRENCY/i.test(e instanceof Error ? e.message : String(e)))
2560
- throw e;
2561
- await send((await this.readDefectDoc(defectId)) ?? doc);
2562
- }
2563
- }
2564
- catch (e) {
2565
- const m = e instanceof Error ? e.message : String(e);
2566
- if (/INVALIDTOKEN|Don't Have Privileges|privilege/i.test(m)) {
2567
- throw new Error(`Updating a defect needs the "add_defect" privilege in this project, and the connected user does not have it (${m}).`);
2739
+ const m = e instanceof Error ? e.message : String(e);
2740
+ if (/INVALIDTOKEN|Don't Have Privileges|privilege/i.test(m)) {
2741
+ throw new Error(`Updating a defect needs the "add_defect" privilege in this project, and the connected user does not have it (${m}).`);
2742
+ }
2743
+ throw e;
2568
2744
  }
2569
- throw e;
2570
- }
2571
- // read the defect back and compare
2572
- const after = await this.readDefectDoc(defectId);
2573
- if (!after)
2574
- throw new Error(`${code} was updated but could not be read back.`);
2575
- for (const k of Object.keys(changes)) {
2576
- const want = changes[k];
2577
- const got = after[k];
2578
- const same = k === 'ownerId'
2579
- ? JSON.stringify([...(Array.isArray(got) ? got : [])].map(Number).sort()) === JSON.stringify([...want].sort())
2580
- : k === 'selectedTestCase'
2581
- ? sig(Array.isArray(got) ? got : []) === sig(want)
2582
- : String(got ?? '') === String(want ?? '');
2583
- if (!same)
2584
- throw new Error(`${code}: "${k}" was sent as ${JSON.stringify(want).slice(0, 200)} but reads back as ${JSON.stringify(got).slice(0, 200)}.`);
2745
+ // read the defect back and compare
2746
+ const after = await this.readDefectDoc(defectId);
2747
+ if (!after)
2748
+ throw new Error(`${code} was updated but could not be read back.`);
2749
+ for (const k of Object.keys(changes)) {
2750
+ const want = changes[k];
2751
+ const got = after[k];
2752
+ const same = k === 'ownerId'
2753
+ ? JSON.stringify([...(Array.isArray(got) ? got : [])].map(Number).sort()) === JSON.stringify([...want].sort())
2754
+ : k === 'plannedStartDate' || k === 'plannedEndDate'
2755
+ ? String(got ?? '').slice(0, 10) === String(want ?? '').slice(0, 10)
2756
+ : k === 'selectedTestCase'
2757
+ ? sig(Array.isArray(got) ? got : []) === sig(want)
2758
+ : String(got ?? '') === String(want ?? '');
2759
+ if (!same)
2760
+ throw new Error(`${code}: "${k}" was sent as ${JSON.stringify(want).slice(0, 200)} but reads back as ${JSON.stringify(got).slice(0, 200)}.`);
2761
+ }
2762
+ nameNow = String(after['name'] ?? name);
2585
2763
  }
2586
2764
  // the test case's own linked-defects list is written by the backend with its failures swallowed — check it, repair it, re-check
2587
2765
  for (const t of added) {
@@ -2598,7 +2776,19 @@ export class SimplifyQaAdapter {
2598
2776
  if (!state.ok)
2599
2777
  warnings.push(`${t.label}: the defect is saved with the test case, but the test case's own linked-defects list does not show ${code}.`);
2600
2778
  }
2601
- return { id: String(defectId), code, name: String(after['name'] ?? name), changes: shown, written: true, warnings };
2779
+ // Linkages, saved from the DEFECT's side (each is read back from /pm/linkages inside linkBacklogItem)
2780
+ let linksAdded = 0;
2781
+ for (const l of wantLinks) {
2782
+ const r = await this.linkBacklogItem({ sourceType: 'defect', sourceId: String(defectId), destType: l.destType, destId: l.destId, linkType: l.linkType });
2783
+ const to = `${r.destinationCode ?? l.destId} (${l.linkType})`;
2784
+ if (r.alreadyLinked)
2785
+ warnings.push(`${code} was already linked to ${to} — left as it is.`);
2786
+ else {
2787
+ shown.push({ field: 'linkage', from: '(none)', to });
2788
+ linksAdded++;
2789
+ }
2790
+ }
2791
+ return { id: String(defectId), code, name: nameNow, changes: shown, written: shown.length > linksAdded || linksAdded > 0, warnings };
2602
2792
  }
2603
2793
  // ---------------------------------------------------------------------- Defect create
2604
2794
  /** Log a defect the way Defect Management → Create Defect does (`POST /pm/defect`), then read it back. The backend requires a name,
@@ -2606,6 +2796,7 @@ export class SimplifyQaAdapter {
2606
2796
  * logged from an execution) enforces the project's mandatory custom fields, which it reports in its own words. The User Story and
2607
2797
  * Test Case fields are set as the form stores them, and each test case is checked to list the defect. */
2608
2798
  async createDefect(input) {
2799
+ assertPlannedDates(input.plannedStartDate, input.plannedEndDate);
2609
2800
  const projectId = this.requireProjectId();
2610
2801
  const canon = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
2611
2802
  const name = String(input.name ?? '').trim();
@@ -2684,8 +2875,11 @@ export class SimplifyQaAdapter {
2684
2875
  moduleId = await this.resolveModuleId('Default module').catch(() => undefined);
2685
2876
  if (moduleId !== undefined && !Number.isFinite(moduleId))
2686
2877
  moduleId = undefined;
2878
+ // Environment, Type (execution type), Feature, planned dates — checked now, before anything is created
2879
+ const extra = await this.defectFormFields(input, false);
2687
2880
  const body = {
2688
2881
  projectId, name, state, priority, description: input.description ?? '',
2882
+ ...extra.wire,
2689
2883
  ...(severity ? { severity } : {}), ...(category ? { category } : {}),
2690
2884
  ...(ownerId ? { ownerId } : {}),
2691
2885
  ...(plan.releaseId != null ? { releaseId: plan.releaseId } : {}), ...(plan.iterationId != null ? { iterationId: plan.iterationId } : {}),
@@ -2724,10 +2918,34 @@ export class SimplifyQaAdapter {
2724
2918
  warnings.push(`${t.label}: the defect is saved with the test case, but the test case's own linked-defects list does not show ${defectCode}.`);
2725
2919
  }
2726
2920
  }
2921
+ // the extra form fields as stored (a mismatch is reported, never hidden — the defect exists by now)
2922
+ const fields = [];
2923
+ const FIELD_NAMES = { environment: 'environment', executionType: 'type', featureId: 'feature', plannedStartDate: 'planned start', plannedEndDate: 'planned end' };
2924
+ for (const [key, sent] of Object.entries(extra.wire)) {
2925
+ const dateKey = key === 'plannedStartDate' || key === 'plannedEndDate';
2926
+ const got = dateKey ? String(doc[key] ?? '').slice(0, 10) : String(doc[key] ?? '');
2927
+ const want = dateKey ? String(sent ?? '').slice(0, 10) : String(sent ?? '');
2928
+ if (got === want)
2929
+ fields.push(`${FIELD_NAMES[key] ?? key} ${extra.labels[key] ?? got}`);
2930
+ else
2931
+ warnings.push(`${defectCode}: ${FIELD_NAMES[key] ?? key} was sent as ${want || 'empty'} but reads back as ${got || 'empty'}.`);
2932
+ }
2933
+ // Linkages, saved from the new defect's side; a failed one is reported with its reason while the defect stays logged
2934
+ const linked = [];
2935
+ for (const l of input.linkages ?? []) {
2936
+ try {
2937
+ const r = await this.linkBacklogItem({ sourceType: 'defect', sourceId: String(defectId), destType: l.destType, destId: l.destId, linkType: l.linkType });
2938
+ linked.push(`${r.destinationCode ?? l.destId} (${l.linkType})`);
2939
+ }
2940
+ catch (e) {
2941
+ warnings.push(`${defectCode} was logged, but linking it to ${l.destType} ${l.destId} failed: ${e instanceof Error ? e.message : String(e)}`);
2942
+ }
2943
+ }
2727
2944
  return {
2728
2945
  defectId: String(defectId), defectCode, name, state: String(doc['state'] ?? state ?? ''), priority: String(doc['priority'] ?? priority ?? ''),
2729
2946
  ...(severity ? { severity: String(doc['severity'] ?? severity) } : {}), testCases: tcEntries.map((t) => t.label),
2730
- ...(userstoryId !== undefined ? { storyId: userstoryId } : {}), defaults, warnings,
2947
+ ...(userstoryId !== undefined ? { storyId: userstoryId } : {}),
2948
+ ...(fields.length ? { fields } : {}), ...(linked.length ? { linked } : {}), defaults, warnings,
2731
2949
  };
2732
2950
  }
2733
2951
  // ---------------------------------------------------------------------- Defects from a failed step
@@ -3098,6 +3316,7 @@ export class SimplifyQaAdapter {
3098
3316
  const defaults = await this.getBacklogDefaults(3);
3099
3317
  const state = input.state ?? defaults.state;
3100
3318
  const priority = input.priority ?? defaults.priority;
3319
+ assertPlannedDates(input.plannedStartDate, input.plannedEndDate);
3101
3320
  const body = {
3102
3321
  ...input,
3103
3322
  // SQA userstory expects a singular numeric projectId; fill from the connected project when omitted.
@@ -3111,6 +3330,7 @@ export class SimplifyQaAdapter {
3111
3330
  }
3112
3331
  async updateStory(id, patch) {
3113
3332
  const resolvedId = await this.resolveStoryNumericId(id);
3333
+ assertPlannedDates(patch.plannedStartDate, patch.plannedEndDate);
3114
3334
  // The backend's update controller runs its privilege check with `req.body.projectId`; a partial
3115
3335
  // patch that omits it makes that call throw (HTTP 500), which is why a story edit has to carry the
3116
3336
  // project. Default to the connected project — the story being edited belongs to it.
@@ -3123,6 +3343,8 @@ export class SimplifyQaAdapter {
3123
3343
  * `userstoryObj` + `filename1`), so this re-saves the item with its existing fields + attachments
3124
3344
  * and the new file. Reads the attachments back and returns them. */
3125
3345
  async addAttachment(input) {
3346
+ if (input.entityType === 'defect')
3347
+ return this.addDefectAttachment(input);
3126
3348
  const spec = BACKLOG_ATTACHMENT_SPECS[input.entityType];
3127
3349
  const numeric = input.entityType === 'epic' ? await this.resolveEpicNumericId(input.itemId)
3128
3350
  : input.entityType === 'feature' ? await this.resolveFeatureNumericId(input.itemId)
@@ -3156,7 +3378,66 @@ export class SimplifyQaAdapter {
3156
3378
  }
3157
3379
  return { ...(doc['id'] !== undefined ? { id: String(doc['id']) } : {}), name: input.fileName, attachments };
3158
3380
  }
3159
- /** Attachments of an epic / feature / user story (`/pm/attachment/:id/:parentType`). */
3381
+ /** Attach a file to a DEFECT: the defect's own update with the file as the multipart `filename1` part and ONLY the project and version
3382
+ * as fields — a defect update takes just what changes, and its existing attachments are left alone. Read back from `/pm/attachment/:id/DE`. */
3383
+ async addDefectAttachment(input) {
3384
+ if (!this.http.putMultipartWithFiles)
3385
+ throw new Error('This connection cannot upload attachments.');
3386
+ const projectId = this.requireProjectId();
3387
+ let doc = await this.findDefectDoc(input.itemId);
3388
+ const id = String(doc['id']);
3389
+ const send = (d) => this.http.putMultipartWithFiles(`/pm/defect/${id}`, 'defectObj', { projectId, updateVersion: typeof d['updateVersion'] === 'number' ? d['updateVersion'] : 0 }, [{ partName: 'filename1', fileName: input.fileName, ...(input.contentType ? { contentType: input.contentType } : {}), data: input.data }]);
3390
+ try {
3391
+ try {
3392
+ await send(doc);
3393
+ }
3394
+ catch (e) {
3395
+ if (!/CONCURRENCY/i.test(e instanceof Error ? e.message : String(e)))
3396
+ throw e;
3397
+ doc = (await this.readDefectDoc(Number(id))) ?? doc;
3398
+ await send(doc);
3399
+ }
3400
+ }
3401
+ catch (e) {
3402
+ const m = e instanceof Error ? e.message : String(e);
3403
+ if (/INVALIDTOKEN|Don't Have Privileges|privilege/i.test(m)) {
3404
+ throw new Error(`Attaching a file to a defect needs the "add_defect" privilege in this project, and the connected user does not have it (${m}).`);
3405
+ }
3406
+ throw e;
3407
+ }
3408
+ const attachments = await this.entityAttachments('defect', id);
3409
+ if (!attachments.some((a) => String(a['original_name'] ?? a['name'] ?? '') === input.fileName)) {
3410
+ throw new Error(`Uploaded "${input.fileName}" to defect ${input.itemId}, but reading the attachments back did not find it. ` +
3411
+ `Attachments now: ${attachments.map((a) => String(a['original_name'] ?? a['name'] ?? '')).join(', ') || '(none)'}`);
3412
+ }
3413
+ return { id, name: input.fileName, attachments };
3414
+ }
3415
+ /** Remove one attachment from a DEFECT: the update's `attachments` names the rows to delete — the row with `deleted:true` and the project
3416
+ * (the backend scopes the delete by it). Read back to confirm it is gone. */
3417
+ async removeDefectAttachment(input) {
3418
+ if (!this.http.putMultipart)
3419
+ throw new Error('This connection cannot update attachments.');
3420
+ const projectId = this.requireProjectId();
3421
+ const doc = await this.findDefectDoc(input.itemId);
3422
+ const id = String(doc['id']);
3423
+ const rows = await this.entityAttachments('defect', id);
3424
+ const wanted = input.attachment.trim();
3425
+ const match = rows.find((a) => String(a['id']) === wanted || String(a['original_name'] ?? a['name'] ?? '') === wanted);
3426
+ if (!match) {
3427
+ throw new Error(`No attachment "${input.attachment}" on defect ${input.itemId}. Attachments: ${rows.map((a) => String(a['original_name'] ?? a['name'] ?? a['id'])).join(', ') || '(none)'}`);
3428
+ }
3429
+ const row = { ...match, deleted: true, projectId };
3430
+ delete row['file'];
3431
+ await this.http.putMultipart(`/pm/defect/${id}`, 'defectObj', {
3432
+ projectId, updateVersion: typeof doc['updateVersion'] === 'number' ? doc['updateVersion'] : 0, attachments: [row],
3433
+ });
3434
+ const attachments = await this.entityAttachments('defect', id);
3435
+ if (attachments.some((a) => String(a['id']) === String(match['id']))) {
3436
+ throw new Error(`Tried to delete "${input.attachment}" but it is still listed after the save.`);
3437
+ }
3438
+ return { removed: true, attachments };
3439
+ }
3440
+ /** Attachments of an epic / feature / user story / defect (`/pm/attachment/:id/:parentType`). */
3160
3441
  async entityAttachments(entityType, id) {
3161
3442
  const spec = BACKLOG_ATTACHMENT_SPECS[entityType];
3162
3443
  const projectId = this.requireProjectId();
@@ -3173,7 +3454,7 @@ export class SimplifyQaAdapter {
3173
3454
  if (!this.http.getBinary)
3174
3455
  throw new Error('This connection cannot download files.');
3175
3456
  const base = (this.cfg.baseUrl ?? '').replace(/\/+$/, '');
3176
- const rows = await this.entityAttachments(input.entityType, input.itemId);
3457
+ const rows = await this.entityAttachments(input.entityType, input.entityType === 'defect' ? String((await this.findDefectDoc(input.itemId))['id']) : input.itemId);
3177
3458
  const nameOf = (a) => String(a['original_name'] ?? a['name'] ?? '').trim();
3178
3459
  const sizeOf = (a) => {
3179
3460
  const n = typeof a['size'] === 'number' ? a['size'] : Number(a['size'] ?? a['fileSize']);
@@ -3251,6 +3532,8 @@ export class SimplifyQaAdapter {
3251
3532
  /** Remove one attachment (by id or stored/original name) from an epic / feature / user story.
3252
3533
  * Mirrors the UI: mark the row `deleted:true` and re-save the item (multipart, no file part). */
3253
3534
  async removeAttachment(input) {
3535
+ if (input.entityType === 'defect')
3536
+ return this.removeDefectAttachment(input);
3254
3537
  const spec = BACKLOG_ATTACHMENT_SPECS[input.entityType];
3255
3538
  const numeric = input.entityType === 'epic' ? await this.resolveEpicNumericId(input.itemId)
3256
3539
  : input.entityType === 'feature' ? await this.resolveFeatureNumericId(input.itemId)
@@ -3329,6 +3612,7 @@ export class SimplifyQaAdapter {
3329
3612
  return toEpic(doc && typeof doc === 'object' ? doc : {});
3330
3613
  }
3331
3614
  async createEpic(input) {
3615
+ assertPlannedDates(input.plannedStartDate, input.plannedEndDate);
3332
3616
  const defaults = await this.getBacklogDefaults(1);
3333
3617
  const state = input.state ?? defaults.state;
3334
3618
  const body = {
@@ -3341,6 +3625,7 @@ export class SimplifyQaAdapter {
3341
3625
  return toSavedRef(raw, true);
3342
3626
  }
3343
3627
  async updateEpic(id, patch) {
3628
+ assertPlannedDates(patch.plannedStartDate, patch.plannedEndDate);
3344
3629
  const resolvedId = await this.resolveEpicNumericId(id);
3345
3630
  const raw = await this.http.putJson(`/pm/epic/${resolvedId}`, patch);
3346
3631
  return toSavedRef(raw ?? { id: resolvedId }, false);
@@ -3397,6 +3682,7 @@ export class SimplifyQaAdapter {
3397
3682
  return toFeature(doc && typeof doc === 'object' ? doc : {});
3398
3683
  }
3399
3684
  async createFeature(input) {
3685
+ assertPlannedDates(input.plannedStartDate, input.plannedEndDate);
3400
3686
  const defaults = await this.getBacklogDefaults(2);
3401
3687
  const state = input.state ?? defaults.state;
3402
3688
  const priority = input.priority ?? defaults.priority;
@@ -3411,6 +3697,7 @@ export class SimplifyQaAdapter {
3411
3697
  return toSavedRef(raw, true);
3412
3698
  }
3413
3699
  async updateFeature(id, patch) {
3700
+ assertPlannedDates(patch.plannedStartDate, patch.plannedEndDate);
3414
3701
  const resolvedId = await this.resolveFeatureNumericId(id);
3415
3702
  const raw = await this.http.putJson(`/pm/feature/${resolvedId}`, patch);
3416
3703
  return toSavedRef(raw ?? { id: resolvedId }, false);
@@ -3964,6 +4251,62 @@ export class SimplifyQaAdapter {
3964
4251
  }
3965
4252
  return { id, code, name: String(after.name ?? row.name ?? ''), stateBefore, stateAfter: String(after.state ?? ''), changed: changes, warnings, written: true };
3966
4253
  }
4254
+ /** Everything that still uses a release / sprint, found by the MCP itself (nothing is written). A lookup that FAILS
4255
+ * stops the whole preview — "could not check" must never read as "nothing uses it". */
4256
+ async releaseOrSprintDeletePreview(kind, ref) {
4257
+ const row = await this.findPm(kind, ref);
4258
+ const n = Number(row.id);
4259
+ const column = kind === 'release' ? 'releaseId' : 'iterationId';
4260
+ const where = async (label, path) => {
4261
+ try {
4262
+ const raw = await this.http.postJson(path, this.searchBody([{ column, value: n }], { selectFields: ['id', 'code', 'name'], limit: 100 }));
4263
+ return pickArray(raw, 'data', 'content').map(toRef);
4264
+ }
4265
+ catch (e) {
4266
+ throw new Error(`Could not check the ${label} that use ${row.code ?? `#${n}`} (${e instanceof Error ? e.message : String(e)}). Nothing was deleted.`);
4267
+ }
4268
+ };
4269
+ const [stories, defects, tasks, executionPlans, pipelines, schedules] = await Promise.all([
4270
+ where('stories', '/pm/userstory/search'), where('defects', '/pm/defect/search'), where('tasks', '/pm/task/search'),
4271
+ where('execution plans', '/tm/executionplan/search'), where('pipelines', '/pl/pipelines/search'), where('schedules', '/sh/scheduler/search'),
4272
+ ]);
4273
+ const sprints = kind === 'release'
4274
+ ? (await this.pmRows('sprint')).filter((s) => String(s?.releaseId) === String(n)).map(toRef)
4275
+ : [];
4276
+ // A release can belong to several projects, and deleting it removes it from all of them.
4277
+ const projectId = this.requireProjectId();
4278
+ const otherIds = kind === 'release' && Array.isArray(row.projectIds)
4279
+ ? row.projectIds.map(Number).filter((p) => Number.isFinite(p) && String(p) !== String(projectId))
4280
+ : [];
4281
+ const otherProjects = otherIds.length ? await this.refsByIds('/pm/project/search', otherIds) : [];
4282
+ return {
4283
+ kind,
4284
+ record: { ...toRef(row), ...(row.state ? { state: String(row.state) } : {}) },
4285
+ blockers: { sprints, stories, defects, tasks, executionPlans, pipelines, schedules, otherProjects },
4286
+ callerIsAdmin: await this.isCallerAdmin(),
4287
+ };
4288
+ }
4289
+ /** Delete a release / sprint (`PATCH /pm/release|sprint { id:[n] }` — admin only) — only when nothing uses it, and proven by
4290
+ * re-reading: SimplifyQA answers 201 whether or not the row was found. */
4291
+ async deleteReleaseOrSprint(kind, ref) {
4292
+ const { record, blockers } = await this.releaseOrSprintDeletePreview(kind, ref);
4293
+ if (Object.values(blockers).some((b) => b.length))
4294
+ throw new PmBlockedError(kind, record, blockers);
4295
+ try {
4296
+ await this.http.patchJson(`/pm/${kind}`, { id: [Number(record.id)] });
4297
+ }
4298
+ catch (e) {
4299
+ const m = e instanceof Error ? e.message : String(e);
4300
+ if (/INVALIDUSERTYPE|admin privileges|not.*authori[sz]ed|forbidden|\b40[13]\b/i.test(m)) {
4301
+ throw new Error(`Deleting a ${kind} needs an admin user in SimplifyQA, and the connected user is not one (${m}). Nothing was deleted.`);
4302
+ }
4303
+ throw e;
4304
+ }
4305
+ const still = (await this.pmRows(kind)).some((r) => String(r.id) === record.id);
4306
+ if (still)
4307
+ throw new Error(`SimplifyQA answered OK but ${record.code ?? record.id} is still listed — nothing was deleted.`);
4308
+ return record;
4309
+ }
3967
4310
  /** Create a release or a sprint the way Releases → Create does (`POST /pm/release` / `/pm/sprint`), then read it back.
3968
4311
  * The backend requires a state and at least one owner, so the state defaults to the project's first one (New) and the owner to
3969
4312
  * the connected user. A sprint needs an existing release of this project. */
@@ -4302,19 +4645,54 @@ export class SimplifyQaAdapter {
4302
4645
  jiraIssueKey: '',
4303
4646
  jiraLinkId: '',
4304
4647
  };
4305
- const sourceRaw = asDoc(await this.http.getJson(`${specs[input.sourceType].path}/${source.id}`));
4306
- const existing = Array.isArray(sourceRaw['linkedIssues']) ? sourceRaw['linkedIssues'] : [];
4307
- const merged = [
4308
- ...existing.filter((e) => !(Number(e['destinationId']) === dest.id && String(e['linkTypeKey']) === chosen.key)),
4309
- entry,
4310
- ];
4311
- const version = typeof sourceRaw['updateVersion'] === 'number' ? sourceRaw['updateVersion'] : 0;
4312
- if (input.sourceType === 'epic')
4313
- await this.updateEpic(String(source.id), { linkedIssues: merged, updateVersion: version });
4314
- else if (input.sourceType === 'feature')
4315
- await this.updateFeature(String(source.id), { linkedIssues: merged, updateVersion: version });
4316
- else
4317
- await this.updateStory(String(source.id), { linkedIssues: merged });
4648
+ const readLinks = async () => {
4649
+ const rawLinks = await this.http.getJson(`/pm/linkages/${source.id}/${specs[input.sourceType].parentType}?projectId=${projectId}`);
4650
+ return (Array.isArray(rawLinks) ? rawLinks : pickArray(rawLinks, 'data', 'content', 'linkages'));
4651
+ };
4652
+ if (input.sourceType === 'defect') {
4653
+ // A defect's save ADDS the rows that carry no id and leaves the others alone, and its document does not echo its links — so only the
4654
+ // new row is sent, and only when this exact link (same item, same type) is not already there.
4655
+ const present = await readLinks();
4656
+ if (present.some((l) => Number(l['destinationId']) === dest.id && String(l['linkTypeKey']) === chosen.key)) {
4657
+ return { linkTypeKey: chosen.key, ...(dest.code ? { destinationCode: dest.code } : {}), linkedIssues: present, alreadyLinked: true };
4658
+ }
4659
+ const sendLink = async () => {
4660
+ const d = await this.readDefectDoc(source.id);
4661
+ return this.http.putJson(`/pm/defect/${source.id}`, { projectId, updateVersion: typeof d?.['updateVersion'] === 'number' ? d['updateVersion'] : 0, linkedIssues: [entry] });
4662
+ };
4663
+ try {
4664
+ try {
4665
+ await sendLink();
4666
+ }
4667
+ catch (e) {
4668
+ if (!/CONCURRENCY/i.test(e instanceof Error ? e.message : String(e)))
4669
+ throw e;
4670
+ await sendLink();
4671
+ }
4672
+ }
4673
+ catch (e) {
4674
+ const m = e instanceof Error ? e.message : String(e);
4675
+ if (/INVALIDTOKEN|Don't Have Privileges|privilege/i.test(m)) {
4676
+ throw new Error(`Linking from a defect needs the "add_defect" privilege in this project, and the connected user does not have it (${m}).`);
4677
+ }
4678
+ throw e;
4679
+ }
4680
+ }
4681
+ else {
4682
+ const sourceRaw = asDoc(await this.http.getJson(`${specs[input.sourceType].path}/${source.id}`));
4683
+ const existing = Array.isArray(sourceRaw['linkedIssues']) ? sourceRaw['linkedIssues'] : [];
4684
+ const merged = [
4685
+ ...existing.filter((e) => !(Number(e['destinationId']) === dest.id && String(e['linkTypeKey']) === chosen.key)),
4686
+ entry,
4687
+ ];
4688
+ const version = typeof sourceRaw['updateVersion'] === 'number' ? sourceRaw['updateVersion'] : 0;
4689
+ if (input.sourceType === 'epic')
4690
+ await this.updateEpic(String(source.id), { linkedIssues: merged, updateVersion: version });
4691
+ else if (input.sourceType === 'feature')
4692
+ await this.updateFeature(String(source.id), { linkedIssues: merged, updateVersion: version });
4693
+ else
4694
+ await this.updateStory(String(source.id), { linkedIssues: merged });
4695
+ }
4318
4696
  // Confirm from the linkages sub-resource (the item document does not echo the array).
4319
4697
  const rawLinks = await this.http.getJson(`/pm/linkages/${source.id}/${specs[input.sourceType].parentType}?projectId=${projectId}`);
4320
4698
  const links = (Array.isArray(rawLinks) ? rawLinks : pickArray(rawLinks, 'data', 'content', 'linkages'));
@@ -4455,11 +4833,29 @@ export class SimplifyQaAdapter {
4455
4833
  * failed step only when this is on AND the suite / execution plan has autoDefectLog set — the UI
4456
4834
  * refuses the suite/plan toggle while it is off. `undefined` = could not be read (no access): callers
4457
4835
  * must then not block. */
4836
+ /** What a CLOUD run's browser question offers: the UI's cloud picker (headless only). */
4837
+ cloudBrowserOptions() {
4838
+ return [...CLOUD_BROWSER_NAMES];
4839
+ }
4458
4840
  async autoDefectLogStatus() {
4459
4841
  try {
4460
4842
  const project = await this.getProjectById(String(this.requireProjectId()));
4461
- const flag = project?.['generalSettings']?.['defectManagement']?.['autoDefectFlag'];
4462
- return { adminEnabled: flag === true };
4843
+ const dm = project?.['generalSettings']?.['defectManagement'];
4844
+ // the backend builds the defect from this config (owner, priority, state); without them the defect is not created
4845
+ const cfg = dm?.['configAutologgedDefect'] ?? {};
4846
+ const missing = [['assignee', cfg['assigneeId']], ['priority', cfg['priority']], ['state', cfg['state'] ?? cfg['status']]]
4847
+ .filter(([, v]) => v === undefined || v === null || v === '').map(([k]) => String(k));
4848
+ return { adminEnabled: dm?.['autoDefectFlag'] === true, configMissing: missing };
4849
+ }
4850
+ catch {
4851
+ return undefined;
4852
+ }
4853
+ }
4854
+ /** The suite's / execution plan's own Auto Defect Logging flag (what its Settings panel shows), or undefined when it cannot be read. */
4855
+ async autoDefectLogOf(kind, id) {
4856
+ try {
4857
+ const raw = kind === 'suite' ? await this.readOwnSuite(id) : await this.readOwnPlan(id);
4858
+ return raw['autoDefectLog'] === true;
4463
4859
  }
4464
4860
  catch {
4465
4861
  return undefined;
@@ -4775,6 +5171,9 @@ export class SimplifyQaAdapter {
4775
5171
  * multipart with the assembled `testcaseObj`. */
4776
5172
  async createTestCase(tc) {
4777
5173
  const projectId = this.requireProjectId();
5174
+ // A blank placeholder row (the editor seeds one for a NEW test case) is never a step: drop it so
5175
+ // the save can't store a phantom step that doubles the count (DE-2320).
5176
+ tc = withoutBlankSteps(tc);
4778
5177
  await this.pinFunctionCalls(tc);
4779
5178
  await this.resolveFunctionTechnologies(tc);
4780
5179
  const moduleId = await this.resolveModuleId(tc.folderOrModule);
@@ -4798,6 +5197,7 @@ export class SimplifyQaAdapter {
4798
5197
  /** Same shape as create, but with `tcfnObj.id` set. */
4799
5198
  async updateTestCase(id, tc) {
4800
5199
  const projectId = this.requireProjectId();
5200
+ tc = withoutBlankSteps(tc);
4801
5201
  await this.pinFunctionCalls(tc);
4802
5202
  await this.resolveFunctionTechnologies(tc);
4803
5203
  const moduleId = await this.resolveModuleId(tc.folderOrModule);
@@ -4851,6 +5251,40 @@ export class SimplifyQaAdapter {
4851
5251
  // lookup failed — save proceeds without delete markers
4852
5252
  }
4853
5253
  }
5254
+ /**
5255
+ * Remove the blank placeholder step rows a saved test case may carry (DE-2320). The recorder
5256
+ * window's own Save is the one save path the MCP cannot build: the editor pre-seeds a new test
5257
+ * case with an empty row, and that row can be stored, so a 1-step recording shows 2 steps.
5258
+ * Deleting the stored blank rows afterwards makes the test case match what was recorded.
5259
+ * Nothing is touched when the test case has no blanks, and a test case made ONLY of blanks is
5260
+ * left alone (there would be nothing left to save).
5261
+ */
5262
+ async dropEmptySteps(tcId) {
5263
+ const raw = await this.fetchRawTestcase(tcId);
5264
+ const current = await this.fetchStepsCollection(tcId, raw);
5265
+ const live = current.filter((r) => r?.deleted !== true);
5266
+ const blanks = live.filter((r) => isBlankStep(r));
5267
+ if (!blanks.length || blanks.length === live.length) {
5268
+ return { removed: 0, removedSeqs: [], stepCount: live.length };
5269
+ }
5270
+ const ids = new Set(blanks.map((r) => str(r, 'id', '_id')).filter((v) => !!v));
5271
+ if (!ids.size)
5272
+ return { removed: 0, removedSeqs: [], stepCount: live.length };
5273
+ const tc = await this.getTestCase(tcId);
5274
+ const kept = (tc.steps ?? []).filter((s) => !(s.sourceId && ids.has(s.sourceId)));
5275
+ if (!kept.length || kept.length === (tc.steps ?? []).length) {
5276
+ return { removed: 0, removedSeqs: [], stepCount: live.length };
5277
+ }
5278
+ tc.steps = kept;
5279
+ await this.updateTestCase(tcId, tc);
5280
+ const after = (await this.fetchStepsCollection(tcId, await this.fetchRawTestcase(tcId)))
5281
+ .filter((r) => r?.deleted !== true);
5282
+ return {
5283
+ removed: Math.max(0, live.length - after.length),
5284
+ removedSeqs: blanks.map((r) => Number(r?.seq ?? 0)).filter((n) => n > 0),
5285
+ stepCount: after.length,
5286
+ };
5287
+ }
4854
5288
  /** Snapshot the CURRENT server state of a testcase under a NEW version name — same TC id,
4855
5289
  * new `tcfn_version` row with cloned steps. Backed by `PUT /tm/testcase` with
4856
5290
  * `operation:"SAVENEWVERSION"` (see tcfn.service.js:115/242/355 for the branches). The steps
@@ -4872,7 +5306,7 @@ export class SimplifyQaAdapter {
4872
5306
  // tc_save (objects/parameters resolved); only the version stub + operation differ — exactly what
4873
5307
  // the SQA UI's "Save as new version" dialog sends (edited steps + operation SAVENEWVERSION).
4874
5308
  if (opts.tc) {
4875
- const tc = opts.tc;
5309
+ const tc = withoutBlankSteps(opts.tc);
4876
5310
  // tdCopy clones the SOURCE version's iterations. A caller that just says "copy the test data"
4877
5311
  // (no sourceVersionId) must still get it — otherwise verData has no selVersionId and the new
4878
5312
  // version's iteration is created EMPTY. Default to the TC's current version.
@@ -6236,6 +6670,29 @@ export class SimplifyQaAdapter {
6236
6670
  }
6237
6671
  return undefined;
6238
6672
  }
6673
+ /** Every action row of the active project, full documents (for a backup/verify of the Action
6674
+ * catalogue before an AI "sync actions" run, which SimplifyQA applies server-side). */
6675
+ async listAllActionsFull() {
6676
+ const projectId = this.requireProjectId();
6677
+ const raw = await this.http.postJson('/tm/action/search', {
6678
+ searchFields: [{ column: 'deleted', value: false }, { column: 'projectId', value: { $in: [0, projectId] } }],
6679
+ startIndex: 0,
6680
+ limit: 100000,
6681
+ selectFields: ['id', 'code', 'name', 'disname', 'uniqueId', 'type', 'groupName', 'objectRequired',
6682
+ 'deprecated', 'projectId', 'objectTemplate', 'parameters', 'returnType', 'description'],
6683
+ });
6684
+ return pickArray(raw, 'data', 'content', 'actions').filter((r) => !!r && typeof r === 'object');
6685
+ }
6686
+ /** Re-create one action from a backup snapshot (the row's own shape, minus its ids/timestamps). */
6687
+ async createActionFromBackup(row) {
6688
+ const projectId = this.requireProjectId();
6689
+ const body = { ...row, projectId: Number(projectId) };
6690
+ for (const k of ['id', '_id', '__v', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy', 'deleted'])
6691
+ delete body[k];
6692
+ const raw = await this.http.postJson('/tm/action', body);
6693
+ const doc = raw?.data ?? raw;
6694
+ return { id: String(doc?.id ?? doc?._id ?? '') };
6695
+ }
6239
6696
  actionCatalog() {
6240
6697
  if (this.actionCatalogCache)
6241
6698
  return this.actionCatalogCache;
@@ -6639,6 +7096,10 @@ export class SimplifyQaAdapter {
6639
7096
  // The catalog can miss a project's newer custom actions, so look the id / name / display name up
6640
7097
  // directly with a targeted search (never GET /tm/action/:id — that route reads the id as a project id).
6641
7098
  let fallbackDiag = '';
7099
+ // An EXISTING step whose action still cannot be found (a custom method from another catalogue, a
7100
+ // row the search is not allowed to read) must round-trip untouched instead of failing the whole
7101
+ // edit: keep the action id it was saved with. Only a NEW step is refused when it cannot resolve.
7102
+ let preserveAction = false;
6642
7103
  if (!meta) {
6643
7104
  try {
6644
7105
  meta = await this.findActionLive(name);
@@ -6653,12 +7114,16 @@ export class SimplifyQaAdapter {
6653
7114
  if (meta.displayName)
6654
7115
  catalog.set(`dis::${meta.displayName.toLowerCase()}`, meta);
6655
7116
  }
7117
+ else if (isNumericId && s.sourceId) {
7118
+ meta = { id: Number.parseInt(name, 10), objectRequired: false };
7119
+ preserveAction = true;
7120
+ }
6656
7121
  }
6657
7122
  if (!meta) {
6658
7123
  throw new Error(`Automation step ${i + 1}: the action "${name}" was not found in the action list for technology ${tech} (project ${projectId}). Check the action id, method name or display name.${fallbackDiag} [catalog: ${this.actionCatalogFetchDiag}]`);
6659
7124
  }
6660
- let objectId = null;
6661
- if (meta.objectRequired) {
7125
+ let objectId = preserveAction ? undefined : null;
7126
+ if (!preserveAction && meta.objectRequired) {
6662
7127
  // Resolution ladder (first match wins):
6663
7128
  // 1. objectRef.id set → use directly (round-trip OR LLM referencing a known object)
6664
7129
  // 2. sourceId set but no objectRef.id → preserve DB value (existing step, backend may
@@ -6944,9 +7409,19 @@ export class SimplifyQaAdapter {
6944
7409
  const tcNum = numericId(String(op.tcId));
6945
7410
  switch (op.op) {
6946
7411
  case 'add': {
6947
- const already = members.some((m) => String(m['testcaseId']) === tcNum);
6948
- if (!already)
6949
- members.push(await this.buildSuiteEntryFromTestcase(tcNum));
7412
+ // The same test case may legitimately appear once PER VERSION — dedupe on (tc, version),
7413
+ // never on the tc alone, or asking for v2.0 after v1.0 silently keeps v1.0.
7414
+ const wantsVersion = !!(op.versionId || op.version);
7415
+ if (!wantsVersion && members.some((m) => String(m['testcaseId']) === tcNum))
7416
+ break;
7417
+ const entry = await this.buildSuiteEntryFromTestcase(tcNum, {
7418
+ ...(op.versionId ? { versionId: op.versionId } : {}),
7419
+ ...(op.version ? { version: op.version } : {}),
7420
+ });
7421
+ const dup = members.some((m) => String(m['testcaseId']) === tcNum
7422
+ && String(m['versionId'] ?? '') === String(entry['versionId'] ?? ''));
7423
+ if (!dup)
7424
+ members.push(entry);
6950
7425
  break;
6951
7426
  }
6952
7427
  case 'remove': {
@@ -7051,7 +7526,8 @@ export class SimplifyQaAdapter {
7051
7526
  const raw = await this.readOwnSuite(id);
7052
7527
  const payload = {
7053
7528
  id: raw['id'], suiteType: raw['suiteType'], projectId: raw['projectId'],
7054
- autoReExecTriggerOn: raw['autoReExecTriggerOn'], autoReExecCount: raw['autoReExecCount'],
7529
+ // the settings validator requires both; a suite saved without them would otherwise fail on any settings change
7530
+ autoReExecTriggerOn: raw['autoReExecTriggerOn'] ?? 'AFTER_SUITE', autoReExecCount: raw['autoReExecCount'] ?? 0,
7055
7531
  };
7056
7532
  for (const k of SUITE_SETTING_KEYS)
7057
7533
  if (settings[k] !== undefined)
@@ -7185,7 +7661,12 @@ export class SimplifyQaAdapter {
7185
7661
  const candidates = [];
7186
7662
  for (const tcId of input.tcIds ?? []) {
7187
7663
  const raw = await this.readOwnTestcase(tcId);
7188
- const v = testcaseVersion(raw);
7664
+ const v = pickTestcaseVersion(raw, input.versionId, input.version);
7665
+ candidates.push({ raw, ...v, platform: entryPlatform(raw.executionPlatform), source: { sourceType: 'testcase', sourceId: 0 } });
7666
+ }
7667
+ for (const spec of input.testCases ?? []) {
7668
+ const raw = await this.readOwnTestcase(spec.tcId);
7669
+ const v = pickTestcaseVersion(raw, spec.versionId, spec.version);
7189
7670
  candidates.push({ raw, ...v, platform: entryPlatform(raw.executionPlatform), source: { sourceType: 'testcase', sourceId: 0 } });
7190
7671
  }
7191
7672
  for (const suiteId of input.suiteIds ?? []) {
@@ -7206,18 +7687,30 @@ export class SimplifyQaAdapter {
7206
7687
  }
7207
7688
  const existing = await this.listPlanEntries(Number(plan['id']));
7208
7689
  let seq = existing.reduce((m, e) => Math.max(m, Number(e?.seq) || 0), 0);
7209
- const seen = new Set(existing.map((e) => `${Number(e?.testcaseId)}|${e?.expAssignedTo ?? null}`));
7690
+ // Dedupe on (test case, VERSION, assignee): a plan may legitimately hold v1.0 and v2.0 of one TC.
7691
+ // An older entry that stores no version at all is treated as "this test case is already in" (we
7692
+ // cannot prove which version, so adding another would risk an invisible duplicate).
7693
+ const seenExact = new Set(existing
7694
+ .filter((e) => e?.tcVersionId)
7695
+ .map((e) => `${Number(e?.testcaseId)}|${String(e.tcVersionId)}|${e?.expAssignedTo ?? null}`));
7696
+ const seenAnyVersion = new Set(existing
7697
+ .filter((e) => !e?.tcVersionId)
7698
+ .map((e) => `${Number(e?.testcaseId)}|${e?.expAssignedTo ?? null}`));
7210
7699
  const added = [];
7211
7700
  const skipped = [];
7212
7701
  const rows = [];
7213
7702
  for (const c of candidates) {
7214
7703
  const code = str(c.raw, 'code') ?? `TC-${c.raw.id}`;
7215
- const key = `${Number(c.raw.id)}|${assignee}`;
7216
- if (seen.has(key)) {
7704
+ const key = `${Number(c.raw.id)}|${String(c.versionId ?? '')}|${assignee}`;
7705
+ if (seenAnyVersion.has(`${Number(c.raw.id)}|${assignee}`)) {
7217
7706
  skipped.push({ code, reason: 'already in the plan' });
7218
7707
  continue;
7219
7708
  }
7220
- seen.add(key);
7709
+ if (seenExact.has(key)) {
7710
+ skipped.push({ code, reason: `already in the plan (${c.versionName || c.versionId})` });
7711
+ continue;
7712
+ }
7713
+ seenExact.add(key);
7221
7714
  const tcDesc = str(c.raw, 'description');
7222
7715
  rows.push({
7223
7716
  testcaseId: Number(c.raw.id), code, projectId, moduleId: Number(c.raw.moduleId),
@@ -7280,77 +7773,154 @@ export class SimplifyQaAdapter {
7280
7773
  const doc = raw?.data ?? raw;
7281
7774
  return doc && typeof doc === 'object' && doc.id !== undefined ? doc : null;
7282
7775
  }
7283
- /** Configure the plan's STACK canvas with N stacks and distribute its automation test cases across
7284
- * them — the same document the UI's Stack Setup saves (`POST/PUT /tm/executionFlow`, flowType
7285
- * 'STACK'). Round-robin by default; the backend divides the saved stacks at run time. */
7776
+ /** Configure the plan's STACK canvas — N stacks (or one described per stack: local / remote / cloud, its browser, its machine,
7777
+ * its test cases) with the plan's automation test cases spread over them — the same document the UI's Stack Setup saves
7778
+ * (`POST/PUT /tm/executionFlow`, flowType 'STACK'). Round-robin unless test cases are named; `append` adds stacks to the
7779
+ * saved setup. The backend divides the saved stacks at run time. */
7286
7780
  async configurePlanStacks(planId, opts) {
7287
- const count = Math.trunc(opts.count);
7288
- if (!Number.isFinite(count) || count < 1)
7289
- throw new Error('stacks must be at least 1.');
7290
7781
  const plan = await this.readOwnPlan(planId, { writable: true });
7291
7782
  const projectId = this.requireProjectId();
7292
- const mode = (opts.mode ?? 'CLOUD').toUpperCase();
7783
+ const label = String(plan['code'] ?? planId);
7293
7784
  const entries = (await this.listPlanEntries(Number(plan['id'])))
7294
7785
  .filter((e) => String(e.executionType ?? '').toUpperCase() === 'AUTOMATION' && String(e.status ?? '').toUpperCase() !== 'BLOCKED');
7295
7786
  if (!entries.length)
7296
- throw new Error(`${plan['code'] ?? planId} has no AUTOMATION test cases to distribute.`);
7297
- const browserKey = (opts.browser ?? 'chrome').toLowerCase();
7298
- const browser = { name: browserKey.charAt(0).toUpperCase() + browserKey.slice(1), key: browserKey, type: 'NONE' };
7299
- const existing = await this.getPlanStacks(planId);
7300
- const stackDefs = Array.from({ length: count }, (_, i) => ({
7301
- id: randomUUID(), name: `Stack ${i + 1}`, position: null,
7302
- mode, agentId: null,
7303
- executionPlatform: { LOCAL: {}, REMOTE: {}, CLOUD: mode === 'CLOUD' ? { browser } : {} },
7304
- items: [],
7305
- }));
7306
- entries.forEach((e, i) => {
7307
- const stack = stackDefs[i % count];
7787
+ throw new Error(`${label} has no AUTOMATION test cases to distribute.`);
7788
+ const cases = entries.map((e) => {
7308
7789
  const tech = String(e.tcType ?? 'WEB').toUpperCase();
7309
7790
  const p = e.executionPlatform ?? {};
7310
- const platform = PLAN_SPECIAL_TECH.includes(tech)
7311
- ? [{ name: tech, id: tech, technologyType: tech, type: 'NONE' }]
7312
- : tech === 'WEB'
7313
- ? [{ name: browser.name, id: browser.key, technologyType: 'WEB', type: 'NONE' }]
7314
- : [{ name: p.name, id: p.id, technologyType: p.technologyType ?? tech, type: p.type ?? 'NONE',
7315
- ...(p.cloudDeviceType ? { cloudDeviceType: p.cloudDeviceType } : {}), ...(p.osVersion ? { osVersion: p.osVersion } : {}) }];
7316
- const item = {
7317
- id: e.testcaseId, versionId: e.tcVersionId, stepId: e.stepId, type: e.type ?? 'TC',
7318
- technologyType: tech, name: e.tcName ?? '', description: '', versionName: e.versionName ?? '',
7319
- seq: e.seq ?? 0, stepCount: -1, code: e.code ?? '', prerequisite: '',
7320
- projectId, projectName: '', moduleId: e.moduleId ?? null, moduleName: '',
7321
- userstoryId: e.userstoryId ?? null, userstoryName: '',
7322
- sourceType: e.sourceType ?? null, sourceId: e.sourceId ?? null,
7323
- assignTo: e.expAssignedTo ?? null, assignDate: e.expAssignedDate ?? null, assigneeName: '',
7324
- createdByName: '', createdBy: null,
7325
- executionType: 'AUTOMATION', status: 'NOTEXECUTED', executionId: null, executionOS: null,
7326
- iterationsSelected: [], platform,
7791
+ return {
7792
+ ref: { code: e.code ?? `TC-${e.testcaseId}`, id: String(e.testcaseId) },
7793
+ key: `${e.testcaseId}|${e.stepId ?? ''}`, tech,
7794
+ nativePlatform: { name: p.name, id: p.id, technologyType: p.technologyType ?? tech, type: p.type ?? 'NONE',
7795
+ ...(p.cloudDeviceType ? { cloudDeviceType: p.cloudDeviceType } : {}), ...(p.osVersion ? { osVersion: p.osVersion } : {}) },
7796
+ item: (platform) => ({
7797
+ id: e.testcaseId, versionId: e.tcVersionId, stepId: e.stepId, type: e.type ?? 'TC',
7798
+ technologyType: tech, name: e.tcName ?? '', description: '', versionName: e.versionName ?? '',
7799
+ seq: e.seq ?? 0, stepCount: -1, code: e.code ?? '', prerequisite: '',
7800
+ projectId, projectName: '', moduleId: e.moduleId ?? null, moduleName: '',
7801
+ userstoryId: e.userstoryId ?? null, userstoryName: '',
7802
+ sourceType: e.sourceType ?? null, sourceId: e.sourceId ?? null,
7803
+ assignTo: e.expAssignedTo ?? null, assignDate: e.expAssignedDate ?? null, assigneeName: '',
7804
+ createdByName: '', createdBy: null,
7805
+ executionType: 'AUTOMATION', status: 'NOTEXECUTED', executionId: null, executionOS: null,
7806
+ iterationsSelected: [], platform,
7807
+ }),
7327
7808
  };
7328
- stack.items.push(item);
7329
7809
  });
7810
+ return this.saveStackFlow('EP', Number(plan['id']), label, projectId, cases, opts, await this.getPlanStacks(planId));
7811
+ }
7812
+ /** Save a STACK canvas (plan or suite) the way the UI's Save does and read it back. Per stack: its platform (LOCAL stamps this
7813
+ * machine's agent, REMOTE the chosen machine, CLOUD none) and the browser its WEB test cases run in; test cases spread
7814
+ * round-robin, or as named. `append` keeps the saved stacks and adds new ones. Refuses what the UI refuses (an empty stack). */
7815
+ async saveStackFlow(parentType, parentId, label, projectId, cases, opts, existing) {
7816
+ const append = opts.append === true;
7817
+ const savedStacks = Array.isArray(existing?.['stacks']) ? existing['stacks'] : [];
7818
+ if (append && !savedStacks.length)
7819
+ throw new Error(`${label} has no saved stack setup to add to — run stack_setup without append first.`);
7820
+ const fresh = resolveStacks({ count: opts.count, mode: opts.mode, browser: opts.browser, stackConfigs: opts.stackConfigs });
7821
+ // REMOTE stacks name a machine — resolve it to the registry row id the UI stores, refusing one that does not exist.
7822
+ const needsRemote = fresh.some((s) => s.mode === 'REMOTE');
7823
+ const machines = needsRemote ? await this.listLocalAgents() : [];
7824
+ for (const s of fresh) {
7825
+ if (s.mode !== 'REMOTE')
7826
+ continue;
7827
+ const want = String(s.agentId).trim().toLowerCase();
7828
+ const hit = machines.find((m) => m.id.toLowerCase() === want) ?? machines.find((m) => (m.name ?? '').toLowerCase() === want);
7829
+ if (!hit) {
7830
+ throw new Error(`No machine "${s.agentId}" to run a REMOTE stack on. Registered: ${machines.map((m) => `${m.name ?? m.id} (${m.id})`).join(', ') || '(none)'}.`);
7831
+ }
7832
+ s.agentId = hit.id;
7833
+ }
7834
+ // LOCAL stacks carry the saving user's own agent (the UI stamps `_us.agentId`); without a registered agent it stays empty.
7835
+ let localAgent = null;
7836
+ if (fresh.some((s) => s.mode === 'LOCAL'))
7837
+ localAgent = await this.resolveLocalAgentId().catch(() => null);
7838
+ const keyOf = (it) => `${it?.id ?? it?.testcaseId}|${it?.stepId ?? ''}`;
7839
+ const current = append
7840
+ ? savedStacks.map((s) => (Array.isArray(s?.items) ? s.items : [])
7841
+ .map((it) => cases.findIndex((c) => c.key === keyOf(it))).filter((i) => i >= 0))
7842
+ : [];
7843
+ const { buckets, unassigned } = distributeCases(cases.map((c) => c.ref), fresh, current);
7844
+ const empty = firstEmptyStack(buckets);
7845
+ if (empty !== undefined) {
7846
+ throw new Error(`${label} has ${cases.length} test case(s) — it cannot fill ${buckets.length} stacks (stack ${empty} would have none, and every stack needs at least one). Use fewer stacks or name test cases for it.`);
7847
+ }
7848
+ const cfgs = savedStacks.map((s, i) => ({
7849
+ id: String(s.id), name: String(s.name ?? `Stack ${i + 1}`), position: s.position ?? null,
7850
+ mode: String(s.mode ?? 'LOCAL').toUpperCase(), agentId: s.agentId ?? null,
7851
+ executionPlatform: { LOCAL: {}, REMOTE: {}, CLOUD: {}, ...(s.executionPlatform ?? {}) },
7852
+ ...(s.createdBy !== undefined ? { createdBy: s.createdBy } : {}),
7853
+ }));
7854
+ if (!append)
7855
+ cfgs.length = 0;
7856
+ const taken = new Set(cfgs.map((c) => c.name.toLowerCase()));
7857
+ fresh.forEach((s) => {
7858
+ let n = cfgs.length + 1;
7859
+ while (taken.has(`stack ${n}`))
7860
+ n++;
7861
+ const name = `Stack ${n}`;
7862
+ taken.add(name.toLowerCase());
7863
+ cfgs.push({
7864
+ id: randomUUID(), name, position: null, mode: s.mode,
7865
+ agentId: s.mode === 'REMOTE' ? s.agentId : s.mode === 'LOCAL' ? localAgent : null,
7866
+ executionPlatform: { LOCAL: {}, REMOTE: {}, CLOUD: {}, [s.mode]: { browser: { id: s.browser.key, key: s.browser.key, name: s.browser.key, technologyType: 'WEB', type: 'NONE' } } },
7867
+ });
7868
+ });
7869
+ const stackDefs = cfgs.map((c, n) => {
7870
+ const mine = (buckets[n] ?? []).map((i) => cases[i]);
7871
+ const bucket = c.executionPlatform[c.mode] ?? {};
7872
+ const savedKey = bucket.browser?.key ?? bucket.browser?.id;
7873
+ const browser = savedKey ? { key: String(savedKey), name: String(savedKey), technologyType: 'WEB', type: 'NONE' } : pickBrowser(undefined, c.mode);
7874
+ // like the UI, a browser pick only stays where the stack has a WEB test case
7875
+ const hasWeb = mine.some((k) => k.tech === 'WEB');
7876
+ for (const m of ['LOCAL', 'REMOTE', 'CLOUD'])
7877
+ if (!hasWeb && c.executionPlatform[m]?.browser)
7878
+ delete c.executionPlatform[m].browser;
7879
+ if (hasWeb && !c.executionPlatform[c.mode].browser)
7880
+ c.executionPlatform[c.mode] = { ...c.executionPlatform[c.mode], browser: { id: browser.key, key: browser.key, name: browser.key, technologyType: 'WEB', type: 'NONE' } };
7881
+ return {
7882
+ ...c,
7883
+ items: mine.map((k) => k.item(PLAN_SPECIAL_TECH.includes(k.tech)
7884
+ ? [{ name: k.tech, id: k.tech, technologyType: k.tech, type: 'NONE' }]
7885
+ : k.tech === 'WEB' ? [{ name: browser.key, id: browser.key, technologyType: 'WEB', type: 'NONE' }] : [k.nativePlatform])),
7886
+ };
7887
+ });
7888
+ const viewMode = existing?.['viewMode'] === 'canvas' ? 'canvas' : 'grid'; // the validator takes only 'grid' | 'canvas'
7330
7889
  const payload = {
7331
7890
  ...(existing?.['id'] ? { id: existing['id'] } : {}),
7332
- parentId: Number(plan['id']), parentType: 'EP', flowType: 'STACK', projectId,
7333
- viewMode: false, stacks: stackDefs.map((s) => ({ ...s, position: s.position ?? null })),
7334
- connections: [], canvasConfig: { startNodePosition: { x: 0, y: 0 } },
7891
+ parentId, parentType, flowType: 'STACK', projectId, viewMode, stacks: stackDefs,
7892
+ connections: append && Array.isArray(existing?.['connections']) ? existing['connections'] : [],
7893
+ canvasConfig: existing?.['canvasConfig'] ?? { startNodePosition: { x: 300, y: 50 } },
7335
7894
  };
7336
7895
  if (existing?.['id'])
7337
7896
  await this.http.putJson('/tm/executionFlow', payload);
7338
7897
  else
7339
7898
  await this.http.postJson('/tm/executionFlow', payload);
7340
7899
  // Read it back — the canvas shows the saved document, and a run divides by it.
7341
- const after = await this.getPlanStacks(planId);
7342
- const savedStacks = Array.isArray(after?.['stacks']) ? after['stacks'] : [];
7343
- if (savedStacks.length !== count) {
7344
- throw new Error(`Saved ${count} stack(s) but the plan's STACK drawing reads back ${savedStacks.length}.`);
7900
+ const after = parentType === 'EP' ? await this.getPlanStacks(String(parentId)) : await this.getSuiteStacks(String(parentId));
7901
+ const saved = Array.isArray(after?.['stacks']) ? after['stacks'] : [];
7902
+ if (saved.length !== stackDefs.length)
7903
+ throw new Error(`Saved ${stackDefs.length} stack(s) but ${label}'s STACK drawing reads back ${saved.length}.`);
7904
+ const wrong = saved.findIndex((s, n) => (Array.isArray(s?.items) ? s.items.length : 0) !== (buckets[n]?.length ?? 0));
7905
+ if (wrong >= 0)
7906
+ throw new Error(`${label}'s stack ${wrong + 1} reads back with a different number of test cases than was saved.`);
7907
+ const usesCloud = saved.some((s) => String(s?.mode).toUpperCase() === 'CLOUD');
7908
+ const cloudAvailable = usesCloud ? (await this.listCloudRunners().catch(() => [])).some((r) => r.online) : undefined;
7909
+ const notes = [];
7910
+ if (fresh.some((s) => s.mode === 'LOCAL') && !localAgent) {
7911
+ notes.push('No local agent is registered on this machine, so the LOCAL stack(s) carry no agent yet — open the Stack Setup and save it from the machine that will run them.');
7345
7912
  }
7346
- const cloudAvailable = mode === 'CLOUD' ? (await this.listCloudRunners().catch(() => [])).some((r) => r.online) : undefined;
7347
7913
  return {
7348
7914
  created: !existing,
7349
7915
  ...(cloudAvailable !== undefined ? { cloudAvailable } : {}),
7350
- stacks: savedStacks.map((s, i) => ({
7351
- id: String(s.id ?? ''), name: String(s.name ?? `Stack ${i + 1}`), mode: String(s.mode ?? mode),
7916
+ stacks: saved.map((s, n) => ({
7917
+ id: String(s.id ?? ''), name: String(s.name ?? `Stack ${n + 1}`), mode: String(s.mode ?? ''),
7918
+ ...(s.agentId ? { agentId: String(s.agentId) } : {}),
7919
+ ...(s.executionPlatform?.[String(s.mode ?? '')]?.browser?.name ? { browser: String(s.executionPlatform[String(s.mode)].browser.name) } : {}),
7352
7920
  codes: (Array.isArray(s.items) ? s.items : []).map((it) => String(it.code ?? `TC-${it.id}`)),
7353
7921
  })),
7922
+ ...(unassigned.length ? { unassigned: unassigned.map((i) => cases[i].ref.code) } : {}),
7923
+ ...(notes.length ? { notes } : {}),
7354
7924
  };
7355
7925
  }
7356
7926
  async startExecutionPlanRun(planId, opts) {
@@ -7383,6 +7953,7 @@ export class SimplifyQaAdapter {
7383
7953
  // (NONE when cloud isn't set up) — it is NOT gated on a cloud machine unless a stack really is CLOUD.
7384
7954
  let agentId;
7385
7955
  let cloudType = 'NONE';
7956
+ let stackCount = 0;
7386
7957
  const requireLocalAgent = async () => {
7387
7958
  const probe = await this.probeLocalAgentDetailed();
7388
7959
  if (!probe.up) {
@@ -7413,6 +7984,7 @@ export class SimplifyQaAdapter {
7413
7984
  const stacks = Array.isArray(flow?.['stacks']) ? flow['stacks'] : [];
7414
7985
  if (!stacks.length)
7415
7986
  throw new Error(`${code} has no saved stack setup — configure it first (action:"stack_setup").`);
7987
+ stackCount = stacks.length;
7416
7988
  // The backend runs only the stacks holding a test case assigned to the user who starts the run, and silently does
7417
7989
  // nothing for anyone else — refuse that here instead of reporting a run that executes nothing.
7418
7990
  const me = await this.ensureUserId();
@@ -7421,6 +7993,10 @@ export class SimplifyQaAdapter {
7421
7993
  throw new Error(`None of ${code}'s stack test cases are assigned to you, so a stack run started by you would execute nothing. ` +
7422
7994
  'Run it as the assignee, or assign the test cases to yourself.');
7423
7995
  }
7996
+ const noMachine = mine.filter((s) => String(s?.mode).toUpperCase() === 'REMOTE' && !s?.agentId);
7997
+ if (noMachine.length) {
7998
+ throw new Error(`${code} has REMOTE stack(s) with no machine chosen (${noMachine.map((s) => s?.name ?? s?.id).join(', ')}) — pick one with stack_setup (stackConfigs: [{ mode:"remote", agentId }]).`);
7999
+ }
7424
8000
  const cloudStacks = mine.filter((s) => String(s?.mode).toUpperCase() === 'CLOUD');
7425
8001
  if (cloudStacks.length) {
7426
8002
  const online = await onlineCloud();
@@ -7446,6 +8022,7 @@ export class SimplifyQaAdapter {
7446
8022
  const shellItems = Array.isArray(shell.executionItems) ? shell.executionItems : [];
7447
8023
  const items = [];
7448
8024
  const started = [];
8025
+ const cloudNeedsBrowser = [];
7449
8026
  const skipped = [];
7450
8027
  for (const e of runnable) {
7451
8028
  const item = shellItems.find((it) => it.id == e.testcaseId && it.assignTo == e.expAssignedTo
@@ -7457,16 +8034,33 @@ export class SimplifyQaAdapter {
7457
8034
  }
7458
8035
  const tech = String(item.technologyType ?? e.tcType ?? '');
7459
8036
  const p = e.executionPlatform ?? {};
7460
- const platform = PLAN_SPECIAL_TECH.includes(tech)
8037
+ let cloudWeb;
8038
+ if (runMode === 'cloud' && tech.toUpperCase() === 'WEB') {
8039
+ // the cloud picker is Chrome / Firefox / Edge Headless: a browser the caller names applies to every web test case
8040
+ if (opts.browser)
8041
+ cloudWeb = [cloudBrowserEntry(opts.browser)];
8042
+ else if (/_HEADLESS$/i.test(String(p.id ?? '')))
8043
+ cloudWeb = [{ name: p.name, id: p.id, technologyType: 'WEB', type: p.type ?? 'NONE' }];
8044
+ else {
8045
+ cloudNeedsBrowser.push(c);
8046
+ continue;
8047
+ }
8048
+ }
8049
+ const platform = cloudWeb ?? (PLAN_SPECIAL_TECH.includes(tech)
7461
8050
  ? [{ name: tech, id: tech, technologyType: tech, type: 'NONE' }]
7462
8051
  : [{ name: p.name, id: p.id, technologyType: p.technologyType, type: p.type,
7463
- ...(p.cloudDeviceType ? { cloudDeviceType: p.cloudDeviceType } : {}), ...(p.osVersion ? { osVersion: p.osVersion } : {}) }];
8052
+ ...(p.cloudDeviceType ? { cloudDeviceType: p.cloudDeviceType } : {}), ...(p.osVersion ? { osVersion: p.osVersion } : {}) }]);
7464
8053
  items.push({ ...item, name: e.tcName, isSelected: true, platform, configuration: {}, startTime: new Date().toISOString() });
7465
8054
  started.push(c);
7466
8055
  }
8056
+ if (cloudNeedsBrowser.length) {
8057
+ throw new Error(`ASK the user which browser to run ${code} in on the cloud — ${CLOUD_BROWSER_NAMES.join(', ')} (cloud runs are headless) — then call again with \`browser\` set. ` +
8058
+ `It has no saved cloud browser for: ${cloudNeedsBrowser.join(', ')}.`);
8059
+ }
7467
8060
  if (!items.length)
7468
8061
  throw new Error(`${code} can't run: none of its test cases are part of the plan's last execution.`);
7469
8062
  const shellCode = String(shell.code ?? `#${shell.id}`);
8063
+ const priorStatus = String(shell.status ?? 'NOTEXECUTED');
7470
8064
  await this.http.putJson('/exec/execution/status', { id: Number(shell.id), projectId, status: 'INPROGRESS' });
7471
8065
  const body = { ...shell };
7472
8066
  for (const k of PLAN_RUN_DROP_KEYS)
@@ -7481,6 +8075,9 @@ export class SimplifyQaAdapter {
7481
8075
  globalConfiguration: {
7482
8076
  TERMINATE_ON_FAIL: plan['terminateOnFailure'] ?? false, NEW_BROWSER_SESSION: plan['newBrowserSession'] ?? false,
7483
8077
  RE_EXECUTION_COUNT: plan['autoReExecCount'] ?? 0, RE_EXECUTION_TYPE: plan['autoReExecTriggerOn'] ?? 'AFTER_TESTCASE',
8078
+ // The Execute dialog's "containers" setting: one per stack for a stack run, else the plan's own limit.
8079
+ MINIMUM_CONTAINER_COUNT: plan['minimumContainerCount'] ?? 0,
8080
+ MAXIMUM_CONTAINER_COUNT: plan['maximumContainerCount'] ?? (runMode === 'stack' ? Math.max(1, stackCount) : 5),
7484
8081
  },
7485
8082
  executionItems: runMode === 'stack' ? [] : items,
7486
8083
  });
@@ -7489,12 +8086,26 @@ export class SimplifyQaAdapter {
7489
8086
  created = await this.http.postJson('/exec/execution', body);
7490
8087
  }
7491
8088
  catch (e) {
7492
- throw new Error(`Starting ${code} failed after its execution ${shellCode} was marked INPROGRESS in SimplifyQA: ` +
7493
- `${e instanceof Error ? e.message : String(e)}. It may show as in progress until it is reset there.`);
8089
+ // The shell was flipped to INPROGRESS above; a refused start must put it back or the plan looks
8090
+ // permanently in progress and every later run reports "no execution id".
8091
+ try {
8092
+ await this.http.putJson('/exec/execution/status', { id: Number(shell.id), projectId, status: priorStatus });
8093
+ }
8094
+ catch { /* best effort — the original error is the one to report */ }
8095
+ throw new Error(`Starting ${code} did not run: ${e instanceof Error ? e.message : String(e)} ` +
8096
+ `(${shellCode} was restored to ${priorStatus}).`);
7494
8097
  }
7495
8098
  const runId = str(created?.data ?? created, 'id');
7496
- if (!runId)
7497
- throw new Error(`Starting ${code}: SimplifyQA returned no execution id (${shellCode} is marked INPROGRESS).`);
8099
+ if (!runId) {
8100
+ // Same rollback as a refused POST: never leave the plan's shell stuck INPROGRESS.
8101
+ try {
8102
+ await this.http.putJson('/exec/execution/status', { id: Number(shell.id), projectId, status: priorStatus });
8103
+ }
8104
+ catch { /* best effort */ }
8105
+ const msg = str(created, 'message') ?? str(created?.error, 'message');
8106
+ throw new Error(`Starting ${code} did not run: SimplifyQA returned no execution id` +
8107
+ `${msg ? ` — ${msg}` : ''} (${shellCode} was restored to ${priorStatus}).`);
8108
+ }
7498
8109
  return { runId, started, skipped: [...skipped] };
7499
8110
  }
7500
8111
  /** Every live entry of a plan (the search has no privilege check; scoped to the active project). */
@@ -7548,33 +8159,21 @@ export class SimplifyQaAdapter {
7548
8159
  const doc = raw?.data ?? raw;
7549
8160
  return doc && typeof doc === 'object' && doc.id !== undefined ? doc : null;
7550
8161
  }
7551
- /** Configure the suite's STACK canvas with N stacks and spread its test cases across them — the same
7552
- * document the suite's Stack canvas saves (`POST/PUT /tm/executionFlow`, parentType 'SU', flowType
7553
- * 'STACK'). Round-robin; the backend divides the saved stacks at run time. */
8162
+ /** Configure the suite's STACK canvas — N stacks (or one described per stack) with its test cases spread over them — the same
8163
+ * document the suite's Stack canvas saves (`POST/PUT /tm/executionFlow`, parentType 'SU', flowType 'STACK'). Same options as
8164
+ * a plan's: per-stack platform / browser / machine, named test cases, `append`. */
7554
8165
  async configureSuiteStacks(suiteId, opts) {
7555
- const count = Math.trunc(opts.count);
7556
- if (!Number.isFinite(count) || count < 1)
7557
- throw new Error('stacks must be at least 1.');
7558
8166
  const suite = await this.readOwnSuite(suiteId);
7559
8167
  const label = String(suite['code'] ?? `SU-${suite['id']}`);
7560
8168
  if (String(suite['suiteType'] ?? 'AUTOMATION').toUpperCase() === 'MANUAL') {
7561
8169
  throw new Error(`${label} is a manual suite — Stack execution is for automation suites.`);
7562
8170
  }
7563
8171
  const projectId = this.requireProjectId();
7564
- const mode = (opts.mode ?? 'CLOUD').toUpperCase();
7565
8172
  const rows = (Array.isArray(suite['testCases']) ? suite['testCases'] : []).filter((r) => r?.deleted !== true && r?.stepId);
7566
8173
  if (!rows.length)
7567
8174
  throw new Error(`${label} has no saved test cases to distribute.`);
7568
- const browserKey = (opts.browser ?? 'chrome').toLowerCase();
7569
- const browser = { name: browserKey.charAt(0).toUpperCase() + browserKey.slice(1), key: browserKey, type: 'NONE' };
7570
- const existing = await this.getSuiteStacks(suiteId);
7571
- const stackDefs = Array.from({ length: count }, (_, i) => ({
7572
- id: randomUUID(), name: `Stack ${i + 1}`, position: null,
7573
- mode, agentId: null,
7574
- executionPlatform: { LOCAL: {}, REMOTE: {}, CLOUD: mode === 'CLOUD' ? { browser } : {} },
7575
- items: [],
7576
- }));
7577
- let i = 0;
8175
+ const cases = [];
8176
+ let seq = 0;
7578
8177
  for (const row of rows) {
7579
8178
  const rawTc = await this.fetchRawTestcase(String(row.testcaseId)).catch(() => undefined);
7580
8179
  if (!rawTc || !Object.keys(rawTc).length)
@@ -7582,53 +8181,29 @@ export class SimplifyQaAdapter {
7582
8181
  const tech = String(str(rawTc, 'tcType') ?? 'WEB').toUpperCase();
7583
8182
  const versions = Array.isArray(rawTc?.versions) ? rawTc.versions : [];
7584
8183
  const ver = versions.find((v) => str(v, 'id', '_id') === String(row.versionId));
7585
- const p = row?.executionPlatform?.[mode] ?? {};
7586
- const platform = PLAN_SPECIAL_TECH.includes(tech)
7587
- ? [{ name: tech, id: tech, technologyType: tech, type: 'NONE' }]
7588
- : tech === 'WEB'
7589
- ? [{ name: browser.name, id: browser.key, technologyType: 'WEB', type: 'NONE' }]
7590
- : [{ name: p.name, id: p.id, technologyType: p.technologyType ?? tech, type: p.type ?? 'NONE',
7591
- ...(p.cloudDeviceType ? { cloudDeviceType: p.cloudDeviceType } : {}), ...(p.osVersion ? { osVersion: p.osVersion } : {}) }];
7592
- stackDefs[i % count].items.push({
7593
- id: Number(rawTc.id ?? row.testcaseId), versionId: row.versionId, stepId: row.stepId, type: 'TC',
7594
- technologyType: tech, name: str(rawTc, 'name', 'title') ?? '', description: '', versionName: str(ver, 'name') ?? '',
7595
- seq: row.seq ?? i + 1, stepCount: -1, code: str(rawTc, 'code') ?? '', prerequisite: '',
7596
- projectId, projectName: '', moduleId: rawTc.moduleId ?? null, moduleName: '',
7597
- userstoryId: rawTc.userstoryId ?? null, userstoryName: '',
7598
- sourceType: null, sourceId: null, assignTo: null, assignDate: null, assigneeName: '',
7599
- createdByName: '', createdBy: null,
7600
- executionType: 'AUTOMATION', status: 'NOTEXECUTED', executionId: null, executionOS: null,
7601
- iterationsSelected: [], platform,
8184
+ const p = row?.executionPlatform?.LOCAL ?? row?.executionPlatform?.CLOUD ?? row?.executionPlatform ?? {};
8185
+ const n = ++seq;
8186
+ cases.push({
8187
+ ref: { code: str(rawTc, 'code') ?? `TC-${rawTc.id ?? row.testcaseId}`, id: String(rawTc.id ?? row.testcaseId) },
8188
+ key: `${rawTc.id ?? row.testcaseId}|${row.stepId ?? ''}`, tech,
8189
+ nativePlatform: { name: p.name, id: p.id, technologyType: p.technologyType ?? tech, type: p.type ?? 'NONE',
8190
+ ...(p.cloudDeviceType ? { cloudDeviceType: p.cloudDeviceType } : {}), ...(p.osVersion ? { osVersion: p.osVersion } : {}) },
8191
+ item: (platform) => ({
8192
+ id: Number(rawTc.id ?? row.testcaseId), versionId: row.versionId, stepId: row.stepId, type: 'TC',
8193
+ technologyType: tech, name: str(rawTc, 'name', 'title') ?? '', description: '', versionName: str(ver, 'name') ?? '',
8194
+ seq: row.seq ?? n, stepCount: -1, code: str(rawTc, 'code') ?? '', prerequisite: '',
8195
+ projectId, projectName: '', moduleId: rawTc.moduleId ?? null, moduleName: '',
8196
+ userstoryId: rawTc.userstoryId ?? null, userstoryName: '',
8197
+ sourceType: null, sourceId: null, assignTo: null, assignDate: null, assigneeName: '',
8198
+ createdByName: '', createdBy: null,
8199
+ executionType: 'AUTOMATION', status: 'NOTEXECUTED', executionId: null, executionOS: null,
8200
+ iterationsSelected: [], platform,
8201
+ }),
7602
8202
  });
7603
- i++;
7604
8203
  }
7605
- if (!i)
8204
+ if (!cases.length)
7606
8205
  throw new Error(`None of ${label}'s test cases could be read, so there is nothing to distribute.`);
7607
- if (count > i)
7608
- throw new Error(`${label} has ${i} test case(s) — it cannot fill ${count} stacks (every stack needs at least one).`);
7609
- const payload = {
7610
- ...(existing?.['id'] ? { id: existing['id'] } : {}),
7611
- parentId: Number(suite['id']), parentType: 'SU', flowType: 'STACK', projectId,
7612
- viewMode: false, stacks: stackDefs,
7613
- connections: [], canvasConfig: { startNodePosition: { x: 0, y: 0 } },
7614
- };
7615
- if (existing?.['id'])
7616
- await this.http.putJson('/tm/executionFlow', payload);
7617
- else
7618
- await this.http.postJson('/tm/executionFlow', payload);
7619
- const after = await this.getSuiteStacks(suiteId);
7620
- const saved = Array.isArray(after?.['stacks']) ? after['stacks'] : [];
7621
- if (saved.length !== count)
7622
- throw new Error(`Saved ${count} stack(s) but ${label}'s STACK drawing reads back ${saved.length}.`);
7623
- const cloudAvailable = mode === 'CLOUD' ? (await this.listCloudRunners().catch(() => [])).some((r) => r.online) : undefined;
7624
- return {
7625
- created: !existing,
7626
- ...(cloudAvailable !== undefined ? { cloudAvailable } : {}),
7627
- stacks: saved.map((s, n) => ({
7628
- id: String(s.id ?? ''), name: String(s.name ?? `Stack ${n + 1}`), mode: String(s.mode ?? mode),
7629
- codes: (Array.isArray(s.items) ? s.items : []).map((it) => String(it.code ?? `TC-${it.id}`)),
7630
- })),
7631
- };
8206
+ return this.saveStackFlow('SU', Number(suite['id']), label, projectId, cases, opts, await this.getSuiteStacks(suiteId));
7632
8207
  }
7633
8208
  /** What a suite STACK run needs, checked before anything is created: a saved canvas with no empty stack,
7634
8209
  * a cloud machine only when a stack is CLOUD, and this machine's agent only when a stack is LOCAL. */
@@ -7654,6 +8229,10 @@ export class SimplifyQaAdapter {
7654
8229
  }
7655
8230
  cloudType = online[0]?.cloudType ?? 'VM';
7656
8231
  }
8232
+ const noMachine = stacks.filter((s) => String(s?.mode).toUpperCase() === 'REMOTE' && !s?.agentId);
8233
+ if (noMachine.length) {
8234
+ throw new Error(`${label} has REMOTE stack(s) with no machine chosen (${noMachine.map((s) => s?.name ?? s?.id).join(', ')}) — pick one with stack_setup (stackConfigs: [{ mode:"remote", agentId }]).`);
8235
+ }
7657
8236
  let agentId = null;
7658
8237
  if (stacks.some((s) => (String(s?.mode ?? 'LOCAL')).toUpperCase() === 'LOCAL')) {
7659
8238
  const probe = await this.probeLocalAgentDetailed();
@@ -7746,7 +8325,7 @@ export class SimplifyQaAdapter {
7746
8325
  if (target.suiteId) {
7747
8326
  schedulerType = 'SU';
7748
8327
  parent = await this.readOwnSuite(target.suiteId);
7749
- platForm = suitePlatform(parent, opts.browser, 'schedule it');
8328
+ platForm = suitePlatform(parent, opts.browser, 'schedule it', opts.mode === 'cloud');
7750
8329
  }
7751
8330
  else if (target.tcId) {
7752
8331
  schedulerType = 'TC';
@@ -7756,7 +8335,7 @@ export class SimplifyQaAdapter {
7756
8335
  if (Number(parent['projectId']) !== projectId)
7757
8336
  throw new Error(`${parent['code'] ?? `TC-${parent['id']}`} is not in project ${projectId}.`);
7758
8337
  parentVersionId = testcaseVersion(parent, true).versionId || undefined;
7759
- platForm = tcPlatform(parent, opts.browser);
8338
+ platForm = tcPlatform(parent, opts.browser, opts.mode === 'cloud');
7760
8339
  }
7761
8340
  else {
7762
8341
  throw new Error('Nothing to schedule: give a test case or a suite.');
@@ -7897,6 +8476,8 @@ export class SimplifyQaAdapter {
7897
8476
  // WHAT it runs: a test case or a suite — the same schedule, re-pointed (the Scheduler form's type + target), with the platform and
7898
8477
  // version that kind of schedule carries, as createSchedule builds them.
7899
8478
  const notes = [];
8479
+ // a cloud schedule's browsers are the cloud ones (headless); the mode being changed in the same call counts
8480
+ const scheduleIsCloud = String(changes.mode ?? doc['executionMode'] ?? '').toLowerCase() === 'cloud';
7900
8481
  let target;
7901
8482
  if (changes.tcId !== undefined || changes.suiteId !== undefined) {
7902
8483
  if (changes.tcId !== undefined && changes.suiteId !== undefined)
@@ -7905,7 +8486,7 @@ export class SimplifyQaAdapter {
7905
8486
  const wasType = String(doc['schedulerType'] ?? '');
7906
8487
  if (changes.suiteId !== undefined) {
7907
8488
  const suite = await this.readOwnSuite(changes.suiteId);
7908
- const platForm = suitePlatform(suite, changes.browser, 'schedule it');
8489
+ const platForm = suitePlatform(suite, changes.browser, 'schedule it', scheduleIsCloud);
7909
8490
  Object.assign(patch, { schedulerType: 'SU', parentId: Number(suite['id']), platForm, parentVersionId: undefined });
7910
8491
  target = { type: 'SU', id: Number(suite['id']), code: String(suite['code'] ?? `SU-${suite['id']}`) };
7911
8492
  }
@@ -7919,7 +8500,7 @@ export class SimplifyQaAdapter {
7919
8500
  const webEntry = (Array.isArray(doc['platForm']) ? doc['platForm'] : []).find((p) => String(p?.technologyType ?? '').toUpperCase() === 'WEB');
7920
8501
  const keepBrowser = changes.browser ?? (webEntry?.id ? String(webEntry.id) : undefined);
7921
8502
  Object.assign(patch, {
7922
- schedulerType: 'TC', parentId: Number(tc['id']), platForm: tcPlatform(tc, keepBrowser),
8503
+ schedulerType: 'TC', parentId: Number(tc['id']), platForm: tcPlatform(tc, keepBrowser, scheduleIsCloud),
7923
8504
  parentVersionId: testcaseVersion(tc, true).versionId || undefined,
7924
8505
  });
7925
8506
  target = { type: 'TC', id: Number(tc['id']), code: String(tc['code'] ?? `TC-${tc['id']}`) };
@@ -7950,8 +8531,9 @@ export class SimplifyQaAdapter {
7950
8531
  throw new Error('A suite schedule needs a release (the Scheduler marks Release as required for a suite) — pass releaseId (id, code or name).');
7951
8532
  }
7952
8533
  if (changes.browser && doc['schedulerType'] === 'TC' && finalType === 'TC' && !('platForm' in patch)) {
7953
- const b = sqaBrowser(changes.browser);
7954
- patch['platForm'] = [{ id: b, name: b, type: 'NONE', technologyType: 'WEB' }];
8534
+ patch['platForm'] = scheduleIsCloud
8535
+ ? [cloudBrowserEntry(changes.browser)]
8536
+ : (() => { const b = sqaBrowser(changes.browser); return [{ id: b, name: b, type: 'NONE', technologyType: 'WEB' }]; })();
7955
8537
  }
7956
8538
  if (changes.environmentId)
7957
8539
  patch['environment'] = await this.environmentKey(changes.environmentId);
@@ -8189,7 +8771,8 @@ export class SimplifyQaAdapter {
8189
8771
  if (input.pipelineType === 'SU') {
8190
8772
  const suite = await this.readOwnSuite(input.parentId);
8191
8773
  parentId = Number(suite['id']);
8192
- platForm = suitePlatform(suite, input.browser, 'create its pipeline');
8774
+ // A CLOUD pipeline is headless (the cloud picker): bind the *_HEADLESS platform, like a cloud run does.
8775
+ platForm = suitePlatform(suite, input.browser, 'create its pipeline', input.mode === 'cloud');
8193
8776
  }
8194
8777
  else {
8195
8778
  const tc = await this.fetchRawTestcase(input.parentId);
@@ -8199,7 +8782,7 @@ export class SimplifyQaAdapter {
8199
8782
  throw new Error(`${tc.code ?? `TC-${tc.id}`} is not in project ${projectId}.`);
8200
8783
  parentId = Number(tc.id);
8201
8784
  parentVersion = testcaseVersion(tc, true).versionId || undefined;
8202
- platForm = tcPlatform(tc, input.browser);
8785
+ platForm = tcPlatform(tc, input.browser, input.mode === 'cloud');
8203
8786
  }
8204
8787
  const body = {
8205
8788
  name: input.name, projectId, pipelineType: input.pipelineType, parentId,
@@ -8304,16 +8887,36 @@ export class SimplifyQaAdapter {
8304
8887
  }
8305
8888
  /** Assemble the strict allow-listed suite entry for an ADD op. Required fields per the SQA
8306
8889
  * validator: testcaseId, code, seq (set by the caller), version, versionId, tcType. */
8307
- async buildSuiteEntryFromTestcase(tcNum) {
8890
+ async buildSuiteEntryFromTestcase(tcNum, requested) {
8308
8891
  const raw = await this.fetchRawTestcase(tcNum);
8309
8892
  if (Object.keys(raw).length === 0)
8310
8893
  throw new Error(`test case ${tcNum} not found (cannot add to suite)`);
8311
8894
  const code = str(raw, 'code', 'tcCode') ?? `TC_${tcNum}`;
8312
8895
  const tcType = str(raw, 'tcType') ?? 'WEB';
8896
+ const versions = Array.isArray(raw?.versions) ? raw.versions : [];
8313
8897
  let versionName = str(raw, 'versionName', 'selectedVersionName');
8314
8898
  let versionId = str(raw, 'versionId', 'selectedVersionId');
8315
- if ((!versionName || !versionId) && Array.isArray(raw?.versions) && raw.versions.length > 0) {
8316
- const v = raw.versions[0];
8899
+ // A caller may pin a version (the same TC can sit in a suite once per version). The backend only
8900
+ // stores what we send, so an unknown version must FAIL here — otherwise v1.0 was silently added
8901
+ // again and the caller saw "success" for a row that is not the requested one.
8902
+ const wantId = (requested?.versionId ?? '').trim();
8903
+ const wantName = (requested?.version ?? '').trim();
8904
+ if (wantId || wantName) {
8905
+ const hit = versions.find((v) => {
8906
+ const id = str(v, 'id', '_id', 'versionId') ?? '';
8907
+ const name = str(v, 'name', 'versionName') ?? '';
8908
+ return (wantId && id === wantId) || (wantName && name.trim().toLowerCase() === wantName.toLowerCase());
8909
+ });
8910
+ if (!hit) {
8911
+ const available = versions.map((v) => `${str(v, 'name') ?? '?'} (${str(v, 'id', '_id', 'versionId') ?? '?'})`).join(', ');
8912
+ throw new Error(`${code} has no version ${wantId ? `"${wantId}"` : `"${wantName}"`}. ` +
8913
+ `Available versions: ${available || '(none)'}. Read them with sqa_query({ op:"get", collection:"testcases", id:"${code}" }).`);
8914
+ }
8915
+ versionName = str(hit, 'name', 'versionName') ?? versionName;
8916
+ versionId = str(hit, 'id', '_id', 'versionId') ?? versionId;
8917
+ }
8918
+ else if ((!versionName || !versionId) && versions.length > 0) {
8919
+ const v = versions.find((x) => x?.isChecked === true || x?.selected === true) ?? versions[0];
8317
8920
  versionName ?? (versionName = str(v, 'name'));
8318
8921
  versionId ?? (versionId = str(v, 'id', '_id'));
8319
8922
  }
@@ -10370,6 +10973,7 @@ export class SimplifyQaAdapter {
10370
10973
  const stackRun = mode === 'STACK' ? await this.suiteStackRunPlan(rawSuite, opts) : undefined;
10371
10974
  const members = !stackRun && Array.isArray(rawSuite.testCases) ? rawSuite.testCases : [];
10372
10975
  const executionItems = [];
10976
+ const cloudNeedsBrowser = [];
10373
10977
  let seqCounter = 0;
10374
10978
  for (const row of members) {
10375
10979
  seqCounter++;
@@ -10398,7 +11002,17 @@ export class SimplifyQaAdapter {
10398
11002
  // mode, send `[]` and let the backend reject/accept per its own rules.
10399
11003
  const savedPlatform = row?.executionPlatform?.[mode];
10400
11004
  let platform = [];
10401
- if (savedPlatform && typeof savedPlatform === 'object') {
11005
+ if (mode === 'CLOUD' && tcType === 'WEB') {
11006
+ // the cloud picker is Chrome / Firefox / Edge Headless: a browser the caller names applies to every web test case (as the Run dialog's does)
11007
+ const saved = savedPlatform && typeof savedPlatform === 'object' ? String(savedPlatform.id ?? savedPlatform.name ?? '') : '';
11008
+ if (opts.browser)
11009
+ platform = [cloudBrowserEntry(opts.browser)];
11010
+ else if (/_HEADLESS$/i.test(saved))
11011
+ platform = [{ name: savedPlatform.name, id: savedPlatform.id ?? savedPlatform.name, technologyType: 'WEB', type: savedPlatform.type ?? 'NONE' }];
11012
+ else
11013
+ cloudNeedsBrowser.push(str(rawTc, 'code') ?? `TC-${memberTcId}`);
11014
+ }
11015
+ else if (savedPlatform && typeof savedPlatform === 'object') {
10402
11016
  const p = {
10403
11017
  name: savedPlatform.name,
10404
11018
  id: savedPlatform.id ?? savedPlatform.name,
@@ -10450,6 +11064,10 @@ export class SimplifyQaAdapter {
10450
11064
  userstoryName: '',
10451
11065
  });
10452
11066
  }
11067
+ if (cloudNeedsBrowser.length) {
11068
+ throw new Error(`ASK the user which browser to run ${rawSuite.code ?? suiteId} in on the cloud — ${CLOUD_BROWSER_NAMES.join(', ')} (cloud runs are headless) — then call again with \`browser\` set. ` +
11069
+ `It has no saved cloud browser for: ${cloudNeedsBrowser.join(', ')}.`);
11070
+ }
10453
11071
  if (!stackRun && executionItems.length === 0) {
10454
11072
  throw new Error(`startRun: suite ${suiteId} has no runnable test cases (all members were deleted, ` +
10455
11073
  `unreadable, or filtered out).`);
@@ -10906,10 +11524,8 @@ export class SimplifyQaAdapter {
10906
11524
  buildRunPlatform(tcType, mode, opts) {
10907
11525
  const t = tcType.toUpperCase();
10908
11526
  if (t === 'WEB') {
10909
- if (mode === 'CLOUD') {
10910
- const key = `${(opts.browser ?? 'CHROME').toUpperCase()}_HEADLESS`;
10911
- return [{ name: key, id: key, technologyType: 'WEB', type: 'NONE' }];
10912
- }
11527
+ if (mode === 'CLOUD')
11528
+ return [cloudBrowserEntry(opts.browser)];
10913
11529
  const b = (opts.browser ?? 'CHROME').toUpperCase();
10914
11530
  return [{ name: b, id: b, technologyType: 'WEB', type: 'NONE' }];
10915
11531
  }
@@ -11084,7 +11700,22 @@ export class SimplifyQaAdapter {
11084
11700
  const m = e instanceof Error ? e.message : String(e);
11085
11701
  return /Could not reach the product MCP|fetch failed|ECONNREFUSED/i.test(m);
11086
11702
  }
11087
- async readJournal(tcId) {
11703
+ /** A version of the test case by id or name ("v2.0"). Only versions of THIS test case are accepted —
11704
+ * an unknown one is refused with the list, never silently replaced by the current version. */
11705
+ async resolveTcVersion(tcId, ref) {
11706
+ const raw = await this.fetchRawTestcase(tcId);
11707
+ const versions = toVersionEntries(Array.isArray(raw?.versions) ? raw.versions : []);
11708
+ const want = ref.trim().toLowerCase();
11709
+ const hit = versions.find((v) => v.id === ref.trim()) ?? versions.find((v) => (v.name ?? '').trim().toLowerCase() === want);
11710
+ if (!hit) {
11711
+ throw new Error(`${tcId} has no version "${ref}". Its versions: ${versions.map((v) => `${v.name ?? '?'} (${v.id})`).join(', ') || '(none)'}.`);
11712
+ }
11713
+ return { id: hit.id, name: hit.name ?? hit.id };
11714
+ }
11715
+ async readJournal(tcId, versionId) {
11716
+ // A non-current version has no journal on the agent (it only knows the recorded/current one): read its saved steps.
11717
+ if (versionId)
11718
+ return this.stepsView(tcId, versionId);
11088
11719
  const h = this.hop();
11089
11720
  if (h) {
11090
11721
  try {
@@ -11097,7 +11728,17 @@ export class SimplifyQaAdapter {
11097
11728
  }
11098
11729
  return this.stepsView(tcId);
11099
11730
  }
11100
- async editJournal(tcId, ops) {
11731
+ async editJournal(tcId, ops, versionId) {
11732
+ if (versionId) {
11733
+ // The agent's journal belongs to the current version only, so a pinned version is edited on its saved steps.
11734
+ const pinned = new Set(['set_meta', 'add_step', 'update_step', 'update_steps', 'add_assertions', 'remove_step', 'remove_steps', 'move_step', 'insert_nested', 'duplicate_step']);
11735
+ const needsAgent = ops.filter((o) => !pinned.has(o.op)).map((o) => o.op);
11736
+ if (needsAgent.length) {
11737
+ throw new Error(`${needsAgent.join(', ')} cannot be applied to a chosen version (versionId "${versionId}") — it needs the agent, which only edits the current version. ` +
11738
+ 'Select that version as current in SimplifyQA first, or use the other ops.');
11739
+ }
11740
+ return this.editStepsDirect(tcId, ops, versionId);
11741
+ }
11101
11742
  // Every step-editing op is applied straight to the saved test case. Sent through the agent, an edit
11102
11743
  // either opened the recorder window (SCRPY) and never landed, or — as with a plain `update_step` on
11103
11744
  // a saved TC — hit the agent's JOURNAL editor, which only knows recording journals and rejected a
@@ -11126,14 +11767,21 @@ export class SimplifyQaAdapter {
11126
11767
  }
11127
11768
  return this.editStepsDirect(tcId, ops);
11128
11769
  }
11129
- async stepsView(tcId) {
11130
- const tc = await this.getTestCase(tcId);
11131
- return { tcId, source: 'steps', steps: tc.steps ?? [] };
11770
+ async stepsView(tcId, versionRef) {
11771
+ const pinned = versionRef ? await this.resolveTcVersion(tcId, versionRef) : undefined;
11772
+ const tc = await this.getTestCase(tcId, pinned?.id);
11773
+ const cur = tc.versions?.find((v) => v.id === tc.currentVersionId);
11774
+ return {
11775
+ tcId, source: 'steps', steps: tc.steps ?? [],
11776
+ ...(cur ? { version: { id: cur.id, name: cur.name ?? cur.id } } : {}),
11777
+ ...(tc.versions ? { versionCount: tc.versions.length } : {}),
11778
+ };
11132
11779
  }
11133
11780
  /** Agent-free step edit: read the test case, apply remove / update / move by step number, renumber, and
11134
11781
  * save through updateTestCase (which sends removed steps back with `deleted:true`, as the UI does). */
11135
- async editStepsDirect(tcId, ops) {
11136
- let tc = await this.getTestCase(tcId);
11782
+ async editStepsDirect(tcId, ops, versionRef) {
11783
+ const pinned = versionRef ? await this.resolveTcVersion(tcId, versionRef) : undefined;
11784
+ let tc = await this.getTestCase(tcId, pinned?.id);
11137
11785
  log(`[mcp][editStepsDirect] tcId=${tcId} technologyType=${tc.technologyType ?? '(none)'} executionPlatform=${tc.executionPlatform ? JSON.stringify(tc.executionPlatform) : '(none)'} steps=${tc.steps?.length ?? 0} ops=${ops.map(o => o.op).join(',')}`);
11138
11786
  let steps = [...(tc.steps ?? [])];
11139
11787
  for (const op of ops) {
@@ -11263,7 +11911,7 @@ export class SimplifyQaAdapter {
11263
11911
  steps = steps.map((x, k) => ({ ...x, n: k + 1 }));
11264
11912
  }
11265
11913
  await this.updateTestCase(tcId, { ...tc, steps });
11266
- return this.stepsView(tcId);
11914
+ return this.stepsView(tcId, pinned?.id);
11267
11915
  }
11268
11916
  // ---------------------------------------------------------------------- Self-healing
11269
11917
  /** `heal_propose` on the product server: replay + DOM evidence + proposals. Read-only — it never