@spec-wave/cli 0.34.2 → 1.0.1

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 (52) hide show
  1. package/package.json +2 -2
  2. package/protocol/qa-result.v1.json +9 -0
  3. package/src/agent/anthropic-agent.mjs +35 -2
  4. package/src/api/github-graphql.mjs +60 -2
  5. package/src/api/github-rest.mjs +23 -0
  6. package/src/cli.mjs +23 -0
  7. package/src/commands/code-review.mjs +71 -60
  8. package/src/commands/decompose.mjs +75 -4
  9. package/src/commands/doctor.mjs +105 -4
  10. package/src/commands/implement.mjs +82 -10
  11. package/src/commands/init.mjs +147 -29
  12. package/src/commands/merge.mjs +56 -4
  13. package/src/commands/move.mjs +4 -7
  14. package/src/commands/order.mjs +2 -2
  15. package/src/commands/qa-run.mjs +140 -19
  16. package/src/commands/qa.mjs +22 -21
  17. package/src/commands/repair-stage.mjs +2 -5
  18. package/src/commands/story.mjs +2 -2
  19. package/src/commands/task.mjs +2 -2
  20. package/src/commands/triage.mjs +2 -5
  21. package/src/commands/update.mjs +31 -8
  22. package/src/commands/validate.mjs +2 -5
  23. package/src/commands/workspace.mjs +112 -0
  24. package/src/config.mjs +19 -0
  25. package/src/lib/artifact-pr.mjs +1 -1
  26. package/src/lib/bug-doc.mjs +6 -1
  27. package/src/lib/claude.mjs +4 -0
  28. package/src/lib/decomposition-doc.mjs +56 -3
  29. package/src/lib/dependency-map.mjs +3 -0
  30. package/src/lib/doc-paths.mjs +6 -1
  31. package/src/lib/flow-run.mjs +14 -3
  32. package/src/lib/pr-link.mjs +109 -0
  33. package/src/lib/pr-ready.mjs +146 -0
  34. package/src/lib/project-root.mjs +51 -0
  35. package/src/lib/qa-exec.mjs +73 -0
  36. package/src/lib/qa-report.mjs +172 -8
  37. package/src/lib/repo-role.mjs +102 -0
  38. package/src/lib/workspace.mjs +151 -0
  39. package/src/plugin/.claude-plugin/plugin.json +1 -1
  40. package/src/plugin/skills/decompose/SKILL.md +1 -0
  41. package/src/plugin/skills/decompose/model-prompt.feature.md +4 -2
  42. package/src/plugin/skills/implement/SKILL.md +2 -2
  43. package/src/plugin/skills/merge/SKILL.md +3 -2
  44. package/src/plugin/skills/qa/SKILL.md +6 -1
  45. package/src/plugin/skills/qa-executor/SKILL.md +43 -1
  46. package/src/plugin/skills/setup/SKILL.md +12 -0
  47. package/src/setup/files.mjs +35 -13
  48. package/src/templates/skill/SKILL.md +27 -5
  49. package/src/templates/skill/core.md +5 -1
  50. package/src/templates/workflows/code/code-review.yml +60 -0
  51. package/src/templates/workflows/code/qa.yml +59 -0
  52. package/src/templates/workflows/pr-events.yml +116 -0
@@ -24,11 +24,12 @@ import {
24
24
  getIssue, getPR, getRepoDefaultBranch, updatePRBase, mergePR, deleteBranch,
25
25
  listPullRequestCommitMessages,
26
26
  } from '../api/github-rest.mjs';
27
- import { listIssuePullRequests } from '../api/github-graphql.mjs';
27
+ import { listIssuePullRequests, listOpenPullRequests } from '../api/github-graphql.mjs';
28
28
  import { missingTrailers } from '../lib/commit-trailers.mjs';
29
29
  import { detectIssueType } from '../lib/issue-type.mjs';
30
30
  import { orderStories } from '../lib/dependencies.mjs';
31
- import { resolveRepoContext, loadConfig } from '../lib/project-root.mjs';
31
+ import { resolveHubContext, loadConfig } from '../lib/project-root.mjs';
32
+ import { extractIssueRefs, hubIssueNumbers, resolveLinkMode } from '../lib/pr-link.mjs';
32
33
  import { loadFeatureStories } from '../lib/story-graph.mjs';
33
34
  import { resolveCacheTtl, invalidateCache } from '../lib/net-cache.mjs';
34
35
  import { CONFIG_FILE } from '../config.mjs';
@@ -112,6 +113,41 @@ export function planMerge({ sorted = [], byNumber = new Map(), prsByStory = new
112
113
  return { fila, concluidas, semPr, bloqueios, avisos };
113
114
  }
114
115
 
116
+ /**
117
+ * Complementa o vínculo nativo com o parse do corpo (função PURA — testável).
118
+ *
119
+ * O GitHub só cria closedByPullRequestsReferences quando a base do PR é a
120
+ * default — numa pilha, só o PR de baixo tem, e as Stories dos demais chegavam
121
+ * aqui "sem PR" e ficavam fora da fila. O corpo (`Closes #N`, mesmo parser do
122
+ * code-review) preenche exatamente esse vão. Só Stories SEM vínculo nativo
123
+ * recebem PRs do corpo — quando o GitHub conhece o PR, a fonte nativa vence e
124
+ * uma menção redundante no corpo de outro PR não cria ambiguidade.
125
+ *
126
+ * @param {object} params
127
+ * @param {number[]} params.sorted ordem topológica (números de Story)
128
+ * @param {Map<number, Array>} params.prsByStory vínculos nativos já coletados
129
+ * @param {Array<{number, body}>} params.openPrs PRs abertos do hub
130
+ * @param {{owner:string, repo:string}} params.hub o repositório das Stories —
131
+ * um `#N` solto nesses PRs é issue do hub, e um `outro/repo#N` não é Story
132
+ * @param {'explicit'|'any-mention'} [params.linkMode]
133
+ * @returns {{ prsByStory: Map<number, Array>, adicionados: Array<{story:number, pr:number}> }}
134
+ */
135
+ export function complementWithBodyLinks({ sorted = [], prsByStory = new Map(), openPrs = [], hub, linkMode = 'explicit' } = {}) {
136
+ const out = new Map(prsByStory);
137
+ const adicionados = [];
138
+ const faltantes = new Set(sorted.filter(s => (out.get(s) || []).length === 0));
139
+ if (faltantes.size === 0) return { prsByStory: out, adicionados };
140
+
141
+ for (const pr of openPrs) {
142
+ for (const n of hubIssueNumbers(extractIssueRefs(pr.body || '', { prRepo: hub, linkMode }), hub)) {
143
+ if (!faltantes.has(n)) continue;
144
+ out.set(n, [...(out.get(n) || []), pr]);
145
+ adicionados.push({ story: n, pr: pr.number });
146
+ }
147
+ }
148
+ return { prsByStory: out, adicionados };
149
+ }
150
+
115
151
  export async function merge({
116
152
  feature: featureArg, yes = false, dryRun = false, keepBranches = false,
117
153
  remote = false, refresh = false,
@@ -131,7 +167,7 @@ export async function merge({
131
167
  return;
132
168
  }
133
169
 
134
- const { owner, repo, root } = resolveRepoContext();
170
+ const { owner, repo, root } = resolveHubContext();
135
171
  if (!owner || !repo) {
136
172
  p.log.error(
137
173
  'Não foi possível determinar owner/repo.\n' +
@@ -226,11 +262,27 @@ export async function merge({
226
262
  return;
227
263
  }
228
264
 
229
- const prsByStory = new Map();
265
+ let prsByStory = new Map();
230
266
  for (const story of sorted) {
231
267
  prsByStory.set(story, await listIssuePullRequests(token, byNumber.get(story).nodeId).catch(() => []));
232
268
  }
233
269
 
270
+ // Vínculo nativo só existe com base na default — numa pilha, só o PR de
271
+ // baixo. Para as Stories que ficaram sem nada, o corpo dos PRs abertos
272
+ // (`Closes #N`) é a fonte que o autor de fato escreveu.
273
+ if (sorted.some(story => (prsByStory.get(story) || []).length === 0)) {
274
+ const abertos = await listOpenPullRequests(token, owner, repo).catch(() => []);
275
+ const linkMode = resolveLinkMode(fileConfig);
276
+ const comp = complementWithBodyLinks({ sorted, prsByStory, openPrs: abertos, hub: { owner, repo }, linkMode });
277
+ prsByStory = comp.prsByStory;
278
+ if (comp.adicionados.length > 0) {
279
+ p.log.info(chalk.dim(
280
+ comp.adicionados.map(({ story, pr }) => `Story #${story} ← PR #${pr}`).join(' · ') +
281
+ ' — vínculo pelo corpo (Closes #N); o GitHub só registra o nativo quando a base é a default.'
282
+ ));
283
+ }
284
+ }
285
+
234
286
  const plano = planMerge({ sorted, byNumber, prsByStory, defaultBranch });
235
287
  s.stop(`${plano.fila.length} PR(s) a mergear · ${plano.concluidas.length} já mergeado(s).`);
236
288
 
@@ -17,7 +17,7 @@ import { getIssue } from '../api/github-rest.mjs';
17
17
  import { addProjectItem, getItemSingleSelectValue } from '../api/github-graphql.mjs';
18
18
  import { detectIssueType } from '../lib/issue-type.mjs';
19
19
  import { loadProjectConfig, resolveField, advanceToStage, resolveStageName } from '../lib/board.mjs';
20
- import { loadConfig } from '../lib/project-root.mjs';
20
+ import { resolveHubContext } from '../lib/project-root.mjs';
21
21
  import {
22
22
  CONFIG_FILE, PROGRESS_TODO, PROGRESS_IN_PROGRESS, PROGRESS_DONE,
23
23
  isManualStageType, MANUAL_STAGE_TYPES, isStageInTrack, STAGE_TRACKS,
@@ -117,12 +117,9 @@ export async function move({ issue: issueArg, stage: stageArg, status: statusArg
117
117
  return;
118
118
  }
119
119
 
120
- // owner/repo: env GITHUB_REPOSITORY (padrão dos comandos de Action) com
121
- // fallback no .spec-wave.json, procurado subindo na árvore.
122
- const [envOwner, envRepo] = (process.env.GITHUB_REPOSITORY || '').split('/');
123
- const { config, root } = loadConfig();
124
- const owner = envOwner || config?.owner;
125
- const repo = envRepo || config?.repo;
120
+ // owner/repo do hub: env GITHUB_REPOSITORY (padrão dos comandos de Action)
121
+ // com fallback no .spec-wave.json, procurado subindo na árvore.
122
+ const { owner, repo, config, root } = resolveHubContext();
126
123
  if (!owner || !repo) {
127
124
  p.log.error(
128
125
  'Não foi possível determinar owner/repo.\n' +
@@ -29,7 +29,7 @@ import { listSubIssues } from '../api/github-graphql.mjs';
29
29
  import { detectIssueType } from '../lib/issue-type.mjs';
30
30
  import { parseDependencies, orderStories } from '../lib/dependencies.mjs';
31
31
  import { loadProjectConfig, selectOpenFeatures } from '../lib/board.mjs';
32
- import { resolveRepoContext, loadConfig } from '../lib/project-root.mjs';
32
+ import { resolveHubContext, loadConfig } from '../lib/project-root.mjs';
33
33
  import { featureDocPaths } from '../lib/doc-paths.mjs';
34
34
  import { parseDecompositionDoc, renderDecompositionDoc } from '../lib/decomposition-doc.mjs';
35
35
  import {
@@ -273,7 +273,7 @@ export async function order({
273
273
  return;
274
274
  }
275
275
 
276
- const { owner, repo } = resolveRepoContext();
276
+ const { owner, repo } = resolveHubContext();
277
277
  if (!owner || !repo) {
278
278
  emitError(opts,
279
279
  'Não foi possível determinar owner/repo.\n' +
@@ -12,7 +12,9 @@
12
12
  // perigoso.
13
13
 
14
14
  import { execSync } from 'node:child_process';
15
- import { existsSync, mkdirSync, writeFileSync, readFileSync, unlinkSync } from 'node:fs';
15
+ import {
16
+ existsSync, mkdirSync, writeFileSync, readFileSync, unlinkSync, rmSync, copyFileSync, statSync,
17
+ } from 'node:fs';
16
18
  import path from 'node:path';
17
19
  import chalk from 'chalk';
18
20
 
@@ -34,11 +36,13 @@ import { parseQaPlanDoc, resolveTargetScenarios } from '../lib/qa-plan-doc.mjs';
34
36
  import {
35
37
  qaExecutionGate, greenTargetStage, storyCanAdvance, featureCanAdvanceQa,
36
38
  extractRegressionSection, renderQaCommand, buildQaContext, qaProcessEnv,
39
+ resolveQaEvidenceConfig,
37
40
  } from '../lib/qa-exec.mjs';
38
41
  import { pushWithRebase } from '../lib/git-retry.mjs';
39
42
  import {
40
43
  aggregateVerdict, validateQaResults, combineWithPrevious, parseLastQaReport,
41
44
  renderQaReport, renderQaBugDoc, qaOriginMarker, matchesQaOrigin, shortSha,
45
+ evidenceScenarioDir, evidenceMediaUrl, QA_EVIDENCE_MAX_BYTES,
42
46
  } from '../lib/qa-report.mjs';
43
47
  import {
44
48
  CONFIG_FILE, STAGE_QA, STAGE_UAT, STAGE_READY, PROGRESS_TODO, PROGRESS_IN_PROGRESS,
@@ -103,24 +107,105 @@ function headShaOf(root) {
103
107
  }
104
108
  }
105
109
 
106
- // Commit LOCAL escopado ao arquivo — o `qa` roda no checkout do usuário, e o
107
- // bug.md de reprovação é conteúdo determinístico produzido aqui mesmo. Nunca
108
- // varre o index: `git commit -- <path>` só leva o que este comando escreveu.
109
- function commitLocalFile(root, fileRel, message) {
110
+ // Commit LOCAL escopado ao caminho (arquivo OU diretório) — o `qa` roda no
111
+ // checkout do usuário, e tanto o bug.md de reprovação quanto a evidência visual
112
+ // são conteúdo produzido aqui mesmo. Nunca varre o index: `git commit -- <path>`
113
+ // só leva o que este comando escreveu. `git add -- <dir>` também registra as
114
+ // remoções dentro dele, que é como a re-execução substitui a evidência antiga.
115
+ //
116
+ // Devolve o SHA curto do commit (ou do HEAD, quando não havia nada a commitar
117
+ // — conteúdo idêntico é no-op, não falha), ou null quando o commit falhou.
118
+ function commitLocalPath(root, rel, message) {
110
119
  const cwd = root || process.cwd();
111
120
  try {
112
- execSync(`git add -- ${JSON.stringify(fileRel)}`, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
113
- execSync(`git commit -m ${JSON.stringify(message)} -- ${JSON.stringify(fileRel)}`, {
114
- cwd, stdio: ['ignore', 'pipe', 'pipe'],
115
- });
116
- return true;
121
+ execSync(`git add -A -- ${JSON.stringify(rel)}`, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
122
+ const staged = execSync(`git diff --cached --name-only -- ${JSON.stringify(rel)}`, {
123
+ cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'],
124
+ }).trim();
125
+ if (staged) {
126
+ execSync(`git commit -m ${JSON.stringify(message)} -- ${JSON.stringify(rel)}`, {
127
+ cwd, stdio: ['ignore', 'pipe', 'pipe'],
128
+ });
129
+ }
130
+ return headShaOf(root) || 'HEAD';
117
131
  } catch (err) {
118
132
  console.warn(chalk.yellow(
119
- `⚠️ ${fileRel} escrito, mas o commit local falhou (${String(err.message).split('\n')[0]}) — ` +
133
+ `⚠️ ${rel} escrito, mas o commit local falhou (${String(err.message).split('\n')[0]}) — ` +
120
134
  'commite-o você mesmo.'
121
135
  ));
122
- return false;
136
+ return null;
137
+ }
138
+ }
139
+
140
+ // Publica a evidência visual (vídeo/foto) que o executor deixou no staging:
141
+ // copia cada arquivo declarado em `evidenceFiles` para o diretório versionado
142
+ // (`docs/features/<slug>/qa/cenario-<n>/` ou `docs/bugs/<slug>/qa/...`), num
143
+ // commit ÚNICO, e empurra. Roda ANTES do roteamento por veredito, para que o
144
+ // bug.md de uma reprova já possa linkar o caminho publicado.
145
+ //
146
+ // Evidência é ENRIQUECIMENTO, nunca o canal do veredito: arquivo declarado mas
147
+ // ausente, acima do teto, commit ou push rejeitado → aviso e segue. Um `fail`
148
+ // real NUNCA vira `blocked` por causa de um vídeo que não subiu.
149
+ //
150
+ // Cada `cenario-<n>` EXECUTADO é limpo antes da cópia: a pasta reflete a última
151
+ // corrida, mesmo quando ela não gravou nada (evidência velha ao lado de veredito
152
+ // novo seria pior que pasta vazia). Cenários fora do alvo (`--only`) não são
153
+ // tocados — herdam links do relatório anterior.
154
+ //
155
+ // Muta `results[i].evidenceFiles` para os caminhos PUBLICADOS (relativos à raiz
156
+ // do repo); devolve o sha que os serve, ou null quando nada foi publicado.
157
+ //
158
+ // Exportada para o teste de integração em repositório temporário; `push` é
159
+ // injetável pelo mesmo motivo (o teste não tem remoto).
160
+ export async function publishEvidence({
161
+ root, results, stagingAbs, targetRel, targetAbs, push = pushWithRebase,
162
+ }) {
163
+ const cwd = root || process.cwd();
164
+ let copied = 0;
165
+ let removed = 0;
166
+ for (const r of results) {
167
+ const scenarioRel = `${targetRel}/${evidenceScenarioDir(r.numero)}`;
168
+ const scenarioAbs = path.join(targetAbs, evidenceScenarioDir(r.numero));
169
+ if (existsSync(scenarioAbs)) {
170
+ rmSync(scenarioAbs, { recursive: true, force: true });
171
+ removed += 1;
172
+ }
173
+ const published = [];
174
+ for (const name of r.evidenceFiles || []) {
175
+ const src = path.join(stagingAbs, evidenceScenarioDir(r.numero), name);
176
+ if (!existsSync(src)) {
177
+ console.warn(chalk.yellow(`⚠️ Cenário ${r.numero}: evidência "${name}" declarada mas ausente em ${path.relative(cwd, src)} — ignorada.`));
178
+ continue;
179
+ }
180
+ const size = statSync(src).size;
181
+ if (size > QA_EVIDENCE_MAX_BYTES) {
182
+ console.warn(chalk.yellow(
183
+ `⚠️ Cenário ${r.numero}: "${name}" tem ${(size / 1024 / 1024).toFixed(1)} MB, acima do teto de ` +
184
+ `${QA_EVIDENCE_MAX_BYTES / 1024 / 1024} MB que a UI serve — não publicada. Grave clipes mais curtos/leves.`
185
+ ));
186
+ continue;
187
+ }
188
+ mkdirSync(scenarioAbs, { recursive: true });
189
+ copyFileSync(src, path.join(scenarioAbs, name));
190
+ published.push(`${scenarioRel}/${name}`);
191
+ copied += 1;
192
+ }
193
+ r.evidenceFiles = published;
194
+ }
195
+ if (copied === 0 && removed === 0) return null;
196
+
197
+ const sha = commitLocalPath(root, targetRel,
198
+ `docs: evidência visual do QA em ${targetRel} (${copied} arquivo(s)) [spec-wave]`);
199
+ if (!sha) return null;
200
+ if (copied > 0) console.log(`Evidência visual publicada em ${chalk.cyan(targetRel)}/ (${copied} arquivo(s), commit ${sha}).`);
201
+ const pushed = await push({ cwd });
202
+ if (!pushed.ok) {
203
+ console.warn(chalk.yellow(
204
+ `⚠️ Evidência commitada, mas o push foi rejeitado após ${pushed.attempts} tentativa(s): ` +
205
+ `${String(pushed.error).split('\n')[0]} — os links do relatório só vão resolver depois do seu push.`
206
+ ));
123
207
  }
208
+ return headShaOf(root) || sha;
124
209
  }
125
210
 
126
211
  function parseOnly(only) {
@@ -230,10 +315,12 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
230
315
  let qaPlanRel = null;
231
316
  let specRel = null;
232
317
  let featureStories = []; // Stories da Feature (modo Feature — o verde as aprova uma a uma)
318
+ let evidenceTarget = null; // { rel, abs } — onde a evidência visual é publicada
233
319
 
234
320
  if (type === 'Bug') {
235
- const { fileRel, fileAbs } = bugDocPaths(issue.title, root);
321
+ const { fileRel, fileAbs, qaEvidenceDirRel, qaEvidenceDirAbs } = bugDocPaths(issue.title, root);
236
322
  qaPlanRel = fileRel;
323
+ evidenceTarget = { rel: qaEvidenceDirRel, abs: qaEvidenceDirAbs };
237
324
  if (!existsSync(fileAbs)) {
238
325
  const achado = await loadArtifact({
239
326
  token, owner, repo, root, pathRel: fileRel, doc: 'bug', issueNumber: number,
@@ -273,6 +360,7 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
273
360
  const paths = featureDocPaths(root, { title: feature.title }, 'Feature');
274
361
  qaPlanRel = paths['qa-plan'].rel;
275
362
  specRel = paths.spec.rel;
363
+ evidenceTarget = paths.qaEvidenceDir;
276
364
  const plano = await loadArtifact({
277
365
  token, owner, repo, root, pathRel: qaPlanRel, doc: 'qa-plan', issueNumber: feature.number,
278
366
  }).catch(() => null);
@@ -369,6 +457,11 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
369
457
  const resultFile = path.join(WORK_DIR, `qa-result-${number}.json`);
370
458
  const contextAbs = path.join(root || process.cwd(), contextFile);
371
459
  const resultAbs = path.join(root || process.cwd(), resultFile);
460
+ // Staging da evidência visual — mesmo padrão do resultado: gitignored, limpo
461
+ // antes de cada corrida (vídeo velho não pode virar evidência nova).
462
+ const evidenceDir = path.join(WORK_DIR, `qa-evidence-${number}`);
463
+ const evidenceAbs = path.join(root || process.cwd(), evidenceDir);
464
+ const evidence = resolveQaEvidenceConfig(config?.qa);
372
465
 
373
466
  const context = buildQaContext({
374
467
  type, issue: { number, title: issue.title }, stage,
@@ -376,9 +469,11 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
376
469
  comments: commentGroups, pullRequests,
377
470
  setup: config?.qa?.setup || null,
378
471
  resultFile,
472
+ evidenceDir, evidence, env: config?.qa?.env || null,
379
473
  });
380
474
  writeFileSync(contextAbs, context);
381
475
  if (existsSync(resultAbs)) unlinkSync(resultAbs); // resultado velho não pode virar veredito novo
476
+ if (!dryRun) rmSync(evidenceAbs, { recursive: true, force: true });
382
477
 
383
478
  const template = process.env.SPEC_WAVE_QA_CMD || config?.qa?.command;
384
479
  const vars = {
@@ -479,6 +574,25 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
479
574
  }
480
575
  }
481
576
 
577
+ // headSha = o commit TESTADO (vai no marcador do relatório). O commit da
578
+ // evidência vem depois e só serve os links.
579
+ const headSha = headShaOf(root);
580
+
581
+ // ── Evidência visual → repositório (antes do veredito, nunca o altera) ─────
582
+ let evidenceBase = null;
583
+ try {
584
+ const evidenceSha = evidenceTarget
585
+ ? await publishEvidence({
586
+ root, results, stagingAbs: evidenceAbs, targetRel: evidenceTarget.rel, targetAbs: evidenceTarget.abs,
587
+ })
588
+ : null;
589
+ if (evidenceSha) evidenceBase = { owner, repo, sha: evidenceSha };
590
+ } catch (err) {
591
+ console.warn(chalk.yellow(`⚠️ Falha ao publicar a evidência visual: ${err.message} — seguindo sem ela.`));
592
+ for (const r of results) r.evidenceFiles = [];
593
+ }
594
+ rmSync(evidenceAbs, { recursive: true, force: true });
595
+
482
596
  // ── Estado acumulado e veredito ────────────────────────────────────────────
483
597
  const { combined, pendingNumbers } = combineWithPrevious({
484
598
  executed: results,
@@ -487,14 +601,13 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
487
601
  });
488
602
  let verdict = aggregateVerdict(combined);
489
603
  const planSha = shortSha(planContent);
490
- const headSha = headShaOf(root);
491
604
  const byNumero = new Map(scenarios.map(s => [s.numero, s]));
492
605
 
493
606
  console.log(`\nVeredito agregado: ${chalk.bold(verdict)} (${combined.length} cenário(s) no escopo, ${results.length} executado(s) agora).`);
494
607
 
495
608
  const outcome = {
496
609
  token, projectToken, owner, repo, root, config, board, issue, number, type, feature,
497
- featureStories,
610
+ featureStories, evidenceBase,
498
611
  };
499
612
 
500
613
  let bugs = [];
@@ -579,14 +692,18 @@ export async function qaRun({ issue: issueArg, only: onlyArg, severity: severity
579
692
  // ── Desfechos ────────────────────────────────────────────────────────────────
580
693
 
581
694
  async function postReport({
582
- token, owner, repo, number, type, run, verdict, planSha, headSha,
695
+ token, owner, repo, number, type, run, verdict, planSha, headSha, evidenceBase,
583
696
  combined, pendingNumbers, bugs, trailer,
584
697
  }) {
698
+ // Cenário herdado (`--only`) traz links de uma corrida anterior, servidos
699
+ // pelo commit daquela corrida — sem a base desta, cai na branch default.
700
+ const base = evidenceBase || { owner, repo, sha: 'HEAD' };
585
701
  const markdown = renderQaReport({
586
702
  issue: number,
587
703
  scope: `${type} #${number}`,
588
704
  run, verdict, planSha, headSha,
589
705
  results: combined,
706
+ evidenceBase: base,
590
707
  bugs,
591
708
  pendingNumbers,
592
709
  trailer,
@@ -613,7 +730,7 @@ async function stayInQa({ projectToken, board, issue }) {
613
730
  // estado que a spec proíbe.
614
731
  async function openBugsForFailures({
615
732
  token, projectToken, owner, repo, root, board,
616
- failed, byNumero, severity, headSha, qaPlanRel, feature, type, number,
733
+ failed, byNumero, severity, headSha, qaPlanRel, feature, evidenceBase,
617
734
  }) {
618
735
  const bugs = [];
619
736
  const pushFailures = [];
@@ -640,10 +757,13 @@ async function openBugsForFailures({
640
757
  matchesQaOrigin(c.body, { issue: storyNumber, cenario: scenario.numero }));
641
758
  if (existing) {
642
759
  console.log(`Cenário ${scenario.numero} já tem Bug aberto (#${existing.number}) — comentando nele.`);
760
+ const midia = (r.evidenceFiles || []).length > 0 && evidenceBase
761
+ ? `\n\n**Evidência visual:** ${r.evidenceFiles.map(f => `[${f.split('/').pop()}](${evidenceMediaUrl(evidenceBase.owner, evidenceBase.repo, evidenceBase.sha, f)})`).join(' · ')}`
762
+ : '';
643
763
  await commentOnIssue(token, owner, repo, existing.number,
644
764
  `🧪 **O cenário ${scenario.numero} da Story #${storyNumber} reprovou de novo** ` +
645
765
  `(${headSha ? `commit \`${headSha}\`` : 'nova execução'}).\n\n` +
646
- `**Evidência:** ${r.evidencia || '(sem evidência registrada)'}`
766
+ `**Evidência:** ${r.evidencia || '(sem evidência registrada)'}${midia}`
647
767
  ).catch(() => {});
648
768
  bugs.push({ number: existing.number, cenario: scenario.numero, existing: true });
649
769
  continue;
@@ -675,6 +795,7 @@ async function openBugsForFailures({
675
795
  mkdirSync(dirAbs, { recursive: true });
676
796
  writeFileSync(fileAbs, renderQaBugDoc({
677
797
  title: resumo, scenario, evidence: r.evidencia, severity, headSha,
798
+ evidenceFiles: r.evidenceFiles || [], evidenceBase,
678
799
  featureNumber: feature?.number ?? null,
679
800
  }));
680
801
  } catch (err) {
@@ -682,7 +803,7 @@ async function openBugsForFailures({
682
803
  pushFailures.push({ numero: r.numero, error: `escrita do ${fileRel} falhou: ${err.message}` });
683
804
  continue;
684
805
  }
685
- const committed = commitLocalFile(root, fileRel,
806
+ const committed = commitLocalPath(root, fileRel,
686
807
  `docs: gera ${fileRel} (reprovação de QA, cenário ${scenario.numero} da Story #${storyNumber}) [spec-wave]`);
687
808
  if (!committed) {
688
809
  pushFailures.push({ numero: r.numero, error: `commit do ${fileRel} falhou` });
@@ -3,23 +3,13 @@ import { getIssue, getPR, commentOnIssue } from '../api/github-rest.mjs';
3
3
  import { getIssueParent } from '../api/github-graphql.mjs';
4
4
  import { detectIssueType } from '../lib/issue-type.mjs';
5
5
  import { loadProjectConfig, resolveField, advanceToStage } from '../lib/board.mjs';
6
- import { loadConfig } from '../lib/project-root.mjs';
6
+ import { resolveHubContext, resolvePrRepo } from '../lib/project-root.mjs';
7
+ import { extractIssueRefs, hubIssueNumbers, resolveLinkMode } from '../lib/pr-link.mjs';
7
8
  import { STATUS_OPTIONS, PROGRESS_TODO } from '../config.mjs';
8
9
 
9
10
  const QA_STAGE = STATUS_OPTIONS.find(s => s.name.includes('QA'))?.name;
10
11
  const TODO_STATUS = PROGRESS_TODO;
11
12
 
12
- function extractIssueNumbers(body) {
13
- if (!body) return [];
14
- const nums = new Set();
15
- const re = /(?:closes?|fixes?|resolves?)\s+#(\d+)|(?<![/\w#])#(\d+)/gi;
16
- for (const m of body.matchAll(re)) {
17
- const n = parseInt(m[1] || m[2], 10);
18
- if (n) nums.add(n);
19
- }
20
- return [...nums];
21
- }
22
-
23
13
  async function resolveFeatureIssue(token, owner, repo, issueNumber) {
24
14
  let issue;
25
15
  try {
@@ -42,13 +32,13 @@ async function resolveFeatureIssue(token, owner, repo, issueNumber) {
42
32
  return null;
43
33
  }
44
34
 
45
- export async function qa({ prNumber }) {
35
+ export async function qa({ prNumber, prRepo: prRepoOpt }) {
46
36
  const token = await resolveToken();
47
37
  const projectToken = process.env.PROJECT_TOKEN || token;
48
- const [envOwner, envRepo] = (process.env.GITHUB_REPOSITORY || '').split('/');
49
- const { config: cfg } = loadConfig();
50
- const owner = envOwner || cfg?.owner;
51
- const repo = envRepo || cfg?.repo;
38
+ // Mesma separação do code-review: o comando roda no hub (dono das issues) e
39
+ // o PR pode estar num repo de código — `--pr-repo` diz qual.
40
+ const ctx = resolveHubContext();
41
+ const { owner, repo, config: cfg } = ctx;
52
42
 
53
43
  if (!owner || !repo) {
54
44
  throw new Error(
@@ -56,12 +46,23 @@ export async function qa({ prNumber }) {
56
46
  'Defina GITHUB_REPOSITORY=owner/repo ou rode dentro de um repositório com .spec-wave.json.'
57
47
  );
58
48
  }
49
+ const hub = { owner, repo };
50
+ const prRepo = resolvePrRepo(prRepoOpt, ctx);
51
+ const prNum = parseInt(prNumber, 10);
59
52
 
60
- const pr = await getPR(token, owner, repo, parseInt(prNumber, 10));
61
- const issueNums = extractIssueNumbers(pr.body || '');
53
+ const pr = await getPR(token, prRepo.owner, prRepo.repo, prNum);
54
+ // Mesmo parser e mesma régua do code-review: o vínculo que levou a Story a
55
+ // 👀 Code Review é o que a leva a 🧪 QA. Antes o qa tinha um parser próprio,
56
+ // mais frouxo (qualquer `#N`), que o code-review já havia abandonado.
57
+ const linkMode = resolveLinkMode(cfg);
58
+ const issueNums = hubIssueNumbers(extractIssueRefs(pr.body || '', { prRepo, linkMode }), hub);
62
59
 
63
60
  if (issueNums.length === 0) {
64
- console.log('PR sem referências a issues — nenhuma Feature atualizada.');
61
+ console.log(
62
+ linkMode === 'explicit'
63
+ ? 'PR sem vínculo explícito (Closes/Fixes/Resolves/Implements #N) com issue do hub — board não atualizado.'
64
+ : 'PR sem referências a issues — nenhuma Feature atualizada.'
65
+ );
65
66
  return;
66
67
  }
67
68
 
@@ -124,7 +125,7 @@ export async function qa({ prNumber }) {
124
125
 
125
126
  if (updated.length > 0) {
126
127
  await commentOnIssue(
127
- token, owner, repo, parseInt(prNumber, 10),
128
+ token, prRepo.owner, prRepo.repo, prNum,
128
129
  `🧪 **PR aprovado — QA iniciado**\n\n` +
129
130
  `Item(ns) movido(s) para **${QA_STAGE}**:\n\n` +
130
131
  updated.map(f => `- ${f}`).join('\n')
@@ -23,7 +23,7 @@ import { getIssue, commentOnIssue } from '../api/github-rest.mjs';
23
23
  import { verifyTokenScopes } from '../api/auth.mjs';
24
24
  import { detectIssueType } from '../lib/issue-type.mjs';
25
25
  import { loadProjectConfig, resolveField, setItemStage, resolveStageName } from '../lib/board.mjs';
26
- import { loadConfig } from '../lib/project-root.mjs';
26
+ import { resolveHubContext } from '../lib/project-root.mjs';
27
27
  import { resolveProgressName } from './move.mjs';
28
28
  import { CONFIG_FILE } from '../config.mjs';
29
29
 
@@ -130,10 +130,7 @@ export async function repairStage(issuesArg, stageArg, options = {}) {
130
130
  return;
131
131
  }
132
132
 
133
- const [envOwner, envRepo] = (process.env.GITHUB_REPOSITORY || '').split('/');
134
- const { config, root } = loadConfig();
135
- const owner = envOwner || config?.owner;
136
- const repo = envRepo || config?.repo;
133
+ const { owner, repo, config, root } = resolveHubContext();
137
134
  if (!owner || !repo) {
138
135
  p.log.error(
139
136
  'Não foi possível determinar owner/repo.\n' +
@@ -12,7 +12,7 @@ import { getIssue } from '../api/github-rest.mjs';
12
12
  import { addProjectItem, getItemSingleSelectValue } from '../api/github-graphql.mjs';
13
13
  import { detectIssueType } from '../lib/issue-type.mjs';
14
14
  import { loadProjectConfig, resolveField, advanceToStage } from '../lib/board.mjs';
15
- import { resolveRepoContext } from '../lib/project-root.mjs';
15
+ import { resolveHubContext } from '../lib/project-root.mjs';
16
16
  import { CONFIG_FILE, STAGE_CODE_REVIEW, PROGRESS_TODO } from '../config.mjs';
17
17
 
18
18
  export async function story({ action, issue: issueArg }) {
@@ -32,7 +32,7 @@ export async function story({ action, issue: issueArg }) {
32
32
  return;
33
33
  }
34
34
 
35
- const { owner, repo } = resolveRepoContext();
35
+ const { owner, repo } = resolveHubContext();
36
36
  if (!owner || !repo) {
37
37
  p.log.error(
38
38
  'Não foi possível determinar owner/repo.\n' +
@@ -15,7 +15,7 @@ import { getIssue } from '../api/github-rest.mjs';
15
15
  import { addProjectItem, getIssueParent, listSubIssues, getItemSingleSelectValue } from '../api/github-graphql.mjs';
16
16
  import { detectIssueType } from '../lib/issue-type.mjs';
17
17
  import { loadProjectConfig, resolveField, advanceToStage, setItemStatus } from '../lib/board.mjs';
18
- import { resolveRepoContext } from '../lib/project-root.mjs';
18
+ import { resolveHubContext } from '../lib/project-root.mjs';
19
19
  import {
20
20
  CONFIG_FILE, STAGE_DEVELOPMENT, STAGE_DONE,
21
21
  PROGRESS_IN_PROGRESS, PROGRESS_DONE,
@@ -53,7 +53,7 @@ export async function task({ action, issue: issueArg }) {
53
53
  return;
54
54
  }
55
55
 
56
- const { owner, repo } = resolveRepoContext();
56
+ const { owner, repo } = resolveHubContext();
57
57
  if (!owner || !repo) {
58
58
  p.log.error(
59
59
  'Não foi possível determinar owner/repo.\n' +
@@ -16,7 +16,7 @@ import {
16
16
  } from '../api/github-rest.mjs';
17
17
  import { detectIssueType } from '../lib/issue-type.mjs';
18
18
  import { loadProjectConfig, resolveField, advanceToStage } from '../lib/board.mjs';
19
- import { loadConfig } from '../lib/project-root.mjs';
19
+ import { resolveHubContext } from '../lib/project-root.mjs';
20
20
  import { resolveTriageAction, canAcceptBug } from '../lib/bug-triage.mjs';
21
21
  import {
22
22
  CONFIG_FILE, STAGE_READY, PROGRESS_TODO, PRIORITY_LABELS,
@@ -45,10 +45,7 @@ export async function triage({ action: actionArg, issue: issueArg, reason, of, s
45
45
  return;
46
46
  }
47
47
 
48
- const [envOwner, envRepo] = (process.env.GITHUB_REPOSITORY || '').split('/');
49
- const { config, root } = loadConfig();
50
- const owner = envOwner || config?.owner;
51
- const repo = envRepo || config?.repo;
48
+ const { owner, repo, config, root } = resolveHubContext();
52
49
  if (!owner || !repo) {
53
50
  p.log.error(
54
51
  'Não foi possível determinar owner/repo.\n' +