@spec-wave/cli 1.0.8 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/package.json +1 -1
  2. package/src/commands/audit.mjs +24 -18
  3. package/src/commands/code-review.mjs +89 -58
  4. package/src/commands/decompose.mjs +254 -218
  5. package/src/commands/generate-bug.mjs +51 -44
  6. package/src/commands/generate-plan.mjs +83 -63
  7. package/src/commands/generate-qa-plan.mjs +144 -117
  8. package/src/commands/generate-spec.mjs +33 -28
  9. package/src/commands/implement.mjs +154 -79
  10. package/src/commands/init.mjs +8 -3
  11. package/src/commands/issue.mjs +26 -39
  12. package/src/commands/merge.mjs +71 -20
  13. package/src/commands/mode.mjs +8 -4
  14. package/src/commands/move.mjs +16 -20
  15. package/src/commands/order.mjs +33 -22
  16. package/src/commands/preflight.mjs +24 -13
  17. package/src/commands/qa-lead.mjs +28 -16
  18. package/src/commands/qa-run.mjs +122 -101
  19. package/src/commands/qa.mjs +55 -44
  20. package/src/commands/refresh.mjs +24 -16
  21. package/src/commands/repair-stage.mjs +29 -16
  22. package/src/commands/repo.mjs +10 -3
  23. package/src/commands/run.mjs +23 -11
  24. package/src/commands/story.mjs +20 -25
  25. package/src/commands/task.mjs +21 -27
  26. package/src/commands/triage.mjs +33 -31
  27. package/src/commands/uninstall.mjs +7 -3
  28. package/src/commands/update.mjs +29 -21
  29. package/src/commands/validate.mjs +60 -52
  30. package/src/commands/workspace.mjs +7 -5
  31. package/src/config.mjs +7 -1
  32. package/src/lib/artifact-publish.mjs +20 -18
  33. package/src/lib/board-policy.mjs +144 -0
  34. package/src/lib/board.mjs +134 -233
  35. package/src/lib/doc-availability.mjs +10 -3
  36. package/src/lib/doc-source.mjs +9 -9
  37. package/src/lib/implement-board.mjs +23 -26
  38. package/src/lib/issue-type.mjs +5 -1
  39. package/src/lib/pr-ready.mjs +48 -10
  40. package/src/lib/pr-step.mjs +3 -1
  41. package/src/lib/qa-exec.mjs +3 -1
  42. package/src/lib/qa-lead.mjs +11 -3
  43. package/src/lib/qa-plan-doc.mjs +10 -4
  44. package/src/lib/spec-audit.mjs +1 -1
  45. package/src/lib/story-graph.mjs +62 -8
  46. package/src/lib/usage-report.mjs +8 -5
  47. package/src/lib/work-item-ref.mjs +176 -0
  48. package/src/plugin/.claude-plugin/plugin.json +1 -1
  49. package/src/plugins/scm-github/index.mjs +439 -0
  50. package/src/plugins/tracker-github-projects/fields.mjs +73 -0
  51. package/src/plugins/tracker-github-projects/index.mjs +625 -0
  52. package/src/ports/scm.mjs +197 -0
  53. package/src/ports/tracker.mjs +239 -0
  54. package/src/ports/types.mjs +254 -0
  55. package/src/setup/files.mjs +14 -12
  56. package/src/setup/labels.mjs +17 -12
  57. package/src/setup/project.mjs +40 -59
@@ -9,9 +9,7 @@
9
9
  // RELATADOS — sem o relato, ela só avalia coerência interna.
10
10
  // 3. Escreve em docs/bugs/<slug>/, fora de docs/features/.
11
11
  import { resolveToken } from '../api/auth.mjs';
12
- import {
13
- getIssue, removeLabel, addLabel, commentOnIssue, listIssueComments,
14
- } from '../api/github-rest.mjs';
12
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
15
13
  import { generateDocument } from '../lib/claude.mjs';
16
14
  import { unwrapGeneratedDoc } from '../lib/unwrap-doc.mjs';
17
15
  import { recordUsage } from '../lib/usage-report.mjs';
@@ -32,11 +30,14 @@ import {
32
30
  // Relato = corpo + comentários humanos, na ordem cronológica. Comentários do
33
31
  // próprio spec-wave são ruído aqui (críticas anteriores, relatórios de uso):
34
32
  // realimentá-los faria o modelo auditar a si mesmo em vez do defeito.
35
- function buildReport(issue, comments) {
33
+ export function buildReport(issue, comments) {
36
34
  const parts = [`### Descrição da issue\n\n${issue.body || '(sem descrição)'}`];
37
35
  const humanos = (comments || []).filter(c => !isSpecWaveComment(c.body));
38
36
  for (const c of humanos) {
39
- const autor = c.user?.login || 'desconhecido';
37
+ // `author` é a forma do contrato (CommentRef); `user.login` é a REST crua.
38
+ // Ler só a segunda fazia TODO comentário virar "@desconhecido" no relato
39
+ // que vai para o modelo — e o relato É o insumo do bug gerado.
40
+ const autor = c.author || c.user?.login || 'desconhecido';
40
41
  parts.push(`### Comentário de @${autor}\n\n${c.body}`);
41
42
  }
42
43
  return parts.join('\n\n');
@@ -54,33 +55,36 @@ export async function generateBug({ issueNumber }) {
54
55
  // do runner mandando exportá-la — dentro de um repo que já sabe seu owner/repo.
55
56
  const { owner, repo, root, config, mode } = resolveFlowContext({ command: 'generate-bug', requireRoot: true });
56
57
  const n = parseInt(issueNumber, 10);
58
+ const tracker = createGithubTracker({ token, owner, repo });
59
+ const ref = { key: String(n) };
57
60
 
58
61
  console.log(`Buscando issue #${n}...`);
59
- const issue = await getIssue(token, owner, repo, n);
62
+ const issue = await tracker.getWorkItem({ ref: ref });
60
63
 
61
64
  // Guarda invertida em relação ao generate-spec: aqui só Bug passa.
62
65
  const type = detectIssueType(issue);
63
66
  if (type !== 'Bug') {
64
67
  console.log(`Issue #${n} é ${type}: bug.md é gerado só para Bug.`);
65
- await removeLabel(token, owner, repo, n, LABEL_BUG);
66
- await commentOnIssue(
67
- token, owner, repo, n,
68
- `ℹ️ **bug.md não gerado:** o tipo **${type}** não usa esse artefato. ` +
69
- 'Nenhum arquivo foi criado.'
70
- ).catch(() => {});
68
+ await tracker.removeTag({ ref: ref, tag: LABEL_BUG });
69
+ await tracker.addComment({
70
+ ref: ref,
71
+ body:
72
+ `ℹ️ **bug.md não gerado:** o tipo **${type}** não usa esse artefato. ` +
73
+ 'Nenhum arquivo foi criado.',
74
+ }).catch(() => {});
71
75
  return;
72
76
  }
73
77
 
74
78
  const issueLabels = labelNames(issue);
75
79
  if (issueLabels.includes(LABEL_NEEDS_HUMAN)) {
76
80
  console.log(`Issue #${n} está com ${LABEL_NEEDS_HUMAN}: geração bloqueada.`);
77
- await removeLabel(token, owner, repo, n, LABEL_BUG);
81
+ await tracker.removeTag({ ref: ref, tag: LABEL_BUG });
78
82
  return;
79
83
  }
80
84
 
81
85
  const { fileRel } = bugDocPaths(issue.title, root);
82
86
 
83
- const comments = await listIssueComments(token, owner, repo, n).catch(() => []);
87
+ const comments = await tracker.listComments({ ref: ref }).catch(() => []);
84
88
  const report = buildReport(issue, comments);
85
89
 
86
90
  const payload = {
@@ -122,46 +126,48 @@ export async function generateBug({ issueNumber }) {
122
126
  doc: 'bug',
123
127
  issueNumber: n,
124
128
  issueTitle: issue.title,
125
- issueUrl: issue.html_url,
129
+ issueUrl: issue.ref.url,
126
130
  pathRel: fileRel,
127
131
  content,
128
132
  nextLabel: 'spec-wave:ready',
129
133
  });
130
134
  if (published.warning) console.warn(`⚠️ ${published.warning}`);
131
135
 
132
- await removeLabel(token, owner, repo, n, LABEL_BUG);
136
+ await tracker.removeTag({ ref: ref, tag: LABEL_BUG });
133
137
 
134
138
  // Crítica adversarial: NÃO fatal. Um bug.md gerado e criticado como grave
135
139
  // ainda é melhor que nenhum — o portão é a label, verificada na triagem.
136
140
  const critique = await critiqueBugDoc({
137
- token, owner, repo, issueNumber: n, issue,
141
+ tracker, issueNumber: n, issue,
138
142
  bugDoc: content, report, labels: issueLabels, cwd: root, usage: usageEntries,
139
143
  });
140
144
 
141
- await commentOnIssue(
142
- token, owner, repo, n,
143
- '🐞 **bug.md gerado automaticamente!**\n\n' +
144
- `📄 Arquivo: [\`${fileRel}\`](${published.blobUrl})\n\n` +
145
- `${renderPrLine(published)}\n\n` +
146
- 'Revise a **causa raiz** e o **teste de regressão** no Pull Request — são as duas seções ' +
147
- 'que decidem se a correção ataca o defeito ou o sintoma. Depois do merge, valide com:\n' +
148
- `\`\`\`\ngh issue edit ${n} --add-label "spec-wave:ready"\n\`\`\`` +
149
- (critique?.blocked ? '\n\n⛔ A crítica adversarial encontrou problemas graves (acima).' : '')
150
- );
145
+ await tracker.addComment({
146
+ ref: ref,
147
+ body:
148
+ '🐞 **bug.md gerado automaticamente!**\n\n' +
149
+ `📄 Arquivo: [\`${fileRel}\`](${published.blobUrl})\n\n` +
150
+ `${renderPrLine(published)}\n\n` +
151
+ 'Revise a **causa raiz** e o **teste de regressão** no Pull Request — são as duas seções ' +
152
+ 'que decidem se a correção ataca o defeito ou o sintoma. Depois do merge, valide com:\n' +
153
+ `\`\`\`\ngh issue edit ${n} --add-label "spec-wave:ready"\n\`\`\`` +
154
+ (critique?.blocked ? '\n\n⛔ A crítica adversarial encontrou problemas graves (acima).' : ''),
155
+ });
151
156
 
152
157
  console.log(`bug.md publicado em ${published.branch} (${fileRel}).`);
153
158
  return { pr: published.pr, branch: published.branch };
154
159
  } catch (err) {
155
160
  // Mesmo motivo do generate-spec: sem remover a label, re-aplicá-la não
156
161
  // emite evento e a issue vira beco sem saída.
157
- await removeLabel(token, owner, repo, n, LABEL_BUG).catch(() => {});
158
- await commentOnIssue(
159
- token, owner, repo, n,
160
- '❌ **Falha ao gerar o bug.md**\n\n' +
161
- `\`\`\`\n${err.message}\n\`\`\`\n\n` +
162
- `A label \`${LABEL_BUG}\` foi removida para destravar o gatilho — ` +
163
- 'adicione-a de novo para tentar outra vez.'
164
- ).catch(() => {});
162
+ await tracker.removeTag({ ref: ref, tag: LABEL_BUG }).catch(() => {});
163
+ await tracker.addComment({
164
+ ref: ref,
165
+ body:
166
+ '❌ **Falha ao gerar o bug.md**\n\n' +
167
+ `\`\`\`\n${err.message}\n\`\`\`\n\n` +
168
+ `A label \`${LABEL_BUG}\` foi removida para destravar o gatilho — ` +
169
+ 'adicione-a de novo para tentar outra vez.',
170
+ }).catch(() => {});
165
171
  throw err;
166
172
  } finally {
167
173
  await recordUsage({ token, owner, repo, issueNumber: n, entries: usageEntries });
@@ -171,29 +177,30 @@ export async function generateBug({ issueNumber }) {
171
177
  // Roda a crítica e reflete o veredito em labels/comentário. Best-effort: uma
172
178
  // falha da crítica não invalida o documento já commitado.
173
179
  async function critiqueBugDoc({
174
- token, owner, repo, issueNumber, issue, bugDoc, report, labels, cwd, usage,
180
+ tracker, issueNumber, issue, bugDoc, report, labels, cwd, usage,
175
181
  }) {
182
+ const ref = { key: String(issueNumber) };
176
183
  try {
177
- const comments = await listIssueComments(token, owner, repo, issueNumber).catch(() => []);
184
+ const comments = await tracker.listComments({ ref }).catch(() => []);
178
185
  const { attempt, blocked } = resolveCritiqueAttempt({
179
186
  comments, labels, kind: 'bug', maxAttempts: DEFAULT_MAX_CRITIQUE_ATTEMPTS,
180
187
  });
181
188
 
182
189
  if (blocked) {
183
- await addLabel(token, owner, repo, issueNumber, LABEL_NEEDS_HUMAN);
184
- await commentOnIssue(
185
- token, owner, repo, issueNumber,
186
- renderNeedsHumanComment({ kind: 'bug', maxAttempts: DEFAULT_MAX_CRITIQUE_ATTEMPTS })
187
- );
190
+ await tracker.addTag({ ref, tag: LABEL_NEEDS_HUMAN });
191
+ await tracker.addComment({
192
+ ref,
193
+ body: renderNeedsHumanComment({ kind: 'bug', maxAttempts: DEFAULT_MAX_CRITIQUE_ATTEMPTS }),
194
+ });
188
195
  return { blocked: true };
189
196
  }
190
197
 
191
198
  const result = await runCritique({
192
199
  kind: 'bug', bugDoc, bugReport: report, attempt, labels, usage, cwd,
193
200
  });
194
- await commentOnIssue(token, owner, repo, issueNumber, result.markdown);
201
+ await tracker.addComment({ ref, body: result.markdown });
195
202
  if (result.grave) {
196
- await addLabel(token, owner, repo, issueNumber, LABEL_CRITIQUE_FAILED);
203
+ await tracker.addTag({ ref, tag: LABEL_CRITIQUE_FAILED });
197
204
  return { blocked: true };
198
205
  }
199
206
  return { blocked: false };
@@ -1,9 +1,8 @@
1
1
  import path from 'node:path';
2
2
  import { readFileSync, existsSync } from 'node:fs';
3
3
  import { resolveToken } from '../api/auth.mjs';
4
- import {
5
- getIssue, removeLabel, addLabel, commentOnIssue, listIssueComments, getRepoDefaultBranch,
6
- } from '../api/github-rest.mjs';
4
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
5
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
7
6
  import { detectIssueType } from '../lib/issue-type.mjs';
8
7
  import {
9
8
  allowsSpecPlan, SPEC_PLAN_EXCLUDED_TYPES, TARGET_LANGUAGE,
@@ -56,8 +55,9 @@ function formatLintWarning(lintFindings) {
56
55
  * Nunca lança: o plan já foi commitado e o humano precisa dele para corrigir.
57
56
  */
58
57
  async function critiquePlan({
59
- token, owner, repo, issueNumber, spec, plan, techContextYaml, labels, config, usage,
58
+ tracker, issueNumber, spec, plan, techContextYaml, labels, config, usage,
60
59
  }) {
60
+ const ref = { key: String(issueNumber) };
61
61
  if (labels.includes(LABEL_NEEDS_HUMAN)) {
62
62
  console.log(`Crítica pulada: a issue tem a label ${LABEL_NEEDS_HUMAN} (revisão humana pendente).`);
63
63
  return;
@@ -68,7 +68,7 @@ async function critiquePlan({
68
68
  : DEFAULT_MAX_CRITIQUE_ATTEMPTS;
69
69
  const escalationModel = config?.ai?.escalationModel || null;
70
70
 
71
- const comments = await listIssueComments(token, owner, repo, issueNumber).catch(err => {
71
+ const comments = await tracker.listComments({ ref }).catch(err => {
72
72
  console.warn(`Não foi possível listar comentários: ${err.message} — contador de tentativas em 1.`);
73
73
  return [];
74
74
  });
@@ -79,9 +79,11 @@ async function critiquePlan({
79
79
 
80
80
  if (blocked) {
81
81
  console.log(`Teto de ${maxAttempts} tentativas de crítica atingido — exigindo revisão humana.`);
82
- await commentOnIssue(token, owner, repo, issueNumber,
83
- renderNeedsHumanComment({ kind: 'plan', attempt, maxAttempts, escalationModel })).catch(() => {});
84
- await addLabel(token, owner, repo, issueNumber, LABEL_NEEDS_HUMAN).catch(() => {});
82
+ await tracker.addComment({
83
+ ref,
84
+ body: renderNeedsHumanComment({ kind: 'plan', attempt, maxAttempts, escalationModel }),
85
+ }).catch(() => {});
86
+ await tracker.addTag({ ref, tag: LABEL_NEEDS_HUMAN }).catch(() => {});
85
87
  return;
86
88
  }
87
89
 
@@ -96,17 +98,19 @@ async function critiquePlan({
96
98
  });
97
99
  } catch (err) {
98
100
  console.warn(`Crítica adversarial não concluiu: ${err.message}`);
99
- await commentOnIssue(token, owner, repo, issueNumber,
100
- `⚠️ **A crítica adversarial não concluiu** (erro abaixo) — o \`plan.md\` foi gerado, ` +
101
- 'mas **não foi auditado**. Revise-o com atenção extra.\n\n' +
102
- `\`\`\`\n${err.message}\n\`\`\``
103
- ).catch(() => {});
101
+ await tracker.addComment({
102
+ ref,
103
+ body:
104
+ `⚠️ **A crítica adversarial não concluiu** (erro abaixo) — o \`plan.md\` foi gerado, ` +
105
+ 'mas **não foi auditado**. Revise-o com atenção extra.\n\n' +
106
+ `\`\`\`\n${err.message}\n\`\`\``,
107
+ }).catch(() => {});
104
108
  return;
105
109
  }
106
110
 
107
111
  // O comentário fica FORA do try da label: falhar ao comentar não pode impedir
108
112
  // o bloqueio de uma crítica grave.
109
- await commentOnIssue(token, owner, repo, issueNumber, critique.markdown)
113
+ await tracker.addComment({ ref, body: critique.markdown })
110
114
  .catch(err => console.warn(`Falha ao comentar a crítica: ${err.message}`));
111
115
 
112
116
  // O portão olha os graves SEM decisão do TL. Um grave que ele marcou como
@@ -114,19 +118,21 @@ async function critiquePlan({
114
118
  // humana explícita, registrada e auditável na issue.
115
119
  const { blocking, accepted } = applyCritiqueDecisions(critique.findings, decisions, 'plan');
116
120
  if (accepted.length > 0) {
117
- await addLabel(token, owner, repo, issueNumber, LABEL_RISK_ACCEPTED).catch(() => {});
118
- await commentOnIssue(token, owner, repo, issueNumber,
119
- renderRiskAcceptedComment({ kind: 'plan', accepted })).catch(() => {});
121
+ await tracker.addTag({ ref, tag: LABEL_RISK_ACCEPTED }).catch(() => {});
122
+ await tracker.addComment({
123
+ ref,
124
+ body: renderRiskAcceptedComment({ kind: 'plan', accepted }),
125
+ }).catch(() => {});
120
126
  console.log(`${accepted.length} finding(s) aceito(s) como risco pelo Tech Leader.`);
121
127
  }
122
128
  if (blocking.length > 0) {
123
- await addLabel(token, owner, repo, issueNumber, LABEL_CRITIQUE_FAILED);
129
+ await tracker.addTag({ ref, tag: LABEL_CRITIQUE_FAILED });
124
130
  console.log(`Crítica adversarial apontou ${blocking.length} finding(s) GRAVE(s) sem decisão — label ${LABEL_CRITIQUE_FAILED} aplicada.`);
125
131
  return;
126
132
  }
127
133
  // Crítica limpa remove o bloqueio anterior — é isso que zera o contador de
128
134
  // tentativas na rodada seguinte (ver resolveCritiqueAttempt).
129
- await removeLabel(token, owner, repo, issueNumber, LABEL_CRITIQUE_FAILED).catch(() => {});
135
+ await tracker.removeTag({ ref, tag: LABEL_CRITIQUE_FAILED }).catch(() => {});
130
136
  }
131
137
 
132
138
  export async function generatePlan({ issueNumber }) {
@@ -136,7 +142,10 @@ export async function generatePlan({ issueNumber }) {
136
142
  console.log(`Modo de execução: ${mode}`);
137
143
 
138
144
  console.log(`Buscando issue #${issueNumber}...`);
139
- const issue = await getIssue(token, owner, repo, parseInt(issueNumber, 10));
145
+ const tracker = createGithubTracker({ token, owner, repo });
146
+ const scm = createGithubScm({ link: githubLink({ owner, repo }), token });
147
+ const ref = { key: String(parseInt(issueNumber, 10)) };
148
+ const issue = await tracker.getWorkItem({ ref });
140
149
 
141
150
  // plan.md é artefato de Feature — não se aplica a Spike/RFC/Bug.
142
151
  const type = detectIssueType(issue);
@@ -144,12 +153,13 @@ export async function generatePlan({ issueNumber }) {
144
153
  const issueLabels = labelNames(issue);
145
154
  if (!allowsSpecPlan(type)) {
146
155
  console.log(`Issue #${issueNumber} é ${type}: plan.md não é gerado para ${SPEC_PLAN_EXCLUDED_TYPES.join('/')}.`);
147
- await removeLabel(token, owner, repo, parseInt(issueNumber, 10), 'spec-wave:plan');
148
- await commentOnIssue(
149
- token, owner, repo, parseInt(issueNumber, 10),
150
- `ℹ️ **plan.md não gerado:** o tipo **${type}** não usa spec/plan no fluxo spec-wave ` +
151
- `(esses artefatos são exclusivos de Features). Nenhum arquivo foi criado.`
152
- ).catch(() => {});
156
+ await tracker.removeTag({ ref, tag: 'spec-wave:plan' });
157
+ await tracker.addComment({
158
+ ref,
159
+ body:
160
+ `ℹ️ **plan.md não gerado:** o tipo **${type}** não usa spec/plan no fluxo spec-wave ` +
161
+ `(esses artefatos são exclusivos de Features). Nenhum arquivo foi criado.`,
162
+ }).catch(() => {});
153
163
  return;
154
164
  }
155
165
 
@@ -162,7 +172,7 @@ export async function generatePlan({ issueNumber }) {
162
172
  // A spec é a ENTRADA do plano, e agora ela pode estar em três lugares: no
163
173
  // clone, na branch base, ou num Pull Request que ninguém mergeou ainda.
164
174
  const specRel = `${featureRel}/spec.md`;
165
- const base = await getRepoDefaultBranch(token, owner, repo).catch(() => null);
175
+ const base = await scm.defaultBranch().catch(() => null);
166
176
  const spec = await loadArtifact({
167
177
  token, owner, repo, root, pathRel: specRel, doc: 'spec',
168
178
  issueNumber: parseInt(issueNumber, 10), base,
@@ -181,12 +191,14 @@ export async function generatePlan({ issueNumber }) {
181
191
  message: `\`${specRel}\` não existe — o plano depende da spec.`,
182
192
  unblock: `Aplique \`${LABEL_SPEC}\` para gerar a spec primeiro.`,
183
193
  };
184
- await removeLabel(token, owner, repo, n, 'spec-wave:plan').catch(() => {});
185
- await commentOnIssue(token, owner, repo, n,
186
- `⏸️ **plan.md não gerado:** ${motivo.message}\n\n${motivo.unblock}\n\n` +
187
- 'Gerar o plano sem a spec produziria um documento plausível e errado, ' +
188
- 'com a chamada de IA já paga.'
189
- ).catch(() => {});
194
+ await tracker.removeTag({ ref, tag: 'spec-wave:plan' }).catch(() => {});
195
+ await tracker.addComment({
196
+ ref,
197
+ body:
198
+ `⏸️ **plan.md não gerado:** ${motivo.message}\n\n${motivo.unblock}\n\n` +
199
+ 'Gerar o plano sem a spec produziria um documento plausível e errado, ' +
200
+ 'com a chamada de IA já paga.',
201
+ }).catch(() => {});
190
202
  throw new Error(motivo.message);
191
203
  }
192
204
  const specContent = spec.content;
@@ -233,7 +245,7 @@ export async function generatePlan({ issueNumber }) {
233
245
  doc: 'plan',
234
246
  issueNumber: parseInt(issueNumber, 10),
235
247
  issueTitle: issue.title,
236
- issueUrl: issue.html_url,
248
+ issueUrl: issue.ref.url,
237
249
  pathRel: fileRel,
238
250
  content,
239
251
  base,
@@ -242,24 +254,25 @@ export async function generatePlan({ issueNumber }) {
242
254
  if (published.warning) console.warn(`⚠️ ${published.warning}`);
243
255
 
244
256
  // Remove trigger label
245
- await removeLabel(token, owner, repo, parseInt(issueNumber, 10), 'spec-wave:plan');
257
+ await tracker.removeTag({ ref, tag: 'spec-wave:plan' });
246
258
 
247
259
  // Comment on issue
248
- await commentOnIssue(
249
- token, owner, repo, parseInt(issueNumber, 10),
250
- `📋 **plan.md gerado automaticamente!**\n\n` +
251
- `📄 Arquivo: [\`${fileRel}\`](${published.blobUrl})\n\n` +
252
- `${renderPrLine(published)}\n\n` +
253
- `Revise o plano **no Pull Request** e faça o merge. Depois, valide a Feature: mova o card para **✅ Ready** ou use:\n` +
254
- `\`\`\`\ngh issue edit ${issueNumber} --add-label "spec-wave:ready"\n\`\`\`` +
255
- formatLintWarning(lintFindings)
256
- );
260
+ await tracker.addComment({
261
+ ref,
262
+ body:
263
+ `📋 **plan.md gerado automaticamente!**\n\n` +
264
+ `📄 Arquivo: [\`${fileRel}\`](${published.blobUrl})\n\n` +
265
+ `${renderPrLine(published)}\n\n` +
266
+ `Revise o plano **no Pull Request** e faça o merge. Depois, valide a Feature: mova o card para **✅ Ready** ou use:\n` +
267
+ `\`\`\`\ngh issue edit ${issueNumber} --add-label "spec-wave:ready"\n\`\`\`` +
268
+ formatLintWarning(lintFindings),
269
+ });
257
270
 
258
271
  // Crítica adversarial: audita o plan recém-comitado contra spec +
259
272
  // tech_context. NUNCA desfaz o plan — falha da crítica vira só um aviso, e o
260
273
  // humano segue com a ferramenta que precisa para corrigir.
261
274
  await critiquePlan({
262
- token, owner, repo, issueNumber: parseInt(issueNumber, 10),
275
+ tracker, issueNumber: parseInt(issueNumber, 10),
263
276
  spec: specContent, plan: content, techContextYaml: tech.yaml,
264
277
  labels: issueLabels, config, usage: usageEntries,
265
278
  });
@@ -271,14 +284,15 @@ export async function generatePlan({ issueNumber }) {
271
284
  // então com a label ainda aplicada re-adicioná-la não dispara nada. Remove
272
285
  // o gatilho e reporta na issue; o erro segue propagando.
273
286
  // (O catch acima, na crítica adversarial, cobre só aquele trecho.)
274
- await removeLabel(token, owner, repo, parseInt(issueNumber, 10), 'spec-wave:plan').catch(() => {});
275
- await commentOnIssue(
276
- token, owner, repo, parseInt(issueNumber, 10),
277
- `❌ **Falha ao gerar o plan.md**\n\n` +
278
- `\`\`\`\n${err.message}\n\`\`\`\n\n` +
279
- `A label \`spec-wave:plan\` foi removida para destravar o gatilho — ` +
280
- `adicione-a de novo para tentar outra vez.`
281
- ).catch(() => {});
287
+ await tracker.removeTag({ ref, tag: 'spec-wave:plan' }).catch(() => {});
288
+ await tracker.addComment({
289
+ ref,
290
+ body:
291
+ `❌ **Falha ao gerar o plan.md**\n\n` +
292
+ `\`\`\`\n${err.message}\n\`\`\`\n\n` +
293
+ `A label \`spec-wave:plan\` foi removida para destravar o gatilho — ` +
294
+ `adicione-a de novo para tentar outra vez.`,
295
+ }).catch(() => {});
282
296
  throw err;
283
297
  } finally {
284
298
  // Best-effort: nunca propaga erro (ver recordUsage).
@@ -389,18 +403,21 @@ export async function critique({ issueNumber, file, kind, failOnGrave = false })
389
403
  console.log(`Modo de execução: ${mode}`);
390
404
 
391
405
  const n = parseInt(issueNumber, 10);
392
- const issue = await getIssue(token, owner, repo, n);
406
+ const tracker = createGithubTracker({ token, owner, repo });
407
+ const scm = createGithubScm({ link: githubLink({ owner, repo }), token });
408
+ const ref = { key: String(n) };
409
+ const issue = await tracker.getWorkItem({ ref });
393
410
  const type = detectIssueType(issue);
394
411
  if (!allowsSpecPlan(type)) {
395
412
  console.log(`Issue #${n} é ${type}: não usa plan.md, nada a criticar.`);
396
- await removeLabel(token, owner, repo, n, LABEL_CRITIQUE).catch(() => {});
413
+ await tracker.removeTag({ ref, tag: LABEL_CRITIQUE }).catch(() => {});
397
414
  return;
398
415
  }
399
416
 
400
417
  const featureRel = `docs/features/${slugify(issue.title)}`;
401
418
  const planRel = `${featureRel}/plan.md`;
402
419
  const specRel = `${featureRel}/spec.md`;
403
- const base = await getRepoDefaultBranch(token, owner, repo).catch(() => null);
420
+ const base = await scm.defaultBranch().catch(() => null);
404
421
  const ler = (doc, pathRel) => loadArtifact({
405
422
  token, owner, repo, root, pathRel, doc, issueNumber: n, base,
406
423
  });
@@ -412,10 +429,13 @@ export async function critique({ issueNumber, file, kind, failOnGrave = false })
412
429
  const plan = await ler('plan', planRel);
413
430
  if (plan.content == null) {
414
431
  console.log('plan.md ainda não existe — gere o plano antes de criticá-lo.');
415
- await removeLabel(token, owner, repo, n, LABEL_CRITIQUE).catch(() => {});
416
- await commentOnIssue(token, owner, repo, n,
417
- 'ℹ️ **Nada a criticar:** o `plan.md` ainda não foi gerado. ' +
418
- 'Aplique `spec-wave:plan` para gerá-lo.').catch(() => {});
432
+ await tracker.removeTag({ ref, tag: LABEL_CRITIQUE }).catch(() => {});
433
+ await tracker.addComment({
434
+ ref,
435
+ body:
436
+ 'ℹ️ **Nada a criticar:** o `plan.md` ainda não foi gerado. ' +
437
+ 'Aplique `spec-wave:plan` para gerá-lo.',
438
+ }).catch(() => {});
419
439
  return;
420
440
  }
421
441
  if (plan.state === 'pending-pr') {
@@ -423,9 +443,9 @@ export async function critique({ issueNumber, file, kind, failOnGrave = false })
423
443
  }
424
444
  const spec = await ler('spec', specRel);
425
445
 
426
- const issueLabels = labelNames(issue.labels || []);
446
+ const issueLabels = labelNames(issue);
427
447
  await critiquePlan({
428
- token, owner, repo, issueNumber: n,
448
+ tracker, issueNumber: n,
429
449
  spec: spec.content,
430
450
  plan: plan.content,
431
451
  techContextYaml: buildTechContext({ issueBody: issue.body || '' }).yaml,
@@ -434,5 +454,5 @@ export async function critique({ issueNumber, file, kind, failOnGrave = false })
434
454
 
435
455
  // O gatilho sai SEMPRE: `issues: [labeled]` não redispara com a label ainda
436
456
  // aplicada, então mantê-la deixaria a issue sem como pedir outra crítica.
437
- await removeLabel(token, owner, repo, n, LABEL_CRITIQUE).catch(() => {});
457
+ await tracker.removeTag({ ref, tag: LABEL_CRITIQUE }).catch(() => {});
438
458
  }