@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,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';
@@ -47,15 +66,16 @@ const MAX_COMMENT_CHARS = 2000;
47
66
  // "Feature" e devolve { number, title } — usado para resolver docs/features/<slug>
48
67
  // e para as instruções de fim de Story (mover a Feature para Code Review). Limita
49
68
  // a profundidade para evitar loops em dados inconsistentes.
50
- async function resolveFeature(token, startNodeId) {
51
- let current = startNodeId;
69
+ async function resolveFeature(token, owner, repo, startRef) {
70
+ const tracker = trackerDe(token, owner, repo);
71
+ let current = startRef;
52
72
  for (let depth = 0; depth < 5 && current; depth++) {
53
- const parent = await getIssueParent(token, current);
73
+ const parent = await tracker.getParent({ ref: current });
54
74
  if (!parent) return null;
55
75
  if (detectIssueType({ title: parent.title }) === 'Feature') {
56
- return { number: parent.number, title: parent.title, nodeId: parent.nodeId };
76
+ return { number: Number(parent.ref.key), title: parent.title, nodeId: parent.ref.id };
57
77
  }
58
- current = parent.nodeId;
78
+ current = parent.ref;
59
79
  }
60
80
  return null;
61
81
  }
@@ -82,7 +102,10 @@ async function probeMissingDoc({ token, owner, repo, root, pathRel, doc, issueNu
82
102
  if (achado?.state === 'remote') return missingDocMessage({ pathRel, onRemote: true, fallback });
83
103
  if (achado?.state === 'missing') return missingDocMessage({ pathRel, onRemote: false, fallback });
84
104
  }
85
- 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 });
86
109
  return missingDocMessage({ pathRel, onRemote, fallback });
87
110
  }
88
111
 
@@ -190,12 +213,44 @@ export function closesRef(hub, number) {
190
213
  return hub?.owner && hub?.repo ? `${hub.owner}/${hub.repo}#${number}` : `#${number}`;
191
214
  }
192
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
+
193
248
  export function buildContext({
194
249
  type, issue, tasks, feature, siblingStories = [], spec, plan, specPath, planPath,
195
250
  comments = [], codeDigest = null, blockedByWarnings = [], mode = 'pr-stack', hub = null,
196
251
  }) {
197
252
  const lines = [];
198
- lines.push(`# Contexto de implementação — ${type} #${issue.number}`);
253
+ lines.push(`# Contexto de implementação — ${type} #${itemNumber(issue)}`);
199
254
  lines.push('');
200
255
  lines.push(`**${type}:** ${issue.title}`);
201
256
  if (issue.body && issue.body.trim()) {
@@ -223,12 +278,12 @@ export function buildContext({
223
278
  lines.push('');
224
279
  if (type === 'Story') {
225
280
  lines.push(
226
- `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}**. ` +
227
282
  `Durante o desenvolvimento de cada Task, mexa no **Status**; ao **concluir** a Task, ela ` +
228
283
  `**avança para a Etapa ${STAGE_DONE}** (com Status ${PROGRESS_DONE}).`
229
284
  );
230
285
  lines.push('');
231
- 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}**.`);
232
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:`);
233
288
  lines.push(` 1. **Ao começar:** Status da Task → **${PROGRESS_IN_PROGRESS}** (a Etapa continua ${STAGE_DEVELOPMENT}).`);
234
289
  lines.push(' 2. **Implemente** a Task por completo.');
@@ -243,7 +298,7 @@ export function buildContext({
243
298
  );
244
299
  lines.push(' ```');
245
300
  lines.push(renderTrailers({
246
- story: issue.number, tasks: tasks.map(t => t.number),
301
+ story: itemNumber(issue), tasks: tasks.map(t => t.number),
247
302
  agent: mode === 'agent' ? 'spec-wave-agent' : undefined,
248
303
  }).split('\n').map(l => ` ${l}`).join('\n'));
249
304
  lines.push(' ```');
@@ -264,27 +319,27 @@ export function buildContext({
264
319
  // required check continua valendo. Quem tira do rascunho é o próprio
265
320
  // implement, quando a ÚLTIMA Story da Feature entra em Code Review (ver
266
321
  // lib/pr-ready.mjs): até lá o rascunho diz "feature em andamento".
267
- 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.**`);
268
323
  }
269
324
  lines.push(
270
- ` 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}** ` +
271
326
  `(reinicie o Status para ${PROGRESS_TODO}). As Tasks já estão em ${STAGE_DONE}.`
272
327
  );
273
328
  // A Feature só avança quando TODAS as suas Stories estiverem implementadas.
274
- 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:**`);
275
330
  if (siblingStories.length === 0) {
276
- 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}).`);
277
332
  } else {
278
333
  lines.push(` - Outras Stories desta Feature: ${siblingStories.map(s => `#${s.number}`).join(', ')}.`);
279
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).`);
280
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.`);
281
336
  }
282
337
  } else {
283
- lines.push(`Esta Task #${issue.number} está na Etapa **${STAGE_DEVELOPMENT}**:`);
338
+ lines.push(`Esta Task #${itemNumber(issue)} está na Etapa **${STAGE_DEVELOPMENT}**:`);
284
339
  lines.push('');
285
- 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}).`);
286
341
  lines.push('2. **Implemente** a Task por completo.');
287
- 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}**.`);
288
343
  }
289
344
  lines.push('');
290
345
  lines.push(boardRuleBlockquote());
@@ -322,7 +377,7 @@ export function buildContext({
322
377
  * @param {{warnOnSkip?:boolean}} [opts]
323
378
  * @returns {Promise<Map<number, string|null>>}
324
379
  */
325
- async function fetchStagesOf(token, items, { warnOnSkip = false } = {}) {
380
+ async function fetchStagesOf(token, owner, repo, items, { warnOnSkip = false } = {}) {
326
381
  const stageOf = new Map();
327
382
  if (items.length === 0) return stageOf;
328
383
  const { project, error: projectError } = loadProjectConfig();
@@ -334,7 +389,7 @@ async function fetchStagesOf(token, items, { warnOnSkip = false } = {}) {
334
389
  }
335
390
  try {
336
391
  const { root } = loadConfig();
337
- const snapshot = await loadBoardSnapshot({ token, project, root, fresh: true });
392
+ const snapshot = await loadBoardSnapshot({ token, owner, repo, project, root, fresh: true });
338
393
  for (const s of items) {
339
394
  stageOf.set(s.number, snapshot.index.get(s.number)?.fields?.Etapa ?? null);
340
395
  }
@@ -420,7 +475,7 @@ export function buildFeatureContext({
420
475
  comments = [], codeDigest = null, blockedByWarnings = [], mode = 'pr-stack', hub = null,
421
476
  }) {
422
477
  const lines = [];
423
- lines.push(`# Contexto de implementação — Feature #${feature.number}`);
478
+ lines.push(`# Contexto de implementação — Feature #${itemNumber(feature)}`);
424
479
  lines.push('');
425
480
  lines.push(`**Feature:** ${feature.title}`);
426
481
  if (feature.body && feature.body.trim()) {
@@ -475,7 +530,7 @@ export function buildFeatureContext({
475
530
  lines.push('4. Só então inicie a próxima Story.');
476
531
  lines.push('');
477
532
  lines.push(
478
- `**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}) ` +
479
534
  `**somente após concluir a ÚLTIMA Story da lista**${skipped.length > 0 ? ' (as Stories já implementadas listadas abaixo não precisam ser refeitas)' : ''}. ` +
480
535
  `Enquanto houver Story pendente, a Feature permanece em ${STAGE_DEVELOPMENT}.` +
481
536
  // Só na pilha existem PRs de Story para deixar em rascunho; no modo agent o
@@ -499,7 +554,7 @@ export function buildFeatureContext({
499
554
  lines.push(
500
555
  '**Ao terminar, informe no relatório final:** os PRs ficam **empilhados** (cada um baseado no anterior) — ' +
501
556
  'o merge é **ordem-dependente**. Depois da revisão humana (marcar cada PR como pronto), o merge é ' +
502
- `\`npx ${cliRef()} merge ${feature.number}\`: ele mergeia na ordem das dependências, ` +
557
+ `\`npx ${cliRef()} merge ${itemNumber(feature)}\`: ele mergeia na ordem das dependências, ` +
503
558
  'reaponta as bases, move o board até 🧪 QA e só apaga as branches no fim. ' +
504
559
  '**NUNCA** mergeie um PR da pilha com `--delete-branch` à mão — apagar a branch antes de reapontar o dependente fecha o PR seguinte.'
505
560
  );
@@ -592,9 +647,14 @@ async function implementBug({ token, owner, repo, config, bug, dryRun, repoRoot
592
647
  // de um Bug pode ser Feature OU Story — o tipo vem do prefixo do título.
593
648
  let parent = null;
594
649
  try {
595
- const p0 = await getIssueParent(token, bug.node_id);
596
- if (p0?.number) {
597
- 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
+ };
598
658
  }
599
659
  } catch {
600
660
  // sem pai legível — bug órfão é caso previsto (reporte de suporte)
@@ -623,7 +683,7 @@ async function implementBug({ token, owner, repo, config, bug, dryRun, repoRoot
623
683
  });
624
684
 
625
685
  const comments = [];
626
- const all = await listIssueComments(token, owner, repo, issueNumber).catch(() => []);
686
+ const all = await trackerDe(token, owner, repo).listComments({ ref: { key: String(issueNumber) } }).catch(() => []);
627
687
  if (all.length > 0) {
628
688
  const items = all.slice(-MAX_COMMENTS_PER_ISSUE).map(c => ({
629
689
  ...c,
@@ -636,16 +696,18 @@ async function implementBug({ token, owner, repo, config, bug, dryRun, repoRoot
636
696
 
637
697
  let codeDigest = null;
638
698
  try {
639
- codeDigest = await buildCodeDigest({ sinceIso: bug.created_at || null, paths: [] });
699
+ codeDigest = await buildCodeDigest({ sinceIso: bug.createdAt || null, paths: [] });
640
700
  } catch {
641
701
  codeDigest = null;
642
702
  }
643
703
 
644
704
  const blockedByWarnings = [];
645
705
  try {
646
- const blocked = await listBlockedBy(token, owner, repo, issueNumber).catch(() => []);
706
+ const blocked = await trackerDe(token, owner, repo).listBlockedBy({ ref: { key: String(issueNumber) } }).catch(() => []);
647
707
  for (const b of blocked) {
648
- 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}`);
649
711
  }
650
712
  } catch {
651
713
  // dependências não legíveis — segue
@@ -701,18 +763,18 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
701
763
  try {
702
764
  carga = await loadFeatureStories({
703
765
  token, owner, repo, root: repoRoot,
704
- feature: { number: feature.number, nodeId: feature.node_id, title: feature.title },
766
+ feature: { number: itemNumber(feature), nodeId: feature.node_id, title: feature.title },
705
767
  refresh, ttlSec,
706
768
  });
707
769
  } catch (err) {
708
- 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}`);
709
771
  process.exitCode = 1;
710
772
  return;
711
773
  }
712
774
  const stories = carga.stories;
713
775
  if (stories.length === 0) {
714
776
  p.log.error(
715
- `Feature #${feature.number} não tem Stories (sub-issues). ` +
777
+ `Feature #${itemNumber(feature)} não tem Stories (sub-issues). ` +
716
778
  'Decomponha primeiro: adicione a label spec-wave:decompose.'
717
779
  );
718
780
  process.exitCode = 1;
@@ -723,7 +785,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
723
785
 
724
786
  // F1-board. Feature → Desenvolvimento (In Progress) já no início.
725
787
  await applyBoardMoves({ token, dryRun, moves: planBoardMoves('start', {
726
- feature: { nodeId: feature.node_id, number: feature.number },
788
+ feature: { nodeId: feature.node_id, number: itemNumber(feature) },
727
789
  }) });
728
790
 
729
791
  const enriched = stories.map(s => ({
@@ -735,7 +797,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
735
797
  const codeRepos = codeReposForItems(config, { labels: feature.labels || [], children: enriched }).repos;
736
798
 
737
799
  // F3. Etapa de cada Story no board (best-effort — sem board, nada é pulado).
738
- const stageOf = await fetchStagesOf(token, enriched, { warnOnSkip: true });
800
+ const stageOf = await fetchStagesOf(token, owner, repo, enriched, { warnOnSkip: true });
739
801
 
740
802
  // F4. Planejamento: pendentes em ordem topológica, puladas, ciclos.
741
803
  const { pending, skipped, cycle } = planFeatureImplementation(
@@ -745,7 +807,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
745
807
  p.log.error(
746
808
  `Ciclo de dependências entre Stories pendentes: ${cycle.map(n => `#${n}`).join(', ')}. ` +
747
809
  'Corrija as linhas "Depende de:" (ou as relações blocked by) dessas Stories — ' +
748
- `use \`spec-wave order ${feature.number}\` para visualizar.`
810
+ `use \`spec-wave order ${itemNumber(feature)}\` para visualizar.`
749
811
  );
750
812
  process.exitCode = 1;
751
813
  return;
@@ -763,17 +825,17 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
763
825
  // sem mover o card, run interrompido) não tinha como ser destravada —
764
826
  // reexecutar o implement caía aqui e retornava.
765
827
  await applyBoardMoves({ token, dryRun, moves: planBoardMoves('success', {
766
- feature: { nodeId: feature.node_id, number: feature.number },
828
+ feature: { nodeId: feature.node_id, number: itemNumber(feature) },
767
829
  }) });
768
830
  // Mesmo destravamento do lado dos PRs: a Feature está pronta para review,
769
831
  // então nenhum PR dela tem motivo para continuar em rascunho.
770
832
  await markFeaturePrsReady({
771
833
  token, owner, repo, dryRun, codeRepos,
772
- feature: { nodeId: feature.node_id, number: feature.number },
834
+ feature: { nodeId: feature.node_id, number: itemNumber(feature) },
773
835
  stories: enriched,
774
836
  linkMode: resolveLinkMode(config),
775
837
  });
776
- 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.`);
777
839
  return;
778
840
  }
779
841
  p.log.info(`Ordem de implementação: ${pending.map(s => `#${s.number}`).join(' → ')}`);
@@ -809,7 +871,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
809
871
  const specRel = `docs/features/${slugify(feature.title)}/spec.md`;
810
872
  p.log.warn(await probeMissingDoc({
811
873
  token, owner, repo, root: repoRoot,
812
- pathRel: specRel, doc: 'spec', issueNumber: feature.number,
874
+ pathRel: specRel, doc: 'spec', issueNumber: itemNumber(feature),
813
875
  fallback: 'seguindo só com as Stories.',
814
876
  }));
815
877
  }
@@ -820,16 +882,19 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
820
882
  try {
821
883
  const internal = new Set(stories.map(s => s.number));
822
884
  const featureDeps = new Set(parseDependencies(feature.body));
823
- const featureBlocked = await listBlockedBy(token, owner, repo, feature.number).catch(() => []);
824
- 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);
825
887
  const check = [
826
- { kind: 'Feature', number: feature.number, deps: featureDeps },
888
+ { kind: 'Feature', number: itemNumber(feature), deps: featureDeps },
827
889
  ...pending.map(s => ({ kind: 'Story', number: s.number, deps: new Set(s.dependsOn) })),
828
890
  ];
829
891
  for (const c of check) {
830
892
  for (const depNumber of [...c.deps].sort((a, b) => a - b)) {
831
893
  if (internal.has(depNumber)) continue;
832
- 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);
833
898
  if (!dep || dep.state === 'closed') continue;
834
899
  const warning =
835
900
  `${c.kind} #${c.number} depende de #${depNumber} («${dep.title}»), ` +
@@ -843,11 +908,11 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
843
908
  // F8. Comentários: Feature primeiro, depois cada Story pendente na ordem.
844
909
  const comments = [];
845
910
  const commentSources = [
846
- { number: feature.number, kind: 'Feature' },
911
+ { number: itemNumber(feature), kind: 'Feature' },
847
912
  ...pending.map(s => ({ number: s.number, kind: 'Story' })),
848
913
  ];
849
914
  for (const src of commentSources) {
850
- 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(() => []);
851
916
  if (all.length === 0) continue;
852
917
  const items = all.slice(-MAX_COMMENTS_PER_ISSUE).map(c => ({
853
918
  ...c,
@@ -862,14 +927,14 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
862
927
  let codeDigest = null;
863
928
  try {
864
929
  const paths = specPlan.plan ? extractPathsFromPlan(specPlan.plan) : [];
865
- codeDigest = await buildCodeDigest({ sinceIso: feature.created_at || null, paths });
930
+ codeDigest = await buildCodeDigest({ sinceIso: feature.createdAt || null, paths });
866
931
  } catch {
867
932
  codeDigest = null;
868
933
  }
869
934
 
870
935
  // F10. Contexto único + spec-kit (uma execução).
871
936
  const context = buildFeatureContext({
872
- feature: { number: feature.number, title: feature.title, body: feature.body || '' },
937
+ feature: { number: itemNumber(feature), title: feature.title, body: feature.body || '' },
873
938
  stories: pending,
874
939
  skipped,
875
940
  ...specPlan,
@@ -882,7 +947,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
882
947
  await writeContextAndRunSpecKit({
883
948
  config,
884
949
  repoSlugs: slugsForItem({ labels: feature.labels || [], children: pending }),
885
- issueNumber: feature.number,
950
+ issueNumber: itemNumber(feature),
886
951
  type: 'Feature',
887
952
  title: feature.title,
888
953
  specPlan,
@@ -892,10 +957,10 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
892
957
  repoRoot,
893
958
  expectedBranch: currentBranch,
894
959
  outroSuccess: mode === 'agent'
895
- ? `${chalk.green('✓')} Implementação acionada para a Feature #${feature.number} ` +
960
+ ? `${chalk.green('✓')} Implementação acionada para a Feature #${itemNumber(feature)} ` +
896
961
  `(${pending.length} story(ies) pendente(s)).\n` +
897
962
  ` Próximo: acompanhe o PR único da Feature; ele é aberto pelo próprio agente ao final.`
898
- : `${chalk.green('✓')} Implementação acionada para a Feature #${feature.number} ` +
963
+ : `${chalk.green('✓')} Implementação acionada para a Feature #${itemNumber(feature)} ` +
899
964
  `(${pending.length} story(ies) pendente(s)).\n` +
900
965
  ` Próximo: acompanhe os PRs de cada Story; a Feature avança para ${STAGE_CODE_REVIEW} após a última.`,
901
966
  onSuccess: async () => {
@@ -918,7 +983,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
918
983
  // não abre PR, nenhum dos dois acontecia: as 6 Stories da feature #18
919
984
  // foram para Code Review e a Feature ficou em Desenvolvimento.
920
985
  await applyBoardMoves({ token, moves: planBoardMoves('success', {
921
- feature: { nodeId: feature.node_id, number: feature.number },
986
+ feature: { nodeId: feature.node_id, number: itemNumber(feature) },
922
987
  }) });
923
988
  // A Feature avançou de Etapa; os PRs precisam contar a mesma história.
924
989
  // Enquanto as Stories eram implementadas, cada PR nasceu em rascunho para
@@ -926,7 +991,7 @@ async function implementFeature({ token, owner, repo, config, feature, featureDi
926
991
  // inteira fica revisável no mesmo instante.
927
992
  await markFeaturePrsReady({
928
993
  token, owner, repo, codeRepos,
929
- feature: { nodeId: feature.node_id, number: feature.number },
994
+ feature: { nodeId: feature.node_id, number: itemNumber(feature) },
930
995
  stories: enriched,
931
996
  linkMode: resolveLinkMode(config),
932
997
  });
@@ -983,7 +1048,9 @@ export async function implement({
983
1048
  // 2. Lê a issue alvo.
984
1049
  let issue;
985
1050
  try {
986
- 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));
987
1054
  } catch (err) {
988
1055
  p.log.error(`Não foi possível ler a issue #${issueNumber}: ${err.message}`);
989
1056
  process.exitCode = 1;
@@ -994,7 +1061,7 @@ export async function implement({
994
1061
  const type = detectIssueType(issue);
995
1062
  let tasks;
996
1063
  if (type === 'Story') {
997
- const subs = await listSubIssues(token, issue.node_id);
1064
+ const subs = (await trackerDe(token, owner, repo).listChildren({ ref: issue.ref })).map(comoSubIssue);
998
1065
  tasks = subs.filter(s => detectIssueType({ title: s.title, labels: s.labels }) === 'Task');
999
1066
  if (tasks.length === 0) {
1000
1067
  p.log.error(`Story #${issueNumber} não tem Tasks (sub-issues) para implementar.`);
@@ -1003,7 +1070,7 @@ export async function implement({
1003
1070
  }
1004
1071
  p.log.info(`Story com ${tasks.length} task(s): ${tasks.map(t => `#${t.number}`).join(', ')}`);
1005
1072
  } else if (type === 'Task') {
1006
- 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 }];
1007
1074
  p.log.info(`Task única #${issueNumber}.`);
1008
1075
  } else if (type === 'Feature') {
1009
1076
  // Modo Feature: Stories pendentes em ordem de dependência, contexto único.
@@ -1024,7 +1091,7 @@ export async function implement({
1024
1091
 
1025
1092
  // 4. Resolve a Feature (pai na cadeia) — para spec.md/plan.md e para as
1026
1093
  // instruções de fim de Story (avançar a Etapa para Code Review).
1027
- const feature = await resolveFeature(token, issue.node_id);
1094
+ const feature = await resolveFeature(token, owner, repo, issue.ref);
1028
1095
  let featureDir = featureDirOpt;
1029
1096
  if (!featureDir && feature?.title) {
1030
1097
  // Ancorado na RAIZ do repo: o config é encontrado subindo na árvore, e os
@@ -1053,8 +1120,8 @@ export async function implement({
1053
1120
  // Progress) já no início — a UI mostra o desenvolvimento em andamento sem
1054
1121
  // depender de o LLM mover cards. Best-effort: falha vira warn.
1055
1122
  await applyBoardMoves({ token, dryRun, moves: planBoardMoves('start', {
1056
- feature: feature ? { nodeId: feature.nodeId, number: feature.number } : null,
1057
- 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,
1058
1125
  tasks: tasks.map(t => ({ nodeId: t.nodeId, number: t.number })),
1059
1126
  tasksStartStatus: type === 'Task' ? PROGRESS_IN_PROGRESS : PROGRESS_TODO,
1060
1127
  }) });
@@ -1064,9 +1131,11 @@ export async function implement({
1064
1131
  // verificar antes de mover a Feature.
1065
1132
  let siblingStories = [];
1066
1133
  if (type === 'Story' && feature?.nodeId) {
1067
- 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);
1068
1137
  siblingStories = featureSubs
1069
- .filter(s => detectIssueType({ title: s.title }) === 'Story' && s.number !== issue.number)
1138
+ .filter(s => detectIssueType({ title: s.title }) === 'Story' && s.number !== itemNumber(issue))
1070
1139
  // nodeId serve à consulta de Etapa no fim da Story (avanço da Feature).
1071
1140
  .map(s => ({ number: s.number, title: s.title, nodeId: s.nodeId }));
1072
1141
  }
@@ -1076,12 +1145,12 @@ export async function implement({
1076
1145
  // corrigidas. Feature primeiro (correções de escopo), depois a issue-alvo.
1077
1146
  const comments = [];
1078
1147
  const commentSources = [];
1079
- if (feature && feature.number !== issue.number) {
1080
- commentSources.push({ number: feature.number, kind: 'Feature' });
1148
+ if (feature && itemNumber(feature) !== itemNumber(issue)) {
1149
+ commentSources.push({ number: itemNumber(feature), kind: 'Feature' });
1081
1150
  }
1082
- commentSources.push({ number: issue.number, kind: type });
1151
+ commentSources.push({ number: itemNumber(issue), kind: type });
1083
1152
  for (const src of commentSources) {
1084
- 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(() => []);
1085
1154
  if (all.length === 0) continue;
1086
1155
  const items = all.slice(-MAX_COMMENTS_PER_ISSUE).map(c => ({
1087
1156
  ...c,
@@ -1097,10 +1166,13 @@ export async function implement({
1097
1166
  // já existe em vez de reimplementar.
1098
1167
  let codeDigest = null;
1099
1168
  try {
1100
- let sinceIso = issue.created_at || null;
1169
+ let sinceIso = issue.createdAt || null;
1101
1170
  if (feature?.number) {
1102
- const featureIssue = await getIssue(token, owner, repo, feature.number).catch(() => null);
1103
- 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;
1104
1176
  }
1105
1177
  const paths = specPlan.plan ? extractPathsFromPlan(specPlan.plan) : [];
1106
1178
  codeDigest = await buildCodeDigest({ sinceIso, paths });
@@ -1114,13 +1186,16 @@ export async function implement({
1114
1186
  const blockedByWarnings = [];
1115
1187
  try {
1116
1188
  const depNumbers = new Set(parseDependencies(issue.body));
1117
- const blocked = await listBlockedBy(token, owner, repo, issue.number).catch(() => []);
1118
- 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);
1119
1191
  for (const depNumber of [...depNumbers].sort((a, b) => a - b)) {
1120
- 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);
1121
1196
  if (!dep || dep.state === 'closed') continue;
1122
1197
  const warning =
1123
- `${type} #${issue.number} depende de #${depNumber} («${dep.title}»), ` +
1198
+ `${type} #${itemNumber(issue)} depende de #${depNumber} («${dep.title}»), ` +
1124
1199
  `que ainda não está concluída (state: ${dep.state}).`;
1125
1200
  blockedByWarnings.push(warning);
1126
1201
  p.log.warn(warning);
@@ -1144,7 +1219,7 @@ export async function implement({
1144
1219
  verifyCommits,
1145
1220
  repoSlugs: slugsForItem({ labels: issue.labels, children: tasks }),
1146
1221
  expectedTrailers: {
1147
- stories: type === 'Story' ? [issue.number] : [],
1222
+ stories: type === 'Story' ? [itemNumber(issue)] : [],
1148
1223
  tasks: tasks.map(t => t.number),
1149
1224
  },
1150
1225
  outroSuccess: mode === 'agent'
@@ -1154,7 +1229,7 @@ export async function implement({
1154
1229
  ' Próximo: revise as mudanças e abra o PR — o board já foi atualizado.',
1155
1230
  onSuccess: async () => {
1156
1231
  await applyBoardMoves({ token, moves: planBoardMoves('success', {
1157
- story: type === 'Story' ? { nodeId: issue.node_id, number: issue.number } : null,
1232
+ story: type === 'Story' ? { nodeId: issue.node_id, number: itemNumber(issue) } : null,
1158
1233
  tasks: tasks.map(t => ({ nodeId: t.nodeId, number: t.number })),
1159
1234
  }) });
1160
1235
  // Última Story da Feature? Então a Feature avança junto.
@@ -1172,11 +1247,11 @@ export async function implement({
1172
1247
  // Sem irmãs, esta era a única Story: a Feature avança direto (nada a
1173
1248
  // consultar). Com irmãs, todas precisam já estar em Code Review+.
1174
1249
  if (siblingStories.length > 0) {
1175
- const stageOf = await fetchStagesOf(token, siblingStories, {});
1250
+ const stageOf = await fetchStagesOf(token, owner, repo, siblingStories, {});
1176
1251
  if (!featureCanAdvance(siblingStories, stageOf)) return;
1177
1252
  }
1178
1253
  await applyBoardMoves({ token, dryRun, moves: planBoardMoves('success', {
1179
- feature: { nodeId: feature.nodeId, number: feature.number },
1254
+ feature: { nodeId: feature.nodeId, number: itemNumber(feature) },
1180
1255
  }) });
1181
1256
  // Chegou aqui = era a última Story pendente. É ESTE o momento que o
1182
1257
  // rascunho dos PRs estava esperando: enquanto o dev-agent ia de Story em
@@ -1187,8 +1262,8 @@ export async function implement({
1187
1262
  token, owner, repo, dryRun,
1188
1263
  // União dos repos de todas as Stories: os PRs da Feature vivem neles.
1189
1264
  codeRepos: codeReposForItems(config, { children: [...siblingStories, { labels: issue.labels }] }).repos,
1190
- feature: { nodeId: feature.nodeId, number: feature.number },
1191
- 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 }],
1192
1267
  linkMode: resolveLinkMode(config),
1193
1268
  });
1194
1269
  },
@@ -7,7 +7,8 @@ import { runWizard } from '../ui/wizard.mjs';
7
7
  import { setupProject } from '../setup/project.mjs';
8
8
  import { setupLabels } from '../setup/labels.mjs';
9
9
  import { setupFiles } from '../setup/files.mjs';
10
- import { getFileContent, getOwnerType } 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 {
12
13
  CONFIG_FILE, AI_PROVIDERS, getProvider, DEFAULT_PROVIDER, PORTAL_URL, WORKFLOW_FILES, CODE_WORKFLOW_FILES,
13
14
  ISSUE_TEMPLATE_FILES, STATUS_OPTIONS, ALL_LABELS, HUB_DISPATCH_SECRET,
@@ -136,7 +137,10 @@ export async function init(options) {
136
137
  ownerSpinner.start(`Verificando se ${owner} é uma organização...`);
137
138
  let ownerType;
138
139
  try {
139
- ownerType = await getOwnerType(token, owner);
140
+ // `verify()` é a sonda org-vs-user: o GitHub App só alcança Projects v2 de
141
+ // ORGANIZAÇÃO, e é aqui que o init recusa antes de criar qualquer coisa.
142
+ const diag = await createGithubTracker({ token, owner, repo }).verify();
143
+ ownerType = diag.facts.ownerType;
140
144
  } catch (err) {
141
145
  ownerSpinner.stop('');
142
146
  p.log.error(`Erro ao verificar owner "${owner}": ${err.message}`);
@@ -184,7 +188,8 @@ export async function init(options) {
184
188
  const localConfigPath = path.join(process.cwd(), CONFIG_FILE);
185
189
  const raw = existsSync(localConfigPath)
186
190
  ? readFileSync(localConfigPath, 'utf-8')
187
- : await getFileContent(token, owner, repo, CONFIG_FILE);
191
+ : await createGithubScm({ link: githubLink({ owner, repo }), token })
192
+ .readFile({ path: CONFIG_FILE });
188
193
  if (raw) {
189
194
  const existing = JSON.parse(raw);
190
195
  if (existing.project) {