@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
@@ -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';
@@ -55,13 +53,13 @@ class QaPlanBlockedError extends Error {
55
53
  }
56
54
 
57
55
  // Sobe a cadeia de pais até achar a Feature (mesma mecânica do implement).
58
- async function resolveParentFeature(token, startNodeId) {
59
- let current = startNodeId;
56
+ async function resolveParentFeature(tracker, startRef) {
57
+ let current = startRef;
60
58
  for (let depth = 0; depth < 5 && current; depth++) {
61
- const parent = await getIssueParent(token, current);
59
+ const parent = await tracker.getParent({ ref: current });
62
60
  if (!parent) return null;
63
61
  if (detectIssueType({ title: parent.title }) === 'Feature') return parent;
64
- current = parent.nodeId;
62
+ current = parent.ref;
65
63
  }
66
64
  return null;
67
65
  }
@@ -72,36 +70,45 @@ export async function generateQaPlan({ issueNumber }) {
72
70
  console.log(`Modo de execução: ${runMode}`);
73
71
 
74
72
  const number = parseInt(issueNumber, 10);
75
- 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 });
76
77
  const type = detectIssueType(issue);
77
78
  const labels = labelNames(issue);
78
79
 
79
80
  // ── Escopo por tipo (spec §3): o plano é POR FEATURE, arquivo único ────────
80
81
  if (type !== 'Feature') {
81
82
  console.log(`Issue #${number} é ${type || 'desconhecido'} — qa-plan é gerado só para Feature.`);
82
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
83
+ await tracker.removeTag({ ref, tag: LABEL_QA }).catch(() => {});
83
84
  if (type === 'Story') {
84
- const feature = await resolveParentFeature(token, issue.node_id).catch(() => null);
85
- await commentOnIssue(token, owner, repo, number,
86
- `ℹ️ **O plano de QA é por Feature, não por Story** (D-QA1). ` +
87
- (feature
88
- ? `Aplique \`${LABEL_QA}\` na Feature-pai **#${feature.number}** — o plano dela ` +
89
- `cobre esta Story com seções \`## Cenário N — Story #${number}\`.`
90
- : 'Não encontrei a Feature-pai desta Story — vincule-a como sub-issue de uma Feature e ' +
91
- `aplique \`${LABEL_QA}\` lá.`) +
92
- `\n\nPara **executar** os cenários desta Story: \`npx ${cliRef()} qa ${number}\`.`
93
- ).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(() => {});
94
97
  } else if (type === 'Bug') {
95
- await commentOnIssue(token, owner, repo, number,
96
- `ℹ️ **Bug não gera plano de QA:** o QA de um Bug usa a seção ` +
97
- '`Teste de Regressão` do próprio `bug.md`. ' +
98
- `Execute direto: \`npx ${cliRef()} qa ${number}\`.`
99
- ).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(() => {});
100
105
  } else {
101
- await commentOnIssue(token, owner, repo, number,
102
- `ℹ️ **qa-plan não se aplica a ${type || 'este tipo'}.** ` +
103
- 'O plano de QA é gerado para **Features** (um arquivo, com cenários por Story).'
104
- ).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(() => {});
105
112
  }
106
113
  return;
107
114
  }
@@ -112,11 +119,13 @@ export async function generateQaPlan({ issueNumber }) {
112
119
  [LABEL_CRITIQUE_FAILED, 'corrija o documento apontado no comentário 🔎 e remova a label'],
113
120
  ]) {
114
121
  if (labels.includes(label)) {
115
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
116
- await commentOnIssue(token, owner, repo, number,
117
- `⏸️ **generate-qa-plan parado:** a issue tem a label \`${label}\` — ${remedio}, ` +
118
- `e reaplique \`${LABEL_QA}\`.`
119
- ).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(() => {});
120
129
  throw new QaPlanBlockedError(`portão humano pendente: ${label}`);
121
130
  }
122
131
  }
@@ -125,7 +134,7 @@ export async function generateQaPlan({ issueNumber }) {
125
134
  if (!root) throw new Error(missingRootMessage('generate-qa-plan', executionMode()));
126
135
  const { rel: dirRel } = resolveDocDir(root, issue, type);
127
136
  const docRel = `${dirRel}/${QA_PLAN_FILE}`;
128
- const base = await getRepoDefaultBranch(token, owner, repo).catch(() => null);
137
+ const base = await scm.defaultBranch().catch(() => null);
129
138
 
130
139
  const ler = (doc, pathRel) => loadArtifact({
131
140
  token, owner, repo, root, pathRel, doc, issueNumber: number, base,
@@ -139,11 +148,13 @@ export async function generateQaPlan({ issueNumber }) {
139
148
  const bloqueio = awaitingMergeBlock({
140
149
  pathRel: `${dirRel}/${nome}`, state: doc.state, pr: doc.pr, branch: doc.ref,
141
150
  });
142
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
143
- await commentOnIssue(token, owner, repo, number,
144
- `⏸️ **generate-qa-plan parado:** ${bloqueio.message}\n\n${bloqueio.unblock}\n\n` +
145
- `Reaplique \`${LABEL_QA}\` depois do merge.`
146
- ).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(() => {});
147
158
  throw new QaPlanBlockedError(bloqueio.message);
148
159
  }
149
160
  }
@@ -151,56 +162,64 @@ export async function generateQaPlan({ issueNumber }) {
151
162
  .filter(([, doc]) => doc.content == null).map(([nome]) => nome);
152
163
  if (ausentes.length > 0) {
153
164
  console.log(`Documentos ausentes: ${ausentes.join(', ')} — nada gerado.`);
154
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
155
- await commentOnIssue(token, owner, repo, number,
156
- `ℹ️ **Plano de QA não gerado:** falta ${ausentes.map(a => `\`${a}\``).join(' e ')} em \`${dirRel}/\`. ` +
157
- 'O plano deriva dos critérios de aceite da spec — gere e valide spec/plan primeiro, ' +
158
- `depois reaplique \`${LABEL_QA}\`.`
159
- ).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(() => {});
160
173
  return;
161
174
  }
162
175
 
163
176
  // ── Stories da Feature: o plano mapeia cenário → Story real ────────────────
164
177
  let subIssues = [];
165
178
  try {
166
- subIssues = await listSubIssues(token, issue.node_id);
179
+ subIssues = await tracker.listChildren({ ref: issue.ref });
167
180
  } catch (err) {
168
181
  // Sem a árvore não há como validar as referências `Story #X` — e um plano
169
182
  // publicado sem essa checagem é o que a validação determinística existe
170
183
  // para impedir.
171
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
172
- await commentOnIssue(token, owner, repo, number,
173
- `❌ **generate-qa-plan falhou:** não consegui listar as sub-issues da Feature ` +
174
- `(${err.message}). Reaplique \`${LABEL_QA}\` para tentar de novo.`
175
- ).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(() => {});
176
191
  throw new QaPlanBlockedError(`sub-issues não legíveis: ${err.message}`);
177
192
  }
178
- const stories = subIssues.filter(s => detectIssueType({ title: s.title, labels: s.labels }) === 'Story');
193
+ const stories = subIssues.filter(s => detectIssueType(s) === 'Story');
179
194
  if (stories.length === 0) {
180
195
  console.log('Feature sem Stories — nada a planejar.');
181
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
182
- await commentOnIssue(token, owner, repo, number,
183
- 'ℹ️ **Plano de QA não gerado:** a Feature não tem Stories (sub-issues). ' +
184
- `Decomponha primeiro (\`spec-wave:decompose\`) e reaplique \`${LABEL_QA}\`.`
185
- ).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(() => {});
186
203
  return;
187
204
  }
188
205
 
189
206
  const usageEntries = [];
190
207
  try {
191
208
  await runDraftOrCritique({
192
- token, owner, repo, issue, number, labels, config, root, runMode,
209
+ token, owner, repo, tracker, scm, ref, issue, number, labels, config, root, runMode,
193
210
  dirRel, docRel, base, spec, plan, stories, usage: usageEntries, ler,
194
211
  });
195
212
  } catch (err) {
196
213
  if (!err.blocked) {
197
- await removeLabel(token, owner, repo, number, LABEL_QA).catch(() => {});
198
- await commentOnIssue(token, owner, repo, number,
199
- '❌ **Falha ao gerar o plano de QA**\n\n' +
200
- `\`\`\`\n${err.message}\n\`\`\`\n\n` +
201
- `A label \`${LABEL_QA}\` foi removida para destravar o gatilho — ` +
202
- 'adicione-a de novo para tentar outra vez.'
203
- ).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(() => {});
204
223
  }
205
224
  throw err;
206
225
  } finally {
@@ -210,9 +229,11 @@ export async function generateQaPlan({ issueNumber }) {
210
229
 
211
230
  async function runDraftOrCritique(ctx) {
212
231
  const {
213
- token, owner, repo, issue, number, labels, config, root, runMode,
232
+ token, owner, repo, tracker, scm, ref, issue, number, labels, config, root, runMode,
214
233
  dirRel, docRel, base, spec, plan, stories, usage, ler,
215
234
  } = ctx;
235
+ // O resto da função chama a issue de `issueNumber` desde antes das portas.
236
+ const issueNumber = number;
216
237
 
217
238
  // Plano existente é preservado COMO ESTÁ — inclusive o que vive num PR ainda
218
239
  // não mergeado (é lá que o revisor edita). Mesma invariante do decompose.
@@ -235,7 +256,7 @@ async function runDraftOrCritique(ctx) {
235
256
  console.log(`Gerando plano de QA para: ${issue.title}`);
236
257
  const payload = {
237
258
  feature: { number, title: issue.title },
238
- 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 || '' })),
239
260
  spec: spec.content,
240
261
  plan: plan.content,
241
262
  };
@@ -270,7 +291,7 @@ async function runDraftOrCritique(ctx) {
270
291
  });
271
292
  publicado = await publishArtifact({
272
293
  token, owner, repo, doc: 'qa-plan',
273
- issueNumber: number, issueTitle: issue.title, issueUrl: issue.html_url,
294
+ issueNumber: number, issueTitle: issue.title, issueUrl: issue.ref.url,
274
295
  pathRel: docRel, content: markdown, base,
275
296
  });
276
297
  if (publicado.warning) console.warn(`⚠️ ${publicado.warning}`);
@@ -287,13 +308,15 @@ async function runDraftOrCritique(ctx) {
287
308
  try {
288
309
  doc = parseQaPlanDoc(markdown);
289
310
  } catch (err) {
290
- await commentOnIssue(token, owner, repo, number,
291
- `❌ **Não consegui ler o plano de QA.**\n\n` +
292
- `\`\`\`\n${err.message}\n\`\`\`\n\n` +
293
- `Corrija [\`${docRel}\`](${blobUrl}) e reaplique \`${LABEL_QA}\`. ` +
294
- 'Para começar de novo do zero, apague o arquivo.'
295
- ).catch(() => {});
296
- 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(() => {});
297
320
  throw new QaPlanBlockedError(err.message);
298
321
  }
299
322
 
@@ -301,13 +324,15 @@ async function runDraftOrCritique(ctx) {
301
324
  const errosDeterministicos = validateQaPlan({ doc, stories, content: markdown });
302
325
  if (errosDeterministicos.length > 0) {
303
326
  console.log(`Validação determinística reprovou: ${errosDeterministicos.length} problema(s) — crítica não executada.`);
304
- await commentOnIssue(token, owner, repo, number,
305
- '⚠️ **Plano de QA reprovado na validação determinística** (a crítica adversarial ' +
306
- 'nem chegou a rodar — nada de IA foi gasto):\n\n' +
307
- errosDeterministicos.map(e => `- ${e}`).join('\n') +
308
- `\n\nCorrija [\`${docRel}\`](${blobUrl}) e reaplique \`${LABEL_QA}\`.`
309
- ).catch(() => {});
310
- 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(() => {});
311
336
  throw new QaPlanBlockedError(
312
337
  `validação determinística reprovou o plano: ${errosDeterministicos[0]}`
313
338
  );
@@ -315,7 +340,7 @@ async function runDraftOrCritique(ctx) {
315
340
  console.log(`Plano válido: ${doc.scenarios.length} cenário(s) cobrindo ${stories.length} Story(ies).`);
316
341
 
317
342
  // ── Crítica adversarial (kind 'qa') — mesma máquina de tentativas ──────────
318
- const comments = await listIssueComments(token, owner, repo, number).catch(err => {
343
+ const comments = await tracker.listComments({ ref }).catch(err => {
319
344
  console.warn(`Não foi possível listar comentários: ${err.message} — contador de tentativas em 1.`);
320
345
  return [];
321
346
  });
@@ -328,10 +353,9 @@ async function runDraftOrCritique(ctx) {
328
353
 
329
354
  if (blocked) {
330
355
  console.log(`Teto de ${maxAttempts} tentativas de crítica atingido — exigindo revisão humana.`);
331
- await commentOnIssue(token, owner, repo, number,
332
- renderNeedsHumanComment({ kind: 'qa', attempt, maxAttempts, escalationModel })).catch(() => {});
333
- await addLabel(token, owner, repo, number, LABEL_NEEDS_HUMAN);
334
- 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 });
335
359
  throw new QaPlanBlockedError(
336
360
  `A crítica reprovou ${maxAttempts - 1}x seguidas. Label ${LABEL_NEEDS_HUMAN} aplicada.`
337
361
  );
@@ -360,40 +384,41 @@ async function runDraftOrCritique(ctx) {
360
384
  } catch (err) {
361
385
  // O verde do QA é automático (D-QA3), então o portão do plano não pode ser
362
386
  // pulado: sem crítica não há `qa-ready`, e o run fica vermelho.
363
- await commentOnIssue(token, owner, repo, number,
364
- `❌ **A crítica adversarial do plano de QA não concluiu.**\n\n` +
365
- `\`\`\`\n${err.message}\n\`\`\`\n\n` +
366
- `O plano está em [\`${docRel}\`](${blobUrl}), mas **sem crítica não há liberação** — ` +
367
- `o verde do QA avança o board sozinho, e este é o portão. Reaplique \`${LABEL_QA}\`.`
368
- ).catch(() => {});
369
- 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(() => {});
370
396
  throw new QaPlanBlockedError(`Crítica adversarial não concluiu: ${err.message}`);
371
397
  }
372
398
 
373
- await commentOnIssue(token, owner, repo, number, critique.markdown)
399
+ await tracker.addComment({ ref, body: critique.markdown })
374
400
  .catch(err => console.warn(`Falha ao comentar a crítica: ${err.message}`));
375
401
 
376
402
  const { blocking, accepted } = applyCritiqueDecisions(critique.findings, decisions, 'qa');
377
403
  if (accepted.length > 0) {
378
- await addLabel(token, owner, repo, number, LABEL_RISK_ACCEPTED).catch(() => {});
379
- await commentOnIssue(token, owner, repo, number,
380
- 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(() => {});
381
406
  }
382
407
  if (blocking.length > 0) {
383
408
  console.log(`Crítica apontou ${blocking.length} finding(s) GRAVE(s) sem decisão.`);
384
- await addLabel(token, owner, repo, number, LABEL_CRITIQUE_FAILED);
385
- await removeLabel(token, owner, repo, number, LABEL_QA_READY).catch(() => {});
386
- 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 });
387
412
  throw new QaPlanBlockedError(
388
413
  `A crítica adversarial apontou findings graves no plano (tentativa ${attempt}). ` +
389
414
  `Corrija ${docRel} e reaplique ${LABEL_QA}.`
390
415
  );
391
416
  }
392
- await removeLabel(token, owner, repo, number, LABEL_CRITIQUE_FAILED).catch(() => {});
417
+ await tracker.removeTag({ ref, tag: LABEL_CRITIQUE_FAILED }).catch(() => {});
393
418
 
394
419
  // ── Liberação: qa-ready = passou na validação + crítica, espera humano ─────
395
- await addLabel(token, owner, repo, number, LABEL_QA_READY);
396
- 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 });
397
422
 
398
423
  const porStory = new Map();
399
424
  for (const s of doc.scenarios) porStory.set(s.story, (porStory.get(s.story) || 0) + 1);
@@ -407,18 +432,20 @@ async function runDraftOrCritique(ctx) {
407
432
  'são preservadas) e faça o merge. '
408
433
  : '**Revise o plano** (edite o que precisar — as edições são preservadas). ';
409
434
 
410
- await commentOnIssue(token, owner, repo, number,
411
- `🧪 **Plano de QA pronto para revisão humana** (${doc.scenarios.length} cenário(s)).\n\n` +
412
- `📄 Arquivo: [\`${docRel}\`](${blobUrl})\n\n${resumo}\n\n` +
413
- 'A crítica adversarial não encontrou problemas graves e a label ' +
414
- `\`${LABEL_QA_READY}\` foi aplicada — **ela é o portão humano**: o veredito verde da ` +
415
- 'execução avança a Etapa sozinho, então revise os cenários ANTES de rodar.\n\n' +
416
- revisao +
417
- 'Depois execute localmente:\n' +
418
- `\`\`\`\nnpx ${cliRef()} qa ${number} --dry-run\nnpx ${cliRef()} qa ${number}\n\`\`\`\n` +
419
- `Para uma nova crítica depois de editar, reaplique \`${LABEL_QA}\` — o arquivo é ` +
420
- 'criticado como está, sem ser regerado. Para gerar outro do zero, apague o arquivo.'
421
- ).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}`));
422
449
  console.log(`Plano de QA liberado para revisão (${doc.scenarios.length} cenário(s)).`);
423
450
  return { pr: pr || null };
424
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).