@spec-wave/cli 1.0.8 → 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 (57) hide show
  1. package/package.json +1 -1
  2. package/src/commands/audit.mjs +24 -18
  3. package/src/commands/code-review.mjs +89 -58
  4. package/src/commands/decompose.mjs +254 -218
  5. package/src/commands/generate-bug.mjs +51 -44
  6. package/src/commands/generate-plan.mjs +83 -63
  7. package/src/commands/generate-qa-plan.mjs +144 -117
  8. package/src/commands/generate-spec.mjs +33 -28
  9. package/src/commands/implement.mjs +154 -79
  10. package/src/commands/init.mjs +8 -3
  11. package/src/commands/issue.mjs +26 -39
  12. package/src/commands/merge.mjs +71 -20
  13. package/src/commands/mode.mjs +8 -4
  14. package/src/commands/move.mjs +16 -20
  15. package/src/commands/order.mjs +33 -22
  16. package/src/commands/preflight.mjs +24 -13
  17. package/src/commands/qa-lead.mjs +28 -16
  18. package/src/commands/qa-run.mjs +122 -101
  19. package/src/commands/qa.mjs +55 -44
  20. package/src/commands/refresh.mjs +24 -16
  21. package/src/commands/repair-stage.mjs +29 -16
  22. package/src/commands/repo.mjs +10 -3
  23. package/src/commands/run.mjs +23 -11
  24. package/src/commands/story.mjs +20 -25
  25. package/src/commands/task.mjs +21 -27
  26. package/src/commands/triage.mjs +33 -31
  27. package/src/commands/uninstall.mjs +7 -3
  28. package/src/commands/update.mjs +29 -21
  29. package/src/commands/validate.mjs +60 -52
  30. package/src/commands/workspace.mjs +7 -5
  31. package/src/config.mjs +7 -1
  32. package/src/lib/artifact-publish.mjs +20 -18
  33. package/src/lib/board-policy.mjs +144 -0
  34. package/src/lib/board.mjs +134 -233
  35. package/src/lib/doc-availability.mjs +10 -3
  36. package/src/lib/doc-source.mjs +9 -9
  37. package/src/lib/implement-board.mjs +23 -26
  38. package/src/lib/issue-type.mjs +5 -1
  39. package/src/lib/pr-ready.mjs +48 -10
  40. package/src/lib/pr-step.mjs +3 -1
  41. package/src/lib/qa-exec.mjs +3 -1
  42. package/src/lib/qa-lead.mjs +11 -3
  43. package/src/lib/qa-plan-doc.mjs +10 -4
  44. package/src/lib/spec-audit.mjs +1 -1
  45. package/src/lib/story-graph.mjs +62 -8
  46. package/src/lib/usage-report.mjs +8 -5
  47. package/src/lib/work-item-ref.mjs +176 -0
  48. package/src/plugin/.claude-plugin/plugin.json +1 -1
  49. package/src/plugins/scm-github/index.mjs +439 -0
  50. package/src/plugins/tracker-github-projects/fields.mjs +73 -0
  51. package/src/plugins/tracker-github-projects/index.mjs +625 -0
  52. package/src/ports/scm.mjs +197 -0
  53. package/src/ports/tracker.mjs +239 -0
  54. package/src/ports/types.mjs +254 -0
  55. package/src/setup/files.mjs +14 -12
  56. package/src/setup/labels.mjs +17 -12
  57. package/src/setup/project.mjs +40 -59
@@ -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';
@@ -63,39 +75,34 @@ class QaRefusal extends Error {
63
75
  }
64
76
  }
65
77
 
66
- async function resolveParentFeature(token, startNodeId) {
67
- let current = startNodeId;
78
+ async function resolveParentFeature(token, owner, repo, startRef) {
79
+ const tracker = trackerDe(token, owner, repo);
80
+ let current = startRef;
68
81
  for (let depth = 0; depth < 5 && current; depth++) {
69
- const parent = await getIssueParent(token, current);
82
+ const parent = await tracker.getParent({ ref: current });
70
83
  if (!parent) return null;
71
- if (detectIssueType({ title: parent.title }) === 'Feature') return parent;
72
- 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;
73
88
  }
74
89
  return null;
75
90
  }
76
91
 
77
92
  // Campos do board, resolvidos uma vez. Best-effort: sem board, os movimentos
78
93
  // viram avisos (o veredito e o relatório não dependem dele).
79
- async function resolveBoard(root, projectToken) {
80
- const { project, error } = loadProjectConfig({ cwd: root || process.cwd() });
81
- if (error || !project?.id) {
82
- return { project: null, error: error || 'Project não configurado', etapaField: null, statusField: null, typeField: null };
83
- }
84
- const etapaField = await resolveField(projectToken, project, 'Etapa').catch(() => null);
85
- const statusField = await resolveField(projectToken, project, 'Status').catch(() => null);
86
- const typeField = await resolveField(projectToken, project, 'Work Item Type').catch(() => null);
87
- const priorityField = await resolveField(projectToken, project, 'Priority').catch(() => null);
88
- 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 };
89
99
  }
90
100
 
91
- async function readStage(projectToken, board, nodeId) {
92
- if (!board.project || !board.etapaField?.id) return null;
93
- try {
94
- const itemId = await addProjectItem(projectToken, board.project.id, nodeId);
95
- return await getItemSingleSelectValue(projectToken, itemId, board.etapaField.id);
96
- } catch {
97
- return null;
98
- }
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);
99
106
  }
100
107
 
101
108
  function headShaOf(root) {
@@ -219,11 +226,15 @@ function parseOnly(only) {
219
226
  }
220
227
 
221
228
  async function trimmedComments(token, owner, repo, issueNumber, kind) {
222
- const all = await listIssueComments(token, owner, repo, issueNumber).catch(() => []);
229
+ const all = await trackerDe(token, owner, repo).listComments({ ref: { key: String(issueNumber) } }).catch(() => []);
223
230
  if (all.length === 0) return { all, groups: [] };
224
231
  const items = all.slice(-MAX_COMMENTS).map(c => ({
225
- author: c.user?.login,
226
- 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,
227
238
  body: c.body.length > MAX_COMMENT_CHARS ? `${c.body.slice(0, MAX_COMMENT_CHARS)}…[truncado]` : c.body,
228
239
  }));
229
240
  return { all, groups: [{ issueNumber, kind, total: all.length, items }] };
@@ -258,7 +269,7 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
258
269
  const token = await resolveToken();
259
270
  const projectToken = process.env.PROJECT_TOKEN || token;
260
271
 
261
- const issue = await getIssue(token, owner, repo, number);
272
+ const issue = comoItem(await trackerDe(token, owner, repo).getWorkItem({ ref: { key: String(number) } }));
262
273
  const type = detectIssueType(issue);
263
274
 
264
275
  // ── Feature dona do plano (Feature/Story) ──────────────────────────────────
@@ -269,29 +280,29 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
269
280
  labels: labelNames(issue), milestone: issue.milestone || null,
270
281
  };
271
282
  } else if (type === 'Story') {
272
- const parent = await resolveParentFeature(token, issue.node_id).catch(() => null);
283
+ const parent = await resolveParentFeature(token, owner, repo, issue.ref).catch(() => null);
273
284
  if (!parent) {
274
285
  throw new QaRefusal(
275
286
  `A Story #${number} não tem Feature-pai — o plano de QA é por Feature (D-QA1), ` +
276
287
  'e sem ela não há plano a executar. Vincule a Story como sub-issue de uma Feature.'
277
288
  );
278
289
  }
279
- const parentIssue = await getIssue(token, owner, repo, parent.number);
290
+ const parentIssue = comoItem(await trackerDe(token, owner, repo).getWorkItem({ ref: parent.ref }));
280
291
  feature = {
281
292
  number: parent.number, title: parentIssue.title, nodeId: parentIssue.node_id,
282
293
  labels: labelNames(parentIssue), milestone: parentIssue.milestone || null,
283
294
  };
284
295
  }
285
296
 
286
- // ── Etapa no board. Pulada no dry-run: a leitura passa por addProjectItem,
287
- // 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. ─────────
288
299
  const board = dryRun
289
- ? { project: null, error: 'dry-run', etapaField: null, statusField: null, typeField: null }
290
- : await resolveBoard(root, projectToken);
300
+ ? { tracker: null, error: 'dry-run' }
301
+ : await resolveBoard(root, projectToken, token, owner, repo);
291
302
  let stage = null;
292
303
  if (!dryRun) {
293
304
  if (board.error) console.warn(chalk.yellow(`⚠️ ${board.error} — Etapa não verificada e board não será atualizado.`));
294
- else stage = await readStage(projectToken, board, issue.node_id);
305
+ else stage = await readStage(board, issue.number, issue.node_id);
295
306
  } else {
296
307
  console.log(chalk.dim('Dry-run: Etapa do board não consultada (a leitura adicionaria o item ao Project).'));
297
308
  }
@@ -403,7 +414,7 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
403
414
  // Stories já aprovadas saem do alvo no modo Feature.
404
415
  let subStories = [];
405
416
  try {
406
- 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)
407
418
  .filter(s => detectIssueType({ title: s.title, labels: s.labels }) === 'Story');
408
419
  } catch (err) {
409
420
  console.warn(chalk.yellow(`⚠️ Não foi possível listar as Stories da Feature: ${err.message}.`));
@@ -451,7 +462,9 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
451
462
  const previous = parseLastQaReport(allComments);
452
463
  const run = previous.run + 1;
453
464
 
454
- 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(() => []);
455
468
 
456
469
  mkdirSync(path.join(root || process.cwd(), WORK_DIR), { recursive: true });
457
470
  const contextFile = path.join(WORK_DIR, `qa-${number}.md`);
@@ -709,14 +722,17 @@ async function postReport({
709
722
  pendingNumbers,
710
723
  trailer,
711
724
  });
712
- await commentOnIssue(token, owner, repo, number, markdown)
725
+ await trackerDe(token, owner, repo).addComment({ ref: { key: String(number) }, body: markdown })
713
726
  .catch(err => console.warn(chalk.yellow(`⚠️ Falha ao comentar o relatório: ${err.message}`)));
714
727
  }
715
728
 
716
- async function stayInQa({ projectToken, board, issue }) {
717
- if (!board.project || !board.statusField) return;
718
- await setItemStatus(projectToken, board.project, board.statusField, issue.node_id, PROGRESS_IN_PROGRESS)
719
- .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(() => {});
720
736
  }
721
737
 
722
738
  // Vermelho: um Bug por cenário reprovado — filho da STORY dona do cenário
@@ -742,7 +758,7 @@ async function openBugsForFailures({
742
758
 
743
759
  let story = null;
744
760
  try {
745
- story = await getIssue(token, owner, repo, storyNumber);
761
+ story = comoItem(await trackerDe(token, owner, repo).getWorkItem({ ref: { key: String(storyNumber) } }));
746
762
  } catch (err) {
747
763
  console.warn(chalk.yellow(`⚠️ Não consegui ler a Story #${storyNumber} (${err.message}) — Bug do cenário ${r.numero} NÃO criado.`));
748
764
  pushFailures.push({ numero: r.numero, error: `Story #${storyNumber} ilegível: ${err.message}` });
@@ -751,7 +767,7 @@ async function openBugsForFailures({
751
767
 
752
768
  // Idempotência: Bug filho ABERTO com o mesmo marcador de origem → comenta
753
769
  // nele em vez de duplicar.
754
- 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);
755
771
  const existing = children.find(c =>
756
772
  detectIssueType({ title: c.title, labels: c.labels }) === 'Bug' &&
757
773
  c.state !== 'closed' &&
@@ -761,11 +777,13 @@ async function openBugsForFailures({
761
777
  const midia = (r.evidenceFiles || []).length > 0 && evidenceBase
762
778
  ? `\n\n**Evidência visual:** ${r.evidenceFiles.map(f => `[${f.split('/').pop()}](${evidenceMediaUrl(evidenceBase.owner, evidenceBase.repo, evidenceBase.sha, f)})`).join(' · ')}`
763
779
  : '';
764
- await commentOnIssue(token, owner, repo, existing.number,
765
- `🧪 **O cenário ${scenario.numero} da Story #${storyNumber} reprovou de novo** ` +
766
- `(${headSha ? `commit \`${headSha}\`` : 'nova execução'}).\n\n` +
767
- `**Evidência:** ${r.evidencia || '(sem evidência registrada)'}${midia}`
768
- ).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(() => {});
769
787
  bugs.push({ number: existing.number, cenario: scenario.numero, existing: true });
770
788
  continue;
771
789
  }
@@ -822,7 +840,13 @@ async function openBugsForFailures({
822
840
 
823
841
  let created;
824
842
  try {
825
- 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
+ });
826
850
  } catch (err) {
827
851
  console.warn(chalk.yellow(`⚠️ Falha ao criar o Bug do cenário ${scenario.numero}: ${err.message}`));
828
852
  pushFailures.push({ numero: r.numero, error: `criação da issue falhou: ${err.message}` });
@@ -830,39 +854,40 @@ async function openBugsForFailures({
830
854
  }
831
855
  console.log(`Bug #${created.number} criado para o cenário ${scenario.numero} (filho da Story #${storyNumber}).`);
832
856
 
833
- 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 })
834
858
  .catch(err => console.warn(chalk.yellow(`⚠️ Bug #${created.number} criado, mas não vinculado à Story: ${err.message}`)));
835
859
 
836
860
  // Board: 🧪 QA achou → o Bug nasce em ✅ Ready (triagem já feita pela reprova).
837
- if (board.project && board.etapaField) {
861
+ if (board.tracker) {
862
+ const bugRef = { key: String(created.number), id: created.nodeId };
838
863
  try {
839
- await advanceToStage(
840
- projectToken, board.project, board.etapaField, board.statusField,
841
- created.nodeId, STAGE_READY, PROGRESS_TODO,
842
- { typeField: board.typeField, itemType: 'Bug' });
864
+ await advanceToStage({
865
+ tracker: board.tracker, ref: bugRef,
866
+ stage: STAGE_READY, progress: PROGRESS_TODO, itemType: 'Bug',
867
+ });
843
868
  } catch (err) {
844
869
  console.warn(chalk.yellow(`⚠️ Bug #${created.number} sem Etapa no board: ${err.message} — repare com \`spec-wave repair-stage\`.`));
845
870
  }
846
- if (board.priorityField?.options?.[severity]) {
847
- try {
848
- const itemId = await addProjectItem(projectToken, board.project.id, created.nodeId);
849
- await setItemSingleSelect(projectToken, board.project.id, itemId,
850
- board.priorityField.id, board.priorityField.options[severity]);
851
- } catch { /* prioridade no board é acessório */ }
852
- }
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);
853
876
  }
854
877
 
855
878
  // `bug-approved` direto: reprodução, esperado/obtido e regressão são a
856
879
  // execução observada — regerar por IA só introduziria alucinação.
857
- await addLabel(token, owner, repo, created.number, LABEL_BUG_APPROVED).catch(() => {});
858
-
859
- await commentOnIssue(token, owner, repo, created.number,
860
- `🧪 **Bug aberto pela reprovação de QA** — ${scenario.anchor} da Story #${storyNumber}.\n\n` +
861
- `📄 \`${fileRel}\` foi escrito, commitado e publicado com as seis seções preenchidas a partir ` +
862
- 'do cenário e da saída real da execução (exceção documentada à regra do `spec-wave:bug` — ' +
863
- 'conteúdo determinístico de uma execução observada, sem IA).\n\n' +
864
- `Após o fix, re-teste: \`npx ${cliRef()} qa ${storyNumber} --only ${scenario.numero}\``
865
- ).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(() => {});
866
891
 
867
892
  bugs.push({ number: created.number, cenario: scenario.numero, existing: false });
868
893
  }
@@ -875,19 +900,18 @@ async function applyGreen({
875
900
  token, projectToken, owner, repo, board, issue, number, type, feature, combined, byNumero,
876
901
  featureStories = [],
877
902
  }) {
878
- const move = async (nodeId, targetStage, itemType) => {
879
- if (!board.project || !board.etapaField) return false;
880
- return await advanceToStage(
881
- projectToken, board.project, board.etapaField, board.statusField,
882
- nodeId, targetStage, PROGRESS_TODO,
883
- { 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
+ });
884
908
  };
885
909
 
886
910
  if (type === 'Bug') {
887
- 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(() => {});
888
912
  const target = greenTargetStage('Bug');
889
913
  try {
890
- await move(issue.node_id, target, 'Bug');
914
+ await move(issue.ref, target, 'Bug');
891
915
  console.log(`Bug #${number} → "${target}" (D-QA6: Bug não passa por Homologação).`);
892
916
  } catch (err) {
893
917
  console.warn(chalk.yellow(`⚠️ Falha ao mover o Bug no board: ${err.message}`));
@@ -896,7 +920,7 @@ async function applyGreen({
896
920
  }
897
921
 
898
922
  if (type === 'Story') {
899
- const children = (await listSubIssues(token, issue.node_id).catch(() => []))
923
+ const children = ((await trackerDe(token, owner, repo).listChildren({ ref: issue.ref }).catch(() => [])).map(comoItem))
900
924
  .map(c => ({ ...c, type: detectIssueType({ title: c.title, labels: c.labels }) }));
901
925
  const guard = storyCanAdvance({ children });
902
926
  if (!guard.ok) {
@@ -909,9 +933,9 @@ async function applyGreen({
909
933
  'e rode o `qa` de novo.',
910
934
  };
911
935
  }
912
- 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(() => {});
913
937
  try {
914
- await move(issue.node_id, STAGE_UAT, 'Story');
938
+ await move(issue.ref, STAGE_UAT, 'Story');
915
939
  console.log(`Story #${number} → "${STAGE_UAT}" / Status "${PROGRESS_TODO}".`);
916
940
  } catch (err) {
917
941
  console.warn(chalk.yellow(`⚠️ Falha ao mover a Story no board: ${err.message}`));
@@ -941,16 +965,16 @@ async function applyGreen({
941
965
  const daStory = combined.filter(r => byNumero.get(r.numero)?.story === story.number);
942
966
  if (daStory.length === 0) continue;
943
967
  if (!daStory.every(r => r.verdict === 'pass')) continue;
944
- 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))
945
969
  .map(c => ({ ...c, type: detectIssueType({ title: c.title, labels: c.labels }) }));
946
970
  const guard = storyCanAdvance({ children });
947
971
  if (!guard.ok) {
948
972
  console.log(chalk.yellow(`Story #${story.number} verde, mas com Bug aberto (${guard.openBugs.map(n => `#${n}`).join(', ')}) — não avança.`));
949
973
  continue;
950
974
  }
951
- 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(() => {});
952
976
  try {
953
- await move(story.nodeId, STAGE_UAT, 'Story');
977
+ await move(story.ref ?? { key: String(story.number), id: story.nodeId }, STAGE_UAT, 'Story');
954
978
  console.log(`Story #${story.number} → "${STAGE_UAT}".`);
955
979
  } catch (err) {
956
980
  console.warn(chalk.yellow(`⚠️ Falha ao mover a Story #${story.number}: ${err.message}`));
@@ -978,7 +1002,7 @@ async function maybeAdvanceFeature({ token, projectToken, owner, repo, board, fe
978
1002
  const aprovadas = new Set(Array.isArray(justApproved) ? justApproved : [justApproved]);
979
1003
  let stories = [];
980
1004
  try {
981
- 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))
982
1006
  .filter(s => detectIssueType({ title: s.title, labels: s.labels }) === 'Story');
983
1007
  } catch {
984
1008
  return false; // sem a lista, na dúvida a Feature não avança
@@ -987,11 +1011,8 @@ async function maybeAdvanceFeature({ token, projectToken, owner, repo, board, fe
987
1011
  for (const s of stories) {
988
1012
  const labels = aprovadas.has(s.number) ? [...(s.labels || []), LABEL_QA_APPROVED] : (s.labels || []);
989
1013
  let stage = null;
990
- if (!labelNames(labels).includes(LABEL_QA_APPROVED) && board.project && board.etapaField) {
991
- try {
992
- const itemId = await addProjectItem(projectToken, board.project.id, s.nodeId);
993
- stage = await getItemSingleSelectValue(projectToken, itemId, board.etapaField.id);
994
- } catch { stage = null; }
1014
+ if (!labelNames(labels).includes(LABEL_QA_APPROVED) && board.tracker) {
1015
+ stage = await readStage(board, s.number, s.nodeId);
995
1016
  }
996
1017
  enriched.push({ number: s.number, labels, stage });
997
1018
  }
@@ -1002,9 +1023,9 @@ async function maybeAdvanceFeature({ token, projectToken, owner, repo, board, fe
1002
1023
  }
1003
1024
  return false;
1004
1025
  }
1005
- 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(() => {});
1006
1027
  try {
1007
- await move(feature.nodeId, STAGE_UAT, 'Feature');
1028
+ await move(feature.ref ?? { key: String(feature.number), id: feature.nodeId }, STAGE_UAT, 'Feature');
1008
1029
  console.log(`Feature #${feature.number} → "${STAGE_UAT}".`);
1009
1030
  return true;
1010
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).`);