@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
@@ -4,7 +4,8 @@ import { readFileSync, existsSync, unlinkSync } from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { resolveToken } from '../api/auth.mjs';
6
6
  import { CONFIG_FILE, ALL_LABELS, WORKFLOW_FILES, ISSUE_TEMPLATE_FILES } from '../config.mjs';
7
- import { deleteLabel, deleteFile } from '../api/github-rest.mjs';
7
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
8
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
8
9
 
9
10
  const REPO_FILES = [
10
11
  ...WORKFLOW_FILES.map(f => `.github/workflows/${f}`),
@@ -80,6 +81,9 @@ export async function uninstall(options = {}) {
80
81
  return;
81
82
  }
82
83
 
84
+ const tracker = createGithubTracker({ token, owner, repo });
85
+ const scm = createGithubScm({ link: githubLink({ owner, repo }), token });
86
+
83
87
  // --- Labels ---
84
88
  if (doLabels) {
85
89
  const spinner = p.spinner();
@@ -88,7 +92,7 @@ export async function uninstall(options = {}) {
88
92
  try {
89
93
  for (let i = 0; i < ALL_LABELS.length; i++) {
90
94
  spinner.message(`Removendo label ${i + 1}/${ALL_LABELS.length}: ${ALL_LABELS[i].name}`);
91
- if (await deleteLabel(token, owner, repo, ALL_LABELS[i].name)) removed++;
95
+ if (await tracker.deleteTag({ name: ALL_LABELS[i].name })) removed++;
92
96
  }
93
97
  spinner.stop(`Labels removidas (${removed}/${ALL_LABELS.length}).`);
94
98
  } catch (err) {
@@ -106,7 +110,7 @@ export async function uninstall(options = {}) {
106
110
  for (let i = 0; i < REPO_FILES.length; i++) {
107
111
  const filePath = REPO_FILES[i];
108
112
  spinner.message(`Removendo ${i + 1}/${REPO_FILES.length}: ${filePath}`);
109
- if (await deleteFile(token, owner, repo, filePath, `chore: remove ${filePath} [spec-wave]`)) removed++;
113
+ if (await scm.deleteFile({ path: filePath, message: `chore: remove ${filePath} [spec-wave]` })) removed++;
110
114
  }
111
115
  spinner.stop(`Arquivos removidos (${removed}/${REPO_FILES.length}).`);
112
116
  } catch (err) {
@@ -5,12 +5,8 @@ import { homedir } from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { resolveToken } from '../api/auth.mjs';
7
7
  import { CONFIG_FILE, WORKFLOW_FILES, CODE_WORKFLOW_FILES, ISSUE_TEMPLATE_FILES, ALL_LABELS, allLabelsFor } from '../config.mjs';
8
- import { getProjectSnapshot } from '../api/github-graphql.mjs';
9
- import {
10
- getFileContent, upsertFile, listLabels, createLabel, updateLabel, deleteLabel,
11
- getRepoDefaultBranch, compareBranches, commitFilesToBranch, ensurePullRequest,
12
- countOpenIssuesWithLabel,
13
- } from '../api/github-rest.mjs';
8
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
9
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
14
10
  import {
15
11
  resolveBranchName, composePrTitle, composePrBody, buildCommitMessage,
16
12
  decideConfigInPr, decideSkillInPr, composeConfigCleanupHint, explainGitWriteError,
@@ -27,6 +23,7 @@ import { planPluginSkillFiles } from '../lib/plugin-skills.mjs';
27
23
  import { findConfigPath } from '../lib/project-root.mjs';
28
24
  import { configuredRole } from '../lib/repo-role.mjs';
29
25
  import { currentGitBranch } from '../lib/repo-links.mjs';
26
+ import { cliRef } from '../lib/cli-ref.mjs';
30
27
 
31
28
  // Arquivos do repo gerenciados pela CLI (comparados com o template empacotado).
32
29
  const REPO_FILES = [
@@ -201,8 +198,16 @@ async function buildConfigContent(token, config) {
201
198
  if (configuredRole(config) === 'code') {
202
199
  return { content: `${JSON.stringify({ ...config, version: CLI_VERSION }, null, 2)}\n`, error: null };
203
200
  }
204
- const snapshot = await getProjectSnapshot(token, config.project.id);
205
- if (!snapshot) return { content: null, error: 'Project não encontrado' };
201
+ // `provision: false` é leitura do schema vivo — a mesma operação que o
202
+ // `refresh --config` usa para regravar os ids do board.
203
+ const { config: vivo } = await createGithubTracker({
204
+ token, owner: config.owner, repo: config.repo, project: config.project,
205
+ }).setup({ provision: false });
206
+ if (!vivo) return { content: null, error: 'Project não encontrado' };
207
+ const snapshot = {
208
+ id: vivo.projectId, number: vivo.projectNumber,
209
+ url: vivo.projectUrl, title: vivo.projectTitle, fields: vivo.fields,
210
+ };
206
211
  const { etapaFieldId: _e, stageOptions: _s, ...projectRest } = config.project;
207
212
  const updated = {
208
213
  ...config,
@@ -242,11 +247,15 @@ async function buildConfigContent(token, config) {
242
247
  * só o que REALMENTE passou — é o que o corpo do PR vai afirmar a quem
243
248
  * revisa, e ele não pode prometer o que falhou.
244
249
  */
250
+ /** Porta de SCM do repositório-alvo. Memoizada por token: `tk` é lazy. */
251
+ const scmDe = (tk, owner, repo) => createGithubScm({ link: githubLink({ owner, repo }), token: tk });
252
+
245
253
  async function applyLabels(token, owner, repo, labelDiff, forceLabels = false) {
254
+ const tracker = createGithubTracker({ token, owner, repo });
246
255
  const done = { created: [], updated: [], removed: [] };
247
256
  for (const label of labelDiff.missing) {
248
257
  try {
249
- await createLabel(token, owner, repo, label);
258
+ await tracker.ensureTags({ tags: [label] });
250
259
  done.created.push(label.name);
251
260
  p.log.success(`Label criada: ${label.name}`);
252
261
  } catch (err) {
@@ -255,7 +264,7 @@ async function applyLabels(token, owner, repo, labelDiff, forceLabels = false) {
255
264
  }
256
265
  for (const label of labelDiff.changed) {
257
266
  try {
258
- await updateLabel(token, owner, repo, label);
267
+ await tracker.ensureTags({ tags: [label], overwrite: true });
259
268
  done.updated.push(label.name);
260
269
  p.log.success(`Label atualizada: ${label.name}`);
261
270
  } catch (err) {
@@ -266,13 +275,13 @@ async function applyLabels(token, owner, repo, labelDiff, forceLabels = false) {
266
275
  try {
267
276
  const inUse = forceLabels
268
277
  ? 0
269
- : await countOpenIssuesWithLabel(token, owner, repo, label.name).catch(() => null);
278
+ : await tracker.countOpenWithTag({ tag: label.name }).catch(() => null);
270
279
  const decision = shouldDeleteOrphanLabel({ inUse, forceLabels });
271
280
  if (!decision.ok) {
272
281
  p.log.warn(`Label ${label.name}: ${decision.motivo}. Use --force-labels para remover mesmo assim.`);
273
282
  continue;
274
283
  }
275
- await deleteLabel(token, owner, repo, label.name);
284
+ await tracker.deleteTag({ name: label.name });
276
285
  done.removed.push(label.name);
277
286
  p.log.success(`Label descontinuada removida: ${label.name}`);
278
287
  } catch (err) {
@@ -373,12 +382,12 @@ export async function update(options = {}) {
373
382
  } else {
374
383
  try {
375
384
  for (const f of repoFilesFor(role)) {
376
- const remote = await getFileContent(tk, owner, repo, f.repoPath);
385
+ const remote = await scmDe(tk, owner, repo).readFile({ path: f.repoPath });
377
386
  const local = readTemplate(...f.template);
378
387
  if (remote === null) repoFiles.push({ ...f, reason: 'ausente', local });
379
388
  else if (remote !== local) repoFiles.push({ ...f, reason: 'desatualizado', local });
380
389
  }
381
- labelDiff = diffLabels(await listLabels(tk, owner, repo), config?.ai, config?.devAgent);
390
+ labelDiff = diffLabels(await createGithubTracker({ token: tk, owner, repo }).listTags(), config?.ai, config?.devAgent);
382
391
  repoChecked = true;
383
392
  s.stop('Repositório comparado.');
384
393
  } catch (err) {
@@ -398,7 +407,7 @@ export async function update(options = {}) {
398
407
  if (prMode) {
399
408
  const tk = await getToken();
400
409
  try {
401
- base = await getRepoDefaultBranch(tk, owner, repo);
410
+ base = await scmDe(tk, owner, repo).defaultBranch();
402
411
  if (branch === base) {
403
412
  p.log.error(
404
413
  `--branch "${branch}" é a própria branch default do repositório; ` +
@@ -407,8 +416,8 @@ export async function update(options = {}) {
407
416
  p.cancel('Update cancelado.');
408
417
  return;
409
418
  }
410
- remoteConfigRaw = await getFileContent(tk, owner, repo, CONFIG_FILE, base);
411
- const status = await compareBranches(tk, owner, repo, base, branch);
419
+ remoteConfigRaw = await scmDe(tk, owner, repo).readFile({ path: CONFIG_FILE, ref: base });
420
+ const status = await scmDe(tk, owner, repo).compare({ base: base, head: branch });
412
421
  branchExists = status !== null;
413
422
  if (status === 'behind' || status === 'identical') {
414
423
  // Não fazemos force-push: só avisamos. Empilhar um commit numa branch já
@@ -459,7 +468,7 @@ export async function update(options = {}) {
459
468
  // Em paralelo: o destino do Codex são 20+ arquivos, e um GET por vez
460
469
  // transformaria a checagem na parte mais lenta do comando.
461
470
  const remotes = await Promise.all(
462
- targets.map(t => getFileContent(tk, owner, repo, t.relPath, base))
471
+ targets.map(t => scmDe(tk, owner, repo).readFile({ path: t.relPath, ref: base }))
463
472
  );
464
473
  targets.forEach((t, i) => {
465
474
  const remote = remotes[i];
@@ -645,7 +654,7 @@ export async function update(options = {}) {
645
654
  let configContent = null;
646
655
  if (configStale) {
647
656
  if (!configStale.canApply) {
648
- p.log.warn(`${CONFIG_FILE}: sem project.id — pulei. Rode \`npx @spec-wave/cli@latest init\` (sem --skip-project).`);
657
+ p.log.warn(`${CONFIG_FILE}: sem project.id — pulei. Rode \`npx ${cliRef()} init\` (sem --skip-project).`);
649
658
  } else {
650
659
  const tk = role === 'code' ? null : await getToken();
651
660
  if (role !== 'code' && !tk) {
@@ -723,7 +732,7 @@ export async function update(options = {}) {
723
732
  s.start(`Enviando ${treeFiles.length} arquivo(s) em um único commit para "${branch}"...`);
724
733
  let commitOk = false;
725
734
  try {
726
- const res = await commitFilesToBranch(tk, owner, repo, {
735
+ const res = await scmDe(tk, owner, repo).writeFiles({
727
736
  branch,
728
737
  base,
729
738
  files: treeFiles.map(f => ({ path: f.path, content: f.content })),
@@ -743,7 +752,7 @@ export async function update(options = {}) {
743
752
  // write" pode não ter "Pull requests: write" — permissão NOVA neste modo.
744
753
  if (commitOk) {
745
754
  try {
746
- const pr = await ensurePullRequest(tk, owner, repo, {
755
+ const { pr } = await scmDe(tk, owner, repo).ensurePullRequest({
747
756
  branch,
748
757
  base,
749
758
  title: composePrTitle({ version: CLI_VERSION }),
@@ -782,7 +791,7 @@ export async function update(options = {}) {
782
791
  const tk = await getToken();
783
792
  for (const f of repoFiles) {
784
793
  try {
785
- await upsertFile(tk, owner, repo, f.repoPath, f.local, `chore: update ${path.basename(f.repoPath)} [spec-wave]`);
794
+ await scmDe(tk, owner, repo).installAutomation({ files: [{ path: f.repoPath, content: f.local, message: `chore: update ${path.basename(f.repoPath)} [spec-wave]` }] });
786
795
  p.log.success(`Arquivo atualizado no repo: ${f.repoPath}`);
787
796
  } catch (err) {
788
797
  p.log.error(`Falha ao atualizar ${f.repoPath}: ${err.message}`);
@@ -1,5 +1,5 @@
1
1
  import { resolveToken } from '../api/auth.mjs';
2
- import { getIssue, removeLabel, addLabel, commentOnIssue } from '../api/github-rest.mjs';
2
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
3
3
  import { slugify } from '../lib/slugify.mjs';
4
4
  import {
5
5
  CONFIG_FILE, LABEL_CRITIQUE_FAILED, LABEL_NEEDS_HUMAN, LABEL_BUG, LABEL_BUG_APPROVED,
@@ -15,7 +15,7 @@ import { docBlobUrl } from '../lib/repo-links.mjs';
15
15
  import { loadArtifact } from '../lib/doc-source.mjs';
16
16
  import { awaitingMergeBlock } from '../lib/artifact-pr.mjs';
17
17
  import { isAwaitingMerge } from '../lib/doc-source.mjs';
18
- import { getRepoDefaultBranch } from '../api/github-rest.mjs';
18
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
19
19
  import { dependencySection } from '../lib/spec-audit.mjs';
20
20
 
21
21
  /**
@@ -33,7 +33,7 @@ import { dependencySection } from '../lib/spec-audit.mjs';
33
33
  * Aborta ANTES do removeLabel: a label fica, e reaplicá-la depois do merge
34
34
  * simplesmente funciona.
35
35
  */
36
- async function abortIfPendingPr({ token, owner, repo, n, docs }) {
36
+ async function abortIfPendingPr({ tracker, n, docs }) {
37
37
  const pendentes = docs.filter(d => isAwaitingMerge(d.state));
38
38
  if (pendentes.length === 0) return null;
39
39
 
@@ -45,12 +45,14 @@ async function abortIfPendingPr({ token, owner, repo, n, docs }) {
45
45
  }));
46
46
  const linhas = blocos.map(b => `- ${b.message}\n ${b.unblock}`);
47
47
 
48
- await commentOnIssue(token, owner, repo, n,
49
- '⏸️ **Validação adiada — documento ainda não está na branch base.**\n\n' +
50
- `${linhas.join('\n')}\n\n` +
51
- 'Resolvido isso, reaplique `spec-wave:ready` — a label foi **mantida** na issue, ' +
52
- 'e nada foi reprovado.'
53
- ).catch(() => {});
48
+ await tracker.addComment({
49
+ ref: { key: String(n) },
50
+ body:
51
+ '⏸️ **Validação adiada — documento ainda não está na branch base.**\n\n' +
52
+ `${linhas.join('\n')}\n\n` +
53
+ 'Resolvido isso, reaplique `spec-wave:ready` — a label foi **mantida** na issue, ' +
54
+ 'e nada foi reprovado.',
55
+ }).catch(() => {});
54
56
 
55
57
  console.error(`Validação adiada: ${pendentes.map(d => d.pathRel).join(', ')} fora da base.`);
56
58
  return { ok: false, errors: linhas, awaitingMerge: true };
@@ -64,7 +66,7 @@ async function abortIfPendingPr({ token, owner, repo, n, docs }) {
64
66
  * um único arquivo, e a falha NÃO devolve o item para a etapa de spec (Bug não
65
67
  * tem etapa de spec). Reaplicar `spec-wave:bug` é o caminho de retomada.
66
68
  */
67
- async function validateBug({ token, owner, repo, issue, issueNumber, root, base }) {
69
+ async function validateBug({ tracker, token, owner, repo, issue, issueNumber, root, base }) {
68
70
  const n = parseInt(issueNumber, 10);
69
71
  const { fileRel } = bugDocPaths(issue.title, root);
70
72
  const errors = [];
@@ -73,7 +75,7 @@ async function validateBug({ token, owner, repo, issue, issueNumber, root, base
73
75
  token, owner, repo, root, pathRel: fileRel, doc: 'bug', issueNumber: n, base,
74
76
  });
75
77
  const adiado = await abortIfPendingPr({
76
- token, owner, repo, n, docs: [{ ...bug, pathRel: fileRel }],
78
+ tracker, n, docs: [{ ...bug, pathRel: fileRel }],
77
79
  });
78
80
  if (adiado) return adiado;
79
81
 
@@ -107,27 +109,29 @@ async function validateBug({ token, owner, repo, issue, issueNumber, root, base
107
109
  }
108
110
  }
109
111
 
110
- await removeLabel(token, owner, repo, n, LABEL_READY);
112
+ await tracker.removeTag({ ref: { key: String(n) }, tag: LABEL_READY });
111
113
 
112
114
  if (errors.length > 0) {
113
- await commentOnIssue(
114
- token, owner, repo, n,
115
- '⚠️ **Validação falhou — o bug.md não está pronto.**\n\n' +
116
- errors.join('\n') +
117
- `\n\nCorrija os problemas e adicione novamente a label \`spec-wave:ready\`.`
118
- );
115
+ await tracker.addComment({
116
+ ref: { key: String(n) },
117
+ body:
118
+ '⚠️ **Validação falhou — o bug.md não está pronto.**\n\n' +
119
+ errors.join('\n') +
120
+ `\n\nCorrija os problemas e adicione novamente a label \`spec-wave:ready\`.`,
121
+ });
119
122
  console.error('Validação falhou:', errors.join(', '));
120
123
  return { ok: false, errors };
121
124
  }
122
125
 
123
- await addLabel(token, owner, repo, n, LABEL_BUG_APPROVED);
124
- await commentOnIssue(
125
- token, owner, repo, n,
126
- '✅ **bug.md validado.**\n\n' +
127
- `📄 [\`${fileRel}\`](${docBlobUrl({ owner, repo, pathRel: fileRel, mode: executionMode(), root })})\n\n` +
128
- 'As seis seções obrigatórias estão presentes — reprodução, causa raiz e teste de ' +
129
- 'regressão inclusive. O bug pode ser aceito na triagem.'
130
- );
126
+ await tracker.addTag({ ref: { key: String(n) }, tag: LABEL_BUG_APPROVED });
127
+ await tracker.addComment({
128
+ ref: { key: String(n) },
129
+ body:
130
+ '✅ **bug.md validado.**\n\n' +
131
+ `📄 [\`${fileRel}\`](${docBlobUrl({ owner, repo, pathRel: fileRel, mode: executionMode(), root })})\n\n` +
132
+ 'As seis seções obrigatórias estão presentes — reprodução, causa raiz e teste de ' +
133
+ 'regressão inclusive. O bug pode ser aceito na triagem.',
134
+ });
131
135
  console.log('bug.md validado.');
132
136
  return { ok: true, errors: [] };
133
137
  }
@@ -159,7 +163,7 @@ export function renderMissingSection(doc, { section, found }) {
159
163
  * @param {{issueNumber: string|number}} params
160
164
  * @returns {Promise<{ok: boolean, errors: string[]}>}
161
165
  */
162
- export async function validate({ issueNumber }) {
166
+ export async function validate({ issueNumber, deps = {} }) {
163
167
  const token = await resolveToken();
164
168
  const { owner, repo, config: cfg, root } = resolveHubContext();
165
169
 
@@ -171,16 +175,18 @@ export async function validate({ issueNumber }) {
171
175
  }
172
176
 
173
177
  const n = parseInt(issueNumber, 10);
174
- const issue = await getIssue(token, owner, repo, n);
178
+ const tracker = deps.tracker ?? createGithubTracker({ token, owner, repo });
179
+ const scm = deps.scm ?? createGithubScm({ link: githubLink({ owner, repo }), token });
180
+ const issue = await tracker.getWorkItem({ ref: { key: String(n) } });
175
181
 
176
182
  // Branch base para a leitura em camadas. Best-effort: sem ela o resolvedor cai
177
183
  // no default da API, que é a mesma branch.
178
- const base = await getRepoDefaultBranch(token, owner, repo).catch(() => null);
184
+ const base = await scm.defaultBranch().catch(() => null);
179
185
 
180
186
  // Bug tem artefato próprio (bug.md) e caminho próprio de validação — não passa
181
187
  // pelo par spec.md + plan.md, que é exclusivo de Feature.
182
188
  if (detectIssueType(issue) === 'Bug') {
183
- return await validateBug({ token, owner, repo, issue, issueNumber, root, base });
189
+ return await validateBug({ tracker, token, owner, repo, issue, issueNumber, root, base });
184
190
  }
185
191
 
186
192
  const slug = slugify(issue.title);
@@ -220,7 +226,7 @@ export async function validate({ issueNumber }) {
220
226
  const spec = await ler('spec', specRel);
221
227
 
222
228
  const adiado = await abortIfPendingPr({
223
- token, owner, repo, n,
229
+ tracker, n,
224
230
  docs: [{ ...plan, pathRel: planRel }, { ...spec, pathRel: specRel }],
225
231
  });
226
232
  if (adiado) return adiado;
@@ -266,18 +272,19 @@ export async function validate({ issueNumber }) {
266
272
  }
267
273
 
268
274
  // Remove trigger label
269
- await removeLabel(token, owner, repo, parseInt(issueNumber, 10), LABEL_READY);
275
+ await tracker.removeTag({ ref: { key: String(parseInt(issueNumber, 10)) }, tag: LABEL_READY });
270
276
 
271
277
  if (errors.length > 0) {
272
- await commentOnIssue(
273
- token, owner, repo, parseInt(issueNumber, 10),
274
- `⚠️ **Validação falhou — Feature não está pronta.**\n\n` +
275
- errors.join('\n') +
276
- `\n\nCorrija os problemas e adicione novamente a label \`spec-wave:ready\`.` +
277
- `\n\nSe os documentos precisam mesmo ser REGERADOS (e não só corrigidos), aplique ` +
278
- `você a label \`spec-wave:spec\` — ela **sobrescreve** o \`spec.md\`, inclusive o que ` +
279
- 'foi revisado à mão.'
280
- );
278
+ await tracker.addComment({
279
+ ref: { key: String(parseInt(issueNumber, 10)) },
280
+ body:
281
+ `⚠️ **Validação falhou — Feature não está pronta.**\n\n` +
282
+ errors.join('\n') +
283
+ `\n\nCorrija os problemas e adicione novamente a label \`spec-wave:ready\`.` +
284
+ `\n\nSe os documentos precisam mesmo ser REGERADOS (e não só corrigidos), aplique ` +
285
+ `você a label \`spec-wave:spec\` — ela **sobrescreve** o \`spec.md\`, inclusive o que ` +
286
+ 'foi revisado à mão.',
287
+ });
281
288
  // A reprova NÃO aplica mais `spec-wave:spec` sozinha.
282
289
  //
283
290
  // `spec-wave:spec` é label de GATILHO: aplicá-la manda o generate-spec
@@ -295,18 +302,19 @@ export async function validate({ issueNumber }) {
295
302
  }
296
303
 
297
304
  // Validação passou: adiciona label plan-approved.
298
- await addLabel(token, owner, repo, parseInt(issueNumber, 10), LABEL_PLAN_APPROVED);
305
+ await tracker.addTag({ ref: { key: String(parseInt(issueNumber, 10)) }, tag: LABEL_PLAN_APPROVED });
299
306
 
300
- await commentOnIssue(
301
- token, owner, repo, parseInt(issueNumber, 10),
302
- `✅ **Validação concluída com sucesso!**\n\n` +
303
- `- [\`${featureRel}/spec.md\`](${featureRel}/spec.md) ✓\n` +
304
- `- [\`${featureRel}/plan.md\`](${featureRel}/plan.md) ✓\n\n` +
305
- (warnings.length > 0 ? `${warnings.join('\n')}\n\n` : '') +
306
- `A Feature está pronta para a decomposição. O próximo passo gera o **rascunho** ` +
307
- `em \`${featureRel}/decomposition.md\` para revisão (nada é criado ainda):\n` +
308
- `\`\`\`\ngh issue edit ${issueNumber} --add-label "spec-wave:decompose"\n\`\`\``
309
- );
307
+ await tracker.addComment({
308
+ ref: { key: String(parseInt(issueNumber, 10)) },
309
+ body:
310
+ `✅ **Validação concluída com sucesso!**\n\n` +
311
+ `- [\`${featureRel}/spec.md\`](${featureRel}/spec.md) ✓\n` +
312
+ `- [\`${featureRel}/plan.md\`](${featureRel}/plan.md) ✓\n\n` +
313
+ (warnings.length > 0 ? `${warnings.join('\n')}\n\n` : '') +
314
+ `A Feature está pronta para a decomposição. O próximo passo gera o **rascunho** ` +
315
+ `em \`${featureRel}/decomposition.md\` para revisão (nada é criado ainda):\n` +
316
+ `\`\`\`\ngh issue edit ${issueNumber} --add-label "spec-wave:decompose"\n\`\`\``,
317
+ });
310
318
 
311
319
  console.log('Validação OK. Feature pronta para decomposição.');
312
320
  return { ok: true, errors: [] };
@@ -6,7 +6,7 @@
6
6
  import * as p from '@clack/prompts';
7
7
  import chalk from 'chalk';
8
8
  import { resolveToken } from '../api/auth.mjs';
9
- import { getIssue } from '../api/github-rest.mjs';
9
+ import { createGithubTracker } from '../plugins/tracker-github-projects/index.mjs';
10
10
  import { detectIssueType } from '../lib/issue-type.mjs';
11
11
  import { resolveHubContext } from '../lib/project-root.mjs';
12
12
  import { cachedSubIssues } from '../lib/story-graph.mjs';
@@ -18,7 +18,7 @@ import {
18
18
  } from '../lib/workspace.mjs';
19
19
  import { CONFIG_FILE } from '../config.mjs';
20
20
 
21
- export async function workspace({ action, issue: issueArg, json = false, dryRun = false, refresh = false } = {}) {
21
+ export async function workspace({ action, issue: issueArg, json = false, dryRun = false, refresh = false, deps = {} } = {}) {
22
22
  if (action !== 'prepare') {
23
23
  throw new Error(`Ação inválida: "${action}". Use \`spec-wave workspace prepare --issue <n>\`.`);
24
24
  }
@@ -40,18 +40,20 @@ export async function workspace({ action, issue: issueArg, json = false, dryRun
40
40
 
41
41
  const log = json ? { info() {}, warn: (m) => console.error(m) } : { info: p.log.info, warn: p.log.warn };
42
42
  const token = await resolveToken();
43
- const issue = await getIssue(token, owner, repo, issueNumber);
43
+ const issue = await (deps.tracker ?? createGithubTracker({ token, owner, repo }))
44
+ .getWorkItem({ ref: { key: String(issueNumber) } });
44
45
  const type = detectIssueType(issue);
45
46
 
46
47
  let children = [];
47
48
  if (type === 'Feature' || type === 'Epic') {
48
49
  const { subs } = await cachedSubIssues({
49
50
  token, owner, repo, root, refresh, ttlSec: resolveCacheTtl(config),
50
- parent: { number: issue.number, nodeId: issue.node_id },
51
+ tracker: deps.tracker,
52
+ parent: { number: Number(issue.ref.key), nodeId: issue.ref.id },
51
53
  }).catch(() => ({ subs: [] }));
52
54
  children = subs;
53
55
  }
54
- const slugs = slugsForItem({ labels: issue.labels, children });
56
+ const slugs = slugsForItem({ labels: issue.tags, children });
55
57
 
56
58
  // Feature sem repo declarado degrada para o hub (mono-repo), COM aviso: um
57
59
  // Glob que não acha nada é indistinguível de um repo ausente (§7.2).
package/src/config.mjs CHANGED
@@ -586,7 +586,13 @@ export function allLabelsFor(fileAi, devAgent) {
586
586
  * @returns {string[]} nomes, sem entradas vazias
587
587
  */
588
588
  export function labelNames(issueOrLabels) {
589
- const labels = Array.isArray(issueOrLabels) ? issueOrLabels : (issueOrLabels?.labels || []);
589
+ // `tags` é a forma CANÔNICA (WorkItem, RFC-006): a porta de tracker devolve
590
+ // nomes de tag já normalizados, sem o `{name}` da REST do GitHub. `labels`
591
+ // continua aceito porque a issue crua ainda circula em vários pontos, e
592
+ // aceitar as duas aqui poupa uma conversão em cada chamador.
593
+ const labels = Array.isArray(issueOrLabels)
594
+ ? issueOrLabels
595
+ : (issueOrLabels?.tags || issueOrLabels?.labels || []);
590
596
  return labels.map(l => (typeof l === 'string' ? l : l?.name)).filter(Boolean);
591
597
  }
592
598
 
@@ -22,15 +22,11 @@
22
22
  // deixaria no clone um arquivo que o usuário não pediu e que colide no `git pull`
23
23
  // depois do merge — justamente porque o merge pode trazer as edições do revisor.
24
24
 
25
- import {
26
- getRepoDefaultBranch, compareBranches, findOpenPR, commitFilesToBranch,
27
- ensurePullRequest, deleteBranch,
28
- } from '../api/github-rest.mjs';
25
+ import { createGithubScm, githubLink } from '../plugins/scm-github/index.mjs';
29
26
  import { resolveBranchName, explainGitWriteError } from './pr-branch.mjs';
30
27
  import {
31
28
  artifactBranch, composeArtifactPrTitle, composeArtifactPrBody, artifactCommitMessage,
32
29
  } from './artifact-pr.mjs';
33
- import { blobUrl } from './repo-links.mjs';
34
30
 
35
31
  /**
36
32
  * Token usado para abrir o PR.
@@ -80,23 +76,26 @@ export function isStaleArtifactBranch(status, openPr) {
80
76
  * @param {string} params.content conteúdo FINAL do documento
81
77
  * @param {string|null} [params.base] branch de destino (null = default do repo)
82
78
  * @param {string|null} [params.nextLabel] label do passo seguinte, para o corpo do PR
83
- * @param {object} [params.deps] injeção para teste
79
+ * @param {object} [params.scm] porta de SCM; ausente = uma do GitHub, montada
80
+ * aqui com a credencial de PR já resolvida
84
81
  * @returns {Promise<{branch, base, commitSha, unchanged, pr, blobUrl, warning}>}
85
82
  */
86
83
  export async function publishArtifact({
87
84
  token, owner, repo, doc, issueNumber, issueTitle = '', issueUrl = '',
88
- pathRel, content, base = null, nextLabel = null, extraFiles = [], deps = {},
85
+ pathRel, content, base = null, nextLabel = null, extraFiles = [], scm = null,
89
86
  }) {
90
- const api = {
91
- getRepoDefaultBranch, compareBranches, findOpenPR, commitFilesToBranch,
92
- ensurePullRequest, deleteBranch, ...deps,
93
- };
87
+ // `resolvePrToken` entra na CONSTRUÇÃO da porta, não numa chamada: a porta
88
+ // já sabe que só `ensurePullRequest` usa essa credencial. A política de qual
89
+ // token abre PR continua visível aqui, que é onde ela sempre esteve.
90
+ const porta = scm || createGithubScm({
91
+ link: githubLink({ owner, repo }), token, prToken: resolvePrToken(token),
92
+ });
94
93
 
95
94
  const branch = artifactBranch({ issueNumber, doc });
96
95
  const { error: branchError } = resolveBranchName(branch);
97
96
  if (branchError) throw new Error(branchError);
98
97
 
99
- const alvo = base || await api.getRepoDefaultBranch(token, owner, repo);
98
+ const alvo = base || await porta.defaultBranch();
100
99
  if (branch === alvo) {
101
100
  throw new Error(
102
101
  `A branch do artefato ("${branch}") é a própria base — publicar nela seria ` +
@@ -107,20 +106,20 @@ export async function publishArtifact({
107
106
  // Branch obsoleta ANTES de commitar: depois já seria tarde, o commit teria um
108
107
  // pai errado.
109
108
  const [status, prAberto] = await Promise.all([
110
- api.compareBranches(token, owner, repo, alvo, branch),
111
- api.findOpenPR(token, owner, repo, branch).catch(() => null),
109
+ porta.compare({ base: alvo, head: branch }),
110
+ porta.findOpenPullRequest({ branch }).catch(() => null),
112
111
  ]);
113
112
  if (isStaleArtifactBranch(status, prAberto)) {
114
113
  console.warn(
115
114
  `Branch "${branch}" sobrou de um merge anterior e não tem PR aberto — ` +
116
115
  'recriando a partir da base.'
117
116
  );
118
- await api.deleteBranch(token, owner, repo, branch).catch(() => {});
117
+ await porta.deleteBranch({ branch }).catch(() => {});
119
118
  }
120
119
 
121
120
  let commit;
122
121
  try {
123
- commit = await api.commitFilesToBranch(token, owner, repo, {
122
+ commit = await porta.writeFiles({
124
123
  branch,
125
124
  base: alvo,
126
125
  // `extraFiles`: derivados que viajam no MESMO commit do documento (ex.: o
@@ -139,7 +138,7 @@ export async function publishArtifact({
139
138
  let pr = null;
140
139
  let warning = null;
141
140
  try {
142
- pr = await api.ensurePullRequest(resolvePrToken(token), owner, repo, {
141
+ const res = await porta.ensurePullRequest({
143
142
  branch,
144
143
  base: alvo,
145
144
  title: composeArtifactPrTitle({ doc, issueNumber, issueTitle }),
@@ -147,6 +146,9 @@ export async function publishArtifact({
147
146
  doc, issueUrl, issueTitle, pathRel, base: alvo, branch, nextLabel,
148
147
  }),
149
148
  });
149
+ // `created` continua ao lado do PR porque `renderPrLine` distingue "PR
150
+ // aberto" de "PR atualizado" — e quem lê a issue precisa dos dois.
151
+ pr = res?.pr ? { ...res.pr, created: res.created } : null;
150
152
  if (!pr && !commit.unchanged) {
151
153
  warning =
152
154
  `A branch "${branch}" não tem nada novo em relação a "${alvo}" e não há PR ` +
@@ -166,7 +168,7 @@ export async function publishArtifact({
166
168
  commitSha: commit.commitSha,
167
169
  unchanged: commit.unchanged,
168
170
  pr,
169
- blobUrl: blobUrl({ owner, repo, ref: branch, pathRel }),
171
+ blobUrl: porta.fileUrl({ ref: branch, pathRel }),
170
172
  warning,
171
173
  };
172
174
  }