@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spec-wave/cli",
3
- "version": "1.0.8",
3
+ "version": "1.2.0",
4
4
  "description": "Setup spec-driven GitHub workflow with Projects v2, labels, issue templates, and AI-powered Actions",
5
5
  "type": "module",
6
6
  "bin": {
@@ -550,6 +550,57 @@ export async function setItemSingleSelect(token, projectId, itemId, fieldId, opt
550
550
  `, { projectId, itemId, fieldId, optionId });
551
551
  }
552
552
 
553
+ // Define o valor de um campo TEXT para um item do Project.
554
+ //
555
+ // Rota separada da de single-select porque a mutation exige `value: { text: }`
556
+ // contra `value: { singleSelectOptionId: }` — não é o mesmo payload com outro
557
+ // argumento.
558
+ export async function setItemText(token, projectId, itemId, fieldId, text) {
559
+ const client = makeClient(token);
560
+ await client(`
561
+ mutation SetTextField($projectId: ID!, $itemId: ID!, $fieldId: ID!, $text: String!) {
562
+ updateProjectV2ItemFieldValue(input: {
563
+ projectId: $projectId
564
+ itemId: $itemId
565
+ fieldId: $fieldId
566
+ value: { text: $text }
567
+ }) {
568
+ projectV2Item { id }
569
+ }
570
+ }
571
+ `, { projectId, itemId, fieldId, text: String(text ?? '') });
572
+ }
573
+
574
+ // Lê o valor atual de um campo TEXT.
575
+ //
576
+ // Função NOVA em vez de um fragmento a mais em `getItemSingleSelectValue`: essa
577
+ // query é a leitura que o guard "a Etapa só avança" faz em todo movimento de
578
+ // board, e nenhum teste desta suíte fala GraphQL de verdade. Mexer nela para
579
+ // atender um campo que nada escreve hoje seria arriscar o caminho mais
580
+ // carregado do sistema pelo menos carregado.
581
+ export async function getItemTextValue(token, itemId, fieldId) {
582
+ const client = makeClient(token);
583
+ const result = await client(`
584
+ query ItemTextValue($itemId: ID!) {
585
+ node(id: $itemId) {
586
+ ... on ProjectV2Item {
587
+ fieldValues(first: 50) {
588
+ nodes {
589
+ ... on ProjectV2ItemFieldTextValue {
590
+ text
591
+ field { ... on ProjectV2Field { id } }
592
+ }
593
+ }
594
+ }
595
+ }
596
+ }
597
+ }
598
+ `, { itemId });
599
+ const nodes = result.node?.fieldValues?.nodes || [];
600
+ const value = nodes.find(n => n && n.field?.id === fieldId);
601
+ return value?.text ?? null;
602
+ }
603
+
553
604
  export async function createTextField(token, projectId, name) {
554
605
  const client = makeClient(token);
555
606
  const result = await client(`
@@ -351,6 +351,54 @@ export async function updateMilestoneDescription(token, owner, repo, milestoneNu
351
351
  return res.data;
352
352
  }
353
353
 
354
+ // Cria uma milestone. `dueOn` é ISO-8601 e vai como `due_on`.
355
+ //
356
+ // O GitHub recusa (422) título repetido, e isso é RESULTADO, não falha de rede:
357
+ // quem chama decide entre reusar a existente e reclamar. Devolver `null` aqui
358
+ // apagaria a diferença entre "já existe" e "não consegui falar com a API", que
359
+ // é justamente a distinção que o chamador precisa — então o 422 sobe.
360
+ export async function createMilestone(token, owner, repo, { title, description, dueOn } = {}) {
361
+ const octokit = makeOctokit(token);
362
+ const res = await octokit.rest.issues.createMilestone({
363
+ owner, repo, title,
364
+ ...(description == null ? {} : { description }),
365
+ ...(dueOn ? { due_on: dueOn } : {}),
366
+ });
367
+ return res.data;
368
+ }
369
+
370
+ // Atualiza campos de uma milestone. PATCH parcial: campo não passado não é
371
+ // tocado — por isso cada um só entra no payload quando veio.
372
+ //
373
+ // `updateMilestoneDescription` continua existindo e NÃO é um caso particular
374
+ // desta: ela promete mexer só na descrição, e é dessa promessa estreita que o
375
+ // `qa-lead` depende ao substituir o bloco de trilha.
376
+ export async function updateMilestone(token, owner, repo, milestoneNumber, { title, description, dueOn, state } = {}) {
377
+ const octokit = makeOctokit(token);
378
+ const res = await octokit.rest.issues.updateMilestone({
379
+ owner, repo, milestone_number: milestoneNumber,
380
+ ...(title == null ? {} : { title }),
381
+ ...(description == null ? {} : { description }),
382
+ ...(dueOn === undefined ? {} : { due_on: dueOn }),
383
+ ...(state == null ? {} : { state }),
384
+ });
385
+ return res.data;
386
+ }
387
+
388
+ // Atribui (ou REMOVE, com `null`) a milestone de uma issue que já existe.
389
+ //
390
+ // A assimetria com `createIssue` é da API e é fácil de trocar: lá `milestone:
391
+ // null` leva 422 e por isso o campo só entra quando existe; aqui `null` é
392
+ // justamente como se remove, e omitir o campo é que seria "não mexe". Um `...(m
393
+ // ? {m} : {})` copiado de lá tornaria a remoção silenciosamente inócua.
394
+ export async function setIssueMilestone(token, owner, repo, issueNumber, milestoneNumber) {
395
+ const octokit = makeOctokit(token);
396
+ await octokit.rest.issues.update({
397
+ owner, repo, issue_number: issueNumber,
398
+ milestone: milestoneNumber == null ? null : Number(milestoneNumber),
399
+ });
400
+ }
401
+
354
402
  // Issues de uma milestone (pelo NÚMERO dela), abertas e fechadas.
355
403
  //
356
404
  // `state: 'all'` de propósito: uma Feature fechada continua contando para o
@@ -22,9 +22,8 @@ import { readdirSync } from 'node:fs';
22
22
  import path from 'node:path';
23
23
 
24
24
  import { resolveToken } from '../api/auth.mjs';
25
- import {
26
- getIssue, getRepoDefaultBranch, listMilestones, listIssuesByMilestone,
27
- } from '../api/github-rest.mjs';
25
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
26
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
28
27
  import { CONFIG_FILE } from '../config.mjs';
29
28
  import { detectIssueType } from '../lib/issue-type.mjs';
30
29
  import { featureDocPaths } from '../lib/doc-paths.mjs';
@@ -74,7 +73,7 @@ export function listRepoFiles(root, { maxFiles = MAX_FILES, maxDepth = 8 } = {})
74
73
  return out;
75
74
  }
76
75
 
77
- export async function audit({ milestone: milestoneArg, critique = false, json = false } = {}) {
76
+ export async function audit({ milestone: milestoneArg, critique = false, json = false, deps = {} } = {}) {
78
77
  const falhar = (msg) => {
79
78
  if (json) console.log(JSON.stringify({ erro: msg }, null, 2));
80
79
  else p.log.error(msg);
@@ -96,14 +95,17 @@ export async function audit({ milestone: milestoneArg, critique = false, json =
96
95
  return falhar(`Sem token utilizável para ${owner}/${repo}: ${err.message}`);
97
96
  }
98
97
 
98
+ const tracker = deps.tracker ?? createGithubTracker({ token, owner, repo });
99
+ const scm = deps.scm ?? createGithubScm({ link: githubLink({ owner, repo }), token });
100
+
99
101
  const s = json ? null : p.spinner();
100
102
  s?.start('Montando o catálogo de Features...');
101
103
 
102
104
  let base;
103
105
  let milestones;
104
106
  try {
105
- base = await getRepoDefaultBranch(token, owner, repo);
106
- milestones = await listMilestones(token, owner, repo);
107
+ base = await scm.defaultBranch();
108
+ milestones = await tracker.listMilestones();
107
109
  } catch (err) {
108
110
  s?.stop('');
109
111
  return falhar(`Não foi possível ler o repositório ${owner}/${repo}: ${err.message}`);
@@ -120,16 +122,16 @@ export async function audit({ milestone: milestoneArg, critique = false, json =
120
122
  let targetIssues = [];
121
123
  try {
122
124
  for (const m of milestones) {
123
- const issues = await listIssuesByMilestone(token, owner, repo, m.number);
124
- if (m.number === milestone.number) targetIssues = issues;
125
+ const issues = await tracker.listWorkItemsByMilestone({ milestone: m });
126
+ if (m.key === milestone.key) targetIssues = issues;
125
127
  for (const i of issues) {
126
128
  if (detectIssueType(i) !== 'Feature') continue;
127
129
  catalog.push({
128
- number: i.number,
130
+ number: Number(i.ref.key),
129
131
  title: i.title,
130
132
  slug: slugify(i.title),
131
133
  closed: i.state === 'closed',
132
- milestone: { number: m.number, title: m.title, due_on: m.due_on ?? null },
134
+ milestone: { number: Number(m.key), title: m.title, due_on: m.dueOn ?? null },
133
135
  });
134
136
  }
135
137
  }
@@ -149,14 +151,14 @@ export async function audit({ milestone: milestoneArg, critique = false, json =
149
151
  // agentes-2026-08.md: descartar isso é a mesma lacuna que o preflight já
150
152
  // corrigiu (PRs #65/#66) e que este comando herdou sem herdar a distinção.
151
153
  const { content, state } = await loadArtifact({
152
- token, owner, repo, root, base,
153
- pathRel: docs.spec.rel, doc: 'spec', issueNumber: issue.number,
154
+ token, owner, repo, root, base, scm,
155
+ pathRel: docs.spec.rel, doc: 'spec', issueNumber: issue.ref.key,
154
156
  });
155
157
  features.push({
156
- number: issue.number,
158
+ number: Number(issue.ref.key),
157
159
  title: issue.title,
158
160
  slug: slugify(issue.title),
159
- milestone: { number: milestone.number, title: milestone.title, due_on: milestone.due_on ?? null },
161
+ milestone: { number: Number(milestone.key), title: milestone.title, due_on: milestone.dueOn ?? null },
160
162
  spec: content,
161
163
  specState: state,
162
164
  });
@@ -179,15 +181,19 @@ export async function audit({ milestone: milestoneArg, critique = false, json =
179
181
  }
180
182
  const missingRefs = [];
181
183
  for (const n of desconhecidas) {
182
- const issue = await getIssue(token, owner, repo, n).catch(() => null);
184
+ const issue = await tracker.getWorkItem({ ref: { key: String(n) } }).catch(() => null);
183
185
  if (!issue) { missingRefs.push(n); continue; }
184
186
  catalog.push({
185
- number: issue.number,
187
+ number: Number(issue.ref.key),
186
188
  title: issue.title,
187
189
  slug: slugify(issue.title),
188
190
  closed: issue.state === 'closed',
189
191
  milestone: issue.milestone
190
- ? { number: issue.milestone.number, title: issue.milestone.title, due_on: issue.milestone.due_on ?? null }
192
+ ? {
193
+ number: Number(issue.milestone.key),
194
+ title: issue.milestone.title,
195
+ due_on: issue.milestone.dueOn ?? null,
196
+ }
191
197
  : null,
192
198
  });
193
199
  }
@@ -245,7 +251,7 @@ export async function audit({ milestone: milestoneArg, critique = false, json =
245
251
  }
246
252
 
247
253
  const saida = {
248
- milestone: { title: milestone.title, number: milestone.number },
254
+ milestone: { title: milestone.title, number: Number(milestone.key) },
249
255
  features: features.map(f => ({ number: f.number, title: f.title, temSpec: !!f.spec })),
250
256
  auditoria: resultado,
251
257
  // `markdown` é o comentário pronto para a issue — quem posta (nas DUAS
@@ -1,11 +1,23 @@
1
1
  import { appendFileSync } from 'node:fs';
2
2
  import { resolveToken } from '../api/auth.mjs';
3
- import { getIssue, getPR, commentOnIssue } from '../api/github-rest.mjs';
4
- import {
5
- addProjectItem, getIssueParent, listSubIssues, getItemSingleSelectValue, getPRClosingIssues,
6
- } from '../api/github-graphql.mjs';
3
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
4
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
5
+
6
+ // WorkItem → a forma `{number, nodeId, title, labels}` que este arquivo usa nos
7
+ // mapas de Stories/Tasks. Um lugar só, no ponto de leitura.
8
+ const comoItem = w => w && ({
9
+ number: Number(w.ref.key),
10
+ nodeId: w.ref.id,
11
+ node_id: w.ref.id,
12
+ title: w.title,
13
+ body: w.body || '',
14
+ labels: w.tags || [],
15
+ state: w.state || null,
16
+ createdAt: w.createdAt || null,
17
+ ref: w.ref,
18
+ });
7
19
  import { detectIssueType } from '../lib/issue-type.mjs';
8
- import { loadProjectConfig, resolveField, advanceToStage } from '../lib/board.mjs';
20
+ import { openTracker, advanceToStage } from '../lib/board.mjs';
9
21
  import { resolveHubContext, resolvePrRepo } from '../lib/project-root.mjs';
10
22
  import { markFeaturePrsReady } from '../lib/pr-ready.mjs';
11
23
  import { codeReposForItems } from '../lib/workspace.mjs';
@@ -55,24 +67,25 @@ export function partitionByCreation(subs = [], notAfter = null) {
55
67
  }
56
68
 
57
69
  // A partir de qualquer issue (Feature/Story/Task), sobe a hierarquia e retorna a Feature.
58
- async function resolveFeatureIssue(token, owner, repo, issueNumber) {
70
+ async function resolveFeatureIssue(tracker, issueNumber) {
59
71
  let issue;
60
72
  try {
61
- issue = await getIssue(token, owner, repo, issueNumber);
73
+ issue = comoItem(await tracker.getWorkItem({ ref: { key: String(issueNumber) } }));
62
74
  } catch {
63
75
  return null;
64
76
  }
77
+ if (!issue) return null;
65
78
  const type = detectIssueType(issue);
66
79
  if (type === 'Feature') return issue;
67
80
  if (type !== 'Story' && type !== 'Task') return null;
68
- let currentNodeId = issue.node_id;
81
+ let atual = issue.ref;
69
82
  for (let depth = 0; depth < 5; depth++) {
70
- const parent = await getIssueParent(token, currentNodeId);
83
+ const parent = await tracker.getParent({ ref: atual });
71
84
  if (!parent) return null;
72
85
  if (detectIssueType({ title: parent.title }) === 'Feature') {
73
- return await getIssue(token, owner, repo, parent.number).catch(() => null);
86
+ return comoItem(await tracker.getWorkItem({ ref: parent.ref }).catch(() => null));
74
87
  }
75
- currentNodeId = parent.nodeId;
88
+ atual = parent.ref;
76
89
  }
77
90
  return null;
78
91
  }
@@ -108,7 +121,7 @@ function isDecomposing(issue) {
108
121
  return labelNames(issue?.labels || []).some(n => DECOMPOSING_LABELS.includes(n));
109
122
  }
110
123
 
111
- async function collectReviewUnit(token, owner, repo, issueNumber, { notAfter = null } = {}) {
124
+ async function collectReviewUnit(tracker, issueNumber, { notAfter = null } = {}) {
112
125
  const stories = new Map();
113
126
  const tasks = new Map();
114
127
  const bugs = new Map();
@@ -118,7 +131,8 @@ async function collectReviewUnit(token, owner, repo, issueNumber, { notAfter = n
118
131
  const empty = (extra = {}) => ({ feature: null, stories, tasks, bugs, skipped, deferred: null, ...extra });
119
132
 
120
133
  let issue;
121
- try { issue = await getIssue(token, owner, repo, issueNumber); } catch { return empty(); }
134
+ try { issue = comoItem(await tracker.getWorkItem({ ref: { key: String(issueNumber) } })); } catch { return empty(); }
135
+ if (!issue) return empty();
122
136
  const type = detectIssueType(issue);
123
137
  const kind = classifyReviewTarget(type);
124
138
  if (kind === 'ignore') return empty();
@@ -127,7 +141,7 @@ async function collectReviewUnit(token, owner, repo, issueNumber, { notAfter = n
127
141
  return empty({ bugs });
128
142
  }
129
143
 
130
- const featureIssue = await resolveFeatureIssue(token, owner, repo, issueNumber);
144
+ const featureIssue = await resolveFeatureIssue(tracker, issueNumber);
131
145
  const feature = featureIssue
132
146
  ? { number: featureIssue.number, nodeId: featureIssue.node_id, title: featureIssue.title }
133
147
  : null;
@@ -142,8 +156,8 @@ async function collectReviewUnit(token, owner, repo, issueNumber, { notAfter = n
142
156
  const isManual = (sub) => isManualStageType(detectIssueType({ title: sub.title, labels: sub.labels }));
143
157
 
144
158
  // Desce um nível aplicando o recorte temporal, registrando o que ficou de fora.
145
- const children = async (nodeId) => {
146
- const all = await listSubIssues(token, nodeId).catch(() => []);
159
+ const children = async (ref) => {
160
+ const all = (await tracker.listChildren({ ref }).catch(() => [])).map(comoItem);
147
161
  const { kept, skipped: out } = partitionByCreation(all, notAfter);
148
162
  skipped.push(...out);
149
163
  return kept;
@@ -151,48 +165,49 @@ async function collectReviewUnit(token, owner, repo, issueNumber, { notAfter = n
151
165
 
152
166
  if (type === 'Feature') {
153
167
  // Referência direta à Feature: toda a subárvore (Stories + Tasks).
154
- for (const st of await children(issue.node_id)) {
168
+ for (const st of await children(issue.ref)) {
155
169
  if (isManual(st)) continue;
156
170
  addStory(st.number, st.nodeId, st.title);
157
- for (const t of await children(st.nodeId)) { if (isManual(t)) continue; addTask(t.number, t.nodeId, t.title); }
171
+ for (const t of await children(st.ref)) { if (isManual(t)) continue; addTask(t.number, t.nodeId, t.title); }
158
172
  }
159
173
  } else if (type === 'Story') {
160
174
  addStory(issue.number, issue.node_id, issue.title);
161
- for (const t of await children(issue.node_id)) { if (isManual(t)) continue; addTask(t.number, t.nodeId, t.title); }
175
+ for (const t of await children(issue.ref)) { if (isManual(t)) continue; addTask(t.number, t.nodeId, t.title); }
162
176
  } else { // Task → inclui a Story pai e as Tasks irmãs.
163
177
  addTask(issue.number, issue.node_id, issue.title);
164
- const parent = await getIssueParent(token, issue.node_id).catch(() => null);
178
+ const parent = await tracker.getParent({ ref: issue.ref }).catch(() => null);
165
179
  if (parent && detectIssueType({ title: parent.title }) === 'Story') {
166
- addStory(parent.number, parent.nodeId, parent.title);
167
- for (const t of await children(parent.nodeId)) { if (isManual(t)) continue; addTask(t.number, t.nodeId, t.title); }
180
+ addStory(Number(parent.ref.key), parent.ref.id, parent.title);
181
+ for (const t of await children(parent.ref)) { if (isManual(t)) continue; addTask(t.number, t.nodeId, t.title); }
168
182
  }
169
183
  }
170
184
  return { feature, stories, tasks, bugs, skipped, deferred: null };
171
185
  }
172
186
 
173
187
  // A Feature só avança quando TODAS as suas Stories já estiverem em Code Review
174
- // (ou etapa posterior). readToken lê as issues; projToken opera no Project.
188
+ // (ou etapa posterior). Uma porta só: `listChildren` usa o token simples e
189
+ // `getStage` o de board — a assimetria vive dentro da instância, não aqui.
175
190
  //
176
191
  // Devolve também as Stories: quem chama usa a mesma lista para tirar os PRs da
177
- // Feature do rascunho, sem repetir o listSubIssues.
178
- async function allStoriesReadyForReview(readToken, projToken, project, etapaField, featureNodeId) {
179
- const subs = await listSubIssues(readToken, featureNodeId).catch(() => []);
192
+ // Feature do rascunho, sem repetir a leitura dos filhos.
193
+ async function allStoriesReadyForReview(tracker, featureRef) {
194
+ const subs = (await tracker.listChildren({ ref: featureRef }).catch(() => [])).map(comoItem);
180
195
  const stories = subs
181
196
  .filter(s => detectIssueType({ title: s.title }) === 'Story')
182
- .map(s => ({ number: s.number, nodeId: s.nodeId }));
183
- if (!etapaField?.id) return { ready: true, stories }; // sem campo Etapa não há como checar — assume ok
197
+ .map(s => ({ number: s.number, nodeId: s.nodeId, ref: s.ref }));
184
198
  if (stories.length === 0) return { ready: true, stories };
185
199
  const tgtIdx = STAGE_ORDER.indexOf(CODE_REVIEW_STAGE);
186
200
  for (const st of stories) {
187
- const itemId = await addProjectItem(projToken, project.id, st.nodeId);
188
- const current = await getItemSingleSelectValue(projToken, itemId, etapaField.id).catch(() => null);
201
+ // Etapa ilegível conta como pendente, igual a antes: sem saber onde a Story
202
+ // está, avançar a Feature seria adivinhar que o trabalho acabou.
203
+ const current = await tracker.getStage({ ref: st.ref }).catch(() => null);
189
204
  const idx = current ? STAGE_ORDER.indexOf(current) : -1;
190
205
  if (idx === -1 || idx < tgtIdx) return { ready: false, stories }; // há Story pendente
191
206
  }
192
207
  return { ready: true, stories };
193
208
  }
194
209
 
195
- export async function codeReview({ prNumber, prRepo: prRepoOpt, resolveOnly = false }) {
210
+ export async function codeReview({ prNumber, prRepo: prRepoOpt, resolveOnly = false, deps = {} }) {
196
211
  const token = await resolveToken();
197
212
  const projectToken = process.env.PROJECT_TOKEN || token;
198
213
  // Dois repositórios, que só coincidem no mono-repo: o hub (dono das issues e
@@ -212,7 +227,16 @@ export async function codeReview({ prNumber, prRepo: prRepoOpt, resolveOnly = fa
212
227
  const prRepo = resolvePrRepo(prRepoOpt, ctx);
213
228
  const prNum = parseInt(prNumber, 10);
214
229
 
215
- const pr = await getPR(token, prRepo.owner, prRepo.repo, prNum);
230
+ // Porta do repositório DO PR — `--pr-repo` pode apontar para um repo de
231
+ // código, e o número de PR colide entre repositórios.
232
+ const prScm = deps.scm ?? createGithubScm({
233
+ link: githubLink({
234
+ owner: prRepo.owner, repo: prRepo.repo, role: sameRepo(prRepo, hub) ? 'hub' : 'code',
235
+ }),
236
+ token,
237
+ });
238
+ const pr = await prScm.getPullRequest({ number: String(prNum) });
239
+ const prCriadoEm = pr?.createdAt ?? null;
216
240
  const linkMode = resolveLinkMode(cfg);
217
241
 
218
242
  // Duas fontes de vínculo, nesta ordem: o que o GitHub reconhece nativamente
@@ -221,10 +245,10 @@ export async function codeReview({ prNumber, prRepo: prRepoOpt, resolveOnly = fa
221
245
  // O vínculo nativo é sempre do repositório do PR — cross-repo o GitHub não
222
246
  // popula (RFC-005 §4) — então só conta quando o PR está no próprio hub.
223
247
  const linked = sameRepo(prRepo, hub)
224
- ? await getPRClosingIssues(token, prRepo.owner, prRepo.repo, prNum).catch(err => {
248
+ ? (await prScm.getPullRequestClosingWorkItems({ number: String(prNum) }).catch(err => {
225
249
  console.warn(`Não foi possível ler os vínculos nativos do PR: ${err.message}`);
226
250
  return [];
227
- })
251
+ })).map(Number)
228
252
  : [];
229
253
  const refs = extractIssueRefs(pr.body || '', { prRepo, linkMode });
230
254
  const issueNums = [...new Set([...linked, ...hubIssueNumbers(refs, hub)])];
@@ -259,20 +283,15 @@ export async function codeReview({ prNumber, prRepo: prRepoOpt, resolveOnly = fa
259
283
  return;
260
284
  }
261
285
 
262
- // Carrega projeto do .spec-wave.json
263
- const { project, error: projectError } = loadProjectConfig();
286
+ // Uma instância para todo o comando: o memo de item do board é dela, e é o
287
+ // que mantém a contagem de chamadas igual à de antes.
288
+ // PROJECT_TOKEN é a credencial do board; `token` segue fazendo as issues.
289
+ const { tracker, error: projectError } = openTracker({ token, projectToken, owner, repo, tracker: deps.tracker });
264
290
  if (projectError) {
265
291
  console.warn(`${projectError} — board não atualizado.`);
266
292
  return;
267
293
  }
268
294
 
269
- // Resolve campos uma vez, reutiliza em todas as Features.
270
- const etapaField = await resolveField(projectToken, project, 'Etapa').catch(() => null);
271
- const statusField = await resolveField(projectToken, project, 'Status').catch(() => null);
272
- // Repara o Work Item Type vazio de passagem (o apply nunca o escreveu).
273
- // Só preenche o vazio e nunca derruba o movimento — ver ensureWorkItemType.
274
- const typeField = await resolveField(projectToken, project, 'Work Item Type').catch(() => null);
275
-
276
295
  const seen = new Set();
277
296
  const updated = [];
278
297
  const featuresChecked = new Set();
@@ -284,7 +303,7 @@ export async function codeReview({ prNumber, prRepo: prRepoOpt, resolveOnly = fa
284
303
  // Stories → 👀 Code Review; Feature → Code Review só quando TODAS as suas
285
304
  // Stories já estiverem em Code Review.
286
305
  for (const num of issueNums) {
287
- const unit = await collectReviewUnit(token, owner, repo, num, { notAfter: pr.created_at });
306
+ const unit = await collectReviewUnit(tracker, num, { notAfter: prCriadoEm });
288
307
  const { feature, stories, tasks, bugs } = unit;
289
308
  if (unit.deferred) {
290
309
  deferred.add(unit.deferred);
@@ -303,9 +322,11 @@ export async function codeReview({ prNumber, prRepo: prRepoOpt, resolveOnly = fa
303
322
  if (seen.has(n)) continue;
304
323
  seen.add(n);
305
324
  try {
306
- const moved = await advanceToStage(
307
- projectToken, project, etapaField, statusField, info.nodeId, DONE_STAGE, DONE_STATUS,
308
- { typeField, itemType: 'Task' });
325
+ const moved = await advanceToStage({
326
+ tracker,
327
+ ref: { key: String(n), id: info.nodeId },
328
+ stage: DONE_STAGE, progress: DONE_STATUS, itemType: 'Task',
329
+ });
309
330
  if (moved) {
310
331
  updated.push(`#${n} ${info.title} → ${DONE_STAGE}`);
311
332
  console.log(`#${n} → "${DONE_STAGE}" / Status "${DONE_STATUS}".`);
@@ -322,9 +343,11 @@ export async function codeReview({ prNumber, prRepo: prRepoOpt, resolveOnly = fa
322
343
  if (seen.has(n)) continue;
323
344
  seen.add(n);
324
345
  try {
325
- const moved = await advanceToStage(
326
- projectToken, project, etapaField, statusField, info.nodeId, CODE_REVIEW_STAGE, TODO_STATUS,
327
- { typeField, itemType: 'Story' });
346
+ const moved = await advanceToStage({
347
+ tracker,
348
+ ref: { key: String(n), id: info.nodeId },
349
+ stage: CODE_REVIEW_STAGE, progress: TODO_STATUS, itemType: 'Story',
350
+ });
328
351
  if (moved) {
329
352
  updated.push(`#${n} ${info.title} → ${CODE_REVIEW_STAGE}`);
330
353
  console.log(`#${n} → "${CODE_REVIEW_STAGE}" / Status "${TODO_STATUS}".`);
@@ -341,9 +364,11 @@ export async function codeReview({ prNumber, prRepo: prRepoOpt, resolveOnly = fa
341
364
  if (seen.has(n)) continue;
342
365
  seen.add(n);
343
366
  try {
344
- const moved = await advanceToStage(
345
- projectToken, project, etapaField, statusField, info.nodeId, CODE_REVIEW_STAGE, TODO_STATUS,
346
- { typeField, itemType: 'Bug' });
367
+ const moved = await advanceToStage({
368
+ tracker,
369
+ ref: { key: String(n), id: info.nodeId },
370
+ stage: CODE_REVIEW_STAGE, progress: TODO_STATUS, itemType: 'Bug',
371
+ });
347
372
  if (moved) {
348
373
  updated.push(`#${n} ${info.title} → ${CODE_REVIEW_STAGE}`);
349
374
  console.log(`Bug #${n} → "${CODE_REVIEW_STAGE}" / Status "${TODO_STATUS}".`);
@@ -360,14 +385,16 @@ export async function codeReview({ prNumber, prRepo: prRepoOpt, resolveOnly = fa
360
385
  featuresChecked.add(feature.number);
361
386
  try {
362
387
  const { ready, stories: featureStories } = await allStoriesReadyForReview(
363
- token, projectToken, project, etapaField, feature.nodeId);
388
+ tracker, { key: String(feature.number), id: feature.nodeId });
364
389
  if (!ready) {
365
390
  console.log(`Feature #${feature.number} mantida em desenvolvimento — ainda há Stories pendentes (fora de "${CODE_REVIEW_STAGE}").`);
366
391
  } else if (!seen.has(feature.number)) {
367
392
  seen.add(feature.number);
368
- const moved = await advanceToStage(
369
- projectToken, project, etapaField, statusField, feature.nodeId, CODE_REVIEW_STAGE, TODO_STATUS,
370
- { typeField, itemType: 'Feature' });
393
+ const moved = await advanceToStage({
394
+ tracker,
395
+ ref: { key: String(feature.number), id: feature.nodeId },
396
+ stage: CODE_REVIEW_STAGE, progress: TODO_STATUS, itemType: 'Feature',
397
+ });
371
398
  if (moved) {
372
399
  updated.push(`#${feature.number} ${feature.title} (Feature) → ${CODE_REVIEW_STAGE}`);
373
400
  console.log(`Feature #${feature.number} → "${CODE_REVIEW_STAGE}" (todas as Stories concluídas).`);
@@ -381,6 +408,7 @@ export async function codeReview({ prNumber, prRepo: prRepoOpt, resolveOnly = fa
381
408
  // impossível de mergear no GitHub. Best-effort, como o resto.
382
409
  const marcados = await markFeaturePrsReady({
383
410
  token, owner, repo, feature, stories: featureStories, linkMode,
411
+ scmDe: deps.scmDe,
384
412
  codeRepos: codeReposForItems(cfg, { labels: feature.labels || [], children: featureStories }).repos,
385
413
  // `updated` vira a lista "Board atualizado" no comentário do PR;
386
414
  // desrascunhar não é movimento de board e ganha parágrafo próprio.
@@ -429,7 +457,10 @@ export async function codeReview({ prNumber, prRepo: prRepoOpt, resolveOnly = fa
429
457
  `\`npx ${cliRef()} code-review --pr-number ${prNumber}\`.`
430
458
  );
431
459
  }
432
- await commentOnIssue(token, prRepo.owner, prRepo.repo, prNum, partes.join('\n\n')).catch(() => {});
460
+ // O comentário vai no PR, no repositório do PR.
461
+ await (deps.prTracker ?? createGithubTracker({ token, owner: prRepo.owner, repo: prRepo.repo }))
462
+ .addComment({ ref: { key: String(prNum) }, body: partes.join('\n\n') })
463
+ .catch(() => {});
433
464
  }
434
465
 
435
466
  console.log(`code-review: ${updated.length} item(ns) atualizado(s) no board.`);