@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
@@ -4,7 +4,7 @@ import { readFileSync, writeFileSync } from 'node:fs';
4
4
  import { resolveToken } from '../api/auth.mjs';
5
5
  import { CONFIG_FILE, STATUS_OPTIONS } from '../config.mjs';
6
6
  import { findConfigPath } from '../lib/project-root.mjs';
7
- import { getProjectSnapshot, updateStatusField } from '../api/github-graphql.mjs';
7
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
8
8
  // Trata o escape de empacotamento (SPEC_WAVE_CLI_VERSION) — ver lib/templates.mjs.
9
9
  import { CLI_VERSION } from '../lib/templates.mjs';
10
10
 
@@ -60,7 +60,7 @@ export function planStageSync(current, canonical) {
60
60
  *
61
61
  * @returns {Promise<boolean>} true se o comando deve continuar
62
62
  */
63
- async function syncStages(token, snapshot, options) {
63
+ async function syncStages(tracker, snapshot, options) {
64
64
  const etapa = snapshot.fields?.['Etapa'];
65
65
  if (!etapa?.id) {
66
66
  p.log.error('Campo "Etapa" não encontrado no Project — nada a sincronizar.');
@@ -106,24 +106,18 @@ async function syncStages(token, snapshot, options) {
106
106
 
107
107
  const spinner = p.spinner();
108
108
  spinner.start('Atualizando o campo "Etapa"...');
109
+ let after;
109
110
  try {
110
- await updateStatusField(token, etapa.id, ordered);
111
+ // A porta escreve E relê: a verificação pós-escrita é do contrato, não uma
112
+ // cortesia do chamador — uma opção recriada com id novo esvazia a Etapa de
113
+ // todo item que apontava para a antiga, em silêncio.
114
+ after = await tracker.syncStages({ stages: ordered });
111
115
  } catch (err) {
112
116
  spinner.stop('');
113
117
  p.log.error(`Falha ao atualizar o campo "Etapa": ${err.message}`);
114
118
  process.exitCode = 1;
115
119
  return false;
116
120
  }
117
-
118
- // Verificação pós-escrita: releitura, não confiança na mutação.
119
- let after;
120
- try {
121
- after = await getProjectSnapshot(token, snapshot.id);
122
- } catch (err) {
123
- spinner.stop('');
124
- p.log.warn(`Campo atualizado, mas a verificação falhou: ${err.message}`);
125
- return true;
126
- }
127
121
  const depois = after?.fields?.['Etapa']?.options || {};
128
122
  const now = Object.keys(depois);
129
123
  const lost = nomesAntes.filter(name => !now.includes(name));
@@ -210,11 +204,25 @@ export async function refresh(options = {}) {
210
204
 
211
205
  p.intro(chalk.bold(`spec-wave refresh${options.stages ? ' --stages' : ' --config'}`));
212
206
 
207
+ const tracker = createGithubTracker({
208
+ token, owner: config.owner, repo: config.repo, project: config.project,
209
+ });
210
+ const leSchema = async () => {
211
+ // `provision: false` é leitura: devolve o bloco de config que descreve o
212
+ // board agora. É o que o --config grava de volta.
213
+ const { config: vivo, warnings } = await tracker.setup({ provision: false });
214
+ if (warnings.length > 0 && !vivo) throw new Error(warnings[0]);
215
+ return vivo && {
216
+ id: vivo.projectId, number: vivo.projectNumber,
217
+ url: vivo.projectUrl, title: vivo.projectTitle, fields: vivo.fields,
218
+ };
219
+ };
220
+
213
221
  const spinner = p.spinner();
214
222
  spinner.start('Consultando o GitHub Project...');
215
223
  let snapshot;
216
224
  try {
217
- snapshot = await getProjectSnapshot(token, projectId);
225
+ snapshot = await leSchema();
218
226
  } catch (err) {
219
227
  spinner.stop('');
220
228
  p.log.error(`Erro ao consultar o Project: ${err.message}`);
@@ -230,11 +238,11 @@ export async function refresh(options = {}) {
230
238
  spinner.stop('Project consultado.');
231
239
 
232
240
  if (options.stages) {
233
- const ok = await syncStages(token, snapshot, options);
241
+ const ok = await syncStages(tracker, snapshot, options);
234
242
  if (!ok) return;
235
243
  // Depois de mexer no board, o .spec-wave.json guarda ids de opção velhos —
236
244
  // relê o Project para que o resto do comando grave o estado novo.
237
- snapshot = await getProjectSnapshot(token, projectId);
245
+ snapshot = await leSchema();
238
246
  if (!options.config) {
239
247
  p.outro('Campo "Etapa" sincronizado. Rode `spec-wave refresh --config` para atualizar o .spec-wave.json.');
240
248
  return;
@@ -19,10 +19,9 @@
19
19
  import * as p from '@clack/prompts';
20
20
  import chalk from 'chalk';
21
21
  import { resolveToken } from '../api/auth.mjs';
22
- import { getIssue, commentOnIssue } from '../api/github-rest.mjs';
23
22
  import { verifyTokenScopes } from '../api/auth.mjs';
24
23
  import { detectIssueType } from '../lib/issue-type.mjs';
25
- import { loadProjectConfig, resolveField, setItemStage, resolveStageName } from '../lib/board.mjs';
24
+ import { openTracker, forceStage, resolveStageName } from '../lib/board.mjs';
26
25
  import { resolveHubContext } from '../lib/project-root.mjs';
27
26
  import { resolveProgressName } from './move.mjs';
28
27
  import { CONFIG_FILE } from '../config.mjs';
@@ -153,25 +152,31 @@ export async function repairStage(issuesArg, stageArg, options = {}) {
153
152
  `spec-wave repair-stage ${numbers.map(n => `#${n}`).join(', ')} → ${stage}${options.dryRun ? ' (dry-run)' : ''}`
154
153
  ));
155
154
 
156
- const { project, error: projectError } = loadProjectConfig({ cwd: root || process.cwd() });
155
+ const { tracker, error: projectError } = openTracker({ token, owner, repo, cwd: root || process.cwd(), tracker: options.deps?.tracker });
157
156
  if (projectError) {
158
157
  p.log.error(`${projectError} — nada a reparar. Rode \`spec-wave init\` (ou \`spec-wave refresh --config\`).`);
159
158
  process.exitCode = 1;
160
159
  return;
161
160
  }
162
- const etapaField = await resolveField(token, project, 'Etapa').catch(() => null);
163
- const statusField = status ? await resolveField(token, project, 'Status').catch(() => null) : null;
164
- // Reparar a Etapa e deixar o item sem tipo seria consertar metade: os mesmos
165
- // itens que perderam a Etapa nasceram do apply, que também não escrevia o
166
- // Work Item Type. Só preenche o vazio (ver ensureWorkItemType).
167
- const typeField = await resolveField(token, project, 'Work Item Type').catch(() => null);
161
+ // O reparo ignora o guard de avanço, e isso exige que o tracker saiba VOLTAR.
162
+ // No GitHub a Etapa é um campo que se escreve; num tracker por transição
163
+ // (Jira) pode simplesmente não existir caminho de volta — daí a capability
164
+ // ser consultada aqui e não descoberta no meio do laço.
165
+ if (tracker.capabilities?.stages?.reopenable === false) {
166
+ p.log.error(
167
+ `O tracker "${tracker.kind}" não permite retroceder a Etapa, e é exatamente isso ` +
168
+ 'que `repair-stage` faz. Ajuste o item direto na ferramenta.'
169
+ );
170
+ process.exitCode = 1;
171
+ return;
172
+ }
168
173
 
169
174
  // Lê tudo ANTES de escrever qualquer coisa: reparo parcial por issue
170
175
  // inexistente no meio da lista é o tipo de surpresa que ninguém quer aqui.
171
176
  const alvos = [];
172
177
  for (const n of numbers) {
173
178
  try {
174
- const issue = await getIssue(token, owner, repo, n);
179
+ const issue = await tracker.getWorkItem({ ref: { key: String(n) } });
175
180
  alvos.push({ number: n, issue, type: detectIssueType(issue) });
176
181
  } catch (err) {
177
182
  p.log.error(`Não foi possível ler a issue #${n}: ${err.message}`);
@@ -216,14 +221,22 @@ export async function repairStage(issuesArg, stageArg, options = {}) {
216
221
  let reparados = 0;
217
222
  for (const alvo of alvos) {
218
223
  try {
219
- const { from } = await setItemStage(
220
- token, project, etapaField, statusField, alvo.issue.node_id, stage, status,
221
- { typeField, itemType: alvo.type });
224
+ // Reparar a Etapa e deixar o item sem tipo seria consertar metade: os
225
+ // mesmos itens que perderam a Etapa nasceram do apply, que também não
226
+ // escrevia o Work Item Type. Só preenche o vazio (ensureWorkItemType).
227
+ const { from } = await forceStage({
228
+ tracker,
229
+ ref: alvo.issue.ref,
230
+ stage,
231
+ progress: status,
232
+ itemType: alvo.type,
233
+ });
222
234
  reparados += 1;
223
235
  p.log.success(`#${alvo.number}: ${from || '(sem etapa)'} → ${chalk.bold(stage)}${status ? ` / ${status}` : ''}`);
224
- await commentOnIssue(token, owner, repo, alvo.number, renderRepairComment({
225
- from, to: stage, status, reason: options.reason, actor, version,
226
- })).catch(err => p.log.warn(`#${alvo.number}: reparo aplicado, mas o registro falhou: ${err.message}`));
236
+ await tracker.addComment({
237
+ ref: alvo.issue.ref,
238
+ body: renderRepairComment({ from, to: stage, status, reason: options.reason, actor, version }),
239
+ }).catch(err => p.log.warn(`#${alvo.number}: reparo aplicado, mas o registro falhou: ${err.message}`));
227
240
  } catch (err) {
228
241
  p.log.error(`#${alvo.number}: falha ao reparar — ${err.message}`);
229
242
  process.exitCode = 1;
@@ -7,7 +7,8 @@
7
7
  import * as p from '@clack/prompts';
8
8
  import chalk from 'chalk';
9
9
  import { resolveToken } from '../api/auth.mjs';
10
- import { getRepoNodeId, createLabel } from '../api/github-rest.mjs';
10
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
11
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
11
12
  import { resolveHubContext } from '../lib/project-root.mjs';
12
13
  import { updateConfig } from '../lib/config-file.mjs';
13
14
  import {
@@ -73,7 +74,12 @@ export async function repoCommand({ action, slug, repo: repoArg, dryRun = false,
73
74
  // o nada só apareceria na primeira Story, dentro do apply.
74
75
  const token = await resolveToken();
75
76
  try {
76
- await getRepoNodeId(token, target.owner, target.repo);
77
+ // Sonda de ALCANCE, não leitura: o que importa é se o token enxerga o
78
+ // repositório-alvo antes de o hub passar a apontar para ele.
79
+ const alvo = await createGithubScm({
80
+ link: githubLink({ owner: target.owner, repo: target.repo, role: 'code' }), token,
81
+ }).verify();
82
+ if (!alvo.ok) throw new Error(alvo.problems.join('; '));
77
83
  } catch (err) {
78
84
  throw new Error(`Não consegui ler ${target.owner}/${target.repo}: ${err.status === 404 ? 'não existe ou o token não o enxerga' : err.message}.`);
79
85
  }
@@ -88,7 +94,8 @@ export async function repoCommand({ action, slug, repo: repoArg, dryRun = false,
88
94
 
89
95
  const spec = repoLabelSpec(slug);
90
96
  try {
91
- await createLabel(token, ctx.owner, ctx.repo, spec);
97
+ await createGithubTracker({ token, owner: ctx.owner, repo: ctx.repo })
98
+ .ensureTags({ tags: [spec] });
92
99
  p.log.success(`Label ${spec.name} garantida em ${ctx.owner}/${ctx.repo}.`);
93
100
  } catch (err) {
94
101
  p.log.warn(`Não consegui criar a label ${spec.name}: ${err.message} — o decompose --apply tenta de novo.`);
@@ -20,8 +20,9 @@ import path from 'node:path';
20
20
  import chalk from 'chalk';
21
21
 
22
22
  import { resolveToken } from '../api/auth.mjs';
23
- import { getIssue, getPR, listPullRequestReviews } from '../api/github-rest.mjs';
24
- import { loadProjectConfig } from '../lib/board.mjs';
23
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
24
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
25
+ import { trackerAvailable } from '../lib/board.mjs';
25
26
  import { loadArtifact } from '../lib/doc-source.mjs';
26
27
  import { featureDocPaths, bugDocPaths } from '../lib/doc-paths.mjs';
27
28
  import { isActionsRun, resolveFlowContext } from '../lib/flow-run.mjs';
@@ -30,6 +31,7 @@ import { nextStep, resolveForcedStep, stepDocs, docsForType, STEPS } from '../li
30
31
  import { nextPrStep, reviewVerdict } from '../lib/pr-step.mjs';
31
32
  import { configuredMode } from '../lib/execution-mode.mjs';
32
33
  import { labelNames } from '../config.mjs';
34
+ import { refKey } from '../lib/work-item-ref.mjs';
33
35
 
34
36
  const LOCK_STALE_MS = 30 * 60 * 1000;
35
37
 
@@ -339,19 +341,22 @@ async function runForPr({ prNumber, dryRun, yes, only, json }) {
339
341
  const token = await resolveToken();
340
342
  const n = parseInt(prNumber, 10);
341
343
 
342
- const pr = await getPR(token, owner, repo, n);
343
- const reviews = await listPullRequestReviews(token, owner, repo, n);
344
+ const scm = createGithubScm({ link: githubLink({ owner, repo }), token });
345
+ const pr = await scm.getPullRequest({ number: String(n) });
346
+ const reviews = await scm.listPullRequestReviews({ number: String(n) });
344
347
  const verdict = reviewVerdict(reviews);
345
348
  const decision = nextPrStep({
346
- state: pr.state,
349
+ // A porta já normaliza: `state` vira 'merged' quando mergeado, então o
350
+ // `merged_at` cru deixa de ser consultado aqui.
351
+ state: pr.state === 'merged' ? 'closed' : pr.state,
347
352
  draft: Boolean(pr.draft),
348
- merged: Boolean(pr.merged_at),
353
+ merged: pr.state === 'merged',
349
354
  approved: verdict.approved,
350
355
  changesRequestedAfterApproval: verdict.changesRequestedAfterApproval,
351
356
  only: only || null,
352
357
  });
353
358
 
354
- const { error: boardError } = loadProjectConfig({ cwd: root || process.cwd() });
359
+ const { error: boardError } = trackerAvailable({ cwd: root || process.cwd() });
355
360
  if (boardError) decision.warnings.push(`${boardError} — o board não será atualizado.`);
356
361
 
357
362
  if (json) {
@@ -369,7 +374,7 @@ async function runForPr({ prNumber, dryRun, yes, only, json }) {
369
374
  return decision;
370
375
  }
371
376
  // Mergeado, o pedido de mudanças pré-merge já foi decidido por quem mergeou.
372
- if (verdict.changesRequestedAfterApproval && !pr.merged_at && !yes) {
377
+ if (verdict.changesRequestedAfterApproval && pr.state !== 'merged' && !yes) {
373
378
  console.log(chalk.yellow('\n⛔ needs-confirmation: há pedido de mudanças além da aprovação. Confirme com `--yes`.'));
374
379
  process.exitCode = 2;
375
380
  return decision;
@@ -415,7 +420,13 @@ export async function run(issueArg, options = {}) {
415
420
 
416
421
  const { owner, repo, root, config } = resolveFlowContext({ command: 'run' });
417
422
  const token = await resolveToken();
418
- const issueNumber = String(issueArg).replace(/^#/, '');
423
+ // `refKey` e não um `replace` local: este valor é a RAIZ de dois nomes de
424
+ // arquivo — o lock e o manifesto de workspace — e tudo a jusante deriva dele.
425
+ // Com `'007'` cru, o lock virava `run-007.lock` (um `run 7` concorrente não
426
+ // via conflito) e `claude.mjs` procurava `workspace-007.json` enquanto o
427
+ // `workspace prepare` gravava `workspace-7.json`, derrubando a seção
428
+ // multi-repo do prompt sem um único aviso.
429
+ const issueNumber = refKey(issueArg);
419
430
  const teto = Math.max(1, parseInt(maxSteps, 10) || 1);
420
431
 
421
432
  if (configuredMode(config) !== 'local') {
@@ -436,10 +447,11 @@ export async function run(issueArg, options = {}) {
436
447
  let ultimoTipo = null;
437
448
 
438
449
  for (let i = 0; i < teto; i++) {
439
- const issue = await getIssue(token, owner, repo, parseInt(issueNumber, 10));
450
+ const issue = await createGithubTracker({ token, owner, repo })
451
+ .getWorkItem({ ref: { key: String(parseInt(issueNumber, 10)) } });
440
452
  const type = detectIssueType(issue);
441
453
  const { docs, docPaths } = localDocStates(issue, type, root);
442
- const { error: boardError } = loadProjectConfig({ cwd: root || process.cwd() });
454
+ const { error: boardError } = trackerAvailable({ cwd: root || process.cwd() });
443
455
 
444
456
  let forcedStep = null;
445
457
  if (forced && i === 0) {
@@ -8,14 +8,13 @@
8
8
  import * as p from '@clack/prompts';
9
9
  import chalk from 'chalk';
10
10
  import { resolveToken } from '../api/auth.mjs';
11
- import { getIssue } from '../api/github-rest.mjs';
12
- import { addProjectItem, getItemSingleSelectValue } from '../api/github-graphql.mjs';
11
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
13
12
  import { detectIssueType } from '../lib/issue-type.mjs';
14
- import { loadProjectConfig, resolveField, advanceToStage } from '../lib/board.mjs';
13
+ import { openTracker, advanceToStage } from '../lib/board.mjs';
15
14
  import { resolveHubContext } from '../lib/project-root.mjs';
16
15
  import { CONFIG_FILE, STAGE_CODE_REVIEW, PROGRESS_TODO } from '../config.mjs';
17
16
 
18
- export async function story({ action, issue: issueArg }) {
17
+ export async function story({ action, issue: issueArg, deps = {} }) {
19
18
  if (action !== 'review') {
20
19
  p.log.error(
21
20
  `Ação desconhecida: "${action}".\n` +
@@ -56,7 +55,8 @@ export async function story({ action, issue: issueArg }) {
56
55
  // 1. Lê a issue e valida o tipo.
57
56
  let issue;
58
57
  try {
59
- issue = await getIssue(token, owner, repo, issueNumber);
58
+ issue = await (deps.tracker ?? createGithubTracker({ token, owner, repo }))
59
+ .getWorkItem({ ref: { key: String(issueNumber) } });
60
60
  } catch (err) {
61
61
  p.log.error(`Não foi possível ler a issue #${issueNumber}: ${err.message}`);
62
62
  process.exitCode = 1;
@@ -72,25 +72,26 @@ export async function story({ action, issue: issueArg }) {
72
72
  return;
73
73
  }
74
74
 
75
- // 2. Project do .spec-wave.json — sem ele não há board para atualizar.
76
- const { project, error: projectError } = loadProjectConfig();
75
+ // 2. Tracker do .spec-wave.json — sem ele não há board para atualizar.
76
+ const { tracker, error: projectError } = openTracker({ token, owner, repo, tracker: deps.tracker });
77
77
  if (projectError) {
78
78
  p.log.error(`${projectError} — board não atualizado. Rode \`spec-wave init\` (ou \`spec-wave refresh --config\`).`);
79
79
  process.exitCode = 1;
80
80
  return;
81
81
  }
82
- const etapaField = await resolveField(token, project, 'Etapa').catch(() => null);
83
- const statusField = await resolveField(token, project, 'Status').catch(() => null);
84
- // Repara o Work Item Type vazio de passagem (o apply nunca o escreveu).
85
- // Só preenche o vazio e nunca derruba o movimento — ver ensureWorkItemType.
86
- const typeField = await resolveField(token, project, 'Work Item Type').catch(() => null);
87
82
 
88
- // 3. Avança para Code Review (Status reinicia em Todo ao trocar de etapa).
83
+ // 3. Avança para Code Review (o progresso reinicia em Todo ao trocar de
84
+ // etapa). `itemType` repara o Work Item Type vazio de passagem — só preenche
85
+ // o vazio e nunca derruba o movimento (ver ensureWorkItemType).
89
86
  let moved;
90
87
  try {
91
- moved = await advanceToStage(
92
- token, project, etapaField, statusField, issue.node_id, STAGE_CODE_REVIEW, PROGRESS_TODO,
93
- { typeField, itemType: type });
88
+ moved = await advanceToStage({
89
+ tracker,
90
+ ref: issue.ref,
91
+ stage: STAGE_CODE_REVIEW,
92
+ progress: PROGRESS_TODO,
93
+ itemType: type,
94
+ });
94
95
  } catch (err) {
95
96
  p.log.error(`Falha ao atualizar o board: ${err.message}`);
96
97
  process.exitCode = 1;
@@ -105,15 +106,9 @@ export async function story({ action, issue: issueArg }) {
105
106
 
106
107
  // false = a Story já está em Code Review ou em etapa posterior — e a Etapa
107
108
  // NUNCA retrocede. Lê a Etapa atual só para informar o usuário.
108
- let current = null;
109
- if (etapaField?.id) {
110
- try {
111
- const itemId = await addProjectItem(token, project.id, issue.node_id);
112
- current = await getItemSingleSelectValue(token, itemId, etapaField.id);
113
- } catch {
114
- // sem leitura da Etapa — segue com o aviso genérico
115
- }
116
- }
109
+ const current = await tracker
110
+ .getStage({ ref: issue.ref })
111
+ .catch(() => null); // sem leitura da Etapa — segue com o aviso genérico
117
112
  p.log.info(
118
113
  `Story #${issueNumber} não foi movida: a Etapa nunca retrocede, e ela já está em ` +
119
114
  `${chalk.bold(current || `"${STAGE_CODE_REVIEW}" ou etapa posterior`)}.`
@@ -11,10 +11,10 @@
11
11
  import * as p from '@clack/prompts';
12
12
  import chalk from 'chalk';
13
13
  import { resolveToken } from '../api/auth.mjs';
14
- import { getIssue } from '../api/github-rest.mjs';
15
- import { addProjectItem, getIssueParent, listSubIssues, getItemSingleSelectValue } from '../api/github-graphql.mjs';
14
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
15
+
16
16
  import { detectIssueType } from '../lib/issue-type.mjs';
17
- import { loadProjectConfig, resolveField, advanceToStage, setItemStatus } from '../lib/board.mjs';
17
+ import { openTracker, advanceToStage, setProgress } from '../lib/board.mjs';
18
18
  import { resolveHubContext } from '../lib/project-root.mjs';
19
19
  import {
20
20
  CONFIG_FILE, STAGE_DEVELOPMENT, STAGE_DONE,
@@ -36,7 +36,7 @@ export function canStartTask({ siblings } = {}) {
36
36
  }
37
37
 
38
38
 
39
- export async function task({ action, issue: issueArg }) {
39
+ export async function task({ action, issue: issueArg, deps = {} }) {
40
40
  if (action !== 'start' && action !== 'done') {
41
41
  p.log.error(
42
42
  `Ação desconhecida: "${action}".\n` +
@@ -77,7 +77,8 @@ export async function task({ action, issue: issueArg }) {
77
77
  // 1. Lê a issue e valida o tipo.
78
78
  let issue;
79
79
  try {
80
- issue = await getIssue(token, owner, repo, issueNumber);
80
+ issue = await (deps.tracker ?? createGithubTracker({ token, owner, repo }))
81
+ .getWorkItem({ ref: { key: String(issueNumber) } });
81
82
  } catch (err) {
82
83
  p.log.error(`Não foi possível ler a issue #${issueNumber}: ${err.message}`);
83
84
  process.exitCode = 1;
@@ -93,40 +94,33 @@ export async function task({ action, issue: issueArg }) {
93
94
  return;
94
95
  }
95
96
 
96
- // 2. Project do .spec-wave.json — sem ele não há board para atualizar.
97
- const { project, error: projectError } = loadProjectConfig();
97
+ // 2. Tracker do .spec-wave.json — sem ele não há board para atualizar.
98
+ const { tracker, error: projectError } = openTracker({ token, owner, repo, tracker: deps.tracker });
98
99
  if (projectError) {
99
100
  p.log.error(`${projectError} — board não atualizado. Rode \`spec-wave init\` (ou \`spec-wave refresh --config\`).`);
100
101
  process.exitCode = 1;
101
102
  return;
102
103
  }
103
- const etapaField = await resolveField(token, project, 'Etapa').catch(() => null);
104
- const statusField = await resolveField(token, project, 'Status').catch(() => null);
105
- // Repara o Work Item Type vazio de passagem (o apply nunca o escreveu).
106
- // Só preenche o vazio e nunca derruba o movimento — ver ensureWorkItemType.
107
- const typeField = await resolveField(token, project, 'Work Item Type').catch(() => null);
104
+ const ref = issue.ref;
108
105
 
109
106
  // 3. start: garante que nenhuma task irmã (mesma Story) está In Progress.
110
107
  if (action === 'start') {
111
- const parent = await getIssueParent(token, issue.node_id).catch(() => null);
108
+ const parent = await tracker.getParent({ ref: issue.ref }).catch(() => null);
112
109
  const parentIsStory = parent && detectIssueType({ title: parent.title }) === 'Story';
113
- if (!statusField?.id) {
114
- p.log.warn('Campo "Status" não encontrado no Project — verificação de task em andamento pulada.');
115
- } else if (!parentIsStory) {
110
+ if (!parentIsStory) {
116
111
  p.log.warn(`Task #${issueNumber} sem Story-pai — verificação de tasks irmãs pulada.`);
117
112
  } else {
118
- const subs = await listSubIssues(token, parent.nodeId).catch(() => []);
119
- const siblingTasks = subs.filter(s =>
120
- s.number !== issueNumber && detectIssueType({ title: s.title, labels: s.labels }) === 'Task'
113
+ const irmas = await tracker.listChildren({ ref: parent.ref }).catch(() => []);
114
+ const siblingTasks = irmas.filter(s =>
115
+ s.ref.key !== String(issueNumber) && detectIssueType(s) === 'Task'
121
116
  );
122
117
  // Status de cada irmã; falha de leitura → status desconhecido (não bloqueia).
123
118
  const siblings = await Promise.all(siblingTasks.map(async (s) => {
124
119
  try {
125
- const itemId = await addProjectItem(token, project.id, s.nodeId);
126
- const status = await getItemSingleSelectValue(token, itemId, statusField.id);
127
- return { number: s.number, title: s.title, status };
120
+ const status = await tracker.getProgress({ ref: s.ref });
121
+ return { number: Number(s.ref.key), title: s.title, status };
128
122
  } catch {
129
- return { number: s.number, title: s.title, status: null };
123
+ return { number: Number(s.ref.key), title: s.title, status: null };
130
124
  }
131
125
  }));
132
126
  const { ok, blocker } = canStartTask({ siblings });
@@ -149,9 +143,9 @@ export async function task({ action, issue: issueArg }) {
149
143
 
150
144
  let moved;
151
145
  try {
152
- moved = await advanceToStage(
153
- token, project, etapaField, statusField, issue.node_id, target.stage, target.status,
154
- { typeField, itemType: type });
146
+ moved = await advanceToStage({
147
+ tracker, ref, stage: target.stage, progress: target.status, itemType: type,
148
+ });
155
149
  } catch (err) {
156
150
  p.log.error(`Falha ao atualizar o board: ${err.message}`);
157
151
  process.exitCode = 1;
@@ -163,7 +157,7 @@ export async function task({ action, issue: issueArg }) {
163
157
  } else {
164
158
  // Etapa já está no destino ou adiante (nunca retrocede) — só garante o Status.
165
159
  try {
166
- await setItemStatus(token, project, statusField, issue.node_id, target.status);
160
+ await setProgress({ tracker, ref, progress: target.status });
167
161
  p.log.info(`Etapa já à frente — apenas Status ajustado para ${chalk.bold(target.status)}.`);
168
162
  } catch (err) {
169
163
  p.log.warn(`Etapa já à frente, mas falhou ao ajustar o Status: ${err.message}`);
@@ -11,11 +11,9 @@
11
11
  import * as p from '@clack/prompts';
12
12
  import chalk from 'chalk';
13
13
  import { resolveToken } from '../api/auth.mjs';
14
- import {
15
- getIssue, addLabel, removeLabel, commentOnIssue, setIssueState,
16
- } from '../api/github-rest.mjs';
14
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
17
15
  import { detectIssueType } from '../lib/issue-type.mjs';
18
- import { loadProjectConfig, resolveField, advanceToStage } from '../lib/board.mjs';
16
+ import { openTracker, advanceToStage } from '../lib/board.mjs';
19
17
  import { resolveHubContext } from '../lib/project-root.mjs';
20
18
  import { resolveTriageAction, canAcceptBug } from '../lib/bug-triage.mjs';
21
19
  import {
@@ -25,7 +23,7 @@ import {
25
23
 
26
24
  const PRIORITIES = PRIORITY_LABELS.map(l => l.name);
27
25
 
28
- export async function triage({ action: actionArg, issue: issueArg, reason, of, severity }) {
26
+ export async function triage({ action: actionArg, issue: issueArg, reason, of, severity, deps = {} }) {
29
27
  const { action, error: actionError } = resolveTriageAction(actionArg);
30
28
  if (actionError) {
31
29
  p.log.error(actionError);
@@ -66,9 +64,12 @@ export async function triage({ action: actionArg, issue: issueArg, reason, of, s
66
64
 
67
65
  p.intro(chalk.bold(`spec-wave triage ${action} #${issueNumber}`));
68
66
 
67
+ const tracker = deps.tracker ?? createGithubTracker({ token, owner, repo });
68
+ const ref = { key: String(issueNumber) };
69
+
69
70
  let issue;
70
71
  try {
71
- issue = await getIssue(token, owner, repo, issueNumber);
72
+ issue = await tracker.getWorkItem({ ref });
72
73
  } catch (err) {
73
74
  p.log.error(`Não foi possível ler a issue #${issueNumber}: ${err.message}`);
74
75
  process.exitCode = 1;
@@ -96,16 +97,15 @@ export async function triage({ action: actionArg, issue: issueArg, reason, of, s
96
97
  // mesma issue tornam a ordem da fila indefinida.
97
98
  if (severity) {
98
99
  for (const outra of PRIORITIES) {
99
- if (outra !== severity) await removeLabel(token, owner, repo, issueNumber, outra).catch(() => {});
100
+ if (outra !== severity) await tracker.removeTag({ ref, tag: outra }).catch(() => {});
100
101
  }
101
- await addLabel(token, owner, repo, issueNumber, severity);
102
+ await tracker.addTag({ ref, tag: severity });
102
103
  p.log.info(`Severidade → ${severity}.`);
103
104
  }
104
105
 
105
- await addLabel(token, owner, repo, issueNumber, LABEL_TRIAGED);
106
- await commentOnIssue(token, owner, repo, issueNumber,
107
- '**Triado:** aceito para a fila técnica.').catch(() => {});
108
- await moveToReady({ token, issueNumber, issue, root });
106
+ await tracker.addTag({ ref, tag: LABEL_TRIAGED });
107
+ await tracker.addComment({ ref, body: '**Triado:** aceito para a fila técnica.' }).catch(() => {});
108
+ await moveToReady({ token, issueNumber, issue, root, deps });
109
109
 
110
110
  p.outro(`${chalk.green('✓')} Bug #${issueNumber} aceito → ${STAGE_READY}.`);
111
111
  return;
@@ -117,11 +117,10 @@ export async function triage({ action: actionArg, issue: issueArg, reason, of, s
117
117
  process.exitCode = 1;
118
118
  return;
119
119
  }
120
- await addLabel(token, owner, repo, issueNumber, LABEL_WONT_FIX);
121
- await addLabel(token, owner, repo, issueNumber, LABEL_TRIAGED);
122
- await commentOnIssue(token, owner, repo, issueNumber,
123
- `**Rejeitado na triagem:** ${reason.trim()}`).catch(() => {});
124
- await setIssueState(token, owner, repo, issueNumber, 'closed');
120
+ await tracker.addTag({ ref, tag: LABEL_WONT_FIX });
121
+ await tracker.addTag({ ref, tag: LABEL_TRIAGED });
122
+ await tracker.addComment({ ref, body: `**Rejeitado na triagem:** ${reason.trim()}` }).catch(() => {});
123
+ await tracker.closeWorkItem({ ref, reason: 'not-planned' });
125
124
  p.outro(`${chalk.green('✓')} Bug #${issueNumber} rejeitado e fechado.`);
126
125
  return;
127
126
  }
@@ -139,32 +138,35 @@ export async function triage({ action: actionArg, issue: issueArg, reason, of, s
139
138
  return;
140
139
  }
141
140
 
142
- await addLabel(token, owner, repo, issueNumber, LABEL_DUPLICATE);
143
- await addLabel(token, owner, repo, issueNumber, LABEL_TRIAGED);
144
- await commentOnIssue(token, owner, repo, issueNumber, `**Duplicata de #${original}.**`).catch(() => {});
141
+ await tracker.addTag({ ref, tag: LABEL_DUPLICATE });
142
+ await tracker.addTag({ ref, tag: LABEL_TRIAGED });
143
+ await tracker.addComment({ ref, body: `**Duplicata de #${original}.**` }).catch(() => {});
145
144
  // Comentar também na original: sem isso, quem acompanha #original não fica
146
145
  // sabendo que há outro relato do mesmo defeito — e o contexto extra está lá.
147
- await commentOnIssue(token, owner, repo, original,
148
- `#${issueNumber} foi marcada como duplicata desta issue.`).catch(() => {});
149
- await setIssueState(token, owner, repo, issueNumber, 'closed');
146
+ await tracker.addComment({
147
+ ref: { key: String(original) },
148
+ body: `#${issueNumber} foi marcada como duplicata desta issue.`,
149
+ }).catch(() => {});
150
+ await tracker.closeWorkItem({ ref, reason: 'duplicate' });
150
151
 
151
152
  p.outro(`${chalk.green('✓')} Bug #${issueNumber} marcado como duplicata de #${original} e fechado.`);
152
153
  }
153
154
 
154
- async function moveToReady({ token, issueNumber, issue, root }) {
155
- const { project, error } = loadProjectConfig({ cwd: root || process.cwd() });
155
+ async function moveToReady({ token, issueNumber, issue, root, deps = {} }) {
156
+ const { tracker, error } = openTracker({ token, cwd: root || process.cwd(), tracker: deps.tracker });
156
157
  if (error) {
157
158
  p.log.warn(`${error} — board não atualizado.`);
158
159
  return;
159
160
  }
160
161
  try {
161
- const etapaField = await resolveField(token, project, 'Etapa').catch(() => null);
162
- const statusField = await resolveField(token, project, 'Status').catch(() => null);
163
162
  // Triagem só trata Bug — o tipo aqui é certeza, não inferência de título.
164
- const typeField = await resolveField(token, project, 'Work Item Type').catch(() => null);
165
- const moved = await advanceToStage(
166
- token, project, etapaField, statusField, issue.node_id, STAGE_READY, PROGRESS_TODO,
167
- { typeField, itemType: 'Bug' });
163
+ const moved = await advanceToStage({
164
+ tracker,
165
+ ref: issue.ref,
166
+ stage: STAGE_READY,
167
+ progress: PROGRESS_TODO,
168
+ itemType: 'Bug',
169
+ });
168
170
  if (!moved) {
169
171
  p.log.info(`#${issueNumber} já está em ${STAGE_READY} ou etapa posterior — mantido.`);
170
172
  }
@@ -4,7 +4,8 @@ import { readFileSync, existsSync, unlinkSync } from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { resolveToken } from '../api/auth.mjs';
6
6
  import { CONFIG_FILE, ALL_LABELS, WORKFLOW_FILES, ISSUE_TEMPLATE_FILES } from '../config.mjs';
7
- import { deleteLabel, deleteFile } from '../api/github-rest.mjs';
7
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
8
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
8
9
 
9
10
  const REPO_FILES = [
10
11
  ...WORKFLOW_FILES.map(f => `.github/workflows/${f}`),
@@ -80,6 +81,9 @@ export async function uninstall(options = {}) {
80
81
  return;
81
82
  }
82
83
 
84
+ const tracker = createGithubTracker({ token, owner, repo });
85
+ const scm = createGithubScm({ link: githubLink({ owner, repo }), token });
86
+
83
87
  // --- Labels ---
84
88
  if (doLabels) {
85
89
  const spinner = p.spinner();
@@ -88,7 +92,7 @@ export async function uninstall(options = {}) {
88
92
  try {
89
93
  for (let i = 0; i < ALL_LABELS.length; i++) {
90
94
  spinner.message(`Removendo label ${i + 1}/${ALL_LABELS.length}: ${ALL_LABELS[i].name}`);
91
- if (await deleteLabel(token, owner, repo, ALL_LABELS[i].name)) removed++;
95
+ if (await tracker.deleteTag({ name: ALL_LABELS[i].name })) removed++;
92
96
  }
93
97
  spinner.stop(`Labels removidas (${removed}/${ALL_LABELS.length}).`);
94
98
  } catch (err) {
@@ -106,7 +110,7 @@ export async function uninstall(options = {}) {
106
110
  for (let i = 0; i < REPO_FILES.length; i++) {
107
111
  const filePath = REPO_FILES[i];
108
112
  spinner.message(`Removendo ${i + 1}/${REPO_FILES.length}: ${filePath}`);
109
- if (await deleteFile(token, owner, repo, filePath, `chore: remove ${filePath} [spec-wave]`)) removed++;
113
+ if (await scm.deleteFile({ path: filePath, message: `chore: remove ${filePath} [spec-wave]` })) removed++;
110
114
  }
111
115
  spinner.stop(`Arquivos removidos (${removed}/${REPO_FILES.length}).`);
112
116
  } catch (err) {