@spec-wave/cli 1.0.7 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/package.json +1 -1
  2. package/src/commands/audit.mjs +24 -18
  3. package/src/commands/code-review.mjs +91 -59
  4. package/src/commands/decompose.mjs +258 -221
  5. package/src/commands/doctor.mjs +16 -11
  6. package/src/commands/generate-bug.mjs +51 -44
  7. package/src/commands/generate-plan.mjs +83 -63
  8. package/src/commands/generate-qa-plan.mjs +145 -117
  9. package/src/commands/generate-spec.mjs +33 -28
  10. package/src/commands/implement.mjs +155 -79
  11. package/src/commands/info.mjs +4 -3
  12. package/src/commands/init.mjs +11 -5
  13. package/src/commands/install-skill.mjs +19 -0
  14. package/src/commands/issue.mjs +26 -39
  15. package/src/commands/merge.mjs +71 -20
  16. package/src/commands/mode.mjs +11 -6
  17. package/src/commands/move.mjs +16 -20
  18. package/src/commands/order.mjs +33 -22
  19. package/src/commands/preflight.mjs +24 -13
  20. package/src/commands/qa-lead.mjs +30 -17
  21. package/src/commands/qa-run.mjs +125 -103
  22. package/src/commands/qa.mjs +55 -44
  23. package/src/commands/refresh.mjs +24 -16
  24. package/src/commands/repair-stage.mjs +29 -16
  25. package/src/commands/repo.mjs +12 -4
  26. package/src/commands/run.mjs +23 -11
  27. package/src/commands/story.mjs +20 -25
  28. package/src/commands/task.mjs +21 -27
  29. package/src/commands/triage.mjs +33 -31
  30. package/src/commands/uninstall.mjs +7 -3
  31. package/src/commands/update.mjs +31 -22
  32. package/src/commands/validate.mjs +60 -52
  33. package/src/commands/workspace.mjs +7 -5
  34. package/src/config.mjs +7 -1
  35. package/src/lib/artifact-publish.mjs +20 -18
  36. package/src/lib/board-policy.mjs +144 -0
  37. package/src/lib/board.mjs +134 -233
  38. package/src/lib/cli-ref.mjs +75 -0
  39. package/src/lib/config-file.mjs +2 -1
  40. package/src/lib/doc-availability.mjs +10 -3
  41. package/src/lib/doc-source.mjs +9 -9
  42. package/src/lib/execution-mode.mjs +5 -3
  43. package/src/lib/implement-board.mjs +23 -26
  44. package/src/lib/issue-type.mjs +5 -1
  45. package/src/lib/plugin-skills.mjs +10 -0
  46. package/src/lib/pr-ready.mjs +48 -10
  47. package/src/lib/pr-step.mjs +3 -1
  48. package/src/lib/qa-exec.mjs +3 -1
  49. package/src/lib/qa-lead.mjs +11 -3
  50. package/src/lib/qa-plan-doc.mjs +10 -4
  51. package/src/lib/qa-report.mjs +2 -1
  52. package/src/lib/skill-compose.mjs +3 -0
  53. package/src/lib/spec-audit.mjs +1 -1
  54. package/src/lib/story-graph.mjs +62 -8
  55. package/src/lib/usage-report.mjs +8 -5
  56. package/src/lib/work-item-ref.mjs +176 -0
  57. package/src/plugin/.claude-plugin/plugin.json +1 -1
  58. package/src/plugins/scm-github/index.mjs +439 -0
  59. package/src/plugins/tracker-github-projects/fields.mjs +73 -0
  60. package/src/plugins/tracker-github-projects/index.mjs +625 -0
  61. package/src/ports/scm.mjs +197 -0
  62. package/src/ports/tracker.mjs +239 -0
  63. package/src/ports/types.mjs +254 -0
  64. package/src/setup/files.mjs +14 -12
  65. package/src/setup/labels.mjs +17 -12
  66. package/src/setup/project.mjs +40 -59
  67. package/src/templates/workflows/code/code-review.yml +1 -1
  68. package/src/templates/workflows/code/qa.yml +1 -1
@@ -19,16 +19,28 @@ import path from 'node:path';
19
19
  import chalk from 'chalk';
20
20
 
21
21
  import { resolveToken } from '../api/auth.mjs';
22
- import {
23
- getIssue, createIssue, addLabel, commentOnIssue, listIssueComments,
24
- } from '../api/github-rest.mjs';
25
- import {
26
- getIssueParent, listSubIssues, listIssuePullRequests, addSubIssue,
27
- addProjectItem, getItemSingleSelectValue, setItemSingleSelect,
28
- } from '../api/github-graphql.mjs';
22
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
23
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
24
+
25
+ /** Portas do hub — o QA roda sempre contra o repositório das issues. */
26
+ const trackerDe = (token, owner, repo) => createGithubTracker({ token, owner, repo });
27
+ const scmDe = (token, owner, repo) => createGithubScm({ link: githubLink({ owner, repo }), token });
28
+
29
+ /** WorkItem → a forma `{number, nodeId, title, labels}` que este arquivo usa. */
30
+ const comoItem = w => w && ({
31
+ number: Number(w.ref.key),
32
+ nodeId: w.ref.id,
33
+ node_id: w.ref.id,
34
+ title: w.title,
35
+ body: w.body || '',
36
+ labels: w.tags || [],
37
+ state: w.state || null,
38
+ milestone: w.milestone ? { number: Number(w.milestone.key), title: w.milestone.title } : null,
39
+ ref: w.ref,
40
+ });
29
41
  import { detectIssueType } from '../lib/issue-type.mjs';
30
42
  import { loadConfig, findConfigPath } from '../lib/project-root.mjs';
31
- import { loadProjectConfig, resolveField, advanceToStage, setItemStatus } from '../lib/board.mjs';
43
+ import { openTracker, advanceToStage, setProgress } from '../lib/board.mjs';
32
44
  import { loadArtifact, isAwaitingMerge } from '../lib/doc-source.mjs';
33
45
  import { awaitingMergeBlock } from '../lib/artifact-pr.mjs';
34
46
  import { featureDocPaths, bugDocPaths } from '../lib/doc-paths.mjs';
@@ -39,6 +51,7 @@ import {
39
51
  resolveQaEvidenceConfig,
40
52
  } from '../lib/qa-exec.mjs';
41
53
  import { pushWithRebase } from '../lib/git-retry.mjs';
54
+ import { cliRef } from '../lib/cli-ref.mjs';
42
55
  import {
43
56
  aggregateVerdict, validateQaResults, combineWithPrevious, parseLastQaReport,
44
57
  renderQaReport, renderQaBugDoc, qaOriginMarker, matchesQaOrigin, shortSha,
@@ -62,39 +75,34 @@ class QaRefusal extends Error {
62
75
  }
63
76
  }
64
77
 
65
- async function resolveParentFeature(token, startNodeId) {
66
- let current = startNodeId;
78
+ async function resolveParentFeature(token, owner, repo, startRef) {
79
+ const tracker = trackerDe(token, owner, repo);
80
+ let current = startRef;
67
81
  for (let depth = 0; depth < 5 && current; depth++) {
68
- const parent = await getIssueParent(token, current);
82
+ const parent = await tracker.getParent({ ref: current });
69
83
  if (!parent) return null;
70
- if (detectIssueType({ title: parent.title }) === 'Feature') return parent;
71
- current = parent.nodeId;
84
+ if (detectIssueType({ title: parent.title }) === 'Feature') {
85
+ return { number: Number(parent.ref.key), title: parent.title, nodeId: parent.ref.id, ref: parent.ref };
86
+ }
87
+ current = parent.ref;
72
88
  }
73
89
  return null;
74
90
  }
75
91
 
76
92
  // Campos do board, resolvidos uma vez. Best-effort: sem board, os movimentos
77
93
  // viram avisos (o veredito e o relatório não dependem dele).
78
- async function resolveBoard(root, projectToken) {
79
- const { project, error } = loadProjectConfig({ cwd: root || process.cwd() });
80
- if (error || !project?.id) {
81
- return { project: null, error: error || 'Project não configurado', etapaField: null, statusField: null, typeField: null };
82
- }
83
- const etapaField = await resolveField(projectToken, project, 'Etapa').catch(() => null);
84
- const statusField = await resolveField(projectToken, project, 'Status').catch(() => null);
85
- const typeField = await resolveField(projectToken, project, 'Work Item Type').catch(() => null);
86
- const priorityField = await resolveField(projectToken, project, 'Priority').catch(() => null);
87
- return { project, error: null, etapaField, statusField, typeField, priorityField };
94
+ async function resolveBoard(root, projectToken, token, owner, repo) {
95
+ const { tracker, error } = openTracker({
96
+ token, projectToken, owner, repo, cwd: root || process.cwd(),
97
+ });
98
+ return { tracker, error: error || null };
88
99
  }
89
100
 
90
- async function readStage(projectToken, board, nodeId) {
91
- if (!board.project || !board.etapaField?.id) return null;
92
- try {
93
- const itemId = await addProjectItem(projectToken, board.project.id, nodeId);
94
- return await getItemSingleSelectValue(projectToken, itemId, board.etapaField.id);
95
- } catch {
96
- return null;
97
- }
101
+ async function readStage(board, number, nodeId) {
102
+ if (!board.tracker) return null;
103
+ return await board.tracker
104
+ .getStage({ ref: { key: String(number), id: nodeId } })
105
+ .catch(() => null);
98
106
  }
99
107
 
100
108
  function headShaOf(root) {
@@ -218,11 +226,15 @@ function parseOnly(only) {
218
226
  }
219
227
 
220
228
  async function trimmedComments(token, owner, repo, issueNumber, kind) {
221
- const all = await listIssueComments(token, owner, repo, issueNumber).catch(() => []);
229
+ const all = await trackerDe(token, owner, repo).listComments({ ref: { key: String(issueNumber) } }).catch(() => []);
222
230
  if (all.length === 0) return { all, groups: [] };
223
231
  const items = all.slice(-MAX_COMMENTS).map(c => ({
224
- author: c.user?.login,
225
- createdAt: c.created_at,
232
+ // Formas do contrato (`author`, `createdAt`) primeiro, REST crua depois.
233
+ // Lendo só a crua, o mapeamento já descartava `user` aqui e nem o leitor
234
+ // tolerante de qa-exec.mjs conseguia recuperar: todo comentário saía como
235
+ // `**desconhecido** ():` na entrada do modelo.
236
+ author: c.author || c.user?.login,
237
+ createdAt: c.createdAt || c.created_at,
226
238
  body: c.body.length > MAX_COMMENT_CHARS ? `${c.body.slice(0, MAX_COMMENT_CHARS)}…[truncado]` : c.body,
227
239
  }));
228
240
  return { all, groups: [{ issueNumber, kind, total: all.length, items }] };
@@ -240,7 +252,7 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
240
252
  if (!configPath) {
241
253
  throw new QaRefusal(
242
254
  `Repositório não inicializado (sem ${CONFIG_FILE}). ` +
243
- 'Rode `npx @spec-wave/cli@latest init` (ou a skill setup) primeiro.'
255
+ `Rode \`npx ${cliRef()} init\` (ou a skill setup) primeiro.`
244
256
  );
245
257
  }
246
258
  const { config, root } = loadConfig();
@@ -257,7 +269,7 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
257
269
  const token = await resolveToken();
258
270
  const projectToken = process.env.PROJECT_TOKEN || token;
259
271
 
260
- const issue = await getIssue(token, owner, repo, number);
272
+ const issue = comoItem(await trackerDe(token, owner, repo).getWorkItem({ ref: { key: String(number) } }));
261
273
  const type = detectIssueType(issue);
262
274
 
263
275
  // ── Feature dona do plano (Feature/Story) ──────────────────────────────────
@@ -268,29 +280,29 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
268
280
  labels: labelNames(issue), milestone: issue.milestone || null,
269
281
  };
270
282
  } else if (type === 'Story') {
271
- const parent = await resolveParentFeature(token, issue.node_id).catch(() => null);
283
+ const parent = await resolveParentFeature(token, owner, repo, issue.ref).catch(() => null);
272
284
  if (!parent) {
273
285
  throw new QaRefusal(
274
286
  `A Story #${number} não tem Feature-pai — o plano de QA é por Feature (D-QA1), ` +
275
287
  'e sem ela não há plano a executar. Vincule a Story como sub-issue de uma Feature.'
276
288
  );
277
289
  }
278
- const parentIssue = await getIssue(token, owner, repo, parent.number);
290
+ const parentIssue = comoItem(await trackerDe(token, owner, repo).getWorkItem({ ref: parent.ref }));
279
291
  feature = {
280
292
  number: parent.number, title: parentIssue.title, nodeId: parentIssue.node_id,
281
293
  labels: labelNames(parentIssue), milestone: parentIssue.milestone || null,
282
294
  };
283
295
  }
284
296
 
285
- // ── Etapa no board. Pulada no dry-run: a leitura passa por addProjectItem,
286
- // que é mutação, e o dry-run promete ZERO escrita no GitHub. ────────────────
297
+ // ── Etapa no board. Pulada no dry-run: ler a Etapa passa por adicionar o
298
+ // item ao Project, que é mutação, e o dry-run promete ZERO escrita. ─────────
287
299
  const board = dryRun
288
- ? { project: null, error: 'dry-run', etapaField: null, statusField: null, typeField: null }
289
- : await resolveBoard(root, projectToken);
300
+ ? { tracker: null, error: 'dry-run' }
301
+ : await resolveBoard(root, projectToken, token, owner, repo);
290
302
  let stage = null;
291
303
  if (!dryRun) {
292
304
  if (board.error) console.warn(chalk.yellow(`⚠️ ${board.error} — Etapa não verificada e board não será atualizado.`));
293
- else stage = await readStage(projectToken, board, issue.node_id);
305
+ else stage = await readStage(board, issue.number, issue.node_id);
294
306
  } else {
295
307
  console.log(chalk.dim('Dry-run: Etapa do board não consultada (a leitura adicionaria o item ao Project).'));
296
308
  }
@@ -402,7 +414,7 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
402
414
  // Stories já aprovadas saem do alvo no modo Feature.
403
415
  let subStories = [];
404
416
  try {
405
- subStories = (await listSubIssues(token, feature.nodeId))
417
+ subStories = (await trackerDe(token, owner, repo).listChildren({ ref: feature.ref ?? { key: String(feature.number), id: feature.nodeId } })).map(comoItem)
406
418
  .filter(s => detectIssueType({ title: s.title, labels: s.labels }) === 'Story');
407
419
  } catch (err) {
408
420
  console.warn(chalk.yellow(`⚠️ Não foi possível listar as Stories da Feature: ${err.message}.`));
@@ -450,7 +462,9 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
450
462
  const previous = parseLastQaReport(allComments);
451
463
  const run = previous.run + 1;
452
464
 
453
- const pullRequests = await listIssuePullRequests(token, issue.node_id).catch(() => []);
465
+ const pullRequests = await scmDe(token, owner, repo)
466
+ .findPullRequestsReferencing({ ref: issue.ref ?? { key: String(issue.number), id: issue.node_id } })
467
+ .catch(() => []);
454
468
 
455
469
  mkdirSync(path.join(root || process.cwd(), WORK_DIR), { recursive: true });
456
470
  const contextFile = path.join(WORK_DIR, `qa-${number}.md`);
@@ -649,7 +663,7 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
649
663
  ? `❌ **O teste de regressão ainda reprova** — o fix não cobriu o defeito. O Bug permanece ` +
650
664
  `em **${STAGE_QA}** (Status ${PROGRESS_IN_PROGRESS}); nenhum Bug novo foi aberto (é o mesmo defeito).`
651
665
  : `O item permanece em **${STAGE_QA}** (Status ${PROGRESS_IN_PROGRESS}). Corrija o(s) Bug(s) e ` +
652
- `re-teste com \`npx @spec-wave/cli@latest qa <story> --only <cenário>\`.`,
666
+ `re-teste com \`npx ${cliRef()} qa <story> --only <cenário>\`.`,
653
667
  });
654
668
  process.exitCode = 1;
655
669
  return { verdict, bugs };
@@ -708,14 +722,17 @@ async function postReport({
708
722
  pendingNumbers,
709
723
  trailer,
710
724
  });
711
- await commentOnIssue(token, owner, repo, number, markdown)
725
+ await trackerDe(token, owner, repo).addComment({ ref: { key: String(number) }, body: markdown })
712
726
  .catch(err => console.warn(chalk.yellow(`⚠️ Falha ao comentar o relatório: ${err.message}`)));
713
727
  }
714
728
 
715
- async function stayInQa({ projectToken, board, issue }) {
716
- if (!board.project || !board.statusField) return;
717
- await setItemStatus(projectToken, board.project, board.statusField, issue.node_id, PROGRESS_IN_PROGRESS)
718
- .catch(() => {});
729
+ async function stayInQa({ board, issue }) {
730
+ if (!board.tracker) return;
731
+ await setProgress({
732
+ tracker: board.tracker,
733
+ ref: { key: String(issue.number), id: issue.node_id },
734
+ progress: PROGRESS_IN_PROGRESS,
735
+ }).catch(() => {});
719
736
  }
720
737
 
721
738
  // Vermelho: um Bug por cenário reprovado — filho da STORY dona do cenário
@@ -741,7 +758,7 @@ async function openBugsForFailures({
741
758
 
742
759
  let story = null;
743
760
  try {
744
- story = await getIssue(token, owner, repo, storyNumber);
761
+ story = comoItem(await trackerDe(token, owner, repo).getWorkItem({ ref: { key: String(storyNumber) } }));
745
762
  } catch (err) {
746
763
  console.warn(chalk.yellow(`⚠️ Não consegui ler a Story #${storyNumber} (${err.message}) — Bug do cenário ${r.numero} NÃO criado.`));
747
764
  pushFailures.push({ numero: r.numero, error: `Story #${storyNumber} ilegível: ${err.message}` });
@@ -750,7 +767,7 @@ async function openBugsForFailures({
750
767
 
751
768
  // Idempotência: Bug filho ABERTO com o mesmo marcador de origem → comenta
752
769
  // nele em vez de duplicar.
753
- const children = await listSubIssues(token, story.node_id).catch(() => []);
770
+ const children = (await trackerDe(token, owner, repo).listChildren({ ref: story.ref ?? { key: String(story.number), id: story.node_id } }).catch(() => [])).map(comoItem);
754
771
  const existing = children.find(c =>
755
772
  detectIssueType({ title: c.title, labels: c.labels }) === 'Bug' &&
756
773
  c.state !== 'closed' &&
@@ -760,11 +777,13 @@ async function openBugsForFailures({
760
777
  const midia = (r.evidenceFiles || []).length > 0 && evidenceBase
761
778
  ? `\n\n**Evidência visual:** ${r.evidenceFiles.map(f => `[${f.split('/').pop()}](${evidenceMediaUrl(evidenceBase.owner, evidenceBase.repo, evidenceBase.sha, f)})`).join(' · ')}`
762
779
  : '';
763
- await commentOnIssue(token, owner, repo, existing.number,
764
- `🧪 **O cenário ${scenario.numero} da Story #${storyNumber} reprovou de novo** ` +
765
- `(${headSha ? `commit \`${headSha}\`` : 'nova execução'}).\n\n` +
766
- `**Evidência:** ${r.evidencia || '(sem evidência registrada)'}${midia}`
767
- ).catch(() => {});
780
+ await trackerDe(token, owner, repo).addComment({
781
+ ref: { key: String(existing.number) },
782
+ body:
783
+ `🧪 **O cenário ${scenario.numero} da Story #${storyNumber} reprovou de novo** ` +
784
+ `(${headSha ? `commit \`${headSha}\`` : 'nova execução'}).\n\n` +
785
+ `**Evidência:** ${r.evidencia || '(sem evidência registrada)'}${midia}`,
786
+ }).catch(() => {});
768
787
  bugs.push({ number: existing.number, cenario: scenario.numero, existing: true });
769
788
  continue;
770
789
  }
@@ -821,7 +840,13 @@ async function openBugsForFailures({
821
840
 
822
841
  let created;
823
842
  try {
824
- created = await createIssue(token, owner, repo, title, bodyLines.join('\n'), labels, { milestone });
843
+ created = comoItem({
844
+ ref: await trackerDe(token, owner, repo).createWorkItem({
845
+ title, body: bodyLines.join('\n'), type: 'Bug', tags: labels,
846
+ milestone: milestone ? { key: String(milestone) } : null,
847
+ }),
848
+ title, body: bodyLines.join('\n'), tags: labels, state: 'open',
849
+ });
825
850
  } catch (err) {
826
851
  console.warn(chalk.yellow(`⚠️ Falha ao criar o Bug do cenário ${scenario.numero}: ${err.message}`));
827
852
  pushFailures.push({ numero: r.numero, error: `criação da issue falhou: ${err.message}` });
@@ -829,39 +854,40 @@ async function openBugsForFailures({
829
854
  }
830
855
  console.log(`Bug #${created.number} criado para o cenário ${scenario.numero} (filho da Story #${storyNumber}).`);
831
856
 
832
- await addSubIssue(token, story.node_id, created.nodeId)
857
+ await trackerDe(token, owner, repo).addChild({ parent: story.ref ?? { key: String(story.number), id: story.node_id }, child: created.ref })
833
858
  .catch(err => console.warn(chalk.yellow(`⚠️ Bug #${created.number} criado, mas não vinculado à Story: ${err.message}`)));
834
859
 
835
860
  // Board: 🧪 QA achou → o Bug nasce em ✅ Ready (triagem já feita pela reprova).
836
- if (board.project && board.etapaField) {
861
+ if (board.tracker) {
862
+ const bugRef = { key: String(created.number), id: created.nodeId };
837
863
  try {
838
- await advanceToStage(
839
- projectToken, board.project, board.etapaField, board.statusField,
840
- created.nodeId, STAGE_READY, PROGRESS_TODO,
841
- { typeField: board.typeField, itemType: 'Bug' });
864
+ await advanceToStage({
865
+ tracker: board.tracker, ref: bugRef,
866
+ stage: STAGE_READY, progress: PROGRESS_TODO, itemType: 'Bug',
867
+ });
842
868
  } catch (err) {
843
869
  console.warn(chalk.yellow(`⚠️ Bug #${created.number} sem Etapa no board: ${err.message} — repare com \`spec-wave repair-stage\`.`));
844
870
  }
845
- if (board.priorityField?.options?.[severity]) {
846
- try {
847
- const itemId = await addProjectItem(projectToken, board.project.id, created.nodeId);
848
- await setItemSingleSelect(projectToken, board.project.id, itemId,
849
- board.priorityField.id, board.priorityField.options[severity]);
850
- } catch { /* prioridade no board é acessório */ }
851
- }
871
+ // Prioridade no board é acessório: campo ou opção ausente devolve false
872
+ // em vez de lançar, e o Bug segue existindo com Etapa.
873
+ await board.tracker
874
+ .setField({ ref: bugRef, field: 'priority', value: severity })
875
+ .catch(() => false);
852
876
  }
853
877
 
854
878
  // `bug-approved` direto: reprodução, esperado/obtido e regressão são a
855
879
  // execução observada — regerar por IA só introduziria alucinação.
856
- await addLabel(token, owner, repo, created.number, LABEL_BUG_APPROVED).catch(() => {});
857
-
858
- await commentOnIssue(token, owner, repo, created.number,
859
- `🧪 **Bug aberto pela reprovação de QA** — ${scenario.anchor} da Story #${storyNumber}.\n\n` +
860
- `📄 \`${fileRel}\` foi escrito, commitado e publicado com as seis seções preenchidas a partir ` +
861
- 'do cenário e da saída real da execução (exceção documentada à regra do `spec-wave:bug` — ' +
862
- 'conteúdo determinístico de uma execução observada, sem IA).\n\n' +
863
- `Após o fix, re-teste: \`npx @spec-wave/cli@latest qa ${storyNumber} --only ${scenario.numero}\``
864
- ).catch(() => {});
880
+ await trackerDe(token, owner, repo).addTag({ ref: { key: String(created.number) }, tag: LABEL_BUG_APPROVED }).catch(() => {});
881
+
882
+ await trackerDe(token, owner, repo).addComment({
883
+ ref: { key: String(created.number) },
884
+ body:
885
+ `🧪 **Bug aberto pela reprovação de QA** — ${scenario.anchor} da Story #${storyNumber}.\n\n` +
886
+ `📄 \`${fileRel}\` foi escrito, commitado e publicado com as seis seções preenchidas a partir ` +
887
+ 'do cenário e da saída real da execução (exceção documentada à regra do `spec-wave:bug` — ' +
888
+ 'conteúdo determinístico de uma execução observada, sem IA).\n\n' +
889
+ `Após o fix, re-teste: \`npx ${cliRef()} qa ${storyNumber} --only ${scenario.numero}\``,
890
+ }).catch(() => {});
865
891
 
866
892
  bugs.push({ number: created.number, cenario: scenario.numero, existing: false });
867
893
  }
@@ -874,19 +900,18 @@ async function applyGreen({
874
900
  token, projectToken, owner, repo, board, issue, number, type, feature, combined, byNumero,
875
901
  featureStories = [],
876
902
  }) {
877
- const move = async (nodeId, targetStage, itemType) => {
878
- if (!board.project || !board.etapaField) return false;
879
- return await advanceToStage(
880
- projectToken, board.project, board.etapaField, board.statusField,
881
- nodeId, targetStage, PROGRESS_TODO,
882
- { typeField: board.typeField, itemType });
903
+ const move = async (ref, targetStage, itemType) => {
904
+ if (!board.tracker) return false;
905
+ return await advanceToStage({
906
+ tracker: board.tracker, ref, stage: targetStage, progress: PROGRESS_TODO, itemType,
907
+ });
883
908
  };
884
909
 
885
910
  if (type === 'Bug') {
886
- await addLabel(token, owner, repo, number, LABEL_QA_APPROVED).catch(() => {});
911
+ await trackerDe(token, owner, repo).addTag({ ref: { key: String(number) }, tag: LABEL_QA_APPROVED }).catch(() => {});
887
912
  const target = greenTargetStage('Bug');
888
913
  try {
889
- await move(issue.node_id, target, 'Bug');
914
+ await move(issue.ref, target, 'Bug');
890
915
  console.log(`Bug #${number} → "${target}" (D-QA6: Bug não passa por Homologação).`);
891
916
  } catch (err) {
892
917
  console.warn(chalk.yellow(`⚠️ Falha ao mover o Bug no board: ${err.message}`));
@@ -895,7 +920,7 @@ async function applyGreen({
895
920
  }
896
921
 
897
922
  if (type === 'Story') {
898
- const children = (await listSubIssues(token, issue.node_id).catch(() => []))
923
+ const children = ((await trackerDe(token, owner, repo).listChildren({ ref: issue.ref }).catch(() => [])).map(comoItem))
899
924
  .map(c => ({ ...c, type: detectIssueType({ title: c.title, labels: c.labels }) }));
900
925
  const guard = storyCanAdvance({ children });
901
926
  if (!guard.ok) {
@@ -908,9 +933,9 @@ async function applyGreen({
908
933
  'e rode o `qa` de novo.',
909
934
  };
910
935
  }
911
- await addLabel(token, owner, repo, number, LABEL_QA_APPROVED).catch(() => {});
936
+ await trackerDe(token, owner, repo).addTag({ ref: { key: String(number) }, tag: LABEL_QA_APPROVED }).catch(() => {});
912
937
  try {
913
- await move(issue.node_id, STAGE_UAT, 'Story');
938
+ await move(issue.ref, STAGE_UAT, 'Story');
914
939
  console.log(`Story #${number} → "${STAGE_UAT}" / Status "${PROGRESS_TODO}".`);
915
940
  } catch (err) {
916
941
  console.warn(chalk.yellow(`⚠️ Falha ao mover a Story no board: ${err.message}`));
@@ -940,16 +965,16 @@ async function applyGreen({
940
965
  const daStory = combined.filter(r => byNumero.get(r.numero)?.story === story.number);
941
966
  if (daStory.length === 0) continue;
942
967
  if (!daStory.every(r => r.verdict === 'pass')) continue;
943
- const children = (await listSubIssues(token, story.nodeId).catch(() => []))
968
+ const children = ((await trackerDe(token, owner, repo).listChildren({ ref: story.ref ?? { key: String(story.number), id: story.nodeId } }).catch(() => [])).map(comoItem))
944
969
  .map(c => ({ ...c, type: detectIssueType({ title: c.title, labels: c.labels }) }));
945
970
  const guard = storyCanAdvance({ children });
946
971
  if (!guard.ok) {
947
972
  console.log(chalk.yellow(`Story #${story.number} verde, mas com Bug aberto (${guard.openBugs.map(n => `#${n}`).join(', ')}) — não avança.`));
948
973
  continue;
949
974
  }
950
- await addLabel(token, owner, repo, story.number, LABEL_QA_APPROVED).catch(() => {});
975
+ await trackerDe(token, owner, repo).addTag({ ref: { key: String(story.number) }, tag: LABEL_QA_APPROVED }).catch(() => {});
951
976
  try {
952
- await move(story.nodeId, STAGE_UAT, 'Story');
977
+ await move(story.ref ?? { key: String(story.number), id: story.nodeId }, STAGE_UAT, 'Story');
953
978
  console.log(`Story #${story.number} → "${STAGE_UAT}".`);
954
979
  } catch (err) {
955
980
  console.warn(chalk.yellow(`⚠️ Falha ao mover a Story #${story.number}: ${err.message}`));
@@ -977,7 +1002,7 @@ async function maybeAdvanceFeature({ token, projectToken, owner, repo, board, fe
977
1002
  const aprovadas = new Set(Array.isArray(justApproved) ? justApproved : [justApproved]);
978
1003
  let stories = [];
979
1004
  try {
980
- stories = (await listSubIssues(token, feature.nodeId))
1005
+ stories = ((await trackerDe(token, owner, repo).listChildren({ ref: feature.ref ?? { key: String(feature.number), id: feature.nodeId } })).map(comoItem))
981
1006
  .filter(s => detectIssueType({ title: s.title, labels: s.labels }) === 'Story');
982
1007
  } catch {
983
1008
  return false; // sem a lista, na dúvida a Feature não avança
@@ -986,11 +1011,8 @@ async function maybeAdvanceFeature({ token, projectToken, owner, repo, board, fe
986
1011
  for (const s of stories) {
987
1012
  const labels = aprovadas.has(s.number) ? [...(s.labels || []), LABEL_QA_APPROVED] : (s.labels || []);
988
1013
  let stage = null;
989
- if (!labelNames(labels).includes(LABEL_QA_APPROVED) && board.project && board.etapaField) {
990
- try {
991
- const itemId = await addProjectItem(projectToken, board.project.id, s.nodeId);
992
- stage = await getItemSingleSelectValue(projectToken, itemId, board.etapaField.id);
993
- } catch { stage = null; }
1014
+ if (!labelNames(labels).includes(LABEL_QA_APPROVED) && board.tracker) {
1015
+ stage = await readStage(board, s.number, s.nodeId);
994
1016
  }
995
1017
  enriched.push({ number: s.number, labels, stage });
996
1018
  }
@@ -1001,9 +1023,9 @@ async function maybeAdvanceFeature({ token, projectToken, owner, repo, board, fe
1001
1023
  }
1002
1024
  return false;
1003
1025
  }
1004
- await addLabel(token, owner, repo, feature.number, LABEL_QA_APPROVED).catch(() => {});
1026
+ await trackerDe(token, owner, repo).addTag({ ref: { key: String(feature.number) }, tag: LABEL_QA_APPROVED }).catch(() => {});
1005
1027
  try {
1006
- await move(feature.nodeId, STAGE_UAT, 'Feature');
1028
+ await move(feature.ref ?? { key: String(feature.number), id: feature.nodeId }, STAGE_UAT, 'Feature');
1007
1029
  console.log(`Feature #${feature.number} → "${STAGE_UAT}".`);
1008
1030
  return true;
1009
1031
  } catch (err) {
@@ -1,8 +1,8 @@
1
1
  import { resolveToken } from '../api/auth.mjs';
2
- import { getIssue, getPR, commentOnIssue } from '../api/github-rest.mjs';
3
- import { getIssueParent } from '../api/github-graphql.mjs';
2
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
3
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
4
4
  import { detectIssueType } from '../lib/issue-type.mjs';
5
- import { loadProjectConfig, resolveField, advanceToStage } from '../lib/board.mjs';
5
+ import { openTracker, advanceToStage } from '../lib/board.mjs';
6
6
  import { resolveHubContext, resolvePrRepo } from '../lib/project-root.mjs';
7
7
  import { extractIssueRefs, hubIssueNumbers, resolveLinkMode } from '../lib/pr-link.mjs';
8
8
  import { STATUS_OPTIONS, PROGRESS_TODO } from '../config.mjs';
@@ -10,29 +10,30 @@ import { STATUS_OPTIONS, PROGRESS_TODO } from '../config.mjs';
10
10
  const QA_STAGE = STATUS_OPTIONS.find(s => s.name.includes('QA'))?.name;
11
11
  const TODO_STATUS = PROGRESS_TODO;
12
12
 
13
- async function resolveFeatureIssue(token, owner, repo, issueNumber) {
13
+ async function resolveFeatureIssue(tracker, issueNumber) {
14
14
  let issue;
15
15
  try {
16
- issue = await getIssue(token, owner, repo, issueNumber);
16
+ issue = await tracker.getWorkItem({ ref: { key: String(issueNumber) } });
17
17
  } catch {
18
18
  return null;
19
19
  }
20
+ if (!issue) return null;
20
21
  const type = detectIssueType(issue);
21
22
  if (type === 'Feature') return issue;
22
23
  if (type !== 'Story' && type !== 'Task') return null;
23
- let currentNodeId = issue.node_id;
24
+ let atual = issue.ref;
24
25
  for (let depth = 0; depth < 5; depth++) {
25
- const parent = await getIssueParent(token, currentNodeId);
26
+ const parent = await tracker.getParent({ ref: atual });
26
27
  if (!parent) return null;
27
28
  if (detectIssueType({ title: parent.title }) === 'Feature') {
28
- return await getIssue(token, owner, repo, parent.number).catch(() => null);
29
+ return await tracker.getWorkItem({ ref: parent.ref }).catch(() => null);
29
30
  }
30
- currentNodeId = parent.nodeId;
31
+ atual = parent.ref;
31
32
  }
32
33
  return null;
33
34
  }
34
35
 
35
- export async function qa({ prNumber, prRepo: prRepoOpt }) {
36
+ export async function qa({ prNumber, prRepo: prRepoOpt, deps = {} }) {
36
37
  const token = await resolveToken();
37
38
  const projectToken = process.env.PROJECT_TOKEN || token;
38
39
  // Mesma separação do code-review: o comando roda no hub (dono das issues) e
@@ -50,7 +51,12 @@ export async function qa({ prNumber, prRepo: prRepoOpt }) {
50
51
  const prRepo = resolvePrRepo(prRepoOpt, ctx);
51
52
  const prNum = parseInt(prNumber, 10);
52
53
 
53
- const pr = await getPR(token, prRepo.owner, prRepo.repo, prNum);
54
+ // A porta do PR é a do repositório DELE (RFC-005): `--pr-repo` pode apontar
55
+ // para um repo de código, e o número de PR colide entre repositórios.
56
+ const prScm = deps.scm ?? createGithubScm({
57
+ link: githubLink({ owner: prRepo.owner, repo: prRepo.repo, role: 'code' }), token,
58
+ });
59
+ const pr = await prScm.getPullRequest({ number: String(prNum) });
54
60
  // Mesmo parser e mesma régua do code-review: o vínculo que levou a Story a
55
61
  // 👀 Code Review é o que a leva a 🧪 QA. Antes o qa tinha um parser próprio,
56
62
  // mais frouxo (qualquer `#N`), que o code-review já havia abandonado.
@@ -66,70 +72,75 @@ export async function qa({ prNumber, prRepo: prRepoOpt }) {
66
72
  return;
67
73
  }
68
74
 
69
- const { project, error: projectError } = loadProjectConfig();
75
+ // PROJECT_TOKEN é a credencial do board; `token` segue fazendo as issues.
76
+ const { tracker, error: projectError } = openTracker({ token, projectToken, owner, repo, tracker: deps.tracker });
70
77
  if (projectError) {
71
78
  console.warn(`${projectError} — board não atualizado.`);
72
79
  return;
73
80
  }
74
81
 
75
- const etapaField = await resolveField(projectToken, project, 'Etapa').catch(() => null);
76
- const statusField = await resolveField(projectToken, project, 'Status').catch(() => null);
77
- // Repara o Work Item Type vazio de passagem (o apply nunca o escreveu).
78
- // Só preenche o vazio e nunca derruba o movimento — ver ensureWorkItemType.
79
- const typeField = await resolveField(projectToken, project, 'Work Item Type').catch(() => null);
80
-
81
82
  const seen = new Set();
82
83
  const updated = [];
83
84
 
84
85
  for (const num of issueNums) {
85
86
  // Bug é unidade própria: vai para 🧪 QA sozinho, sem arrastar a Feature-pai
86
87
  // (que pode ter Stories ainda em desenvolvimento).
87
- const issue = await getIssue(token, owner, repo, num).catch(() => null);
88
+ const issue = await tracker.getWorkItem({ ref: { key: String(num) } }).catch(() => null);
88
89
  if (issue && detectIssueType(issue) === 'Bug') {
89
- if (seen.has(issue.number)) continue;
90
- seen.add(issue.number);
90
+ if (seen.has(issue.ref.key)) continue;
91
+ seen.add(issue.ref.key);
91
92
  try {
92
- const moved = await advanceToStage(
93
- projectToken, project, etapaField, statusField, issue.node_id, QA_STAGE, TODO_STATUS,
94
- { typeField, itemType: 'Bug' });
93
+ // `itemType` repara o Work Item Type vazio de passagem — só no vazio,
94
+ // e nunca derruba o movimento (ver ensureWorkItemType).
95
+ const moved = await advanceToStage({
96
+ tracker,
97
+ ref: issue.ref,
98
+ stage: QA_STAGE, progress: TODO_STATUS, itemType: 'Bug',
99
+ });
95
100
  if (moved) {
96
- updated.push(`#${issue.number} ${issue.title} (bug)`);
97
- console.log(`Bug #${issue.number} → "${QA_STAGE}" / Status "${TODO_STATUS}".`);
101
+ updated.push(`#${issue.ref.key} ${issue.title} (bug)`);
102
+ console.log(`Bug #${issue.ref.key} → "${QA_STAGE}" / Status "${TODO_STATUS}".`);
98
103
  } else {
99
- console.log(`Bug #${issue.number} já está em "${QA_STAGE}" ou etapa posterior — mantido.`);
104
+ console.log(`Bug #${issue.ref.key} já está em "${QA_STAGE}" ou etapa posterior — mantido.`);
100
105
  }
101
106
  } catch (err) {
102
- console.warn(`Falha ao atualizar Bug #${issue.number}: ${err.message}`);
107
+ console.warn(`Falha ao atualizar Bug #${issue.ref.key}: ${err.message}`);
103
108
  }
104
109
  continue;
105
110
  }
106
111
 
107
- const feature = await resolveFeatureIssue(token, owner, repo, num);
108
- if (!feature || seen.has(feature.number)) continue;
109
- seen.add(feature.number);
112
+ const feature = await resolveFeatureIssue(tracker, num);
113
+ if (!feature || seen.has(feature.ref.key)) continue;
114
+ seen.add(feature.ref.key);
110
115
  try {
111
116
  // Avança para "🧪 QA" e reinicia o Status em "Todo" (nunca retrocede).
112
- const moved = await advanceToStage(
113
- projectToken, project, etapaField, statusField, feature.node_id, QA_STAGE, TODO_STATUS,
114
- { typeField, itemType: 'Feature' });
117
+ const moved = await advanceToStage({
118
+ tracker,
119
+ ref: feature.ref,
120
+ stage: QA_STAGE, progress: TODO_STATUS, itemType: 'Feature',
121
+ });
115
122
  if (moved) {
116
- updated.push(`#${feature.number} ${feature.title}`);
117
- console.log(`Feature #${feature.number} → "${QA_STAGE}" / Status "${TODO_STATUS}".`);
123
+ updated.push(`#${feature.ref.key} ${feature.title}`);
124
+ console.log(`Feature #${feature.ref.key} → "${QA_STAGE}" / Status "${TODO_STATUS}".`);
118
125
  } else {
119
- console.log(`Feature #${feature.number} já está em "${QA_STAGE}" ou etapa posterior — mantida (não retrocede).`);
126
+ console.log(`Feature #${feature.ref.key} já está em "${QA_STAGE}" ou etapa posterior — mantida (não retrocede).`);
120
127
  }
121
128
  } catch (err) {
122
- console.warn(`Falha ao atualizar Feature #${feature.number}: ${err.message}`);
129
+ console.warn(`Falha ao atualizar Feature #${feature.ref.key}: ${err.message}`);
123
130
  }
124
131
  }
125
132
 
126
133
  if (updated.length > 0) {
127
- await commentOnIssue(
128
- token, prRepo.owner, prRepo.repo, prNum,
129
- `🧪 **PR aprovado — QA iniciado**\n\n` +
130
- `Item(ns) movido(s) para **${QA_STAGE}**:\n\n` +
131
- updated.map(f => `- ${f}`).join('\n')
132
- ).catch(() => {});
134
+ // O comentário vai no PR, no repositório do PR — por isso um tracker
135
+ // próprio dali, e não o do hub.
136
+ await (deps.prTracker ?? createGithubTracker({ token, owner: prRepo.owner, repo: prRepo.repo }))
137
+ .addComment({
138
+ ref: { key: String(prNum) },
139
+ body:
140
+ `🧪 **PR aprovado — QA iniciado**\n\n` +
141
+ `Item(ns) movido(s) para **${QA_STAGE}**:\n\n` +
142
+ updated.map(f => `- ${f}`).join('\n'),
143
+ }).catch(() => {});
133
144
  }
134
145
 
135
146
  console.log(`qa: ${updated.length} item(ns) atualizado(s).`);