@spec-wave/cli 1.0.7 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/package.json +1 -1
  2. package/src/commands/audit.mjs +24 -18
  3. package/src/commands/code-review.mjs +91 -59
  4. package/src/commands/decompose.mjs +258 -221
  5. package/src/commands/doctor.mjs +16 -11
  6. package/src/commands/generate-bug.mjs +51 -44
  7. package/src/commands/generate-plan.mjs +83 -63
  8. package/src/commands/generate-qa-plan.mjs +145 -117
  9. package/src/commands/generate-spec.mjs +33 -28
  10. package/src/commands/implement.mjs +155 -79
  11. package/src/commands/info.mjs +4 -3
  12. package/src/commands/init.mjs +11 -5
  13. package/src/commands/install-skill.mjs +19 -0
  14. package/src/commands/issue.mjs +26 -39
  15. package/src/commands/merge.mjs +71 -20
  16. package/src/commands/mode.mjs +11 -6
  17. package/src/commands/move.mjs +16 -20
  18. package/src/commands/order.mjs +33 -22
  19. package/src/commands/preflight.mjs +24 -13
  20. package/src/commands/qa-lead.mjs +30 -17
  21. package/src/commands/qa-run.mjs +125 -103
  22. package/src/commands/qa.mjs +55 -44
  23. package/src/commands/refresh.mjs +24 -16
  24. package/src/commands/repair-stage.mjs +29 -16
  25. package/src/commands/repo.mjs +12 -4
  26. package/src/commands/run.mjs +23 -11
  27. package/src/commands/story.mjs +20 -25
  28. package/src/commands/task.mjs +21 -27
  29. package/src/commands/triage.mjs +33 -31
  30. package/src/commands/uninstall.mjs +7 -3
  31. package/src/commands/update.mjs +31 -22
  32. package/src/commands/validate.mjs +60 -52
  33. package/src/commands/workspace.mjs +7 -5
  34. package/src/config.mjs +7 -1
  35. package/src/lib/artifact-publish.mjs +20 -18
  36. package/src/lib/board-policy.mjs +144 -0
  37. package/src/lib/board.mjs +134 -233
  38. package/src/lib/cli-ref.mjs +75 -0
  39. package/src/lib/config-file.mjs +2 -1
  40. package/src/lib/doc-availability.mjs +10 -3
  41. package/src/lib/doc-source.mjs +9 -9
  42. package/src/lib/execution-mode.mjs +5 -3
  43. package/src/lib/implement-board.mjs +23 -26
  44. package/src/lib/issue-type.mjs +5 -1
  45. package/src/lib/plugin-skills.mjs +10 -0
  46. package/src/lib/pr-ready.mjs +48 -10
  47. package/src/lib/pr-step.mjs +3 -1
  48. package/src/lib/qa-exec.mjs +3 -1
  49. package/src/lib/qa-lead.mjs +11 -3
  50. package/src/lib/qa-plan-doc.mjs +10 -4
  51. package/src/lib/qa-report.mjs +2 -1
  52. package/src/lib/skill-compose.mjs +3 -0
  53. package/src/lib/spec-audit.mjs +1 -1
  54. package/src/lib/story-graph.mjs +62 -8
  55. package/src/lib/usage-report.mjs +8 -5
  56. package/src/lib/work-item-ref.mjs +176 -0
  57. package/src/plugin/.claude-plugin/plugin.json +1 -1
  58. package/src/plugins/scm-github/index.mjs +439 -0
  59. package/src/plugins/tracker-github-projects/fields.mjs +73 -0
  60. package/src/plugins/tracker-github-projects/index.mjs +625 -0
  61. package/src/ports/scm.mjs +197 -0
  62. package/src/ports/tracker.mjs +239 -0
  63. package/src/ports/types.mjs +254 -0
  64. package/src/setup/files.mjs +14 -12
  65. package/src/setup/labels.mjs +17 -12
  66. package/src/setup/project.mjs +40 -59
  67. package/src/templates/workflows/code/code-review.yml +1 -1
  68. package/src/templates/workflows/code/qa.yml +1 -1
@@ -12,10 +12,8 @@
12
12
  // Só um plano estruturalmente válido gasta uma chamada de crítica.
13
13
 
14
14
  import { resolveToken } from '../api/auth.mjs';
15
- import {
16
- getIssue, removeLabel, addLabel, commentOnIssue, listIssueComments, getRepoDefaultBranch,
17
- } from '../api/github-rest.mjs';
18
- import { getIssueParent, listSubIssues } from '../api/github-graphql.mjs';
15
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
16
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
19
17
  import { detectIssueType } from '../lib/issue-type.mjs';
20
18
  import { generateDocument } from '../lib/claude.mjs';
21
19
  import { unwrapGeneratedDoc } from '../lib/unwrap-doc.mjs';
@@ -33,6 +31,7 @@ import { loadArtifact, isAwaitingMerge } from '../lib/doc-source.mjs';
33
31
  import { awaitingMergeBlock, renderPrLine } from '../lib/artifact-pr.mjs';
34
32
  import { loadPrompt, systemPromptWithTools } from '../lib/prompt-loader.mjs';
35
33
  import { buildTechContext } from '../lib/tech-context.mjs';
34
+ import { cliRef } from '../lib/cli-ref.mjs';
36
35
  import {
37
36
  QA_PLAN_FILE, parseQaPlanDoc, renderQaPlanDoc, validateQaPlan,
38
37
  } from '../lib/qa-plan-doc.mjs';
@@ -54,13 +53,13 @@ class QaPlanBlockedError extends Error {
54
53
  }
55
54
 
56
55
  // Sobe a cadeia de pais até achar a Feature (mesma mecânica do implement).
57
- async function resolveParentFeature(token, startNodeId) {
58
- let current = startNodeId;
56
+ async function resolveParentFeature(tracker, startRef) {
57
+ let current = startRef;
59
58
  for (let depth = 0; depth < 5 && current; depth++) {
60
- const parent = await getIssueParent(token, current);
59
+ const parent = await tracker.getParent({ ref: current });
61
60
  if (!parent) return null;
62
61
  if (detectIssueType({ title: parent.title }) === 'Feature') return parent;
63
- current = parent.nodeId;
62
+ current = parent.ref;
64
63
  }
65
64
  return null;
66
65
  }
@@ -71,36 +70,45 @@ export async function generateQaPlan({ issueNumber }) {
71
70
  console.log(`Modo de execução: ${runMode}`);
72
71
 
73
72
  const number = parseInt(issueNumber, 10);
74
- const issue = await getIssue(token, owner, repo, number);
73
+ const tracker = createGithubTracker({ token, owner, repo });
74
+ const scm = createGithubScm({ link: githubLink({ owner, repo }), token });
75
+ const ref = { key: String(number) };
76
+ const issue = await tracker.getWorkItem({ ref });
75
77
  const type = detectIssueType(issue);
76
78
  const labels = labelNames(issue);
77
79
 
78
80
  // ── Escopo por tipo (spec §3): o plano é POR FEATURE, arquivo único ────────
79
81
  if (type !== 'Feature') {
80
82
  console.log(`Issue #${number} é ${type || 'desconhecido'} — qa-plan é gerado só para Feature.`);
81
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
83
+ await tracker.removeTag({ ref, tag: LABEL_QA }).catch(() => {});
82
84
  if (type === 'Story') {
83
- const feature = await resolveParentFeature(token, issue.node_id).catch(() => null);
84
- await commentOnIssue(token, owner, repo, number,
85
- `ℹ️ **O plano de QA é por Feature, não por Story** (D-QA1). ` +
86
- (feature
87
- ? `Aplique \`${LABEL_QA}\` na Feature-pai **#${feature.number}** — o plano dela ` +
88
- `cobre esta Story com seções \`## Cenário N — Story #${number}\`.`
89
- : 'Não encontrei a Feature-pai desta Story — vincule-a como sub-issue de uma Feature e ' +
90
- `aplique \`${LABEL_QA}\` lá.`) +
91
- `\n\nPara **executar** os cenários desta Story: \`npx @spec-wave/cli@latest qa ${number}\`.`
92
- ).catch(() => {});
85
+ const feature = await resolveParentFeature(tracker, issue.ref).catch(() => null);
86
+ await tracker.addComment({
87
+ ref: { key: String(number) },
88
+ body:
89
+ `ℹ️ **O plano de QA é por Feature, não por Story** (D-QA1). ` +
90
+ (feature
91
+ ? `Aplique \`${LABEL_QA}\` na Feature-pai **#${feature.ref.key}** — o plano dela ` +
92
+ `cobre esta Story com seções \`## Cenário N — Story #${number}\`.`
93
+ : 'Não encontrei a Feature-pai desta Story — vincule-a como sub-issue de uma Feature e ' +
94
+ `aplique \`${LABEL_QA}\` lá.`) +
95
+ `\n\nPara **executar** os cenários desta Story: \`npx ${cliRef()} qa ${number}\`.`,
96
+ }).catch(() => {});
93
97
  } else if (type === 'Bug') {
94
- await commentOnIssue(token, owner, repo, number,
95
- `ℹ️ **Bug não gera plano de QA:** o QA de um Bug usa a seção ` +
96
- '`Teste de Regressão` do próprio `bug.md`. ' +
97
- `Execute direto: \`npx @spec-wave/cli@latest qa ${number}\`.`
98
- ).catch(() => {});
98
+ await tracker.addComment({
99
+ ref: { key: String(number) },
100
+ body:
101
+ `ℹ️ **Bug não gera plano de QA:** o QA de um Bug usa a seção ` +
102
+ '`Teste de Regressão` do próprio `bug.md`. ' +
103
+ `Execute direto: \`npx ${cliRef()} qa ${number}\`.`,
104
+ }).catch(() => {});
99
105
  } else {
100
- await commentOnIssue(token, owner, repo, number,
101
- `ℹ️ **qa-plan não se aplica a ${type || 'este tipo'}.** ` +
102
- 'O plano de QA é gerado para **Features** (um arquivo, com cenários por Story).'
103
- ).catch(() => {});
106
+ await tracker.addComment({
107
+ ref: { key: String(number) },
108
+ body:
109
+ `ℹ️ **qa-plan não se aplica a ${type || 'este tipo'}.** ` +
110
+ 'O plano de QA é gerado para **Features** (um arquivo, com cenários por Story).',
111
+ }).catch(() => {});
104
112
  }
105
113
  return;
106
114
  }
@@ -111,11 +119,13 @@ export async function generateQaPlan({ issueNumber }) {
111
119
  [LABEL_CRITIQUE_FAILED, 'corrija o documento apontado no comentário 🔎 e remova a label'],
112
120
  ]) {
113
121
  if (labels.includes(label)) {
114
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
115
- await commentOnIssue(token, owner, repo, number,
116
- `⏸️ **generate-qa-plan parado:** a issue tem a label \`${label}\` — ${remedio}, ` +
117
- `e reaplique \`${LABEL_QA}\`.`
118
- ).catch(() => {});
122
+ await tracker.removeTag({ ref, tag: LABEL_QA }).catch(() => {});
123
+ await tracker.addComment({
124
+ ref: { key: String(number) },
125
+ body:
126
+ `⏸️ **generate-qa-plan parado:** a issue tem a label \`${label}\` — ${remedio}, ` +
127
+ `e reaplique \`${LABEL_QA}\`.`,
128
+ }).catch(() => {});
119
129
  throw new QaPlanBlockedError(`portão humano pendente: ${label}`);
120
130
  }
121
131
  }
@@ -124,7 +134,7 @@ export async function generateQaPlan({ issueNumber }) {
124
134
  if (!root) throw new Error(missingRootMessage('generate-qa-plan', executionMode()));
125
135
  const { rel: dirRel } = resolveDocDir(root, issue, type);
126
136
  const docRel = `${dirRel}/${QA_PLAN_FILE}`;
127
- const base = await getRepoDefaultBranch(token, owner, repo).catch(() => null);
137
+ const base = await scm.defaultBranch().catch(() => null);
128
138
 
129
139
  const ler = (doc, pathRel) => loadArtifact({
130
140
  token, owner, repo, root, pathRel, doc, issueNumber: number, base,
@@ -138,11 +148,13 @@ export async function generateQaPlan({ issueNumber }) {
138
148
  const bloqueio = awaitingMergeBlock({
139
149
  pathRel: `${dirRel}/${nome}`, state: doc.state, pr: doc.pr, branch: doc.ref,
140
150
  });
141
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
142
- await commentOnIssue(token, owner, repo, number,
143
- `⏸️ **generate-qa-plan parado:** ${bloqueio.message}\n\n${bloqueio.unblock}\n\n` +
144
- `Reaplique \`${LABEL_QA}\` depois do merge.`
145
- ).catch(() => {});
151
+ await tracker.removeTag({ ref, tag: LABEL_QA }).catch(() => {});
152
+ await tracker.addComment({
153
+ ref: { key: String(number) },
154
+ body:
155
+ `⏸️ **generate-qa-plan parado:** ${bloqueio.message}\n\n${bloqueio.unblock}\n\n` +
156
+ `Reaplique \`${LABEL_QA}\` depois do merge.`,
157
+ }).catch(() => {});
146
158
  throw new QaPlanBlockedError(bloqueio.message);
147
159
  }
148
160
  }
@@ -150,56 +162,64 @@ export async function generateQaPlan({ issueNumber }) {
150
162
  .filter(([, doc]) => doc.content == null).map(([nome]) => nome);
151
163
  if (ausentes.length > 0) {
152
164
  console.log(`Documentos ausentes: ${ausentes.join(', ')} — nada gerado.`);
153
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
154
- await commentOnIssue(token, owner, repo, number,
155
- `ℹ️ **Plano de QA não gerado:** falta ${ausentes.map(a => `\`${a}\``).join(' e ')} em \`${dirRel}/\`. ` +
156
- 'O plano deriva dos critérios de aceite da spec — gere e valide spec/plan primeiro, ' +
157
- `depois reaplique \`${LABEL_QA}\`.`
158
- ).catch(() => {});
165
+ await tracker.removeTag({ ref, tag: LABEL_QA }).catch(() => {});
166
+ await tracker.addComment({
167
+ ref: { key: String(number) },
168
+ body:
169
+ `ℹ️ **Plano de QA não gerado:** falta ${ausentes.map(a => `\`${a}\``).join(' e ')} em \`${dirRel}/\`. ` +
170
+ 'O plano deriva dos critérios de aceite da spec — gere e valide spec/plan primeiro, ' +
171
+ `depois reaplique \`${LABEL_QA}\`.`,
172
+ }).catch(() => {});
159
173
  return;
160
174
  }
161
175
 
162
176
  // ── Stories da Feature: o plano mapeia cenário → Story real ────────────────
163
177
  let subIssues = [];
164
178
  try {
165
- subIssues = await listSubIssues(token, issue.node_id);
179
+ subIssues = await tracker.listChildren({ ref: issue.ref });
166
180
  } catch (err) {
167
181
  // Sem a árvore não há como validar as referências `Story #X` — e um plano
168
182
  // publicado sem essa checagem é o que a validação determinística existe
169
183
  // para impedir.
170
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
171
- await commentOnIssue(token, owner, repo, number,
172
- `❌ **generate-qa-plan falhou:** não consegui listar as sub-issues da Feature ` +
173
- `(${err.message}). Reaplique \`${LABEL_QA}\` para tentar de novo.`
174
- ).catch(() => {});
184
+ await tracker.removeTag({ ref, tag: LABEL_QA }).catch(() => {});
185
+ await tracker.addComment({
186
+ ref: { key: String(number) },
187
+ body:
188
+ `❌ **generate-qa-plan falhou:** não consegui listar as sub-issues da Feature ` +
189
+ `(${err.message}). Reaplique \`${LABEL_QA}\` para tentar de novo.`,
190
+ }).catch(() => {});
175
191
  throw new QaPlanBlockedError(`sub-issues não legíveis: ${err.message}`);
176
192
  }
177
- const stories = subIssues.filter(s => detectIssueType({ title: s.title, labels: s.labels }) === 'Story');
193
+ const stories = subIssues.filter(s => detectIssueType(s) === 'Story');
178
194
  if (stories.length === 0) {
179
195
  console.log('Feature sem Stories — nada a planejar.');
180
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
181
- await commentOnIssue(token, owner, repo, number,
182
- 'ℹ️ **Plano de QA não gerado:** a Feature não tem Stories (sub-issues). ' +
183
- `Decomponha primeiro (\`spec-wave:decompose\`) e reaplique \`${LABEL_QA}\`.`
184
- ).catch(() => {});
196
+ await tracker.removeTag({ ref, tag: LABEL_QA }).catch(() => {});
197
+ await tracker.addComment({
198
+ ref: { key: String(number) },
199
+ body:
200
+ 'ℹ️ **Plano de QA não gerado:** a Feature não tem Stories (sub-issues). ' +
201
+ `Decomponha primeiro (\`spec-wave:decompose\`) e reaplique \`${LABEL_QA}\`.`,
202
+ }).catch(() => {});
185
203
  return;
186
204
  }
187
205
 
188
206
  const usageEntries = [];
189
207
  try {
190
208
  await runDraftOrCritique({
191
- token, owner, repo, issue, number, labels, config, root, runMode,
209
+ token, owner, repo, tracker, scm, ref, issue, number, labels, config, root, runMode,
192
210
  dirRel, docRel, base, spec, plan, stories, usage: usageEntries, ler,
193
211
  });
194
212
  } catch (err) {
195
213
  if (!err.blocked) {
196
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
197
- await commentOnIssue(token, owner, repo, number,
198
- '❌ **Falha ao gerar o plano de QA**\n\n' +
199
- `\`\`\`\n${err.message}\n\`\`\`\n\n` +
200
- `A label \`${LABEL_QA}\` foi removida para destravar o gatilho — ` +
201
- 'adicione-a de novo para tentar outra vez.'
202
- ).catch(() => {});
214
+ await tracker.removeTag({ ref, tag: LABEL_QA }).catch(() => {});
215
+ await tracker.addComment({
216
+ ref: { key: String(number) },
217
+ body:
218
+ '❌ **Falha ao gerar o plano de QA**\n\n' +
219
+ `\`\`\`\n${err.message}\n\`\`\`\n\n` +
220
+ `A label \`${LABEL_QA}\` foi removida para destravar o gatilho — ` +
221
+ 'adicione-a de novo para tentar outra vez.',
222
+ }).catch(() => {});
203
223
  }
204
224
  throw err;
205
225
  } finally {
@@ -209,9 +229,11 @@ export async function generateQaPlan({ issueNumber }) {
209
229
 
210
230
  async function runDraftOrCritique(ctx) {
211
231
  const {
212
- token, owner, repo, issue, number, labels, config, root, runMode,
232
+ token, owner, repo, tracker, scm, ref, issue, number, labels, config, root, runMode,
213
233
  dirRel, docRel, base, spec, plan, stories, usage, ler,
214
234
  } = ctx;
235
+ // O resto da função chama a issue de `issueNumber` desde antes das portas.
236
+ const issueNumber = number;
215
237
 
216
238
  // Plano existente é preservado COMO ESTÁ — inclusive o que vive num PR ainda
217
239
  // não mergeado (é lá que o revisor edita). Mesma invariante do decompose.
@@ -234,7 +256,7 @@ async function runDraftOrCritique(ctx) {
234
256
  console.log(`Gerando plano de QA para: ${issue.title}`);
235
257
  const payload = {
236
258
  feature: { number, title: issue.title },
237
- stories: stories.map(s => ({ number: s.number, title: s.title, body: s.body || '' })),
259
+ stories: stories.map(s => ({ number: Number(s.ref.key), title: s.title, body: s.body || '' })),
238
260
  spec: spec.content,
239
261
  plan: plan.content,
240
262
  };
@@ -269,7 +291,7 @@ async function runDraftOrCritique(ctx) {
269
291
  });
270
292
  publicado = await publishArtifact({
271
293
  token, owner, repo, doc: 'qa-plan',
272
- issueNumber: number, issueTitle: issue.title, issueUrl: issue.html_url,
294
+ issueNumber: number, issueTitle: issue.title, issueUrl: issue.ref.url,
273
295
  pathRel: docRel, content: markdown, base,
274
296
  });
275
297
  if (publicado.warning) console.warn(`⚠️ ${publicado.warning}`);
@@ -286,13 +308,15 @@ async function runDraftOrCritique(ctx) {
286
308
  try {
287
309
  doc = parseQaPlanDoc(markdown);
288
310
  } catch (err) {
289
- await commentOnIssue(token, owner, repo, number,
290
- `❌ **Não consegui ler o plano de QA.**\n\n` +
291
- `\`\`\`\n${err.message}\n\`\`\`\n\n` +
292
- `Corrija [\`${docRel}\`](${blobUrl}) e reaplique \`${LABEL_QA}\`. ` +
293
- 'Para começar de novo do zero, apague o arquivo.'
294
- ).catch(() => {});
295
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
311
+ await tracker.addComment({
312
+ ref: { key: String(number) },
313
+ body:
314
+ `❌ **Não consegui ler o plano de QA.**\n\n` +
315
+ `\`\`\`\n${err.message}\n\`\`\`\n\n` +
316
+ `Corrija [\`${docRel}\`](${blobUrl}) e reaplique \`${LABEL_QA}\`. ` +
317
+ 'Para começar de novo do zero, apague o arquivo.',
318
+ }).catch(() => {});
319
+ await tracker.removeTag({ ref, tag: LABEL_QA }).catch(() => {});
296
320
  throw new QaPlanBlockedError(err.message);
297
321
  }
298
322
 
@@ -300,13 +324,15 @@ async function runDraftOrCritique(ctx) {
300
324
  const errosDeterministicos = validateQaPlan({ doc, stories, content: markdown });
301
325
  if (errosDeterministicos.length > 0) {
302
326
  console.log(`Validação determinística reprovou: ${errosDeterministicos.length} problema(s) — crítica não executada.`);
303
- await commentOnIssue(token, owner, repo, number,
304
- '⚠️ **Plano de QA reprovado na validação determinística** (a crítica adversarial ' +
305
- 'nem chegou a rodar — nada de IA foi gasto):\n\n' +
306
- errosDeterministicos.map(e => `- ${e}`).join('\n') +
307
- `\n\nCorrija [\`${docRel}\`](${blobUrl}) e reaplique \`${LABEL_QA}\`.`
308
- ).catch(() => {});
309
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
327
+ await tracker.addComment({
328
+ ref: { key: String(number) },
329
+ body:
330
+ '⚠️ **Plano de QA reprovado na validação determinística** (a crítica adversarial ' +
331
+ 'nem chegou a rodar — nada de IA foi gasto):\n\n' +
332
+ errosDeterministicos.map(e => `- ${e}`).join('\n') +
333
+ `\n\nCorrija [\`${docRel}\`](${blobUrl}) e reaplique \`${LABEL_QA}\`.`,
334
+ }).catch(() => {});
335
+ await tracker.removeTag({ ref, tag: LABEL_QA }).catch(() => {});
310
336
  throw new QaPlanBlockedError(
311
337
  `validação determinística reprovou o plano: ${errosDeterministicos[0]}`
312
338
  );
@@ -314,7 +340,7 @@ async function runDraftOrCritique(ctx) {
314
340
  console.log(`Plano válido: ${doc.scenarios.length} cenário(s) cobrindo ${stories.length} Story(ies).`);
315
341
 
316
342
  // ── Crítica adversarial (kind 'qa') — mesma máquina de tentativas ──────────
317
- const comments = await listIssueComments(token, owner, repo, number).catch(err => {
343
+ const comments = await tracker.listComments({ ref }).catch(err => {
318
344
  console.warn(`Não foi possível listar comentários: ${err.message} — contador de tentativas em 1.`);
319
345
  return [];
320
346
  });
@@ -327,10 +353,9 @@ async function runDraftOrCritique(ctx) {
327
353
 
328
354
  if (blocked) {
329
355
  console.log(`Teto de ${maxAttempts} tentativas de crítica atingido — exigindo revisão humana.`);
330
- await commentOnIssue(token, owner, repo, number,
331
- renderNeedsHumanComment({ kind: 'qa', attempt, maxAttempts, escalationModel })).catch(() => {});
332
- await addLabel(token, owner, repo, number, LABEL_NEEDS_HUMAN);
333
- await removeLabel(token, owner, repo, number, LABEL_QA);
356
+ await tracker.addComment({ ref, body: renderNeedsHumanComment({ kind: 'qa', attempt, maxAttempts, escalationModel }) }).catch(() => {});
357
+ await tracker.addTag({ ref, tag: LABEL_NEEDS_HUMAN });
358
+ await tracker.removeTag({ ref, tag: LABEL_QA });
334
359
  throw new QaPlanBlockedError(
335
360
  `A crítica reprovou ${maxAttempts - 1}x seguidas. Label ${LABEL_NEEDS_HUMAN} aplicada.`
336
361
  );
@@ -359,40 +384,41 @@ async function runDraftOrCritique(ctx) {
359
384
  } catch (err) {
360
385
  // O verde do QA é automático (D-QA3), então o portão do plano não pode ser
361
386
  // pulado: sem crítica não há `qa-ready`, e o run fica vermelho.
362
- await commentOnIssue(token, owner, repo, number,
363
- `❌ **A crítica adversarial do plano de QA não concluiu.**\n\n` +
364
- `\`\`\`\n${err.message}\n\`\`\`\n\n` +
365
- `O plano está em [\`${docRel}\`](${blobUrl}), mas **sem crítica não há liberação** — ` +
366
- `o verde do QA avança o board sozinho, e este é o portão. Reaplique \`${LABEL_QA}\`.`
367
- ).catch(() => {});
368
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
387
+ await tracker.addComment({
388
+ ref: { key: String(number) },
389
+ body:
390
+ `❌ **A crítica adversarial do plano de QA não concluiu.**\n\n` +
391
+ `\`\`\`\n${err.message}\n\`\`\`\n\n` +
392
+ `O plano está em [\`${docRel}\`](${blobUrl}), mas **sem crítica não há liberação** — ` +
393
+ `o verde do QA avança o board sozinho, e este é o portão. Reaplique \`${LABEL_QA}\`.`,
394
+ }).catch(() => {});
395
+ await tracker.removeTag({ ref, tag: LABEL_QA }).catch(() => {});
369
396
  throw new QaPlanBlockedError(`Crítica adversarial não concluiu: ${err.message}`);
370
397
  }
371
398
 
372
- await commentOnIssue(token, owner, repo, number, critique.markdown)
399
+ await tracker.addComment({ ref, body: critique.markdown })
373
400
  .catch(err => console.warn(`Falha ao comentar a crítica: ${err.message}`));
374
401
 
375
402
  const { blocking, accepted } = applyCritiqueDecisions(critique.findings, decisions, 'qa');
376
403
  if (accepted.length > 0) {
377
- await addLabel(token, owner, repo, number, LABEL_RISK_ACCEPTED).catch(() => {});
378
- await commentOnIssue(token, owner, repo, number,
379
- renderRiskAcceptedComment({ kind: 'qa', accepted })).catch(() => {});
404
+ await tracker.addTag({ ref, tag: LABEL_RISK_ACCEPTED }).catch(() => {});
405
+ await tracker.addComment({ ref, body: renderRiskAcceptedComment({ kind: 'qa', accepted }) }).catch(() => {});
380
406
  }
381
407
  if (blocking.length > 0) {
382
408
  console.log(`Crítica apontou ${blocking.length} finding(s) GRAVE(s) sem decisão.`);
383
- await addLabel(token, owner, repo, number, LABEL_CRITIQUE_FAILED);
384
- await removeLabel(token, owner, repo, number, LABEL_QA_READY).catch(() => {});
385
- await removeLabel(token, owner, repo, number, LABEL_QA);
409
+ await tracker.addTag({ ref, tag: LABEL_CRITIQUE_FAILED });
410
+ await tracker.removeTag({ ref, tag: LABEL_QA_READY }).catch(() => {});
411
+ await tracker.removeTag({ ref, tag: LABEL_QA });
386
412
  throw new QaPlanBlockedError(
387
413
  `A crítica adversarial apontou findings graves no plano (tentativa ${attempt}). ` +
388
414
  `Corrija ${docRel} e reaplique ${LABEL_QA}.`
389
415
  );
390
416
  }
391
- await removeLabel(token, owner, repo, number, LABEL_CRITIQUE_FAILED).catch(() => {});
417
+ await tracker.removeTag({ ref, tag: LABEL_CRITIQUE_FAILED }).catch(() => {});
392
418
 
393
419
  // ── Liberação: qa-ready = passou na validação + crítica, espera humano ─────
394
- await addLabel(token, owner, repo, number, LABEL_QA_READY);
395
- await removeLabel(token, owner, repo, number, LABEL_QA);
420
+ await tracker.addTag({ ref, tag: LABEL_QA_READY });
421
+ await tracker.removeTag({ ref, tag: LABEL_QA });
396
422
 
397
423
  const porStory = new Map();
398
424
  for (const s of doc.scenarios) porStory.set(s.story, (porStory.get(s.story) || 0) + 1);
@@ -406,18 +432,20 @@ async function runDraftOrCritique(ctx) {
406
432
  'são preservadas) e faça o merge. '
407
433
  : '**Revise o plano** (edite o que precisar — as edições são preservadas). ';
408
434
 
409
- await commentOnIssue(token, owner, repo, number,
410
- `🧪 **Plano de QA pronto para revisão humana** (${doc.scenarios.length} cenário(s)).\n\n` +
411
- `📄 Arquivo: [\`${docRel}\`](${blobUrl})\n\n${resumo}\n\n` +
412
- 'A crítica adversarial não encontrou problemas graves e a label ' +
413
- `\`${LABEL_QA_READY}\` foi aplicada — **ela é o portão humano**: o veredito verde da ` +
414
- 'execução avança a Etapa sozinho, então revise os cenários ANTES de rodar.\n\n' +
415
- revisao +
416
- 'Depois execute localmente:\n' +
417
- `\`\`\`\nnpx @spec-wave/cli@latest qa ${number} --dry-run\nnpx @spec-wave/cli@latest qa ${number}\n\`\`\`\n` +
418
- `Para uma nova crítica depois de editar, reaplique \`${LABEL_QA}\` — o arquivo é ` +
419
- 'criticado como está, sem ser regerado. Para gerar outro do zero, apague o arquivo.'
420
- ).catch(err => console.warn(`Falha ao comentar a liberação: ${err.message}`));
435
+ await tracker.addComment({
436
+ ref: { key: String(number) },
437
+ body:
438
+ `🧪 **Plano de QA pronto para revisão humana** (${doc.scenarios.length} cenário(s)).\n\n` +
439
+ `📄 Arquivo: [\`${docRel}\`](${blobUrl})\n\n${resumo}\n\n` +
440
+ 'A crítica adversarial não encontrou problemas graves e a label ' +
441
+ `\`${LABEL_QA_READY}\` foi aplicada — **ela é o portão humano**: o veredito verde da ` +
442
+ 'execução avança a Etapa sozinho, então revise os cenários ANTES de rodar.\n\n' +
443
+ revisao +
444
+ 'Depois execute localmente:\n' +
445
+ `\`\`\`\nnpx ${cliRef()} qa ${number} --dry-run\nnpx ${cliRef()} qa ${number}\n\`\`\`\n` +
446
+ `Para uma nova crítica depois de editar, reaplique \`${LABEL_QA}\` — o arquivo é ` +
447
+ 'criticado como está, sem ser regerado. Para gerar outro do zero, apague o arquivo.',
448
+ }).catch(err => console.warn(`Falha ao comentar a liberação: ${err.message}`));
421
449
  console.log(`Plano de QA liberado para revisão (${doc.scenarios.length} cenário(s)).`);
422
450
  return { pr: pr || null };
423
451
  }
@@ -1,5 +1,5 @@
1
1
  import { resolveToken } from '../api/auth.mjs';
2
- import { getIssue, removeLabel, commentOnIssue } from '../api/github-rest.mjs';
2
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
3
3
  import { generateDocument } from '../lib/claude.mjs';
4
4
  import { unwrapGeneratedDoc } from '../lib/unwrap-doc.mjs';
5
5
  import { recordUsage } from '../lib/usage-report.mjs';
@@ -36,7 +36,9 @@ export async function generateSpec({ issueNumber }) {
36
36
  console.log(`Modo de execução: ${mode}`);
37
37
 
38
38
  console.log(`Buscando issue #${issueNumber}...`);
39
- const issue = await getIssue(token, owner, repo, parseInt(issueNumber, 10));
39
+ const tracker = createGithubTracker({ token, owner, repo });
40
+ const ref = { key: String(issueNumber) };
41
+ const issue = await tracker.getWorkItem({ ref });
40
42
 
41
43
  // spec.md/plan.md são artefatos funcionais de Feature — não se aplicam a
42
44
  // Spike/RFC/Bug. Pula a geração, remove o trigger e avisa na issue.
@@ -45,12 +47,13 @@ export async function generateSpec({ issueNumber }) {
45
47
  const issueLabels = labelNames(issue);
46
48
  if (!allowsSpecPlan(type)) {
47
49
  console.log(`Issue #${issueNumber} é ${type}: spec.md não é gerada para ${SPEC_PLAN_EXCLUDED_TYPES.join('/')}.`);
48
- await removeLabel(token, owner, repo, parseInt(issueNumber, 10), 'spec-wave:spec');
49
- await commentOnIssue(
50
- token, owner, repo, parseInt(issueNumber, 10),
51
- `ℹ️ **spec.md não gerada:** o tipo **${type}** não usa spec/plan no fluxo spec-wave ` +
52
- `(esses artefatos são exclusivos de Features). Nenhum arquivo foi criado.`
53
- ).catch(() => {});
50
+ await tracker.removeTag({ ref, tag: 'spec-wave:spec' });
51
+ await tracker.addComment({
52
+ ref,
53
+ body:
54
+ `ℹ️ **spec.md não gerada:** o tipo **${type}** não usa spec/plan no fluxo spec-wave ` +
55
+ `(esses artefatos são exclusivos de Features). Nenhum arquivo foi criado.`,
56
+ }).catch(() => {});
54
57
  return;
55
58
  }
56
59
 
@@ -65,7 +68,7 @@ export async function generateSpec({ issueNumber }) {
65
68
  metadata: {
66
69
  feature_title: issue.title,
67
70
  feature_description: issue.body || '(sem descrição)',
68
- labels: (issue.labels || []).map((l) => (typeof l === 'string' ? l : l.name)),
71
+ labels: issue.tags,
69
72
  },
70
73
  business_input: {
71
74
  raw: issue.body || '(sem descrição)',
@@ -99,7 +102,7 @@ export async function generateSpec({ issueNumber }) {
99
102
  doc: 'spec',
100
103
  issueNumber: parseInt(issueNumber, 10),
101
104
  issueTitle: issue.title,
102
- issueUrl: issue.html_url,
105
+ issueUrl: issue.ref.url,
103
106
  pathRel: fileRel,
104
107
  content,
105
108
  nextLabel: 'spec-wave:plan',
@@ -107,18 +110,19 @@ export async function generateSpec({ issueNumber }) {
107
110
  if (published.warning) console.warn(`⚠️ ${published.warning}`);
108
111
 
109
112
  // Remove trigger label
110
- await removeLabel(token, owner, repo, parseInt(issueNumber, 10), 'spec-wave:spec');
113
+ await tracker.removeTag({ ref, tag: 'spec-wave:spec' });
111
114
 
112
115
  // Comment on issue
113
- await commentOnIssue(
114
- token, owner, repo, parseInt(issueNumber, 10),
115
- `📋 **spec.md gerado automaticamente!**\n\n` +
116
- `📄 Arquivo: [\`${fileRel}\`](${published.blobUrl})\n\n` +
117
- `${renderPrLine(published)}\n\n` +
118
- `Revise a especificação **no Pull Request** e faça o merge. Depois, gere o plano técnico: mova o card para **📋 Plan** ou use:\n` +
119
- `\`\`\`\ngh issue edit ${issueNumber} --add-label "spec-wave:plan"\n\`\`\`` +
120
- formatLintWarning(lintFindings)
121
- );
116
+ await tracker.addComment({
117
+ ref,
118
+ body:
119
+ `📋 **spec.md gerado automaticamente!**\n\n` +
120
+ `📄 Arquivo: [\`${fileRel}\`](${published.blobUrl})\n\n` +
121
+ `${renderPrLine(published)}\n\n` +
122
+ `Revise a especificação **no Pull Request** e faça o merge. Depois, gere o plano técnico: mova o card para **📋 Plan** ou use:\n` +
123
+ `\`\`\`\ngh issue edit ${issueNumber} --add-label "spec-wave:plan"\n\`\`\`` +
124
+ formatLintWarning(lintFindings),
125
+ });
122
126
 
123
127
  console.log(`spec.md publicado em ${published.branch} (${fileRel}).`);
124
128
  // Devolvido para o `run` saber que o próximo passo depende de um merge.
@@ -129,14 +133,15 @@ export async function generateSpec({ issueNumber }) {
129
133
  // a issue vira um beco sem saída, sem comentário e sem sinal no board.
130
134
  // Espelha o tratamento do tipo não suportado (acima): remove o gatilho e
131
135
  // reporta na issue. O erro segue propagando para o Action falhar visível.
132
- await removeLabel(token, owner, repo, parseInt(issueNumber, 10), 'spec-wave:spec').catch(() => {});
133
- await commentOnIssue(
134
- token, owner, repo, parseInt(issueNumber, 10),
135
- `❌ **Falha ao gerar a spec.md**\n\n` +
136
- `\`\`\`\n${err.message}\n\`\`\`\n\n` +
137
- `A label \`spec-wave:spec\` foi removida para destravar o gatilho — ` +
138
- `adicione-a de novo para tentar outra vez.`
139
- ).catch(() => {});
136
+ await tracker.removeTag({ ref, tag: 'spec-wave:spec' }).catch(() => {});
137
+ await tracker.addComment({
138
+ ref,
139
+ body:
140
+ `❌ **Falha ao gerar a spec.md**\n\n` +
141
+ `\`\`\`\n${err.message}\n\`\`\`\n\n` +
142
+ `A label \`spec-wave:spec\` foi removida para destravar o gatilho — ` +
143
+ `adicione-a de novo para tentar outra vez.`,
144
+ }).catch(() => {});
140
145
  throw err;
141
146
  } finally {
142
147
  // Best-effort: nunca propaga erro (ver recordUsage).