@spec-wave/cli 1.4.0 → 1.6.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/protocol/scm.v1.json +165 -0
  3. package/protocol/tracker.v1.json +175 -0
  4. package/src/api/github-rest.mjs +124 -2
  5. package/src/commands/audit.mjs +3 -5
  6. package/src/commands/code-review.mjs +10 -6
  7. package/src/commands/decompose.mjs +7 -6
  8. package/src/commands/doctor.mjs +389 -220
  9. package/src/commands/generate-bug.mjs +2 -2
  10. package/src/commands/generate-plan.mjs +5 -7
  11. package/src/commands/generate-qa-plan.mjs +3 -5
  12. package/src/commands/generate-spec.mjs +2 -2
  13. package/src/commands/implement.mjs +33 -21
  14. package/src/commands/init.mjs +36 -7
  15. package/src/commands/issue.mjs +6 -2
  16. package/src/commands/merge.mjs +20 -15
  17. package/src/commands/mode.mjs +18 -11
  18. package/src/commands/move.mjs +3 -3
  19. package/src/commands/order.mjs +3 -3
  20. package/src/commands/preflight.mjs +10 -6
  21. package/src/commands/qa-lead.mjs +6 -8
  22. package/src/commands/qa-run.mjs +39 -27
  23. package/src/commands/qa.mjs +10 -7
  24. package/src/commands/refresh.mjs +6 -3
  25. package/src/commands/repair-stage.mjs +1 -1
  26. package/src/commands/repo.mjs +6 -7
  27. package/src/commands/run.mjs +7 -5
  28. package/src/commands/story.mjs +3 -3
  29. package/src/commands/task.mjs +3 -3
  30. package/src/commands/triage.mjs +3 -3
  31. package/src/commands/uninstall.mjs +14 -6
  32. package/src/commands/update.mjs +47 -20
  33. package/src/commands/validate.mjs +3 -5
  34. package/src/commands/workspace.mjs +2 -2
  35. package/src/lib/artifact-publish.mjs +3 -3
  36. package/src/lib/board.mjs +22 -24
  37. package/src/lib/config-ports.mjs +114 -0
  38. package/src/lib/doc-source.mjs +16 -3
  39. package/src/lib/doctor-capabilities.mjs +168 -0
  40. package/src/lib/implement-board.mjs +1 -1
  41. package/src/lib/pr-ready.mjs +23 -11
  42. package/src/lib/story-graph.mjs +19 -6
  43. package/src/lib/tag-registry.mjs +58 -0
  44. package/src/lib/usage-report.mjs +15 -2
  45. package/src/plugin/.claude-plugin/plugin.json +1 -1
  46. package/src/plugins/load.mjs +427 -0
  47. package/src/plugins/scm-github/index.mjs +92 -6
  48. package/src/plugins/tracker-github-projects/index.mjs +52 -10
  49. package/src/ports/capabilities.mjs +47 -0
  50. package/src/ports/index.mjs +201 -46
  51. package/src/ports/scm.mjs +71 -3
  52. package/src/ports/tracker.mjs +43 -2
  53. package/src/ports/types.mjs +30 -6
  54. package/src/setup/files.mjs +2 -3
  55. package/src/setup/labels.mjs +2 -2
  56. package/src/setup/project.mjs +2 -2
  57. package/src/ui/wizard.mjs +76 -1
@@ -20,9 +20,7 @@ import * as p from '@clack/prompts';
20
20
  import chalk from 'chalk';
21
21
 
22
22
  import { resolveToken } from '../api/auth.mjs';
23
- import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
24
- import { createGithubScm } from '../plugins/scm-github/index.mjs';
25
- import { resolveScmLink } from '../ports/index.mjs';
23
+ import { requireScm, requireTracker, resolveScmLink } from '../ports/index.mjs';
26
24
  import { CONFIG_FILE } from '../config.mjs';
27
25
  import { inspectPrPublishing, readPrPublishingContext } from './doctor.mjs';
28
26
  import { configuredMode, describeModeState, EXECUTION_VARIABLE } from '../lib/execution-mode.mjs';
@@ -199,8 +197,8 @@ export async function preflight({ milestone: milestoneArg, json = false, deps =
199
197
  return falhar(`Sem token utilizável para ${owner}/${repo}: ${err.message}`);
200
198
  }
201
199
 
202
- const tracker = deps.tracker ?? createGithubTracker({ token, owner, repo });
203
- const scm = deps.scm ?? createGithubScm({ link: resolveScmLink({ owner, repo }), token });
200
+ const tracker = await requireTracker({ token, owner, repo, deps });
201
+ const scm = await requireScm({ link: resolveScmLink({ owner, repo }), token, deps });
204
202
 
205
203
  const s = json ? null : p.spinner();
206
204
  s?.start('Consultando o repositório...');
@@ -227,8 +225,14 @@ export async function preflight({ milestone: milestoneArg, json = false, deps =
227
225
  });
228
226
 
229
227
  // --- Publicação por Pull Request: é o desfecho de toda geração.
228
+ // `deep: true` traz os fatos de automação (secrets, permissão de workflow,
229
+ // proteção de branch) que `inspectPrPublishing` julga. `null` quando a
230
+ // verificação falha: os três viram "não consegui olhar", nunca "está errado".
230
231
  const publicacao = inspectPrPublishing(
231
- await readPrPublishingContext({ token, owner, repo, root })
232
+ readPrPublishingContext({
233
+ verificacao: await scm.verify({ deep: true }).catch(() => null),
234
+ root,
235
+ })
232
236
  );
233
237
 
234
238
  // --- Inventário da milestone.
@@ -23,13 +23,11 @@ import { setTimeout as sleep } from 'node:timers/promises';
23
23
  import chalk from 'chalk';
24
24
 
25
25
  import { resolveToken } from '../api/auth.mjs';
26
- import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
26
+ import { requireTracker } from '../ports/index.mjs';
27
27
  import { detectIssueType } from '../lib/issue-type.mjs';
28
28
  import { loadConfig, findConfigPath } from '../lib/project-root.mjs';
29
29
  import { loadProjectConfig } from '../lib/board.mjs';
30
30
 
31
- /** Porta de tracker do hub — este comando trabalha por TRILHA, sempre no hub. */
32
- const trackerDe = (token, owner, repo) => createGithubTracker({ token, owner, repo });
33
31
  import { featureDocPaths } from '../lib/doc-paths.mjs';
34
32
  import { orderStories } from '../lib/dependencies.mjs';
35
33
  import { loadFeatureStories, loadBoardSnapshot } from '../lib/story-graph.mjs';
@@ -66,10 +64,10 @@ class QaLeadRefusal extends Error {
66
64
  * @param {object} [params.deps] seam de teste — `tracker`, `exec` (no lugar de
67
65
  * `execSync`) e `push` (no lugar de `pushWithRebase`).
68
66
  *
69
- * `trackerDe` é const de topo de módulo, chamada em dez lugares de cinco
70
- * funções. Em vez de levar o `deps` às cinco, o `bootstrap` — que já é o ponto
71
- * único onde token/owner/repo são resolvidos — passa a devolver a PORTA, e os
72
- * dez call sites viram leitura de variável.
67
+ * O `bootstrap` é o ponto único onde token/owner/repo são resolvidos, e é ele
68
+ * que devolve a PORTA — os dez call sites são leitura de variável. Foi essa
69
+ * forma que tornou a leva 4 do bloco E uma troca de UMA linha aqui: a fábrica
70
+ * de topo de módulo já não era consultada em dez lugares.
73
71
  */
74
72
  export async function qaLead({ action, milestone: milestoneArg, ...options }) {
75
73
  const acoes = { plan: qaLeadPlan, run: qaLeadRun, report: qaLeadReport };
@@ -100,7 +98,7 @@ async function bootstrap(milestoneArg, deps = {}) {
100
98
  }
101
99
  const token = await resolveToken();
102
100
 
103
- const tracker = deps.tracker ?? trackerDe(token, owner, repo);
101
+ const tracker = await requireTracker({ token, owner, repo, deps });
104
102
  const milestones = await tracker.listMilestones();
105
103
  const resolved = resolveMilestoneRef(milestones, milestoneArg);
106
104
  if (resolved.error) throw new QaLeadRefusal(resolved.error);
@@ -19,13 +19,9 @@ import path from 'node:path';
19
19
  import chalk from 'chalk';
20
20
 
21
21
  import { resolveToken } from '../api/auth.mjs';
22
- import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
23
- import { createGithubScm } from '../plugins/scm-github/index.mjs';
24
- import { resolveScmLink } from '../ports/index.mjs';
22
+ import { requireScm, requireTracker, resolveScmLink } from '../ports/index.mjs';
25
23
 
26
24
  /** Portas do hub — o QA roda sempre contra o repositório das issues. */
27
- const trackerDe = (token, owner, repo) => createGithubTracker({ token, owner, repo });
28
- const scmDe = (token, owner, repo) => createGithubScm({ link: resolveScmLink({ owner, repo }), token });
29
25
 
30
26
  /** WorkItem → a forma `{number, nodeId, title, labels}` que este arquivo usa. */
31
27
  const comoItem = w => w && ({
@@ -77,7 +73,7 @@ class QaRefusal extends Error {
77
73
  }
78
74
 
79
75
  async function resolveParentFeature(token, owner, repo, startRef, deps = {}) {
80
- const tracker = deps.tracker ?? (deps.tracker ?? trackerDe(token, owner, repo));
76
+ const tracker = deps.tracker ?? deps.tracker;
81
77
  let current = startRef;
82
78
  for (let depth = 0; depth < 5 && current; depth++) {
83
79
  const parent = await tracker.getParent({ ref: current });
@@ -93,7 +89,7 @@ async function resolveParentFeature(token, owner, repo, startRef, deps = {}) {
93
89
  // Campos do board, resolvidos uma vez. Best-effort: sem board, os movimentos
94
90
  // viram avisos (o veredito e o relatório não dependem dele).
95
91
  async function resolveBoard(root, projectToken, token, owner, repo, deps = {}) {
96
- const { tracker, error } = openTracker({
92
+ const { tracker, error } = await openTracker({
97
93
  token, projectToken, owner, repo, cwd: root || process.cwd(), tracker: deps.tracker,
98
94
  });
99
95
  return { tracker, error: error || null };
@@ -227,7 +223,7 @@ function parseOnly(only) {
227
223
  }
228
224
 
229
225
  async function trimmedComments(token, owner, repo, issueNumber, kind, deps = {}) {
230
- const all = await (deps.tracker ?? (deps.tracker ?? trackerDe(token, owner, repo))).listComments({ ref: { key: String(issueNumber) } }).catch(() => []);
226
+ const all = await deps.tracker.listComments({ ref: { key: String(issueNumber) } }).catch(() => []);
231
227
  if (all.length === 0) return { all, groups: [] };
232
228
  const items = all.slice(-MAX_COMMENTS).map(c => ({
233
229
  // Formas do contrato (`author`, `createdAt`) primeiro, REST crua depois.
@@ -281,7 +277,17 @@ export async function qaRun({
281
277
  const token = await resolveToken();
282
278
  const projectToken = process.env.PROJECT_TOKEN || token;
283
279
 
284
- const issue = comoItem(await (deps.tracker ?? trackerDe(token, owner, repo)).getWorkItem({ ref: { key: String(number) } }));
280
+ // Bloco E, leva 4: a porta do hub é resolvida UMA vez e viaja no `deps`, que já
281
+ // era o caminho dela para as 21 chamadas espalhadas por sete funções — o
282
+ // `outcome` a espalha nas três de escrita. Resolver por site custaria 21
283
+ // leituras de config (`loadConfig` não cacheia) para uma porta que é única.
284
+ //
285
+ // `projectToken` NÃO entra aqui: esta é a porta de ISSUE. A do board sai do
286
+ // `openTracker`, que é quem leva a credencial de Projects v2 — promovê-la aqui
287
+ // daria 403 num PAT com escopo `project` e sem `repo`, que nenhum teste vê.
288
+ deps = { ...deps, tracker: await requireTracker({ token, owner, repo, deps }) };
289
+
290
+ const issue = comoItem(await deps.tracker.getWorkItem({ ref: { key: String(number) } }));
285
291
  const type = detectIssueType(issue);
286
292
 
287
293
  // ── Feature dona do plano (Feature/Story) ──────────────────────────────────
@@ -299,7 +305,7 @@ export async function qaRun({
299
305
  'e sem ela não há plano a executar. Vincule a Story como sub-issue de uma Feature.'
300
306
  );
301
307
  }
302
- const parentIssue = comoItem(await (deps.tracker ?? trackerDe(token, owner, repo)).getWorkItem({ ref: parent.ref }));
308
+ const parentIssue = comoItem(await deps.tracker.getWorkItem({ ref: parent.ref }));
303
309
  feature = {
304
310
  number: parent.number, title: parentIssue.title, nodeId: parentIssue.node_id,
305
311
  labels: labelNames(parentIssue), milestone: parentIssue.milestone || null,
@@ -428,7 +434,7 @@ export async function qaRun({
428
434
  // Stories já aprovadas saem do alvo no modo Feature.
429
435
  let subStories = [];
430
436
  try {
431
- subStories = (await (deps.tracker ?? trackerDe(token, owner, repo)).listChildren({ ref: feature.ref ?? { key: String(feature.number), id: feature.nodeId } })).map(comoItem)
437
+ subStories = (await deps.tracker.listChildren({ ref: feature.ref ?? { key: String(feature.number), id: feature.nodeId } })).map(comoItem)
432
438
  .filter(s => detectIssueType({ title: s.title, labels: s.labels }) === 'Story');
433
439
  } catch (err) {
434
440
  console.warn(chalk.yellow(`⚠️ Não foi possível listar as Stories da Feature: ${err.message}.`));
@@ -476,7 +482,13 @@ export async function qaRun({
476
482
  const previous = parseLastQaReport(allComments);
477
483
  const run = previous.run + 1;
478
484
 
479
- const pullRequests = await (deps.scm ?? scmDe(token, owner, repo))
485
+ // A porta em UMA linha e a chamada em outra, de propósito. `await requireScm(…)
486
+ // .findPullRequestsReferencing(…)` chamaria o método na PROMESSA — `undefined`,
487
+ // `TypeError` sincrônico, e o `.catch(() => [])` abaixo não o pega, porque só
488
+ // existe depois de haver promessa. O sintoma foi a lista de PRs vazia, e o que
489
+ // o denunciou foi o teste que afirma que o EXECUTOR foi invocado.
490
+ const scmHub = await requireScm({ link: resolveScmLink({ owner, repo }), token, deps });
491
+ const pullRequests = await scmHub
480
492
  .findPullRequestsReferencing({ ref: issue.ref ?? { key: String(issue.number), id: issue.node_id } })
481
493
  .catch(() => []);
482
494
 
@@ -737,7 +749,7 @@ async function postReport({
737
749
  pendingNumbers,
738
750
  trailer,
739
751
  });
740
- await (deps.tracker ?? trackerDe(token, owner, repo)).addComment({ ref: { key: String(number) }, body: markdown })
752
+ await deps.tracker.addComment({ ref: { key: String(number) }, body: markdown })
741
753
  .catch(err => console.warn(chalk.yellow(`⚠️ Falha ao comentar o relatório: ${err.message}`)));
742
754
  }
743
755
 
@@ -773,7 +785,7 @@ async function openBugsForFailures({
773
785
 
774
786
  let story = null;
775
787
  try {
776
- story = comoItem(await (deps.tracker ?? trackerDe(token, owner, repo)).getWorkItem({ ref: { key: String(storyNumber) } }));
788
+ story = comoItem(await deps.tracker.getWorkItem({ ref: { key: String(storyNumber) } }));
777
789
  } catch (err) {
778
790
  console.warn(chalk.yellow(`⚠️ Não consegui ler a Story #${storyNumber} (${err.message}) — Bug do cenário ${r.numero} NÃO criado.`));
779
791
  pushFailures.push({ numero: r.numero, error: `Story #${storyNumber} ilegível: ${err.message}` });
@@ -782,7 +794,7 @@ async function openBugsForFailures({
782
794
 
783
795
  // Idempotência: Bug filho ABERTO com o mesmo marcador de origem → comenta
784
796
  // nele em vez de duplicar.
785
- const children = (await (deps.tracker ?? trackerDe(token, owner, repo)).listChildren({ ref: story.ref ?? { key: String(story.number), id: story.node_id } }).catch(() => [])).map(comoItem);
797
+ const children = (await deps.tracker.listChildren({ ref: story.ref ?? { key: String(story.number), id: story.node_id } }).catch(() => [])).map(comoItem);
786
798
  const existing = children.find(c =>
787
799
  detectIssueType({ title: c.title, labels: c.labels }) === 'Bug' &&
788
800
  c.state !== 'closed' &&
@@ -792,7 +804,7 @@ async function openBugsForFailures({
792
804
  const midia = (r.evidenceFiles || []).length > 0 && evidenceBase
793
805
  ? `\n\n**Evidência visual:** ${r.evidenceFiles.map(f => `[${f.split('/').pop()}](${evidenceMediaUrl(evidenceBase.owner, evidenceBase.repo, evidenceBase.sha, f)})`).join(' · ')}`
794
806
  : '';
795
- await (deps.tracker ?? trackerDe(token, owner, repo)).addComment({
807
+ await deps.tracker.addComment({
796
808
  ref: { key: String(existing.number) },
797
809
  body:
798
810
  `🧪 **O cenário ${scenario.numero} da Story #${storyNumber} reprovou de novo** ` +
@@ -857,7 +869,7 @@ async function openBugsForFailures({
857
869
  let created;
858
870
  try {
859
871
  created = comoItem({
860
- ref: await (deps.tracker ?? trackerDe(token, owner, repo)).createWorkItem({
872
+ ref: await deps.tracker.createWorkItem({
861
873
  title, body: bodyLines.join('\n'), type: 'Bug', tags: labels,
862
874
  milestone: milestone ? { key: String(milestone) } : null,
863
875
  }),
@@ -870,7 +882,7 @@ async function openBugsForFailures({
870
882
  }
871
883
  console.log(`Bug #${created.number} criado para o cenário ${scenario.numero} (filho da Story #${storyNumber}).`);
872
884
 
873
- await (deps.tracker ?? trackerDe(token, owner, repo)).addChild({ parent: story.ref ?? { key: String(story.number), id: story.node_id }, child: created.ref })
885
+ await deps.tracker.addChild({ parent: story.ref ?? { key: String(story.number), id: story.node_id }, child: created.ref })
874
886
  .catch(err => console.warn(chalk.yellow(`⚠️ Bug #${created.number} criado, mas não vinculado à Story: ${err.message}`)));
875
887
 
876
888
  // Board: 🧪 QA achou → o Bug nasce em ✅ Ready (triagem já feita pela reprova).
@@ -893,9 +905,9 @@ async function openBugsForFailures({
893
905
 
894
906
  // `bug-approved` direto: reprodução, esperado/obtido e regressão são a
895
907
  // execução observada — regerar por IA só introduziria alucinação.
896
- await (deps.tracker ?? trackerDe(token, owner, repo)).addTag({ ref: { key: String(created.number) }, tag: LABEL_BUG_APPROVED }).catch(() => {});
908
+ await deps.tracker.addTag({ ref: { key: String(created.number) }, tag: LABEL_BUG_APPROVED }).catch(() => {});
897
909
 
898
- await (deps.tracker ?? trackerDe(token, owner, repo)).addComment({
910
+ await deps.tracker.addComment({
899
911
  ref: { key: String(created.number) },
900
912
  body:
901
913
  `🧪 **Bug aberto pela reprovação de QA** — ${scenario.anchor} da Story #${storyNumber}.\n\n` +
@@ -924,7 +936,7 @@ async function applyGreen({
924
936
  };
925
937
 
926
938
  if (type === 'Bug') {
927
- await (deps.tracker ?? trackerDe(token, owner, repo)).addTag({ ref: { key: String(number) }, tag: LABEL_QA_APPROVED }).catch(() => {});
939
+ await deps.tracker.addTag({ ref: { key: String(number) }, tag: LABEL_QA_APPROVED }).catch(() => {});
928
940
  const target = greenTargetStage('Bug');
929
941
  try {
930
942
  await move(issue.ref, target, 'Bug');
@@ -936,7 +948,7 @@ async function applyGreen({
936
948
  }
937
949
 
938
950
  if (type === 'Story') {
939
- const children = ((await (deps.tracker ?? trackerDe(token, owner, repo)).listChildren({ ref: issue.ref }).catch(() => [])).map(comoItem))
951
+ const children = ((await deps.tracker.listChildren({ ref: issue.ref }).catch(() => [])).map(comoItem))
940
952
  .map(c => ({ ...c, type: detectIssueType({ title: c.title, labels: c.labels }) }));
941
953
  const guard = storyCanAdvance({ children });
942
954
  if (!guard.ok) {
@@ -949,7 +961,7 @@ async function applyGreen({
949
961
  'e rode o `qa` de novo.',
950
962
  };
951
963
  }
952
- await (deps.tracker ?? trackerDe(token, owner, repo)).addTag({ ref: { key: String(number) }, tag: LABEL_QA_APPROVED }).catch(() => {});
964
+ await deps.tracker.addTag({ ref: { key: String(number) }, tag: LABEL_QA_APPROVED }).catch(() => {});
953
965
  try {
954
966
  await move(issue.ref, STAGE_UAT, 'Story');
955
967
  console.log(`Story #${number} → "${STAGE_UAT}" / Status "${PROGRESS_TODO}".`);
@@ -981,14 +993,14 @@ async function applyGreen({
981
993
  const daStory = combined.filter(r => byNumero.get(r.numero)?.story === story.number);
982
994
  if (daStory.length === 0) continue;
983
995
  if (!daStory.every(r => r.verdict === 'pass')) continue;
984
- const children = ((await (deps.tracker ?? trackerDe(token, owner, repo)).listChildren({ ref: story.ref ?? { key: String(story.number), id: story.nodeId } }).catch(() => [])).map(comoItem))
996
+ const children = ((await deps.tracker.listChildren({ ref: story.ref ?? { key: String(story.number), id: story.nodeId } }).catch(() => [])).map(comoItem))
985
997
  .map(c => ({ ...c, type: detectIssueType({ title: c.title, labels: c.labels }) }));
986
998
  const guard = storyCanAdvance({ children });
987
999
  if (!guard.ok) {
988
1000
  console.log(chalk.yellow(`Story #${story.number} verde, mas com Bug aberto (${guard.openBugs.map(n => `#${n}`).join(', ')}) — não avança.`));
989
1001
  continue;
990
1002
  }
991
- await (deps.tracker ?? trackerDe(token, owner, repo)).addTag({ ref: { key: String(story.number) }, tag: LABEL_QA_APPROVED }).catch(() => {});
1003
+ await deps.tracker.addTag({ ref: { key: String(story.number) }, tag: LABEL_QA_APPROVED }).catch(() => {});
992
1004
  try {
993
1005
  await move(story.ref ?? { key: String(story.number), id: story.nodeId }, STAGE_UAT, 'Story');
994
1006
  console.log(`Story #${story.number} → "${STAGE_UAT}".`);
@@ -1018,7 +1030,7 @@ async function maybeAdvanceFeature({ token, projectToken, owner, repo, board, fe
1018
1030
  const aprovadas = new Set(Array.isArray(justApproved) ? justApproved : [justApproved]);
1019
1031
  let stories = [];
1020
1032
  try {
1021
- stories = ((await (deps.tracker ?? trackerDe(token, owner, repo)).listChildren({ ref: feature.ref ?? { key: String(feature.number), id: feature.nodeId } })).map(comoItem))
1033
+ stories = ((await deps.tracker.listChildren({ ref: feature.ref ?? { key: String(feature.number), id: feature.nodeId } })).map(comoItem))
1022
1034
  .filter(s => detectIssueType({ title: s.title, labels: s.labels }) === 'Story');
1023
1035
  } catch {
1024
1036
  return false; // sem a lista, na dúvida a Feature não avança
@@ -1039,7 +1051,7 @@ async function maybeAdvanceFeature({ token, projectToken, owner, repo, board, fe
1039
1051
  }
1040
1052
  return false;
1041
1053
  }
1042
- await (deps.tracker ?? trackerDe(token, owner, repo)).addTag({ ref: { key: String(feature.number) }, tag: LABEL_QA_APPROVED }).catch(() => {});
1054
+ await deps.tracker.addTag({ ref: { key: String(feature.number) }, tag: LABEL_QA_APPROVED }).catch(() => {});
1043
1055
  try {
1044
1056
  await move(feature.ref ?? { key: String(feature.number), id: feature.nodeId }, STAGE_UAT, 'Feature');
1045
1057
  console.log(`Feature #${feature.number} → "${STAGE_UAT}".`);
@@ -1,7 +1,5 @@
1
1
  import { resolveToken } from '../api/auth.mjs';
2
- import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
3
- import { createGithubScm } from '../plugins/scm-github/index.mjs';
4
- import { resolveScmLink } from '../ports/index.mjs';
2
+ import { requireScm, requireTracker, resolveScmLink } from '../ports/index.mjs';
5
3
  import { detectIssueType } from '../lib/issue-type.mjs';
6
4
  import { openTracker, advanceToStage } from '../lib/board.mjs';
7
5
  import { resolveHubContext, resolvePrRepo } from '../lib/project-root.mjs';
@@ -54,8 +52,8 @@ export async function qa({ prNumber, prRepo: prRepoOpt, deps = {} }) {
54
52
 
55
53
  // A porta do PR é a do repositório DELE (RFC-005): `--pr-repo` pode apontar
56
54
  // para um repo de código, e o número de PR colide entre repositórios.
57
- const prScm = deps.scm ?? createGithubScm({
58
- link: resolveScmLink({ owner: prRepo.owner, repo: prRepo.repo, role: 'code' }), token,
55
+ const prScm = await requireScm({
56
+ link: resolveScmLink({ owner: prRepo.owner, repo: prRepo.repo, role: 'code' }), token, deps,
59
57
  });
60
58
  const pr = await prScm.getPullRequest({ number: String(prNum) });
61
59
  // Mesmo parser e mesma régua do code-review: o vínculo que levou a Story a
@@ -74,7 +72,7 @@ export async function qa({ prNumber, prRepo: prRepoOpt, deps = {} }) {
74
72
  }
75
73
 
76
74
  // PROJECT_TOKEN é a credencial do board; `token` segue fazendo as issues.
77
- const { tracker, error: projectError } = openTracker({ token, projectToken, owner, repo, tracker: deps.tracker });
75
+ const { tracker, error: projectError } = await openTracker({ token, projectToken, owner, repo, tracker: deps.tracker });
78
76
  if (projectError) {
79
77
  console.warn(`${projectError} — board não atualizado.`);
80
78
  return;
@@ -134,7 +132,12 @@ export async function qa({ prNumber, prRepo: prRepoOpt, deps = {} }) {
134
132
  if (updated.length > 0) {
135
133
  // O comentário vai no PR, no repositório do PR — por isso um tracker
136
134
  // próprio dali, e não o do hub.
137
- await (deps.prTracker ?? createGithubTracker({ token, owner: prRepo.owner, repo: prRepo.repo }))
135
+ // `deps.prTracker` e NÃO `deps.tracker`: o PR #77 do repo de código não é a
136
+ // issue #77 do hub. A porta do PR entra pelo seam próprio mesmo passando pelo
137
+ // loader — sem fallback, que é o que o `.catch` do call site esconderia.
138
+ await (await requireTracker({
139
+ token, owner: prRepo.owner, repo: prRepo.repo, deps: { tracker: deps.prTracker },
140
+ }))
138
141
  .addComment({
139
142
  ref: { key: String(prNum) },
140
143
  body:
@@ -4,9 +4,9 @@ import { readFileSync, writeFileSync } from 'node:fs';
4
4
  import { resolveToken } from '../api/auth.mjs';
5
5
  import { CONFIG_FILE, STATUS_OPTIONS } from '../config.mjs';
6
6
  import { findConfigPath } from '../lib/project-root.mjs';
7
- import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
8
7
  // Trata o escape de empacotamento (SPEC_WAVE_CLI_VERSION) — ver lib/templates.mjs.
9
8
  import { CLI_VERSION } from '../lib/templates.mjs';
9
+ import { requireTracker } from '../ports/index.mjs';
10
10
 
11
11
  /**
12
12
  * Plano de sincronização das opções do campo "Etapa" (função PURA).
@@ -204,8 +204,11 @@ export async function refresh(options = {}) {
204
204
 
205
205
  p.intro(chalk.bold(`spec-wave refresh${options.stages ? ' --stages' : ' --config'}`));
206
206
 
207
- const tracker = createGithubTracker({
208
- token, owner: config.owner, repo: config.repo, project: config.project,
207
+ // `board: true`: o `refresh` LÊ o schema do board para regravar os ids. Sem o
208
+ // bloco `project` não há o que ler, e a mensagem que manda rodar o `init` é
209
+ // melhor que um `setup({provision:false})` devolvendo vazio.
210
+ const tracker = await requireTracker({
211
+ token, owner: config.owner, repo: config.repo, board: true,
209
212
  });
210
213
  const leSchema = async () => {
211
214
  // `provision: false` é leitura: devolve o bloco de config que descreve o
@@ -152,7 +152,7 @@ export async function repairStage(issuesArg, stageArg, options = {}) {
152
152
  `spec-wave repair-stage ${numbers.map(n => `#${n}`).join(', ')} → ${stage}${options.dryRun ? ' (dry-run)' : ''}`
153
153
  ));
154
154
 
155
- const { tracker, error: projectError } = openTracker({ token, owner, repo, cwd: root || process.cwd(), tracker: options.deps?.tracker });
155
+ const { tracker, error: projectError } = await openTracker({ token, owner, repo, cwd: root || process.cwd(), tracker: options.deps?.tracker });
156
156
  if (projectError) {
157
157
  p.log.error(`${projectError} — nada a reparar. Rode \`spec-wave init\` (ou \`spec-wave refresh --config\`).`);
158
158
  process.exitCode = 1;
@@ -7,9 +7,7 @@
7
7
  import * as p from '@clack/prompts';
8
8
  import chalk from 'chalk';
9
9
  import { resolveToken } from '../api/auth.mjs';
10
- import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
11
- import { createGithubScm } from '../plugins/scm-github/index.mjs';
12
- import { resolveScmLink } from '../ports/index.mjs';
10
+ import { requireScm, requireTracker, resolveScmLink } from '../ports/index.mjs';
13
11
  import { resolveHubContext } from '../lib/project-root.mjs';
14
12
  import { updateConfig } from '../lib/config-file.mjs';
15
13
  import {
@@ -77,9 +75,10 @@ export async function repoCommand({ action, slug, repo: repoArg, dryRun = false,
77
75
  try {
78
76
  // Sonda de ALCANCE, não leitura: o que importa é se o token enxerga o
79
77
  // repositório-alvo antes de o hub passar a apontar para ele.
80
- const alvo = await createGithubScm({
78
+ const alvoScm = await requireScm({
81
79
  link: resolveScmLink({ owner: target.owner, repo: target.repo, role: 'code' }), token,
82
- }).verify();
80
+ });
81
+ const alvo = await alvoScm.verify();
83
82
  if (!alvo.ok) throw new Error(alvo.problems.join('; '));
84
83
  } catch (err) {
85
84
  throw new Error(`Não consegui ler ${target.owner}/${target.repo}: ${err.status === 404 ? 'não existe ou o token não o enxerga' : err.message}.`);
@@ -95,8 +94,8 @@ export async function repoCommand({ action, slug, repo: repoArg, dryRun = false,
95
94
 
96
95
  const spec = repoLabelSpec(slug);
97
96
  try {
98
- await createGithubTracker({ token, owner: ctx.owner, repo: ctx.repo })
99
- .ensureTags({ tags: [spec] });
97
+ const trackerHub = await requireTracker({ token, owner: ctx.owner, repo: ctx.repo });
98
+ await trackerHub.ensureTags({ tags: [spec] });
100
99
  p.log.success(`Label ${spec.name} garantida em ${ctx.owner}/${ctx.repo}.`);
101
100
  } catch (err) {
102
101
  p.log.warn(`Não consegui criar a label ${spec.name}: ${err.message} — o decompose --apply tenta de novo.`);
@@ -20,9 +20,7 @@ import path from 'node:path';
20
20
  import chalk from 'chalk';
21
21
 
22
22
  import { resolveToken } from '../api/auth.mjs';
23
- import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
24
- import { createGithubScm } from '../plugins/scm-github/index.mjs';
25
- import { resolveScmLink } from '../ports/index.mjs';
23
+ import { requireScm, requireTracker, resolveScmLink } from '../ports/index.mjs';
26
24
  import { trackerAvailable } from '../lib/board.mjs';
27
25
  import { loadArtifact } from '../lib/doc-source.mjs';
28
26
  import { featureDocPaths, bugDocPaths } from '../lib/doc-paths.mjs';
@@ -342,7 +340,7 @@ async function runForPr({ prNumber, dryRun, yes, only, json }) {
342
340
  const token = await resolveToken();
343
341
  const n = parseInt(prNumber, 10);
344
342
 
345
- const scm = createGithubScm({ link: resolveScmLink({ owner, repo }), token });
343
+ const scm = await requireScm({ link: resolveScmLink({ owner, repo }), token });
346
344
  const pr = await scm.getPullRequest({ number: String(n) });
347
345
  const reviews = await scm.listPullRequestReviews({ number: String(n) });
348
346
  const verdict = reviewVerdict(reviews);
@@ -447,8 +445,12 @@ export async function run(issueArg, options = {}) {
447
445
  const passos = [];
448
446
  let ultimoTipo = null;
449
447
 
448
+ // A porta sai do laço: ela era reconstruída a cada volta, e agora cada
449
+ // construção custaria uma leitura de config também. O laço roda até `teto`.
450
+ const trackerRun = await requireTracker({ token, owner, repo });
451
+
450
452
  for (let i = 0; i < teto; i++) {
451
- const issue = await createGithubTracker({ token, owner, repo })
453
+ const issue = await trackerRun
452
454
  .getWorkItem({ ref: { key: String(parseInt(issueNumber, 10)) } });
453
455
  const type = detectIssueType(issue);
454
456
  const { docs, docPaths } = localDocStates(issue, type, root);
@@ -8,11 +8,11 @@
8
8
  import * as p from '@clack/prompts';
9
9
  import chalk from 'chalk';
10
10
  import { resolveToken } from '../api/auth.mjs';
11
- import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
12
11
  import { detectIssueType } from '../lib/issue-type.mjs';
13
12
  import { openTracker, advanceToStage } from '../lib/board.mjs';
14
13
  import { resolveHubContext } from '../lib/project-root.mjs';
15
14
  import { CONFIG_FILE, STAGE_CODE_REVIEW, PROGRESS_TODO } from '../config.mjs';
15
+ import { requireTracker } from '../ports/index.mjs';
16
16
 
17
17
  export async function story({ action, issue: issueArg, deps = {} }) {
18
18
  if (action !== 'review') {
@@ -55,7 +55,7 @@ export async function story({ action, issue: issueArg, deps = {} }) {
55
55
  // 1. Lê a issue e valida o tipo.
56
56
  let issue;
57
57
  try {
58
- issue = await (deps.tracker ?? createGithubTracker({ token, owner, repo }))
58
+ issue = await (await requireTracker({ token, owner, repo, deps }))
59
59
  .getWorkItem({ ref: { key: String(issueNumber) } });
60
60
  } catch (err) {
61
61
  p.log.error(`Não foi possível ler a issue #${issueNumber}: ${err.message}`);
@@ -73,7 +73,7 @@ export async function story({ action, issue: issueArg, deps = {} }) {
73
73
  }
74
74
 
75
75
  // 2. Tracker do .spec-wave.json — sem ele não há board para atualizar.
76
- const { tracker, error: projectError } = openTracker({ token, owner, repo, tracker: deps.tracker });
76
+ const { tracker, error: projectError } = await openTracker({ token, owner, repo, tracker: deps.tracker });
77
77
  if (projectError) {
78
78
  p.log.error(`${projectError} — board não atualizado. Rode \`spec-wave init\` (ou \`spec-wave refresh --config\`).`);
79
79
  process.exitCode = 1;
@@ -11,11 +11,11 @@
11
11
  import * as p from '@clack/prompts';
12
12
  import chalk from 'chalk';
13
13
  import { resolveToken } from '../api/auth.mjs';
14
- import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
15
14
 
16
15
  import { detectIssueType } from '../lib/issue-type.mjs';
17
16
  import { openTracker, advanceToStage, setProgress } from '../lib/board.mjs';
18
17
  import { resolveHubContext } from '../lib/project-root.mjs';
18
+ import { requireTracker } from '../ports/index.mjs';
19
19
  import {
20
20
  CONFIG_FILE, STAGE_DEVELOPMENT, STAGE_DONE,
21
21
  PROGRESS_IN_PROGRESS, PROGRESS_DONE,
@@ -77,7 +77,7 @@ export async function task({ action, issue: issueArg, deps = {} }) {
77
77
  // 1. Lê a issue e valida o tipo.
78
78
  let issue;
79
79
  try {
80
- issue = await (deps.tracker ?? createGithubTracker({ token, owner, repo }))
80
+ issue = await (await requireTracker({ token, owner, repo, deps }))
81
81
  .getWorkItem({ ref: { key: String(issueNumber) } });
82
82
  } catch (err) {
83
83
  p.log.error(`Não foi possível ler a issue #${issueNumber}: ${err.message}`);
@@ -95,7 +95,7 @@ export async function task({ action, issue: issueArg, deps = {} }) {
95
95
  }
96
96
 
97
97
  // 2. Tracker do .spec-wave.json — sem ele não há board para atualizar.
98
- const { tracker, error: projectError } = openTracker({ token, owner, repo, tracker: deps.tracker });
98
+ const { tracker, error: projectError } = await openTracker({ token, owner, repo, tracker: deps.tracker });
99
99
  if (projectError) {
100
100
  p.log.error(`${projectError} — board não atualizado. Rode \`spec-wave init\` (ou \`spec-wave refresh --config\`).`);
101
101
  process.exitCode = 1;
@@ -11,11 +11,11 @@
11
11
  import * as p from '@clack/prompts';
12
12
  import chalk from 'chalk';
13
13
  import { resolveToken } from '../api/auth.mjs';
14
- import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
15
14
  import { detectIssueType } from '../lib/issue-type.mjs';
16
15
  import { openTracker, advanceToStage } from '../lib/board.mjs';
17
16
  import { resolveHubContext } from '../lib/project-root.mjs';
18
17
  import { resolveTriageAction, canAcceptBug } from '../lib/bug-triage.mjs';
18
+ import { requireTracker } from '../ports/index.mjs';
19
19
  import {
20
20
  CONFIG_FILE, STAGE_READY, PROGRESS_TODO, PRIORITY_LABELS,
21
21
  LABEL_TRIAGED, LABEL_DUPLICATE, LABEL_WONT_FIX, labelNames,
@@ -64,7 +64,7 @@ export async function triage({ action: actionArg, issue: issueArg, reason, of, s
64
64
 
65
65
  p.intro(chalk.bold(`spec-wave triage ${action} #${issueNumber}`));
66
66
 
67
- const tracker = deps.tracker ?? createGithubTracker({ token, owner, repo });
67
+ const tracker = await requireTracker({ token, owner, repo, deps });
68
68
  const ref = { key: String(issueNumber) };
69
69
 
70
70
  let issue;
@@ -153,7 +153,7 @@ export async function triage({ action: actionArg, issue: issueArg, reason, of, s
153
153
  }
154
154
 
155
155
  async function moveToReady({ token, issueNumber, issue, root, deps = {} }) {
156
- const { tracker, error } = openTracker({ token, cwd: root || process.cwd(), tracker: deps.tracker });
156
+ const { tracker, error } = await openTracker({ token, cwd: root || process.cwd(), tracker: deps.tracker });
157
157
  if (error) {
158
158
  p.log.warn(`${error} — board não atualizado.`);
159
159
  return;
@@ -4,9 +4,8 @@ import { readFileSync, existsSync, unlinkSync } from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { resolveToken } from '../api/auth.mjs';
6
6
  import { CONFIG_FILE, ALL_LABELS, WORKFLOW_FILES, ISSUE_TEMPLATE_FILES } from '../config.mjs';
7
- import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
8
- import { createGithubScm } from '../plugins/scm-github/index.mjs';
9
- import { resolveScmLink } from '../ports/index.mjs';
7
+ import { requireScm, requireTracker, resolveScmLink } from '../ports/index.mjs';
8
+ import { tagRegistryPlan } from '../lib/tag-registry.mjs';
10
9
 
11
10
  const REPO_FILES = [
12
11
  ...WORKFLOW_FILES.map(f => `.github/workflows/${f}`),
@@ -46,7 +45,9 @@ export async function uninstall(options = {}) {
46
45
  return;
47
46
  }
48
47
 
49
- const doLabels = !options.skipLabels;
48
+ // `let` porque o guard de `deleteTag` pode desligá-lo depois de a porta existir
49
+ // (um tracker sem registro de labels — ver o bloco de labels abaixo).
50
+ let doLabels = !options.skipLabels;
50
51
  const doFiles = !options.skipFiles;
51
52
  const doConfig = hasConfig && !options.keepConfig;
52
53
 
@@ -82,10 +83,17 @@ export async function uninstall(options = {}) {
82
83
  return;
83
84
  }
84
85
 
85
- const tracker = createGithubTracker({ token, owner, repo });
86
- const scm = createGithubScm({ link: resolveScmLink({ owner, repo }), token });
86
+ const tracker = await requireTracker({ token, owner, repo });
87
+ const scm = await requireScm({ link: resolveScmLink({ owner, repo }), token });
87
88
 
88
89
  // --- Labels ---
90
+ // `deleteTag` é OPCIONAL no contrato e nenhuma capability a liga — ver
91
+ // `lib/tag-registry.mjs`, que tem a razão inteira.
92
+ const registro = tagRegistryPlan(tracker);
93
+ if (doLabels && !registro.canDelete) {
94
+ p.log.warn(registro.warning);
95
+ doLabels = false;
96
+ }
89
97
  if (doLabels) {
90
98
  const spinner = p.spinner();
91
99
  spinner.start('Removendo labels...');