@spec-wave/cli 1.0.8 → 1.2.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 (59) hide show
  1. package/package.json +1 -1
  2. package/src/api/github-graphql.mjs +51 -0
  3. package/src/api/github-rest.mjs +48 -0
  4. package/src/commands/audit.mjs +24 -18
  5. package/src/commands/code-review.mjs +89 -58
  6. package/src/commands/decompose.mjs +254 -218
  7. package/src/commands/generate-bug.mjs +51 -44
  8. package/src/commands/generate-plan.mjs +83 -63
  9. package/src/commands/generate-qa-plan.mjs +144 -117
  10. package/src/commands/generate-spec.mjs +33 -28
  11. package/src/commands/implement.mjs +154 -79
  12. package/src/commands/init.mjs +8 -3
  13. package/src/commands/issue.mjs +26 -39
  14. package/src/commands/merge.mjs +71 -20
  15. package/src/commands/mode.mjs +8 -4
  16. package/src/commands/move.mjs +16 -20
  17. package/src/commands/order.mjs +33 -22
  18. package/src/commands/preflight.mjs +24 -13
  19. package/src/commands/qa-lead.mjs +28 -16
  20. package/src/commands/qa-run.mjs +122 -101
  21. package/src/commands/qa.mjs +55 -44
  22. package/src/commands/refresh.mjs +24 -16
  23. package/src/commands/repair-stage.mjs +29 -16
  24. package/src/commands/repo.mjs +10 -3
  25. package/src/commands/run.mjs +23 -11
  26. package/src/commands/story.mjs +20 -25
  27. package/src/commands/task.mjs +21 -27
  28. package/src/commands/triage.mjs +33 -31
  29. package/src/commands/uninstall.mjs +7 -3
  30. package/src/commands/update.mjs +29 -21
  31. package/src/commands/validate.mjs +60 -52
  32. package/src/commands/workspace.mjs +7 -5
  33. package/src/config.mjs +7 -1
  34. package/src/lib/artifact-publish.mjs +20 -18
  35. package/src/lib/board-policy.mjs +144 -0
  36. package/src/lib/board.mjs +134 -233
  37. package/src/lib/doc-availability.mjs +10 -3
  38. package/src/lib/doc-source.mjs +9 -9
  39. package/src/lib/implement-board.mjs +23 -26
  40. package/src/lib/issue-type.mjs +5 -1
  41. package/src/lib/pr-ready.mjs +48 -10
  42. package/src/lib/pr-step.mjs +3 -1
  43. package/src/lib/qa-exec.mjs +3 -1
  44. package/src/lib/qa-lead.mjs +11 -3
  45. package/src/lib/qa-plan-doc.mjs +10 -4
  46. package/src/lib/spec-audit.mjs +1 -1
  47. package/src/lib/story-graph.mjs +62 -8
  48. package/src/lib/usage-report.mjs +8 -5
  49. package/src/lib/work-item-ref.mjs +176 -0
  50. package/src/plugin/.claude-plugin/plugin.json +1 -1
  51. package/src/plugins/scm-github/index.mjs +439 -0
  52. package/src/plugins/tracker-github-projects/fields.mjs +73 -0
  53. package/src/plugins/tracker-github-projects/index.mjs +662 -0
  54. package/src/ports/scm.mjs +197 -0
  55. package/src/ports/tracker.mjs +280 -0
  56. package/src/ports/types.mjs +295 -0
  57. package/src/setup/files.mjs +14 -12
  58. package/src/setup/labels.mjs +17 -12
  59. package/src/setup/project.mjs +40 -59
@@ -20,7 +20,7 @@
20
20
  import { existsSync, readFileSync } from 'node:fs';
21
21
  import path from 'node:path';
22
22
 
23
- import { getFileContent, findOpenPR } from '../api/github-rest.mjs';
23
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
24
24
  import { artifactBranch } from './artifact-pr.mjs';
25
25
 
26
26
  /**
@@ -75,14 +75,13 @@ export function isAwaitingMerge(state) {
75
75
  * @param {string} params.doc chave de ARTIFACT_DOCS
76
76
  * @param {number|string} params.issueNumber
77
77
  * @param {string|null} [params.base] branch base (null = deixa a API escolher)
78
- * @param {object} [params.deps] injeção para teste
78
+ * @param {object} [params.scm] porta de SCM; ausente = uma do GitHub
79
79
  * @returns {Promise<{content: string|null, state: DocState, ref: string|null,
80
80
  * pr: {number: number, url: string}|null}>}
81
81
  */
82
82
  export async function loadArtifact({
83
- token, owner, repo, root, pathRel, doc, issueNumber, base = null, deps = {},
83
+ token, owner, repo, root, pathRel, doc, issueNumber, base = null, scm = null,
84
84
  }) {
85
- const api = { getFileContent, findOpenPR, ...deps };
86
85
 
87
86
  const abs = path.resolve(root || process.cwd(), pathRel);
88
87
  if (existsSync(abs)) {
@@ -94,10 +93,11 @@ export async function loadArtifact({
94
93
  if (!token || !owner || !repo) {
95
94
  return { content: null, state: 'unknown', ref: null, pr: null };
96
95
  }
96
+ const porta = scm || createGithubScm({ link: githubLink({ owner, repo }), token });
97
97
 
98
98
  let naBase;
99
99
  try {
100
- naBase = await api.getFileContent(token, owner, repo, pathRel, base || undefined);
100
+ naBase = await porta.readFile({ path: pathRel, ref: base || undefined });
101
101
  } catch {
102
102
  return { content: null, state: 'unknown', ref: null, pr: null };
103
103
  }
@@ -115,7 +115,7 @@ export async function loadArtifact({
115
115
 
116
116
  let naBranch;
117
117
  try {
118
- naBranch = await api.getFileContent(token, owner, repo, pathRel, branch);
118
+ naBranch = await porta.readFile({ path: pathRel, ref: branch });
119
119
  } catch {
120
120
  return { content: null, state: 'unknown', ref: null, pr: null };
121
121
  }
@@ -126,7 +126,7 @@ export async function loadArtifact({
126
126
  // é o REMÉDIO, não a existência.
127
127
  let pr;
128
128
  try {
129
- pr = await api.findOpenPR(token, owner, repo, branch);
129
+ pr = await porta.findOpenPullRequest({ branch });
130
130
  } catch {
131
131
  // O documento existe; não saber se há PR não pode rebaixá-lo a inexistente,
132
132
  // que é o estado que autoriza regerar por cima.
@@ -149,12 +149,12 @@ export async function loadArtifact({
149
149
  * @returns {Promise<Record<string, {state: DocState, pr: object|null}>>}
150
150
  */
151
151
  export async function artifactStates({
152
- token, owner, repo, root, docs = [], issueNumber, base = null, deps = {},
152
+ token, owner, repo, root, docs = [], issueNumber, base = null, scm = null,
153
153
  }) {
154
154
  const out = {};
155
155
  for (const { doc, pathRel } of docs) {
156
156
  const { state, pr } = await loadArtifact({
157
- token, owner, repo, root, pathRel, doc, issueNumber, base, deps,
157
+ token, owner, repo, root, pathRel, doc, issueNumber, base, scm,
158
158
  });
159
159
  out[doc] = { state, pr };
160
160
  }
@@ -8,7 +8,7 @@
8
8
  // implementação (warn e segue).
9
9
 
10
10
  import * as p from '@clack/prompts';
11
- import { loadProjectConfig, resolveField, advanceToStage, setItemStatus } from './board.mjs';
11
+ import { openTracker, advanceToStage, setProgress } from './board.mjs';
12
12
  import {
13
13
  STAGE_DEVELOPMENT, STAGE_CODE_REVIEW, STAGE_DONE,
14
14
  PROGRESS_TODO, PROGRESS_IN_PROGRESS, PROGRESS_DONE,
@@ -37,37 +37,37 @@ export function planBoardMoves(phase, {
37
37
  const moves = [];
38
38
  if (phase === 'start') {
39
39
  if (feature?.nodeId) {
40
- moves.push({ nodeId: feature.nodeId, label: `Feature #${feature.number}`, type: 'Feature',
40
+ moves.push({ nodeId: feature.nodeId, number: feature.number, label: `Feature #${feature.number}`, type: 'Feature',
41
41
  stage: STAGE_DEVELOPMENT, status: PROGRESS_IN_PROGRESS, statusFallback: true });
42
42
  }
43
43
  if (story?.nodeId) {
44
- moves.push({ nodeId: story.nodeId, label: `Story #${story.number}`, type: 'Story',
44
+ moves.push({ nodeId: story.nodeId, number: story.number, label: `Story #${story.number}`, type: 'Story',
45
45
  stage: STAGE_DEVELOPMENT, status: PROGRESS_IN_PROGRESS, statusFallback: true });
46
46
  }
47
47
  // Bug é folha e não tem Feature-pai a arrastar: um defeito em correção não
48
48
  // deve puxar a Feature inteira de volta para Desenvolvimento.
49
49
  if (bug?.nodeId) {
50
- moves.push({ nodeId: bug.nodeId, label: `Bug #${bug.number}`, type: 'Bug',
50
+ moves.push({ nodeId: bug.nodeId, number: bug.number, label: `Bug #${bug.number}`, type: 'Bug',
51
51
  stage: STAGE_DEVELOPMENT, status: PROGRESS_IN_PROGRESS, statusFallback: true });
52
52
  }
53
53
  for (const t of tasks) {
54
54
  if (!t?.nodeId) continue;
55
- moves.push({ nodeId: t.nodeId, label: `Task #${t.number}`, type: 'Task',
55
+ moves.push({ nodeId: t.nodeId, number: t.number, label: `Task #${t.number}`, type: 'Task',
56
56
  stage: STAGE_DEVELOPMENT, status: tasksStartStatus,
57
57
  statusFallback: tasksStartStatus === PROGRESS_IN_PROGRESS });
58
58
  }
59
59
  } else if (phase === 'success') {
60
60
  for (const t of tasks) {
61
61
  if (!t?.nodeId) continue;
62
- moves.push({ nodeId: t.nodeId, label: `Task #${t.number}`, type: 'Task',
62
+ moves.push({ nodeId: t.nodeId, number: t.number, label: `Task #${t.number}`, type: 'Task',
63
63
  stage: STAGE_DONE, status: PROGRESS_DONE, statusFallback: false });
64
64
  }
65
65
  if (story?.nodeId) {
66
- moves.push({ nodeId: story.nodeId, label: `Story #${story.number}`, type: 'Story',
66
+ moves.push({ nodeId: story.nodeId, number: story.number, label: `Story #${story.number}`, type: 'Story',
67
67
  stage: STAGE_CODE_REVIEW, status: PROGRESS_TODO, statusFallback: false });
68
68
  }
69
69
  if (bug?.nodeId) {
70
- moves.push({ nodeId: bug.nodeId, label: `Bug #${bug.number}`, type: 'Bug',
70
+ moves.push({ nodeId: bug.nodeId, number: bug.number, label: `Bug #${bug.number}`, type: 'Bug',
71
71
  stage: STAGE_CODE_REVIEW, status: PROGRESS_TODO, statusFallback: false });
72
72
  }
73
73
  // Feature: só o modo Feature passa `feature` aqui, e só depois de TODAS as
@@ -77,7 +77,7 @@ export function planBoardMoves(phase, {
77
77
  // num branch único e não abre PR), a Feature ficava presa em
78
78
  // Desenvolvimento com todas as Stories já em Code Review.
79
79
  if (feature?.nodeId) {
80
- moves.push({ nodeId: feature.nodeId, label: `Feature #${feature.number}`, type: 'Feature',
80
+ moves.push({ nodeId: feature.nodeId, number: feature.number, label: `Feature #${feature.number}`, type: 'Feature',
81
81
  stage: STAGE_CODE_REVIEW, status: PROGRESS_TODO, statusFallback: false });
82
82
  }
83
83
  }
@@ -105,31 +105,28 @@ export async function applyBoardMoves({
105
105
  return;
106
106
  }
107
107
  try {
108
- const { project, error } = loadProjectConfig({ cwd });
108
+ // PROJECT_TOKEN é a credencial do board — ver a tabela em
109
+ // src/plugins/tracker-github-projects/index.mjs.
110
+ const { tracker, error } = openTracker({
111
+ token, projectToken: process.env.PROJECT_TOKEN || token, cwd,
112
+ });
109
113
  if (error) {
110
114
  log.warn(`board: ${error} — Etapas não atualizadas.`);
111
115
  return;
112
116
  }
113
- const projectToken = process.env.PROJECT_TOKEN || token;
114
- const etapaField = await resolveField(projectToken, project, 'Etapa').catch(() => null);
115
- const statusField = await resolveField(projectToken, project, 'Status').catch(() => null);
116
- // Repara o Work Item Type vazio de passagem — o tipo de cada movimento é
117
- // conhecido por construção (planBoardMoves). Ver ensureWorkItemType.
118
- const typeField = await resolveField(projectToken, project, 'Work Item Type').catch(() => null);
119
- if (!etapaField?.id) {
120
- log.warn('board: campo Etapa não resolvido — Etapas não atualizadas.');
121
- return;
122
- }
123
117
  for (const m of moves) {
118
+ const ref = { key: String(m.number ?? ''), id: m.nodeId };
124
119
  try {
125
- const advanced = await advanceToStage(
126
- projectToken, project, etapaField, statusField, m.nodeId, m.stage, m.status,
127
- { typeField, itemType: m.type });
120
+ // `itemType` repara o Work Item Type vazio de passagem — o tipo de cada
121
+ // movimento é conhecido por construção (planBoardMoves).
122
+ const advanced = await advanceToStage({
123
+ tracker, ref, stage: m.stage, progress: m.status, itemType: m.type,
124
+ });
128
125
  if (advanced) {
129
126
  log.info(`board: ${m.label} → ${m.stage} (${m.status})`);
130
- } else if (m.statusFallback && statusField?.id) {
131
- // Etapa já está nessa fase ou adiante: ao menos alinha o Status.
132
- await setItemStatus(projectToken, project, statusField, m.nodeId, m.status);
127
+ } else if (m.statusFallback) {
128
+ // Etapa já está nessa fase ou adiante: ao menos alinha o progresso.
129
+ await setProgress({ tracker, ref, progress: m.status });
133
130
  log.info(`board: ${m.label} já em ${m.stage}+ — Status → ${m.status}`);
134
131
  }
135
132
  } catch (err) {
@@ -26,7 +26,11 @@ export function detectIssueType(issue) {
26
26
  }
27
27
 
28
28
  // 2. Fallback: varrer as labels da issue procurando um dos prefixos de tipo.
29
- const labels = Array.isArray(issue.labels) ? issue.labels : [];
29
+ // `tags` é a forma canônica do WorkItem (RFC-006); `labels` é a issue crua da
30
+ // REST, que ainda circula. As duas valem — ver labelNames em config.mjs.
31
+ const labels = Array.isArray(issue.tags)
32
+ ? issue.tags
33
+ : (Array.isArray(issue.labels) ? issue.labels : []);
30
34
  for (const label of labels) {
31
35
  const name = (typeof label === 'string' ? label : label?.name) || '';
32
36
  const type = TAG_TO_TYPE[name.toUpperCase()];
@@ -17,7 +17,7 @@
17
17
  // implementação, que a essa altura já está commitada.
18
18
 
19
19
  import * as p from '@clack/prompts';
20
- import { listIssuePullRequests, listOpenPullRequests, markPullRequestReadyForReview } from '../api/github-graphql.mjs';
20
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
21
21
  import { extractIssueRefs, hubIssueNumbers } from './pr-link.mjs';
22
22
 
23
23
  /**
@@ -36,8 +36,13 @@ import { extractIssueRefs, hubIssueNumbers } from './pr-link.mjs';
36
36
  */
37
37
  export function planPrsToReady(prs = []) {
38
38
  const out = new Map();
39
+ // Duas formas: a crua do GraphQL (`isDraft`, `merged`) e a do contrato
40
+ // (`draft`, `state: 'merged'`). Ler só a primeira faz `!pr.isDraft` ser
41
+ // sempre verdadeiro — e aí nenhum PR sai do rascunho, em silêncio.
42
+ const emRascunho = pr => pr.isDraft ?? pr.draft;
43
+ const mergeado = pr => Boolean(pr.merged) || pr.state === 'merged';
39
44
  for (const pr of prs) {
40
- if (!pr?.id || !pr.isDraft || pr.merged) continue;
45
+ if (!pr?.id || !emRascunho(pr) || mergeado(pr)) continue;
41
46
  if (pr.state && pr.state !== 'open') continue;
42
47
  // Chave = node id: o número colide entre repositórios (PR #42 do `api` e
43
48
  // #42 do `web`), o id não.
@@ -65,6 +70,7 @@ export function planPrsToReady(prs = []) {
65
70
  */
66
71
  export async function collectFeaturePullRequests({
67
72
  token, owner, repo, issueNumbers = [], issueNodes = [], linkMode = 'explicit', codeRepos = [],
73
+ scmDe = null,
68
74
  }) {
69
75
  const alvo = new Set(issueNumbers);
70
76
  const byKey = new Map();
@@ -75,26 +81,44 @@ export async function collectFeaturePullRequests({
75
81
  // onde foi listado — o número colide entre repos, o par não. Um `#N` solto
76
82
  // é issue do repo do PR; só o que aponta para o hub é desta Feature.
77
83
  const hub = { owner, repo };
84
+ // Uma porta POR REPOSITÓRIO — é o que o contrato manda, e é a razão de
85
+ // `PullRequestRef` carregar o `link`: o número do PR colide entre repos.
86
+ const portaDe = scmDe ?? (r => createGithubScm({
87
+ link: githubLink({ owner: r.owner, repo: r.repo, role: sameRepoQue(r, hub) ? 'hub' : 'code' }),
88
+ token,
89
+ }));
90
+
78
91
  for (const r of [hub, ...codeRepos]) {
79
- const abertos = await listOpenPullRequests(token, r.owner, r.repo).catch(() => []);
80
- for (const raw of abertos) {
81
- const pr = { ...raw, repo: { owner: r.owner, repo: r.repo } };
92
+ const abertos = await portaDe(r).listOpenPullRequests().catch(() => []);
93
+ for (const bruto of abertos) {
94
+ const pr = { ...bruto, repo: { owner: r.owner, repo: r.repo } };
82
95
  const fecha = hubIssueNumbers(extractIssueRefs(pr.body || '', { prRepo: pr.repo, linkMode }), hub);
83
96
  if (fecha.some(n => alvo.has(n))) byKey.set(keyOf(pr), pr);
84
97
  }
85
98
  }
86
99
 
87
- // Vínculo nativo: só existe no hub (o GitHub não fecha issue entre repos).
100
+ // Vínculo NATIVO: só existe no hub (o GitHub não fecha issue entre repos).
101
+ const hubScm = portaDe(hub);
88
102
  for (const node of issueNodes) {
89
103
  if (!node?.nodeId) continue;
90
- for (const raw of await listIssuePullRequests(token, node.nodeId).catch(() => [])) {
91
- const pr = { ...raw, repo: raw.repo || hub };
104
+ const achados = await hubScm
105
+ .findPullRequestsReferencing({ ref: { key: String(node.number), id: node.nodeId } })
106
+ .catch(() => []);
107
+ for (const bruto of achados) {
108
+ const pr = { ...bruto, repo: hub };
92
109
  if (!byKey.has(keyOf(pr))) byKey.set(keyOf(pr), pr);
93
110
  }
94
111
  }
95
112
  return [...byKey.values()];
96
113
  }
97
114
 
115
+ /** Dois endereços de repositório são o mesmo? (case-insensitive) */
116
+ function sameRepoQue(a, b) {
117
+ return Boolean(a && b)
118
+ && a.owner.toLowerCase() === b.owner.toLowerCase()
119
+ && a.repo.toLowerCase() === b.repo.toLowerCase();
120
+ }
121
+
98
122
  /** `#12` no hub, `acme/api#12` fora dele. */
99
123
  export function prLabel(pr, hub) {
100
124
  const r = pr.repo;
@@ -119,12 +143,13 @@ export function prLabel(pr, hub) {
119
143
  */
120
144
  export async function markFeaturePrsReady({
121
145
  token, owner, repo, feature, stories = [], dryRun = false, log = p.log, linkMode = 'explicit', codeRepos = [],
146
+ scmDe = null,
122
147
  }) {
123
148
  if (!token || !owner || !repo || !feature?.number) return [];
124
149
  const hub = { owner, repo };
125
150
  try {
126
151
  const prs = await collectFeaturePullRequests({
127
- token, owner, repo, linkMode, codeRepos,
152
+ token, owner, repo, linkMode, codeRepos, scmDe,
128
153
  issueNumbers: [feature.number, ...stories.map(s => s.number)].filter(Boolean),
129
154
  issueNodes: [feature, ...stories],
130
155
  });
@@ -141,11 +166,24 @@ export async function markFeaturePrsReady({
141
166
 
142
167
  // Devolve os rótulos (`#12`, `acme/api#12`), não os números: fora do hub o
143
168
  // número sozinho não identifica o PR.
169
+ // O PR pode estar em qualquer repo da Feature: a porta é a DELE, não a do
170
+ // hub. Marcar um PR de repo de código com a porta do hub é 404 — ou pior,
171
+ // o PR de mesmo número no hub.
172
+ const portaDoPr = (pr) => {
173
+ const r = { owner: pr.repo?.owner ?? owner, repo: pr.repo?.repo ?? repo };
174
+ if (scmDe) return scmDe(r);
175
+ // `role` sai de `pr.repo`, não de `r`: o par já traz fallback no hub, e
176
+ // computar dali faria um `pr.repo` ausente virar 'hub' onde era 'code'.
177
+ return createGithubScm({
178
+ link: githubLink({ ...r, role: sameRepoQue(pr.repo, hub) ? 'hub' : 'code' }),
179
+ token,
180
+ });
181
+ };
144
182
  const marcados = [];
145
183
  const falhas = [];
146
184
  for (const pr of alvos) {
147
185
  try {
148
- await markPullRequestReadyForReview(token, pr.id);
186
+ await portaDoPr(pr).markReadyForReview({ id: pr.id });
149
187
  marcados.push(prLabel(pr, hub));
150
188
  } catch (err) {
151
189
  falhas.push(`${prLabel(pr, hub)} (${err.message})`);
@@ -27,7 +27,9 @@ export function reviewVerdict(reviews = []) {
27
27
  for (const review of reviews) {
28
28
  const state = String(review?.state || '').toUpperCase();
29
29
  if (!relevant.includes(state)) continue; // COMMENTED/PENDING não são veredito
30
- const autor = review?.user?.login || review?.author || '(desconhecido)';
30
+ // `reviewer` é o nome CANÔNICO (Review, ports/types.mjs); `user.login` e
31
+ // `author` são as formas cruas que ainda circulam.
32
+ const autor = review?.reviewer || review?.user?.login || review?.author || '(desconhecido)';
31
33
  porAutor.set(autor, state);
32
34
  }
33
35
 
@@ -378,7 +378,9 @@ export function buildQaContext({
378
378
  lines.push('## Pull Requests vinculados');
379
379
  lines.push('');
380
380
  for (const pr of pullRequests) {
381
- lines.push(`- PR #${pr.number} — ${pr.merged ? 'mergeado' : pr.state}`);
381
+ // `merged` é a forma crua do GraphQL; no contrato o merge é um ESTADO.
382
+ const mergeado = Boolean(pr.merged) || pr.state === 'merged';
383
+ lines.push(`- PR #${pr.number} — ${mergeado ? 'mergeado' : pr.state}`);
382
384
  }
383
385
  }
384
386
 
@@ -78,10 +78,18 @@ export function qaTrailDir(milestoneTitle, cycle) {
78
78
  * @returns {{ milestone?: object, error?: string }}
79
79
  */
80
80
  export function resolveMilestoneRef(milestones = [], ref) {
81
+ // `key` (MilestoneRef, o que a porta devolve) e `number` (a milestone crua)
82
+ // valem as duas. Sem isso a busca por número deixaria de achar e o comando
83
+ // responderia "não existe" para uma milestone que existe.
84
+ // Comparação NUMÉRICA, não textual: a chave vinda da API nunca tem zero à
85
+ // esquerda, mas a digitada pode ter, e `'007' === '7'` é false. Um comando que
86
+ // responde "não existe" para uma milestone que existe é o pior dos dois
87
+ // mundos. Mesmo tratamento que `dependency-map.mjs` já dá.
88
+ const chave = m => Number(m?.key ?? m?.number);
81
89
  const text = String(ref ?? '').trim();
82
90
  if (/^#?\d+$/.test(text)) {
83
- const number = parseInt(text.replace('#', ''), 10);
84
- const found = milestones.find(m => m.number === number);
91
+ const number = text.replace('#', '');
92
+ const found = milestones.find(m => chave(m) === Number(number));
85
93
  return found
86
94
  ? { milestone: found }
87
95
  : { error: `Milestone #${number} não existe. Existem: ${listMilestoneTitles(milestones)}.` };
@@ -90,7 +98,7 @@ export function resolveMilestoneRef(milestones = [], ref) {
90
98
  if (matches.length === 1) return { milestone: matches[0] };
91
99
  if (matches.length > 1) {
92
100
  return {
93
- error: `Título "${text}" é ambíguo: ${matches.map(m => `#${m.number}`).join(', ')}. Use o número.`,
101
+ error: `Título "${text}" é ambíguo: ${matches.map(m => `#${chave(m)}`).join(', ')}. Use o número.`,
94
102
  };
95
103
  }
96
104
  return { error: `Milestone "${text}" não encontrada. Existem: ${listMilestoneTitles(milestones)}.` };
@@ -267,7 +267,13 @@ export function renderQaPlanDoc({ title = '', issueNumber = null, scenarios = []
267
267
  */
268
268
  export function validateQaPlan({ doc, stories = [], content = '' } = {}) {
269
269
  const errors = [];
270
- const byNumber = new Map(stories.map(s => [s.number, s]));
270
+ // A Story chega em duas formas: a crua (`number`, `stateReason: 'not_planned'`)
271
+ // e a do contrato (`ref.key`, `stateReason: 'not-planned'`). Ler só uma delas
272
+ // faz TODO cenário ser acusado de não pertencer à Feature.
273
+ const numeroDa = st => Number(st?.ref?.key ?? st?.number);
274
+ const descartadaNoRescopo = st => st?.state === 'closed'
275
+ && ['not_planned', 'not-planned'].includes(st?.stateReason);
276
+ const byNumber = new Map(stories.map(s => [numeroDa(s), s]));
271
277
 
272
278
  for (const s of doc?.scenarios || []) {
273
279
  if (!byNumber.has(s.story)) {
@@ -287,10 +293,10 @@ export function validateQaPlan({ doc, stories = [], content = '' } = {}) {
287
293
  // Story descartada no rescopo não precisa de cenário; as demais, sim.
288
294
  const covered = new Set((doc?.scenarios || []).map(s => s.story));
289
295
  for (const story of stories) {
290
- const descartada = story.state === 'closed' && story.stateReason === 'not_planned';
291
- if (!descartada && !covered.has(story.number)) {
296
+ const descartada = descartadaNoRescopo(story);
297
+ if (!descartada && !covered.has(numeroDa(story))) {
292
298
  errors.push(
293
- `A Story #${story.number}${story.title ? ` (${story.title})` : ''} não tem nenhum cenário — ` +
299
+ `A Story #${numeroDa(story)}${story.title ? ` (${story.title})` : ''} não tem nenhum cenário — ` +
294
300
  'toda Story da Feature precisa de ao menos um.'
295
301
  );
296
302
  }
@@ -373,7 +373,7 @@ export function auditMilestone({
373
373
  feature: f.number,
374
374
  dep: d,
375
375
  featureMilestone: f.milestone?.title || `#${f.milestone?.number ?? '?'}`,
376
- depMilestone: dep.milestone.title || `#${dep.milestone.number}`,
376
+ depMilestone: dep.milestone.title || `#${dep.milestone.key ?? dep.milestone.number}`,
377
377
  });
378
378
  }
379
379
  }
@@ -21,8 +21,55 @@
21
21
  import { existsSync, readFileSync } from 'node:fs';
22
22
  import path from 'node:path';
23
23
 
24
- import { listSubIssues, listProjectItems } from '../api/github-graphql.mjs';
25
- import { listBlockedBy, getIssue } from '../api/github-rest.mjs';
24
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
25
+
26
+ // ── Tradução WorkItem → a forma que este módulo SEMPRE devolveu ─────────────
27
+ //
28
+ // `loadFeatureStories` espalha `{...s}` para seis comandos, e o resultado é
29
+ // CACHEADO em disco. Trocar o shape aqui obrigaria a migrar merge, doctor,
30
+ // qa-lead e order no mesmo commit — e a invalidar todo cache gravado por uma
31
+ // versão anterior. A fonte passou a ser a porta; a forma continua a mesma, e
32
+ // some quando o último consumidor migrar.
33
+ //
34
+ // `stateReason` volta à grafia do GitHub (`not_planned`) porque é assim que
35
+ // doctor e qa-plan-doc a comparam hoje. A porta normaliza para `not-planned`;
36
+ // a desnormalização vive aqui, no tradutor, e não neles.
37
+ const RAZAO_CRUA = { 'not-planned': 'not_planned', completed: 'completed', reopened: 'reopened' };
38
+
39
+ function comoSubIssue(w) {
40
+ return {
41
+ number: Number(w.ref.key),
42
+ title: w.title,
43
+ body: w.body || '',
44
+ nodeId: w.ref.id,
45
+ createdAt: w.createdAt || null,
46
+ state: w.state || null,
47
+ stateReason: RAZAO_CRUA[w.stateReason] ?? null,
48
+ milestone: w.milestone ? { number: Number(w.milestone.key), title: w.milestone.title } : null,
49
+ labels: w.tags || [],
50
+ };
51
+ }
52
+
53
+ function comoItemDoBoard(b) {
54
+ const fields = {};
55
+ if (b.stage) fields.Etapa = b.stage;
56
+ if (b.progress) fields.Status = b.progress;
57
+ for (const [canonico, valor] of Object.entries(b.fields || {})) {
58
+ if (canonico === 'workItemType') fields['Work Item Type'] = valor;
59
+ else if (canonico === 'priority') fields.Priority = valor;
60
+ else if (canonico === 'storyPoints') fields['Story Points'] = valor;
61
+ else if (canonico === 'area') fields.Area = valor;
62
+ else if (canonico === 'release') fields.Release = valor;
63
+ }
64
+ return {
65
+ number: Number(b.ref.key),
66
+ title: b.title,
67
+ state: String(b.state || '').toUpperCase(),
68
+ nodeId: b.ref.id,
69
+ milestone: b.milestone ? { number: Number(b.milestone.key), title: b.milestone.title } : null,
70
+ fields,
71
+ };
72
+ }
26
73
  import { detectIssueType } from './issue-type.mjs';
27
74
  import { featureDocPaths } from './doc-paths.mjs';
28
75
  import { parseDecompositionDoc } from './decomposition-doc.mjs';
@@ -66,6 +113,7 @@ export async function loadFeatureStories({
66
113
 
67
114
  // ── sub-issues (com body!) — cache subissues-<n> ───────────────────────────
68
115
  const subsKey = `subissues-${feature.number}`;
116
+ const tracker = createGithubTracker({ token, owner, repo });
69
117
  const cached = refresh ? null : readCacheEntry(root, subsKey, { owner, repo });
70
118
  let allSubs;
71
119
  let subsFrom;
@@ -75,7 +123,7 @@ export async function loadFeatureStories({
75
123
  subsFrom = 'cache';
76
124
  fetchedAt = cached.fetchedAt;
77
125
  } else {
78
- allSubs = await listSubIssues(token, nodeId);
126
+ allSubs = (await tracker.listChildren({ ref: { key: String(feature.number), id: nodeId } })).map(comoSubIssue);
79
127
  subsFrom = 'api';
80
128
  fetchedAt = new Date().toISOString();
81
129
  writeCacheEntry(root, subsKey, 'sub-issues', allSubs, { owner, repo });
@@ -134,7 +182,8 @@ export async function loadFeatureStories({
134
182
  continue;
135
183
  }
136
184
  try {
137
- const deps = (await listBlockedBy(token, owner, repo, s.number)).map(b => b.number);
185
+ const deps = (await tracker.listBlockedBy({ ref: { key: String(s.number) } }))
186
+ .map(b => Number(b.ref.key));
138
187
  remoteEdges.push({ number: s.number, dependsOn: deps });
139
188
  writeCacheEntry(root, key, 'blocked-by', deps, { owner, repo });
140
189
  } catch (err) {
@@ -166,13 +215,16 @@ export async function loadFeatureStories({
166
215
  */
167
216
  export async function cachedSubIssues({
168
217
  token, owner, repo, root, parent, refresh = false, ttlSec = DEFAULT_CACHE_TTL_SEC,
218
+ tracker = null,
169
219
  } = {}) {
170
220
  const key = `subissues-${parent.number}`;
171
221
  if (!refresh) {
172
222
  const hit = readCacheEntry(root, key, { owner, repo });
173
223
  if (hit && isFresh(hit, ttlSec)) return { subs: hit.data, fromCache: true, fetchedAt: hit.fetchedAt };
174
224
  }
175
- const subs = await listSubIssues(token, parent.nodeId || parent.node_id);
225
+ const subs = (await (tracker ?? createGithubTracker({ token, owner, repo })).listChildren({
226
+ ref: { key: String(parent.number), id: parent.nodeId || parent.node_id },
227
+ })).map(comoSubIssue);
176
228
  writeCacheEntry(root, key, 'sub-issues', subs, { owner, repo });
177
229
  return { subs, fromCache: false, fetchedAt: new Date().toISOString() };
178
230
  }
@@ -204,7 +256,7 @@ function safeDocPaths(root, title) {
204
256
  * @returns {Promise<{items:Array, index:Map<number,object>, fetchedAt:string, fromCache:boolean}>}
205
257
  */
206
258
  export async function loadBoardSnapshot({
207
- token, project, root, refresh = false, fresh = false, ttlSec = DEFAULT_CACHE_TTL_SEC,
259
+ token, owner, repo, project, root, refresh = false, fresh = false, ttlSec = DEFAULT_CACHE_TTL_SEC,
208
260
  } = {}) {
209
261
  const key = 'board-items';
210
262
  if (!refresh && !fresh) {
@@ -218,7 +270,8 @@ export async function loadBoardSnapshot({
218
270
  };
219
271
  }
220
272
  }
221
- const items = await listProjectItems(token, project.id);
273
+ const items = (await createGithubTracker({ token, owner, repo, project }).boardSnapshot())
274
+ .map(comoItemDoBoard);
222
275
  writeCacheEntry(root, key, 'board-items', items, { projectId: project.id });
223
276
  return {
224
277
  items,
@@ -244,7 +297,8 @@ export async function externalIssueInfo({
244
297
  const hit = readCacheEntry(root, key, { owner, repo });
245
298
  if (hit && isFresh(hit, ttlSec)) return { ...hit.data, fromCache: true };
246
299
  }
247
- const issue = await getIssue(token, owner, repo, number).catch(() => null);
300
+ const issue = await createGithubTracker({ token, owner, repo })
301
+ .getWorkItem({ ref: { key: String(number) } }).catch(() => null);
248
302
  if (!issue) {
249
303
  // Falha não entra no cache: "não foi possível ler" com cara de fresco por
250
304
  // 10 minutos esconderia uma issue que voltou a ser legível.
@@ -9,7 +9,7 @@
9
9
  // Contrato: registrar uso NUNCA derruba o fluxo principal — recordUsage é
10
10
  // best-effort e engole qualquer erro com um console.warn.
11
11
 
12
- import { listIssueComments, updateComment, commentOnIssue } from '../api/github-rest.mjs';
12
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
13
13
 
14
14
  // Marcador HTML invisível que identifica o comentário de uso na issue.
15
15
  export const USAGE_MARKER = '<!-- spec-wave:usage -->';
@@ -145,11 +145,14 @@ export function renderUsageComment(entries) {
145
145
  * @param {string} params.repo nome do repo
146
146
  * @param {number} params.issueNumber número da issue
147
147
  * @param {Array<object>} params.entries novas entradas de uso
148
+ * @param {object} [params.tracker] porta de tracker; ausente = uma do GitHub
148
149
  */
149
- export async function recordUsage({ token, owner, repo, issueNumber, entries } = {}) {
150
+ export async function recordUsage({ token, owner, repo, issueNumber, entries, tracker = null } = {}) {
150
151
  if (!Array.isArray(entries) || entries.length === 0) return;
152
+ const porta = tracker || createGithubTracker({ token, owner, repo });
153
+ const ref = { key: String(issueNumber) };
151
154
  try {
152
- const comments = await listIssueComments(token, owner, repo, issueNumber);
155
+ const comments = await porta.listComments({ ref });
153
156
  const existing = comments.find(c => (c.body || '').includes(USAGE_MARKER));
154
157
 
155
158
  // Comentário antigo irreconhecível → recomeça só com as novas entradas.
@@ -157,9 +160,9 @@ export async function recordUsage({ token, owner, repo, issueNumber, entries } =
157
160
  const body = renderUsageComment([...(previous || []), ...entries]);
158
161
 
159
162
  if (existing?.id) {
160
- await updateComment(token, owner, repo, existing.id, body);
163
+ await porta.updateComment({ ref, commentId: existing.id, body });
161
164
  } else {
162
- await commentOnIssue(token, owner, repo, issueNumber, body);
165
+ await porta.addComment({ ref, body });
163
166
  }
164
167
  } catch (err) {
165
168
  console.warn('Não foi possível registrar uso de IA:', err.message);