@spec-wave/cli 1.0.7 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/package.json +1 -1
  2. package/src/commands/audit.mjs +24 -18
  3. package/src/commands/code-review.mjs +91 -59
  4. package/src/commands/decompose.mjs +258 -221
  5. package/src/commands/doctor.mjs +16 -11
  6. package/src/commands/generate-bug.mjs +51 -44
  7. package/src/commands/generate-plan.mjs +83 -63
  8. package/src/commands/generate-qa-plan.mjs +145 -117
  9. package/src/commands/generate-spec.mjs +33 -28
  10. package/src/commands/implement.mjs +155 -79
  11. package/src/commands/info.mjs +4 -3
  12. package/src/commands/init.mjs +11 -5
  13. package/src/commands/install-skill.mjs +19 -0
  14. package/src/commands/issue.mjs +26 -39
  15. package/src/commands/merge.mjs +71 -20
  16. package/src/commands/mode.mjs +11 -6
  17. package/src/commands/move.mjs +16 -20
  18. package/src/commands/order.mjs +33 -22
  19. package/src/commands/preflight.mjs +24 -13
  20. package/src/commands/qa-lead.mjs +30 -17
  21. package/src/commands/qa-run.mjs +125 -103
  22. package/src/commands/qa.mjs +55 -44
  23. package/src/commands/refresh.mjs +24 -16
  24. package/src/commands/repair-stage.mjs +29 -16
  25. package/src/commands/repo.mjs +12 -4
  26. package/src/commands/run.mjs +23 -11
  27. package/src/commands/story.mjs +20 -25
  28. package/src/commands/task.mjs +21 -27
  29. package/src/commands/triage.mjs +33 -31
  30. package/src/commands/uninstall.mjs +7 -3
  31. package/src/commands/update.mjs +31 -22
  32. package/src/commands/validate.mjs +60 -52
  33. package/src/commands/workspace.mjs +7 -5
  34. package/src/config.mjs +7 -1
  35. package/src/lib/artifact-publish.mjs +20 -18
  36. package/src/lib/board-policy.mjs +144 -0
  37. package/src/lib/board.mjs +134 -233
  38. package/src/lib/cli-ref.mjs +75 -0
  39. package/src/lib/config-file.mjs +2 -1
  40. package/src/lib/doc-availability.mjs +10 -3
  41. package/src/lib/doc-source.mjs +9 -9
  42. package/src/lib/execution-mode.mjs +5 -3
  43. package/src/lib/implement-board.mjs +23 -26
  44. package/src/lib/issue-type.mjs +5 -1
  45. package/src/lib/plugin-skills.mjs +10 -0
  46. package/src/lib/pr-ready.mjs +48 -10
  47. package/src/lib/pr-step.mjs +3 -1
  48. package/src/lib/qa-exec.mjs +3 -1
  49. package/src/lib/qa-lead.mjs +11 -3
  50. package/src/lib/qa-plan-doc.mjs +10 -4
  51. package/src/lib/qa-report.mjs +2 -1
  52. package/src/lib/skill-compose.mjs +3 -0
  53. package/src/lib/spec-audit.mjs +1 -1
  54. package/src/lib/story-graph.mjs +62 -8
  55. package/src/lib/usage-report.mjs +8 -5
  56. package/src/lib/work-item-ref.mjs +176 -0
  57. package/src/plugin/.claude-plugin/plugin.json +1 -1
  58. package/src/plugins/scm-github/index.mjs +439 -0
  59. package/src/plugins/tracker-github-projects/fields.mjs +73 -0
  60. package/src/plugins/tracker-github-projects/index.mjs +625 -0
  61. package/src/ports/scm.mjs +197 -0
  62. package/src/ports/tracker.mjs +239 -0
  63. package/src/ports/types.mjs +254 -0
  64. package/src/setup/files.mjs +14 -12
  65. package/src/setup/labels.mjs +17 -12
  66. package/src/setup/project.mjs +40 -59
  67. package/src/templates/workflows/code/code-review.yml +1 -1
  68. package/src/templates/workflows/code/qa.yml +1 -1
@@ -9,8 +9,27 @@ import {
9
9
  PROGRESS_TODO, PROGRESS_IN_PROGRESS, PROGRESS_DONE, labelNames,
10
10
  TRAILER_STORY, TRAILER_TASKS, TRAILER_AGENT,
11
11
  } from '../config.mjs';
12
- import { getIssue, listIssueComments, listBlockedBy, getFileContent } from '../api/github-rest.mjs';
13
- import { listSubIssues, getIssueParent } from '../api/github-graphql.mjs';
12
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
13
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
14
+
15
+ // Fábrica local: este arquivo é longo e os helpers recebem (token, owner, repo)
16
+ // separadamente. As operações abaixo são todas de LEITURA e não usam o memo do
17
+ // board, então construir por chamada não muda contagem nenhuma.
18
+ const trackerDe = (token, owner, repo) => createGithubTracker({ token, owner, repo });
19
+
20
+ /** WorkItem → a forma que este arquivo consome em dezenas de pontos. */
21
+ const comoSubIssue = w => ({
22
+ number: Number(w.ref.key),
23
+ nodeId: w.ref.id,
24
+ node_id: w.ref.id,
25
+ title: w.title,
26
+ body: w.body || '',
27
+ labels: w.tags || [],
28
+ state: w.state || null,
29
+ milestone: w.milestone ? { number: Number(w.milestone.key), title: w.milestone.title } : null,
30
+ createdAt: w.createdAt || null,
31
+ ref: w.ref,
32
+ });
14
33
  import { detectIssueType } from '../lib/issue-type.mjs';
15
34
  import { bugDocPaths } from '../lib/bug-doc.mjs';
16
35
  import { missingDocMessage, existsOnRemote } from '../lib/doc-availability.mjs';
@@ -35,6 +54,7 @@ import {
35
54
  slugsForItem, resolveWorkspaceLayout, readWorkspaceOverride, renderRepoDirs, codeReposForItems,
36
55
  } from '../lib/workspace.mjs';
37
56
  import { repoSlugsFromLabels } from '../lib/repo-role.mjs';
57
+ import { cliRef } from '../lib/cli-ref.mjs';
38
58
 
39
59
  const WORK_DIR = '.spec-wave';
40
60
 
@@ -46,15 +66,16 @@ const MAX_COMMENT_CHARS = 2000;
46
66
  // "Feature" e devolve { number, title } — usado para resolver docs/features/<slug>
47
67
  // e para as instruções de fim de Story (mover a Feature para Code Review). Limita
48
68
  // a profundidade para evitar loops em dados inconsistentes.
49
- async function resolveFeature(token, startNodeId) {
50
- let current = startNodeId;
69
+ async function resolveFeature(token, owner, repo, startRef) {
70
+ const tracker = trackerDe(token, owner, repo);
71
+ let current = startRef;
51
72
  for (let depth = 0; depth < 5 && current; depth++) {
52
- const parent = await getIssueParent(token, current);
73
+ const parent = await tracker.getParent({ ref: current });
53
74
  if (!parent) return null;
54
75
  if (detectIssueType({ title: parent.title }) === 'Feature') {
55
- return { number: parent.number, title: parent.title, nodeId: parent.nodeId };
76
+ return { number: Number(parent.ref.key), title: parent.title, nodeId: parent.ref.id };
56
77
  }
57
- current = parent.nodeId;
78
+ current = parent.ref;
58
79
  }
59
80
  return null;
60
81
  }
@@ -81,7 +102,10 @@ async function probeMissingDoc({ token, owner, repo, root, pathRel, doc, issueNu
81
102
  if (achado?.state === 'remote') return missingDocMessage({ pathRel, onRemote: true, fallback });
82
103
  if (achado?.state === 'missing') return missingDocMessage({ pathRel, onRemote: false, fallback });
83
104
  }
84
- const onRemote = await existsOnRemote({ getFileContent, token, owner, repo, pathRel });
105
+ const scm = token && owner && repo
106
+ ? createGithubScm({ link: githubLink({ owner, repo }), token })
107
+ : null;
108
+ const onRemote = await existsOnRemote({ scm, pathRel });
85
109
  return missingDocMessage({ pathRel, onRemote, fallback });
86
110
  }
87
111
 
@@ -189,12 +213,44 @@ export function closesRef(hub, number) {
189
213
  return hub?.owner && hub?.repo ? `${hub.owner}/${hub.repo}#${number}` : `#${number}`;
190
214
  }
191
215
 
216
+ /**
217
+ * O número do work item, venha ele na forma antiga ou na do contrato.
218
+ *
219
+ * `WorkItem.ref.key` é a forma canônica; `number` é a issue crua, que ainda
220
+ * circula. Aceitar as duas aqui é o que impede um `#undefined` de vazar para o
221
+ * contexto que vai para o executor — ver test/context-no-undefined.test.mjs.
222
+ */
223
+ export function itemNumber(item) {
224
+ const bruto = item?.ref?.key ?? item?.number;
225
+ return bruto == null || bruto === '' ? null : Number(bruto);
226
+ }
227
+
228
+ /**
229
+ * Os números de uma lista devolvida pela porta (função PURA).
230
+ *
231
+ * Existe porque os três usos de `listBlockedBy` neste arquivo faziam a MESMA
232
+ * leitura à mão e os três liam `b.number` — campo que o retorno não tem, já que
233
+ * a chave mora em `ref`. O efeito não era erro: os Sets enchiam de `undefined`,
234
+ * o `getWorkItem` seguinte falhava e o catch seguia em frente, de modo que toda
235
+ * dependência nativa sumia da verificação em silêncio.
236
+ *
237
+ * Um leitor só, testável contra a saída real da porta — é o que faz a próxima
238
+ * mudança de forma aparecer num teste em vez de num run.
239
+ *
240
+ * @param {Array<object>} itens
241
+ * @returns {number[]} sem nulos e sem repetição, em ordem crescente
242
+ */
243
+ export function itemNumbers(itens = []) {
244
+ const ns = (itens || []).map(itemNumber).filter(n => Number.isInteger(n));
245
+ return [...new Set(ns)].sort((a, b) => a - b);
246
+ }
247
+
192
248
  export function buildContext({
193
249
  type, issue, tasks, feature, siblingStories = [], spec, plan, specPath, planPath,
194
250
  comments = [], codeDigest = null, blockedByWarnings = [], mode = 'pr-stack', hub = null,
195
251
  }) {
196
252
  const lines = [];
197
- lines.push(`# Contexto de implementação — ${type} #${issue.number}`);
253
+ lines.push(`# Contexto de implementação — ${type} #${itemNumber(issue)}`);
198
254
  lines.push('');
199
255
  lines.push(`**${type}:** ${issue.title}`);
200
256
  if (issue.body && issue.body.trim()) {
@@ -222,12 +278,12 @@ export function buildContext({
222
278
  lines.push('');
223
279
  if (type === 'Story') {
224
280
  lines.push(
225
- `Nesta fase, a Story #${issue.number} e suas Tasks estão na Etapa **${STAGE_DEVELOPMENT}**. ` +
281
+ `Nesta fase, a Story #${itemNumber(issue)} e suas Tasks estão na Etapa **${STAGE_DEVELOPMENT}**. ` +
226
282
  `Durante o desenvolvimento de cada Task, mexa no **Status**; ao **concluir** a Task, ela ` +
227
283
  `**avança para a Etapa ${STAGE_DONE}** (com Status ${PROGRESS_DONE}).`
228
284
  );
229
285
  lines.push('');
230
- lines.push(`1. Garanta que a Story #${issue.number} está na Etapa **${STAGE_DEVELOPMENT}** com Status **${PROGRESS_IN_PROGRESS}**, e que as Tasks estão nessa Etapa com Status **${PROGRESS_TODO}**.`);
286
+ lines.push(`1. Garanta que a Story #${itemNumber(issue)} está na Etapa **${STAGE_DEVELOPMENT}** com Status **${PROGRESS_IN_PROGRESS}**, e que as Tasks estão nessa Etapa com Status **${PROGRESS_TODO}**.`);
231
287
  lines.push(`2. Implemente as ${tasks.length} task(s) **uma de cada vez, na ordem abaixo**. É PROIBIDO ter mais de uma Task com Status **${PROGRESS_IN_PROGRESS}** ao mesmo tempo. Para **cada Task**, na ordem:`);
232
288
  lines.push(` 1. **Ao começar:** Status da Task → **${PROGRESS_IN_PROGRESS}** (a Etapa continua ${STAGE_DEVELOPMENT}).`);
233
289
  lines.push(' 2. **Implemente** a Task por completo.');
@@ -242,7 +298,7 @@ export function buildContext({
242
298
  );
243
299
  lines.push(' ```');
244
300
  lines.push(renderTrailers({
245
- story: issue.number, tasks: tasks.map(t => t.number),
301
+ story: itemNumber(issue), tasks: tasks.map(t => t.number),
246
302
  agent: mode === 'agent' ? 'spec-wave-agent' : undefined,
247
303
  }).split('\n').map(l => ` ${l}`).join('\n'));
248
304
  lines.push(' ```');
@@ -263,27 +319,27 @@ export function buildContext({
263
319
  // required check continua valendo. Quem tira do rascunho é o próprio
264
320
  // implement, quando a ÚLTIMA Story da Feature entra em Code Review (ver
265
321
  // lib/pr-ready.mjs): até lá o rascunho diz "feature em andamento".
266
- lines.push(` 2. Abra o **Pull Request** da Story #${issue.number} **como rascunho** (\`gh pr create --draft\`), **com \`Closes ${closesRef(hub, issue.number)}\` no corpo** — é esse vínculo que localiza o PR da Story. Deixe em rascunho: o \`spec-wave implement\` marca TODOS os PRs da Feature como prontos de uma vez quando a última Story concluir, e é aí que os checks disparam. **Não marque como pronto manualmente.**`);
322
+ lines.push(` 2. Abra o **Pull Request** da Story #${itemNumber(issue)} **como rascunho** (\`gh pr create --draft\`), **com \`Closes ${closesRef(hub, itemNumber(issue))}\` no corpo** — é esse vínculo que localiza o PR da Story. Deixe em rascunho: o \`spec-wave implement\` marca TODOS os PRs da Feature como prontos de uma vez quando a última Story concluir, e é aí que os checks disparam. **Não marque como pronto manualmente.**`);
267
323
  }
268
324
  lines.push(
269
- ` 3. **Avance a Etapa da Story #${issue.number} para ${STAGE_CODE_REVIEW}** ` +
325
+ ` 3. **Avance a Etapa da Story #${itemNumber(issue)} para ${STAGE_CODE_REVIEW}** ` +
270
326
  `(reinicie o Status para ${PROGRESS_TODO}). As Tasks já estão em ${STAGE_DONE}.`
271
327
  );
272
328
  // A Feature só avança quando TODAS as suas Stories estiverem implementadas.
273
- lines.push(` 4. **A Feature${feature ? ` #${feature.number}` : ' (issue pai da Story)'} só avança para ${STAGE_CODE_REVIEW} quando TODAS as suas Stories estiverem implementadas:**`);
329
+ lines.push(` 4. **A Feature${feature ? ` #${itemNumber(feature)}` : ' (issue pai da Story)'} só avança para ${STAGE_CODE_REVIEW} quando TODAS as suas Stories estiverem implementadas:**`);
274
330
  if (siblingStories.length === 0) {
275
- lines.push(` - Esta é a **única Story** da Feature → avance também a Feature${feature ? ` #${feature.number}` : ''} para ${STAGE_CODE_REVIEW} (Status → ${PROGRESS_TODO}).`);
331
+ lines.push(` - Esta é a **única Story** da Feature → avance também a Feature${feature ? ` #${itemNumber(feature)}` : ''} para ${STAGE_CODE_REVIEW} (Status → ${PROGRESS_TODO}).`);
276
332
  } else {
277
333
  lines.push(` - Outras Stories desta Feature: ${siblingStories.map(s => `#${s.number}`).join(', ')}.`);
278
334
  lines.push(` - Verifique a Etapa de cada uma. Avance a Feature para ${STAGE_CODE_REVIEW} **somente se TODAS** já estiverem em ${STAGE_CODE_REVIEW} (ou etapa posterior).`);
279
335
  lines.push(` - Se **qualquer** Story ainda estiver pendente (antes de ${STAGE_CODE_REVIEW}), **NÃO mova a Feature** — deixe-a em ${STAGE_DEVELOPMENT} até a última Story ser concluída.`);
280
336
  }
281
337
  } else {
282
- lines.push(`Esta Task #${issue.number} está na Etapa **${STAGE_DEVELOPMENT}**:`);
338
+ lines.push(`Esta Task #${itemNumber(issue)} está na Etapa **${STAGE_DEVELOPMENT}**:`);
283
339
  lines.push('');
284
- lines.push(`1. **Ao começar:** Status da Task #${issue.number} → **${PROGRESS_IN_PROGRESS}** (Etapa continua ${STAGE_DEVELOPMENT}).`);
340
+ lines.push(`1. **Ao começar:** Status da Task #${itemNumber(issue)} → **${PROGRESS_IN_PROGRESS}** (Etapa continua ${STAGE_DEVELOPMENT}).`);
285
341
  lines.push('2. **Implemente** a Task por completo.');
286
- lines.push(`3. **Ao concluir:** **avance a Task #${issue.number} para a Etapa ${STAGE_DONE}** com Status **${PROGRESS_DONE}**.`);
342
+ lines.push(`3. **Ao concluir:** **avance a Task #${itemNumber(issue)} para a Etapa ${STAGE_DONE}** com Status **${PROGRESS_DONE}**.`);
287
343
  }
288
344
  lines.push('');
289
345
  lines.push(boardRuleBlockquote());
@@ -321,7 +377,7 @@ export function buildContext({
321
377
  * @param {{warnOnSkip?:boolean}} [opts]
322
378
  * @returns {Promise<Map<number, string|null>>}
323
379
  */
324
- async function fetchStagesOf(token, items, { warnOnSkip = false } = {}) {
380
+ async function fetchStagesOf(token, owner, repo, items, { warnOnSkip = false } = {}) {
325
381
  const stageOf = new Map();
326
382
  if (items.length === 0) return stageOf;
327
383
  const { project, error: projectError } = loadProjectConfig();
@@ -333,7 +389,7 @@ async function fetchStagesOf(token, items, { warnOnSkip = false } = {}) {
333
389
  }
334
390
  try {
335
391
  const { root } = loadConfig();
336
- const snapshot = await loadBoardSnapshot({ token, project, root, fresh: true });
392
+ const snapshot = await loadBoardSnapshot({ token, owner, repo, project, root, fresh: true });
337
393
  for (const s of items) {
338
394
  stageOf.set(s.number, snapshot.index.get(s.number)?.fields?.Etapa ?? null);
339
395
  }
@@ -419,7 +475,7 @@ export function buildFeatureContext({
419
475
  comments = [], codeDigest = null, blockedByWarnings = [], mode = 'pr-stack', hub = null,
420
476
  }) {
421
477
  const lines = [];
422
- lines.push(`# Contexto de implementação — Feature #${feature.number}`);
478
+ lines.push(`# Contexto de implementação — Feature #${itemNumber(feature)}`);
423
479
  lines.push('');
424
480
  lines.push(`**Feature:** ${feature.title}`);
425
481
  if (feature.body && feature.body.trim()) {
@@ -474,7 +530,7 @@ export function buildFeatureContext({
474
530
  lines.push('4. Só então inicie a próxima Story.');
475
531
  lines.push('');
476
532
  lines.push(
477
- `**Feature #${feature.number}:** avance-a para a Etapa **${STAGE_CODE_REVIEW}** (Status ${PROGRESS_TODO}) ` +
533
+ `**Feature #${itemNumber(feature)}:** avance-a para a Etapa **${STAGE_CODE_REVIEW}** (Status ${PROGRESS_TODO}) ` +
478
534
  `**somente após concluir a ÚLTIMA Story da lista**${skipped.length > 0 ? ' (as Stories já implementadas listadas abaixo não precisam ser refeitas)' : ''}. ` +
479
535
  `Enquanto houver Story pendente, a Feature permanece em ${STAGE_DEVELOPMENT}.` +
480
536
  // Só na pilha existem PRs de Story para deixar em rascunho; no modo agent o
@@ -498,7 +554,7 @@ export function buildFeatureContext({
498
554
  lines.push(
499
555
  '**Ao terminar, informe no relatório final:** os PRs ficam **empilhados** (cada um baseado no anterior) — ' +
500
556
  'o merge é **ordem-dependente**. Depois da revisão humana (marcar cada PR como pronto), o merge é ' +
501
- `\`npx @spec-wave/cli@latest merge ${feature.number}\`: ele mergeia na ordem das dependências, ` +
557
+ `\`npx ${cliRef()} merge ${itemNumber(feature)}\`: ele mergeia na ordem das dependências, ` +
502
558
  'reaponta as bases, move o board até 🧪 QA e só apaga as branches no fim. ' +
503
559
  '**NUNCA** mergeie um PR da pilha com `--delete-branch` à mão — apagar a branch antes de reapontar o dependente fecha o PR seguinte.'
504
560
  );
@@ -591,9 +647,14 @@ async function implementBug({ token, owner, repo, config, bug, dryRun, repoRoot
591
647
  // de um Bug pode ser Feature OU Story — o tipo vem do prefixo do título.
592
648
  let parent = null;
593
649
  try {
594
- const p0 = await getIssueParent(token, bug.node_id);
595
- if (p0?.number) {
596
- parent = { number: p0.number, title: p0.title, kind: detectIssueType(p0) || 'Item' };
650
+ const p0 = await trackerDe(token, owner, repo)
651
+ .getParent({ ref: { key: String(bug.number), id: bug.node_id } });
652
+ if (p0?.ref?.key) {
653
+ parent = {
654
+ number: Number(p0.ref.key),
655
+ title: p0.title,
656
+ kind: detectIssueType({ title: p0.title }) || 'Item',
657
+ };
597
658
  }
598
659
  } catch {
599
660
  // sem pai legível — bug órfão é caso previsto (reporte de suporte)
@@ -622,7 +683,7 @@ async function implementBug({ token, owner, repo, config, bug, dryRun, repoRoot
622
683
  });
623
684
 
624
685
  const comments = [];
625
- const all = await listIssueComments(token, owner, repo, issueNumber).catch(() => []);
686
+ const all = await trackerDe(token, owner, repo).listComments({ ref: { key: String(issueNumber) } }).catch(() => []);
626
687
  if (all.length > 0) {
627
688
  const items = all.slice(-MAX_COMMENTS_PER_ISSUE).map(c => ({
628
689
  ...c,
@@ -635,16 +696,18 @@ async function implementBug({ token, owner, repo, config, bug, dryRun, repoRoot
635
696
 
636
697
  let codeDigest = null;
637
698
  try {
638
- codeDigest = await buildCodeDigest({ sinceIso: bug.created_at || null, paths: [] });
699
+ codeDigest = await buildCodeDigest({ sinceIso: bug.createdAt || null, paths: [] });
639
700
  } catch {
640
701
  codeDigest = null;
641
702
  }
642
703
 
643
704
  const blockedByWarnings = [];
644
705
  try {
645
- const blocked = await listBlockedBy(token, owner, repo, issueNumber).catch(() => []);
706
+ const blocked = await trackerDe(token, owner, repo).listBlockedBy({ ref: { key: String(issueNumber) } }).catch(() => []);
646
707
  for (const b of blocked) {
647
- if (b?.state !== 'closed') blockedByWarnings.push(`#${b.number} — ${b.title}`);
708
+ // `listBlockedBy` devolve `{ ref, title, state }` — nunca `number`. Lido
709
+ // cru, o aviso que vai para o contexto do executor saía "#undefined".
710
+ if (b?.state !== 'closed') blockedByWarnings.push(`#${itemNumber(b)} — ${b.title}`);
648
711
  }
649
712
  } catch {
650
713
  // dependências não legíveis — segue
@@ -700,18 +763,18 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
700
763
  try {
701
764
  carga = await loadFeatureStories({
702
765
  token, owner, repo, root: repoRoot,
703
- feature: { number: feature.number, nodeId: feature.node_id, title: feature.title },
766
+ feature: { number: itemNumber(feature), nodeId: feature.node_id, title: feature.title },
704
767
  refresh, ttlSec,
705
768
  });
706
769
  } catch (err) {
707
- p.log.error(`Não foi possível listar as Stories da Feature #${feature.number}: ${err.message}`);
770
+ p.log.error(`Não foi possível listar as Stories da Feature #${itemNumber(feature)}: ${err.message}`);
708
771
  process.exitCode = 1;
709
772
  return;
710
773
  }
711
774
  const stories = carga.stories;
712
775
  if (stories.length === 0) {
713
776
  p.log.error(
714
- `Feature #${feature.number} não tem Stories (sub-issues). ` +
777
+ `Feature #${itemNumber(feature)} não tem Stories (sub-issues). ` +
715
778
  'Decomponha primeiro: adicione a label spec-wave:decompose.'
716
779
  );
717
780
  process.exitCode = 1;
@@ -722,7 +785,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
722
785
 
723
786
  // F1-board. Feature → Desenvolvimento (In Progress) já no início.
724
787
  await applyBoardMoves({ token, dryRun, moves: planBoardMoves('start', {
725
- feature: { nodeId: feature.node_id, number: feature.number },
788
+ feature: { nodeId: feature.node_id, number: itemNumber(feature) },
726
789
  }) });
727
790
 
728
791
  const enriched = stories.map(s => ({
@@ -734,7 +797,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
734
797
  const codeRepos = codeReposForItems(config, { labels: feature.labels || [], children: enriched }).repos;
735
798
 
736
799
  // F3. Etapa de cada Story no board (best-effort — sem board, nada é pulado).
737
- const stageOf = await fetchStagesOf(token, enriched, { warnOnSkip: true });
800
+ const stageOf = await fetchStagesOf(token, owner, repo, enriched, { warnOnSkip: true });
738
801
 
739
802
  // F4. Planejamento: pendentes em ordem topológica, puladas, ciclos.
740
803
  const { pending, skipped, cycle } = planFeatureImplementation(
@@ -744,7 +807,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
744
807
  p.log.error(
745
808
  `Ciclo de dependências entre Stories pendentes: ${cycle.map(n => `#${n}`).join(', ')}. ` +
746
809
  'Corrija as linhas "Depende de:" (ou as relações blocked by) dessas Stories — ' +
747
- `use \`spec-wave order ${feature.number}\` para visualizar.`
810
+ `use \`spec-wave order ${itemNumber(feature)}\` para visualizar.`
748
811
  );
749
812
  process.exitCode = 1;
750
813
  return;
@@ -762,17 +825,17 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
762
825
  // sem mover o card, run interrompido) não tinha como ser destravada —
763
826
  // reexecutar o implement caía aqui e retornava.
764
827
  await applyBoardMoves({ token, dryRun, moves: planBoardMoves('success', {
765
- feature: { nodeId: feature.node_id, number: feature.number },
828
+ feature: { nodeId: feature.node_id, number: itemNumber(feature) },
766
829
  }) });
767
830
  // Mesmo destravamento do lado dos PRs: a Feature está pronta para review,
768
831
  // então nenhum PR dela tem motivo para continuar em rascunho.
769
832
  await markFeaturePrsReady({
770
833
  token, owner, repo, dryRun, codeRepos,
771
- feature: { nodeId: feature.node_id, number: feature.number },
834
+ feature: { nodeId: feature.node_id, number: itemNumber(feature) },
772
835
  stories: enriched,
773
836
  linkMode: resolveLinkMode(config),
774
837
  });
775
- p.outro(`Todas as ${stories.length} story(ies) da Feature #${feature.number} já estão implementadas — nada a fazer.`);
838
+ p.outro(`Todas as ${stories.length} story(ies) da Feature #${itemNumber(feature)} já estão implementadas — nada a fazer.`);
776
839
  return;
777
840
  }
778
841
  p.log.info(`Ordem de implementação: ${pending.map(s => `#${s.number}`).join(' → ')}`);
@@ -808,7 +871,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
808
871
  const specRel = `docs/features/${slugify(feature.title)}/spec.md`;
809
872
  p.log.warn(await probeMissingDoc({
810
873
  token, owner, repo, root: repoRoot,
811
- pathRel: specRel, doc: 'spec', issueNumber: feature.number,
874
+ pathRel: specRel, doc: 'spec', issueNumber: itemNumber(feature),
812
875
  fallback: 'seguindo só com as Stories.',
813
876
  }));
814
877
  }
@@ -819,16 +882,19 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
819
882
  try {
820
883
  const internal = new Set(stories.map(s => s.number));
821
884
  const featureDeps = new Set(parseDependencies(feature.body));
822
- const featureBlocked = await listBlockedBy(token, owner, repo, feature.number).catch(() => []);
823
- for (const b of featureBlocked) featureDeps.add(b.number);
885
+ const featureBlocked = await trackerDe(token, owner, repo).listBlockedBy({ ref: { key: String(itemNumber(feature)) } }).catch(() => []);
886
+ for (const n of itemNumbers(featureBlocked)) featureDeps.add(n);
824
887
  const check = [
825
- { kind: 'Feature', number: feature.number, deps: featureDeps },
888
+ { kind: 'Feature', number: itemNumber(feature), deps: featureDeps },
826
889
  ...pending.map(s => ({ kind: 'Story', number: s.number, deps: new Set(s.dependsOn) })),
827
890
  ];
828
891
  for (const c of check) {
829
892
  for (const depNumber of [...c.deps].sort((a, b) => a - b)) {
830
893
  if (internal.has(depNumber)) continue;
831
- const dep = await getIssue(token, owner, repo, depNumber).catch(() => null);
894
+ const dep = await trackerDe(token, owner, repo)
895
+ .getWorkItem({ ref: { key: String(depNumber) } })
896
+ .then(w => w && comoSubIssue(w))
897
+ .catch(() => null);
832
898
  if (!dep || dep.state === 'closed') continue;
833
899
  const warning =
834
900
  `${c.kind} #${c.number} depende de #${depNumber} («${dep.title}»), ` +
@@ -842,11 +908,11 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
842
908
  // F8. Comentários: Feature primeiro, depois cada Story pendente na ordem.
843
909
  const comments = [];
844
910
  const commentSources = [
845
- { number: feature.number, kind: 'Feature' },
911
+ { number: itemNumber(feature), kind: 'Feature' },
846
912
  ...pending.map(s => ({ number: s.number, kind: 'Story' })),
847
913
  ];
848
914
  for (const src of commentSources) {
849
- const all = await listIssueComments(token, owner, repo, src.number).catch(() => []);
915
+ const all = await trackerDe(token, owner, repo).listComments({ ref: { key: String(src.number) } }).catch(() => []);
850
916
  if (all.length === 0) continue;
851
917
  const items = all.slice(-MAX_COMMENTS_PER_ISSUE).map(c => ({
852
918
  ...c,
@@ -861,14 +927,14 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
861
927
  let codeDigest = null;
862
928
  try {
863
929
  const paths = specPlan.plan ? extractPathsFromPlan(specPlan.plan) : [];
864
- codeDigest = await buildCodeDigest({ sinceIso: feature.created_at || null, paths });
930
+ codeDigest = await buildCodeDigest({ sinceIso: feature.createdAt || null, paths });
865
931
  } catch {
866
932
  codeDigest = null;
867
933
  }
868
934
 
869
935
  // F10. Contexto único + spec-kit (uma execução).
870
936
  const context = buildFeatureContext({
871
- feature: { number: feature.number, title: feature.title, body: feature.body || '' },
937
+ feature: { number: itemNumber(feature), title: feature.title, body: feature.body || '' },
872
938
  stories: pending,
873
939
  skipped,
874
940
  ...specPlan,
@@ -881,7 +947,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
881
947
  await writeContextAndRunSpecKit({
882
948
  config,
883
949
  repoSlugs: slugsForItem({ labels: feature.labels || [], children: pending }),
884
- issueNumber: feature.number,
950
+ issueNumber: itemNumber(feature),
885
951
  type: 'Feature',
886
952
  title: feature.title,
887
953
  specPlan,
@@ -891,10 +957,10 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
891
957
  repoRoot,
892
958
  expectedBranch: currentBranch,
893
959
  outroSuccess: mode === 'agent'
894
- ? `${chalk.green('✓')} Implementação acionada para a Feature #${feature.number} ` +
960
+ ? `${chalk.green('✓')} Implementação acionada para a Feature #${itemNumber(feature)} ` +
895
961
  `(${pending.length} story(ies) pendente(s)).\n` +
896
962
  ` Próximo: acompanhe o PR único da Feature; ele é aberto pelo próprio agente ao final.`
897
- : `${chalk.green('✓')} Implementação acionada para a Feature #${feature.number} ` +
963
+ : `${chalk.green('✓')} Implementação acionada para a Feature #${itemNumber(feature)} ` +
898
964
  `(${pending.length} story(ies) pendente(s)).\n` +
899
965
  ` Próximo: acompanhe os PRs de cada Story; a Feature avança para ${STAGE_CODE_REVIEW} após a última.`,
900
966
  onSuccess: async () => {
@@ -917,7 +983,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
917
983
  // não abre PR, nenhum dos dois acontecia: as 6 Stories da feature #18
918
984
  // foram para Code Review e a Feature ficou em Desenvolvimento.
919
985
  await applyBoardMoves({ token, moves: planBoardMoves('success', {
920
- feature: { nodeId: feature.node_id, number: feature.number },
986
+ feature: { nodeId: feature.node_id, number: itemNumber(feature) },
921
987
  }) });
922
988
  // A Feature avançou de Etapa; os PRs precisam contar a mesma história.
923
989
  // Enquanto as Stories eram implementadas, cada PR nasceu em rascunho para
@@ -925,7 +991,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
925
991
  // inteira fica revisável no mesmo instante.
926
992
  await markFeaturePrsReady({
927
993
  token, owner, repo, codeRepos,
928
- feature: { nodeId: feature.node_id, number: feature.number },
994
+ feature: { nodeId: feature.node_id, number: itemNumber(feature) },
929
995
  stories: enriched,
930
996
  linkMode: resolveLinkMode(config),
931
997
  });
@@ -982,7 +1048,9 @@ export async function implement({
982
1048
  // 2. Lê a issue alvo.
983
1049
  let issue;
984
1050
  try {
985
- issue = await getIssue(token, owner, repo, issueNumber);
1051
+ issue = await trackerDe(token, owner, repo)
1052
+ .getWorkItem({ ref: { key: String(issueNumber) } })
1053
+ .then(w => w && comoSubIssue(w));
986
1054
  } catch (err) {
987
1055
  p.log.error(`Não foi possível ler a issue #${issueNumber}: ${err.message}`);
988
1056
  process.exitCode = 1;
@@ -993,7 +1061,7 @@ export async function implement({
993
1061
  const type = detectIssueType(issue);
994
1062
  let tasks;
995
1063
  if (type === 'Story') {
996
- const subs = await listSubIssues(token, issue.node_id);
1064
+ const subs = (await trackerDe(token, owner, repo).listChildren({ ref: issue.ref })).map(comoSubIssue);
997
1065
  tasks = subs.filter(s => detectIssueType({ title: s.title, labels: s.labels }) === 'Task');
998
1066
  if (tasks.length === 0) {
999
1067
  p.log.error(`Story #${issueNumber} não tem Tasks (sub-issues) para implementar.`);
@@ -1002,7 +1070,7 @@ export async function implement({
1002
1070
  }
1003
1071
  p.log.info(`Story com ${tasks.length} task(s): ${tasks.map(t => `#${t.number}`).join(', ')}`);
1004
1072
  } else if (type === 'Task') {
1005
- tasks = [{ number: issue.number, title: issue.title, body: issue.body || '', nodeId: issue.node_id }];
1073
+ tasks = [{ number: itemNumber(issue), title: issue.title, body: issue.body || '', nodeId: issue.node_id }];
1006
1074
  p.log.info(`Task única #${issueNumber}.`);
1007
1075
  } else if (type === 'Feature') {
1008
1076
  // Modo Feature: Stories pendentes em ordem de dependência, contexto único.
@@ -1023,7 +1091,7 @@ export async function implement({
1023
1091
 
1024
1092
  // 4. Resolve a Feature (pai na cadeia) — para spec.md/plan.md e para as
1025
1093
  // instruções de fim de Story (avançar a Etapa para Code Review).
1026
- const feature = await resolveFeature(token, issue.node_id);
1094
+ const feature = await resolveFeature(token, owner, repo, issue.ref);
1027
1095
  let featureDir = featureDirOpt;
1028
1096
  if (!featureDir && feature?.title) {
1029
1097
  // Ancorado na RAIZ do repo: o config é encontrado subindo na árvore, e os
@@ -1052,8 +1120,8 @@ export async function implement({
1052
1120
  // Progress) já no início — a UI mostra o desenvolvimento em andamento sem
1053
1121
  // depender de o LLM mover cards. Best-effort: falha vira warn.
1054
1122
  await applyBoardMoves({ token, dryRun, moves: planBoardMoves('start', {
1055
- feature: feature ? { nodeId: feature.nodeId, number: feature.number } : null,
1056
- story: type === 'Story' ? { nodeId: issue.node_id, number: issue.number } : null,
1123
+ feature: feature ? { nodeId: feature.nodeId, number: itemNumber(feature) } : null,
1124
+ story: type === 'Story' ? { nodeId: issue.node_id, number: itemNumber(issue) } : null,
1057
1125
  tasks: tasks.map(t => ({ nodeId: t.nodeId, number: t.number })),
1058
1126
  tasksStartStatus: type === 'Task' ? PROGRESS_IN_PROGRESS : PROGRESS_TODO,
1059
1127
  }) });
@@ -1063,9 +1131,11 @@ export async function implement({
1063
1131
  // verificar antes de mover a Feature.
1064
1132
  let siblingStories = [];
1065
1133
  if (type === 'Story' && feature?.nodeId) {
1066
- const featureSubs = await listSubIssues(token, feature.nodeId).catch(() => []);
1134
+ const featureSubs = (await trackerDe(token, owner, repo)
1135
+ .listChildren({ ref: { key: String(itemNumber(feature)), id: feature.nodeId } })
1136
+ .catch(() => [])).map(comoSubIssue);
1067
1137
  siblingStories = featureSubs
1068
- .filter(s => detectIssueType({ title: s.title }) === 'Story' && s.number !== issue.number)
1138
+ .filter(s => detectIssueType({ title: s.title }) === 'Story' && s.number !== itemNumber(issue))
1069
1139
  // nodeId serve à consulta de Etapa no fim da Story (avanço da Feature).
1070
1140
  .map(s => ({ number: s.number, title: s.title, nodeId: s.nodeId }));
1071
1141
  }
@@ -1075,12 +1145,12 @@ export async function implement({
1075
1145
  // corrigidas. Feature primeiro (correções de escopo), depois a issue-alvo.
1076
1146
  const comments = [];
1077
1147
  const commentSources = [];
1078
- if (feature && feature.number !== issue.number) {
1079
- commentSources.push({ number: feature.number, kind: 'Feature' });
1148
+ if (feature && itemNumber(feature) !== itemNumber(issue)) {
1149
+ commentSources.push({ number: itemNumber(feature), kind: 'Feature' });
1080
1150
  }
1081
- commentSources.push({ number: issue.number, kind: type });
1151
+ commentSources.push({ number: itemNumber(issue), kind: type });
1082
1152
  for (const src of commentSources) {
1083
- const all = await listIssueComments(token, owner, repo, src.number).catch(() => []);
1153
+ const all = await trackerDe(token, owner, repo).listComments({ ref: { key: String(src.number) } }).catch(() => []);
1084
1154
  if (all.length === 0) continue;
1085
1155
  const items = all.slice(-MAX_COMMENTS_PER_ISSUE).map(c => ({
1086
1156
  ...c,
@@ -1096,10 +1166,13 @@ export async function implement({
1096
1166
  // já existe em vez de reimplementar.
1097
1167
  let codeDigest = null;
1098
1168
  try {
1099
- let sinceIso = issue.created_at || null;
1169
+ let sinceIso = issue.createdAt || null;
1100
1170
  if (feature?.number) {
1101
- const featureIssue = await getIssue(token, owner, repo, feature.number).catch(() => null);
1102
- if (featureIssue?.created_at) sinceIso = featureIssue.created_at;
1171
+ const featureIssue = await trackerDe(token, owner, repo)
1172
+ .getWorkItem({ ref: { key: String(itemNumber(feature)) } })
1173
+ .then(w => w && comoSubIssue(w))
1174
+ .catch(() => null);
1175
+ if (featureIssue?.createdAt) sinceIso = featureIssue.createdAt;
1103
1176
  }
1104
1177
  const paths = specPlan.plan ? extractPathsFromPlan(specPlan.plan) : [];
1105
1178
  codeDigest = await buildCodeDigest({ sinceIso, paths });
@@ -1113,13 +1186,16 @@ export async function implement({
1113
1186
  const blockedByWarnings = [];
1114
1187
  try {
1115
1188
  const depNumbers = new Set(parseDependencies(issue.body));
1116
- const blocked = await listBlockedBy(token, owner, repo, issue.number).catch(() => []);
1117
- for (const b of blocked) depNumbers.add(b.number);
1189
+ const blocked = await trackerDe(token, owner, repo).listBlockedBy({ ref: { key: String(itemNumber(issue)) } }).catch(() => []);
1190
+ for (const n of itemNumbers(blocked)) depNumbers.add(n);
1118
1191
  for (const depNumber of [...depNumbers].sort((a, b) => a - b)) {
1119
- const dep = await getIssue(token, owner, repo, depNumber).catch(() => null);
1192
+ const dep = await trackerDe(token, owner, repo)
1193
+ .getWorkItem({ ref: { key: String(depNumber) } })
1194
+ .then(w => w && comoSubIssue(w))
1195
+ .catch(() => null);
1120
1196
  if (!dep || dep.state === 'closed') continue;
1121
1197
  const warning =
1122
- `${type} #${issue.number} depende de #${depNumber} («${dep.title}»), ` +
1198
+ `${type} #${itemNumber(issue)} depende de #${depNumber} («${dep.title}»), ` +
1123
1199
  `que ainda não está concluída (state: ${dep.state}).`;
1124
1200
  blockedByWarnings.push(warning);
1125
1201
  p.log.warn(warning);
@@ -1143,7 +1219,7 @@ export async function implement({
1143
1219
  verifyCommits,
1144
1220
  repoSlugs: slugsForItem({ labels: issue.labels, children: tasks }),
1145
1221
  expectedTrailers: {
1146
- stories: type === 'Story' ? [issue.number] : [],
1222
+ stories: type === 'Story' ? [itemNumber(issue)] : [],
1147
1223
  tasks: tasks.map(t => t.number),
1148
1224
  },
1149
1225
  outroSuccess: mode === 'agent'
@@ -1153,7 +1229,7 @@ export async function implement({
1153
1229
  ' Próximo: revise as mudanças e abra o PR — o board já foi atualizado.',
1154
1230
  onSuccess: async () => {
1155
1231
  await applyBoardMoves({ token, moves: planBoardMoves('success', {
1156
- story: type === 'Story' ? { nodeId: issue.node_id, number: issue.number } : null,
1232
+ story: type === 'Story' ? { nodeId: issue.node_id, number: itemNumber(issue) } : null,
1157
1233
  tasks: tasks.map(t => ({ nodeId: t.nodeId, number: t.number })),
1158
1234
  }) });
1159
1235
  // Última Story da Feature? Então a Feature avança junto.
@@ -1171,11 +1247,11 @@ export async function implement({
1171
1247
  // Sem irmãs, esta era a única Story: a Feature avança direto (nada a
1172
1248
  // consultar). Com irmãs, todas precisam já estar em Code Review+.
1173
1249
  if (siblingStories.length > 0) {
1174
- const stageOf = await fetchStagesOf(token, siblingStories, {});
1250
+ const stageOf = await fetchStagesOf(token, owner, repo, siblingStories, {});
1175
1251
  if (!featureCanAdvance(siblingStories, stageOf)) return;
1176
1252
  }
1177
1253
  await applyBoardMoves({ token, dryRun, moves: planBoardMoves('success', {
1178
- feature: { nodeId: feature.nodeId, number: feature.number },
1254
+ feature: { nodeId: feature.nodeId, number: itemNumber(feature) },
1179
1255
  }) });
1180
1256
  // Chegou aqui = era a última Story pendente. É ESTE o momento que o
1181
1257
  // rascunho dos PRs estava esperando: enquanto o dev-agent ia de Story em
@@ -1186,8 +1262,8 @@ export async function implement({
1186
1262
  token, owner, repo, dryRun,
1187
1263
  // União dos repos de todas as Stories: os PRs da Feature vivem neles.
1188
1264
  codeRepos: codeReposForItems(config, { children: [...siblingStories, { labels: issue.labels }] }).repos,
1189
- feature: { nodeId: feature.nodeId, number: feature.number },
1190
- stories: [...siblingStories, { number: issue.number, nodeId: issue.node_id }],
1265
+ feature: { nodeId: feature.nodeId, number: itemNumber(feature) },
1266
+ stories: [...siblingStories, { number: itemNumber(issue), nodeId: issue.node_id }],
1191
1267
  linkMode: resolveLinkMode(config),
1192
1268
  });
1193
1269
  },
@@ -5,6 +5,7 @@ import path from 'node:path';
5
5
  import { CONFIG_FILE, PORTAL_URL } from '../config.mjs';
6
6
  import { findConfigPath } from '../lib/project-root.mjs';
7
7
  import { skillStatus } from './install-skill.mjs';
8
+ import { cliRef } from '../lib/cli-ref.mjs';
8
9
 
9
10
  // Resume o estado da skill para a saída JSON. `null` = não foi possível checar.
10
11
  function skillJson(status) {
@@ -24,7 +25,7 @@ function reportSkill(status) {
24
25
  if (status.agentsDetected.length === 0) {
25
26
  p.log.warn(
26
27
  'Nenhum agente de código detectado neste diretório — a skill spec-wave ' +
27
- 'não parece instalada. Rode `npx @spec-wave/cli@latest install-skill`.'
28
+ `não parece instalada. Rode \`npx ${cliRef()} install-skill\`.`
28
29
  );
29
30
  return;
30
31
  }
@@ -35,7 +36,7 @@ function reportSkill(status) {
35
36
  p.log.warn(
36
37
  'Skill pendente de instalação/atualização:\n' +
37
38
  status.pending.map(s => ` ${chalk.yellow('↻')} ${s.agent} (${s.reason}) — ${chalk.dim(s.path)}`).join('\n') +
38
- '\nRode `npx @spec-wave/cli@latest install-skill` (ou `npx @spec-wave/cli@latest update`).'
39
+ `\nRode \`npx ${cliRef()} install-skill\` (ou \`npx ${cliRef()} update\`).`
39
40
  );
40
41
  }
41
42
 
@@ -56,7 +57,7 @@ export async function info(options = {}) {
56
57
  p.log.warn(`Este repositório ${chalk.bold('não foi inicializado')} (sem ${CONFIG_FILE}).`);
57
58
  reportSkill(skill);
58
59
  p.log.info(`🌐 Acesse o Portal Web da ferramenta em ${chalk.cyan(PORTAL_URL)}`);
59
- p.outro('Execute `npx @spec-wave/cli@latest init` para configurar.');
60
+ p.outro(`Execute \`npx ${cliRef()} init\` para configurar.`);
60
61
  return;
61
62
  }
62
63